withruntime 1.1.1 → 1.4.58

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.
Files changed (77) hide show
  1. package/README.md +5 -2
  2. package/dist/generated/agentSessions.d.ts +2 -2
  3. package/dist/generated/agentSessions.js +2 -2
  4. package/dist/generated/agents.d.ts +2 -2
  5. package/dist/generated/agents.js +1 -1
  6. package/dist/generated/apps.d.ts +8 -6
  7. package/dist/generated/apps.js +10 -6
  8. package/dist/generated/browsers.d.ts +8 -6
  9. package/dist/generated/browsers.js +10 -6
  10. package/dist/generated/builds.d.ts +8 -6
  11. package/dist/generated/builds.js +10 -6
  12. package/dist/generated/ci.d.ts +106 -6
  13. package/dist/generated/ci.js +14 -6
  14. package/dist/generated/containers.d.ts +8 -6
  15. package/dist/generated/containers.js +10 -6
  16. package/dist/generated/desktops.d.ts +8 -6
  17. package/dist/generated/desktops.js +10 -6
  18. package/dist/generated/dropins/e2b.d.ts +180 -0
  19. package/dist/generated/dropins/e2b.js +342 -0
  20. package/dist/generated/dropins/e2b_code_interpreter.d.ts +180 -0
  21. package/dist/generated/dropins/e2b_code_interpreter.js +342 -0
  22. package/dist/generated/dropins/modal.d.ts +195 -0
  23. package/dist/generated/dropins/modal.js +375 -0
  24. package/dist/generated/dropins/runtime.d.ts +74 -0
  25. package/dist/generated/dropins/runtime.js +180 -0
  26. package/dist/generated/dropins/vercel.d.ts +78 -0
  27. package/dist/generated/dropins/vercel.js +154 -0
  28. package/dist/generated/egressIps.d.ts +2 -2
  29. package/dist/generated/egressIps.js +2 -2
  30. package/dist/generated/functions.d.ts +8 -6
  31. package/dist/generated/functions.js +10 -6
  32. package/dist/generated/identities.d.ts +42 -4
  33. package/dist/generated/identities.js +60 -0
  34. package/dist/generated/images.d.ts +3 -0
  35. package/dist/generated/images.js +4 -0
  36. package/dist/generated/index.d.ts +1 -1
  37. package/dist/generated/jobs.d.ts +2 -2
  38. package/dist/generated/jobs.js +1 -1
  39. package/dist/generated/keys.d.ts +28 -0
  40. package/dist/generated/keys.js +4 -0
  41. package/dist/generated/notebooks.d.ts +8 -6
  42. package/dist/generated/notebooks.js +10 -6
  43. package/dist/generated/ports.d.ts +2 -0
  44. package/dist/generated/projects.d.ts +49 -7
  45. package/dist/generated/projects.js +72 -3
  46. package/dist/generated/roles.d.ts +43 -5
  47. package/dist/generated/roles.js +61 -0
  48. package/dist/generated/routes.js +1 -1
  49. package/dist/generated/runtime.d.ts +49 -3
  50. package/dist/generated/runtime.js +235 -26
  51. package/dist/generated/sandboxes.d.ts +33 -14
  52. package/dist/generated/sandboxes.js +10 -6
  53. package/dist/generated/sites.d.ts +8 -6
  54. package/dist/generated/sites.js +10 -6
  55. package/dist/generated/snapshots.d.ts +7 -2
  56. package/dist/generated/snapshots.js +6 -2
  57. package/dist/generated/usage.d.ts +9 -3
  58. package/dist/generated/volumes.d.ts +30 -11
  59. package/dist/generated/volumes.js +19 -6
  60. package/dist/generated/workspaces.d.ts +8 -6
  61. package/dist/generated/workspaces.js +10 -6
  62. package/dist/v2/cli.d.ts +29 -0
  63. package/dist/v2/cli.js +156 -7
  64. package/dist/v2/login.d.ts +6 -0
  65. package/dist/v2/login.js +2 -1
  66. package/dist/v2/mcp.d.ts +5 -0
  67. package/dist/v2/mcp.js +196 -35
  68. package/dist/v2/openapi.json +3053 -1772
  69. package/dist/v2/shims/base.d.ts +0 -3
  70. package/dist/v2/shims/base.js +2 -7
  71. package/dist/v2/shims/blaxel.js +2 -1
  72. package/dist/v2/shims/daytona.js +3 -2
  73. package/dist/v2/shims/morph.js +3 -1
  74. package/dist/v2/shims/vercel.js +2 -1
  75. package/package.json +3 -2
  76. package/dist/v2/shims/e2b.d.ts +0 -142
  77. package/dist/v2/shims/e2b.js +0 -238
@@ -45,7 +45,7 @@ export class WorkspaceFiles {
45
45
  writeFolderUpload(upload, data, query = {}, options) {
46
46
  return this.#c.writeFolderUpload(this.#id, upload, data, query, options);
47
47
  }
48
- /** Ends a folder upload's input and returns once tar has ended, as an exec returns once its command has: the folder, or 400 `invalid_archive` with what tar said. A front that restarts meanwhile returns 503 `run_goes_on`; sent again, it returns how tar ended. An upload no call has named for 10 minutes since its last part or commit is ended. */
48
+ /** Ends a folder upload's input and returns once tar has ended, as an exec returns once its command has: the folder, or 400 `invalid_archive` with what tar said. Sent again, it returns how tar ended. An upload no call has named for 10 minutes since its last part or commit is ended. */
49
49
  commitFolderUpload(upload, options) {
50
50
  return this.#c.commitFolderUpload(this.#id, upload, options);
51
51
  }
@@ -61,7 +61,7 @@ export class WorkspaceFiles {
61
61
  rename(input, options) {
62
62
  return this.#c.rename(this.#id, input, options);
63
63
  }
64
- /** Makes an expiring address for one file that anyone may open with no API key, from a browser, curl or another service: GET downloads it (Range works, so videos play and downloads resume; archive: true downloads a folder as .tar.gz), PUT with the raw body uploads it (up to maxBytes, written whole; Content-Length required). The link acts as the key that made it: an upload link needs write, and the link ends with its key, with revokeLinks or with its workspace. A paused workspace is woken for it unless wake is false. */
64
+ /** Makes an expiring address for one file that anyone may open with no API key, from a browser, curl or another service: GET downloads it (Range works, so videos play and downloads resume; archive: true downloads a folder as .tar.gz), PUT with the raw body uploads it (up to maxBytes, written whole; Content-Length required). The link acts as the key that made it: an upload link needs write, and the link ends with its key, with revokeLinks or with its workspace. A paused workspace is woken for it unless wake is false. A port it serves is shared by a preview (previews.create), not a link. */
65
65
  link(path, input = {}, options) {
66
66
  return this.#c.link(this.#id, { ...input, path: path }, options);
67
67
  }
@@ -135,7 +135,7 @@ export class Workspace {
135
135
  get id() {
136
136
  return this.info.id;
137
137
  }
138
- /** Its vCPUs; its product's default when omitted. At least 1. */
138
+ /** Its vCPUs, at least every plan's least (a smaller number is taken as it); its product's default when omitted. At least 2. */
139
139
  get vcpu() {
140
140
  return this.info.vcpu;
141
141
  }
@@ -151,7 +151,7 @@ export class Workspace {
151
151
  get image() {
152
152
  return this.info.image;
153
153
  }
154
- /** The secrets it may get, by name, at most 64: only those of them whose scope admits it; [] none; every one whose scope admits it when omitted. A name with no secret yet takes effect once that secret is created. Fixed for its life: a fork or a copy of a snapshot keeps it. At most 64 items. */
154
+ /** The secrets it may get, by name, at most 64: only those of them whose scope admits it; [] none; every one whose scope admits it when omitted. A name with no secret yet takes effect once that secret is created. An update changes it; a fork or a copy of a snapshot keeps it. At most 64 items. */
155
155
  get secrets() {
156
156
  return this.info.secrets;
157
157
  }
@@ -219,6 +219,10 @@ export class Workspace {
219
219
  get ready() {
220
220
  return this.info.ready;
221
221
  }
222
+ /** For a machine that serves a port of its own (an app, a site or a function on 8080, a container on its image's, a notebook on 8888, a workspace on 8080, a desktop on 6080, a browser's DevTools on 9222): a link that opens it, answered by its create, get and update, none for a key that may not share its ports. It works for 10 minutes; a browser that opens it is given a cookie for that address for a day and sent on to the address without it, so no history keeps a link that still opens it. Another port is shared with previews.create. */
223
+ get url() {
224
+ return this.info.url;
225
+ }
222
226
  /** When Runtime deletes it (`deleteAfterSeconds`), finally: it can't be undone, as its delete can't; none: kept until deleted. */
223
227
  get deleteAt() {
224
228
  return this.info.deleteAt;
@@ -382,7 +386,7 @@ export class Workspaces {
382
386
  writeFolderUpload(id, upload, data, query = {}, options) {
383
387
  return this.transport.request("PUT", `/v2/workspaces/${encodeURIComponent(id)}/files/archive/uploads/${encodeURIComponent(upload)}`, { data: toBytes(data), query: { ...query }, options, idempotent: true });
384
388
  }
385
- /** Ends a folder upload's input and returns once tar has ended, as an exec returns once its command has: the folder, or 400 `invalid_archive` with what tar said. A front that restarts meanwhile returns 503 `run_goes_on`; sent again, it returns how tar ended. An upload no call has named for 10 minutes since its last part or commit is ended. */
389
+ /** Ends a folder upload's input and returns once tar has ended, as an exec returns once its command has: the folder, or 400 `invalid_archive` with what tar said. Sent again, it returns how tar ended. An upload no call has named for 10 minutes since its last part or commit is ended. */
386
390
  commitFolderUpload(id, upload, options) {
387
391
  return this.transport.request("POST", `/v2/workspaces/${encodeURIComponent(id)}/files/archive/uploads/${encodeURIComponent(upload)}:commit`, { options, idempotent: true });
388
392
  }
@@ -398,7 +402,7 @@ export class Workspaces {
398
402
  rename(id, input, options) {
399
403
  return this.transport.request("POST", `/v2/workspaces/${encodeURIComponent(id)}/files:rename`, { body: input, options });
400
404
  }
401
- /** Makes an expiring address for one file that anyone may open with no API key, from a browser, curl or another service: GET downloads it (Range works, so videos play and downloads resume; archive: true downloads a folder as .tar.gz), PUT with the raw body uploads it (up to maxBytes, written whole; Content-Length required). The link acts as the key that made it: an upload link needs write, and the link ends with its key, with revokeLinks or with its workspace. A paused workspace is woken for it unless wake is false. */
405
+ /** Makes an expiring address for one file that anyone may open with no API key, from a browser, curl or another service: GET downloads it (Range works, so videos play and downloads resume; archive: true downloads a folder as .tar.gz), PUT with the raw body uploads it (up to maxBytes, written whole; Content-Length required). The link acts as the key that made it: an upload link needs write, and the link ends with its key, with revokeLinks or with its workspace. A paused workspace is woken for it unless wake is false. A port it serves is shared by a preview (previews.create), not a link. */
402
406
  link(id, input, options) {
403
407
  return this.transport.request("POST", `/v2/workspaces/${encodeURIComponent(id)}/files:link`, { body: input, options });
404
408
  }
package/dist/v2/cli.d.ts CHANGED
@@ -9,6 +9,34 @@ export declare function readSecret(c: Command, args: Record<string, unknown>, st
9
9
  * path's parts, flags its fields, and after `--`, its command (`cmd`) when
10
10
  * it takes one. */
11
11
  export declare function parse(c: Command, argv: string[]): Record<string, unknown>;
12
+ /** This folder's GitHub repository, `owner/name`, from its git remote `origin`; none outside one. */
13
+ export declare function gitHubRepository(remote?: () => string): string | undefined;
14
+ /** A change an answer asks this computer's git to commit and push, as its own: on `commit`, as `branch`. */
15
+ type Push = {
16
+ branch: string;
17
+ base: string;
18
+ commit: string;
19
+ message: string;
20
+ patch: string;
21
+ };
22
+ /** `push` committed and pushed to GitHub's `repository` with this computer's own git and its own credentials: in this
23
+ * folder's clone when its `origin` is that repository, else in a bare copy made for it. The patch is applied to a
24
+ * temporary index on `push.commit`, so the folder's working tree, index and branch are left as they are. */
25
+ export declare function pushChange(repository: string, push: Push, o?: {
26
+ git?: (args: string[], env?: Record<string, string>, input?: string) => string;
27
+ here?: () => string | undefined;
28
+ say?: (line: string) => void;
29
+ }): void;
30
+ /** `call` made again until its answer waits on no person ([`Next`]): each new step's page told once and opened in
31
+ * this computer's browser when it is the API's own site's ([`sitePage`]), for at most `most` milliseconds. */
32
+ export declare function follow(call: () => Promise<unknown>, baseUrl: string, o?: {
33
+ say?: (line: string) => void;
34
+ open?: (url: string) => void;
35
+ sleep?: (ms: number) => Promise<void>;
36
+ now?: () => number;
37
+ most?: number;
38
+ push?: (repository: string, push: Push) => void;
39
+ }): Promise<unknown>;
12
40
  /** The commands this file serves itself, ahead of the API's: each by its name, given the API's URL and what follows. */
13
41
  export declare const own: Record<string, (baseUrl: string, rest: string[]) => number | Promise<number>>;
14
42
  /** The API's command argv names (a shortcut by its name, a verb by its product and verb), and what follows it; an
@@ -18,3 +46,4 @@ export declare function find(commands: Command[], argv: string[]): {
18
46
  rest: string[];
19
47
  };
20
48
  export declare function main(argv: string[]): Promise<number>;
49
+ export {};
package/dist/v2/cli.js CHANGED
@@ -3,14 +3,23 @@
3
3
  argv into a verb's arguments, printing its answer, and the primitives a
4
4
  composition of verbs cannot be (standard input and output, a key from
5
5
  the environment or from `runtime login`, the stdio MCP bridge) are all
6
- it does. */
7
- import { readFileSync } from "node:fs";
6
+ it does. Three rules hold for every command: one run with no key logs
7
+ this computer in first; a `repository` it needs and is not given is
8
+ this folder's GitHub repository (its `origin`); and an answer with a
9
+ `next` (a page a person opens) is followed: the page opened, the same
10
+ call made again until no person is waited on; one with a `push` (a
11
+ change to a repository) is committed and pushed with this computer's
12
+ own git, then the call is made again. */
13
+ import { execFileSync } from "node:child_process";
14
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
8
17
  import { Runtime } from "../generated/index.js";
9
18
  import { Transport, callRoute, routesOf } from "../generated/runtime.js";
10
19
  import { commandsOf, document, kebab } from "./table.js";
11
20
  import { obj, str } from "./json.js";
12
21
  import { serveMcp } from "./mcp.js";
13
- import { login, logout, savedKey } from "./login.js";
22
+ import { login, logout, openBrowser, savedKey, sitePage } from "./login.js";
14
23
  import { serveMachinesApi } from "./shims/fly.js";
15
24
  /** This package's version, from its package.json. */
16
25
  function version() {
@@ -187,6 +196,11 @@ export function parse(c, argv) {
187
196
  if (given.length === 1)
188
197
  args[field] = given[0];
189
198
  }
199
+ // A command whose path names nothing takes its one required field bare (`runtime ci connect acme/api`).
200
+ const sole = c.flags.filter((f) => f.required && !f.secret && !f.command);
201
+ if (c.args.length === 0 && positional.length === 1 && sole.length === 1 && args[sole[0].field] === undefined) {
202
+ args[sole[0].field] = value(sole[0], positional.pop());
203
+ }
190
204
  if (positional.length > c.args.length) {
191
205
  // A shortcut's command after its flags, without `--`.
192
206
  const command = c.flags.find((f) => f.command);
@@ -206,11 +220,125 @@ export function parse(c, argv) {
206
220
  for (const n of c.args)
207
221
  if (args[n] === undefined)
208
222
  throw new Error(`${c.name} needs <${n}>.`);
223
+ if (args["repository"] === undefined && c.flags.some((f) => f.field === "repository" && f.type === "string")) {
224
+ const here = gitHubRepository();
225
+ if (here)
226
+ args["repository"] = here;
227
+ }
209
228
  for (const f of c.flags)
210
229
  if (f.required && !f.secret && args[f.field] === undefined)
211
230
  throw new Error(`${c.name} needs --${f.flag}.`);
212
231
  return args;
213
232
  }
233
+ /** This folder's GitHub repository, `owner/name`, from its git remote `origin`; none outside one. */
234
+ export function gitHubRepository(remote = () => execFileSync("git", ["remote", "get-url", "origin"], {
235
+ encoding: "utf8",
236
+ stdio: ["ignore", "pipe", "ignore"],
237
+ })) {
238
+ let url;
239
+ try {
240
+ url = remote().trim();
241
+ }
242
+ catch {
243
+ return undefined;
244
+ }
245
+ const m = /^(?:https:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url);
246
+ return m ? `${m[1]}/${m[2]}` : undefined;
247
+ }
248
+ function pushOf(answer) {
249
+ const a = answer;
250
+ const p = a?.push;
251
+ return p && typeof a.repository === "string" && typeof p.branch === "string" && typeof p.commit === "string" && typeof p.patch === "string"
252
+ ? { repository: a.repository, push: { branch: p.branch, base: p.base ?? "", commit: p.commit, message: p.message ?? "", patch: p.patch } }
253
+ : undefined;
254
+ }
255
+ /** `push` committed and pushed to GitHub's `repository` with this computer's own git and its own credentials: in this
256
+ * folder's clone when its `origin` is that repository, else in a bare copy made for it. The patch is applied to a
257
+ * temporary index on `push.commit`, so the folder's working tree, index and branch are left as they are. */
258
+ export function pushChange(repository, push, o = {}) {
259
+ const say = o.say ?? ((line) => process.stderr.write(`${line}\n`));
260
+ const tmp = mkdtempSync(join(tmpdir(), "runtime-push-"));
261
+ const run = o.git ??
262
+ ((args, env, input) => execFileSync("git", args, { encoding: "utf8", env: { ...process.env, ...env }, input, stdio: ["pipe", "pipe", "pipe"] }));
263
+ try {
264
+ const own = (o.here ?? gitHubRepository)()?.toLowerCase() === repository.toLowerCase();
265
+ const at = own ? [] : ["-C", join(tmp, "repo.git")];
266
+ const remote = own ? "origin" : `https://github.com/${repository}.git`;
267
+ if (!own)
268
+ run(["init", "-q", "--bare", join(tmp, "repo.git")]);
269
+ say(`Pushing the runs-on change to ${repository} as the branch ${push.branch}, with this computer's git...`);
270
+ run([...at, "fetch", "-q", "--no-tags", ...(own ? [] : ["--depth", "1", "--filter=blob:none"]), remote, push.commit]);
271
+ const index = { GIT_INDEX_FILE: join(tmp, "index") };
272
+ run([...at, "read-tree", push.commit], index);
273
+ run([...at, "apply", "--cached", "-"], index, push.patch);
274
+ const tree = run([...at, "write-tree"], index).trim();
275
+ // A computer whose git names no one commits as Runtime's change.
276
+ let who = [];
277
+ try {
278
+ run([...at, "config", "user.email"]);
279
+ }
280
+ catch {
281
+ who = ["-c", "user.name=Runtime", "-c", "user.email=noreply@withruntime.com"];
282
+ }
283
+ const commit = run([...who, ...at, "commit-tree", tree, "-p", push.commit, "-m", push.message]).trim();
284
+ run([...at, "push", "-q", remote, `+${commit}:refs/heads/${push.branch}`]);
285
+ }
286
+ catch (e) {
287
+ const stderr = e.stderr;
288
+ const why = (typeof stderr === "string" || stderr instanceof Uint8Array ? String(stderr) : e.message).trim();
289
+ const scope = /workflow` scope|without `workflows?` permission/i.test(why)
290
+ ? " This computer's GitHub credentials cannot change workflow files: run `gh auth refresh -s workflow`, or push over SSH, then run this again."
291
+ : "";
292
+ throw new Error(`git could not push the change to ${repository}: ${why.split("\n").slice(-3).join(" ")}${scope}`);
293
+ }
294
+ finally {
295
+ rmSync(tmp, { recursive: true, force: true });
296
+ }
297
+ }
298
+ function nextOf(answer) {
299
+ const n = answer?.next;
300
+ return n && typeof n.url === "string" && typeof n.message === "string"
301
+ ? { url: n.url, message: n.message, againSeconds: Math.max(1, Number(n.againSeconds) || 3) }
302
+ : undefined;
303
+ }
304
+ /** `call` made again until its answer waits on no person ([`Next`]): each new step's page told once and opened in
305
+ * this computer's browser when it is the API's own site's ([`sitePage`]), for at most `most` milliseconds. */
306
+ export async function follow(call, baseUrl, o = {}) {
307
+ const say = o.say ?? ((line) => process.stderr.write(`${line}\n`));
308
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
309
+ const now = o.now ?? Date.now;
310
+ const until = now() + (o.most ?? 30 * 60_000);
311
+ let told;
312
+ let answer = await call();
313
+ let pushed = false;
314
+ for (;;) {
315
+ // A change to push is pushed once, then the call is made again; asked for twice, the API is not taking it.
316
+ const asked = pushOf(answer);
317
+ if (asked) {
318
+ if (pushed)
319
+ throw new Error(`the branch ${asked.push.branch} was pushed, and the API still asks for it.`);
320
+ pushed = true;
321
+ (o.push ?? ((r, p) => pushChange(r, p, { say })))(asked.repository, asked.push);
322
+ answer = await call();
323
+ continue;
324
+ }
325
+ const next = nextOf(answer);
326
+ if (!next)
327
+ return answer;
328
+ if (next.message !== told) {
329
+ told = next.message;
330
+ say(`${next.message}\n ${next.url}`);
331
+ const page = sitePage(next.url, baseUrl);
332
+ if (page)
333
+ (o.open ?? openBrowser)(page);
334
+ say("Waiting...");
335
+ }
336
+ if (now() >= until)
337
+ throw new Error(`still waiting after 30 minutes: ${next.message} ${next.url}`);
338
+ await sleep(next.againSeconds * 1000);
339
+ answer = await call();
340
+ }
341
+ }
214
342
  /** A shortcut's steps in order, each verb by its route; a failed step ends
215
343
  * it, but for the steps that always run once what they read is in. */
216
344
  async function shortcut(t, routes, c, args) {
@@ -265,6 +393,10 @@ function print(answer) {
265
393
  process.stderr.write(r.stderr);
266
394
  return typeof r.exitCode === "number" ? r.exitCode : 124;
267
395
  }
396
+ // An object's sentence for a person goes to them; the object itself to standard output.
397
+ const said = answer;
398
+ if (said && typeof said.object === "string" && typeof said.message === "string")
399
+ process.stderr.write(`${said.message}\n`);
268
400
  if (answer !== undefined)
269
401
  process.stdout.write(`${JSON.stringify(answer, null, 2)}\n`);
270
402
  return 0;
@@ -368,16 +500,33 @@ export async function main(argv) {
368
500
  process.stdout.write(`${help(c)}\n`);
369
501
  return 0;
370
502
  }
371
- const t = new Transport({ baseUrl });
372
503
  const routes = routesOf(doc);
504
+ const keyed = Boolean(process.env["RUNTIME_API_KEY"]);
373
505
  try {
374
506
  const args = parse(c, rest);
375
507
  if (c.stdin)
376
508
  args["data"] = new Uint8Array(readFileSync(0));
377
509
  readSecret(c, args, () => (process.stdin.isTTY ? undefined : readFileSync(0, "utf8")));
378
- const answer = c.shortcut
379
- ? await shortcut(t, routes, c, args)
380
- : await callRoute(t, routes[c.name], args);
510
+ const once = () => {
511
+ const t = new Transport({ baseUrl });
512
+ return c.shortcut ? shortcut(t, routes, c, args) : callRoute(t, routes[c.name], args);
513
+ };
514
+ let answer;
515
+ try {
516
+ answer = await follow(once, baseUrl);
517
+ }
518
+ catch (e) {
519
+ // No key on this computer: it logs in as `runtime login` does, and the command goes on.
520
+ if (keyed || e.status !== 401)
521
+ throw e;
522
+ if ((await login(baseUrl)) !== 0)
523
+ return 1;
524
+ const key = savedKey(baseUrl);
525
+ if (!key)
526
+ return 1;
527
+ process.env["RUNTIME_API_KEY"] = key;
528
+ answer = await follow(once, baseUrl);
529
+ }
381
530
  return print(answer);
382
531
  }
383
532
  catch (e) {
@@ -16,6 +16,10 @@ export declare function savedKey(baseUrl: string, env?: NodeJS.ProcessEnv): stri
16
16
  * hosts are anyone's. Any other scheme or host is the answer of
17
17
  * something that is not the API, and is printed but never opened. */
18
18
  export declare function sitePage(link: string, baseUrl: string): string | undefined;
19
+ /** Opens `url`, a checked https page ([`sitePage`]), in this computer's
20
+ * browser, as one argument and never through a shell; a computer without a
21
+ * browser has the link printed. */
22
+ export declare function openBrowser(url: string): void;
19
23
  export type LoginOptions = {
20
24
  /** Whether standard output is a terminal: a key that cannot be saved is shown only there. */
21
25
  tty?: () => boolean;
@@ -25,6 +29,8 @@ export type LoginOptions = {
25
29
  sleep?: (ms: number) => Promise<void>;
26
30
  now?: () => number;
27
31
  say?: (line: string) => void;
32
+ /** Told the link and code once the API has given them, before the wait for the approval. */
33
+ started?: (link: string, userCode: string) => void;
28
34
  };
29
35
  export declare function login(baseUrl: string, o?: LoginOptions): Promise<number>;
30
36
  /** Forgets the key a login saved for `baseUrl`. The key itself works until
package/dist/v2/login.js CHANGED
@@ -84,7 +84,7 @@ export function sitePage(link, baseUrl) {
84
84
  /** Opens `url`, a checked https page ([`sitePage`]), in this computer's
85
85
  * browser, as one argument and never through a shell; a computer without a
86
86
  * browser has the link printed. */
87
- function openBrowser(url) {
87
+ export function openBrowser(url) {
88
88
  const [cmd, args] = process.platform === "darwin"
89
89
  ? ["open", ["--", url]]
90
90
  : process.platform === "win32"
@@ -141,6 +141,7 @@ export async function login(baseUrl, o = {}) {
141
141
  const link = started.verification_uri_complete ?? started.verification_uri;
142
142
  say(`Approve this computer at ${link}`);
143
143
  say(`and check that the page shows the code ${started.user_code}.`);
144
+ o.started?.(link, started.user_code);
144
145
  const page = sitePage(link, baseUrl);
145
146
  if (page)
146
147
  (o.open ?? openBrowser)(page);
package/dist/v2/mcp.d.ts CHANGED
@@ -1 +1,6 @@
1
+ import { type LoginOptions } from "./login.js";
2
+ /** The bridge: `handle` takes one line a client sent, and each answer goes to `write`. Each line's request to the API
3
+ * waits at most `silentMs` for each byte of its answer ([`Silence`]): a connection silent longer is dropped, and the
4
+ * request sent once more on a new one when sending it again is safe ([`resendable`]); else its error names the wait. */
5
+ export declare function bridge(baseUrl: string, write: (m: unknown) => void, fetcher?: typeof fetch, connect?: LoginOptions, silentMs?: number): (line: string) => Promise<void>;
1
6
  export declare function serveMcp(baseUrl: string, fetcher?: typeof fetch): Promise<number>;
package/dist/v2/mcp.js CHANGED
@@ -3,60 +3,221 @@
3
3
  to the API's own MCP endpoint (POST /mcp, which serves every verb and
4
4
  shortcut the spec names) under RUNTIME_API_KEY, and its answer written
5
5
  back as one line: the tools are always the server's, never this
6
- package's, so a verb is a tool the moment it is live. */
6
+ package's, so a verb is a tool the moment it is live.
7
+
8
+ With no key (none set, none saved by `runtime login`), the bridge answers
9
+ itself with one tool, runtime_connect, which signs this computer in as
10
+ `runtime login` does, from inside the agent; once approved, the server's
11
+ tools are listed. 24 Nov 2026: without a key every message was refused,
12
+ `initialize` too, so a client added before `npx withruntime login` showed
13
+ the server as failed and nothing said what to do. */
7
14
  import { createInterface } from "node:readline";
8
- export async function serveMcp(baseUrl, fetcher = fetch) {
9
- const key = process.env["RUNTIME_API_KEY"];
10
- const endpoint = `${baseUrl}/mcp`;
11
- const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
12
- const write = (m) => process.stdout.write(`${JSON.stringify(m)}\n`);
13
- for await (const line of lines) {
15
+ import { SILENT_MS, Silence } from "../generated/runtime.js";
16
+ import { login, savedKey } from "./login.js";
17
+ const CONNECT = "runtime_connect";
18
+ /** The server's tool that calls another by its name (`params.arguments.name`), with that tool's own arguments. */
19
+ const CALL_TOOL = "runtime_call_tool";
20
+ const NOT_CONNECTED = "Runtime is not connected on this computer. Call runtime_connect to sign in: it returns a link and a code for the person you work for to approve in a browser, and Runtime's tools are listed once they have. With RUNTIME_API_KEY set, or after `npx withruntime login`, the server starts connected.";
21
+ const connectTool = {
22
+ name: CONNECT,
23
+ title: "Connect this computer to Runtime",
24
+ description: "Signs this computer in to Runtime with a browser approval, with no key to copy. The first call returns a link and a code: show both to the person you work for and ask them to approve. Call it again after they have; it waits up to 45 seconds for the approval, then Runtime's tools are listed.",
25
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
26
+ };
27
+ /** How long a call of runtime_connect after the first waits for the approval. */
28
+ const WAIT_MS = 45_000;
29
+ /** The bridge: `handle` takes one line a client sent, and each answer goes to `write`. Each line's request to the API
30
+ * waits at most `silentMs` for each byte of its answer ([`Silence`]): a connection silent longer is dropped, and the
31
+ * request sent once more on a new one when sending it again is safe ([`resendable`]); else its error names the wait. */
32
+ export function bridge(baseUrl, write, fetcher = fetch, connect = {}, silentMs = SILENT_MS) {
33
+ const env = connect.env ?? process.env;
34
+ /** The tools the server says only read (`readOnlyHint`), from the lists and searches it answered. */
35
+ const reads = new Set();
36
+ let key = env["RUNTIME_API_KEY"] || undefined;
37
+ let pending;
38
+ /** Starts a sign-in, resolved with its link and code once the API gave them; its `done` is the error, or "". */
39
+ const begin = () => new Promise((started, failed) => {
40
+ const said = [];
41
+ const done = login(baseUrl, {
42
+ fetch: fetcher,
43
+ // The wait for an approval never holds the process: a client that closes the server's input ends it.
44
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms).unref()),
45
+ ...connect,
46
+ env,
47
+ tty: () => false,
48
+ say: (l) => void (said.push(l), process.stderr.write(`${l}\n`)),
49
+ started: (link, code) => started({ link, code, done }),
50
+ }).then((code) => {
51
+ const saved = code === 0 ? savedKey(baseUrl, env) : undefined;
52
+ if (saved) {
53
+ key = saved;
54
+ write({ jsonrpc: "2.0", method: "notifications/tools/list_changed" });
55
+ return "";
56
+ }
57
+ pending = undefined;
58
+ const why = said.at(-1)?.replace(/^runtime login: /, "") ?? "the sign-in ended.";
59
+ failed(new Error(why));
60
+ return why;
61
+ });
62
+ });
63
+ const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...(isError ? { isError } : {}) });
64
+ const ask = (p) => `Open ${p.link} and check that the page shows the code ${p.code}, then choose Connect. Show the link and code to the person you work for. When they have approved, call runtime_connect again.`;
65
+ async function connectCall() {
66
+ if (key)
67
+ return text("Connected. Runtime's tools are listed.");
68
+ if (!pending) {
69
+ try {
70
+ pending = await begin();
71
+ }
72
+ catch (e) {
73
+ return text(`The sign-in could not start: ${e.message}`, true);
74
+ }
75
+ return text(ask(pending));
76
+ }
77
+ const p = pending;
78
+ const why = await Promise.race([p.done, new Promise((r) => setTimeout(() => r(null), WAIT_MS).unref())]);
79
+ if (why === "")
80
+ return text("Connected. Runtime's tools are listed.");
81
+ if (why === null)
82
+ return text(`Not approved yet. ${ask(p)}`);
83
+ return text(`The sign-in ended: ${why} Call runtime_connect for a new link.`, true);
84
+ }
85
+ /** The answer to `m` while no key is held. */
86
+ async function unconnected(m) {
87
+ switch (m.method) {
88
+ case "initialize":
89
+ return {
90
+ protocolVersion: typeof m.params?.protocolVersion === "string" ? m.params.protocolVersion : "2025-06-18",
91
+ capabilities: { tools: { listChanged: true } },
92
+ serverInfo: { name: "runtime-cloud", version: "not connected" },
93
+ instructions: NOT_CONNECTED,
94
+ };
95
+ case "ping":
96
+ return {};
97
+ case "tools/list":
98
+ return { tools: [connectTool] };
99
+ case "tools/call":
100
+ return m.params?.name === CONNECT ? connectCall() : text(NOT_CONNECTED, true);
101
+ default:
102
+ throw new Error(NOT_CONNECTED);
103
+ }
104
+ }
105
+ return async (line) => {
14
106
  if (!line.trim())
15
- continue;
16
- let id = null;
107
+ return;
108
+ let m;
17
109
  try {
18
- id = JSON.parse(line).id ?? null;
110
+ m = JSON.parse(line);
19
111
  }
20
112
  catch {
21
113
  write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "The line is not JSON." } });
22
- continue;
114
+ return;
115
+ }
116
+ const id = m.id ?? null;
117
+ if (!key || (m.method === "tools/call" && m.params?.name === CONNECT)) {
118
+ if (m.id === undefined)
119
+ return; // a notification
120
+ try {
121
+ write({ jsonrpc: "2.0", id, result: await (key ? connectCall() : unconnected(m)) });
122
+ }
123
+ catch (e) {
124
+ write({ jsonrpc: "2.0", id, error: { code: -32001, message: e.message } });
125
+ }
126
+ return;
23
127
  }
24
128
  try {
25
- const res = await fetcher(endpoint, {
26
- method: "POST",
27
- headers: {
28
- "content-type": "application/json",
29
- accept: "application/json, text/event-stream",
30
- ...(key ? { authorization: `Bearer ${key}` } : {}),
31
- },
32
- body: line,
33
- });
129
+ const { res, body } = await post(line, m);
34
130
  if (res.status === 202)
35
- continue;
36
- const text = await res.text();
37
- let body;
131
+ return;
132
+ let parsed;
38
133
  try {
39
- body = JSON.parse(text);
134
+ parsed = JSON.parse(body);
40
135
  }
41
136
  catch {
42
- write({ jsonrpc: "2.0", id, error: { code: -32603, message: `The API answered ${res.status}: ${text.slice(0, 200)}` } });
43
- continue;
137
+ write({ jsonrpc: "2.0", id, error: { code: -32603, message: `The API answered ${res.status}: ${body.slice(0, 200)}` } });
138
+ return;
44
139
  }
45
140
  if (res.ok) {
46
- write(body);
47
- continue;
48
- }
49
- // A refusal of the call itself (no key, a bad key, a limit) is the API's error body, not a JSON-RPC answer: the
50
- // client is told it as this request's error, or it waits for an answer that never comes.
51
- const api = body.error;
52
- const message = !key && res.status === 401
53
- ? "No API key. Set RUNTIME_API_KEY, or run `npx withruntime login` once on this machine."
54
- : `${api?.code ?? res.status}: ${api?.message ?? text.slice(0, 200)}${api?.hint ? ` ${api.hint}` : ""}`;
141
+ learn(m, parsed);
142
+ write(parsed);
143
+ return;
144
+ }
145
+ // A refusal of the call itself (a bad key, a limit) is the API's error body, not a JSON-RPC answer: the client
146
+ // is told it as this request's error, or it waits for an answer that never comes.
147
+ const api = parsed.error;
148
+ const message = `${api?.code ?? res.status}: ${api?.message ?? body.slice(0, 200)}${api?.hint ? ` ${api.hint}` : ""}`;
55
149
  write({ jsonrpc: "2.0", id, error: { code: -32001, message, data: { status: res.status, ...api } } });
56
150
  }
57
151
  catch (e) {
58
152
  write({ jsonrpc: "2.0", id, error: { code: -32603, message: `The API did not answer: ${e.message}` } });
59
153
  }
154
+ };
155
+ /** `line` sent to the API's MCP endpoint, and its answer read whole, each attempt under its own [`Silence`]. A
156
+ * connection that failed or went silent is dropped, and the request sent once more, on a new connection, only when
157
+ * a second copy cannot run it twice. */
158
+ async function post(line, m) {
159
+ for (let attempt = 0;; attempt++) {
160
+ const quiet = new Silence(silentMs);
161
+ try {
162
+ const res = await quiet.within(fetcher(`${baseUrl}/mcp`, {
163
+ method: "POST",
164
+ headers: {
165
+ "content-type": "application/json",
166
+ accept: "application/json, text/event-stream",
167
+ authorization: `Bearer ${key}`,
168
+ },
169
+ body: line,
170
+ signal: quiet.signal,
171
+ }));
172
+ return { res, body: new TextDecoder().decode(await quiet.read(res)) };
173
+ }
174
+ catch (e) {
175
+ const again = attempt === 0 && resendable(m);
176
+ process.stderr.write(`runtime mcp: ${typeof m.method === "string" ? m.method : "a message"} failed${again ? ", sent once more on a new connection" : ""}: ${e.message}\n`);
177
+ if (again)
178
+ continue;
179
+ if (!quiet.silent)
180
+ throw e;
181
+ throw new Error(`${e.message} The call was not sent again, as it may have run: check its effect before calling it again, or call it with an idempotencyKey, which runs it at most once however often it is sent.`);
182
+ }
183
+ finally {
184
+ quiet.done();
185
+ }
186
+ }
187
+ }
188
+ /** Whether `m` may be sent twice: a message that only reads (any but a tool's call), a call of a tool the server
189
+ * said only reads, or one under an idempotencyKey, which the server runs at most once. */
190
+ function resendable(m) {
191
+ if (m.method !== "tools/call")
192
+ return true;
193
+ let name = m.params?.name;
194
+ let args = m.params?.arguments;
195
+ if (name === CALL_TOOL) {
196
+ name = args?.name;
197
+ args = args?.arguments;
198
+ }
199
+ return typeof args?.idempotencyKey === "string" || (typeof name === "string" && reads.has(name));
200
+ }
201
+ /** The read-only tools in `answer`, the server's to `m`: its list (`tools/list`), or a search's (`structuredContent`). */
202
+ function learn(m, answer) {
203
+ const result = answer.result;
204
+ const tools = m.method === "tools/list" ? result?.tools : result?.structuredContent?.tools;
205
+ if (!Array.isArray(tools))
206
+ return;
207
+ for (const t of tools)
208
+ if (typeof t?.name === "string" && t.annotations?.readOnlyHint === true)
209
+ reads.add(t.name);
210
+ }
211
+ }
212
+ export async function serveMcp(baseUrl, fetcher = fetch) {
213
+ const handle = bridge(baseUrl, (m) => process.stdout.write(`${JSON.stringify(m)}\n`), fetcher);
214
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
215
+ // Each line at once: a runtime_connect that waits for an approval holds up no other call.
216
+ const running = new Set();
217
+ for await (const line of lines) {
218
+ const p = handle(line).finally(() => running.delete(p));
219
+ running.add(p);
60
220
  }
221
+ await Promise.all(running);
61
222
  return 0;
62
223
  }