@sandboxrouter/sdk 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -54,6 +54,112 @@ export declare class Client {
54
54
  }>;
55
55
  /** A handle on a sandbox you created earlier. */
56
56
  sandbox(id: string): RemoteSandbox;
57
+ /**
58
+ * Workspaces, on the hosted service: a computer with an id that outlives any one sandbox. It sleeps
59
+ * when nothing has used it for a while and wakes on the next call, with its files as you left them.
60
+ *
61
+ * const ws = await sr.workspaces.create({ name: "my desk" });
62
+ * await ws.exec("echo hello > note.txt");
63
+ * // ...hours later, from anywhere:
64
+ * const again = sr.workspaces.get(ws.id);
65
+ * console.log((await again.exec("cat note.txt")).stdout);
66
+ */
67
+ readonly workspaces: {
68
+ create: (opts?: WorkspaceOptions) => Promise<RemoteWorkspace>;
69
+ list: () => Promise<WorkspaceInfo[]>;
70
+ /** A handle to a workspace you already have. No request is made until you use it. */
71
+ get: (id: string) => RemoteWorkspace;
72
+ };
73
+ }
74
+ /** What a workspace is created with: a sandbox's size and routing options, plus how it sleeps and what it keeps. */
75
+ export interface WorkspaceOptions extends Pick<SandboxSpec, "vcpu" | "memoryGb" | "image" | "env">, Pick<RouteOptions, "provider" | "strategy" | "fallback" | "maxHourlyUsd"> {
76
+ name?: string;
77
+ /** Seconds without a call before it sleeps. Default 300, at least 60. */
78
+ idleSeconds?: number;
79
+ /** "price": when it goes idle, move it to a provider that is much cheaper. Default "off". */
80
+ autoMove?: "off" | "price";
81
+ /** The folder snapshots and moves carry. Default: the folder commands run in. */
82
+ folder?: string;
83
+ }
84
+ export interface WorkspaceInfo {
85
+ id: string;
86
+ name: string;
87
+ state: "awake" | "asleep" | "gone";
88
+ provider: string;
89
+ size: {
90
+ vcpu: number;
91
+ memoryGb: number;
92
+ };
93
+ idleSeconds: number;
94
+ autoMove: "off" | "price";
95
+ /** What it is charged per hour right now: 0 while asleep. */
96
+ hourlyUsd: number;
97
+ costUsd: number;
98
+ /** Billed awake periods so far: the first start, each wake, each move or restore. */
99
+ sessions: number;
100
+ createdAt: string;
101
+ lastUsedAt: string;
102
+ folder?: string;
103
+ /** The copy of its folder kept outside the provider, from the last time it went to sleep. */
104
+ snapshot: {
105
+ at: string;
106
+ bytes: number;
107
+ } | null;
108
+ /** Why the last attempt left no new snapshot. */
109
+ snapshotNote?: string;
110
+ sleptAt?: string;
111
+ /** When a sleeping workspace is deleted if nothing wakes it. */
112
+ deletedIfAsleepUntil?: string;
113
+ }
114
+ /** What a call adds when the workspace was asleep, or had to be rebuilt from its snapshot on another provider. */
115
+ export interface WorkspaceWake {
116
+ woke: boolean;
117
+ wakeMs?: number;
118
+ restored?: {
119
+ from: string;
120
+ to: string;
121
+ snapshotAt: string;
122
+ folder: string;
123
+ };
124
+ }
125
+ /** A workspace on the hosted service. Calls wake it when it sleeps. */
126
+ export declare class RemoteWorkspace {
127
+ private readonly client;
128
+ readonly id: string;
129
+ readonly created?: WorkspaceInfo | undefined;
130
+ /**
131
+ * @internal
132
+ * @param created What the create call answered, when this handle came from `workspaces.create`.
133
+ */
134
+ constructor(client: Client, id: string, created?: WorkspaceInfo | undefined);
135
+ private path;
136
+ private json;
137
+ /** Its state, provider and cost now. */
138
+ info(): Promise<WorkspaceInfo>;
139
+ /** Run a command, waking the workspace first if it sleeps. `woke` and `restored` say what that took. */
140
+ exec(cmd: string, opts?: Pick<ExecOptions, "cwd" | "env" | "timeoutSeconds">): Promise<ExecResult & WorkspaceWake>;
141
+ writeFile(path: string, content: string | Uint8Array): Promise<void>;
142
+ readFile(path: string): Promise<Uint8Array>;
143
+ readText(path: string): Promise<string>;
144
+ /** Put it to sleep now: paused, files kept, nothing charged until the next call. */
145
+ sleep(): Promise<WorkspaceInfo>;
146
+ wake(): Promise<WorkspaceInfo & WorkspaceWake>;
147
+ /** Save its folder outside the provider now. One is also taken every time it goes to sleep. */
148
+ snapshot(): Promise<WorkspaceInfo>;
149
+ /** Move it to another provider (the cheapest other one when none is named). Its folder is copied; the id stays. */
150
+ move(opts?: {
151
+ provider?: string;
152
+ }): Promise<WorkspaceInfo & {
153
+ moved: {
154
+ from: string;
155
+ to: string;
156
+ folder: string;
157
+ movedTo: string;
158
+ bytes: number;
159
+ };
160
+ }>;
161
+ /** Delete the workspace, its sandbox and its snapshot. */
162
+ delete(): Promise<void>;
57
163
  }
58
164
  export declare class ClientError extends Error {
59
165
  readonly status: number;
package/dist/client.js CHANGED
@@ -82,6 +82,84 @@ export class Client {
82
82
  sandbox(id) {
83
83
  return new RemoteSandbox(this, id, id.split(":")[0]);
84
84
  }
85
+ /**
86
+ * Workspaces, on the hosted service: a computer with an id that outlives any one sandbox. It sleeps
87
+ * when nothing has used it for a while and wakes on the next call, with its files as you left them.
88
+ *
89
+ * const ws = await sr.workspaces.create({ name: "my desk" });
90
+ * await ws.exec("echo hello > note.txt");
91
+ * // ...hours later, from anywhere:
92
+ * const again = sr.workspaces.get(ws.id);
93
+ * console.log((await again.exec("cat note.txt")).stdout);
94
+ */
95
+ workspaces = {
96
+ create: async (opts = {}) => {
97
+ const info = await this.json("POST", "/v1/workspaces", opts);
98
+ return new RemoteWorkspace(this, info.id, info);
99
+ },
100
+ list: async () => (await this.json("GET", "/v1/workspaces")).workspaces,
101
+ /** A handle to a workspace you already have. No request is made until you use it. */
102
+ get: (id) => new RemoteWorkspace(this, id),
103
+ };
104
+ }
105
+ /** A workspace on the hosted service. Calls wake it when it sleeps. */
106
+ export class RemoteWorkspace {
107
+ client;
108
+ id;
109
+ created;
110
+ /**
111
+ * @internal
112
+ * @param created What the create call answered, when this handle came from `workspaces.create`.
113
+ */
114
+ constructor(client, id, created) {
115
+ this.client = client;
116
+ this.id = id;
117
+ this.created = created;
118
+ }
119
+ path(suffix = "") {
120
+ return `/v1/workspaces/${encodeURIComponent(this.id)}${suffix}`;
121
+ }
122
+ async json(method, suffix = "", body) {
123
+ return (await this.client.request(method, this.path(suffix), body)).json();
124
+ }
125
+ /** Its state, provider and cost now. */
126
+ info() {
127
+ return this.json("GET");
128
+ }
129
+ /** Run a command, waking the workspace first if it sleeps. `woke` and `restored` say what that took. */
130
+ exec(cmd, opts = {}) {
131
+ return this.json("POST", "/exec", { cmd, ...opts });
132
+ }
133
+ async writeFile(path, content) {
134
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
135
+ await this.client.request("PUT", this.path(`/files?path=${encodeURIComponent(path)}`), data);
136
+ }
137
+ async readFile(path) {
138
+ const res = await this.client.request("GET", this.path(`/files?path=${encodeURIComponent(path)}`), undefined, "application/octet-stream");
139
+ return new Uint8Array(await res.arrayBuffer());
140
+ }
141
+ async readText(path) {
142
+ return new TextDecoder().decode(await this.readFile(path));
143
+ }
144
+ /** Put it to sleep now: paused, files kept, nothing charged until the next call. */
145
+ sleep() {
146
+ return this.json("POST", "/sleep");
147
+ }
148
+ wake() {
149
+ return this.json("POST", "/wake");
150
+ }
151
+ /** Save its folder outside the provider now. One is also taken every time it goes to sleep. */
152
+ snapshot() {
153
+ return this.json("POST", "/snapshot");
154
+ }
155
+ /** Move it to another provider (the cheapest other one when none is named). Its folder is copied; the id stays. */
156
+ move(opts = {}) {
157
+ return this.json("POST", "/move", opts);
158
+ }
159
+ /** Delete the workspace, its sandbox and its snapshot. */
160
+ async delete() {
161
+ await this.client.request("DELETE", this.path());
162
+ }
85
163
  }
86
164
  const DEFAULT_URL = "http://127.0.0.1:8787";
87
165
  export class ClientError extends Error {
@@ -0,0 +1,103 @@
1
+ import type { Router } from "./router.js";
2
+ import type { ProviderId } from "./types.js";
3
+ /**
4
+ * Image boot benchmark: start a sandbox straight from a public registry image reference, with no template,
5
+ * snapshot or rebuild step in between, and time it.
6
+ *
7
+ * The first start includes the provider pulling and preparing the image, and happens once per image and
8
+ * account, so it is one observation. The repeat starts come after it. Every sandbox runs a command whose
9
+ * output must contain an expected text, so a provider that starts some other image is not counted.
10
+ */
11
+ export interface ImageVerify {
12
+ /** Run in every sandbox. */
13
+ command: string;
14
+ /** Its output must contain this, e.g. "Python 3.11". */
15
+ contains: string;
16
+ }
17
+ export interface ImageRow {
18
+ provider: string;
19
+ size: {
20
+ vcpu: number;
21
+ memoryGb: number;
22
+ };
23
+ /** Create time of the first start from this image, in ms. Missing when the first start failed. */
24
+ firstCreateMs?: number;
25
+ /** Create time of each later start that was verified, in ms. */
26
+ repeatCreateMs: number[];
27
+ medianRepeatCreateMs?: number;
28
+ /** Starts whose sandbox ran the verify command and printed the expected text. */
29
+ verified: number;
30
+ /** Starts that failed, or whose sandbox was not the image asked for. */
31
+ failures: number;
32
+ /** List price per hour at this size. */
33
+ hourlyUsd?: number;
34
+ }
35
+ /** A saved image boot report (results/, tool "sandboxrouter-image"). */
36
+ export interface ImageReport {
37
+ tool: "sandboxrouter-image";
38
+ version: string;
39
+ date: string;
40
+ label?: string;
41
+ by?: string;
42
+ /** The registry reference every provider was given. */
43
+ image: string;
44
+ verify: ImageVerify;
45
+ spec: {
46
+ vcpu: number;
47
+ memoryGb: number;
48
+ };
49
+ /** Starts after the first one. */
50
+ repeats: number;
51
+ node: string;
52
+ platform: string;
53
+ rows: ImageRow[];
54
+ }
55
+ export interface ImageBenchOptions {
56
+ router: Router;
57
+ providers: ProviderId[];
58
+ image: string;
59
+ verify: ImageVerify;
60
+ spec: {
61
+ vcpu: number;
62
+ memoryGb: number;
63
+ };
64
+ repeats?: number;
65
+ /** Seconds to wait for one create. The first start of a large image can take minutes. */
66
+ createTimeoutSeconds?: number;
67
+ onProgress?: (message: string) => void;
68
+ }
69
+ /** One provider at a time per image, providers in parallel. */
70
+ export declare function imageBench(opts: ImageBenchOptions): Promise<ImageRow[]>;
71
+ export declare function loadImageReports(dir: string): ImageReport[];
72
+ /**
73
+ * For the website: one table per image, each provider's latest run of that image. Only providers whose every
74
+ * start was verified get a row with times; fastest repeat start first.
75
+ */
76
+ export declare function imageTable(reports: ImageReport[]): {
77
+ image: string;
78
+ spec: {
79
+ vcpu: number;
80
+ memoryGb: number;
81
+ };
82
+ repeats: number;
83
+ rows: {
84
+ provider: string;
85
+ size: {
86
+ vcpu: number;
87
+ memoryGb: number;
88
+ };
89
+ /** Create time of the first start from this image, in ms. Missing when the first start failed. */
90
+ firstCreateMs?: number;
91
+ /** Create time of each later start that was verified, in ms. */
92
+ repeatCreateMs: number[];
93
+ medianRepeatCreateMs?: number;
94
+ /** Starts whose sandbox ran the verify command and printed the expected text. */
95
+ verified: number;
96
+ /** Starts that failed, or whose sandbox was not the image asked for. */
97
+ failures: number;
98
+ /** List price per hour at this size. */
99
+ hourlyUsd?: number;
100
+ name: string;
101
+ measuredAt: string;
102
+ }[];
103
+ }[];
@@ -0,0 +1,110 @@
1
+ import { readdirSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { benchmarksPublishable, CATALOG } from "./catalog.js";
4
+ import { median } from "./bench-store.js";
5
+ /** One provider at a time per image, providers in parallel. */
6
+ export async function imageBench(opts) {
7
+ const repeats = opts.repeats ?? 3;
8
+ const timeout = opts.createTimeoutSeconds ?? 900;
9
+ const start = async (provider) => {
10
+ let sbx;
11
+ try {
12
+ const t0 = Date.now();
13
+ sbx = await opts.router.create({ ...opts.spec, timeoutMinutes: 15, image: { [provider]: opts.image } }, { provider, fallback: false, createTimeoutSeconds: timeout, deadlineSeconds: timeout });
14
+ const createMs = Date.now() - t0;
15
+ const r = await sbx.exec(opts.verify.command, { timeoutSeconds: 60 });
16
+ if (!`${r.stdout}${r.stderr}`.includes(opts.verify.contains))
17
+ return { error: "the sandbox is not the image asked for" };
18
+ return { createMs, size: sbx.size };
19
+ }
20
+ catch (e) {
21
+ return { error: e.message.replace(/\s+/g, " ").slice(0, 200) };
22
+ }
23
+ finally {
24
+ await sbx?.kill().catch(() => { });
25
+ }
26
+ };
27
+ return Promise.all(opts.providers.map(async (provider) => {
28
+ const first = await start(provider);
29
+ opts.onProgress?.(`${provider}: first start ${first.error ?? `${first.createMs} ms`}`);
30
+ const later = [];
31
+ if (!first.error) {
32
+ for (let i = 0; i < repeats; i++) {
33
+ const r = await start(provider);
34
+ later.push(r);
35
+ opts.onProgress?.(`${provider}: repeat start ${r.error ?? `${r.createMs} ms`}`);
36
+ }
37
+ }
38
+ const ok = later.filter((r) => r.createMs !== undefined).map((r) => r.createMs);
39
+ let hourlyUsd;
40
+ try {
41
+ const plan = await opts.router.plan({ ...opts.spec, image: { [provider]: opts.image } }, { provider, fallback: false });
42
+ hourlyUsd = plan[0]?.listHourlyUsd;
43
+ }
44
+ catch {
45
+ /* no price: the row still stands */
46
+ }
47
+ return {
48
+ provider,
49
+ size: first.size ?? opts.spec,
50
+ ...(first.createMs !== undefined ? { firstCreateMs: first.createMs } : {}),
51
+ repeatCreateMs: ok,
52
+ ...(ok.length ? { medianRepeatCreateMs: median(ok) } : {}),
53
+ verified: (first.error ? 0 : 1) + ok.length,
54
+ failures: (first.error ? 1 : 0) + later.length - ok.length,
55
+ ...(hourlyUsd !== undefined ? { hourlyUsd } : {}),
56
+ };
57
+ }));
58
+ }
59
+ export function loadImageReports(dir) {
60
+ let files;
61
+ try {
62
+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));
63
+ }
64
+ catch {
65
+ return [];
66
+ }
67
+ const out = [];
68
+ for (const f of files.sort()) {
69
+ try {
70
+ const r = JSON.parse(readFileSync(join(dir, f), "utf8"));
71
+ if (r?.tool === "sandboxrouter-image" && Array.isArray(r.rows))
72
+ out.push(r);
73
+ }
74
+ catch {
75
+ /* skip unreadable files */
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ const KNOWN = new Set(CATALOG.map((c) => c.id));
81
+ /**
82
+ * For the website: one table per image, each provider's latest run of that image. Only providers whose every
83
+ * start was verified get a row with times; fastest repeat start first.
84
+ */
85
+ export function imageTable(reports) {
86
+ const images = new Map();
87
+ for (const rep of reports) {
88
+ const entry = images.get(rep.image) ?? { spec: rep.spec, repeats: rep.repeats, latest: new Map() };
89
+ images.set(rep.image, entry);
90
+ for (const r of rep.rows) {
91
+ if (!KNOWN.has(r.provider) || !benchmarksPublishable(r.provider))
92
+ continue;
93
+ const seen = entry.latest.get(r.provider);
94
+ if (!seen || rep.date > seen.date)
95
+ entry.latest.set(r.provider, { row: r, date: rep.date });
96
+ }
97
+ }
98
+ return [...images.entries()]
99
+ .map(([image, { spec, repeats, latest }]) => ({
100
+ image,
101
+ spec,
102
+ repeats,
103
+ rows: [...latest.values()]
104
+ .filter(({ row }) => row.failures === 0 && row.medianRepeatCreateMs !== undefined && row.firstCreateMs !== undefined)
105
+ .map(({ row, date }) => ({ ...row, name: CATALOG.find((c) => c.id === row.provider).name, measuredAt: date }))
106
+ .sort((a, b) => a.medianRepeatCreateMs - b.medianRepeatCreateMs),
107
+ }))
108
+ .filter((t) => t.rows.length)
109
+ .sort((a, b) => a.image.localeCompare(b.image));
110
+ }
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@ export { BILLED_VS_LIST } from "./billing.js";
12
12
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
13
13
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd, type ProviderInfo } from "./catalog.js";
14
14
  export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS, type ServerHooks } from "./server.js";
15
- export { Client, ClientError, RemoteSandbox, type CreateResponse } from "./client.js";
15
+ export { Client, ClientError, RemoteSandbox, RemoteWorkspace, type CreateResponse, type WorkspaceInfo, type WorkspaceOptions, type WorkspaceWake } from "./client.js";
16
16
  export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES, type CopyOptions, type CopyResult, type FileBox, type MoveOptions, type Mover } from "./move.js";
17
17
  export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, type ComputerRoute, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, type ComputerCatalogEntry, type ComputerCandidate, type ComputerProviderId, type ActionResult, type ComputerAction, type ComputerActionName, type ComputerInfo, type ComputerOs, type ComputerProvider, type ComputerSpec, type ProviderComputer, } from "./computers.js";
18
18
  export { bench, benchMarkdown, type BenchRow } from "./bench.js";
@@ -45,6 +45,7 @@ export { DenoProvider } from "./providers/deno.js";
45
45
  export { FreestyleProvider } from "./providers/freestyle.js";
46
46
  export { KoyebProvider } from "./providers/koyeb.js";
47
47
  export { DedalusProvider } from "./providers/dedalus.js";
48
+ export { RunCloudProvider } from "./providers/runcloud.js";
48
49
  export { OpenScaleProvider } from "./providers/openscale.js";
49
50
  export { SuperserveProvider } from "./providers/superserve.js";
50
51
  export { SailProvider } from "./providers/sail.js";
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { BILLED_VS_LIST } from "./billing.js";
12
12
  export { validate, splitRequest, SPEC_KEYS, ROUTE_KEYS, STRATEGIES } from "./validate.js";
13
13
  export { CATALOG, hourlyCost, unfit, info, billingRules, billedUsd } from "./catalog.js";
14
14
  export { createApp, HttpError, ERROR_STATUS, ORPHAN_GRACE_MS } from "./server.js";
15
- export { Client, ClientError, RemoteSandbox } from "./client.js";
15
+ export { Client, ClientError, RemoteSandbox, RemoteWorkspace } from "./client.js";
16
16
  export { copyFiles, moveSandbox, DEFAULT_COPY_MAX_BYTES } from "./move.js";
17
17
  export { RoutedComputer, createComputer, splitComputerRequest, DEFAULT_COMPUTER_TIMEOUT_S, DEFAULT_COMPUTER_DEADLINE_S, planComputer, computerCatalog, computerHourly, COMPUTER_ENTRIES, } from "./computers.js";
18
18
  export { bench, benchMarkdown } from "./bench.js";
@@ -45,6 +45,7 @@ export { DenoProvider } from "./providers/deno.js";
45
45
  export { FreestyleProvider } from "./providers/freestyle.js";
46
46
  export { KoyebProvider } from "./providers/koyeb.js";
47
47
  export { DedalusProvider } from "./providers/dedalus.js";
48
+ export { RunCloudProvider } from "./providers/runcloud.js";
48
49
  export { OpenScaleProvider } from "./providers/openscale.js";
49
50
  export { SuperserveProvider } from "./providers/superserve.js";
50
51
  export { SailProvider } from "./providers/sail.js";
@@ -1,5 +1,5 @@
1
1
  import { type PhaseMs } from "./task.js";
2
- import type { BenchRow } from "./bench.js";
2
+ import { type BenchRow } from "./bench.js";
3
3
  import { type Size } from "./router.js";
4
4
  import type { ProviderId, SandboxSpec } from "./types.js";
5
5
  /**
@@ -39,6 +39,10 @@ export interface LeaderRow {
39
39
  medianCreateMs?: number;
40
40
  medianExecMs?: number;
41
41
  medianReadyMs?: number;
42
+ /** Median time for the delete call to return, from each location's newest run that timed it. */
43
+ medianKillMs?: number;
44
+ /** The delete time covers waiting until the sandbox is gone (`KILL_WAITS_UNTIL_GONE`). */
45
+ killWaitsUntilGone?: boolean;
42
46
  successRate: number;
43
47
  /** Runs behind the row that the provider was asked to do (refusals for an account limit left out). */
44
48
  runs: number;
@@ -5,6 +5,7 @@ import { BILLED_VS_LIST } from "./billing.js";
5
5
  import { AGENT_TASK_VERSION } from "./agent-bench.js";
6
6
  import { isCurrentTask, TASK_VERSION, taskByVersion, taskUsd } from "./task.js";
7
7
  import { median } from "./bench-store.js";
8
+ import { KILL_WAITS_UNTIL_GONE } from "./bench.js";
8
9
  import { sizeOf } from "./router.js";
9
10
  const sameSize = (a, b) => a.vcpu === b.vcpu && a.memoryGb === b.memoryGb;
10
11
  const DEFAULT_SIZE = { vcpu: 2, memoryGb: 4 };
@@ -68,6 +69,8 @@ export function aggregate(reports, cohort = DEFAULT_SIZE) {
68
69
  newest.set(key, rep.date);
69
70
  }
70
71
  const MONTH = 30 * 86_400_000;
72
+ // Delete timing is newer than most reports: take it from each location's newest run that has it.
73
+ const kills = new Map();
71
74
  for (const rep of comparable) {
72
75
  for (const r of rep.rows) {
73
76
  if (!KNOWN.has(r.provider))
@@ -75,6 +78,8 @@ export function aggregate(reports, cohort = DEFAULT_SIZE) {
75
78
  const key = `${r.provider}\u0000${rep.label ?? ""}`;
76
79
  if (Date.parse(newest.get(key)) - Date.parse(rep.date) > MONTH)
77
80
  continue;
81
+ if (typeof r.medianKillMs === "number" && rep.date > (kills.get(key)?.date ?? ""))
82
+ kills.set(key, { row: r, date: rep.date });
78
83
  const seen = latest.get(key);
79
84
  if (!seen || r.runs > seen.row.runs || (r.runs === seen.row.runs && rep.date > seen.date))
80
85
  latest.set(key, { row: r, date: rep.date });
@@ -92,6 +97,7 @@ export function aggregate(reports, cohort = DEFAULT_SIZE) {
92
97
  const ok = rs.reduce((n, r) => n + (r.runs - r.failures), 0);
93
98
  // Refusals for a limit on the benchmarking account aren't the provider failing: leave them out of the rate.
94
99
  const attempted = runs - rs.reduce((n, r) => n + (r.limited ?? 0), 0);
100
+ const killed = [...kills.values()].filter(({ row }) => row.provider === id && sameSize(row.size ?? sizeOf(id, cohort), size)).map(({ row }) => row.medianKillMs);
95
101
  return {
96
102
  provider: id,
97
103
  name: CATALOG.find((c) => c.id === id).name,
@@ -99,6 +105,7 @@ export function aggregate(reports, cohort = DEFAULT_SIZE) {
99
105
  medianCreateMs: median(rs.map((r) => r.medianCreateMs).filter((n) => typeof n === "number")),
100
106
  medianExecMs: median(rs.map((r) => r.medianExecMs).filter((n) => typeof n === "number")),
101
107
  medianReadyMs: rs.every((r) => r.medianReadyMs !== undefined) ? median(rs.map((r) => r.medianReadyMs)) : undefined,
108
+ ...(killed.length ? { medianKillMs: median(killed), ...(KILL_WAITS_UNTIL_GONE.has(id) ? { killWaitsUntilGone: true } : {}) } : {}),
102
109
  successRate: attempted ? ok / attempted : 0,
103
110
  runs: attempted,
104
111
  hourlyUsd: hourlyCost(id, measured(size)),
@@ -52,3 +52,54 @@ export interface IndexLine {
52
52
  }
53
53
  /** Today's index: one line per standard piece of work. */
54
54
  export declare function priceIndex(verified?: readonly ProviderId[]): IndexLine[];
55
+ /** The size the price spread compares providers at. */
56
+ export declare const SPREAD_SIZE: {
57
+ readonly vcpu: 2;
58
+ readonly memoryGb: 4;
59
+ };
60
+ export interface SpreadRow {
61
+ provider: ProviderId;
62
+ name: string;
63
+ /** List price for a 2 vCPU / 4 GB sandbox running for an hour with every core busy. */
64
+ hourlyUsd: number;
65
+ /** The same, per vCPU (each with its 2 GB of memory). */
66
+ vcpuHourUsd: number;
67
+ /** Passed the real-account check. */
68
+ tested: boolean;
69
+ }
70
+ /**
71
+ * Every hosted provider's list price for the same sandbox, cheapest first, and the median: how far apart
72
+ * prices are today. List prices only, straight from the catalog: no measured-bill correction and no fees.
73
+ */
74
+ export declare function priceSpread(verified?: readonly ProviderId[]): {
75
+ size: typeof SPREAD_SIZE;
76
+ medianVcpuHourUsd: number;
77
+ rows: SpreadRow[];
78
+ };
79
+ export interface PriceHistoryEntry {
80
+ date: string;
81
+ /** Each provider's list price for 2 vCPU / 4 GB for an hour, USD. */
82
+ prices: Record<string, number>;
83
+ /** What changed, where someone wrote it down: a provider's own price change, a new provider, or a correction of ours. */
84
+ note?: string;
85
+ }
86
+ /**
87
+ * The history with today's prices added, if they differ from the last entry. Prices change only when the
88
+ * catalog does, so the entry is written by the same change that edits the catalog.
89
+ */
90
+ export declare function withTodaysPrices(history: PriceHistoryEntry[], today: string, rows?: SpreadRow[]): PriceHistoryEntry[];
91
+ export interface PriceTrendPoint {
92
+ date: string;
93
+ /** The price level per vCPU-hour from this date until the next point. */
94
+ vcpuHourUsd: number;
95
+ /** Providers tracked on this date. */
96
+ providers: number;
97
+ note?: string;
98
+ }
99
+ /**
100
+ * One line from the history: the median list price per vCPU-hour over time, moving only when a provider
101
+ * changes its price. The last point is the median across every provider tracked today. Going back, each step
102
+ * is scaled by how the median moved among the providers present on both sides of it, so adding a provider
103
+ * (which changes who is counted, not what anything costs) does not move the line.
104
+ */
105
+ export declare function priceTrend(history: PriceHistoryEntry[]): PriceTrendPoint[];
@@ -51,3 +51,73 @@ export function priceIndex(verified = Object.keys(VERIFIED)) {
51
51
  };
52
52
  });
53
53
  }
54
+ /** The size the price spread compares providers at. */
55
+ export const SPREAD_SIZE = { vcpu: 2, memoryGb: 4 };
56
+ /**
57
+ * Every hosted provider's list price for the same sandbox, cheapest first, and the median: how far apart
58
+ * prices are today. List prices only, straight from the catalog: no measured-bill correction and no fees.
59
+ */
60
+ export function priceSpread(verified = Object.keys(VERIFIED)) {
61
+ const hosted = CATALOG.filter((c) => !c.local).map((c) => c.id);
62
+ const router = new Router({ providers: hosted.map(stub), ledger: false });
63
+ const round = (n) => Math.round(n * 1e6) / 1e6;
64
+ const rows = router
65
+ .plan(withOwnImages({ ...SPREAD_SIZE }), { strategy: "cheapest" })
66
+ .filter((c) => !c.skip && c.listHourlyUsd > 0)
67
+ .map((c) => ({
68
+ provider: c.provider,
69
+ name: CATALOG.find((p) => p.id === c.provider).name,
70
+ hourlyUsd: round(c.listHourlyUsd),
71
+ vcpuHourUsd: round(c.listHourlyUsd / SPREAD_SIZE.vcpu),
72
+ tested: verified.includes(c.provider),
73
+ }))
74
+ .sort((a, b) => a.hourlyUsd - b.hourlyUsd || a.provider.localeCompare(b.provider));
75
+ return { size: SPREAD_SIZE, medianVcpuHourUsd: round(median(rows.map((r) => r.vcpuHourUsd * 1e6)) / 1e6), rows };
76
+ }
77
+ /**
78
+ * The history with today's prices added, if they differ from the last entry. Prices change only when the
79
+ * catalog does, so the entry is written by the same change that edits the catalog.
80
+ */
81
+ export function withTodaysPrices(history, today, rows = priceSpread().rows) {
82
+ const prices = Object.fromEntries([...rows].sort((a, b) => a.provider.localeCompare(b.provider)).map((r) => [r.provider, r.hourlyUsd]));
83
+ const last = history.at(-1);
84
+ if (last && JSON.stringify(last.prices) === JSON.stringify(prices))
85
+ return history;
86
+ // A second change on the same day replaces that day's entry.
87
+ const kept = last?.date === today ? history.slice(0, -1) : history;
88
+ const note = kept.length ? priceNote(kept.at(-1).prices, prices, new Map(rows.map((r) => [r.provider, r.name]))) : "";
89
+ return [...kept, { date: today, prices, ...(note ? { note } : {}) }];
90
+ }
91
+ /** What differs between two sets of prices, in words: "E2B $0.1656 to $0.18; added Run Cloud". */
92
+ function priceNote(before, after, names) {
93
+ const name = (id) => names.get(id) ?? CATALOG.find((c) => c.id === id)?.name ?? id;
94
+ const moved = Object.keys(after).filter((id) => id in before && before[id] !== after[id]).map((id) => `${name(id)} $${before[id]} to $${after[id]}`);
95
+ const added = Object.keys(after).filter((id) => !(id in before)).map(name);
96
+ const removed = Object.keys(before).filter((id) => !(id in after)).map(name);
97
+ return [...moved, added.length ? `added ${added.join(", ")}` : "", removed.length ? `removed ${removed.join(", ")}` : ""].filter(Boolean).join("; ");
98
+ }
99
+ /**
100
+ * One line from the history: the median list price per vCPU-hour over time, moving only when a provider
101
+ * changes its price. The last point is the median across every provider tracked today. Going back, each step
102
+ * is scaled by how the median moved among the providers present on both sides of it, so adding a provider
103
+ * (which changes who is counted, not what anything costs) does not move the line.
104
+ */
105
+ export function priceTrend(history) {
106
+ if (!history.length)
107
+ return [];
108
+ const mid = (values) => median(values.map((v) => v * 1e6)) / 1e6;
109
+ const levels = new Array(history.length);
110
+ levels[history.length - 1] = mid(Object.values(history.at(-1).prices)) / SPREAD_SIZE.vcpu;
111
+ for (let i = history.length - 2; i >= 0; i--) {
112
+ const common = Object.keys(history[i].prices).filter((id) => id in history[i + 1].prices);
113
+ const before = common.length ? mid(common.map((id) => history[i].prices[id])) : 0;
114
+ const after = common.length ? mid(common.map((id) => history[i + 1].prices[id])) : 0;
115
+ levels[i] = before > 0 && after > 0 ? levels[i + 1] * (before / after) : levels[i + 1];
116
+ }
117
+ return history.map((e, i) => ({
118
+ date: e.date,
119
+ vcpuHourUsd: Math.round(levels[i] * 1e6) / 1e6,
120
+ providers: Object.keys(e.prices).length,
121
+ ...(e.note ? { note: e.note } : {}),
122
+ }));
123
+ }
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { ProviderError } from "../types.js";
3
3
  import { DEFAULT_EXEC_TIMEOUT_S, errorStatus, optionalImport, timeoutError, toBytes, wrapCommand } from "../util.js";
4
+ /** Seconds the Daytona SDK waits for a sandbox started from an image (its default, 60, is too short for a first pull). */
5
+ const IMAGE_CREATE_TIMEOUT_S = 600;
4
6
  /**
5
7
  * Daytona via `@daytonaio/sdk`. Default snapshot; set image.daytona to start from an image.
6
8
  *
@@ -49,7 +51,10 @@ export class DaytonaProvider {
49
51
  ...base,
50
52
  image: spec.image.daytona,
51
53
  resources: { cpu: spec.vcpu, memory: spec.memoryGb },
52
- })
54
+ },
55
+ // Daytona pulls and prepares an image the first time it sees it: about a minute for a 1 GB
56
+ // image, against the SDK's 60 s default. The router's createTimeoutSeconds is the real limit.
57
+ { timeout: IMAGE_CREATE_TIMEOUT_S })
53
58
  : await d.create(base);
54
59
  return new DaytonaBox(sbx);
55
60
  }
@@ -7,7 +7,8 @@ const DEFAULT_IMAGE = "ubuntu:22.04";
7
7
  const MIN_EXPIRY_SECONDS = 300;
8
8
  const MAX_EXPIRY_SECONDS = 604_800;
9
9
  const READY_TIMEOUT_MS = 5 * 60_000;
10
- const DELETE_TIMEOUT_MS = 60_000;
10
+ /** A deleted service takes about 62 s to disappear (measured, any size or image), so 60 s reported every kill as failed. */
11
+ const DELETE_TIMEOUT_MS = 180_000;
11
12
  /**
12
13
  * Northflank sandboxes via `@northflank/js-client`. Auth: NORTHFLANK_API_TOKEN plus
13
14
  * NORTHFLANK_PROJECT_ID (the project every sandbox is created in; its region is fixed at