@computesdk/superserve 0.2.26 → 0.2.28
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 +30 -0
- package/dist/index.d.mts +15 -4
- package/dist/index.d.ts +15 -4
- package/dist/index.js +175 -9
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +180 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -68,10 +68,36 @@ superserve({
|
|
|
68
68
|
| Snapshots (create, list, delete, boot from snapshot) | ✅ |
|
|
69
69
|
| Preview URLs (`getUrl`) | ✅ |
|
|
70
70
|
| Pause / resume (memory, processes and files preserved) | ✅ `instance.pause()` / `instance.resume()` |
|
|
71
|
+
| Persistent volumes (create / get / list / delete, mount / detach) | ✅ Requires volume-enabled account and prepared template |
|
|
71
72
|
| Template build (`template.create`) | ❌ Use `@superserve/sdk` `Template.create` |
|
|
72
73
|
|
|
73
74
|
## API Reference
|
|
74
75
|
|
|
76
|
+
### Persistent volumes
|
|
77
|
+
|
|
78
|
+
Volume mounts require a template with the Superserve volume runtime installed
|
|
79
|
+
at build time and volumes enabled for the account.
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
const volume = await provider.volume!.create({
|
|
83
|
+
name: 'project-data',
|
|
84
|
+
sizeBytes: 1024 ** 3,
|
|
85
|
+
});
|
|
86
|
+
const sandbox = await provider.instances.create({
|
|
87
|
+
templateId: 'my-volume-runtime',
|
|
88
|
+
volumes: [{ volume, mountPath: '/mnt/data' }],
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
await sandbox.detachVolume!(volume, '/mnt/data');
|
|
92
|
+
await sandbox.destroy();
|
|
93
|
+
await provider.volume!.delete(volume.id!);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Volumes can also be mounted on a running instance with
|
|
97
|
+
`await sandbox.attachVolume!(volume, '/mnt/data')`. References accept an ID,
|
|
98
|
+
name, or handle returned by `provider.volume`. Supply the mount path when
|
|
99
|
+
detaching a volume with more than one mount on the instance.
|
|
100
|
+
|
|
75
101
|
### `sandbox.create(options?)`
|
|
76
102
|
|
|
77
103
|
Boots a new microVM. Common options:
|
|
@@ -246,3 +272,7 @@ pnpm superserve
|
|
|
246
272
|
## License
|
|
247
273
|
|
|
248
274
|
MIT
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
[Sandbox providers](https://www.computesdk.com/providers/sandboxes) · [Sandbox Router](https://www.computesdk.com/sandbox-router)
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as computesdk from 'computesdk';
|
|
2
|
-
import { TemplateCreateOptions, Sandbox } from '@superserve/sdk';
|
|
2
|
+
import { TemplateCreateOptions, VolumeCreateOptions, Sandbox } from '@superserve/sdk';
|
|
3
3
|
export { Sandbox as SuperserveSandbox } from '@superserve/sdk';
|
|
4
|
-
import { CreateTemplateOptions } from '@computesdk/provider';
|
|
4
|
+
import { InstanceSizeClass, CreateTemplateOptions, CreateVolumeOptions, Volume } from '@computesdk/provider';
|
|
5
5
|
|
|
6
6
|
interface SuperserveConfig {
|
|
7
7
|
/** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */
|
|
@@ -10,12 +10,23 @@ interface SuperserveConfig {
|
|
|
10
10
|
baseUrl?: string;
|
|
11
11
|
/** Default auto-pause timeout in milliseconds. */
|
|
12
12
|
timeout?: number;
|
|
13
|
+
/** Template to boot per standard `sizeClass`; defaults to {@link SUPERSERVE_SIZE_TEMPLATES}. */
|
|
14
|
+
sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;
|
|
13
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Superserve fixes vCPU, memory and disk when a template is built, so each
|
|
18
|
+
* standard size boots its own template. `superserve/base` (2 vCPU / 4 GiB /
|
|
19
|
+
* 8 GiB disk) is built in to every team; the others are team templates
|
|
20
|
+
* built by `scripts/provider-setup.mjs superserve`. The largest listed plan
|
|
21
|
+
* (Pro) caps a sandbox at 16 vCPU / 64 GiB, so `3xl` has no default.
|
|
22
|
+
*/
|
|
23
|
+
declare const SUPERSERVE_SIZE_TEMPLATES: Readonly<Partial<Record<InstanceSizeClass, string>>>;
|
|
14
24
|
/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set
|
|
15
25
|
* here and every sandbox created from it inherits them. */
|
|
16
26
|
type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;
|
|
17
|
-
|
|
27
|
+
type SuperserveVolumeCreateOptions = CreateVolumeOptions & Pick<VolumeCreateOptions, 'idempotencyKey' | 'timeoutMs' | 'signal'>;
|
|
28
|
+
declare const superserve: (config: SuperserveConfig & computesdk.ProcessRuntimeOptions) => computesdk.Provider<Sandbox, any, any, Volume> & {
|
|
18
29
|
readonly sizes: computesdk.InstanceSizeManager;
|
|
19
30
|
};
|
|
20
31
|
|
|
21
|
-
export { type SuperserveConfig, type SuperserveTemplateCreateOptions, superserve };
|
|
32
|
+
export { SUPERSERVE_SIZE_TEMPLATES, type SuperserveConfig, type SuperserveTemplateCreateOptions, type SuperserveVolumeCreateOptions, superserve };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as computesdk from 'computesdk';
|
|
2
|
-
import { TemplateCreateOptions, Sandbox } from '@superserve/sdk';
|
|
2
|
+
import { TemplateCreateOptions, VolumeCreateOptions, Sandbox } from '@superserve/sdk';
|
|
3
3
|
export { Sandbox as SuperserveSandbox } from '@superserve/sdk';
|
|
4
|
-
import { CreateTemplateOptions } from '@computesdk/provider';
|
|
4
|
+
import { InstanceSizeClass, CreateTemplateOptions, CreateVolumeOptions, Volume } from '@computesdk/provider';
|
|
5
5
|
|
|
6
6
|
interface SuperserveConfig {
|
|
7
7
|
/** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */
|
|
@@ -10,12 +10,23 @@ interface SuperserveConfig {
|
|
|
10
10
|
baseUrl?: string;
|
|
11
11
|
/** Default auto-pause timeout in milliseconds. */
|
|
12
12
|
timeout?: number;
|
|
13
|
+
/** Template to boot per standard `sizeClass`; defaults to {@link SUPERSERVE_SIZE_TEMPLATES}. */
|
|
14
|
+
sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;
|
|
13
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Superserve fixes vCPU, memory and disk when a template is built, so each
|
|
18
|
+
* standard size boots its own template. `superserve/base` (2 vCPU / 4 GiB /
|
|
19
|
+
* 8 GiB disk) is built in to every team; the others are team templates
|
|
20
|
+
* built by `scripts/provider-setup.mjs superserve`. The largest listed plan
|
|
21
|
+
* (Pro) caps a sandbox at 16 vCPU / 64 GiB, so `3xl` has no default.
|
|
22
|
+
*/
|
|
23
|
+
declare const SUPERSERVE_SIZE_TEMPLATES: Readonly<Partial<Record<InstanceSizeClass, string>>>;
|
|
14
24
|
/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set
|
|
15
25
|
* here and every sandbox created from it inherits them. */
|
|
16
26
|
type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;
|
|
17
|
-
|
|
27
|
+
type SuperserveVolumeCreateOptions = CreateVolumeOptions & Pick<VolumeCreateOptions, 'idempotencyKey' | 'timeoutMs' | 'signal'>;
|
|
28
|
+
declare const superserve: (config: SuperserveConfig & computesdk.ProcessRuntimeOptions) => computesdk.Provider<Sandbox, any, any, Volume> & {
|
|
18
29
|
readonly sizes: computesdk.InstanceSizeManager;
|
|
19
30
|
};
|
|
20
31
|
|
|
21
|
-
export { type SuperserveConfig, type SuperserveTemplateCreateOptions, superserve };
|
|
32
|
+
export { SUPERSERVE_SIZE_TEMPLATES, type SuperserveConfig, type SuperserveTemplateCreateOptions, type SuperserveVolumeCreateOptions, superserve };
|
package/dist/index.js
CHANGED
|
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/index.ts
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
|
+
SUPERSERVE_SIZE_TEMPLATES: () => SUPERSERVE_SIZE_TEMPLATES,
|
|
23
24
|
superserve: () => superserve
|
|
24
25
|
});
|
|
25
26
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -27,6 +28,27 @@ var import_node_crypto = require("crypto");
|
|
|
27
28
|
var import_sdk = require("@superserve/sdk");
|
|
28
29
|
var import_provider = require("@computesdk/provider");
|
|
29
30
|
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
31
|
+
var SUPERSERVE_SIZE_TEMPLATES = Object.freeze({
|
|
32
|
+
xs: "csdk-node22-1cpu-1gb",
|
|
33
|
+
sm: "csdk-node22-1cpu-2gb",
|
|
34
|
+
md: "superserve/base",
|
|
35
|
+
lg: "csdk-node22-4cpu-8gb",
|
|
36
|
+
xl: "csdk-node22-8cpu-16gb",
|
|
37
|
+
"2xl": "csdk-node22-16cpu-32gb"
|
|
38
|
+
});
|
|
39
|
+
var BUILT_IN_TEMPLATE_DISK_MIB = Object.freeze({ "superserve/base": 8192 });
|
|
40
|
+
var SOURCE_OPTIONS = ["templateId", "snapshotId", "sandboxId", "fromTemplate", "fromSnapshot"];
|
|
41
|
+
var NATIVE_SIZE_OPTIONS = ["vcpu", "vcpuCount", "memoryMib", "memoryMaxMib", "diskMib"];
|
|
42
|
+
function sizeTemplateOf(config, sizeClass) {
|
|
43
|
+
const name = config.sizeTemplates?.[sizeClass] ?? SUPERSERVE_SIZE_TEMPLATES[sizeClass];
|
|
44
|
+
return typeof name === "string" && name.trim() ? name : void 0;
|
|
45
|
+
}
|
|
46
|
+
function missingSizeTemplate(config, templateId, error) {
|
|
47
|
+
if (typeof templateId !== "string" || !(error instanceof import_sdk.NotFoundError)) return void 0;
|
|
48
|
+
const sizeClass = Object.keys(import_provider.INSTANCE_SIZE_PROFILES).find((c) => sizeTemplateOf(config, c) === templateId);
|
|
49
|
+
if (!sizeClass) return void 0;
|
|
50
|
+
return `Superserve size template '${templateId}' (sizeClass ${sizeClass}) is not built on this Superserve team; run \`node scripts/provider-setup.mjs superserve\` (provider-setup.yml) or point \`sizeTemplates.${sizeClass}\` at an existing template`;
|
|
51
|
+
}
|
|
30
52
|
function resolveApiKey(config) {
|
|
31
53
|
const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;
|
|
32
54
|
if (!apiKey) {
|
|
@@ -44,6 +66,65 @@ function generateSandboxName() {
|
|
|
44
66
|
}
|
|
45
67
|
var FALLBACK_WORKDIR = "/";
|
|
46
68
|
var workdirs = /* @__PURE__ */ new WeakMap();
|
|
69
|
+
var volumeConnections = /* @__PURE__ */ new WeakMap();
|
|
70
|
+
function volumeReference(volume) {
|
|
71
|
+
const reference = typeof volume === "string" ? volume : volume?.id || volume?.name;
|
|
72
|
+
if (typeof reference !== "string" || !reference.trim()) {
|
|
73
|
+
throw new Error("A Superserve volume reference must contain an id or name.");
|
|
74
|
+
}
|
|
75
|
+
return reference;
|
|
76
|
+
}
|
|
77
|
+
function volumeConnection(sandbox) {
|
|
78
|
+
const connection = volumeConnections.get(sandbox);
|
|
79
|
+
if (!connection) throw new Error("The Superserve sandbox has no captured volume connection.");
|
|
80
|
+
return connection;
|
|
81
|
+
}
|
|
82
|
+
function sameSandboxId(left, right) {
|
|
83
|
+
const pattern = /^(?:sb-([A-Za-z0-9]+)-)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
84
|
+
const a = pattern.exec(left);
|
|
85
|
+
const b = pattern.exec(right);
|
|
86
|
+
if (!a || !b) return left === right;
|
|
87
|
+
return a[2].toLowerCase() === b[2].toLowerCase() && (a[1] === void 0 || b[1] === void 0 || a[1] === b[1]);
|
|
88
|
+
}
|
|
89
|
+
function toVolume(info) {
|
|
90
|
+
return {
|
|
91
|
+
id: info.id,
|
|
92
|
+
name: info.name,
|
|
93
|
+
sizeBytes: info.capacityBytes,
|
|
94
|
+
usedBytes: info.usedBytes,
|
|
95
|
+
region: info.region,
|
|
96
|
+
status: info.status,
|
|
97
|
+
createdAt: info.createdAt
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function deleteVolume(connection, idOrName) {
|
|
101
|
+
let volume;
|
|
102
|
+
try {
|
|
103
|
+
volume = await import_sdk.Volume.connect(idOrName, connection);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error instanceof import_sdk.NotFoundError) return;
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const deadline = Date.now() + 12e4;
|
|
109
|
+
for (; ; ) {
|
|
110
|
+
try {
|
|
111
|
+
await import_sdk.Volume.deleteById(volume.id, connection);
|
|
112
|
+
return;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (!(error instanceof import_sdk.ConflictError) || error.code !== "volume_conflict") throw error;
|
|
115
|
+
let attachments;
|
|
116
|
+
try {
|
|
117
|
+
attachments = await volume.listAttachments();
|
|
118
|
+
} catch (lookupError) {
|
|
119
|
+
if (lookupError instanceof import_sdk.NotFoundError) return;
|
|
120
|
+
throw lookupError;
|
|
121
|
+
}
|
|
122
|
+
const closing = attachments.filter((attachment) => attachment.status !== "revoked");
|
|
123
|
+
if (!closing.length || closing.some((attachment) => attachment.status !== "detaching" && attachment.status !== "revoking") || Date.now() >= deadline) throw error;
|
|
124
|
+
await new Promise((resolve) => setTimeout(resolve, 3e3));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
47
128
|
function workdirOf(sandbox, runCommand2) {
|
|
48
129
|
let probe = workdirs.get(sandbox);
|
|
49
130
|
if (!probe) {
|
|
@@ -137,6 +218,30 @@ function toTemplate(info) {
|
|
|
137
218
|
}
|
|
138
219
|
var superserve = (0, import_provider.defineProvider)({
|
|
139
220
|
name: "superserve",
|
|
221
|
+
sizes: (config, profile, options) => {
|
|
222
|
+
const opts = options;
|
|
223
|
+
const nativeSize = NATIVE_SIZE_OPTIONS.find((key) => opts?.[key] !== void 0);
|
|
224
|
+
if (nativeSize) {
|
|
225
|
+
throw new import_provider.InstanceSizeError("conflict", `cannot combine sizeClass with native Superserve ${nativeSize}; Superserve sizes sandboxes by template`);
|
|
226
|
+
}
|
|
227
|
+
const source = SOURCE_OPTIONS.find((key) => opts?.[key] !== void 0);
|
|
228
|
+
if (source) {
|
|
229
|
+
return { status: "unsupported", reason: `A Superserve template or snapshot fixes CPU and memory; drop ${source} to boot the standard size template.` };
|
|
230
|
+
}
|
|
231
|
+
const templateId = sizeTemplateOf(config, profile.sizeClass);
|
|
232
|
+
if (!templateId) {
|
|
233
|
+
return {
|
|
234
|
+
status: "unsupported",
|
|
235
|
+
reason: `Superserve lists at most 16 vCPU / 64 GiB per sandbox (Pro plan); ${profile.sizeClass} needs ${profile.vcpus} vCPU / ${profile.memoryMiB / 1024} GiB. Set sizeTemplates.${profile.sizeClass} to a custom-size template to use it.`
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
const diskMiB = BUILT_IN_TEMPLATE_DISK_MIB[templateId];
|
|
239
|
+
return {
|
|
240
|
+
status: "supported",
|
|
241
|
+
nativeOptions: { templateId },
|
|
242
|
+
...diskMiB === void 0 ? {} : { resolved: { vcpus: profile.vcpus, memoryMiB: profile.memoryMiB, diskMiB } }
|
|
243
|
+
};
|
|
244
|
+
},
|
|
140
245
|
methods: {
|
|
141
246
|
instances: {
|
|
142
247
|
create: async (config, options) => {
|
|
@@ -149,6 +254,7 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
149
254
|
metadata,
|
|
150
255
|
templateId,
|
|
151
256
|
snapshotId,
|
|
257
|
+
volumes,
|
|
152
258
|
namespace: _namespace,
|
|
153
259
|
directory: _directory,
|
|
154
260
|
...providerOptions
|
|
@@ -156,7 +262,7 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
156
262
|
const ttMs = requestedTimeoutMs ?? config.timeout;
|
|
157
263
|
const timeoutSeconds = ttMs !== void 0 ? Math.max(1, Math.ceil(ttMs / 1e3)) : void 0;
|
|
158
264
|
try {
|
|
159
|
-
const
|
|
265
|
+
const createOptions = {
|
|
160
266
|
apiKey,
|
|
161
267
|
baseUrl,
|
|
162
268
|
name: name ?? generateSandboxName(),
|
|
@@ -165,10 +271,21 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
165
271
|
...timeoutSeconds !== void 0 ? { timeoutSeconds } : {},
|
|
166
272
|
...metadata ? { metadata } : {},
|
|
167
273
|
...envs ? { envVars: envs } : {},
|
|
168
|
-
...providerOptions
|
|
169
|
-
|
|
274
|
+
...providerOptions,
|
|
275
|
+
...volumes !== void 0 ? {
|
|
276
|
+
volumes: volumes.map((mount) => ({
|
|
277
|
+
...mount,
|
|
278
|
+
volume: mount.volume instanceof import_sdk.Volume ? mount.volume : volumeReference(mount.volume)
|
|
279
|
+
}))
|
|
280
|
+
} : {}
|
|
281
|
+
};
|
|
282
|
+
const connection = (0, import_sdk.resolveConfig)(createOptions);
|
|
283
|
+
const sandbox = await import_sdk.Sandbox.create(createOptions);
|
|
284
|
+
volumeConnections.set(sandbox, connection);
|
|
170
285
|
return { instance: sandbox, instanceId: sandbox.id };
|
|
171
286
|
} catch (error) {
|
|
287
|
+
const notBuilt = missingSizeTemplate(config, templateId, error);
|
|
288
|
+
if (notBuilt) throw Object.assign(new Error(notBuilt), { status: 404, cause: error });
|
|
172
289
|
rethrowFriendly(error, "Failed to create Superserve sandbox");
|
|
173
290
|
}
|
|
174
291
|
},
|
|
@@ -176,7 +293,9 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
176
293
|
const apiKey = resolveApiKey(config);
|
|
177
294
|
const baseUrl = resolveBaseUrl(config);
|
|
178
295
|
try {
|
|
179
|
-
const
|
|
296
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey, baseUrl });
|
|
297
|
+
const sandbox = await import_sdk.Sandbox.connect(sandboxId, connection);
|
|
298
|
+
volumeConnections.set(sandbox, connection);
|
|
180
299
|
return { instance: sandbox, instanceId: sandbox.id };
|
|
181
300
|
} catch {
|
|
182
301
|
return null;
|
|
@@ -186,11 +305,13 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
186
305
|
const apiKey = resolveApiKey(config);
|
|
187
306
|
const baseUrl = resolveBaseUrl(config);
|
|
188
307
|
try {
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
308
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey, baseUrl });
|
|
309
|
+
const infos = await import_sdk.Sandbox.list(connection);
|
|
310
|
+
return infos.map((info) => {
|
|
311
|
+
const instance = info;
|
|
312
|
+
volumeConnections.set(instance, connection);
|
|
313
|
+
return { instance, instanceId: info.id };
|
|
314
|
+
});
|
|
194
315
|
} catch {
|
|
195
316
|
return [];
|
|
196
317
|
}
|
|
@@ -202,6 +323,18 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
202
323
|
},
|
|
203
324
|
runCommand,
|
|
204
325
|
streamCommand: runCommand,
|
|
326
|
+
attachVolume: async (sandbox, volume, mountPath) => {
|
|
327
|
+
const native = await import_sdk.Volume.connect(volumeReference(volume), volumeConnection(sandbox));
|
|
328
|
+
await native.attach(sandbox.id, { mountPath });
|
|
329
|
+
},
|
|
330
|
+
detachVolume: async (sandbox, volume, mountPath) => {
|
|
331
|
+
const native = await import_sdk.Volume.connect(volumeReference(volume), volumeConnection(sandbox));
|
|
332
|
+
const attachments = (await native.listAttachments()).filter((attachment) => attachment.volumeId === native.id && sameSandboxId(attachment.sandboxId, sandbox.id) && attachment.status !== "revoked" && (mountPath === void 0 || attachment.mountPath === mountPath));
|
|
333
|
+
if (attachments.length > 1) {
|
|
334
|
+
throw new Error("Multiple matching Superserve attachments; provide their mount path to detach one.");
|
|
335
|
+
}
|
|
336
|
+
if (attachments[0]) await native.detach(attachments[0].id);
|
|
337
|
+
},
|
|
205
338
|
getInfo: async (sandbox) => {
|
|
206
339
|
const info = await sandbox.getInfo();
|
|
207
340
|
const status = info.status === "paused" || info.status === "deleted" ? "stopped" : info.status === "failed" ? "error" : "running";
|
|
@@ -323,6 +456,38 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
323
456
|
await import_sdk.Snapshot.deleteById(snapshotId, { apiKey, baseUrl });
|
|
324
457
|
}
|
|
325
458
|
},
|
|
459
|
+
volume: {
|
|
460
|
+
create: async (config, options) => {
|
|
461
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
462
|
+
const volume = await import_sdk.Volume.create({
|
|
463
|
+
...connection,
|
|
464
|
+
name: options.name,
|
|
465
|
+
...options.sizeBytes !== void 0 ? { capacityBytes: options.sizeBytes } : {},
|
|
466
|
+
idempotencyKey: options.idempotencyKey,
|
|
467
|
+
timeoutMs: options.timeoutMs,
|
|
468
|
+
signal: options.signal
|
|
469
|
+
});
|
|
470
|
+
return toVolume(volume);
|
|
471
|
+
},
|
|
472
|
+
get: async (config, idOrName) => {
|
|
473
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
474
|
+
try {
|
|
475
|
+
return toVolume(await import_sdk.Volume.connect(idOrName, connection));
|
|
476
|
+
} catch (error) {
|
|
477
|
+
if (error instanceof import_sdk.NotFoundError) return null;
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
},
|
|
481
|
+
list: async (config, options) => {
|
|
482
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
483
|
+
const volumes = await import_sdk.Volume.list({ ...connection, limit: options?.limit });
|
|
484
|
+
return volumes.map(toVolume);
|
|
485
|
+
},
|
|
486
|
+
delete: async (config, idOrName) => {
|
|
487
|
+
const connection = (0, import_sdk.resolveConfig)({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
488
|
+
await deleteVolume(connection, idOrName);
|
|
489
|
+
}
|
|
490
|
+
},
|
|
326
491
|
template: {
|
|
327
492
|
create: async (config, options) => {
|
|
328
493
|
const apiKey = resolveApiKey(config);
|
|
@@ -372,6 +537,7 @@ var superserve = (0, import_provider.defineProvider)({
|
|
|
372
537
|
});
|
|
373
538
|
// Annotate the CommonJS export names for ESM import in node:
|
|
374
539
|
0 && (module.exports = {
|
|
540
|
+
SUPERSERVE_SIZE_TEMPLATES,
|
|
375
541
|
superserve
|
|
376
542
|
});
|
|
377
543
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Superserve Provider - Factory-based Implementation\n *\n * Wraps `@superserve/sdk` to expose the ComputeSDK provider interface.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n AuthenticationError,\n Sandbox as SuperserveSandbox,\n Snapshot as SuperserveSnapshot,\n Template as SuperserveTemplate,\n} from '@superserve/sdk';\nimport type { SnapshotInfo, TemplateCreateOptions, TemplateInfo } from '@superserve/sdk';\nimport { defineProvider, escapeShellArg } from '@computesdk/provider';\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateTemplateOptions,\n FileEntry,\n RunCommandOptions,\n InstanceInfo,\n} from '@computesdk/provider';\n\nexport interface SuperserveConfig {\n /** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */\n apiKey?: string;\n /** API base URL. Falls back to `SUPERSERVE_BASE_URL` env var, then the `@superserve/sdk` default. */\n baseUrl?: string;\n /** Default auto-pause timeout in milliseconds. */\n timeout?: number;\n}\n\nfunction resolveApiKey(config: SuperserveConfig): string {\n const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;\n if (!apiKey) {\n throw new Error(\n `Missing Superserve API key. Provide 'apiKey' in config or set SUPERSERVE_API_KEY environment variable.`,\n );\n }\n return apiKey;\n}\n\nfunction resolveBaseUrl(config: SuperserveConfig): string | undefined {\n // Returns undefined when unset on purpose: the SDK then applies its own\n // resolution (SUPERSERVE_BASE_URL env var, then its default endpoint), so\n // we don't duplicate that default and risk it drifting.\n return config.baseUrl || process.env.SUPERSERVE_BASE_URL || undefined;\n}\n\nfunction generateSandboxName(): string {\n return `cs-${randomUUID().slice(0, 8)}`;\n}\n\ntype CommandRunner = (\n sandbox: SuperserveSandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\nconst FALLBACK_WORKDIR = '/';\n\n/** Cached `pwd` probes: relative filesystem paths resolve against the cwd a\n * `runCommand` exec would use, so `writeFile('a.txt')` and `cat a.txt` agree. */\nconst workdirs = new WeakMap<SuperserveSandbox, Promise<string>>();\n\nfunction workdirOf(sandbox: SuperserveSandbox, runCommand: CommandRunner): Promise<string> {\n let probe = workdirs.get(sandbox);\n if (!probe) {\n probe = runCommand(sandbox, 'pwd').then((result) => {\n const dir = result.stdout.trim();\n if (result.exitCode === 0 && dir.startsWith('/')) return dir;\n // runCommand reports exec failures as results, not rejections, so a\n // transient failure must not pin the workdir to the fallback forever —\n // evict and let the next filesystem op probe again.\n workdirs.delete(sandbox);\n return FALLBACK_WORKDIR;\n });\n workdirs.set(sandbox, probe);\n probe.catch(() => workdirs.delete(sandbox));\n }\n return probe;\n}\n\n/** Join `path` onto the sandbox workdir. Absolute paths pass through and skip\n * the probe; empty and `.` segments are dropped; `..` segments are preserved\n * for the sandbox filesystem to resolve physically — collapsing them\n * lexically would mis-resolve when a preceding component is a symlink. */\nasync function resolveSandboxPath(\n sandbox: SuperserveSandbox,\n path: string,\n runCommand: CommandRunner,\n): Promise<string> {\n const combined = path.startsWith('/')\n ? path\n : `${await workdirOf(sandbox, runCommand)}/${path}`;\n const segments: string[] = [];\n for (const segment of combined.split('/')) {\n if (segment === '' || segment === '.') continue;\n segments.push(segment);\n }\n return `/${segments.join('/')}`;\n}\n\nfunction rethrowFriendly(error: unknown, fallbackPrefix: string): never {\n if (error instanceof AuthenticationError) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n if (lower.includes('unauthorized') || lower.includes('401') || lower.includes('api key')) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n if (lower.includes('quota') || lower.includes('limit') || lower.includes('429')) {\n throw new Error(`Superserve quota or rate limit reached: ${message}`);\n }\n throw new Error(`${fallbackPrefix}: ${message}`);\n}\n\n// Also serves as `streamCommand`: the SDK streams output over its own exec API\n// when callbacks are passed, so no daemon or routable port is needed.\nconst runCommand: CommandRunner = async (sandbox, command, options) => {\n const startTime = Date.now();\n try {\n let fullCommand = command;\n if (options?.background) {\n // Run the whole command under `sh -c` so the trailing `&` backgrounds\n // the entire command (not just its last statement), and escape it so\n // the user's command can't break out of the nohup wrapper.\n fullCommand = `nohup sh -c \"${escapeShellArg(fullCommand)}\" > /dev/null 2>&1 &`;\n }\n const result = await sandbox.commands.run(fullCommand, {\n cwd: options?.cwd,\n env: options?.env,\n timeoutMs: options?.timeout,\n onStdout: options?.onStdout,\n onStderr: options?.onStderr,\n });\n return {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n stdout: '',\n stderr: error instanceof Error ? error.message : String(error),\n exitCode: 127,\n durationMs: Date.now() - startTime,\n };\n }\n};\n\nfunction toSnapshot(info: SnapshotInfo) {\n return {\n id: info.id,\n provider: 'superserve',\n createdAt: info.createdAt,\n metadata: {\n name: info.name,\n sandboxId: info.sandboxId,\n status: info.status,\n sizeBytes: info.sizeBytes,\n },\n };\n}\n\n/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set\n * here and every sandbox created from it inherits them. */\nexport type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;\n\nfunction toTemplate(info: TemplateInfo) {\n return {\n id: info.id,\n name: info.name,\n createdAt: info.createdAt,\n metadata: { status: info.status, vcpu: info.vcpu, memoryMib: info.memoryMib, diskMib: info.diskMib, errorMessage: info.errorMessage },\n };\n}\n\nexport const superserve = defineProvider<SuperserveSandbox, SuperserveConfig>({\n name: 'superserve',\n methods: {\n instances: {\n create: async (config: SuperserveConfig, options?: CreateInstanceOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n\n const {\n timeout: requestedTimeoutMs,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n namespace: _namespace,\n directory: _directory,\n ...providerOptions\n } = options || {};\n\n const ttMs = requestedTimeoutMs ?? config.timeout;\n const timeoutSeconds = ttMs !== undefined ? Math.max(1, Math.ceil(ttMs / 1000)) : undefined;\n\n try {\n const sandbox = await SuperserveSandbox.create({\n apiKey,\n baseUrl,\n name: name ?? generateSandboxName(),\n ...(templateId ? { fromTemplate: templateId } : {}),\n ...(snapshotId ? { fromSnapshot: snapshotId } : {}),\n ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n ...(metadata ? { metadata: metadata as Record<string, string> } : {}),\n ...(envs ? { envVars: envs } : {}),\n ...providerOptions,\n });\n return { instance: sandbox, instanceId: sandbox.id };\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve sandbox');\n }\n },\n\n getById: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return { instance: sandbox, instanceId: sandbox.id };\n } catch {\n return null;\n }\n },\n\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveSandbox.list({ apiKey, baseUrl });\n // No per-item connect() — that would POST /activate and resume paused sandboxes.\n return infos.map((info) => ({ instance: info as unknown as SuperserveSandbox, instanceId: info.id,\n }));\n } catch {\n return [];\n }\n },\n\n destroy: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n // The SDK handles already-deleted sandboxes and retries transient failures.\n await SuperserveSandbox.killById(sandboxId, { apiKey, baseUrl });\n },\n\n runCommand,\n streamCommand: runCommand,\n\n getInfo: async (sandbox: SuperserveSandbox): Promise<InstanceInfo> => {\n const info = await sandbox.getInfo();\n const status: InstanceInfo['status'] =\n info.status === 'paused' || info.status === 'deleted' ? 'stopped' :\n info.status === 'failed' ? 'error' :\n 'running';\n return {\n id: info.id,\n provider: 'superserve',\n status,\n createdAt: info.createdAt,\n timeout: info.timeoutSeconds ? info.timeoutSeconds * 1000 : DEFAULT_TIMEOUT_MS,\n metadata: info.metadata,\n };\n },\n\n getUrl: async (sandbox: SuperserveSandbox, options: { port: number; protocol?: string }): Promise<string> => {\n // A preview URL only routes once its port is published. A new port takes\n // the sandbox's `previewAccess` default; a published one keeps its mode.\n await sandbox.publishPreviewPort(options.port);\n const url = sandbox.getPreviewUrl(options.port);\n return options.protocol ? url.replace(/^https/, options.protocol) : url;\n },\n\n filesystem: {\n readFile: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n return sandbox.files.readText(await resolveSandboxPath(sandbox, path, runCommand));\n },\n\n writeFile: async (sandbox: SuperserveSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n await sandbox.files.write(await resolveSandboxPath(sandbox, path, runCommand), content);\n },\n\n mkdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`mkdir -p \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`mkdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n\n readdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n // find -printf format: <type>\\t<size>\\t<mtime-epoch>\\t<name>\n const cmd = [\n `cd \"${escapeShellArg(resolved)}\" || exit 2`,\n `find . -mindepth 1 -maxdepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%f\\\\n' 2>/dev/null`,\n ].join(' && ');\n const result = await sandbox.commands.run(cmd);\n if (result.exitCode === 2) {\n throw new Error(`readdir: directory not found: ${path}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n const entries: FileEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...nameParts] = line.split('\\t');\n const name = nameParts.join('\\t');\n if (!name) continue;\n const size = Number.parseInt(sizeStr, 10);\n const mtime = Number.parseFloat(mtimeStr);\n entries.push({\n name,\n type: type === 'd' ? 'directory' : 'file',\n size: Number.isFinite(size) ? size : 0,\n modified: Number.isFinite(mtime) ? new Date(mtime * 1000) : new Date(),\n });\n }\n return entries;\n },\n\n exists: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`test -e \"${escapeShellArg(resolved)}\"`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n // An empty or dot-only path would resolve to the workdir itself —\n // refuse it rather than `rm -rf` the sandbox's whole cwd.\n if (path.split('/').every((s) => s === '' || s === '.')) {\n throw new Error(`remove: refusing ambiguous path: ${JSON.stringify(path)}`);\n }\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`rm -rf \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`remove failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n },\n\n getInstance: (sandbox: SuperserveSandbox): SuperserveSandbox => sandbox,\n\n pause: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n await sandbox.pause({ wait: true });\n } catch (error) {\n rethrowFriendly(error, 'Failed to pause Superserve sandbox');\n }\n },\n\n resume: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n // The access token rotates on resume; the SDK refreshes the handle in place.\n await sandbox.resume();\n } catch (error) {\n rethrowFriendly(error, 'Failed to resume Superserve sandbox');\n }\n },\n\n pauseCapabilities: { memory: true },\n },\n\n snapshot: {\n // Snapshots hold memory and disk: restores keep the whole filesystem,\n // tmpfs /tmp included, and running processes. The source keeps running.\n capabilities: { scope: 'rootfs', memory: true, destroysSource: false },\n create: async (config: SuperserveConfig, sandboxId: string, options?: { name?: string }) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n // connect() activates the sandbox, so a paused one is resumed first.\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return toSnapshot(await sandbox.snapshot({ name: options?.name }));\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve snapshot');\n }\n },\n list: async (config: SuperserveConfig, options?: { sandboxId?: string; limit?: number }) => {\n // Snapshots are listed per sandbox. Callers that aggregate across\n // providers pass no options, so an unscoped call returns nothing\n // instead of throwing and failing their whole listing.\n if (!options?.sandboxId) return [];\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const infos = await SuperserveSnapshot.list(options.sandboxId, { apiKey, baseUrl, limit: options.limit });\n return infos.map(toSnapshot);\n },\n delete: async (config: SuperserveConfig, snapshotId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });\n },\n },\n\n template: {\n create: async (config: SuperserveConfig, options: SuperserveTemplateCreateOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const { name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd } = options;\n if (!from) {\n throw new Error('Superserve templates are built from an image: pass `from` (e.g. \"node:22\").');\n }\n try {\n const template = await SuperserveTemplate.create({\n apiKey, baseUrl, name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd,\n });\n return toTemplate(await template.waitUntilReady());\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve template');\n }\n },\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveTemplate.list({ apiKey, baseUrl });\n return infos.map(toTemplate);\n } catch {\n return [];\n }\n },\n delete: async (config: SuperserveConfig, templateId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n await SuperserveTemplate.deleteById(templateId, { apiKey, baseUrl });\n } catch {\n /* already deleted */\n }\n },\n },\n },\n});\n\nexport type { Sandbox as SuperserveSandbox } from '@superserve/sdk';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,yBAA2B;AAC3B,iBAKO;AAEP,sBAA+C;AAE/C,IAAM,qBAAqB;AAoB3B,SAAS,cAAc,QAAkC;AACvD,QAAM,SAAS,OAAO,UAAU,QAAQ,IAAI;AAC5C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,QAA8C;AAIpE,SAAO,OAAO,WAAW,QAAQ,IAAI,uBAAuB;AAC9D;AAEA,SAAS,sBAA8B;AACrC,SAAO,UAAM,+BAAW,EAAE,MAAM,GAAG,CAAC,CAAC;AACvC;AAQA,IAAM,mBAAmB;AAIzB,IAAM,WAAW,oBAAI,QAA4C;AAEjE,SAAS,UAAU,SAA4BA,aAA4C;AACzF,MAAI,QAAQ,SAAS,IAAI,OAAO;AAChC,MAAI,CAAC,OAAO;AACV,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AAA,QAC/F;AACA,YAAI;AACF,gBAAM,WAAW,MAAM,WAAAC,SAAmB,OAAO;AAAA,YAC/C;AAAA,YAAQ;AAAA,YAAS;AAAA,YAAM;AAAA,YAAM;AAAA,YAAM;AAAA,YAAW;AAAA,YAAS;AAAA,YAAO;AAAA,YAAU;AAAA,UAC1E,CAAC;AACD,iBAAO,WAAW,MAAM,SAAS,eAAe,CAAC;AAAA,QACnD,SAAS,OAAO;AACd,0BAAgB,OAAO,sCAAsC;AAAA,QAC/D;AAAA,MACF;AAAA,MACA,MAAM,OAAO,WAA6B;AACxC,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,QAAQ,MAAM,WAAAA,SAAmB,KAAK,EAAE,QAAQ,QAAQ,CAAC;AAC/D,iBAAO,MAAM,IAAI,UAAU;AAAA,QAC7B,QAAQ;AACN,iBAAO,CAAC;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ,OAAO,QAA0B,eAAuB;AAC9D,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,WAAAA,SAAmB,WAAW,YAAY,EAAE,QAAQ,QAAQ,CAAC;AAAA,QACrE,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["runCommand","SuperserveSandbox","SuperserveSnapshot","SuperserveTemplate"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Superserve Provider - Factory-based Implementation\n *\n * Wraps `@superserve/sdk` to expose the ComputeSDK provider interface.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n AuthenticationError,\n ConflictError,\n NotFoundError,\n Sandbox as SuperserveSandbox,\n Snapshot as SuperserveSnapshot,\n Template as SuperserveTemplate,\n Volume as SuperserveVolume,\n resolveConfig,\n} from '@superserve/sdk';\nimport type {\n ResolvedConfig,\n SnapshotInfo,\n TemplateCreateOptions,\n TemplateInfo,\n VolumeCreateOptions,\n VolumeInfo,\n} from '@superserve/sdk';\nimport { defineProvider, escapeShellArg, InstanceSizeError, INSTANCE_SIZE_PROFILES } from '@computesdk/provider';\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateTemplateOptions,\n CreateVolumeOptions,\n FileEntry,\n InstanceSizeClass,\n RunCommandOptions,\n InstanceInfo,\n Volume,\n} from '@computesdk/provider';\n\nexport interface SuperserveConfig {\n /** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */\n apiKey?: string;\n /** API base URL. Falls back to `SUPERSERVE_BASE_URL` env var, then the `@superserve/sdk` default. */\n baseUrl?: string;\n /** Default auto-pause timeout in milliseconds. */\n timeout?: number;\n /** Template to boot per standard `sizeClass`; defaults to {@link SUPERSERVE_SIZE_TEMPLATES}. */\n sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;\n}\n\n/**\n * Superserve fixes vCPU, memory and disk when a template is built, so each\n * standard size boots its own template. `superserve/base` (2 vCPU / 4 GiB /\n * 8 GiB disk) is built in to every team; the others are team templates\n * built by `scripts/provider-setup.mjs superserve`. The largest listed plan\n * (Pro) caps a sandbox at 16 vCPU / 64 GiB, so `3xl` has no default.\n */\nexport const SUPERSERVE_SIZE_TEMPLATES: Readonly<Partial<Record<InstanceSizeClass, string>>> = Object.freeze({\n xs: 'csdk-node22-1cpu-1gb',\n sm: 'csdk-node22-1cpu-2gb',\n md: 'superserve/base',\n lg: 'csdk-node22-4cpu-8gb',\n xl: 'csdk-node22-8cpu-16gb',\n '2xl': 'csdk-node22-16cpu-32gb',\n});\n\n/** Disk the built-in templates fix; team templates take theirs from the build. */\nconst BUILT_IN_TEMPLATE_DISK_MIB: Readonly<Record<string, number>> = Object.freeze({ 'superserve/base': 8192 });\n\n/** Native selectors that pick or size the VM; `Sandbox.create` drops the sizing ones silently. */\nconst SOURCE_OPTIONS = ['templateId', 'snapshotId', 'sandboxId', 'fromTemplate', 'fromSnapshot'] as const;\nconst NATIVE_SIZE_OPTIONS = ['vcpu', 'vcpuCount', 'memoryMib', 'memoryMaxMib', 'diskMib'] as const;\n\nfunction sizeTemplateOf(config: SuperserveConfig, sizeClass: InstanceSizeClass): string | undefined {\n const name = config.sizeTemplates?.[sizeClass] ?? SUPERSERVE_SIZE_TEMPLATES[sizeClass];\n return typeof name === 'string' && name.trim() ? name : undefined;\n}\n\n/** A create that failed because a standard-size template was never built on this team. */\nfunction missingSizeTemplate(config: SuperserveConfig, templateId: unknown, error: unknown): string | undefined {\n if (typeof templateId !== 'string' || !(error instanceof NotFoundError)) return undefined;\n const sizeClass = (Object.keys(INSTANCE_SIZE_PROFILES) as InstanceSizeClass[]).find(c => sizeTemplateOf(config, c) === templateId);\n if (!sizeClass) return undefined;\n return `Superserve size template '${templateId}' (sizeClass ${sizeClass}) is not built on this Superserve team; run \\`node scripts/provider-setup.mjs superserve\\` (provider-setup.yml) or point \\`sizeTemplates.${sizeClass}\\` at an existing template`;\n}\n\nfunction resolveApiKey(config: SuperserveConfig): string {\n const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;\n if (!apiKey) {\n throw new Error(\n `Missing Superserve API key. Provide 'apiKey' in config or set SUPERSERVE_API_KEY environment variable.`,\n );\n }\n return apiKey;\n}\n\nfunction resolveBaseUrl(config: SuperserveConfig): string | undefined {\n // Returns undefined when unset on purpose: the SDK then applies its own\n // resolution (SUPERSERVE_BASE_URL env var, then its default endpoint), so\n // we don't duplicate that default and risk it drifting.\n return config.baseUrl || process.env.SUPERSERVE_BASE_URL || undefined;\n}\n\nfunction generateSandboxName(): string {\n return `cs-${randomUUID().slice(0, 8)}`;\n}\n\ntype CommandRunner = (\n sandbox: SuperserveSandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\nconst FALLBACK_WORKDIR = '/';\n\n/** Cached `pwd` probes: relative filesystem paths resolve against the cwd a\n * `runCommand` exec would use, so `writeFile('a.txt')` and `cat a.txt` agree. */\nconst workdirs = new WeakMap<SuperserveSandbox, Promise<string>>();\nconst volumeConnections = new WeakMap<SuperserveSandbox, ResolvedConfig>();\n\nfunction volumeReference(volume: string | Volume): string {\n const reference = typeof volume === 'string' ? volume : volume?.id || volume?.name;\n if (typeof reference !== 'string' || !reference.trim()) {\n throw new Error('A Superserve volume reference must contain an id or name.');\n }\n return reference;\n}\n\nfunction volumeConnection(sandbox: SuperserveSandbox): ResolvedConfig {\n const connection = volumeConnections.get(sandbox);\n if (!connection) throw new Error('The Superserve sandbox has no captured volume connection.');\n return connection;\n}\n\nfunction sameSandboxId(left: string, right: string): boolean {\n const pattern = /^(?:sb-([A-Za-z0-9]+)-)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;\n const a = pattern.exec(left);\n const b = pattern.exec(right);\n if (!a || !b) return left === right;\n return a[2].toLowerCase() === b[2].toLowerCase() &&\n (a[1] === undefined || b[1] === undefined || a[1] === b[1]);\n}\n\nfunction toVolume(info: VolumeInfo): Volume {\n return {\n id: info.id,\n name: info.name,\n sizeBytes: info.capacityBytes,\n usedBytes: info.usedBytes,\n region: info.region,\n status: info.status,\n createdAt: info.createdAt,\n };\n}\n\nasync function deleteVolume(connection: ResolvedConfig, idOrName: string): Promise<void> {\n let volume: SuperserveVolume;\n try {\n volume = await SuperserveVolume.connect(idOrName, connection);\n } catch (error) {\n if (error instanceof NotFoundError) return;\n throw error;\n }\n // Names can be reused while closing leases settle. Resolve once so retries\n // and attachment checks stay bound to the original volume.\n const deadline = Date.now() + 120_000;\n for (;;) {\n try {\n await SuperserveVolume.deleteById(volume.id, connection);\n return;\n } catch (error) {\n if (!(error instanceof ConflictError) || error.code !== 'volume_conflict') throw error;\n let attachments;\n try {\n attachments = await volume.listAttachments();\n } catch (lookupError) {\n if (lookupError instanceof NotFoundError) return;\n throw lookupError;\n }\n const closing = attachments.filter((attachment) => attachment.status !== 'revoked');\n // A destroyed sandbox can leave a closing lease briefly. Never wait on\n // an active mount, or turn another kind of conflict into successful cleanup.\n if (!closing.length || closing.some((attachment) =>\n attachment.status !== 'detaching' && attachment.status !== 'revoking') ||\n Date.now() >= deadline) throw error;\n await new Promise((resolve) => setTimeout(resolve, 3_000));\n }\n }\n}\n\nfunction workdirOf(sandbox: SuperserveSandbox, runCommand: CommandRunner): Promise<string> {\n let probe = workdirs.get(sandbox);\n if (!probe) {\n probe = runCommand(sandbox, 'pwd').then((result) => {\n const dir = result.stdout.trim();\n if (result.exitCode === 0 && dir.startsWith('/')) return dir;\n // runCommand reports exec failures as results, not rejections, so a\n // transient failure must not pin the workdir to the fallback forever —\n // evict and let the next filesystem op probe again.\n workdirs.delete(sandbox);\n return FALLBACK_WORKDIR;\n });\n workdirs.set(sandbox, probe);\n probe.catch(() => workdirs.delete(sandbox));\n }\n return probe;\n}\n\n/** Join `path` onto the sandbox workdir. Absolute paths pass through and skip\n * the probe; empty and `.` segments are dropped; `..` segments are preserved\n * for the sandbox filesystem to resolve physically — collapsing them\n * lexically would mis-resolve when a preceding component is a symlink. */\nasync function resolveSandboxPath(\n sandbox: SuperserveSandbox,\n path: string,\n runCommand: CommandRunner,\n): Promise<string> {\n const combined = path.startsWith('/')\n ? path\n : `${await workdirOf(sandbox, runCommand)}/${path}`;\n const segments: string[] = [];\n for (const segment of combined.split('/')) {\n if (segment === '' || segment === '.') continue;\n segments.push(segment);\n }\n return `/${segments.join('/')}`;\n}\n\nfunction rethrowFriendly(error: unknown, fallbackPrefix: string): never {\n if (error instanceof AuthenticationError) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n if (lower.includes('unauthorized') || lower.includes('401') || lower.includes('api key')) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n if (lower.includes('quota') || lower.includes('limit') || lower.includes('429')) {\n throw new Error(`Superserve quota or rate limit reached: ${message}`);\n }\n throw new Error(`${fallbackPrefix}: ${message}`);\n}\n\n// Also serves as `streamCommand`: the SDK streams output over its own exec API\n// when callbacks are passed, so no daemon or routable port is needed.\nconst runCommand: CommandRunner = async (sandbox, command, options) => {\n const startTime = Date.now();\n try {\n let fullCommand = command;\n if (options?.background) {\n // Run the whole command under `sh -c` so the trailing `&` backgrounds\n // the entire command (not just its last statement), and escape it so\n // the user's command can't break out of the nohup wrapper.\n fullCommand = `nohup sh -c \"${escapeShellArg(fullCommand)}\" > /dev/null 2>&1 &`;\n }\n const result = await sandbox.commands.run(fullCommand, {\n cwd: options?.cwd,\n env: options?.env,\n timeoutMs: options?.timeout,\n onStdout: options?.onStdout,\n onStderr: options?.onStderr,\n });\n return {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n stdout: '',\n stderr: error instanceof Error ? error.message : String(error),\n exitCode: 127,\n durationMs: Date.now() - startTime,\n };\n }\n};\n\nfunction toSnapshot(info: SnapshotInfo) {\n return {\n id: info.id,\n provider: 'superserve',\n createdAt: info.createdAt,\n metadata: {\n name: info.name,\n sandboxId: info.sandboxId,\n status: info.status,\n sizeBytes: info.sizeBytes,\n },\n };\n}\n\n/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set\n * here and every sandbox created from it inherits them. */\nexport type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;\nexport type SuperserveVolumeCreateOptions = CreateVolumeOptions &\n Pick<VolumeCreateOptions, 'idempotencyKey' | 'timeoutMs' | 'signal'>;\n\nfunction toTemplate(info: TemplateInfo) {\n return {\n id: info.id,\n name: info.name,\n createdAt: info.createdAt,\n metadata: { status: info.status, vcpu: info.vcpu, memoryMib: info.memoryMib, diskMib: info.diskMib, errorMessage: info.errorMessage },\n };\n}\n\nexport const superserve = defineProvider<SuperserveSandbox, SuperserveConfig>({\n name: 'superserve',\n sizes: (config, profile, options) => {\n const opts = options as Record<string, unknown> | undefined;\n const nativeSize = NATIVE_SIZE_OPTIONS.find(key => opts?.[key] !== undefined);\n if (nativeSize) {\n throw new InstanceSizeError('conflict', `cannot combine sizeClass with native Superserve ${nativeSize}; Superserve sizes sandboxes by template`);\n }\n const source = SOURCE_OPTIONS.find(key => opts?.[key] !== undefined);\n if (source) {\n return { status: 'unsupported', reason: `A Superserve template or snapshot fixes CPU and memory; drop ${source} to boot the standard size template.` };\n }\n const templateId = sizeTemplateOf(config, profile.sizeClass);\n if (!templateId) {\n return {\n status: 'unsupported',\n reason: `Superserve lists at most 16 vCPU / 64 GiB per sandbox (Pro plan); ${profile.sizeClass} needs ${profile.vcpus} vCPU / ${profile.memoryMiB / 1024} GiB. Set sizeTemplates.${profile.sizeClass} to a custom-size template to use it.`,\n };\n }\n const diskMiB = BUILT_IN_TEMPLATE_DISK_MIB[templateId];\n return {\n status: 'supported',\n nativeOptions: { templateId },\n ...(diskMiB === undefined ? {} : { resolved: { vcpus: profile.vcpus, memoryMiB: profile.memoryMiB, diskMiB } }),\n };\n },\n methods: {\n instances: {\n create: async (config: SuperserveConfig, options?: CreateInstanceOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n\n const {\n timeout: requestedTimeoutMs,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n volumes,\n namespace: _namespace,\n directory: _directory,\n ...providerOptions\n } = options || {};\n\n const ttMs = requestedTimeoutMs ?? config.timeout;\n const timeoutSeconds = ttMs !== undefined ? Math.max(1, Math.ceil(ttMs / 1000)) : undefined;\n\n try {\n const createOptions = {\n apiKey,\n baseUrl,\n name: name ?? generateSandboxName(),\n ...(templateId ? { fromTemplate: templateId } : {}),\n ...(snapshotId ? { fromSnapshot: snapshotId } : {}),\n ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n ...(metadata ? { metadata: metadata as Record<string, string> } : {}),\n ...(envs ? { envVars: envs } : {}),\n ...providerOptions,\n ...(volumes !== undefined ? {\n volumes: volumes.map((mount) => ({\n ...mount,\n volume: mount.volume instanceof SuperserveVolume\n ? mount.volume\n : volumeReference(mount.volume),\n })),\n } : {}),\n };\n const connection = resolveConfig(createOptions);\n const sandbox = await SuperserveSandbox.create(createOptions);\n volumeConnections.set(sandbox, connection);\n return { instance: sandbox, instanceId: sandbox.id };\n } catch (error) {\n const notBuilt = missingSizeTemplate(config, templateId, error);\n if (notBuilt) throw Object.assign(new Error(notBuilt), { status: 404, cause: error });\n rethrowFriendly(error, 'Failed to create Superserve sandbox');\n }\n },\n\n getById: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const connection = resolveConfig({ apiKey, baseUrl });\n const sandbox = await SuperserveSandbox.connect(sandboxId, connection);\n volumeConnections.set(sandbox, connection);\n return { instance: sandbox, instanceId: sandbox.id };\n } catch {\n return null;\n }\n },\n\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const connection = resolveConfig({ apiKey, baseUrl });\n const infos = await SuperserveSandbox.list(connection);\n // No per-item connect() — that would POST /activate and resume paused sandboxes.\n return infos.map((info) => {\n const instance = info as unknown as SuperserveSandbox;\n volumeConnections.set(instance, connection);\n return { instance, instanceId: info.id };\n });\n } catch {\n return [];\n }\n },\n\n destroy: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n // The SDK handles already-deleted sandboxes and retries transient failures.\n await SuperserveSandbox.killById(sandboxId, { apiKey, baseUrl });\n },\n\n runCommand,\n streamCommand: runCommand,\n\n attachVolume: async (sandbox, volume, mountPath) => {\n const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));\n await native.attach(sandbox.id, { mountPath });\n },\n\n detachVolume: async (sandbox, volume, mountPath) => {\n const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));\n const attachments = (await native.listAttachments()).filter((attachment) =>\n attachment.volumeId === native.id &&\n sameSandboxId(attachment.sandboxId, sandbox.id) &&\n attachment.status !== 'revoked' &&\n (mountPath === undefined || attachment.mountPath === mountPath));\n if (attachments.length > 1) {\n throw new Error('Multiple matching Superserve attachments; provide their mount path to detach one.');\n }\n if (attachments[0]) await native.detach(attachments[0].id);\n },\n\n getInfo: async (sandbox: SuperserveSandbox): Promise<InstanceInfo> => {\n const info = await sandbox.getInfo();\n const status: InstanceInfo['status'] =\n info.status === 'paused' || info.status === 'deleted' ? 'stopped' :\n info.status === 'failed' ? 'error' :\n 'running';\n return {\n id: info.id,\n provider: 'superserve',\n status,\n createdAt: info.createdAt,\n timeout: info.timeoutSeconds ? info.timeoutSeconds * 1000 : DEFAULT_TIMEOUT_MS,\n metadata: info.metadata,\n };\n },\n\n getUrl: async (sandbox: SuperserveSandbox, options: { port: number; protocol?: string }): Promise<string> => {\n // A preview URL only routes once its port is published. A new port takes\n // the sandbox's `previewAccess` default; a published one keeps its mode.\n await sandbox.publishPreviewPort(options.port);\n const url = sandbox.getPreviewUrl(options.port);\n return options.protocol ? url.replace(/^https/, options.protocol) : url;\n },\n\n filesystem: {\n readFile: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n return sandbox.files.readText(await resolveSandboxPath(sandbox, path, runCommand));\n },\n\n writeFile: async (sandbox: SuperserveSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n await sandbox.files.write(await resolveSandboxPath(sandbox, path, runCommand), content);\n },\n\n mkdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`mkdir -p \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`mkdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n\n readdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n // find -printf format: <type>\\t<size>\\t<mtime-epoch>\\t<name>\n const cmd = [\n `cd \"${escapeShellArg(resolved)}\" || exit 2`,\n `find . -mindepth 1 -maxdepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%f\\\\n' 2>/dev/null`,\n ].join(' && ');\n const result = await sandbox.commands.run(cmd);\n if (result.exitCode === 2) {\n throw new Error(`readdir: directory not found: ${path}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n const entries: FileEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...nameParts] = line.split('\\t');\n const name = nameParts.join('\\t');\n if (!name) continue;\n const size = Number.parseInt(sizeStr, 10);\n const mtime = Number.parseFloat(mtimeStr);\n entries.push({\n name,\n type: type === 'd' ? 'directory' : 'file',\n size: Number.isFinite(size) ? size : 0,\n modified: Number.isFinite(mtime) ? new Date(mtime * 1000) : new Date(),\n });\n }\n return entries;\n },\n\n exists: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`test -e \"${escapeShellArg(resolved)}\"`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n // An empty or dot-only path would resolve to the workdir itself —\n // refuse it rather than `rm -rf` the sandbox's whole cwd.\n if (path.split('/').every((s) => s === '' || s === '.')) {\n throw new Error(`remove: refusing ambiguous path: ${JSON.stringify(path)}`);\n }\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`rm -rf \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`remove failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n },\n\n getInstance: (sandbox: SuperserveSandbox): SuperserveSandbox => sandbox,\n\n pause: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n await sandbox.pause({ wait: true });\n } catch (error) {\n rethrowFriendly(error, 'Failed to pause Superserve sandbox');\n }\n },\n\n resume: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n // The access token rotates on resume; the SDK refreshes the handle in place.\n await sandbox.resume();\n } catch (error) {\n rethrowFriendly(error, 'Failed to resume Superserve sandbox');\n }\n },\n\n pauseCapabilities: { memory: true },\n },\n\n snapshot: {\n // Snapshots hold memory and disk: restores keep the whole filesystem,\n // tmpfs /tmp included, and running processes. The source keeps running.\n capabilities: { scope: 'rootfs', memory: true, destroysSource: false },\n create: async (config: SuperserveConfig, sandboxId: string, options?: { name?: string }) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n // connect() activates the sandbox, so a paused one is resumed first.\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return toSnapshot(await sandbox.snapshot({ name: options?.name }));\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve snapshot');\n }\n },\n list: async (config: SuperserveConfig, options?: { sandboxId?: string; limit?: number }) => {\n // Snapshots are listed per sandbox. Callers that aggregate across\n // providers pass no options, so an unscoped call returns nothing\n // instead of throwing and failing their whole listing.\n if (!options?.sandboxId) return [];\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const infos = await SuperserveSnapshot.list(options.sandboxId, { apiKey, baseUrl, limit: options.limit });\n return infos.map(toSnapshot);\n },\n delete: async (config: SuperserveConfig, snapshotId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });\n },\n },\n\n volume: {\n create: async (config: SuperserveConfig, options: SuperserveVolumeCreateOptions) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n const volume = await SuperserveVolume.create({\n ...connection,\n name: options.name,\n ...(options.sizeBytes !== undefined ? { capacityBytes: options.sizeBytes } : {}),\n idempotencyKey: options.idempotencyKey,\n timeoutMs: options.timeoutMs,\n signal: options.signal,\n });\n return toVolume(volume);\n },\n get: async (config: SuperserveConfig, idOrName: string) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n try {\n return toVolume(await SuperserveVolume.connect(idOrName, connection));\n } catch (error) {\n if (error instanceof NotFoundError) return null;\n throw error;\n }\n },\n list: async (config: SuperserveConfig, options?: { limit?: number }) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n const volumes = await SuperserveVolume.list({ ...connection, limit: options?.limit });\n return volumes.map(toVolume);\n },\n delete: async (config: SuperserveConfig, idOrName: string) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n await deleteVolume(connection, idOrName);\n },\n },\n\n template: {\n create: async (config: SuperserveConfig, options: SuperserveTemplateCreateOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const { name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd } = options;\n if (!from) {\n throw new Error('Superserve templates are built from an image: pass `from` (e.g. \"node:22\").');\n }\n try {\n const template = await SuperserveTemplate.create({\n apiKey, baseUrl, name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd,\n });\n return toTemplate(await template.waitUntilReady());\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve template');\n }\n },\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveTemplate.list({ apiKey, baseUrl });\n return infos.map(toTemplate);\n } catch {\n return [];\n }\n },\n delete: async (config: SuperserveConfig, templateId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n await SuperserveTemplate.deleteById(templateId, { apiKey, baseUrl });\n } catch {\n /* already deleted */\n }\n },\n },\n },\n});\n\nexport type { Sandbox as SuperserveSandbox } from '@superserve/sdk';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,yBAA2B;AAC3B,iBASO;AASP,sBAA0F;AAE1F,IAAM,qBAAqB;AAgCpB,IAAM,4BAAkF,OAAO,OAAO;AAAA,EAC3G,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,IAAI;AAAA,EACJ,OAAO;AACT,CAAC;AAGD,IAAM,6BAA+D,OAAO,OAAO,EAAE,mBAAmB,KAAK,CAAC;AAG9G,IAAM,iBAAiB,CAAC,cAAc,cAAc,aAAa,gBAAgB,cAAc;AAC/F,IAAM,sBAAsB,CAAC,QAAQ,aAAa,aAAa,gBAAgB,SAAS;AAExF,SAAS,eAAe,QAA0B,WAAkD;AAClG,QAAM,OAAO,OAAO,gBAAgB,SAAS,KAAK,0BAA0B,SAAS;AACrF,SAAO,OAAO,SAAS,YAAY,KAAK,KAAK,IAAI,OAAO;AAC1D;AAGA,SAAS,oBAAoB,QAA0B,YAAqB,OAAoC;AAC9G,MAAI,OAAO,eAAe,YAAY,EAAE,iBAAiB,0BAAgB,QAAO;AAChF,QAAM,YAAa,OAAO,KAAK,sCAAsB,EAA0B,KAAK,OAAK,eAAe,QAAQ,CAAC,MAAM,UAAU;AACjI,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,6BAA6B,UAAU,gBAAgB,SAAS,4IAA4I,SAAS;AAC9N;AAEA,SAAS,cAAc,QAAkC;AACvD,QAAM,SAAS,OAAO,UAAU,QAAQ,IAAI;AAC5C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,QAA8C;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serveSnapshot","SuperserveTemplate"]}
|
package/dist/index.mjs
CHANGED
|
@@ -2,12 +2,37 @@
|
|
|
2
2
|
import { randomUUID } from "crypto";
|
|
3
3
|
import {
|
|
4
4
|
AuthenticationError,
|
|
5
|
+
ConflictError,
|
|
6
|
+
NotFoundError,
|
|
5
7
|
Sandbox as SuperserveSandbox,
|
|
6
8
|
Snapshot as SuperserveSnapshot,
|
|
7
|
-
Template as SuperserveTemplate
|
|
9
|
+
Template as SuperserveTemplate,
|
|
10
|
+
Volume as SuperserveVolume,
|
|
11
|
+
resolveConfig
|
|
8
12
|
} from "@superserve/sdk";
|
|
9
|
-
import { defineProvider, escapeShellArg } from "@computesdk/provider";
|
|
13
|
+
import { defineProvider, escapeShellArg, InstanceSizeError, INSTANCE_SIZE_PROFILES } from "@computesdk/provider";
|
|
10
14
|
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
15
|
+
var SUPERSERVE_SIZE_TEMPLATES = Object.freeze({
|
|
16
|
+
xs: "csdk-node22-1cpu-1gb",
|
|
17
|
+
sm: "csdk-node22-1cpu-2gb",
|
|
18
|
+
md: "superserve/base",
|
|
19
|
+
lg: "csdk-node22-4cpu-8gb",
|
|
20
|
+
xl: "csdk-node22-8cpu-16gb",
|
|
21
|
+
"2xl": "csdk-node22-16cpu-32gb"
|
|
22
|
+
});
|
|
23
|
+
var BUILT_IN_TEMPLATE_DISK_MIB = Object.freeze({ "superserve/base": 8192 });
|
|
24
|
+
var SOURCE_OPTIONS = ["templateId", "snapshotId", "sandboxId", "fromTemplate", "fromSnapshot"];
|
|
25
|
+
var NATIVE_SIZE_OPTIONS = ["vcpu", "vcpuCount", "memoryMib", "memoryMaxMib", "diskMib"];
|
|
26
|
+
function sizeTemplateOf(config, sizeClass) {
|
|
27
|
+
const name = config.sizeTemplates?.[sizeClass] ?? SUPERSERVE_SIZE_TEMPLATES[sizeClass];
|
|
28
|
+
return typeof name === "string" && name.trim() ? name : void 0;
|
|
29
|
+
}
|
|
30
|
+
function missingSizeTemplate(config, templateId, error) {
|
|
31
|
+
if (typeof templateId !== "string" || !(error instanceof NotFoundError)) return void 0;
|
|
32
|
+
const sizeClass = Object.keys(INSTANCE_SIZE_PROFILES).find((c) => sizeTemplateOf(config, c) === templateId);
|
|
33
|
+
if (!sizeClass) return void 0;
|
|
34
|
+
return `Superserve size template '${templateId}' (sizeClass ${sizeClass}) is not built on this Superserve team; run \`node scripts/provider-setup.mjs superserve\` (provider-setup.yml) or point \`sizeTemplates.${sizeClass}\` at an existing template`;
|
|
35
|
+
}
|
|
11
36
|
function resolveApiKey(config) {
|
|
12
37
|
const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;
|
|
13
38
|
if (!apiKey) {
|
|
@@ -25,6 +50,65 @@ function generateSandboxName() {
|
|
|
25
50
|
}
|
|
26
51
|
var FALLBACK_WORKDIR = "/";
|
|
27
52
|
var workdirs = /* @__PURE__ */ new WeakMap();
|
|
53
|
+
var volumeConnections = /* @__PURE__ */ new WeakMap();
|
|
54
|
+
function volumeReference(volume) {
|
|
55
|
+
const reference = typeof volume === "string" ? volume : volume?.id || volume?.name;
|
|
56
|
+
if (typeof reference !== "string" || !reference.trim()) {
|
|
57
|
+
throw new Error("A Superserve volume reference must contain an id or name.");
|
|
58
|
+
}
|
|
59
|
+
return reference;
|
|
60
|
+
}
|
|
61
|
+
function volumeConnection(sandbox) {
|
|
62
|
+
const connection = volumeConnections.get(sandbox);
|
|
63
|
+
if (!connection) throw new Error("The Superserve sandbox has no captured volume connection.");
|
|
64
|
+
return connection;
|
|
65
|
+
}
|
|
66
|
+
function sameSandboxId(left, right) {
|
|
67
|
+
const pattern = /^(?:sb-([A-Za-z0-9]+)-)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
68
|
+
const a = pattern.exec(left);
|
|
69
|
+
const b = pattern.exec(right);
|
|
70
|
+
if (!a || !b) return left === right;
|
|
71
|
+
return a[2].toLowerCase() === b[2].toLowerCase() && (a[1] === void 0 || b[1] === void 0 || a[1] === b[1]);
|
|
72
|
+
}
|
|
73
|
+
function toVolume(info) {
|
|
74
|
+
return {
|
|
75
|
+
id: info.id,
|
|
76
|
+
name: info.name,
|
|
77
|
+
sizeBytes: info.capacityBytes,
|
|
78
|
+
usedBytes: info.usedBytes,
|
|
79
|
+
region: info.region,
|
|
80
|
+
status: info.status,
|
|
81
|
+
createdAt: info.createdAt
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
async function deleteVolume(connection, idOrName) {
|
|
85
|
+
let volume;
|
|
86
|
+
try {
|
|
87
|
+
volume = await SuperserveVolume.connect(idOrName, connection);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (error instanceof NotFoundError) return;
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
const deadline = Date.now() + 12e4;
|
|
93
|
+
for (; ; ) {
|
|
94
|
+
try {
|
|
95
|
+
await SuperserveVolume.deleteById(volume.id, connection);
|
|
96
|
+
return;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (!(error instanceof ConflictError) || error.code !== "volume_conflict") throw error;
|
|
99
|
+
let attachments;
|
|
100
|
+
try {
|
|
101
|
+
attachments = await volume.listAttachments();
|
|
102
|
+
} catch (lookupError) {
|
|
103
|
+
if (lookupError instanceof NotFoundError) return;
|
|
104
|
+
throw lookupError;
|
|
105
|
+
}
|
|
106
|
+
const closing = attachments.filter((attachment) => attachment.status !== "revoked");
|
|
107
|
+
if (!closing.length || closing.some((attachment) => attachment.status !== "detaching" && attachment.status !== "revoking") || Date.now() >= deadline) throw error;
|
|
108
|
+
await new Promise((resolve) => setTimeout(resolve, 3e3));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
28
112
|
function workdirOf(sandbox, runCommand2) {
|
|
29
113
|
let probe = workdirs.get(sandbox);
|
|
30
114
|
if (!probe) {
|
|
@@ -118,6 +202,30 @@ function toTemplate(info) {
|
|
|
118
202
|
}
|
|
119
203
|
var superserve = defineProvider({
|
|
120
204
|
name: "superserve",
|
|
205
|
+
sizes: (config, profile, options) => {
|
|
206
|
+
const opts = options;
|
|
207
|
+
const nativeSize = NATIVE_SIZE_OPTIONS.find((key) => opts?.[key] !== void 0);
|
|
208
|
+
if (nativeSize) {
|
|
209
|
+
throw new InstanceSizeError("conflict", `cannot combine sizeClass with native Superserve ${nativeSize}; Superserve sizes sandboxes by template`);
|
|
210
|
+
}
|
|
211
|
+
const source = SOURCE_OPTIONS.find((key) => opts?.[key] !== void 0);
|
|
212
|
+
if (source) {
|
|
213
|
+
return { status: "unsupported", reason: `A Superserve template or snapshot fixes CPU and memory; drop ${source} to boot the standard size template.` };
|
|
214
|
+
}
|
|
215
|
+
const templateId = sizeTemplateOf(config, profile.sizeClass);
|
|
216
|
+
if (!templateId) {
|
|
217
|
+
return {
|
|
218
|
+
status: "unsupported",
|
|
219
|
+
reason: `Superserve lists at most 16 vCPU / 64 GiB per sandbox (Pro plan); ${profile.sizeClass} needs ${profile.vcpus} vCPU / ${profile.memoryMiB / 1024} GiB. Set sizeTemplates.${profile.sizeClass} to a custom-size template to use it.`
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
const diskMiB = BUILT_IN_TEMPLATE_DISK_MIB[templateId];
|
|
223
|
+
return {
|
|
224
|
+
status: "supported",
|
|
225
|
+
nativeOptions: { templateId },
|
|
226
|
+
...diskMiB === void 0 ? {} : { resolved: { vcpus: profile.vcpus, memoryMiB: profile.memoryMiB, diskMiB } }
|
|
227
|
+
};
|
|
228
|
+
},
|
|
121
229
|
methods: {
|
|
122
230
|
instances: {
|
|
123
231
|
create: async (config, options) => {
|
|
@@ -130,6 +238,7 @@ var superserve = defineProvider({
|
|
|
130
238
|
metadata,
|
|
131
239
|
templateId,
|
|
132
240
|
snapshotId,
|
|
241
|
+
volumes,
|
|
133
242
|
namespace: _namespace,
|
|
134
243
|
directory: _directory,
|
|
135
244
|
...providerOptions
|
|
@@ -137,7 +246,7 @@ var superserve = defineProvider({
|
|
|
137
246
|
const ttMs = requestedTimeoutMs ?? config.timeout;
|
|
138
247
|
const timeoutSeconds = ttMs !== void 0 ? Math.max(1, Math.ceil(ttMs / 1e3)) : void 0;
|
|
139
248
|
try {
|
|
140
|
-
const
|
|
249
|
+
const createOptions = {
|
|
141
250
|
apiKey,
|
|
142
251
|
baseUrl,
|
|
143
252
|
name: name ?? generateSandboxName(),
|
|
@@ -146,10 +255,21 @@ var superserve = defineProvider({
|
|
|
146
255
|
...timeoutSeconds !== void 0 ? { timeoutSeconds } : {},
|
|
147
256
|
...metadata ? { metadata } : {},
|
|
148
257
|
...envs ? { envVars: envs } : {},
|
|
149
|
-
...providerOptions
|
|
150
|
-
|
|
258
|
+
...providerOptions,
|
|
259
|
+
...volumes !== void 0 ? {
|
|
260
|
+
volumes: volumes.map((mount) => ({
|
|
261
|
+
...mount,
|
|
262
|
+
volume: mount.volume instanceof SuperserveVolume ? mount.volume : volumeReference(mount.volume)
|
|
263
|
+
}))
|
|
264
|
+
} : {}
|
|
265
|
+
};
|
|
266
|
+
const connection = resolveConfig(createOptions);
|
|
267
|
+
const sandbox = await SuperserveSandbox.create(createOptions);
|
|
268
|
+
volumeConnections.set(sandbox, connection);
|
|
151
269
|
return { instance: sandbox, instanceId: sandbox.id };
|
|
152
270
|
} catch (error) {
|
|
271
|
+
const notBuilt = missingSizeTemplate(config, templateId, error);
|
|
272
|
+
if (notBuilt) throw Object.assign(new Error(notBuilt), { status: 404, cause: error });
|
|
153
273
|
rethrowFriendly(error, "Failed to create Superserve sandbox");
|
|
154
274
|
}
|
|
155
275
|
},
|
|
@@ -157,7 +277,9 @@ var superserve = defineProvider({
|
|
|
157
277
|
const apiKey = resolveApiKey(config);
|
|
158
278
|
const baseUrl = resolveBaseUrl(config);
|
|
159
279
|
try {
|
|
160
|
-
const
|
|
280
|
+
const connection = resolveConfig({ apiKey, baseUrl });
|
|
281
|
+
const sandbox = await SuperserveSandbox.connect(sandboxId, connection);
|
|
282
|
+
volumeConnections.set(sandbox, connection);
|
|
161
283
|
return { instance: sandbox, instanceId: sandbox.id };
|
|
162
284
|
} catch {
|
|
163
285
|
return null;
|
|
@@ -167,11 +289,13 @@ var superserve = defineProvider({
|
|
|
167
289
|
const apiKey = resolveApiKey(config);
|
|
168
290
|
const baseUrl = resolveBaseUrl(config);
|
|
169
291
|
try {
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
292
|
+
const connection = resolveConfig({ apiKey, baseUrl });
|
|
293
|
+
const infos = await SuperserveSandbox.list(connection);
|
|
294
|
+
return infos.map((info) => {
|
|
295
|
+
const instance = info;
|
|
296
|
+
volumeConnections.set(instance, connection);
|
|
297
|
+
return { instance, instanceId: info.id };
|
|
298
|
+
});
|
|
175
299
|
} catch {
|
|
176
300
|
return [];
|
|
177
301
|
}
|
|
@@ -183,6 +307,18 @@ var superserve = defineProvider({
|
|
|
183
307
|
},
|
|
184
308
|
runCommand,
|
|
185
309
|
streamCommand: runCommand,
|
|
310
|
+
attachVolume: async (sandbox, volume, mountPath) => {
|
|
311
|
+
const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));
|
|
312
|
+
await native.attach(sandbox.id, { mountPath });
|
|
313
|
+
},
|
|
314
|
+
detachVolume: async (sandbox, volume, mountPath) => {
|
|
315
|
+
const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));
|
|
316
|
+
const attachments = (await native.listAttachments()).filter((attachment) => attachment.volumeId === native.id && sameSandboxId(attachment.sandboxId, sandbox.id) && attachment.status !== "revoked" && (mountPath === void 0 || attachment.mountPath === mountPath));
|
|
317
|
+
if (attachments.length > 1) {
|
|
318
|
+
throw new Error("Multiple matching Superserve attachments; provide their mount path to detach one.");
|
|
319
|
+
}
|
|
320
|
+
if (attachments[0]) await native.detach(attachments[0].id);
|
|
321
|
+
},
|
|
186
322
|
getInfo: async (sandbox) => {
|
|
187
323
|
const info = await sandbox.getInfo();
|
|
188
324
|
const status = info.status === "paused" || info.status === "deleted" ? "stopped" : info.status === "failed" ? "error" : "running";
|
|
@@ -304,6 +440,38 @@ var superserve = defineProvider({
|
|
|
304
440
|
await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });
|
|
305
441
|
}
|
|
306
442
|
},
|
|
443
|
+
volume: {
|
|
444
|
+
create: async (config, options) => {
|
|
445
|
+
const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
446
|
+
const volume = await SuperserveVolume.create({
|
|
447
|
+
...connection,
|
|
448
|
+
name: options.name,
|
|
449
|
+
...options.sizeBytes !== void 0 ? { capacityBytes: options.sizeBytes } : {},
|
|
450
|
+
idempotencyKey: options.idempotencyKey,
|
|
451
|
+
timeoutMs: options.timeoutMs,
|
|
452
|
+
signal: options.signal
|
|
453
|
+
});
|
|
454
|
+
return toVolume(volume);
|
|
455
|
+
},
|
|
456
|
+
get: async (config, idOrName) => {
|
|
457
|
+
const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
458
|
+
try {
|
|
459
|
+
return toVolume(await SuperserveVolume.connect(idOrName, connection));
|
|
460
|
+
} catch (error) {
|
|
461
|
+
if (error instanceof NotFoundError) return null;
|
|
462
|
+
throw error;
|
|
463
|
+
}
|
|
464
|
+
},
|
|
465
|
+
list: async (config, options) => {
|
|
466
|
+
const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
467
|
+
const volumes = await SuperserveVolume.list({ ...connection, limit: options?.limit });
|
|
468
|
+
return volumes.map(toVolume);
|
|
469
|
+
},
|
|
470
|
+
delete: async (config, idOrName) => {
|
|
471
|
+
const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });
|
|
472
|
+
await deleteVolume(connection, idOrName);
|
|
473
|
+
}
|
|
474
|
+
},
|
|
307
475
|
template: {
|
|
308
476
|
create: async (config, options) => {
|
|
309
477
|
const apiKey = resolveApiKey(config);
|
|
@@ -352,6 +520,7 @@ var superserve = defineProvider({
|
|
|
352
520
|
}
|
|
353
521
|
});
|
|
354
522
|
export {
|
|
523
|
+
SUPERSERVE_SIZE_TEMPLATES,
|
|
355
524
|
superserve
|
|
356
525
|
};
|
|
357
526
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Superserve Provider - Factory-based Implementation\n *\n * Wraps `@superserve/sdk` to expose the ComputeSDK provider interface.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n AuthenticationError,\n Sandbox as SuperserveSandbox,\n Snapshot as SuperserveSnapshot,\n Template as SuperserveTemplate,\n} from '@superserve/sdk';\nimport type { SnapshotInfo, TemplateCreateOptions, TemplateInfo } from '@superserve/sdk';\nimport { defineProvider, escapeShellArg } from '@computesdk/provider';\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateTemplateOptions,\n FileEntry,\n RunCommandOptions,\n InstanceInfo,\n} from '@computesdk/provider';\n\nexport interface SuperserveConfig {\n /** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */\n apiKey?: string;\n /** API base URL. Falls back to `SUPERSERVE_BASE_URL` env var, then the `@superserve/sdk` default. */\n baseUrl?: string;\n /** Default auto-pause timeout in milliseconds. */\n timeout?: number;\n}\n\nfunction resolveApiKey(config: SuperserveConfig): string {\n const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;\n if (!apiKey) {\n throw new Error(\n `Missing Superserve API key. Provide 'apiKey' in config or set SUPERSERVE_API_KEY environment variable.`,\n );\n }\n return apiKey;\n}\n\nfunction resolveBaseUrl(config: SuperserveConfig): string | undefined {\n // Returns undefined when unset on purpose: the SDK then applies its own\n // resolution (SUPERSERVE_BASE_URL env var, then its default endpoint), so\n // we don't duplicate that default and risk it drifting.\n return config.baseUrl || process.env.SUPERSERVE_BASE_URL || undefined;\n}\n\nfunction generateSandboxName(): string {\n return `cs-${randomUUID().slice(0, 8)}`;\n}\n\ntype CommandRunner = (\n sandbox: SuperserveSandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\nconst FALLBACK_WORKDIR = '/';\n\n/** Cached `pwd` probes: relative filesystem paths resolve against the cwd a\n * `runCommand` exec would use, so `writeFile('a.txt')` and `cat a.txt` agree. */\nconst workdirs = new WeakMap<SuperserveSandbox, Promise<string>>();\n\nfunction workdirOf(sandbox: SuperserveSandbox, runCommand: CommandRunner): Promise<string> {\n let probe = workdirs.get(sandbox);\n if (!probe) {\n probe = runCommand(sandbox, 'pwd').then((result) => {\n const dir = result.stdout.trim();\n if (result.exitCode === 0 && dir.startsWith('/')) return dir;\n // runCommand reports exec failures as results, not rejections, so a\n // transient failure must not pin the workdir to the fallback forever —\n // evict and let the next filesystem op probe again.\n workdirs.delete(sandbox);\n return FALLBACK_WORKDIR;\n });\n workdirs.set(sandbox, probe);\n probe.catch(() => workdirs.delete(sandbox));\n }\n return probe;\n}\n\n/** Join `path` onto the sandbox workdir. Absolute paths pass through and skip\n * the probe; empty and `.` segments are dropped; `..` segments are preserved\n * for the sandbox filesystem to resolve physically — collapsing them\n * lexically would mis-resolve when a preceding component is a symlink. */\nasync function resolveSandboxPath(\n sandbox: SuperserveSandbox,\n path: string,\n runCommand: CommandRunner,\n): Promise<string> {\n const combined = path.startsWith('/')\n ? path\n : `${await workdirOf(sandbox, runCommand)}/${path}`;\n const segments: string[] = [];\n for (const segment of combined.split('/')) {\n if (segment === '' || segment === '.') continue;\n segments.push(segment);\n }\n return `/${segments.join('/')}`;\n}\n\nfunction rethrowFriendly(error: unknown, fallbackPrefix: string): never {\n if (error instanceof AuthenticationError) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n if (lower.includes('unauthorized') || lower.includes('401') || lower.includes('api key')) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n if (lower.includes('quota') || lower.includes('limit') || lower.includes('429')) {\n throw new Error(`Superserve quota or rate limit reached: ${message}`);\n }\n throw new Error(`${fallbackPrefix}: ${message}`);\n}\n\n// Also serves as `streamCommand`: the SDK streams output over its own exec API\n// when callbacks are passed, so no daemon or routable port is needed.\nconst runCommand: CommandRunner = async (sandbox, command, options) => {\n const startTime = Date.now();\n try {\n let fullCommand = command;\n if (options?.background) {\n // Run the whole command under `sh -c` so the trailing `&` backgrounds\n // the entire command (not just its last statement), and escape it so\n // the user's command can't break out of the nohup wrapper.\n fullCommand = `nohup sh -c \"${escapeShellArg(fullCommand)}\" > /dev/null 2>&1 &`;\n }\n const result = await sandbox.commands.run(fullCommand, {\n cwd: options?.cwd,\n env: options?.env,\n timeoutMs: options?.timeout,\n onStdout: options?.onStdout,\n onStderr: options?.onStderr,\n });\n return {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n stdout: '',\n stderr: error instanceof Error ? error.message : String(error),\n exitCode: 127,\n durationMs: Date.now() - startTime,\n };\n }\n};\n\nfunction toSnapshot(info: SnapshotInfo) {\n return {\n id: info.id,\n provider: 'superserve',\n createdAt: info.createdAt,\n metadata: {\n name: info.name,\n sandboxId: info.sandboxId,\n status: info.status,\n sizeBytes: info.sizeBytes,\n },\n };\n}\n\n/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set\n * here and every sandbox created from it inherits them. */\nexport type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;\n\nfunction toTemplate(info: TemplateInfo) {\n return {\n id: info.id,\n name: info.name,\n createdAt: info.createdAt,\n metadata: { status: info.status, vcpu: info.vcpu, memoryMib: info.memoryMib, diskMib: info.diskMib, errorMessage: info.errorMessage },\n };\n}\n\nexport const superserve = defineProvider<SuperserveSandbox, SuperserveConfig>({\n name: 'superserve',\n methods: {\n instances: {\n create: async (config: SuperserveConfig, options?: CreateInstanceOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n\n const {\n timeout: requestedTimeoutMs,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n namespace: _namespace,\n directory: _directory,\n ...providerOptions\n } = options || {};\n\n const ttMs = requestedTimeoutMs ?? config.timeout;\n const timeoutSeconds = ttMs !== undefined ? Math.max(1, Math.ceil(ttMs / 1000)) : undefined;\n\n try {\n const sandbox = await SuperserveSandbox.create({\n apiKey,\n baseUrl,\n name: name ?? generateSandboxName(),\n ...(templateId ? { fromTemplate: templateId } : {}),\n ...(snapshotId ? { fromSnapshot: snapshotId } : {}),\n ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n ...(metadata ? { metadata: metadata as Record<string, string> } : {}),\n ...(envs ? { envVars: envs } : {}),\n ...providerOptions,\n });\n return { instance: sandbox, instanceId: sandbox.id };\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve sandbox');\n }\n },\n\n getById: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return { instance: sandbox, instanceId: sandbox.id };\n } catch {\n return null;\n }\n },\n\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveSandbox.list({ apiKey, baseUrl });\n // No per-item connect() — that would POST /activate and resume paused sandboxes.\n return infos.map((info) => ({ instance: info as unknown as SuperserveSandbox, instanceId: info.id,\n }));\n } catch {\n return [];\n }\n },\n\n destroy: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n // The SDK handles already-deleted sandboxes and retries transient failures.\n await SuperserveSandbox.killById(sandboxId, { apiKey, baseUrl });\n },\n\n runCommand,\n streamCommand: runCommand,\n\n getInfo: async (sandbox: SuperserveSandbox): Promise<InstanceInfo> => {\n const info = await sandbox.getInfo();\n const status: InstanceInfo['status'] =\n info.status === 'paused' || info.status === 'deleted' ? 'stopped' :\n info.status === 'failed' ? 'error' :\n 'running';\n return {\n id: info.id,\n provider: 'superserve',\n status,\n createdAt: info.createdAt,\n timeout: info.timeoutSeconds ? info.timeoutSeconds * 1000 : DEFAULT_TIMEOUT_MS,\n metadata: info.metadata,\n };\n },\n\n getUrl: async (sandbox: SuperserveSandbox, options: { port: number; protocol?: string }): Promise<string> => {\n // A preview URL only routes once its port is published. A new port takes\n // the sandbox's `previewAccess` default; a published one keeps its mode.\n await sandbox.publishPreviewPort(options.port);\n const url = sandbox.getPreviewUrl(options.port);\n return options.protocol ? url.replace(/^https/, options.protocol) : url;\n },\n\n filesystem: {\n readFile: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n return sandbox.files.readText(await resolveSandboxPath(sandbox, path, runCommand));\n },\n\n writeFile: async (sandbox: SuperserveSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n await sandbox.files.write(await resolveSandboxPath(sandbox, path, runCommand), content);\n },\n\n mkdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`mkdir -p \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`mkdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n\n readdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n // find -printf format: <type>\\t<size>\\t<mtime-epoch>\\t<name>\n const cmd = [\n `cd \"${escapeShellArg(resolved)}\" || exit 2`,\n `find . -mindepth 1 -maxdepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%f\\\\n' 2>/dev/null`,\n ].join(' && ');\n const result = await sandbox.commands.run(cmd);\n if (result.exitCode === 2) {\n throw new Error(`readdir: directory not found: ${path}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n const entries: FileEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...nameParts] = line.split('\\t');\n const name = nameParts.join('\\t');\n if (!name) continue;\n const size = Number.parseInt(sizeStr, 10);\n const mtime = Number.parseFloat(mtimeStr);\n entries.push({\n name,\n type: type === 'd' ? 'directory' : 'file',\n size: Number.isFinite(size) ? size : 0,\n modified: Number.isFinite(mtime) ? new Date(mtime * 1000) : new Date(),\n });\n }\n return entries;\n },\n\n exists: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`test -e \"${escapeShellArg(resolved)}\"`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n // An empty or dot-only path would resolve to the workdir itself —\n // refuse it rather than `rm -rf` the sandbox's whole cwd.\n if (path.split('/').every((s) => s === '' || s === '.')) {\n throw new Error(`remove: refusing ambiguous path: ${JSON.stringify(path)}`);\n }\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`rm -rf \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`remove failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n },\n\n getInstance: (sandbox: SuperserveSandbox): SuperserveSandbox => sandbox,\n\n pause: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n await sandbox.pause({ wait: true });\n } catch (error) {\n rethrowFriendly(error, 'Failed to pause Superserve sandbox');\n }\n },\n\n resume: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n // The access token rotates on resume; the SDK refreshes the handle in place.\n await sandbox.resume();\n } catch (error) {\n rethrowFriendly(error, 'Failed to resume Superserve sandbox');\n }\n },\n\n pauseCapabilities: { memory: true },\n },\n\n snapshot: {\n // Snapshots hold memory and disk: restores keep the whole filesystem,\n // tmpfs /tmp included, and running processes. The source keeps running.\n capabilities: { scope: 'rootfs', memory: true, destroysSource: false },\n create: async (config: SuperserveConfig, sandboxId: string, options?: { name?: string }) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n // connect() activates the sandbox, so a paused one is resumed first.\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return toSnapshot(await sandbox.snapshot({ name: options?.name }));\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve snapshot');\n }\n },\n list: async (config: SuperserveConfig, options?: { sandboxId?: string; limit?: number }) => {\n // Snapshots are listed per sandbox. Callers that aggregate across\n // providers pass no options, so an unscoped call returns nothing\n // instead of throwing and failing their whole listing.\n if (!options?.sandboxId) return [];\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const infos = await SuperserveSnapshot.list(options.sandboxId, { apiKey, baseUrl, limit: options.limit });\n return infos.map(toSnapshot);\n },\n delete: async (config: SuperserveConfig, snapshotId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });\n },\n },\n\n template: {\n create: async (config: SuperserveConfig, options: SuperserveTemplateCreateOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const { name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd } = options;\n if (!from) {\n throw new Error('Superserve templates are built from an image: pass `from` (e.g. \"node:22\").');\n }\n try {\n const template = await SuperserveTemplate.create({\n apiKey, baseUrl, name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd,\n });\n return toTemplate(await template.waitUntilReady());\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve template');\n }\n },\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveTemplate.list({ apiKey, baseUrl });\n return infos.map(toTemplate);\n } catch {\n return [];\n }\n },\n delete: async (config: SuperserveConfig, templateId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n await SuperserveTemplate.deleteById(templateId, { apiKey, baseUrl });\n } catch {\n /* already deleted */\n }\n },\n },\n },\n});\n\nexport type { Sandbox as SuperserveSandbox } from '@superserve/sdk';\n"],"mappings":";AAMA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,YAAY;AAAA,OACP;AAEP,SAAS,gBAAgB,sBAAsB;AAE/C,IAAM,qBAAqB;AAoB3B,SAAS,cAAc,QAAkC;AACvD,QAAM,SAAS,OAAO,UAAU,QAAQ,IAAI;AAC5C,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eAAe,QAA8C;AAIpE,SAAO,OAAO,WAAW,QAAQ,IAAI,uBAAuB;AAC9D;AAEA,SAAS,sBAA8B;AACrC,SAAO,MAAM,WAAW,EAAE,MAAM,GAAG,CAAC,CAAC;AACvC;AAQA,IAAM,mBAAmB;AAIzB,IAAM,WAAW,oBAAI,QAA4C;AAEjE,SAAS,UAAU,SAA4BA,aAA4C;AACzF,MAAI,QAAQ,SAAS,IAAI,OAAO;AAChC,MAAI,CAAC,OAAO;AACV,YAAQA,YAAW,SAAS,KAAK,EAAE,KAAK,CAAC,WAAW;AAClD,YAAM,MAAM,OAAO,OAAO,KAAK;AAC/B,UAAI,OAAO,aAAa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AA,YAAO;AAAA,YAAU;AAAA,UAC1E,CAAC;AACD,iBAAO,WAAW,MAAM,SAAS,eAAe,CAAC;AAAA,QACnD,SAAS,OAAO;AACd,0BAAgB,OAAO,sCAAsC;AAAA,QAC/D;AAAA,MACF;AAAA,MACA,MAAM,OAAO,WAA6B;AACxC,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,QAAQ,MAAM,mBAAmB,KAAK,EAAE,QAAQ,QAAQ,CAAC;AAC/D,iBAAO,MAAM,IAAI,UAAU;AAAA,QAC7B,QAAQ;AACN,iBAAO,CAAC;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ,OAAO,QAA0B,eAAuB;AAC9D,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,mBAAmB,WAAW,YAAY,EAAE,QAAQ,QAAQ,CAAC;AAAA,QACrE,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["runCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Superserve Provider - Factory-based Implementation\n *\n * Wraps `@superserve/sdk` to expose the ComputeSDK provider interface.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n AuthenticationError,\n ConflictError,\n NotFoundError,\n Sandbox as SuperserveSandbox,\n Snapshot as SuperserveSnapshot,\n Template as SuperserveTemplate,\n Volume as SuperserveVolume,\n resolveConfig,\n} from '@superserve/sdk';\nimport type {\n ResolvedConfig,\n SnapshotInfo,\n TemplateCreateOptions,\n TemplateInfo,\n VolumeCreateOptions,\n VolumeInfo,\n} from '@superserve/sdk';\nimport { defineProvider, escapeShellArg, InstanceSizeError, INSTANCE_SIZE_PROFILES } from '@computesdk/provider';\n\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nimport type {\n CommandResult,\n CreateInstanceOptions,\n CreateTemplateOptions,\n CreateVolumeOptions,\n FileEntry,\n InstanceSizeClass,\n RunCommandOptions,\n InstanceInfo,\n Volume,\n} from '@computesdk/provider';\n\nexport interface SuperserveConfig {\n /** Superserve API key. Falls back to `SUPERSERVE_API_KEY` env var. */\n apiKey?: string;\n /** API base URL. Falls back to `SUPERSERVE_BASE_URL` env var, then the `@superserve/sdk` default. */\n baseUrl?: string;\n /** Default auto-pause timeout in milliseconds. */\n timeout?: number;\n /** Template to boot per standard `sizeClass`; defaults to {@link SUPERSERVE_SIZE_TEMPLATES}. */\n sizeTemplates?: Partial<Record<InstanceSizeClass, string>>;\n}\n\n/**\n * Superserve fixes vCPU, memory and disk when a template is built, so each\n * standard size boots its own template. `superserve/base` (2 vCPU / 4 GiB /\n * 8 GiB disk) is built in to every team; the others are team templates\n * built by `scripts/provider-setup.mjs superserve`. The largest listed plan\n * (Pro) caps a sandbox at 16 vCPU / 64 GiB, so `3xl` has no default.\n */\nexport const SUPERSERVE_SIZE_TEMPLATES: Readonly<Partial<Record<InstanceSizeClass, string>>> = Object.freeze({\n xs: 'csdk-node22-1cpu-1gb',\n sm: 'csdk-node22-1cpu-2gb',\n md: 'superserve/base',\n lg: 'csdk-node22-4cpu-8gb',\n xl: 'csdk-node22-8cpu-16gb',\n '2xl': 'csdk-node22-16cpu-32gb',\n});\n\n/** Disk the built-in templates fix; team templates take theirs from the build. */\nconst BUILT_IN_TEMPLATE_DISK_MIB: Readonly<Record<string, number>> = Object.freeze({ 'superserve/base': 8192 });\n\n/** Native selectors that pick or size the VM; `Sandbox.create` drops the sizing ones silently. */\nconst SOURCE_OPTIONS = ['templateId', 'snapshotId', 'sandboxId', 'fromTemplate', 'fromSnapshot'] as const;\nconst NATIVE_SIZE_OPTIONS = ['vcpu', 'vcpuCount', 'memoryMib', 'memoryMaxMib', 'diskMib'] as const;\n\nfunction sizeTemplateOf(config: SuperserveConfig, sizeClass: InstanceSizeClass): string | undefined {\n const name = config.sizeTemplates?.[sizeClass] ?? SUPERSERVE_SIZE_TEMPLATES[sizeClass];\n return typeof name === 'string' && name.trim() ? name : undefined;\n}\n\n/** A create that failed because a standard-size template was never built on this team. */\nfunction missingSizeTemplate(config: SuperserveConfig, templateId: unknown, error: unknown): string | undefined {\n if (typeof templateId !== 'string' || !(error instanceof NotFoundError)) return undefined;\n const sizeClass = (Object.keys(INSTANCE_SIZE_PROFILES) as InstanceSizeClass[]).find(c => sizeTemplateOf(config, c) === templateId);\n if (!sizeClass) return undefined;\n return `Superserve size template '${templateId}' (sizeClass ${sizeClass}) is not built on this Superserve team; run \\`node scripts/provider-setup.mjs superserve\\` (provider-setup.yml) or point \\`sizeTemplates.${sizeClass}\\` at an existing template`;\n}\n\nfunction resolveApiKey(config: SuperserveConfig): string {\n const apiKey = config.apiKey || process.env.SUPERSERVE_API_KEY;\n if (!apiKey) {\n throw new Error(\n `Missing Superserve API key. Provide 'apiKey' in config or set SUPERSERVE_API_KEY environment variable.`,\n );\n }\n return apiKey;\n}\n\nfunction resolveBaseUrl(config: SuperserveConfig): string | undefined {\n // Returns undefined when unset on purpose: the SDK then applies its own\n // resolution (SUPERSERVE_BASE_URL env var, then its default endpoint), so\n // we don't duplicate that default and risk it drifting.\n return config.baseUrl || process.env.SUPERSERVE_BASE_URL || undefined;\n}\n\nfunction generateSandboxName(): string {\n return `cs-${randomUUID().slice(0, 8)}`;\n}\n\ntype CommandRunner = (\n sandbox: SuperserveSandbox,\n command: string,\n options?: RunCommandOptions,\n) => Promise<CommandResult>;\n\nconst FALLBACK_WORKDIR = '/';\n\n/** Cached `pwd` probes: relative filesystem paths resolve against the cwd a\n * `runCommand` exec would use, so `writeFile('a.txt')` and `cat a.txt` agree. */\nconst workdirs = new WeakMap<SuperserveSandbox, Promise<string>>();\nconst volumeConnections = new WeakMap<SuperserveSandbox, ResolvedConfig>();\n\nfunction volumeReference(volume: string | Volume): string {\n const reference = typeof volume === 'string' ? volume : volume?.id || volume?.name;\n if (typeof reference !== 'string' || !reference.trim()) {\n throw new Error('A Superserve volume reference must contain an id or name.');\n }\n return reference;\n}\n\nfunction volumeConnection(sandbox: SuperserveSandbox): ResolvedConfig {\n const connection = volumeConnections.get(sandbox);\n if (!connection) throw new Error('The Superserve sandbox has no captured volume connection.');\n return connection;\n}\n\nfunction sameSandboxId(left: string, right: string): boolean {\n const pattern = /^(?:sb-([A-Za-z0-9]+)-)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;\n const a = pattern.exec(left);\n const b = pattern.exec(right);\n if (!a || !b) return left === right;\n return a[2].toLowerCase() === b[2].toLowerCase() &&\n (a[1] === undefined || b[1] === undefined || a[1] === b[1]);\n}\n\nfunction toVolume(info: VolumeInfo): Volume {\n return {\n id: info.id,\n name: info.name,\n sizeBytes: info.capacityBytes,\n usedBytes: info.usedBytes,\n region: info.region,\n status: info.status,\n createdAt: info.createdAt,\n };\n}\n\nasync function deleteVolume(connection: ResolvedConfig, idOrName: string): Promise<void> {\n let volume: SuperserveVolume;\n try {\n volume = await SuperserveVolume.connect(idOrName, connection);\n } catch (error) {\n if (error instanceof NotFoundError) return;\n throw error;\n }\n // Names can be reused while closing leases settle. Resolve once so retries\n // and attachment checks stay bound to the original volume.\n const deadline = Date.now() + 120_000;\n for (;;) {\n try {\n await SuperserveVolume.deleteById(volume.id, connection);\n return;\n } catch (error) {\n if (!(error instanceof ConflictError) || error.code !== 'volume_conflict') throw error;\n let attachments;\n try {\n attachments = await volume.listAttachments();\n } catch (lookupError) {\n if (lookupError instanceof NotFoundError) return;\n throw lookupError;\n }\n const closing = attachments.filter((attachment) => attachment.status !== 'revoked');\n // A destroyed sandbox can leave a closing lease briefly. Never wait on\n // an active mount, or turn another kind of conflict into successful cleanup.\n if (!closing.length || closing.some((attachment) =>\n attachment.status !== 'detaching' && attachment.status !== 'revoking') ||\n Date.now() >= deadline) throw error;\n await new Promise((resolve) => setTimeout(resolve, 3_000));\n }\n }\n}\n\nfunction workdirOf(sandbox: SuperserveSandbox, runCommand: CommandRunner): Promise<string> {\n let probe = workdirs.get(sandbox);\n if (!probe) {\n probe = runCommand(sandbox, 'pwd').then((result) => {\n const dir = result.stdout.trim();\n if (result.exitCode === 0 && dir.startsWith('/')) return dir;\n // runCommand reports exec failures as results, not rejections, so a\n // transient failure must not pin the workdir to the fallback forever —\n // evict and let the next filesystem op probe again.\n workdirs.delete(sandbox);\n return FALLBACK_WORKDIR;\n });\n workdirs.set(sandbox, probe);\n probe.catch(() => workdirs.delete(sandbox));\n }\n return probe;\n}\n\n/** Join `path` onto the sandbox workdir. Absolute paths pass through and skip\n * the probe; empty and `.` segments are dropped; `..` segments are preserved\n * for the sandbox filesystem to resolve physically — collapsing them\n * lexically would mis-resolve when a preceding component is a symlink. */\nasync function resolveSandboxPath(\n sandbox: SuperserveSandbox,\n path: string,\n runCommand: CommandRunner,\n): Promise<string> {\n const combined = path.startsWith('/')\n ? path\n : `${await workdirOf(sandbox, runCommand)}/${path}`;\n const segments: string[] = [];\n for (const segment of combined.split('/')) {\n if (segment === '' || segment === '.') continue;\n segments.push(segment);\n }\n return `/${segments.join('/')}`;\n}\n\nfunction rethrowFriendly(error: unknown, fallbackPrefix: string): never {\n if (error instanceof AuthenticationError) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n const message = error instanceof Error ? error.message : String(error);\n const lower = message.toLowerCase();\n if (lower.includes('unauthorized') || lower.includes('401') || lower.includes('api key')) {\n throw new Error(\n `Superserve authentication failed. Please check your SUPERSERVE_API_KEY environment variable.`,\n );\n }\n if (lower.includes('quota') || lower.includes('limit') || lower.includes('429')) {\n throw new Error(`Superserve quota or rate limit reached: ${message}`);\n }\n throw new Error(`${fallbackPrefix}: ${message}`);\n}\n\n// Also serves as `streamCommand`: the SDK streams output over its own exec API\n// when callbacks are passed, so no daemon or routable port is needed.\nconst runCommand: CommandRunner = async (sandbox, command, options) => {\n const startTime = Date.now();\n try {\n let fullCommand = command;\n if (options?.background) {\n // Run the whole command under `sh -c` so the trailing `&` backgrounds\n // the entire command (not just its last statement), and escape it so\n // the user's command can't break out of the nohup wrapper.\n fullCommand = `nohup sh -c \"${escapeShellArg(fullCommand)}\" > /dev/null 2>&1 &`;\n }\n const result = await sandbox.commands.run(fullCommand, {\n cwd: options?.cwd,\n env: options?.env,\n timeoutMs: options?.timeout,\n onStdout: options?.onStdout,\n onStderr: options?.onStderr,\n });\n return {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n return {\n stdout: '',\n stderr: error instanceof Error ? error.message : String(error),\n exitCode: 127,\n durationMs: Date.now() - startTime,\n };\n }\n};\n\nfunction toSnapshot(info: SnapshotInfo) {\n return {\n id: info.id,\n provider: 'superserve',\n createdAt: info.createdAt,\n metadata: {\n name: info.name,\n sandboxId: info.sandboxId,\n status: info.status,\n sizeBytes: info.sizeBytes,\n },\n };\n}\n\n/** Superserve sizes sandboxes at the template: vCPU, memory and disk are set\n * here and every sandbox created from it inherits them. */\nexport type SuperserveTemplateCreateOptions = CreateTemplateOptions & Partial<Omit<TemplateCreateOptions, 'apiKey' | 'baseUrl' | 'name'>>;\nexport type SuperserveVolumeCreateOptions = CreateVolumeOptions &\n Pick<VolumeCreateOptions, 'idempotencyKey' | 'timeoutMs' | 'signal'>;\n\nfunction toTemplate(info: TemplateInfo) {\n return {\n id: info.id,\n name: info.name,\n createdAt: info.createdAt,\n metadata: { status: info.status, vcpu: info.vcpu, memoryMib: info.memoryMib, diskMib: info.diskMib, errorMessage: info.errorMessage },\n };\n}\n\nexport const superserve = defineProvider<SuperserveSandbox, SuperserveConfig>({\n name: 'superserve',\n sizes: (config, profile, options) => {\n const opts = options as Record<string, unknown> | undefined;\n const nativeSize = NATIVE_SIZE_OPTIONS.find(key => opts?.[key] !== undefined);\n if (nativeSize) {\n throw new InstanceSizeError('conflict', `cannot combine sizeClass with native Superserve ${nativeSize}; Superserve sizes sandboxes by template`);\n }\n const source = SOURCE_OPTIONS.find(key => opts?.[key] !== undefined);\n if (source) {\n return { status: 'unsupported', reason: `A Superserve template or snapshot fixes CPU and memory; drop ${source} to boot the standard size template.` };\n }\n const templateId = sizeTemplateOf(config, profile.sizeClass);\n if (!templateId) {\n return {\n status: 'unsupported',\n reason: `Superserve lists at most 16 vCPU / 64 GiB per sandbox (Pro plan); ${profile.sizeClass} needs ${profile.vcpus} vCPU / ${profile.memoryMiB / 1024} GiB. Set sizeTemplates.${profile.sizeClass} to a custom-size template to use it.`,\n };\n }\n const diskMiB = BUILT_IN_TEMPLATE_DISK_MIB[templateId];\n return {\n status: 'supported',\n nativeOptions: { templateId },\n ...(diskMiB === undefined ? {} : { resolved: { vcpus: profile.vcpus, memoryMiB: profile.memoryMiB, diskMiB } }),\n };\n },\n methods: {\n instances: {\n create: async (config: SuperserveConfig, options?: CreateInstanceOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n\n const {\n timeout: requestedTimeoutMs,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n volumes,\n namespace: _namespace,\n directory: _directory,\n ...providerOptions\n } = options || {};\n\n const ttMs = requestedTimeoutMs ?? config.timeout;\n const timeoutSeconds = ttMs !== undefined ? Math.max(1, Math.ceil(ttMs / 1000)) : undefined;\n\n try {\n const createOptions = {\n apiKey,\n baseUrl,\n name: name ?? generateSandboxName(),\n ...(templateId ? { fromTemplate: templateId } : {}),\n ...(snapshotId ? { fromSnapshot: snapshotId } : {}),\n ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),\n ...(metadata ? { metadata: metadata as Record<string, string> } : {}),\n ...(envs ? { envVars: envs } : {}),\n ...providerOptions,\n ...(volumes !== undefined ? {\n volumes: volumes.map((mount) => ({\n ...mount,\n volume: mount.volume instanceof SuperserveVolume\n ? mount.volume\n : volumeReference(mount.volume),\n })),\n } : {}),\n };\n const connection = resolveConfig(createOptions);\n const sandbox = await SuperserveSandbox.create(createOptions);\n volumeConnections.set(sandbox, connection);\n return { instance: sandbox, instanceId: sandbox.id };\n } catch (error) {\n const notBuilt = missingSizeTemplate(config, templateId, error);\n if (notBuilt) throw Object.assign(new Error(notBuilt), { status: 404, cause: error });\n rethrowFriendly(error, 'Failed to create Superserve sandbox');\n }\n },\n\n getById: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const connection = resolveConfig({ apiKey, baseUrl });\n const sandbox = await SuperserveSandbox.connect(sandboxId, connection);\n volumeConnections.set(sandbox, connection);\n return { instance: sandbox, instanceId: sandbox.id };\n } catch {\n return null;\n }\n },\n\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const connection = resolveConfig({ apiKey, baseUrl });\n const infos = await SuperserveSandbox.list(connection);\n // No per-item connect() — that would POST /activate and resume paused sandboxes.\n return infos.map((info) => {\n const instance = info as unknown as SuperserveSandbox;\n volumeConnections.set(instance, connection);\n return { instance, instanceId: info.id };\n });\n } catch {\n return [];\n }\n },\n\n destroy: async (config: SuperserveConfig, sandboxId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n // The SDK handles already-deleted sandboxes and retries transient failures.\n await SuperserveSandbox.killById(sandboxId, { apiKey, baseUrl });\n },\n\n runCommand,\n streamCommand: runCommand,\n\n attachVolume: async (sandbox, volume, mountPath) => {\n const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));\n await native.attach(sandbox.id, { mountPath });\n },\n\n detachVolume: async (sandbox, volume, mountPath) => {\n const native = await SuperserveVolume.connect(volumeReference(volume), volumeConnection(sandbox));\n const attachments = (await native.listAttachments()).filter((attachment) =>\n attachment.volumeId === native.id &&\n sameSandboxId(attachment.sandboxId, sandbox.id) &&\n attachment.status !== 'revoked' &&\n (mountPath === undefined || attachment.mountPath === mountPath));\n if (attachments.length > 1) {\n throw new Error('Multiple matching Superserve attachments; provide their mount path to detach one.');\n }\n if (attachments[0]) await native.detach(attachments[0].id);\n },\n\n getInfo: async (sandbox: SuperserveSandbox): Promise<InstanceInfo> => {\n const info = await sandbox.getInfo();\n const status: InstanceInfo['status'] =\n info.status === 'paused' || info.status === 'deleted' ? 'stopped' :\n info.status === 'failed' ? 'error' :\n 'running';\n return {\n id: info.id,\n provider: 'superserve',\n status,\n createdAt: info.createdAt,\n timeout: info.timeoutSeconds ? info.timeoutSeconds * 1000 : DEFAULT_TIMEOUT_MS,\n metadata: info.metadata,\n };\n },\n\n getUrl: async (sandbox: SuperserveSandbox, options: { port: number; protocol?: string }): Promise<string> => {\n // A preview URL only routes once its port is published. A new port takes\n // the sandbox's `previewAccess` default; a published one keeps its mode.\n await sandbox.publishPreviewPort(options.port);\n const url = sandbox.getPreviewUrl(options.port);\n return options.protocol ? url.replace(/^https/, options.protocol) : url;\n },\n\n filesystem: {\n readFile: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n return sandbox.files.readText(await resolveSandboxPath(sandbox, path, runCommand));\n },\n\n writeFile: async (sandbox: SuperserveSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n await sandbox.files.write(await resolveSandboxPath(sandbox, path, runCommand), content);\n },\n\n mkdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`mkdir -p \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`mkdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n\n readdir: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n // find -printf format: <type>\\t<size>\\t<mtime-epoch>\\t<name>\n const cmd = [\n `cd \"${escapeShellArg(resolved)}\" || exit 2`,\n `find . -mindepth 1 -maxdepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%f\\\\n' 2>/dev/null`,\n ].join(' && ');\n const result = await sandbox.commands.run(cmd);\n if (result.exitCode === 2) {\n throw new Error(`readdir: directory not found: ${path}`);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readdir failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n const entries: FileEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...nameParts] = line.split('\\t');\n const name = nameParts.join('\\t');\n if (!name) continue;\n const size = Number.parseInt(sizeStr, 10);\n const mtime = Number.parseFloat(mtimeStr);\n entries.push({\n name,\n type: type === 'd' ? 'directory' : 'file',\n size: Number.isFinite(size) ? size : 0,\n modified: Number.isFinite(mtime) ? new Date(mtime * 1000) : new Date(),\n });\n }\n return entries;\n },\n\n exists: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`test -e \"${escapeShellArg(resolved)}\"`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: SuperserveSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n // An empty or dot-only path would resolve to the workdir itself —\n // refuse it rather than `rm -rf` the sandbox's whole cwd.\n if (path.split('/').every((s) => s === '' || s === '.')) {\n throw new Error(`remove: refusing ambiguous path: ${JSON.stringify(path)}`);\n }\n const resolved = await resolveSandboxPath(sandbox, path, runCommand);\n const result = await sandbox.commands.run(`rm -rf \"${escapeShellArg(resolved)}\"`);\n if (result.exitCode !== 0) {\n throw new Error(`remove failed: ${result.stderr || `exit code ${result.exitCode}`}`);\n }\n },\n },\n\n getInstance: (sandbox: SuperserveSandbox): SuperserveSandbox => sandbox,\n\n pause: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n await sandbox.pause({ wait: true });\n } catch (error) {\n rethrowFriendly(error, 'Failed to pause Superserve sandbox');\n }\n },\n\n resume: async (sandbox: SuperserveSandbox): Promise<void> => {\n try {\n // The access token rotates on resume; the SDK refreshes the handle in place.\n await sandbox.resume();\n } catch (error) {\n rethrowFriendly(error, 'Failed to resume Superserve sandbox');\n }\n },\n\n pauseCapabilities: { memory: true },\n },\n\n snapshot: {\n // Snapshots hold memory and disk: restores keep the whole filesystem,\n // tmpfs /tmp included, and running processes. The source keeps running.\n capabilities: { scope: 'rootfs', memory: true, destroysSource: false },\n create: async (config: SuperserveConfig, sandboxId: string, options?: { name?: string }) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n // connect() activates the sandbox, so a paused one is resumed first.\n const sandbox = await SuperserveSandbox.connect(sandboxId, { apiKey, baseUrl });\n return toSnapshot(await sandbox.snapshot({ name: options?.name }));\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve snapshot');\n }\n },\n list: async (config: SuperserveConfig, options?: { sandboxId?: string; limit?: number }) => {\n // Snapshots are listed per sandbox. Callers that aggregate across\n // providers pass no options, so an unscoped call returns nothing\n // instead of throwing and failing their whole listing.\n if (!options?.sandboxId) return [];\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const infos = await SuperserveSnapshot.list(options.sandboxId, { apiKey, baseUrl, limit: options.limit });\n return infos.map(toSnapshot);\n },\n delete: async (config: SuperserveConfig, snapshotId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n await SuperserveSnapshot.deleteById(snapshotId, { apiKey, baseUrl });\n },\n },\n\n volume: {\n create: async (config: SuperserveConfig, options: SuperserveVolumeCreateOptions) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n const volume = await SuperserveVolume.create({\n ...connection,\n name: options.name,\n ...(options.sizeBytes !== undefined ? { capacityBytes: options.sizeBytes } : {}),\n idempotencyKey: options.idempotencyKey,\n timeoutMs: options.timeoutMs,\n signal: options.signal,\n });\n return toVolume(volume);\n },\n get: async (config: SuperserveConfig, idOrName: string) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n try {\n return toVolume(await SuperserveVolume.connect(idOrName, connection));\n } catch (error) {\n if (error instanceof NotFoundError) return null;\n throw error;\n }\n },\n list: async (config: SuperserveConfig, options?: { limit?: number }) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n const volumes = await SuperserveVolume.list({ ...connection, limit: options?.limit });\n return volumes.map(toVolume);\n },\n delete: async (config: SuperserveConfig, idOrName: string) => {\n const connection = resolveConfig({ apiKey: resolveApiKey(config), baseUrl: resolveBaseUrl(config) });\n await deleteVolume(connection, idOrName);\n },\n },\n\n template: {\n create: async (config: SuperserveConfig, options: SuperserveTemplateCreateOptions) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n const { name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd } = options;\n if (!from) {\n throw new Error('Superserve templates are built from an image: pass `from` (e.g. \"node:22\").');\n }\n try {\n const template = await SuperserveTemplate.create({\n apiKey, baseUrl, name, from, vcpu, memoryMib, diskMib, steps, startCmd, readyCmd,\n });\n return toTemplate(await template.waitUntilReady());\n } catch (error) {\n rethrowFriendly(error, 'Failed to create Superserve template');\n }\n },\n list: async (config: SuperserveConfig) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n const infos = await SuperserveTemplate.list({ apiKey, baseUrl });\n return infos.map(toTemplate);\n } catch {\n return [];\n }\n },\n delete: async (config: SuperserveConfig, templateId: string) => {\n const apiKey = resolveApiKey(config);\n const baseUrl = resolveBaseUrl(config);\n try {\n await SuperserveTemplate.deleteById(templateId, { apiKey, baseUrl });\n } catch {\n /* already deleted */\n }\n },\n },\n },\n});\n\nexport type { Sandbox as SuperserveSandbox } from '@superserve/sdk';\n"],"mappings":";AAMA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA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AM,MAAM,WAAW,SAAS,OAAO,UAAU,SAAS,IAAI;AAC5E,YAAI,CAAC,MAAM;AACT,gBAAM,IAAI,MAAM,6EAA6E;AAAA,QAC/F;AACA,YAAI;AACF,gBAAM,WAAW,MAAM,mBAAmB,OAAO;AAAA,YAC/C;AAAA,YAAQ;AAAA,YAAS;AAAA,YAAM;AAAA,YAAM;AAAA,YAAM;AAAA,YAAW;AAAA,YAAS;AAAA,YAAO;AAAA,YAAU;AAAA,UAC1E,CAAC;AACD,iBAAO,WAAW,MAAM,SAAS,eAAe,CAAC;AAAA,QACnD,SAAS,OAAO;AACd,0BAAgB,OAAO,sCAAsC;AAAA,QAC/D;AAAA,MACF;AAAA,MACA,MAAM,OAAO,WAA6B;AACxC,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,QAAQ,MAAM,mBAAmB,KAAK,EAAE,QAAQ,QAAQ,CAAC;AAC/D,iBAAO,MAAM,IAAI,UAAU;AAAA,QAC7B,QAAQ;AACN,iBAAO,CAAC;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ,OAAO,QAA0B,eAAuB;AAC9D,cAAM,SAAS,cAAc,MAAM;AACnC,cAAM,UAAU,eAAe,MAAM;AACrC,YAAI;AACF,gBAAM,mBAAmB,WAAW,YAAY,EAAE,QAAQ,QAAQ,CAAC;AAAA,QACrE,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["runCommand"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@computesdk/superserve",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"description": "Superserve
|
|
3
|
+
"version": "0.2.28",
|
|
4
|
+
"description": "Superserve sandbox adapter for ComputeSDK. Run code in Firecracker microVMs.",
|
|
5
5
|
"author": "Superserve",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -18,9 +18,9 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@superserve/sdk": "^0.
|
|
22
|
-
"@computesdk/provider": "2.1.
|
|
23
|
-
"computesdk": "4.1.
|
|
21
|
+
"@superserve/sdk": "^0.13.0",
|
|
22
|
+
"@computesdk/provider": "2.1.29",
|
|
23
|
+
"computesdk": "4.1.23"
|
|
24
24
|
},
|
|
25
25
|
"keywords": [
|
|
26
26
|
"computesdk",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"tsup": "^8.0.0",
|
|
51
51
|
"typescript": "^5.0.0",
|
|
52
52
|
"vitest": "^1.0.0",
|
|
53
|
-
"@computesdk/test-utils": "2.0.
|
|
53
|
+
"@computesdk/test-utils": "2.0.7"
|
|
54
54
|
},
|
|
55
55
|
"scripts": {
|
|
56
56
|
"build": "tsup",
|