withruntime 0.37.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -12,6 +12,7 @@ import { NotFoundError, RuntimeError } from "./errors.js";
12
12
  import { NETWORK_PRODUCTS, networkProductCommand } from "./network-cli.js";
13
13
  import { billingCommand } from "./billing-cli.js";
14
14
  import { cliRefusal, describeRecord, newestCpu, productWords, topicHelp } from "./cli-words.js";
15
+ import { outdatedLine } from "./cli-update.js";
15
16
  import { envFetch } from "./proxy.js";
16
17
  import { logStream, terminalSafe, terminalSafeLines } from "./terminal.js";
17
18
  import { VERSION } from "./transport.js";
@@ -52,15 +53,28 @@ Account
52
53
  reservations ls | get <id> | cancel <id> Your bookings; cancel gives the room back
53
54
  secrets set <NAME> --host <host>... [--header <name> [--format '<text {value}>']]
54
55
  [--allow '[GET,HEAD] /path/*']... Store a secret sandboxes use without seeing it; the
55
- [--only-label key=value[,k=v]]... value is read from standard input, never an argument.
56
- [--only-sandbox <id>]... --allow (paid): only these methods and paths get it.
57
- [--only-app <app id>]... --only-label: only sandboxes with those labels (each
58
- [--all-sandboxes] [--env <VAR>] flag one selector, any may match); --only-sandbox:
59
- only that sandbox; --only-app: every copy of that App,
60
- any version. A new value keeps the scope;
61
- --all-sandboxes gives it to every sandbox again.
62
- --env: the variable sandboxes see it in, if not NAME;
63
- secrets scoped to different sandboxes may share one
56
+ [--only-label key=value[,k=v]]... value is read from standard input or --from-file,
57
+ [--only-sandbox <id>]... never an argument. --allow (paid): only these
58
+ [--only-app <app id>]... methods and paths get it. --only-label: only
59
+ [--all-sandboxes] [--env <VAR>] sandboxes with those labels (each flag one selector,
60
+ [--expected-version N] any may match); --only-sandbox: only that sandbox;
61
+ [--from-file <path>] --only-app: every copy of that App, any version.
62
+ A new value keeps the scope; --all-sandboxes gives
63
+ it to every sandbox again. --env: the variable
64
+ sandboxes see it in, if not NAME; secrets scoped to
65
+ different sandboxes may share one.
66
+ --expected-version: write only over that version
67
+ (get shows it; 0: only if it does not exist yet)
68
+ secrets set <NAME> --exposed [--only-sandbox <id>]... [--only-app <app id>]...
69
+ [--env <VAR>] Give the sandboxes and Apps you name by id the value
70
+ [--expected-version N] itself, for what is not an HTTPS header (a database
71
+ [--from-file <path>] password, an SSH key): up to 64 KiB, several lines,
72
+ read byte for byte. Code in them can read it and
73
+ send it anywhere, and snapshots and forks hold it:
74
+ prefer --host for APIs. A new one needs
75
+ --only-sandbox or --only-app, never labels or every
76
+ sandbox; to change who gets it, set it again.
77
+ The key must be able to run commands in each
64
78
  secrets set <NAME> --keep-value [--host <host>]... [--allow '[GET] /path']...
65
79
  Narrow where it goes without its value: a subset of
66
80
  its hosts, only requests its rules allow now.
@@ -68,10 +82,11 @@ Account
68
82
  secrets set <NAME> --jobs [--host ...] A copy scheduled jobs put in their environment
69
83
  (job create --secret NAME); with --host, both
70
84
  secrets scope <NAME> --only-label k=v... | --only-sandbox <id>... | --only-app <id>... | --all-sandboxes
71
- Change which sandboxes get it; no value needed
85
+ Change which sandboxes get it; no value needed.
86
+ Not for --exposed: set it again with its value
72
87
  secrets ls [--limit N] [--after NAME] | get <NAME>
73
- Names, hosts, placeholders and jobs versions, never values;
74
- by name, a page of N after NAME
88
+ Names, kinds, versions, hosts and placeholders, never
89
+ values; by name, a page of N after NAME
75
90
  secrets rotate <NAME> A new version of the jobs copy, from standard input
76
91
  secrets reveal <NAME> [--version N] Print the jobs copy's value. The sandboxes' copy is
77
92
  never readable, by anyone
@@ -118,14 +133,14 @@ Connect
118
133
  Forward local ports to ports in a sandbox
119
134
 
120
135
  Observability
121
- sandboxes metrics <id> [--range 1h] CPU and memory over time (15m 1h 6h 24h 7d 30d)
136
+ sandboxes metrics <id> [--range 1h] CPU, memory, disk and network over time (15m 1h 6h 24h 7d 30d)
122
137
  events [--sandbox <id>] [--type <type>] Lifecycle events, newest first
123
138
  webhooks ls | create <url> [--events a,b] | test <id> | deliveries <id>
124
139
  | update <id> [--url u] [--events a,b] [--enable|--disable]
125
140
  | rotate-secret <id> [--keep <seconds>] | retry <deliveryId> | rm <id>
126
141
  Signed lifecycle events POSTed to your URL
127
- otel ls | create <endpoint> [--header K=V]... [--signals logs,metrics] | flush <id> | rm <id>
128
- Events and metrics to an OpenTelemetry endpoint
142
+ otel ls | create <endpoint> [--header K=V]... [--signals logs,metrics,traces] | flush <id> | rm <id>
143
+ Events, metrics and API call traces to an OpenTelemetry endpoint
129
144
 
130
145
  Products
131
146
  sandboxes Linux microVMs: exec, shell, files, code, previews, network, desktop, browser
@@ -170,6 +185,9 @@ const SANDBOX_HELP = `runtime sandboxes <command>
170
185
  [--idle-pause <seconds>] [--no-auto-wake] [--persistent] [--get-or-create]
171
186
  [--user root|sandbox] --user root: its commands, processes and
172
187
  shells run as root unless one says otherwise
188
+ [--lease <300-43200>] With no time limit, how far ahead each renewal
189
+ funds it: it runs through a control-plane outage
190
+ half that long
173
191
  Create one; prints its id
174
192
  ls [--all] [--label k=v]... [--state running] List (live ones unless --all)
175
193
  get <id> One sandbox, in full
@@ -205,6 +223,7 @@ const SANDBOX_HELP = `runtime sandboxes <command>
205
223
  extend <id> <seconds> Move a time limit on (one with none needs nothing)
206
224
  update <id> [--name n] [--label k=v]... [--env K[=V]]... [--unset-env K]... [--idle-pause <seconds>] [--auto-wake on|off]
207
225
  [--persistent on|off] [--max-total-cost <usd>|none] [--user root|sandbox]
226
+ [--lease <300-43200>|default]
208
227
  [--timeout <60-86400 from now>|0] [--on-timeout pause|stop|delete]
209
228
  Change its settings; persistent keeps it running until stopped;
210
229
  --env K alone sends K's value from your own environment,
@@ -427,7 +446,9 @@ function usage(message) {
427
446
  /** "Unknown command X." and, when one is close, the command that was meant. */
428
447
  function unknown(what, word, choices) {
429
448
  const meant = closest(word, choices);
430
- return usage(`Unknown ${what} ${word}.${meant ? ` Did you mean ${meant}?` : ""}`);
449
+ // Nothing close: say what it may be, when that is a short list.
450
+ const known = !meant && choices.length && choices.length <= 12 ? ` Use ${choices.join(", ")}.` : "";
451
+ return usage(`Unknown ${what} ${word}.${meant ? ` Did you mean ${meant}?` : known}`);
431
452
  }
432
453
  /** The choice a mistyped word most likely meant, or none when nothing is close:
433
454
  * one edit away (a swap of two letters counts as one), or two for a word longer
@@ -654,6 +675,7 @@ function describe(info) {
654
675
  ...(info.stopReason ? [["stop reason", info.stopReason]] : []),
655
676
  ["auto wake", info.autoWake === false ? "off" : "on"],
656
677
  ["runs as", info.user === "root" ? "root" : "sandbox user"],
678
+ ...(info.leaseSeconds ? [["renews", `${info.leaseSeconds} s ahead`]] : []),
657
679
  [
658
680
  "idle pause",
659
681
  info.idlePauseSeconds
@@ -1121,7 +1143,9 @@ export async function run(argv, env = process.env, out = defaultOut(argv)) {
1121
1143
  : [
1122
1144
  `Your plan: ${current.name} (${current.planId}), ${current.status.replace("_", " ")}, ${current.interval === "year" ? "yearly" : "monthly"}.`,
1123
1145
  current.status === "trialing" && current.trialEndsAt
1124
- ? `The trial ends on ${day(current.trialEndsAt)}.`
1146
+ ? current.cancelAtPeriodEnd
1147
+ ? `The trial ends on ${day(current.trialEndsAt)}, cancelled: its card is not charged.`
1148
+ : `The trial ends on ${day(current.trialEndsAt)}, when its card is charged the first period; \`${me} plans cancel\` before then charges nothing.`
1125
1149
  : undefined,
1126
1150
  current.cancelAtPeriodEnd
1127
1151
  ? `It ends on ${day(current.periodEnd)}; \`${me} plans resume\` keeps it.`
@@ -2222,6 +2246,7 @@ async function sandbox(argv, env, out) {
2222
2246
  "timeout",
2223
2247
  "on-timeout",
2224
2248
  "user",
2249
+ "lease",
2225
2250
  ]);
2226
2251
  const sbx = await get(args.positional[0]);
2227
2252
  const onOff = (name) => {
@@ -2235,6 +2260,9 @@ async function sandbox(argv, env, out) {
2235
2260
  const onTimeout = flag(args, "on-timeout")
2236
2261
  ? oneOf(args, "on-timeout", ["pause", "stop", "delete"])
2237
2262
  : undefined;
2263
+ const lease = flag(args, "lease");
2264
+ if (lease !== undefined && lease !== "default" && !/^\d+$/.test(lease))
2265
+ throw usage("--lease takes seconds, 300 to 43200, or default.");
2238
2266
  const cost = flag(args, "max-total-cost");
2239
2267
  if (cost !== undefined && cost !== "none" && !/^\d+(\.\d{1,6})?$/.test(cost))
2240
2268
  throw usage("--max-total-cost takes dollars, such as 25 or 2.50, or none.");
@@ -2252,6 +2280,9 @@ async function sandbox(argv, env, out) {
2252
2280
  ...(onOff("auto-wake") === undefined ? {} : { autoWake: onOff("auto-wake") }),
2253
2281
  ...(onOff("persistent") === undefined ? {} : { persistent: onOff("persistent") }),
2254
2282
  ...(flag(args, "user") ? { user: oneOf(args, "user", ["sandbox", "root"]) } : {}),
2283
+ ...(lease === undefined
2284
+ ? {}
2285
+ : { leaseSeconds: lease === "default" ? null : Number(lease) }),
2255
2286
  ...(cost === undefined
2256
2287
  ? {}
2257
2288
  : {
@@ -2263,7 +2294,7 @@ async function sandbox(argv, env, out) {
2263
2294
  ...(onTimeout === undefined ? {} : { onTimeout }),
2264
2295
  };
2265
2296
  if (!Object.keys(settings).length)
2266
- throw usage("Say what to change: --name, --label, --env, --unset-env, --idle-pause, --auto-wake, --persistent, --user, --max-total-cost, --timeout or --on-timeout.");
2297
+ throw usage("Say what to change: --name, --label, --env, --unset-env, --idle-pause, --auto-wake, --persistent, --user, --lease, --max-total-cost, --timeout or --on-timeout.");
2267
2298
  await sbx.update(settings);
2268
2299
  print(describe(sbx.info), sbx.info);
2269
2300
  return 0;
@@ -2583,9 +2614,6 @@ function attachment(spec) {
2583
2614
  throw usage("--volume takes <volumeId>:/path, or <volumeId>:/path:snapshot for a copy.");
2584
2615
  return { volumeId, path, mode };
2585
2616
  }
2586
- /** A secret's value, from standard input only, so it never sits in shell
2587
- * history or a process list. Piped: everything, less one trailing newline.
2588
- * A terminal: one line, not shown. */
2589
2617
  /** A pasted secret as the header it becomes: no line breaks (a token copied
2590
2618
  * from a terminal arrives wrapped), no bracketed-paste markers, no space at
2591
2619
  * either end. 13 October 2026: a user's pasted Claude token was refused as
@@ -2597,22 +2625,42 @@ export function cleanSecret(raw) {
2597
2625
  .replace(/[\r\n]/g, "")
2598
2626
  .trim();
2599
2627
  }
2600
- async function readSecret() {
2628
+ /** A secret's value, from standard input only, so it never sits in shell
2629
+ * history or a process list. Piped: everything, cleaned as a header's
2630
+ * (`cleanSecret`). A terminal: one line, not shown. `verbatim`, for a real
2631
+ * value the machines get themselves (a PEM key, a JSON file): piped, every
2632
+ * byte as it is; a terminal, every line until Ctrl-D, less the Enter typed
2633
+ * before it. */
2634
+ async function readSecret(verbatim = false) {
2601
2635
  const stdin = process.stdin;
2602
2636
  if (!stdin.isTTY) {
2603
2637
  const chunks = [];
2604
2638
  for await (const chunk of stdin)
2605
2639
  chunks.push(chunk);
2606
- return cleanSecret(Buffer.concat(chunks).toString("utf8"));
2640
+ const text = Buffer.concat(chunks).toString("utf8");
2641
+ return verbatim ? text : cleanSecret(text);
2607
2642
  }
2608
- process.stderr.write("Value (not shown), then Enter: ");
2643
+ process.stderr.write(verbatim
2644
+ ? "Value (not shown; several lines are fine), then Ctrl-D: "
2645
+ : "Value (not shown), then Enter: ");
2609
2646
  stdin.setRawMode(true);
2610
2647
  stdin.resume();
2648
+ // A character split across two reads is joined, not garbled.
2649
+ const decoder = new TextDecoder();
2611
2650
  try {
2612
2651
  return await new Promise((done, fail) => {
2613
2652
  let value = "";
2614
2653
  const onData = (chunk) => {
2615
- for (const char of chunk.toString("utf8")) {
2654
+ for (const char of decoder.decode(chunk, { stream: true })) {
2655
+ if (verbatim && char === "\u0004") {
2656
+ stdin.off("data", onData);
2657
+ process.stderr.write("\n");
2658
+ return done(value.replaceAll("\u001b[200~", "").replaceAll("\u001b[201~", "").replace(/\n$/, ""));
2659
+ }
2660
+ if (verbatim && (char === "\r" || char === "\n")) {
2661
+ value += "\n";
2662
+ continue;
2663
+ }
2616
2664
  if (char === "\r" || char === "\n") {
2617
2665
  stdin.off("data", onData);
2618
2666
  process.stderr.write("\n");
@@ -2713,10 +2761,11 @@ const ruleText = (rules) => rules?.length
2713
2761
  .join("; ")
2714
2762
  : "-";
2715
2763
  export async function secretsCommand(argv, env, out,
2716
- /** Tests give the value here; the CLI reads standard input. */
2764
+ /** Tests give the value here; the CLI reads standard input, `verbatim`
2765
+ * for a real value (--exposed), cleaned as a header's otherwise. */
2717
2766
  read = readSecret) {
2718
2767
  const [verb, ...rest] = argv;
2719
- const args = parse(rest, ["jobs", "all-sandboxes", "keep-value", "all", "none"], [
2768
+ const args = parse(rest, ["jobs", "all-sandboxes", "keep-value", "all", "none", "exposed"], [
2720
2769
  "host",
2721
2770
  "header",
2722
2771
  "format",
@@ -2730,18 +2779,33 @@ read = readSecret) {
2730
2779
  "env",
2731
2780
  "limit",
2732
2781
  "after",
2782
+ "expected-version",
2783
+ "from-file",
2733
2784
  ]);
2734
2785
  const print = (human, value) => out.write(out.json ? JSON.stringify(value) : human);
2786
+ const kind = (secret) => (secret.exposed ? "real value" : "added on the way out");
2735
2787
  const rows = (list) => list.length
2736
2788
  ? table([
2737
- ["name", "hosts", "header", "placeholder", "allow", "sandboxes", "jobs"],
2789
+ [
2790
+ "name",
2791
+ "hosts",
2792
+ "header",
2793
+ "placeholder",
2794
+ "allow",
2795
+ "sandboxes",
2796
+ "kind",
2797
+ "version",
2798
+ "jobs",
2799
+ ],
2738
2800
  ...list.map(({ name, sandboxes: secret, jobs }) => [
2739
2801
  secret?.env ? `${name} (as ${secret.env})` : name,
2740
- secret ? secret.hosts.join(",") : "-",
2802
+ secret?.hosts.length ? secret.hosts.join(",") : "-",
2741
2803
  secret?.header ? `${secret.header}: ${secret.format ?? "{value}"}` : "-",
2742
2804
  secret ? secret.placeholder : "-",
2743
2805
  secret ? ruleText(secret.rules) : "-",
2744
2806
  secret ? scopeText(secret.only) : "-",
2807
+ secret ? kind(secret) : "-",
2808
+ secret?.version ? `v${secret.version}` : "-",
2745
2809
  jobs ? `v${jobs.version}` : "-",
2746
2810
  ]),
2747
2811
  ])
@@ -2762,16 +2826,26 @@ read = readSecret) {
2762
2826
  print(more ? `${rows(all)}\nMore: ${me} secrets ls --limit ${limit} --after ${more}` : rows(all), all.flatMap((s) => (s.sandboxes ? [s.sandboxes] : [])));
2763
2827
  return 0;
2764
2828
  }
2765
- const jobsOnly = "Only a secret's copy for jobs has versions and can be read back";
2829
+ const jobsOnly = "Only a secret's copy for jobs can be read back";
2766
2830
  if (verb === "get") {
2767
2831
  const found = await (await client(env)).secrets.get(need(args.positional[0], "the secret's name"));
2768
- print(rows([found]), found);
2832
+ const secret = found.sandboxes;
2833
+ const lines = [["name", found.name]];
2834
+ if (secret)
2835
+ lines.push(["kind", kind(secret)], ["version", secret.version ? String(secret.version) : "-"], ["variable", secret.env ?? secret.name], ["hosts", secret.hosts.length ? secret.hosts.join(", ") : "-"], ...(secret.header ? [["header", `${secret.header}: ${secret.format ?? "{value}"}`]] : []), ...(secret.rules?.length ? [["allow", ruleText(secret.rules)]] : []), ["sandboxes", scopeText(secret.only)], ["placeholder", secret.placeholder], ["size", `${secret.valueBytes} bytes`], ["updated", secret.updatedAt]);
2836
+ else
2837
+ lines.push(["sandboxes", "none: a copy for jobs only"]);
2838
+ lines.push(["jobs", found.jobs ? `v${found.jobs.version}` : "-"]);
2839
+ print(table(lines), found);
2769
2840
  return 0;
2770
2841
  }
2771
2842
  if (verb === "set" || verb === "rotate") {
2772
2843
  const name = need(args.positional[0], "the secret's name, such as OPENAI_API_KEY");
2773
2844
  const hosts = args.flags.get("host") ?? [];
2774
2845
  const jobs = verb === "rotate" || has(args, "jobs");
2846
+ const exposed = has(args, "exposed");
2847
+ const expectedVersion = integer(args, "expected-version");
2848
+ const fromFile = flag(args, "from-file");
2775
2849
  if (verb === "rotate" &&
2776
2850
  (hosts.length ||
2777
2851
  args.flags.has("header") ||
@@ -2780,12 +2854,17 @@ read = readSecret) {
2780
2854
  args.flags.has("only-sandbox") ||
2781
2855
  args.flags.has("only-app") ||
2782
2856
  args.flags.has("all-sandboxes") ||
2783
- args.flags.has("env")))
2784
- throw usage(`rotate replaces the copy for jobs. ${jobsOnly}; to change the sandboxes' copy, set it again with --host.`);
2857
+ args.flags.has("env") ||
2858
+ args.flags.has("exposed") ||
2859
+ args.flags.has("expected-version")))
2860
+ throw usage(`rotate replaces the copy for jobs. ${jobsOnly}; to change the sandboxes' copy, set it again with --host or --exposed.`);
2785
2861
  if (verb === "set" && has(args, "keep-value")) {
2786
2862
  // Narrowing needs no value: it only takes places away (secrets.narrow).
2787
2863
  if (jobs ||
2788
2864
  args.flags.has("value") ||
2865
+ args.flags.has("from-file") ||
2866
+ args.flags.has("exposed") ||
2867
+ args.flags.has("expected-version") ||
2789
2868
  args.flags.has("header") ||
2790
2869
  args.flags.has("format") ||
2791
2870
  args.flags.has("only-label") ||
@@ -2809,14 +2888,67 @@ read = readSecret) {
2809
2888
  ].join("\n"), saved);
2810
2889
  return 0;
2811
2890
  }
2812
- if (!hosts.length && !jobs)
2813
- throw usage("Give --host once for each host the value may go to, such as --host api.openai.com, and/or --jobs to let scheduled jobs use it.");
2891
+ if (exposed) {
2892
+ // A real value goes to the machines as it is: nothing the proxy does
2893
+ // with a value applies to it (the API refuses each too).
2894
+ const proxyOnly = ["host", "header", "format", "allow"].filter((f) => args.flags.has(f));
2895
+ if (proxyOnly.length)
2896
+ throw usage(`A real value (--exposed) is given to the machines as it is, so it takes none of ${proxyOnly.map((f) => `--${f}`).join(", ")}: they are for a secret added to HTTPS requests on the way out.`);
2897
+ if (jobs)
2898
+ throw usage("--exposed and --jobs are two separate copies, each with its own version: store them with two commands.");
2899
+ // Code in a machine can read a real value, so it goes only to the
2900
+ // sandboxes and Apps named by id (the API refuses the rest too). A
2901
+ // replacement may name none: it keeps the scope it has.
2902
+ if (args.flags.has("only-label") || args.flags.has("all-sandboxes"))
2903
+ throw usage("A real value (--exposed) goes only to the sandboxes and Apps you name by id, with --only-sandbox and --only-app: code in them can read it, so never to every sandbox (--all-sandboxes) or by label (--only-label).");
2904
+ }
2905
+ if (!hosts.length && !jobs && !exposed)
2906
+ throw usage("Give --host once for each host the value may go to, such as --host api.openai.com; or --exposed to give the machines the value itself (a database password, an SSH key); and/or --jobs to let scheduled jobs use it.");
2907
+ if (expectedVersion !== undefined && !hosts.length && !exposed)
2908
+ throw usage(`--expected-version is the version of the sandboxes' copy (\`${me} secrets get NAME\` shows it), and this stores only the copy for jobs.`);
2814
2909
  if (args.flags.has("value"))
2815
- throw usage('The value is read from standard input, never an argument: printf %s "$KEY" | runtime secrets set NAME --host ...');
2816
- const value = await read();
2910
+ throw usage('The value is read from standard input or --from-file, never an argument: printf %s "$KEY" | runtime secrets set NAME --host ...');
2911
+ const header = flag(args, "header");
2912
+ const format = flag(args, "format");
2913
+ const variable = flag(args, "env");
2914
+ const allow = args.flags.get("allow");
2915
+ const rules = allow ? parseSecretRules(allow) : undefined;
2916
+ const only = parseSecretScope(args.flags.get("only-label"), args.flags.get("only-sandbox"), has(args, "all-sandboxes"), args.flags.get("only-app"));
2917
+ // A real value is kept byte for byte (a PEM key's lines, a JSON file);
2918
+ // any other is cleaned as the header it becomes.
2919
+ let value;
2920
+ if (fromFile !== undefined) {
2921
+ const text = await readFile(fromFile, "utf8").catch((error) => {
2922
+ throw usage(`--from-file could not read ${fromFile}: ${error.code ?? error.message}.`);
2923
+ });
2924
+ value = exposed ? text : cleanSecret(text);
2925
+ }
2926
+ else
2927
+ value = await read(exposed);
2817
2928
  if (!value)
2818
- throw usage('The value is empty. Pipe it in: printf %s "$KEY" | runtime secrets set NAME --host ...; or, to narrow its hosts and rules without it, add --keep-value.');
2929
+ throw usage(exposed
2930
+ ? "The value is empty. Pipe it in, or name a file: runtime secrets set NAME --exposed --from-file key.pem"
2931
+ : 'The value is empty. Pipe it in: printf %s "$KEY" | runtime secrets set NAME --host ...; or, to narrow its hosts and rules without it, add --keep-value.');
2819
2932
  const runtime = await client(env);
2933
+ if (exposed) {
2934
+ const saved = await runtime.secrets.set(name, {
2935
+ value,
2936
+ exposed: true,
2937
+ ...(only ? { only } : {}),
2938
+ ...(variable ? { env: variable } : {}),
2939
+ ...(expectedVersion !== undefined ? { expectedVersion } : {}),
2940
+ });
2941
+ const variableName = saved.env ?? saved.name;
2942
+ print([
2943
+ `Stored ${saved.name}, version ${saved.version}. Only these get its value in ${variableName}: ${scopeText(saved.only)}.`,
2944
+ `In a command's environment, ${saved.placeholder} becomes the value too, so DATABASE_URL=postgres://app:${saved.placeholder}@db/app works.`,
2945
+ "Code in the sandbox can read the value and send it anywhere, and it is in the sandbox's memory, so in its snapshots and forks.",
2946
+ ...(saved.enforced
2947
+ ? []
2948
+ : ["A host is catching up; running sandboxes have it within a minute."]),
2949
+ ].join("\n"), saved);
2950
+ return 0;
2951
+ }
2820
2952
  if (verb === "rotate") {
2821
2953
  const rotated = await runtime.secrets.rotate(name, value);
2822
2954
  print(`Rotated ${name} for jobs to version ${rotated.version}. Runs bound to the old version are refused it.`, rotated);
@@ -2824,17 +2956,11 @@ read = readSecret) {
2824
2956
  }
2825
2957
  if (!hosts.length) {
2826
2958
  if (args.flags.has("env"))
2827
- throw usage("--env names the variable sandboxes see the secret in, so it needs --host; a job names its variable on jobs create (--secret NAME=VAR).");
2959
+ throw usage("--env names the variable sandboxes see the secret in, so it needs --host or --exposed; a job names its variable on jobs create (--secret NAME=VAR).");
2828
2960
  const saved = await runtime.secrets.set(name, { value, jobs: true });
2829
2961
  print(`Stored ${name} for jobs, version ${saved.jobs.version}. Bind it: ${me} jobs create ... --secret ${name}`, saved);
2830
2962
  return 0;
2831
2963
  }
2832
- const header = flag(args, "header");
2833
- const format = flag(args, "format");
2834
- const variable = flag(args, "env");
2835
- const allow = args.flags.get("allow");
2836
- const rules = allow ? parseSecretRules(allow) : undefined;
2837
- const only = parseSecretScope(args.flags.get("only-label"), args.flags.get("only-sandbox"), has(args, "all-sandboxes"), args.flags.get("only-app"));
2838
2964
  const saved = await runtime.secrets.set(name, {
2839
2965
  value,
2840
2966
  hosts,
@@ -2843,6 +2969,7 @@ read = readSecret) {
2843
2969
  ...(rules ? { rules } : {}),
2844
2970
  ...(only ? { only } : {}),
2845
2971
  ...(variable ? { env: variable } : {}),
2972
+ ...(expectedVersion !== undefined ? { expectedVersion } : {}),
2846
2973
  ...(jobs ? { jobs: true } : {}),
2847
2974
  });
2848
2975
  const sees = `${saved.env ?? saved.name}=${saved.placeholder}`;
@@ -4729,6 +4856,7 @@ const CREATE_VALUES = [
4729
4856
  "volume",
4730
4857
  "env",
4731
4858
  "user",
4859
+ "lease",
4732
4860
  ];
4733
4861
  /** Dollars from the command line as integer microdollars: 25, 2.50 or 0.000001. */
4734
4862
  function usdMicros(args, name) {
@@ -4826,6 +4954,7 @@ function createInput(args, env) {
4826
4954
  : {}),
4827
4955
  ...(has(args, "no-auto-wake") ? { autoWake: false } : {}),
4828
4956
  ...(flag(args, "user") ? { user: oneOf(args, "user", ["sandbox", "root"]) } : {}),
4957
+ ...(integer(args, "lease") !== undefined ? { leaseSeconds: integer(args, "lease") } : {}),
4829
4958
  ...(has(args, "persistent") ? { persistent: true } : {}),
4830
4959
  ...(has(args, "get-or-create") ? { getOrCreate: true } : {}),
4831
4960
  ...(has(args, "trial")
@@ -4984,9 +5113,15 @@ if (import.meta.main ||
4984
5113
  const out = defaultOut(argv);
4985
5114
  run(argv, process.env, out).then((code) => {
4986
5115
  process.exitCode = code;
4987
- }, (error) => {
5116
+ }, async (error) => {
4988
5117
  out.error(describeError(error, out.json));
4989
5118
  process.exitCode = 1;
5119
+ // A refused option or command may be one a newer CLI has.
5120
+ if (!out.json && error instanceof RuntimeError && error.code === "usage") {
5121
+ const line = await outdatedLine({ env: process.env });
5122
+ if (line)
5123
+ out.error(line);
5124
+ }
4990
5125
  });
4991
5126
  }
4992
5127
  // ------------------------------------------------------------------ observability
@@ -5004,6 +5139,16 @@ function spark(values) {
5004
5139
  return out.join("");
5005
5140
  }
5006
5141
  const mib = (bytes) => `${Math.round(bytes / 1_048_576).toLocaleString("en-US")} MiB`;
5142
+ /** A rate's bytes in the largest unit under 1,024 of it: B, KiB, MiB, GiB. */
5143
+ const bytes = (value) => {
5144
+ const units = ["B", "KiB", "MiB", "GiB"];
5145
+ let at = 0;
5146
+ while (value >= 1024 && at < units.length - 1) {
5147
+ value /= 1024;
5148
+ at++;
5149
+ }
5150
+ return `${at === 0 ? Math.round(value) : value.toFixed(value < 10 ? 1 : 0)} ${units[at]}`;
5151
+ };
5007
5152
  function metricsText(m) {
5008
5153
  const waiting = (value) => value == null ? "not measured" : `${value}%`;
5009
5154
  const waitingHistory = (field) => m.points.some((point) => point[field] != null)
@@ -5018,6 +5163,11 @@ function metricsText(m) {
5018
5163
  const latest = m.state === "running" ? m.latest : null;
5019
5164
  const still = m.state === "running" ? null : `none: it is ${m.state}`;
5020
5165
  const cpuNow = newestCpu(m);
5166
+ const perSecond = (value) => value == null ? "not measured" : `${bytes(value)}/s`;
5167
+ const ioHistory = (field) => m.points.some((point) => point[field] != null)
5168
+ ? spark(m.points.map((point) => point[field] ?? null))
5169
+ : "not measured";
5170
+ const used = latest?.diskUsedBytes;
5021
5171
  return [
5022
5172
  table([
5023
5173
  ["state", m.state],
@@ -5034,6 +5184,20 @@ function metricsText(m) {
5034
5184
  ],
5035
5185
  ["cpu wait now", still ?? waiting(latest?.cpuWaitPercent)],
5036
5186
  ["memory stalls now", still ?? waiting(latest?.memoryStallPercent)],
5187
+ [
5188
+ "disk now",
5189
+ still ?? (used == null ? "not measured" : `${mib(used)} of ${mib(m.diskLimitBytes)} used`),
5190
+ ],
5191
+ [
5192
+ "disk i/o now",
5193
+ still ??
5194
+ `read ${perSecond(latest?.diskReadBytesPerSecond)}, write ${perSecond(latest?.diskWriteBytesPerSecond)}`,
5195
+ ],
5196
+ [
5197
+ "network now",
5198
+ still ??
5199
+ `in ${perSecond(latest?.networkReceivedBytesPerSecond)}, out ${perSecond(latest?.networkSentBytesPerSecond)}`,
5200
+ ],
5037
5201
  [`cpu, ${m.range}`, m.points.length ? `${spark(cpu)} peak ${peak}%` : "no readings"],
5038
5202
  [`cpu wait, ${m.range}`, waitingHistory("cpuWaitPercent")],
5039
5203
  [`memory stalls, ${m.range}`, waitingHistory("memoryStallPercent")],
@@ -5043,6 +5207,10 @@ function metricsText(m) {
5043
5207
  ? `${spark(memory)} peak ${mib(Math.max(...m.points.map((p) => p.memoryPeakBytes)))}`
5044
5208
  : "no readings",
5045
5209
  ],
5210
+ [`disk read, ${m.range}`, ioHistory("diskReadBytesPerSecond")],
5211
+ [`disk write, ${m.range}`, ioHistory("diskWriteBytesPerSecond")],
5212
+ [`network in, ${m.range}`, ioHistory("networkReceivedBytesPerSecond")],
5213
+ [`network out, ${m.range}`, ioHistory("networkSentBytesPerSecond")],
5046
5214
  ]),
5047
5215
  ].join("\n");
5048
5216
  }
@@ -5169,17 +5337,25 @@ async function otelCommand(argv, env, out) {
5169
5337
  const signals = () => flag(args, "signals")
5170
5338
  ?.split(",")
5171
5339
  .map((s) => s.trim());
5172
- const row = (x) => [
5173
- x.id,
5174
- x.endpoint,
5175
- x.enabled ? "on" : "off",
5176
- x.signals.join(","),
5177
- x.lastError
5178
- ? `last error: ${x.lastError}`
5179
- : x.lastSuccessAt
5180
- ? `sent ${x.lastSuccessAt}`
5181
- : "not sent yet",
5182
- ];
5340
+ const row = (x) => {
5341
+ // Logs and metrics, and traces, each keep their own health: one failing
5342
+ // is shown whatever the other does.
5343
+ const errors = [
5344
+ x.lastError && `last error: ${x.lastError}`,
5345
+ x.tracesLastError && `last traces error: ${x.tracesLastError}`,
5346
+ ].filter(Boolean);
5347
+ const sent = [x.lastSuccessAt, x.tracesLastSuccessAt ?? null]
5348
+ .filter((at) => at !== null)
5349
+ .sort()
5350
+ .at(-1);
5351
+ return [
5352
+ x.id,
5353
+ x.endpoint,
5354
+ x.enabled ? "on" : "off",
5355
+ x.signals.join(","),
5356
+ errors.length ? errors.join("; ") : sent ? `sent ${sent}` : "not sent yet",
5357
+ ];
5358
+ };
5183
5359
  switch (verb) {
5184
5360
  case "ls":
5185
5361
  case "list": {
@@ -456,7 +456,7 @@ function refuseCreate(params) {
456
456
  [
457
457
  "otelEndpointOverride",
458
458
  "Sending sandbox telemetry elsewhere (otelEndpointOverride)",
459
- "Remove it: runtime.otel.create() exports every sandbox's events and CPU and memory metrics over OTLP/HTTP.",
459
+ "Remove it: runtime.otel.create() exports the account's events, every sandbox's CPU, memory, disk and network metrics and, with the traces signal, a span for every API call over OTLP/HTTP.",
460
460
  ],
461
461
  ];
462
462
  for (const [field, feature, alternative] of refusals)
@@ -201,10 +201,11 @@ export declare class Sandbox {
201
201
  getPublicHost(port: number): Promise<string>;
202
202
  get git(): never;
203
203
  /** E2B's metrics, from Runtime's measured readings (`sbx.metrics()`): CPU
204
- * as a percent of the sandbox's vCPUs and resident memory, one entry per
205
- * host reading (every minute by default) between `start` and `end`, kept
206
- * 24 hours at that resolution. Disk use inside the sandbox is not measured:
207
- * `diskUsed` is null and `diskTotal` is the disk's size. */
204
+ * as a percent of the sandbox's vCPUs, resident memory and the bytes used
205
+ * on the root file system (`df /`), one entry per bucket between `start`
206
+ * and `end` (10 s buckets over the last 15 minutes, of readings every
207
+ * 30 s), kept 24 hours at that resolution. `diskTotal` is the disk's size;
208
+ * `diskUsed` is null only for a reading the sandbox did not answer. */
208
209
  getMetrics(opts?: MetricsOpts): Promise<E2BSandboxMetrics[]>;
209
210
  static getMetrics(sandboxId: string, opts?: MetricsOpts & SandboxApiOpts): Promise<E2BSandboxMetrics[]>;
210
211
  updateNetwork(): Promise<never>;
@@ -240,7 +241,7 @@ export type E2BSandboxMetrics = {
240
241
  cpuCount: number;
241
242
  memUsed: number;
242
243
  memTotal: number;
243
- /** Not measured by Runtime: null. */
244
+ /** Bytes used on the root file system; null where a reading carries none. */
244
245
  diskUsed: number | null;
245
246
  diskTotal: number;
246
247
  };
@@ -567,10 +567,11 @@ export class Sandbox {
567
567
  throw new NotSupportedError("E2B's git module (deprecated by E2B too)", "Run git with sandbox.commands.run('git ...'); git is installed.");
568
568
  }
569
569
  /** E2B's metrics, from Runtime's measured readings (`sbx.metrics()`): CPU
570
- * as a percent of the sandbox's vCPUs and resident memory, one entry per
571
- * host reading (every minute by default) between `start` and `end`, kept
572
- * 24 hours at that resolution. Disk use inside the sandbox is not measured:
573
- * `diskUsed` is null and `diskTotal` is the disk's size. */
570
+ * as a percent of the sandbox's vCPUs, resident memory and the bytes used
571
+ * on the root file system (`df /`), one entry per bucket between `start`
572
+ * and `end` (10 s buckets over the last 15 minutes, of readings every
573
+ * 30 s), kept 24 hours at that resolution. `diskTotal` is the disk's size;
574
+ * `diskUsed` is null only for a reading the sandbox did not answer. */
574
575
  async getMetrics(opts = {}) {
575
576
  return e2bMetrics(this.#runtime, opts);
576
577
  }
@@ -774,7 +775,7 @@ async function e2bMetrics(runtime, opts) {
774
775
  cpuCount: metrics.vcpu,
775
776
  memUsed: point.memoryBytes,
776
777
  memTotal: metrics.memoryLimitBytes,
777
- diskUsed: null,
778
+ diskUsed: point.diskUsedBytes ?? null,
778
779
  diskTotal: metrics.diskLimitBytes,
779
780
  }));
780
781
  }
package/dist/errors.d.ts CHANGED
@@ -3,8 +3,9 @@
3
3
  * (runtime.feedback.submit, `runtime feedback`, or support). */
4
4
  /** A product switched off on this deployment, or paused on purpose: the API
5
5
  * answers these with 501 (503 from an older server) in fixed words, and
6
- * retrying cannot change them. host_unavailable and busy pass, and are
7
- * retried. The API also says so itself (`retryable: false`); this set is for
6
+ * retrying cannot change them. host_unavailable, busy and secret_withheld (a
7
+ * host that cannot give a machine its real-value secret right now) pass, and
8
+ * are retried. The API also says so itself (`retryable: false`); this set is for
8
9
  * a server too old to. */
9
10
  export declare const DELIBERATE: ReadonlySet<string>;
10
11
  /** Refusals that guarantee nothing ran: a sandbox running as many commands
package/dist/errors.js CHANGED
@@ -3,8 +3,9 @@
3
3
  * (runtime.feedback.submit, `runtime feedback`, or support). */
4
4
  /** A product switched off on this deployment, or paused on purpose: the API
5
5
  * answers these with 501 (503 from an older server) in fixed words, and
6
- * retrying cannot change them. host_unavailable and busy pass, and are
7
- * retried. The API also says so itself (`retryable: false`); this set is for
6
+ * retrying cannot change them. host_unavailable, busy and secret_withheld (a
7
+ * host that cannot give a machine its real-value secret right now) pass, and
8
+ * are retried. The API also says so itself (`retryable: false`); this set is for
8
9
  * a server too old to. */
9
10
  export const DELIBERATE = new Set([
10
11
  "unavailable",