@parcha/agentrun-computer 0.1.0-beta.45 → 0.1.0-beta.47

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 (50) hide show
  1. package/README.md +75 -7
  2. package/dist/attach.d.ts +23 -5
  3. package/dist/attach.js +83 -20
  4. package/dist/computerd-linux-amd64 +0 -0
  5. package/dist/computerd-linux-arm64 +0 -0
  6. package/dist/computerd.json +2 -2
  7. package/dist/conformance/agent37.js +2 -2
  8. package/dist/conformance/boxd.js +2 -3
  9. package/dist/conformance/cli.js +1 -1
  10. package/dist/conformance/cloudflare.d.ts +2 -0
  11. package/dist/conformance/cloudflare.js +4 -0
  12. package/dist/conformance/e2b.js +2 -3
  13. package/dist/conformance/fixture.js +1 -1
  14. package/dist/conformance/fly.d.ts +4 -0
  15. package/dist/conformance/fly.js +4 -0
  16. package/dist/conformance/kind.d.ts +8 -1
  17. package/dist/conformance/kind.js +6 -1
  18. package/dist/conformance/modal.d.ts +4 -0
  19. package/dist/conformance/modal.js +5 -1
  20. package/dist/conformance/smolcloud.d.ts +47 -0
  21. package/dist/conformance/smolcloud.js +73 -0
  22. package/dist/conformance/sweep.js +1 -1
  23. package/dist/conformance/types.d.ts +2 -1
  24. package/dist/daytona.d.ts +1 -1
  25. package/dist/daytona.js +5 -6
  26. package/dist/descriptor.d.ts +22 -3
  27. package/dist/descriptor.js +31 -2
  28. package/dist/descriptors/cloudflare.js +1 -1
  29. package/dist/descriptors/daytona.d.ts +5 -13
  30. package/dist/descriptors/daytona.js +6 -6
  31. package/dist/descriptors/fly.js +1 -1
  32. package/dist/descriptors/index.d.ts +22 -14
  33. package/dist/descriptors/index.js +3 -2
  34. package/dist/descriptors/smolcloud.d.ts +18 -0
  35. package/dist/descriptors/smolcloud.js +21 -0
  36. package/dist/hosted/provider.js +12 -28
  37. package/dist/hosted/rest.d.ts +2 -0
  38. package/dist/hosted/rest.js +1 -1
  39. package/dist/hosted/values.d.ts +0 -2
  40. package/dist/hosted/values.js +0 -2
  41. package/dist/index.d.ts +3 -2
  42. package/dist/index.js +4 -3
  43. package/dist/kinds.d.ts +11 -71
  44. package/dist/kinds.js +2 -9
  45. package/dist/modal.js +5 -4
  46. package/dist/setting-kinds.d.ts +19 -0
  47. package/dist/setting-kinds.js +9 -0
  48. package/dist/smolcloud.d.ts +21 -0
  49. package/dist/smolcloud.js +254 -0
  50. package/package.json +7 -2
@@ -13,8 +13,8 @@ import { fileURLToPath } from "node:url";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import { ATTACH_PATH, DAEMON_PATH } from "../attach.js";
15
15
  import { CreateRequests, endedWords, otherSpecWords, readBackDiffer } from "../create-requests.js";
16
- import { syncs } from "../descriptor.js";
17
- import { DESKTOP_GROUPS, desktopOf, startDisplay } from "../desktop.js";
16
+ import { mountsOf, syncs } from "../descriptor.js";
17
+ import { desktopOf, startDisplay } from "../desktop.js";
18
18
  import { COMPUTER_LABEL, DAEMON_IN_COMPUTER, DEADLINE_LABEL, helloDrift, probeNetworkDrift, probeNotes, probeReportOf, show, WORK } from "../drift.js";
19
19
  import { BACKSTOP_MARGIN_MS } from "../host.js";
20
20
  import { readOwnNetwork, TOOL_USER } from "../isolation.js";
@@ -45,8 +45,6 @@ const USER = /^(\d+):(\d+)$/;
45
45
  /** A spec's user, where the host takes one: a uid, or uid:gid, in numbers (a uid alone is its own gid). */
46
46
  const SPEC_USER = /^(\d+)(?::(\d+))?$/;
47
47
  const MAX_ID = 4_294_967_294;
48
- /** The calls of a desktop's display (DESKTOP_GROUPS): screen, input, apps and ui. */
49
- const DISPLAY_METHOD = /^(screen|input|apps|ui)\./;
50
48
  const DEFAULTS = {
51
49
  requestMs: 30_000,
52
50
  createMs: 120_000,
@@ -181,6 +179,8 @@ export class HostedProvider {
181
179
  #extending = new Map();
182
180
  /** A dial host's server: what its machines reach, and what holds their tokens and sockets. */
183
181
  #dial;
182
+ /** The host's descriptor's mounts as its machines reach this server (mountsOf): a dial host's take no Archil mount. */
183
+ #mounts;
184
184
  constructor(host, options) {
185
185
  const { kind = "linux", desktop = {}, maxLifetimeMs = host.facts.maxLifetimeMs, daemonPath = hostedDaemonPath(host.facts.arch), daemonUser = TOOL_USER, timeouts = {}, probeTargets = DEFAULT_PROBE_TARGETS, onNote, archilEgress, } = options;
186
186
  const { id, label, capabilities } = host.descriptor;
@@ -228,6 +228,8 @@ export class HostedProvider {
228
228
  this.#timeouts = merged;
229
229
  this.#probeTargets = [...probeTargets];
230
230
  this.#dial = host.facts.connect === "dial" ? options.dial : undefined;
231
+ // The descriptor's keyed mounts are the host's already (Daytona's): no key is read here.
232
+ this.#mounts = mountsOf(host.descriptor, () => false, host.facts.connect === "dial");
231
233
  // Extend only where the end can follow it: the host moves its timer or its deadline label.
232
234
  if (host.extend)
233
235
  this.extend = (ref, ttlMs, context) => this.#extendSerial(ref, ttlMs, context?.signal);
@@ -252,7 +254,7 @@ export class HostedProvider {
252
254
  release: ["delete"],
253
255
  // A synced folder is derived for this configuration alone (descriptor.ts syncs), whatever the descriptor's list
254
256
  // says: a dial machine takes one too, its /workspace made by the box image's agentrun-dial.
255
- mount: [...descriptor.mounts.filter((kind) => kind !== "sync" && !(this.#dialing && kind === "archil")), ...(syncs(descriptor, this.#configuration) ? ["sync"] : [])],
257
+ mount: [...this.#mounts.mounts.filter((kind) => kind !== "sync"), ...(syncs(descriptor, this.#configuration) ? ["sync"] : [])],
256
258
  vendorAgentPorts: [...facts.vendorAgentPorts],
257
259
  ...(gpu === undefined ? {} : { gpu: structuredClone(gpu) }),
258
260
  ...(facts.user === undefined ? {} : { user: [...facts.user] }),
@@ -267,9 +269,7 @@ export class HostedProvider {
267
269
  const label = this.#label;
268
270
  // An Archil mount's own rules hold only where the provider takes one; elsewhere checkMount's refusal says why alone.
269
271
  const archil = mount?.kind === "archil" && (capabilities.mount ?? []).includes("archil");
270
- // A machine that dials takes no Archil mount yet: its helper's steps run as root through exec, which it has none of.
271
- const unmounted = this.#dialing ? { ...this.host.descriptor.unmounted, archil: `${label}'s machines dial this server, and a machine that dials takes no Archil mount yet` } : this.host.descriptor.unmounted;
272
- refusals.push(...checkMount(mount, capabilities.mount ?? [], unmounted), ...(archil ? archilRefusals(given) : []));
272
+ refusals.push(...checkMount(mount, capabilities.mount ?? [], this.#mounts.unmounted), ...(archil ? archilRefusals(given) : []));
273
273
  // A synced folder reads back under the run's claim epoch, as an Archil mount does: nothing in the computer holds one.
274
274
  if (mount?.kind === "sync" && (capabilities.mount ?? []).includes("sync")) {
275
275
  const epoch = epochOf(typeof labels === "object" && labels !== null ? labels : undefined);
@@ -1222,13 +1222,9 @@ export class HostedProvider {
1222
1222
  }
1223
1223
  /** The live view: screen.watch on a connection of the watch's own (daemonWatch); a linux computer has no screen. */
1224
1224
  watch(ref, handlers, options) {
1225
- return daemonWatch({ connect: (one) => this.#connect(one, "screen.watch") }, ref, handlers, options);
1225
+ return daemonWatch(this, ref, handlers, options);
1226
1226
  }
1227
- connect(ref) {
1228
- return this.#connect(ref);
1229
- }
1230
- /** connect; `watching`, a watch's: a dial desktop whose display isn't up yet refuses it in words, as its client does. */
1231
- async #connect(ref, watching) {
1227
+ async connect(ref) {
1232
1228
  const problem = this.#refProblem(ref);
1233
1229
  if (problem)
1234
1230
  return this.#fail("invalid", problem);
@@ -1244,20 +1240,8 @@ export class HostedProvider {
1244
1240
  if (!opened.ok)
1245
1241
  return opened;
1246
1242
  const { kind, groups } = this.capabilities();
1247
- // A dial desktop says linux until its display answers (attach.ts helloMismatch), and until a hello says desktop it is
1248
- // a linux computer: its screen, input, apps and ui calls are refused here in words, never sent.
1249
- const dark = this.#dialing && kind === "desktop" && opened.value.hello?.kind === "linux";
1250
- const expected = dark ? { kind: "linux", groups: groups.filter((group) => !DESKTOP_GROUPS.includes(group)) } : { kind, groups };
1251
- const drifted = helloDrift(opened.value.hello, { version: VERSION, ...expected, arch: this.host.facts.arch, fence: true });
1252
- const notUp = (method) => this.#fail("unsupported", `${ref.name}'s display isn't up yet: ${method} was not sent, and it is a linux computer until its daemon's hello says desktop`);
1253
- if (drifted.length === 0 && dark && watching) {
1254
- await opened.value.close();
1255
- return notUp(watching);
1256
- }
1257
- if (drifted.length === 0 && dark) {
1258
- const client = opened.value.client;
1259
- return ok({ ...opened.value, client: { call: (method, params, options) => (DISPLAY_METHOD.test(method) ? Promise.resolve(notUp(method)) : client.call(method, params, options)), close: () => client.close() } });
1260
- }
1243
+ // A desktop whose display is down says linux (an X server that died): drift, on dial as on exec.
1244
+ const drifted = helloDrift(opened.value.hello, { version: VERSION, kind, groups, arch: this.host.facts.arch, fence: true });
1261
1245
  // An Archil computer's client syncs the run's folder after every call that may change it, before it answers. A synced
1262
1246
  // folder's sync is its runner's (the sink is serve's), which wraps the client itself.
1263
1247
  if (drifted.length === 0)
@@ -11,6 +11,8 @@ export interface RestAnswer {
11
11
  export interface RestInit {
12
12
  json?: unknown;
13
13
  form?: FormData;
14
+ /** A body sent as it is (a file's bytes). */
15
+ bytes?: Uint8Array<ArrayBuffer>;
14
16
  timeoutMs?: number;
15
17
  /**
16
18
  * true: send again on no answer, 429 and 5xx (only for a call that may run twice). A function: send again only on an
@@ -65,7 +65,7 @@ export function rest(options) {
65
65
  const response = await fetcher(url, {
66
66
  method,
67
67
  headers,
68
- body: init.json === undefined ? init.form : JSON.stringify(init.json),
68
+ body: init.json === undefined ? (init.bytes ?? init.form) : JSON.stringify(init.json),
69
69
  redirect: "error",
70
70
  signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
71
71
  });
@@ -3,8 +3,6 @@ import type { ComputerSpec, Refusal } from "../provider.js";
3
3
  /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
4
4
  export declare const DOMAIN: RegExp;
5
5
  export declare const isWhole: (value: unknown) => value is number;
6
- /** Why a provider of both makes no desktop on exec (label: "Modal"): its desktop is the box image's, started over the dial. */
7
- export declare const execDesktopRefusal: (label: string, image: string) => string;
8
6
  /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
9
7
  export declare function sizeRefusals(spec: Partial<ComputerSpec>, computer: string, image: string): Refusal[];
10
8
  /** A time the vendor reports: a Date, an ISO string, or a whole number of ms (or seconds); undefined when it is none of them. */
@@ -4,8 +4,6 @@ import { deflateRawSync, inflateRawSync } from "node:zlib";
4
4
  /** A host name, as a vendor's domain option is one: DNS labels and a top-level name of letters. */
5
5
  export const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
6
6
  export const isWhole = (value) => typeof value === "number" && Number.isSafeInteger(value);
7
- /** Why a provider of both makes no desktop on exec (label: "Modal"): its desktop is the box image's, started over the dial. */
8
- export const execDesktopRefusal = (label, image) => `a ${label} desktop is made on connect "dial" alone, from ${image}, its X server started over the socket its machine dials: connect "exec" makes kind linux`;
9
7
  /** A vendor whose computer has its image's size: a spec's cpus or memoryMb, refused in words (computer: "an E2B computer"). */
10
8
  export function sizeRefusals(spec, computer, image) {
11
9
  return ["cpus", "memoryMb"].filter((field) => spec[field] !== undefined).map((field) => ({ field, message: `${computer} has the size of its ${image}: name a ${image} of the size you need, not ${field}` }));
package/dist/index.d.ts CHANGED
@@ -26,7 +26,8 @@ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_
26
26
  export { waitUntil, type WaitOptions } from "./wait.js";
27
27
  export { type BuiltinProviderId, type ConformanceModule, descriptorOf, isProviderId, type ProviderEnv, providerFor, type ProviderId, providerIds, type ProviderModule, providerModule, type ProviderOptions, providers, } from "./providers.js";
28
28
  export { connectOf, type DescriptorKey, type DescriptorSetting, defineProvider, descriptorProblems, type HostCommand, mountsOf, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
29
- export { AGENT37, AGENT37_BASE_TEMPLATE, BOXD, BOXD_DEFAULT_IMAGE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, MORPH, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
29
+ export { AGENT37, AGENT37_BASE_TEMPLATE, BOXD, BOXD_DEFAULT_IMAGE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, type DaytonaGpuSnapshot, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, MORPH, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, SMOLCLOUD, } from "./descriptors/index.js";
30
30
  export type { PhoneLedger, PhoneLedgerEntry } from "./phone-harness.js";
31
- export { type ComputerSettingKind, configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, kindServed, type ProviderEntry, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, type SettingKindSpec, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
31
+ export { configurationOf, entryOf, imagesOf, type KindCapabilities, kindOf, kindServed, type ProviderEntry, PROVIDERS, serves, servingRefusals, type TestConnection, type TestConnectionOptions, } from "./kinds.js";
32
+ export { type ComputerSettingKind, SETTING_KIND_NAMES, SETTING_KINDS, type SettingKindSpec } from "./setting-kinds.js";
32
33
  export * from "./conformance/index.js";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ export { createActionMapper, daemonWatch, redactWords, ScreenWatchError, toActio
14
14
  export { HostedProvider, hostedDaemonPath } from "./hosted/provider.js";
15
15
  // The provider classes and their option types are not here: each provider loads by its id through the registry
16
16
  // (providerFor), or from its own subpath (@parcha/agentrun-computer/docker, /daytona, /modal, /e2b, /agent37, /morph, /orgo,
17
- // /phone-harness, /browserbase, /kernel, /local: each the provider file's name).
17
+ // /phone-harness, /browserbase, /kernel, /local, /smolcloud: each the provider file's name).
18
18
  export { VOLUME_SUBPATH_ENGINE } from "./docker/volume.js";
19
19
  export { DEFAULT_DOCKER_IMAGE, DOCKER_BASE, DOCKER_RECIPE, DOCKER_RECIPE_HAS, ensureImage, IMAGE_REPOSITORY, IMAGE_TIMEOUT_MS, imageSourceProblem, RECIPE_LABEL, recipeHash, recipeTag, } from "./docker/image.js";
20
20
  export { EGRESS_IMAGE, EGRESS_LABEL, EGRESS_MOUNT, EGRESS_SOCKET } from "./docker/egress.js";
@@ -30,6 +30,7 @@ export { EPOCH_LABEL, epochOf, epochProblem, IDLE_TTL_LABEL, OWNER_LABEL, OWNER_
30
30
  export { waitUntil } from "./wait.js";
31
31
  export { descriptorOf, isProviderId, providerFor, providerIds, providerModule, providers, } from "./providers.js";
32
32
  export { connectOf, defineProvider, descriptorProblems, mountsOf } from "./descriptor.js";
33
- export { AGENT37, AGENT37_BASE_TEMPLATE, BOXD, BOXD_DEFAULT_IMAGE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, MORPH, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, } from "./descriptors/index.js";
34
- export { configurationOf, entryOf, imagesOf, kindOf, kindServed, PROVIDERS, SETTING_KIND_NAMES, SETTING_KINDS, serves, servingRefusals, } from "./kinds.js";
33
+ export { AGENT37, AGENT37_BASE_TEMPLATE, BOXD, BOXD_DEFAULT_IMAGE, BROWSER_IMAGE, BROWSERBASE, DAYTONA, DAYTONA_DEFAULT_SNAPSHOT, DAYTONA_GPU_SNAPSHOT, DESCRIPTORS, daytonaGpu, daytonaGpuSnapshot, DOCKER, E2B, KERNEL, LOCAL, MODAL, MORPH, ORGO, ORGO_BASE_IMAGE, PHONE_GROUPS, PHONE_HARNESS, PHONE_IMAGE, SMOLCLOUD, } from "./descriptors/index.js";
34
+ export { configurationOf, entryOf, imagesOf, kindOf, kindServed, PROVIDERS, serves, servingRefusals, } from "./kinds.js";
35
+ export { SETTING_KIND_NAMES, SETTING_KINDS } from "./setting-kinds.js";
35
36
  export * from "./conformance/index.js";
package/dist/kinds.d.ts CHANGED
@@ -1,26 +1,8 @@
1
- import { type DescriptorKey, type DescriptorSetting, type HostCommand, type ParkedConfiguration, type ProviderDescriptor } from "./descriptor.js";
2
- import type { MountKind, Unmounted } from "./mount.js";
3
- import type { ComputerKind, Group, HelloResult } from "./protocol.js";
4
- import type { ComputerCapabilities, NetworkForm } from "./provider.js";
1
+ import { type ProviderDescriptor } from "./descriptor.js";
2
+ import type { Group, HelloResult } from "./protocol.js";
3
+ import type { ComputerCapabilities } from "./provider.js";
5
4
  import type { Result } from "./result.js";
6
- /**
7
- * What an agent is given. none: the run's folder only, no computer. sandbox: a Linux shell with files and processes.
8
- * desktop: a screen, a pointer and keys (Linux, Windows or macOS), a shell when it has one. phone: a screen, touch and
9
- * apps. browser: a CDP target.
10
- */
11
- export type ComputerSettingKind = "none" | "sandbox" | "desktop" | "phone" | "browser";
12
- /** A setting kind's machine kinds and groups. */
13
- export interface SettingKindSpec {
14
- /** The capabilities().kind values that can serve it. */
15
- machineKinds: readonly ComputerKind[];
16
- /** Every one declared, and passing its conformance cases, to serve it. */
17
- required: readonly Group[];
18
- /** Brought when declared. */
19
- optional: readonly Group[];
20
- }
21
- export declare const SETTING_KINDS: Readonly<Record<ComputerSettingKind, SettingKindSpec>>;
22
- /** Every setting kind, in the table's order. */
23
- export declare const SETTING_KIND_NAMES: ComputerSettingKind[];
5
+ import { type ComputerSettingKind } from "./setting-kinds.js";
24
6
  /**
25
7
  * The capabilities serves() and kindOf() read: one configuration a provider offers, with the GPUs it offers (Settings'
26
8
  * GPU choice), and whether it keeps a computer for an agent (`persistence`, as its built provider declares it: Settings'
@@ -53,56 +35,14 @@ export declare function imagesOf(serving: readonly Pick<KindCapabilities, "image
53
35
  * whose image is the kind's default, else one with no image, else the first. Undefined when the image names none.
54
36
  */
55
37
  export declare function configurationOf<Configuration extends Pick<KindCapabilities, "image">>(serving: readonly Configuration[], image: string | undefined, defaultImage: string | undefined): Configuration | undefined;
56
- /** A provider as Settings shows it: its descriptor's data, and the setting kinds it serves. */
57
- export interface ProviderEntry {
58
- /** Its id: a line of the provider registry (providers.ts). */
59
- readonly id: string;
60
- readonly label: string;
61
- /** Derived: the setting kinds its capabilities serve (serves), never written by hand. */
38
+ /**
39
+ * A provider as Settings shows it: its descriptor's data (descriptor.ts documents each field), with `mounts` derived
40
+ * (derivedMounts: sync added where a configuration takes it; [] cannot mount the run's folder), and `kinds`, the setting
41
+ * kinds its capabilities serve (serves), never written by hand.
42
+ */
43
+ export type ProviderEntry = Omit<ProviderDescriptor, "load"> & {
62
44
  readonly kinds: readonly ComputerSettingKind[];
63
- /** The serve-side key names and the options they fill; never a value. */
64
- readonly keys: readonly DescriptorKey[];
65
- /** Settings that are no key but go to its options. */
66
- readonly settings?: readonly DescriptorSetting[];
67
- /** Whether its machines dial the server: always ("dial"), or as its connect option says ("either"); descriptor.ts connectOf. */
68
- readonly connect?: "dial" | "either";
69
- /** The mount kinds its computers take, sync derived (derivedMounts); [] cannot mount the run's folder. */
70
- readonly mounts: readonly MountKind[];
71
- /** Why its computers take none of these mount kinds, each in one sentence (descriptor.ts). */
72
- readonly unmounted?: Unmounted;
73
- /** Mount kinds its computers take only where the operator sets the key named, by kind (descriptor.ts, mountsOf). */
74
- readonly mountsWith?: Readonly<Partial<Record<MountKind, string>>>;
75
- /**
76
- * The network forms its computers make, its descriptor's: ["none"], a remote computer whose programs run in a network
77
- * of their own; ["open"], the vendor's own network, which no allowlist of this server reaches; Docker's all three.
78
- */
79
- readonly network: readonly NetworkForm[];
80
- /** The vendor bills by time; prices are the vendor's page, not ours. */
81
- readonly metered: boolean;
82
- /** Its static capabilities: the machine kind and groups of each configuration it offers. */
83
- readonly capabilities: readonly KindCapabilities[];
84
- /**
85
- * The image a computer of each setting kind starts from when its setting names none. A kind with no entry has no
86
- * default, and the caller refuses the setting in words. Docker's sandbox has none: its image is made (prepareImage).
87
- */
88
- readonly defaultImage?: Partial<Record<ComputerSettingKind, string>>;
89
- /** Its built providers make or pull their image before the first create (prepareImage()). */
90
- readonly prepareImage?: boolean;
91
- /** The server's environment variable whose value, when set, is the image of every computer of it (descriptor.ts). */
92
- readonly imageEnv?: string;
93
- /** Its computers run on this machine's container engine. */
94
- readonly local?: boolean;
95
- /** create() takes a ledger the server keeps for it, as this option. */
96
- readonly ledger?: {
97
- readonly option: string;
98
- };
99
- /** The server's environment variables its provider reads on this machine, passed as options.env (descriptor.ts). */
100
- readonly hostEnv?: readonly string[];
101
- /** A program its computers need on this machine's PATH, and the machines it is built for (descriptor.ts). */
102
- readonly hostCommand?: HostCommand;
103
- /** Configurations it builds but does not offer yet, each with why: a setting naming one's image is refused as parked. */
104
- readonly parked?: readonly ParkedConfiguration[];
105
- }
45
+ };
106
46
  /** A descriptor as Settings shows it: its data, and the setting kinds its capabilities serve, derived by serves(). */
107
47
  export declare function entryOf(descriptor: ProviderDescriptor): ProviderEntry;
108
48
  /** Every provider Settings offers: each built-in descriptor (descriptors/index.ts), as entryOf gives it. */
package/dist/kinds.js CHANGED
@@ -6,17 +6,10 @@
6
6
  // these groups.
7
7
  // The providers Settings offers (PROVIDERS) are derived from the providers' descriptors (descriptor.ts), each declared
8
8
  // once in its descriptor module: loading this loads descriptors (data) alone, never a provider module or a vendor SDK.
9
+ // The setting kinds themselves (SETTING_KINDS) are a leaf of their own, setting-kinds.ts, which descriptor.ts reads too.
9
10
  import { derivedMounts } from "./descriptor.js";
10
11
  import { DESCRIPTORS } from "./descriptors/index.js";
11
- export const SETTING_KINDS = {
12
- none: { machineKinds: [], required: [], optional: [] },
13
- sandbox: { machineKinds: ["linux"], required: ["exec", "files", "processes"], optional: [] },
14
- desktop: { machineKinds: ["desktop"], required: ["screen", "input.pointer", "input.keys"], optional: ["exec", "files", "processes", "apps", "ui", "stream"] },
15
- phone: { machineKinds: ["android", "ios"], required: ["screen", "input.touch", "apps"], optional: ["input.keys", "apps.install", "ui", "stream"] },
16
- browser: { machineKinds: ["browser"], required: ["cdp"], optional: ["stream", "downloads"] },
17
- };
18
- /** Every setting kind, in the table's order. */
19
- export const SETTING_KIND_NAMES = Object.keys(SETTING_KINDS);
12
+ import { SETTING_KIND_NAMES, SETTING_KINDS } from "./setting-kinds.js";
20
13
  /** Why capabilities do not serve a setting kind, in words; none when they do. */
21
14
  export function servingRefusals(capabilities, kind) {
22
15
  const spec = Object.hasOwn(SETTING_KINDS, kind) ? SETTING_KINDS[kind] : undefined;
package/dist/modal.js CHANGED
@@ -4,8 +4,8 @@ import { DEFAULT_CPUS, DEFAULT_MEMORY_MB, WORK } from "./drift.js";
4
4
  import { HostError } from "./host.js";
5
5
  import { HostedProvider } from "./hosted/provider.js";
6
6
  import { AGENTRUN_DIAL, PID_WRAPPER, pidKill, pidStderr } from "./hosted/scripts.js";
7
- import { connectOf } from "./descriptor.js";
8
- import { execDesktopRefusal, isWhole } from "./hosted/values.js";
7
+ import { connectOf, kindRefusal } from "./descriptor.js";
8
+ import { isWhole } from "./hosted/values.js";
9
9
  import { ok } from "./result.js";
10
10
  /** A GPU as the SDK takes it: the type, then :count past one ("T4", "H100:8"). */
11
11
  const modalGpu = ({ type, count }) => (count === 1 ? type : `${type}:${count}`);
@@ -363,8 +363,9 @@ export class ModalProvider extends HostedProvider {
363
363
  if (typeof app !== "string" || app.trim() === "")
364
364
  throw new Error("options.app, the Modal app's name, is required");
365
365
  const via = connectOf(MODAL, { connect });
366
- if (rest.kind === "desktop" && via === "exec")
367
- throw new Error(execDesktopRefusal("Modal", "the box image"));
366
+ const refused = kindRefusal(MODAL, { kind: rest.kind, connect: via });
367
+ if (refused !== undefined)
368
+ throw new Error(refused);
368
369
  super(new ModalHost(sdk, app, via), { ...rest, timeouts: { ...MODAL_TIMEOUTS, ...timeouts } });
369
370
  }
370
371
  }
@@ -0,0 +1,19 @@
1
+ import type { ComputerKind, Group } from "./protocol.js";
2
+ /**
3
+ * What an agent is given. none: the run's folder only, no computer. sandbox: a Linux shell with files and processes.
4
+ * desktop: a screen, a pointer and keys (Linux, Windows or macOS), a shell when it has one. phone: a screen, touch and
5
+ * apps. browser: a CDP target.
6
+ */
7
+ export type ComputerSettingKind = "none" | "sandbox" | "desktop" | "phone" | "browser";
8
+ /** A setting kind's machine kinds and groups. */
9
+ export interface SettingKindSpec {
10
+ /** The capabilities().kind values that can serve it. */
11
+ machineKinds: readonly ComputerKind[];
12
+ /** Every one declared, and passing its conformance cases, to serve it. */
13
+ required: readonly Group[];
14
+ /** Brought when declared. */
15
+ optional: readonly Group[];
16
+ }
17
+ export declare const SETTING_KINDS: Readonly<Record<ComputerSettingKind, SettingKindSpec>>;
18
+ /** Every setting kind, in the table's order. */
19
+ export declare const SETTING_KIND_NAMES: ComputerSettingKind[];
@@ -0,0 +1,9 @@
1
+ export const SETTING_KINDS = {
2
+ none: { machineKinds: [], required: [], optional: [] },
3
+ sandbox: { machineKinds: ["linux"], required: ["exec", "files", "processes"], optional: [] },
4
+ desktop: { machineKinds: ["desktop"], required: ["screen", "input.pointer", "input.keys"], optional: ["exec", "files", "processes", "apps", "ui", "stream"] },
5
+ phone: { machineKinds: ["android", "ios"], required: ["screen", "input.touch", "apps"], optional: ["input.keys", "apps.install", "ui", "stream"] },
6
+ browser: { machineKinds: ["browser"], required: ["cdp"], optional: ["stream", "downloads"] },
7
+ };
8
+ /** Every setting kind, in the table's order. */
9
+ export const SETTING_KIND_NAMES = Object.keys(SETTING_KINDS);
@@ -0,0 +1,21 @@
1
+ import { HostedProvider, type HostedOptions } from "./hosted/provider.js";
2
+ import { type Result } from "./result.js";
3
+ /** The smol cloud provider's options: the key, then the shared adapter's (HostedOptions). */
4
+ export interface SmolcloudProviderOptions extends Omit<HostedOptions, "kind" | "desktop"> {
5
+ /** The smol cloud API key. The caller passes it; this provider never reads it from the environment. */
6
+ apiKey: string;
7
+ /** The REST API; default https://api.smolmachines.com. */
8
+ apiUrl?: string;
9
+ /** The fetch every call goes through; default the global one. */
10
+ fetch?: typeof fetch;
11
+ }
12
+ export declare function create(options: SmolcloudProviderOptions): Promise<SmolcloudProvider>;
13
+ export declare const conformance: () => Promise<typeof import("./conformance/smolcloud.js")>;
14
+ export declare class SmolcloudProvider extends HostedProvider {
15
+ /**
16
+ * The provider contract's prepareImage (its descriptor declares it): the box image the release publishes, by its
17
+ * public registry tag (box-image.ts). No call: smol cloud pulls it at each create.
18
+ */
19
+ prepareImage(): Promise<Result<string>>;
20
+ constructor(options: SmolcloudProviderOptions);
21
+ }
@@ -0,0 +1,254 @@
1
+ // The smol cloud host: machines on smol cloud (https://smolmachines.com), each a microVM booted from an OCI image,
2
+ // over its REST API (https://api.smolmachines.com, a Bearer key). The exec is a resumable exec started interactive
3
+ // (POST /v1/machines/{id}/execs): the machine's node owns the process, its output is read by offset with a long poll
4
+ // (GET .../execs/{execId}?after=N&wait=25), stdout and stderr apart and the exit code last, stdin is numbered base64
5
+ // frames (POST .../stdin, at most 64 KiB each, resent safely), and DELETE kills it. Labels are smol cloud's own (32 at
6
+ // most, listed with ?label=k=v, changed with PATCH .../labels); the idle stop is off (autoStopSeconds 0) and the delete
7
+ // timer (ttlSeconds) is set to the request's backstop. The rest of the computer is the shared machine-host adapter's.
8
+ import { randomBytes } from "node:crypto";
9
+ import { boxImageRef } from "./box-image.js";
10
+ import { SMOLCLOUD } from "./descriptors/smolcloud.js";
11
+ import { DEADLINE_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
12
+ import { HostError } from "./host.js";
13
+ import { framedExec } from "./hosted/framed-exec.js";
14
+ import { networkFormOf } from "./hosted/network.js";
15
+ import { orThrow, pause } from "./hosted/process.js";
16
+ import { HostedProvider } from "./hosted/provider.js";
17
+ import { jsonOf, rest } from "./hosted/rest.js";
18
+ import { shellLine } from "./hosted/scripts.js";
19
+ import { ok } from "./result.js";
20
+ export async function create(options) {
21
+ return new SmolcloudProvider(options);
22
+ }
23
+ export const conformance = () => import("./conformance/smolcloud.js");
24
+ const DEFAULT_API_URL = "https://api.smolmachines.com";
25
+ /** smol cloud never ends a machine itself once its idle stop is off: the janitor's cap. */
26
+ const DAY_MS = 24 * 60 * 60_000;
27
+ /** Every machine's name starts with this, so an account's own machines and a computer's are told apart. */
28
+ const NAME_PREFIX = "agr-";
29
+ /** A stdin frame's bytes: under the API's 64 KiB, base64 or not. */
30
+ const FRAME_BYTES = 48 * 1024;
31
+ /** One long poll: the API holds it up to 25 s; the call's bound is past that. */
32
+ const POLL_WAIT_S = 25;
33
+ const POLL_MS = 40_000;
34
+ const STDIN_MS = 30_000;
35
+ /** How long the output read waits out reads that fail before it gives up: a control plane down this long is down. */
36
+ const READ_GIVE_UP_MS = 5 * 60_000;
37
+ /** smol cloud's label name (validate.rs label_key) and the most characters of a label's value. */
38
+ const LABEL_KEY = /^[a-z0-9]([a-z0-9._/-]{0,61}[a-z0-9])?$/;
39
+ const LABEL_VALUE_CHARS = 255;
40
+ /** A string's length as smol cloud counts it: in characters (code points), not UTF-16 units or bytes. */
41
+ const chars = (text) => [...text].length;
42
+ /** smol cloud's states (machines.rs) as the adapter's; deleted is a record that won't come back, so none. */
43
+ const STATES = {
44
+ creating: "starting",
45
+ started: "running",
46
+ created: "stopped",
47
+ stopped: "stopped",
48
+ pausing: "stopped",
49
+ paused: "stopped",
50
+ error: "gone",
51
+ deleting: "gone",
52
+ deleted: undefined,
53
+ };
54
+ function machineOf(one) {
55
+ if (!(one.state in STATES))
56
+ return { id: one.id, labels: { ...(one.labels ?? {}) }, state: "stopped", why: `smol cloud reads its state as ${one.state}` };
57
+ const state = STATES[one.state];
58
+ if (state === undefined)
59
+ return undefined;
60
+ const created = one.createdAt ? new Date(one.createdAt) : undefined;
61
+ return {
62
+ id: one.id,
63
+ labels: { ...(one.labels ?? {}) },
64
+ state,
65
+ ...(created && !Number.isNaN(created.getTime()) ? { createdAt: created } : {}),
66
+ ...(state === "gone" && one.error ? { why: one.error } : {}),
67
+ };
68
+ }
69
+ class SmolcloudHost {
70
+ descriptor = SMOLCLOUD;
71
+ facts = {
72
+ daemon: "child",
73
+ isolation: "microvm",
74
+ lifetime: "janitor",
75
+ maxLifetimeMs: DAY_MS,
76
+ // Placement is pinned to amd64 at create (source.arch), so the daemon uploaded matches the node.
77
+ arch: "amd64",
78
+ // smol cloud's agent in the guest is reached over vsock, not TCP.
79
+ vendorAgentPorts: [],
80
+ labels: { count: 32 },
81
+ };
82
+ #api;
83
+ constructor(options) {
84
+ const { apiKey } = options;
85
+ this.#api = rest({
86
+ base: options.apiUrl,
87
+ headers: () => ({ Authorization: `Bearer ${apiKey}`, Accept: "application/json" }),
88
+ vendor: "smolcloud",
89
+ ...(options.fetch ? { fetch: options.fetch } : {}),
90
+ timeoutMs: 30_000,
91
+ retry: { attempts: 3, baseMs: 500 },
92
+ // The error body is RFC 9457 problem details: its detail is the words (OpenAPI ErrorResponse). The account's cap
93
+ // on machines at once answers 422, its code the status's own, so it is read by its words.
94
+ explain: ({ status, bytes, what }) => {
95
+ const detail = jsonOf(bytes)?.detail;
96
+ const words = typeof detail === "string" ? detail : "";
97
+ return { ...(words.startsWith("concurrency limit reached") ? { code: "limit" } : {}), message: `${what} answered ${status}${words ? `: ${words}` : ""}` };
98
+ },
99
+ });
100
+ }
101
+ async #call(method, path, json, ctx, extra = {}) {
102
+ const answer = orThrow(await this.#api.call(method, this.#api.url(path), { ...(json === undefined ? {} : { json }), timeoutMs: ctx.timeoutMs, ...extra }, ctx.signal));
103
+ return jsonOf(answer.bytes);
104
+ }
105
+ async create(req, ctx) {
106
+ const made = await this.#call("POST", "/v1/machines", {
107
+ name: `${NAME_PREFIX}${req.name}`,
108
+ source: { type: "image", reference: req.image, arch: this.facts.arch },
109
+ labels: req.labels,
110
+ resources: { cpus: req.cpus ?? DEFAULT_CPUS, memoryMb: req.memoryMb ?? DEFAULT_MEMORY_MB },
111
+ autoStopSeconds: 0,
112
+ ttlSeconds: Math.max(1, Math.ceil((Date.parse(req.backstopAt) - Date.now()) / 1000)),
113
+ start: true,
114
+ }, ctx, { named: true });
115
+ return { id: made.id };
116
+ }
117
+ async get(id, ctx) {
118
+ return machineOf(await this.#call("GET", `/v1/machines/${encodeURIComponent(id)}`, undefined, ctx, { retry: true }));
119
+ }
120
+ async list(labels, ctx) {
121
+ const query = Object.entries(labels).map(([key, value]) => `label=${encodeURIComponent(`${key}=${value}`)}`);
122
+ const listed = await this.#call("GET", `/v1/machines${query.length > 0 ? `?${query.join("&")}` : ""}`, undefined, ctx, { retry: true });
123
+ return listed.map(machineOf).filter((one) => one !== undefined);
124
+ }
125
+ async delete(id, ctx) {
126
+ await this.#call("DELETE", `/v1/machines/${encodeURIComponent(id)}`, undefined, ctx, { retry: true });
127
+ }
128
+ exec(id, argv, ctx) {
129
+ const base = `/v1/machines/${encodeURIComponent(id)}/execs`;
130
+ let seq = 0;
131
+ // Aborted by kill() before its DELETE, so the output read stops even when the DELETE cannot reach smol cloud.
132
+ const killed = new AbortController();
133
+ const frame = (execId, json) => this.#call("POST", `${base}/${execId}/stdin`, { seq: ++seq, ...json }, { timeoutMs: STDIN_MS }, { retry: true });
134
+ return framedExec({
135
+ start: async (argv, ctx) => {
136
+ const execId = `agr${randomBytes(12).toString("hex")}`;
137
+ // smol cloud refuses an argv with an empty word (400 "command arguments cannot be empty"), which the adapter's
138
+ // scripts pass for an unset option: such an argv runs as one quoted line under /bin/sh -c.
139
+ const command = argv.includes("") ? ["/bin/sh", "-c", `exec ${shellLine(argv)}`] : argv;
140
+ // Safe to send again: smol cloud answers a start retried with the same execId with the session the first try made,
141
+ // never running the command twice (its OpenAPI, POST /v1/machines/{id}/execs).
142
+ await this.#call("POST", base, { execId, command, interactive: true }, ctx, { retry: true });
143
+ return execId;
144
+ },
145
+ events: (execId) => this.#events(base, execId, killed.signal),
146
+ write: async (execId, text) => {
147
+ const bytes = Buffer.from(text, "utf8");
148
+ for (let at = 0; at < bytes.length; at += FRAME_BYTES)
149
+ await frame(execId, { data: bytes.subarray(at, at + FRAME_BYTES).toString("base64") });
150
+ },
151
+ end: async (execId) => void (await frame(execId, { eof: true })),
152
+ kill: async (execId) => {
153
+ killed.abort();
154
+ await this.#call("DELETE", `${base}/${execId}`, undefined, { timeoutMs: STDIN_MS }, { retry: true });
155
+ },
156
+ }, argv, ctx);
157
+ }
158
+ /**
159
+ * A resumable exec's output from its start, read by offset; its exit code last, when it ended with one. It ends when
160
+ * killed aborts, and throws once no read has been answered for READ_GIVE_UP_MS.
161
+ */
162
+ async *#events(base, execId, killed) {
163
+ let after = 0;
164
+ let answeredAt = Date.now();
165
+ for (;;) {
166
+ let read;
167
+ try {
168
+ read = await this.#call("GET", `${base}/${execId}?after=${after}&wait=${POLL_WAIT_S}`, undefined, { timeoutMs: POLL_MS, signal: killed }, { retry: true });
169
+ }
170
+ catch (error) {
171
+ if (killed.aborted)
172
+ return;
173
+ const code = error instanceof HostError ? error.code : "vendor";
174
+ if (code === "not_found")
175
+ return;
176
+ // A node or control that restarts keeps the output: read again from the same offset.
177
+ if (code !== "timeout" && code !== "vendor" && code !== "limit")
178
+ throw error;
179
+ if (Date.now() - answeredAt >= READ_GIVE_UP_MS) {
180
+ throw new Error(`smol cloud answered no read of exec ${execId}'s output for ${READ_GIVE_UP_MS / 60_000} minutes, so it is read no more: the last answer was ${error.message}`);
181
+ }
182
+ await pause(1_000, killed);
183
+ continue;
184
+ }
185
+ answeredAt = Date.now();
186
+ if (read.lost)
187
+ throw new Error(`smol cloud no longer holds part of exec ${execId}'s output: ${JSON.stringify(read.lost)}`);
188
+ for (const chunk of read.output ?? [])
189
+ yield { stream: chunk.stream === "stderr" ? "stderr" : "stdout", base64: chunk.data };
190
+ if (typeof read.next === "number")
191
+ after = read.next;
192
+ if (read.done) {
193
+ if (typeof read.exitCode === "number")
194
+ yield { exit: read.exitCode };
195
+ return;
196
+ }
197
+ }
198
+ }
199
+ /** The daemon's upload through the files API (PUT .../files/{path}), not exec's stdin: 8 MiB there takes about 40 s. */
200
+ async upload(id, path, bytes, ctx) {
201
+ const guest = path.split("/").filter(Boolean).map(encodeURIComponent).join("/");
202
+ await this.#call("PUT", `/v1/machines/${encodeURIComponent(id)}/files/${guest}`, undefined, ctx, { retry: true, bytes: new Uint8Array(bytes) });
203
+ }
204
+ /** The janitor's deadline label, moved (PATCH .../labels changes the keys it names alone). */
205
+ async extend(id, endsAt, ctx) {
206
+ await this.#call("PATCH", `/v1/machines/${encodeURIComponent(id)}/labels`, { labels: { [DEADLINE_LABEL]: endsAt.toISOString() } }, ctx);
207
+ }
208
+ /**
209
+ * An image is an OCI reference; labels are what smol cloud takes (validate.rs): a name of 1 to 63 of a-z, 0-9 and
210
+ * ._/-, starting and ending with a letter or digit, and a value of at most 255 characters, the image and the network
211
+ * list among them (the adapter stores both as label values). Their count, the adapter's own among them, is the
212
+ * adapter's to check (facts.labels).
213
+ */
214
+ check(spec) {
215
+ const refusals = [];
216
+ const { image, labels, network } = spec;
217
+ if (image !== undefined && (typeof image !== "string" || image.trim() === ""))
218
+ refusals.push({ field: "image", message: "a smol cloud image is an OCI reference, such as alpine:3.20" });
219
+ else if (typeof image === "string" && chars(image) > LABEL_VALUE_CHARS)
220
+ refusals.push({ field: "image", message: `smol cloud keeps the image in a label of at most ${LABEL_VALUE_CHARS} characters, and this one has ${chars(image)}` });
221
+ const entries = labels !== null && typeof labels === "object" ? Object.entries(labels) : [];
222
+ const keys = entries.filter(([key]) => !LABEL_KEY.test(key)).map(([key]) => show(key));
223
+ if (keys.length > 0)
224
+ refusals.push({ field: "labels", message: `smol cloud takes label names of 1 to 63 of a-z, 0-9 and ._/-, starting and ending with a letter or digit: ${keys.join(", ")}` });
225
+ const long = entries.filter(([, value]) => typeof value === "string" && chars(value) > LABEL_VALUE_CHARS).map(([key, value]) => `${show(key)} has ${chars(value)}`);
226
+ if (long.length > 0)
227
+ refusals.push({ field: "labels", message: `smol cloud takes label values of at most ${LABEL_VALUE_CHARS} characters: ${long.join(", ")}` });
228
+ let form = "";
229
+ try {
230
+ form = network === undefined ? "" : networkFormOf(network);
231
+ }
232
+ catch {
233
+ // A network the adapter refuses itself, in its own words.
234
+ }
235
+ if (chars(form) > LABEL_VALUE_CHARS)
236
+ refusals.push({ field: "network", message: `smol cloud keeps the network list in a label of at most ${LABEL_VALUE_CHARS} characters, and this one comes to ${chars(form)}: name fewer hosts` });
237
+ return refusals;
238
+ }
239
+ }
240
+ export class SmolcloudProvider extends HostedProvider {
241
+ /**
242
+ * The provider contract's prepareImage (its descriptor declares it): the box image the release publishes, by its
243
+ * public registry tag (box-image.ts). No call: smol cloud pulls it at each create.
244
+ */
245
+ async prepareImage() {
246
+ return ok(boxImageRef());
247
+ }
248
+ constructor(options) {
249
+ const { apiKey, apiUrl = DEFAULT_API_URL, fetch, maxLifetimeMs = DAY_MS, ...rest } = options ?? {};
250
+ if (typeof apiKey !== "string" || apiKey === "")
251
+ throw new Error("options.apiKey, the smol cloud API key, is required: the provider reads no environment, so the caller passes it");
252
+ super(new SmolcloudHost({ apiKey, apiUrl, ...(fetch ? { fetch } : {}) }), { ...rest, maxLifetimeMs });
253
+ }
254
+ }