withruntime 0.37.0 → 0.46.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.
@@ -62,6 +62,61 @@ export type BrowserScreenshotResult = {
62
62
  /** The image. */
63
63
  base64: string;
64
64
  };
65
+ /** A task in plain words, done by an agent that browses (POST /v1/browsers/runs). */
66
+ export type BrowserRunInput = {
67
+ /** What to do, in plain words; at most 16 KiB. */
68
+ task: string;
69
+ /** Opened before the agent's first step. */
70
+ startUrl?: string;
71
+ /** A claude-, gpt-, o1, o3, o4 or gemini- model; the server defaults to
72
+ * claude-sonnet-5-5. Its key is your egress secret ANTHROPIC_API_KEY,
73
+ * OPENAI_API_KEY or GEMINI_API_KEY. */
74
+ model?: string;
75
+ /** 1 to 200; the server defaults to 30. */
76
+ maxSteps?: number;
77
+ /** Only these domains are opened (example.com, *.example.com). */
78
+ allowedDomains?: string[];
79
+ labels?: Record<string, string>;
80
+ };
81
+ export type BrowserRunState = "queued" | "running" | "done" | "failed" | "stopped";
82
+ export type BrowserRun = {
83
+ id: string;
84
+ state: BrowserRunState;
85
+ task: string | null;
86
+ model: string | null;
87
+ startUrl: string | null;
88
+ /** The agent's answer, once done. */
89
+ output: string | null;
90
+ /** Why it failed, and what to do. */
91
+ error: string | null;
92
+ steps: number;
93
+ /** The page the browser ended on. */
94
+ url: string | null;
95
+ sandboxId: string | null;
96
+ labels: Record<string, string>;
97
+ createdAt: string;
98
+ startedAt: string | null;
99
+ endedAt: string | null;
100
+ };
101
+ /** One step of a run: the page the agent saw and what it did. */
102
+ export type BrowserRunStep = {
103
+ /** 0 is the page before the first step; the last is the page at the end. */
104
+ n: number;
105
+ url: string | null;
106
+ title: string | null;
107
+ goal: string | null;
108
+ actions: unknown[];
109
+ /** The page as a JPEG, base64; null when asked without frames. */
110
+ frame: string | null;
111
+ at: string;
112
+ /** Its place in the run's log: pass as `after`. */
113
+ seq: number;
114
+ };
115
+ export type BrowserRunSteps = {
116
+ data: BrowserRunStep[];
117
+ after: number;
118
+ ended: boolean;
119
+ };
65
120
  export type BrowserConnectOptions = {
66
121
  playwright: [endpointURL: string, options: {
67
122
  headers: Record<string, string>;
@@ -94,4 +149,36 @@ export declare function browsers(t: Transport): {
94
149
  screenshot(id: string, input?: BrowserScreenshot, options?: RequestOptions): Promise<BrowserScreenshotResult>;
95
150
  /** End a browser by id; pass RequestOptions to bound or deduplicate the request. */
96
151
  delete: (id: string, options?: RequestOptions) => Promise<void>;
152
+ /** Do a task in a browser, described in plain words, and wait for its
153
+ * end: `output` once done, `error` once failed. A string is the task.
154
+ * Its steps, each with the page it saw, are `runs.steps(run.id)`. */
155
+ run(input: string | BrowserRunInput, options?: RequestOptions): Promise<BrowserRun>;
156
+ runs: {
157
+ /** Start a run and return it at once (state queued). */
158
+ create: (input: BrowserRunInput, options?: RequestOptions) => Promise<BrowserRun>;
159
+ get: (id: string, options?: RequestOptions) => Promise<BrowserRun>;
160
+ list: (query?: {
161
+ cursor?: string;
162
+ limit?: number;
163
+ }, options?: RequestOptions) => Promise<Page<BrowserRun>>;
164
+ /** One page of a run's steps; `wait` (seconds, up to 30) waits for one. */
165
+ steps: (id: string, query?: {
166
+ after?: number;
167
+ limit?: number;
168
+ frames?: boolean;
169
+ wait?: number;
170
+ }, options?: RequestOptions) => Promise<BrowserRunSteps>;
171
+ /** Every step, as it comes, until the run ends: its recording. */
172
+ follow: (id: string, options?: {
173
+ after?: number;
174
+ frames?: boolean;
175
+ signal?: AbortSignal;
176
+ }) => AsyncGenerator<BrowserRunStep>;
177
+ /** Stop a run; its sandbox is deleted and its steps are kept. */
178
+ stop: (id: string, options?: RequestOptions) => Promise<BrowserRun>;
179
+ /** Until the run has ended; answers it then. */
180
+ wait(id: string, options?: {
181
+ signal?: AbortSignal;
182
+ }): Promise<BrowserRun>;
183
+ };
97
184
  };
@@ -9,8 +9,10 @@
9
9
  */
10
10
  import { RuntimeError } from "../errors.js";
11
11
  import { Page } from "../page.js";
12
+ const RUN_ENDED = ["done", "failed", "stopped"];
12
13
  /** Browsers follow the shared resource interface: id, name, labels, state. */
13
14
  export function browsers(t) {
15
+ const runs = browserRuns(t);
14
16
  const path = (id) => `/v1/browsers/${encodeURIComponent(id)}`;
15
17
  /** End a browser by id; API errors retain their code and recovery hint. */
16
18
  const remove = async (id, options) => {
@@ -109,5 +111,70 @@ export function browsers(t) {
109
111
  },
110
112
  /** End a browser by id; pass RequestOptions to bound or deduplicate the request. */
111
113
  delete: remove,
114
+ /** Do a task in a browser, described in plain words, and wait for its
115
+ * end: `output` once done, `error` once failed. A string is the task.
116
+ * Its steps, each with the page it saw, are `runs.steps(run.id)`. */
117
+ async run(input, options) {
118
+ const started = await runs.create(typeof input === "string" ? { task: input } : input, options);
119
+ return runs.wait(started.id, options?.signal ? { signal: options.signal } : {});
120
+ },
121
+ runs,
122
+ };
123
+ }
124
+ /** Browser runs: start one, follow its steps, wait for its end. */
125
+ function browserRuns(t) {
126
+ const runPath = (id) => `/v1/browsers/runs/${encodeURIComponent(id)}`;
127
+ const get = (id, options) => t.json({ method: "GET", path: runPath(id), ...options });
128
+ const steps = (id, query = {}, options) => t.json({
129
+ method: "GET",
130
+ path: `${runPath(id)}/steps`,
131
+ query,
132
+ ...options,
133
+ ...(query.wait ? { timeoutMs: 0 } : {}),
134
+ });
135
+ /** Every step after `after`, as each comes, waiting up to 30 seconds a
136
+ * call; ends when the run has ended. */
137
+ async function* follow(id, options = {}) {
138
+ let after = options.after ?? 0;
139
+ for (;;) {
140
+ options.signal?.throwIfAborted();
141
+ const read = await steps(id, { after, wait: 30, ...(options.frames === false ? { frames: false } : {}) }, options.signal ? { signal: options.signal } : {});
142
+ for (const step of read.data)
143
+ yield step;
144
+ after = read.after;
145
+ if (read.ended && read.data.length === 0)
146
+ return;
147
+ }
148
+ }
149
+ const list = async (query = {}, options) => {
150
+ const page = await t.json({
151
+ method: "GET",
152
+ path: "/v1/browsers/runs",
153
+ query,
154
+ ...options,
155
+ });
156
+ return new Page(page.data, page.nextCursor, (cursor) => list({ ...query, cursor }, options));
157
+ };
158
+ const runs = {
159
+ /** Start a run and return it at once (state queued). */
160
+ create: (input, options) => t.json({ method: "POST", path: "/v1/browsers/runs", body: input, ...options }),
161
+ get,
162
+ list,
163
+ /** One page of a run's steps; `wait` (seconds, up to 30) waits for one. */
164
+ steps,
165
+ /** Every step, as it comes, until the run ends: its recording. */
166
+ follow,
167
+ /** Stop a run; its sandbox is deleted and its steps are kept. */
168
+ stop: (id, options) => t.json({ method: "POST", path: `${runPath(id)}:stop`, body: {}, ...options }),
169
+ /** Until the run has ended; answers it then. */
170
+ async wait(id, options = {}) {
171
+ const now = await get(id, options);
172
+ if (RUN_ENDED.includes(now.state))
173
+ return now;
174
+ for await (const _ of follow(id, { frames: false, ...options }))
175
+ ;
176
+ return get(id, options);
177
+ },
112
178
  };
179
+ return runs;
113
180
  }
@@ -27,6 +27,10 @@ export type Build = Resource & {
27
27
  /** The saved server an App deploys, once a build of a repository with a
28
28
  * start command succeeded; null otherwise. */
29
29
  outputSnapshotId: string | null;
30
+ /** The framework detected in the build folder for the commands its
31
+ * repository leaves unset (nextjs, vite, fastapi, django, rails, go,
32
+ * docker, ...); null when none was or every command is set. */
33
+ framework: string | null;
30
34
  };
31
35
  export type CreateBuild = {
32
36
  repositoryId: string;
@@ -51,11 +55,16 @@ export type ConnectRepository = {
51
55
  previews?: boolean;
52
56
  /** The folder the build runs in; the repository's root by default. */
53
57
  rootDirectory?: string;
54
- /** Leave out to choose by the lockfile (bun, pnpm, Yarn or npm). */
58
+ /** Leave out to use the detected framework's install (when startCommand
59
+ * is left out too), or the lockfile's
60
+ * (bun, pnpm, Yarn or npm). */
55
61
  installCommand?: string | null;
62
+ /** Leave out to use the detected framework's build (when startCommand is
63
+ * left out too), or the lockfile's. */
56
64
  buildCommand?: string | null;
57
65
  /** Run after the build with PORT set; the build ends as this server,
58
- * answering healthPath with 200 and saved with its memory. */
66
+ * answering healthPath with 200 and saved with its memory. Leave out to
67
+ * use the detected framework's server (the build's `framework`). */
59
68
  startCommand?: string | null;
60
69
  port?: number;
61
70
  healthPath?: string | null;
@@ -201,6 +201,8 @@ export type CiJobDetail = CiJob & {
201
201
  export type ListCiChecks = {
202
202
  repositoryId?: string;
203
203
  state?: CiCheckState[];
204
+ /** Only checks started by these events: `merge_group` lists GitHub's merge queue's. */
205
+ event?: CiCheck["event"][];
204
206
  branch?: string;
205
207
  /** A full commit SHA. */
206
208
  commit?: string;
@@ -20,6 +20,21 @@ export type MetricPoint = {
20
20
  memoryPeakBytes: number;
21
21
  /** Host readings in the bucket. */
22
22
  samples: number;
23
+ /** Average bytes used on the root file system, as `df /` in the sandbox
24
+ * reports; null where no reading carries it. Older servers omit it. */
25
+ diskUsedBytes?: number | null;
26
+ /** Bytes read from and written to the sandbox's disks per second, as its
27
+ * kernel counts them; null where unmeasured. */
28
+ diskReadBytesPerSecond?: number | null;
29
+ diskWriteBytesPerSecond?: number | null;
30
+ /** Read and write operations completed per second. */
31
+ diskReadOpsPerSecond?: number | null;
32
+ diskWriteOpsPerSecond?: number | null;
33
+ /** Bytes received and sent per second over the network: what came back on
34
+ * the sandbox's connections, and what it sent on them and served through
35
+ * preview links, custom domains and TCP ports. */
36
+ networkReceivedBytesPerSecond?: number | null;
37
+ networkSentBytesPerSecond?: number | null;
23
38
  };
24
39
  export type SandboxMetrics = {
25
40
  sandboxId: string;
@@ -86,7 +101,7 @@ export type OtelExport = {
86
101
  endpoint: string;
87
102
  /** Header names only; values are never shown back. */
88
103
  headerNames: string[];
89
- signals: Array<"logs" | "metrics">;
104
+ signals: OtelSignal[];
90
105
  enabled: boolean;
91
106
  createdAt: string;
92
107
  updatedAt: string;
@@ -96,7 +111,20 @@ export type OtelExport = {
96
111
  failures: number;
97
112
  exportedEvents: number;
98
113
  exportedPoints: number;
114
+ /** Spans that arrived at the endpoint ("traces"). */
115
+ exportedSpans?: number;
116
+ /** The span pushes' own health. `lastAttemptAt`, `lastSuccessAt`,
117
+ * `lastError` and `failures` describe logs and metrics only. */
118
+ tracesLastAttemptAt?: string | null;
119
+ tracesLastSuccessAt?: string | null;
120
+ tracesLastError?: string | null;
121
+ tracesFailures?: number;
99
122
  };
123
+ /** "logs": events as log records. "metrics": CPU, memory, disk and network.
124
+ * "traces": a span for every API call, a child of the caller's span when the
125
+ * call carried a W3C traceparent (the SDK sends the active OpenTelemetry
126
+ * context's). */
127
+ export type OtelSignal = "logs" | "metrics" | "traces";
100
128
  type List<T> = {
101
129
  data: T[];
102
130
  nextCursor: string | null;
@@ -199,14 +227,14 @@ export declare function otel(t: Transport): {
199
227
  endpoint: string;
200
228
  /** For the endpoint's authentication; never shown back. */
201
229
  headers?: Record<string, string>;
202
- signals?: Array<"logs" | "metrics">;
230
+ signals?: OtelSignal[];
203
231
  }, options?: RequestOptions) => Promise<OtelExport>;
204
232
  list: (options?: RequestOptions) => Promise<List<OtelExport>>;
205
233
  get: (id: string, options?: RequestOptions) => Promise<OtelExport>;
206
234
  update: (id: string, patch: {
207
235
  endpoint?: string;
208
236
  headers?: Record<string, string>;
209
- signals?: Array<"logs" | "metrics">;
237
+ signals?: OtelSignal[];
210
238
  enabled?: boolean;
211
239
  }, options?: RequestOptions) => Promise<OtelExport>;
212
240
  /** Push now instead of at the next interval. */
@@ -45,7 +45,8 @@ export type Plan = {
45
45
  yearlyFeeMicros: string | null;
46
46
  /** Usage given on top of the fee each month. */
47
47
  bonusMicros: string;
48
- /** Days of trial, no card; 0 for none. */
48
+ /** Days of trial; 0 for none. A trial saves a card and charges the
49
+ * first period when it ends, unless cancelled before. */
49
50
  trialDays: number;
50
51
  /** The first month on the plan, and the first after an upgrade to it,
51
52
  * holds twice its usage. */
@@ -70,13 +71,14 @@ export type PlanNow = {
70
71
  planId: string;
71
72
  name: string;
72
73
  /** incomplete: the first payment is not through yet. trialing: a trial,
73
- * until trialEndsAt. past_due: a payment failed and is retried. */
74
+ * until trialEndsAt, when the saved card is charged the first period
75
+ * unless cancelAtPeriodEnd. past_due: a payment failed and is retried. */
74
76
  status: "incomplete" | "trialing" | "active" | "past_due" | "canceled";
75
77
  interval: "month" | "year";
76
78
  periodStart: string | null;
77
79
  /** The next fee, or the end of a cancelled plan. */
78
80
  periodEnd: string | null;
79
- /** When a trial ends; null outside one. */
81
+ /** When a trial ends and its first period is charged; null outside one. */
80
82
  trialEndsAt: string | null;
81
83
  /** True once a cancel takes effect at periodEnd. */
82
84
  cancelAtPeriodEnd: boolean;
@@ -83,17 +83,28 @@ export type SecretApiPolicy = {
83
83
  mutations: string[];
84
84
  };
85
85
  };
86
- /** A secret your sandboxes use without seeing it. Every sandbox of your
86
+ /** A secret, of one of two kinds. The placeholder kind (`exposed: false`):
87
+ * your sandboxes use it without seeing it. Every sandbox of your
87
88
  * organization has an environment variable of the secret's name (or `env`)
88
89
  * holding `placeholder`; the egress proxy sets `header` on every HTTPS request to
89
90
  * `hosts`, or, without `header`, replaces the placeholder in a credential
90
91
  * header (Authorization, x-api-key, x-goog-api-key, api-key, xi-api-key,
91
92
  * x-subscription-token, private-token). Never in the URL or another header.
92
- * The value is never returned. */
93
+ * The real-value kind (`exposed: true`): the sandboxes and Apps its `only`
94
+ * names by id get the value itself in the variable, for a database password
95
+ * or an SSH key; it has no hosts. Either way, the value is never returned. */
93
96
  export type Secret = {
94
97
  name: string;
95
- /** The environment variable the placeholder is in, when not `name`. */
98
+ /** The environment variable the placeholder or value is in, when not `name`. */
96
99
  env?: string;
100
+ /** true: the machines it reaches get the value itself in the variable.
101
+ * false: they see `placeholder`, which the proxy swaps on HTTPS to `hosts`. */
102
+ exposed: boolean;
103
+ /** 1 when stored, one more each time the secret changes: its value, who
104
+ * gets it, its hosts, rules or variable. Pass it as `expectedVersion` to
105
+ * write only if no one else has changed it since. */
106
+ version: number;
107
+ /** Empty for a real-value secret. */
97
108
  hosts: string[];
98
109
  header?: string;
99
110
  format?: string;
@@ -103,18 +114,25 @@ export type Secret = {
103
114
  githubApp?: SecretGithubApp;
104
115
  git?: SecretGit;
105
116
  api?: SecretApiPolicy;
117
+ /** What the variable holds. For a real-value secret, the server running a
118
+ * machine replaces it with the value wherever it stands in an environment
119
+ * variable given to that machine (a command's env, a deploy's), so
120
+ * `DATABASE_URL=postgres://app:<placeholder>@db/app` works. */
106
121
  placeholder: string;
107
122
  valueBytes: number;
108
123
  createdAt: string;
109
124
  updatedAt: string;
110
125
  };
111
126
  export type SetSecret = {
112
- /** Visible ASCII and spaces, at most 8 KiB for sandboxes (64 KiB of UTF-8
113
- * for a jobs-only secret). Stored sealed; the sandboxes' copy is never
127
+ /** Visible ASCII and spaces, one line, at most 8 KiB for sandboxes. With
128
+ * `exposed`: any UTF-8 text without NUL of at most 64 KiB, several lines
129
+ * included (a PEM key, a service account's JSON), sent as it is. 64 KiB of
130
+ * UTF-8 for a jobs-only secret. Stored sealed; the sandboxes' copy is never
114
131
  * returned. */
115
132
  value: string;
116
133
  /** Where the value may go: `api.openai.com`, `*.github.com`. 1 to 16.
117
- * Required unless `jobs` is true. */
134
+ * Required unless `exposed` or `jobs` is true; a real-value secret takes
135
+ * none. */
118
136
  hosts?: string[];
119
137
  /** Set this header on every request to the hosts, replacing the sandbox's
120
138
  * own; the value then goes nowhere else. Needed when the API reads its key
@@ -146,6 +164,30 @@ export type SetSecret = {
146
164
  * secret's own name gives the name back. Absent when replacing a secret:
147
165
  * the variable it has stays. */
148
166
  env?: string;
167
+ /** Give the machines the value itself in the variable (`env`, or the
168
+ * secret's name) instead of a placeholder: for a database password, an SSH
169
+ * or signing key, anything that is not an HTTPS header. It then takes no
170
+ * `hosts`, `header`, `format`, `rules`, `githubApp`, `git` or `api`. It
171
+ * needs `only` naming the sandboxes or Apps that get it by id
172
+ * (`only.sandboxes`, `only.apps`), never labels or every sandbox, since code
173
+ * in them can read it; a replacement may leave `only` out to keep the scope
174
+ * it has. Which machines get it changes only with the value: `scope` is
175
+ * refused for it, so store it again. `env` works as for any secret. An
176
+ * organization's real-value secrets
177
+ * hold at most 64 KiB together. The value is still sealed and opened only on
178
+ * the server running the machine, but code in the machine can read it and
179
+ * send it anywhere, and it is in the machine's memory, so in its snapshots,
180
+ * forks and an App's saved server image. Prefer the placeholder kind for
181
+ * HTTPS APIs. Not kept: give it on every write of such a secret. A command
182
+ * in a machine it reaches may fail with 503 `secret_withheld` while the
183
+ * server cannot give the value right now; nothing ran, and the same call
184
+ * a few seconds later may work (`error.retryable`). */
185
+ exposed?: boolean;
186
+ /** Write only if the sandboxes' copy is at this version (0: it must not
187
+ * exist yet). At another, nothing is written and the call fails with 409
188
+ * `version_conflict`, `details.version` the current one. Read it with
189
+ * `get(name)`. */
190
+ expectedVersion?: number;
149
191
  /** Also keep a copy for scheduled jobs, which a job puts into its run's
150
192
  * environment (`jobs.create({ secrets: [...] })`). Unlike the sandboxes'
151
193
  * copy, the jobs copy is yours rather than the account's, versioned, and can
@@ -190,14 +232,20 @@ export declare class SecretPartlyStoredError extends RuntimeError {
190
232
  export declare function secrets(t: Transport): {
191
233
  /** Store or replace a secret. With `hosts`, sandboxes see a placeholder
192
234
  * and the egress proxy puts the value into HTTPS requests to them
193
- * (replacing keeps the placeholder). With `jobs: true`, a copy scheduled
194
- * jobs can put into their environment; setting it again rotates it. Both
195
- * at once store both; if only the first lands, `SecretPartlyStoredError`
196
- * says so and the same call again finishes it. */
235
+ * (replacing keeps the placeholder). With `exposed: true`, no hosts and
236
+ * `only` naming sandboxes or Apps by id, those machines get the value
237
+ * itself. Each new value raises the
238
+ * sandboxes' copy's version; `expectedVersion` writes only over that
239
+ * one. With `jobs: true`, a copy scheduled jobs can put into their
240
+ * environment; setting it again rotates it. Both at once store both; if
241
+ * only the first lands, `SecretPartlyStoredError` says so and the same
242
+ * call again finishes it. */
197
243
  set: {
198
- (name: string, input: SetSecret & {
244
+ (name: string, input: SetSecret & ({
199
245
  hosts: string[];
200
- }, options?: RequestOptions): Promise<Secret & {
246
+ } | {
247
+ exposed: true;
248
+ }), options?: RequestOptions): Promise<Secret & {
201
249
  enforced: boolean;
202
250
  jobs?: JobSecret;
203
251
  }>;
@@ -211,7 +259,9 @@ export declare function secrets(t: Transport): {
211
259
  }>>;
212
260
  };
213
261
  /** Changes which sandboxes get a secret, without its value: `{}` is every
214
- * sandbox of the organization again. */
262
+ * sandbox of the organization again. Refused (400) for a real-value secret
263
+ * (`exposed`), whose machines change only with its value: `set` it again
264
+ * with `value`, `exposed` and `only`. */
215
265
  scope: (name: string, only: SecretScope, options?: RequestOptions) => Promise<Secret & {
216
266
  enforced: boolean;
217
267
  }>;
@@ -231,7 +281,10 @@ export declare function secrets(t: Transport): {
231
281
  list: (query?: ListSecrets & RequestOptions) => Promise<Secret[]>;
232
282
  /** Every secret by name, with where its value may go. */
233
283
  all: (options?: RequestOptions) => Promise<SecretUse[]>;
234
- /** One secret by name, with where its value may go. */
284
+ /** One secret by name, with where its value may go: `sandboxes` (its
285
+ * kind, `version`, variable, hosts and placeholder, from
286
+ * `GET /v1/egress-secrets/{name}`) and `jobs`, each null when it has no
287
+ * such copy. Never the value. */
235
288
  get: (name: string, options?: RequestOptions) => Promise<SecretUse>;
236
289
  /** Replace the jobs copy's value with a new version. Runs already bound to
237
290
  * the old version are refused it. Only the jobs copy has versions; to
@@ -134,15 +134,24 @@ export function secrets(t) {
134
134
  }
135
135
  async function set(name, input, options) {
136
136
  const { jobs, value, ...egress } = input;
137
- if (!egress.hosts?.length && !jobs)
137
+ // The sandboxes' copy: through the proxy to hosts, or the value itself.
138
+ const forSandboxes = !!egress.hosts?.length || egress.exposed === true;
139
+ if (!forSandboxes && !jobs)
138
140
  throw new RuntimeError({
139
- message: "Say where the value may go: hosts for sandboxes, jobs: true for scheduled jobs, or both.",
141
+ message: "Say where the value may go: hosts for sandboxes through the proxy, exposed: true to give the machines the value itself, jobs: true for scheduled jobs.",
140
142
  code: "invalid_request",
141
143
  status: 0,
142
144
  details: { field: "hosts" },
143
145
  });
146
+ if (!forSandboxes && egress.expectedVersion !== undefined)
147
+ throw new RuntimeError({
148
+ message: "expectedVersion is the version of the sandboxes' copy, and this call stores only the jobs copy.",
149
+ code: "invalid_request",
150
+ status: 0,
151
+ details: { field: "expectedVersion" },
152
+ });
144
153
  let sandboxes;
145
- if (egress.hosts?.length)
154
+ if (forSandboxes)
146
155
  sandboxes = await t.json({
147
156
  method: "PUT",
148
157
  path: path(name),
@@ -173,13 +182,19 @@ export function secrets(t) {
173
182
  return {
174
183
  /** Store or replace a secret. With `hosts`, sandboxes see a placeholder
175
184
  * and the egress proxy puts the value into HTTPS requests to them
176
- * (replacing keeps the placeholder). With `jobs: true`, a copy scheduled
177
- * jobs can put into their environment; setting it again rotates it. Both
178
- * at once store both; if only the first lands, `SecretPartlyStoredError`
179
- * says so and the same call again finishes it. */
185
+ * (replacing keeps the placeholder). With `exposed: true`, no hosts and
186
+ * `only` naming sandboxes or Apps by id, those machines get the value
187
+ * itself. Each new value raises the
188
+ * sandboxes' copy's version; `expectedVersion` writes only over that
189
+ * one. With `jobs: true`, a copy scheduled jobs can put into their
190
+ * environment; setting it again rotates it. Both at once store both; if
191
+ * only the first lands, `SecretPartlyStoredError` says so and the same
192
+ * call again finishes it. */
180
193
  set,
181
194
  /** Changes which sandboxes get a secret, without its value: `{}` is every
182
- * sandbox of the organization again. */
195
+ * sandbox of the organization again. Refused (400) for a real-value secret
196
+ * (`exposed`), whose machines change only with its value: `set` it again
197
+ * with `value`, `exposed` and `only`. */
183
198
  scope: (name, only, options) => t.json({
184
199
  method: "PUT",
185
200
  path: `${path(name)}/sandboxes`,
@@ -202,17 +217,31 @@ export function secrets(t) {
202
217
  list,
203
218
  /** Every secret by name, with where its value may go. */
204
219
  all,
205
- /** One secret by name, with where its value may go. */
220
+ /** One secret by name, with where its value may go: `sandboxes` (its
221
+ * kind, `version`, variable, hosts and placeholder, from
222
+ * `GET /v1/egress-secrets/{name}`) and `jobs`, each null when it has no
223
+ * such copy. Never the value. */
206
224
  get: async (name, options) => {
207
- const found = (await all(options)).find((s) => s.name === name);
208
- if (!found)
225
+ const [sandboxes, jobs] = await Promise.all([
226
+ t.json({ method: "GET", path: path(name), ...options }).catch((error) => {
227
+ if (error instanceof NotFoundError)
228
+ return null;
229
+ throw error;
230
+ }),
231
+ liveCopy(name, options).catch((error) => {
232
+ if (unavailable(error))
233
+ return undefined;
234
+ throw error;
235
+ }),
236
+ ]);
237
+ if (!sandboxes && !jobs)
209
238
  throw new NotFoundError({
210
239
  message: `No secret named ${name}.`,
211
240
  code: "not_found",
212
241
  status: 404,
213
242
  hint: "List them with runtime.secrets.all().",
214
243
  });
215
- return found;
244
+ return { name, sandboxes, jobs: jobs ?? null };
216
245
  },
217
246
  /** Replace the jobs copy's value with a new version. Runs already bound to
218
247
  * the old version are refused it. Only the jobs copy has versions; to
@@ -1,5 +1,5 @@
1
1
  import { RuntimeError } from "./errors.js";
2
- export declare const VERSION = "0.37.0";
2
+ export declare const VERSION = "0.46.0";
3
3
  export declare const DEFAULT_BASE_URL = "https://api.withruntime.com";
4
4
  /** Runtime's API as code inside a Runtime sandbox reaches it: the sandbox's
5
5
  * own host sends each request on to DEFAULT_BASE_URL over HTTPS. The API runs
@@ -69,6 +69,7 @@ export type Call = RequestOptions & {
69
69
  * for capacity never spends the caller's own `timeoutMs`. */
70
70
  extendDeadline?: (ms: number) => void;
71
71
  };
72
+ export declare function traceHeaders(): Record<string, string>;
72
73
  /** How long one attempt waits for its answer to start. The API starts every
73
74
  * answer within 120 s: Caddy answers 503 itself past that, and a longer call
74
75
  * gets its 200 at 90 s and then its JSON (runtime-late-answer). An attempt
package/dist/transport.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ConnectionError, DELIBERATE, errorFor, NOTHING_RAN, RuntimeError, WAITS_FOR_ROOM, } from "./errors.js";
2
2
  import { describeRoute, envFetch, openWebSocket, untrustedCertificate } from "./proxy.js";
3
3
  import { warningText } from "./product-renames.js";
4
- export const VERSION = "0.37.0";
4
+ export const VERSION = "0.46.0";
5
5
  export const DEFAULT_BASE_URL = "https://api.withruntime.com";
6
6
  /** Runtime's API as code inside a Runtime sandbox reaches it: the sandbox's
7
7
  * own host sends each request on to DEFAULT_BASE_URL over HTTPS. The API runs
@@ -39,6 +39,36 @@ export function reachable(origin, inSandbox = inRuntimeSandbox) {
39
39
  function processEnv() {
40
40
  return (globalThis.process?.env ?? {});
41
41
  }
42
+ /** The W3C trace context of the caller's active OpenTelemetry span, when the
43
+ * program uses OpenTelemetry for JavaScript: version 1 of @opentelemetry/api
44
+ * keeps its registered context manager and propagator on globalThis under
45
+ * this symbol, so the SDK reads them without depending on the package. With
46
+ * it, Runtime's span of the call (an export with "traces") is a child of the
47
+ * caller's, in the caller's own trace. Nothing without OpenTelemetry, and
48
+ * never a reason for a call to fail. */
49
+ const OTEL_API = Symbol.for("opentelemetry.js.api.1");
50
+ export function traceHeaders() {
51
+ try {
52
+ const otel = globalThis[OTEL_API];
53
+ const active = otel?.context?.active?.();
54
+ if (!active || !otel?.propagation?.inject)
55
+ return {};
56
+ const carrier = {};
57
+ otel.propagation.inject(active, carrier, {
58
+ set: (into, key, value) => {
59
+ into[key.toLowerCase()] = String(value);
60
+ },
61
+ });
62
+ const headers = {};
63
+ for (const name of ["traceparent", "tracestate"])
64
+ if (typeof carrier[name] === "string" && carrier[name].length <= 512)
65
+ headers[name] = carrier[name];
66
+ return headers;
67
+ }
68
+ catch {
69
+ return {};
70
+ }
71
+ }
42
72
  /** How long an answer that ran nothing (NOTHING_RAN) is retried for a call
43
73
  * that has no deadline of its own. */
44
74
  const NOTHING_RAN_MS = 300_000;
@@ -278,6 +308,7 @@ export class Transport {
278
308
  : { "content-type": "application/json" }),
279
309
  ...(key ? { "idempotency-key": key } : {}),
280
310
  ...(call.wait ? { prefer: `wait=${Math.min(120, Math.ceil(call.wait))}` } : {}),
311
+ ...traceHeaders(),
281
312
  };
282
313
  }
283
314
  /** Sends a call and returns the raw Response once it succeeded. Retries
package/dist/types.d.ts CHANGED
@@ -31,6 +31,10 @@ export type SandboxInfo = {
31
31
  /** Who its commands, processes and terminals run as when one names no
32
32
  * user: "sandbox" (uid 1000) or "root". Absent from APIs before 25 October 2026. */
33
33
  user?: "sandbox" | "root";
34
+ /** With no time limit, how far ahead each renewal funds it, in seconds;
35
+ * it runs for at least half of this even if Runtime cannot renew it.
36
+ * Absent from APIs before 25 October 2026. */
37
+ leaseSeconds?: number;
34
38
  /** Runs until stopped while credit lasts, never paused for idleness or a
35
39
  * time limit, and its disk is kept after a stop. */
36
40
  persistent?: boolean;
@@ -147,6 +151,12 @@ export type CreateSandbox = {
147
151
  * "sandbox"; a sandbox made from a snapshot runs as its source did. Files
148
152
  * written through `files` stay the sandbox user's. */
149
153
  user?: "sandbox" | "root";
154
+ /** With no time limit, how far ahead each renewal funds it: 300 to 43200
155
+ * seconds (12 hours). It is renewed when half is left, so it keeps running
156
+ * for at least half of this through an outage of Runtime's control plane.
157
+ * Each renewal holds that much time's credit; what it does not use is
158
+ * released. Default: its first lease, usually 1800. */
159
+ leaseSeconds?: number;
150
160
  /** Keep it running until you stop it, while credit lasts, with no idle
151
161
  * pause unless idlePauseSeconds asks for one. Its disk is billed as any
152
162
  * sandbox's, and kept after a stop, for restart(), as any sandbox's is.
@@ -502,6 +512,10 @@ export type SandboxSettings = {
502
512
  /** Pause after this many seconds with no activity, counted from now; 0
503
513
  * never, otherwise 60 to 86400 (a shorter time is raised to 60). */
504
514
  idlePauseSeconds?: number;
515
+ /** With no time limit, how far ahead each renewal funds it: 300 to 43200
516
+ * seconds; null the default again. A running one is renewed by it within
517
+ * seconds. */
518
+ leaseSeconds?: number | null;
505
519
  /** Keep it running until you stop it, while credit lasts, and keep its disk
506
520
  * after a stop. Paid only. */
507
521
  persistent?: boolean;