@parcha/agentrun-computer 0.1.0-beta.62 → 0.1.0-beta.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -615,10 +615,20 @@ by its rectangle), so a longer one ends the connection before anything is alloca
615
615
  desktop files of `$XDG_DATA_HOME/applications` and each of `$XDG_DATA_DIRS` (default `~/.local/share`, then
616
616
  `/usr/local/share` and `/usr/share`), as the Desktop Entry spec says: the apps there are, by their desktop file ids
617
617
  (`org.xfce.mousepad`), with their names; hidden and `NoDisplay` entries, and a `TryExec` that is not there, are left
618
- out. Its `foreground` is the app of the window manager's active window, else of the top window. `apps.launch({ id,
619
- url? })` takes an id, a name (`Mousepad`) or a program (`mousepad`), starts the entry's `Exec` (`url` in its `%u`/`%f`
620
- field; an entry with none refuses a `url` as `invalid`) as `process.start` does with orphans `keep`, with `DISPLAY`,
621
- and answers `{}` once a new window of the app shows, raised and focused (through the window manager's
618
+ out. So is an app whose desktop file computerd's own user could change: on the way to it from `/`, every symbolic
619
+ link followed, the user owns a folder, a link or the file, or the mode bits or the kernel (`faccessat2`, which reads
620
+ ACLs) let it write the file or a folder holding one of them (a sticky folder only where it owns what is in it), or
621
+ computerd runs as root. The entry is read from the file that walk checked, opened without following a link and
622
+ refused if another took its place, and read again for each launch. An app runs what its desktop file says, so such a
623
+ file, written through `files`, would run any command with exec off: `apps.launch` and `apps.terminate` refuse such an
624
+ app by its id as `denied`, naming the file and why (a refused file is not read, so its name finds nothing), though
625
+ `apps.terminate` still ends one this computerd launched before its file was refused. Its `foreground` is the
626
+ app of the window manager's active window, else of the top window. `apps.launch({ id, url? })` takes an id, a name
627
+ (`Mousepad`) or a program (`mousepad`), starts the entry's `Exec` (`url` in its `%u`/`%f` field; an entry with none
628
+ refuses a `url` as `invalid`; a `url` is an absolute URL with a scheme, `https://…` or `file:///…`, or an absolute
629
+ path, `/…`, and anything else, such as a leading `-` or a relative path, is refused `invalid` and nothing starts; the
630
+ surface refuses a leading `-` itself, before the call leaves it) as `process.start` does with orphans `keep`, with
631
+ `DISPLAY`, and answers `{}` once a new window of the app shows, raised and focused (through the window manager's
622
632
  `_NET_ACTIVE_WINDOW` when one runs, waiting up to 2 s for it to be the active window), so keys typed right after
623
633
  reach it; none within 10 s is `timeout`, "no window within 10 s", and the app runs on. An
624
634
  app already running with a window is brought to the front and answers at once, unless a `url` is given. A
@@ -2667,9 +2677,12 @@ newer browser has ended, the lost create's is left running for that create, at o
2667
2677
  Otherwise the request's browsers are read again, every 2 s for up to half of `cleanupMs` (once at least, and sooner
2668
2678
  when that half is under 2 s). While every newer one still runs, no converge has answered it (each such create kept its
2669
2679
  own), and at the end it is released. On the first read as on every later one, a newer one that has ended counts before
2670
- an older one that runs, since a converge whose list missed the older may have answered it. A read that fails, or a read again that misses the lost create's
2671
- browser or every newer one, says nothing of who holds it and leaves it running; a first read that fails is tried again
2672
- within the same half before that. The search's own retries, for a vendor that lists a browser late, wait within that
2680
+ an older one that runs, since a converge whose list missed the older may have answered it. That keeps one held by none
2681
+ too: where three creates of a request ran, the newest's converge may have answered the oldest and ended its own, and
2682
+ the lost create's, the middle one, then runs to the vendor's lifetime; its failure says that an older one still runs.
2683
+ A read that fails, or that misses the lost create's browser, or a read again that misses every newer one, says nothing
2684
+ of who holds it and leaves it running; a first read that fails or misses it is tried again within the same half before
2685
+ that. The search's own retries, for a vendor that lists a browser late, wait within that
2673
2686
  half too, so the release keeps the other half.
2674
2687
  Browserbase is asked status by status in a session's own order (pending, then running, then the ended ones), so a
2675
2688
  session that moves on while a list runs is found in a later answer, never missed, and one found in two answers reads as
package/dist/agent37.d.ts CHANGED
@@ -34,6 +34,7 @@ export interface Agent37Instance {
34
34
  image_digest?: string | null;
35
35
  type?: string;
36
36
  region?: string;
37
+ /** The shape: cpu in vCPUs, memory and disk in GB (docs: instances/object). */
37
38
  resources?: {
38
39
  cpu?: number;
39
40
  memory?: number;
package/dist/agent37.js CHANGED
@@ -181,7 +181,20 @@ function stateOf(status) {
181
181
  return "gone";
182
182
  return undefined;
183
183
  }
184
- /** An instance as the adapter reads a machine: its state (a status it does not know is gone, in words), labels, start. */
184
+ /** A positive finite figure of Agent37's answer, else undefined (absent, zero or not a number: never guessed). */
185
+ const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined);
186
+ /** What Agent37 says an instance was given (Machine.resources), the shape it bills by: its vCPUs, its memory (GB, as MB)
187
+ * and its disk (GB), each where its answer says it (docs: instances/object, resources); none where it says nothing. */
188
+ function resourcesOf(given) {
189
+ const [cpus, memory, disk] = [figure(given?.cpu), figure(given?.memory), figure(given?.disk)];
190
+ const resources = {
191
+ ...(cpus === undefined ? {} : { cpus }),
192
+ ...(memory === undefined ? {} : { memoryMb: memory * 1024 }),
193
+ ...(disk === undefined ? {} : { diskGb: disk }),
194
+ };
195
+ return Object.keys(resources).length > 0 ? { resources } : {};
196
+ }
197
+ /** An instance as the adapter reads a machine: its state (a status it does not know is gone, in words), labels, start, size. */
185
198
  function machineOf(instance) {
186
199
  const state = stateOf(instance.status);
187
200
  // A failed instance always carries a why, Agent37's or ours, so create stops on it as vendor, never as gone.
@@ -194,6 +207,7 @@ function machineOf(instance) {
194
207
  state: state ?? "gone",
195
208
  ...(created ? { createdAt: created } : {}),
196
209
  ...(why === undefined || (state !== undefined && state !== "gone") ? {} : { why }),
210
+ ...resourcesOf(instance.resources),
197
211
  };
198
212
  }
199
213
  /** The shape a request's cpus and memoryMb ask for, or undefined when they ask for none of Agent37's. */
package/dist/browser.d.ts CHANGED
@@ -110,11 +110,14 @@ export declare function leftToConverge(mine: string, made: ReadonlyArray<MadeBro
110
110
  /**
111
111
  * Where a lost create's browser left to a converge (leftToConverge) stands when the request's browsers are read again:
112
112
  * "unread" when the read lists neither mine nor any newer one (the first read did, so it says nothing); "release" once
113
- * mine has ended; "answered" when a newer one has ended, since a converge that answers the older ends its own first, and
114
- * one whose list missed an older browser may have answered mine; "release" when an older one runs and every newer one
115
- * runs too; "running" while every newer one still runs, so no converge has answered mine yet.
113
+ * mine has ended; "answered" when a newer one has ended, since a converge that answers the older ends its own first;
114
+ * "answered-older" when an older one also runs, since that converge may have missed the older and answered mine, or
115
+ * answered the older and left mine held by none; "release" when an older one runs and every newer one runs too;
116
+ * "running" while every newer one still runs, so no converge has answered mine yet.
116
117
  */
117
- export declare function convergeSettled(mine: string, made: ReadonlyArray<MadeBrowser>): "answered" | "running" | "release" | "unread";
118
+ export declare function convergeSettled(mine: string, made: ReadonlyArray<MadeBrowser>): Settled;
119
+ /** What a read of a lost create's request says of its browser (convergeSettled). */
120
+ type Settled = "answered" | "answered-older" | "running" | "release" | "unread";
118
121
  /**
119
122
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
120
123
  * makes nothing). A request not answered, aborted, cut short, or answered 5xx or with a body that is no browser may
@@ -131,10 +134,10 @@ export declare const RECOVER_MS = 30000;
131
134
  * of the recovery's own, `ms` in all (the caller's may be what ended the create). The search, its retries for a vendor
132
135
  * that lists late and the reads below wait at most until half of `ms` has passed, each wait RECOVER_GAP_MS or what is
133
136
  * left of that half, so the release keeps the other half. Where `made` reads the request's browsers (ended ones
134
- * included), each found browser's request is read, again after a failed read, and one that cannot be read is kept: a
135
- * failed read says nothing of who holds it. One older than a browser of its request that has ended (convergeSettled) is
136
- * kept at once, even when an older one runs, as a converge that answers it ends its own first and one whose list missed
137
- * the older may have answered it. One left to another create's converge (leftToConverge) is otherwise read again,
137
+ * included), each found browser's request is read, again after a read that failed or did not list it, and one no read
138
+ * lists is kept: such a read says nothing of who holds it. One older than a browser of its request that has ended
139
+ * (convergeSettled) is kept at once, even when an older one runs, as a converge that answers it ends its own first and
140
+ * one whose list missed the older may have answered it; where an older one runs, the words say it may be held by none. One left to another create's converge (leftToConverge) is otherwise read again,
138
141
  * every RECOVER_GAP_MS within that half (once at least), and kept once a newer one has ended or a read fails or misses
139
142
  * a browser the first read listed. One whose newer browsers all still run at the end was answered by no converge (each
140
143
  * kept its own) and is released. The words say what became of them, for the create's failure; they never carry a URL.
@@ -282,3 +285,4 @@ export declare const pointerOk: (pointer: unknown) => pointer is string;
282
285
  * carry a pointer.
283
286
  */
284
287
  export declare function browserSpecRefusals(session: unknown, features: BrowserFeatures, vendor: string): Refusal[];
288
+ export {};
package/dist/browser.js CHANGED
@@ -122,9 +122,10 @@ export function leftToConverge(mine, made) {
122
122
  /**
123
123
  * Where a lost create's browser left to a converge (leftToConverge) stands when the request's browsers are read again:
124
124
  * "unread" when the read lists neither mine nor any newer one (the first read did, so it says nothing); "release" once
125
- * mine has ended; "answered" when a newer one has ended, since a converge that answers the older ends its own first, and
126
- * one whose list missed an older browser may have answered mine; "release" when an older one runs and every newer one
127
- * runs too; "running" while every newer one still runs, so no converge has answered mine yet.
125
+ * mine has ended; "answered" when a newer one has ended, since a converge that answers the older ends its own first;
126
+ * "answered-older" when an older one also runs, since that converge may have missed the older and answered mine, or
127
+ * answered the older and left mine held by none; "release" when an older one runs and every newer one runs too;
128
+ * "running" while every newer one still runs, so no converge has answered mine yet.
128
129
  */
129
130
  export function convergeSettled(mine, made) {
130
131
  const own = made.find((one) => one.id === mine);
@@ -135,9 +136,10 @@ export function convergeSettled(mine, made) {
135
136
  const newer = made.filter((one) => one.id !== mine && oldestBrowserFirst(own, one) < 0);
136
137
  if (newer.length === 0)
137
138
  return "unread";
139
+ const olderRuns = made.some((one) => one.id !== mine && one.live && oldestBrowserFirst(one, own) < 0);
138
140
  if (newer.some((one) => !one.live))
139
- return "answered";
140
- return made.some((one) => one.id !== mine && one.live && oldestBrowserFirst(one, own) < 0) ? "release" : "running";
141
+ return olderRuns ? "answered-older" : "answered";
142
+ return olderRuns ? "release" : "running";
141
143
  }
142
144
  /**
143
145
  * Whether a create that threw may still have made a browser: anything but the vendor's own 4xx answer (a refusal, which
@@ -160,10 +162,10 @@ const RECOVER_GAP_MS = 2_000;
160
162
  * of the recovery's own, `ms` in all (the caller's may be what ended the create). The search, its retries for a vendor
161
163
  * that lists late and the reads below wait at most until half of `ms` has passed, each wait RECOVER_GAP_MS or what is
162
164
  * left of that half, so the release keeps the other half. Where `made` reads the request's browsers (ended ones
163
- * included), each found browser's request is read, again after a failed read, and one that cannot be read is kept: a
164
- * failed read says nothing of who holds it. One older than a browser of its request that has ended (convergeSettled) is
165
- * kept at once, even when an older one runs, as a converge that answers it ends its own first and one whose list missed
166
- * the older may have answered it. One left to another create's converge (leftToConverge) is otherwise read again,
165
+ * included), each found browser's request is read, again after a read that failed or did not list it, and one no read
166
+ * lists is kept: such a read says nothing of who holds it. One older than a browser of its request that has ended
167
+ * (convergeSettled) is kept at once, even when an older one runs, as a converge that answers it ends its own first and
168
+ * one whose list missed the older may have answered it; where an older one runs, the words say it may be held by none. One left to another create's converge (leftToConverge) is otherwise read again,
167
169
  * every RECOVER_GAP_MS within that half (once at least), and kept once a newer one has ended or a read fails or misses
168
170
  * a browser the first read listed. One whose newer browsers all still run at the end was answered by no converge (each
169
171
  * kept its own) and is released. The words say what became of them, for the create's failure; they never carry a URL.
@@ -188,18 +190,23 @@ export async function recoverCreate(what, find, release, sleep, ms = RECOVER_MS,
188
190
  for (const id of found.value) {
189
191
  let unanswered = false;
190
192
  if (made !== undefined) {
191
- const read = await firstRead(made, signal, sleep, settleBy, Math.max(1, Math.ceil(ms / 2 / RECOVER_GAP_MS)));
193
+ const read = await firstRead(id, made, signal, sleep, settleBy, Math.max(1, Math.ceil(ms / 2 / RECOVER_GAP_MS)));
192
194
  if (read === undefined) {
193
- words.push(`the ${what} it made (${id}) may be one another create of its request answered, and the request's browsers could not be read, so nothing says who holds it: it is left running, at most to its lifetime, and its labels let a sweep find it`);
195
+ words.push(`the ${what} it made (${id}) may be one another create of its request answered, and the request's browsers could not be read, or did not list it, so nothing says who holds it: it is left running, at most to its lifetime, and its labels let a sweep find it`);
194
196
  continue;
195
197
  }
196
- const answered = convergeSettled(id, read) === "answered";
198
+ const first = convergeSettled(id, read);
199
+ const answered = first === "answered" || first === "answered-older";
197
200
  if (answered || leftToConverge(id, read)) {
198
- const settled = answered ? "answered" : await settle(id, made, signal, sleep, settleBy, reads);
201
+ const settled = answered ? first : await settle(id, made, signal, sleep, settleBy, reads);
199
202
  if (settled === "answered") {
200
203
  words.push(`the ${what} it made (${id}) is older than one of its request that has ended, as a create's converge ends its own when it answers an older one: it is left running for that create, and if that create did not answer it (aborted, or failed once its own had ended, or its reply lost too) it runs to its lifetime, and its labels let a sweep find it`);
201
204
  continue;
202
205
  }
206
+ if (settled === "answered-older") {
207
+ words.push(`the ${what} it made (${id}) is older than one of its request that has ended, and an older one of its request still runs: the create whose own ended may have missed that one and answered this, so it is left running, and if that create answered the older instead it is held by none and runs to its lifetime; its labels let a sweep find it`);
208
+ continue;
209
+ }
203
210
  if (settled === "unread") {
204
211
  words.push(`the ${what} it made (${id}) is its request's oldest, which another create of the request may answer, and the request's browsers could not be read again: it is left running, at most to its lifetime, and its labels let a sweep find it`);
205
212
  continue;
@@ -230,16 +237,17 @@ async function waitWithin(sleep, by, signal) {
230
237
  return true;
231
238
  }
232
239
  /**
233
- * The request's browsers, read at once and then again after each failed read, `retries` times at most, each after a
234
- * wait that ends no later than `by` (waitWithin): so a window shorter than two gaps still tries again while time is left.
235
- * Undefined when no read answered.
240
+ * The request's browsers, read at once and then again after each read that failed or did not list `mine` (which the
241
+ * search found, so such a read says nothing of it), `retries` times at most, each after a wait that ends no later than
242
+ * `by` (waitWithin): so a window shorter than two gaps still tries again while time is left. Undefined when no read
243
+ * listed it.
236
244
  */
237
- async function firstRead(made, signal, sleep, by, retries) {
245
+ async function firstRead(mine, made, signal, sleep, by, retries) {
238
246
  for (let read = 0; read <= retries; read++) {
239
247
  if (read > 0 && !(await waitWithin(sleep, by, signal)))
240
248
  break;
241
249
  const got = await made(signal);
242
- if (got.ok)
250
+ if (got.ok && got.value.some((one) => one.id === mine))
243
251
  return got.value;
244
252
  }
245
253
  return undefined;
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "0.1.0-beta.62",
3
- "source": "sha256:724f889fc95233b98e71e6ff4456498fb220f704db4ca2caed5772e3984ba4de"
2
+ "version": "0.1.0-beta.64",
3
+ "source": "sha256:ca76a29aaa9ab0216cefc6badb124b6ab39a5a0094b984fa8d26537633ccad1e"
4
4
  }
package/dist/host.d.ts CHANGED
@@ -215,8 +215,9 @@ export interface Machine {
215
215
  createdAt?: Date;
216
216
  /** The vendor's words for a machine that is gone because it failed: a create stops in them. */
217
217
  why?: string;
218
- /** What the vendor's answer says the machine was given (its CPUs, memory, disk, GPUs), where it says it: a create
219
- * returns these as its computer's resources. Absent where the answer says none. */
218
+ /** What the vendor's answer says the machine was given (its CPUs, memory, disk, GPUs), where it says it, or the
219
+ * limits its create set where the vendor reads none back and bills by use up to them (ComputerResources): a create
220
+ * returns these as its computer's resources. Absent where neither says any. */
220
221
  resources?: ComputerResources;
221
222
  }
222
223
  /** A process exec started: its output as it comes, its stdin, and its end. */
@@ -268,7 +269,12 @@ export interface HostFacts {
268
269
  * list by, the map in parts of at most valueBytes each), unpacks those get and list answer, and asks list for that
269
270
  * name alone; the host stores and answers them as they are. count and bytes are then the packed labels'. unpacked:
270
271
  * the host's machines may also carry their labels as given (made before it packed): one with no packed map reads as
271
- * its stored labels, and a listing by name asks for the labels as given beside the packed name.
272
+ * its stored labels, and a listing by name asks for the labels as given beside the packed name. named: the host's
273
+ * machine names carry the run and epoch labels beside the adapter's name (Render's), so a create's sweeps for the
274
+ * machine it made (the wait to be listed, the sweep after a failed create) ask for its run and epoch too where its
275
+ * spec has both, and the host can look up the one whole name; the machines kept are still those whose get carries the
276
+ * name's labels. Its first check and convergence ask by the name alone: they look for the request's machine whatever
277
+ * run or epoch it was made with.
272
278
  */
273
279
  labels?: {
274
280
  count?: number;
@@ -277,6 +283,7 @@ export interface HostFacts {
277
283
  valueBytes?: number;
278
284
  unpacked?: true;
279
285
  };
286
+ named?: true;
280
287
  };
281
288
  /**
282
289
  * Paths of the vendor's image that root runs or reads and whose permissions its template build sets wider than
@@ -186,15 +186,17 @@ export declare class HostedProvider implements ComputerProvider {
186
186
  * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
187
187
  * its machines' labels unpacked. A listing by name on a host whose machines may also carry their labels as given
188
188
  * (facts.labels.packed.unpacked) asks both ways, one after the other within ms together, and answers every machine
189
- * either finds: across an upgrade one request can make one machine of each form, and convergence must see both.
189
+ * either finds: across an upgrade one request can make one machine of each form, and convergence must see both. `also`:
190
+ * labels a host that doesn't pack them is asked beside these, which only narrow its search (nameAsk): never required of
191
+ * a machine.
190
192
  */
191
- export declare function listedBy(host: MachineHost, what: string, labels: Record<string, string>, ms: number, signal?: AbortSignal): Promise<Result<Machine[]>>;
193
+ export declare function listedBy(host: MachineHost, what: string, labels: Record<string, string>, ms: number, signal?: AbortSignal, also?: Record<string, string>): Promise<Result<Machine[]>>;
192
194
  /**
193
195
  * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
194
196
  * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
195
- * not every label. A get that fails fails the whole listing.
197
+ * not every label. A get that fails fails the whole listing. `also`: as listedBy's.
196
198
  */
197
- export declare function foundBy(host: MachineHost, what: string, labels: Record<string, string>, { listMs, requestMs }: Pick<HostedTimeouts, "listMs" | "requestMs">, signal?: AbortSignal): Promise<Result<Machine[]>>;
199
+ export declare function foundBy(host: MachineHost, what: string, labels: Record<string, string>, { listMs, requestMs }: Pick<HostedTimeouts, "listMs" | "requestMs">, signal?: AbortSignal, also?: Record<string, string>): Promise<Result<Machine[]>>;
198
200
  /**
199
201
  * Waits, through waitUntil, until get answers none for a machine after its delete, twice running: the vendor no longer
200
202
  * has it. A machine read gone is still going (a vendor still destroying it), so it holds the wait like any other state.
@@ -554,6 +554,8 @@ export class HostedProvider {
554
554
  }
555
555
  /** taken: the vendor refused this create's name as one a machine has (exists), so the name's machine is read once more. */
556
556
  async #createOnce(spec, name, signal, taken) {
557
+ // By the request's name alone, never narrowed by this spec's run and epoch (nameAsk): the request's computer made
558
+ // under another run or epoch is found, and refused as exists by #again, never made twice.
557
559
  const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
558
560
  if (!listed.ok)
559
561
  return listed;
@@ -629,6 +631,8 @@ export class HostedProvider {
629
631
  * more than one machine holds the name, the oldest (createdAt, or the lowest id where any has none) is kept, and every
630
632
  * other is deleted and read back gone, its Archil folder let go first. Every instance picks the same one from the
631
633
  * same listing. Its value is the machine kept, or undefined when mine holds the name alone (or nothing is listed yet).
634
+ * The listing is by the name alone, never narrowed (nameAsk): two creates of one request that ask another run or epoch
635
+ * must still see each other's machine, so one is kept and the other answered exists.
632
636
  */
633
637
  async #converge(name, mine, signal) {
634
638
  const listed = await foundBy(this.host, "the listing by the request's name", byName(name), this.#timeouts, signal);
@@ -791,7 +795,7 @@ export class HostedProvider {
791
795
  const { createMs } = this.#timeouts;
792
796
  // Never signalled, only raced: an aborted call could leave a machine made whose id never came back. One that lands
793
797
  // after this gave up is deleted by its id; one that fails after it, by its name where it may have made one.
794
- const created = await hostCall(this.host, `${this.#label}'s create`, (ctx) => this.host.create(request, { timeoutMs: ctx.timeoutMs }), createMs, signal, (made) => made.ok ? this.#kill(made.value.id) : mayHaveMade(made.error.code) ? this.#deleteNamed(name) : undefined);
798
+ const created = await hostCall(this.host, `${this.#label}'s create`, (ctx) => this.host.create(request, { timeoutMs: ctx.timeoutMs }), createMs, signal, (made) => made.ok ? this.#kill(made.value.id) : mayHaveMade(made.error.code) ? this.#deleteNamed(name, nameAsk(this.host, spec)) : undefined);
795
799
  if (!created.ok) {
796
800
  // A machine of this create's that lands after this never dials: its token goes with the create.
797
801
  await this.#revoke(name);
@@ -803,7 +807,7 @@ export class HostedProvider {
803
807
  if (!mayHaveMade(code))
804
808
  return created;
805
809
  this.#end(name);
806
- const swept = await this.#deleteNamed(name);
810
+ const swept = await this.#deleteNamed(name, nameAsk(this.host, spec));
807
811
  return this.#fail(code, `${this.#label} did not create the machine: ${message}${swept}`);
808
812
  }
809
813
  this.#requests.made(name);
@@ -855,14 +859,15 @@ export class HostedProvider {
855
859
  * Every machine carrying a name create gave, deleted and read back gone: for a create that may have made one whose
856
860
  * id never came (mayHaveMade), never after a refusal, where a machine under the name is another's. The
857
861
  * listing shows a new machine a moment after the vendor makes it, so it is read for the name until one shows or
858
- * listedMs passes, as create's own wait reads it. Best effort, in words.
862
+ * listedMs passes, as create's own wait reads it. Best effort, in words. `also`: this create's run and epoch
863
+ * (nameAsk), which a machine it made carries in its name.
859
864
  */
860
- async #deleteNamed(name) {
865
+ async #deleteNamed(name, also) {
861
866
  const { listedMs, pollMs } = this.#timeouts;
862
867
  const until = Date.now() + listedMs;
863
868
  let found;
864
869
  for (let delay = Math.min(LISTED_POLL_MS, pollMs);; delay = Math.min(delay * 2, pollMs)) {
865
- const listed = await foundBy(this.host, "the listing by name", byName(name), this.#timeouts);
870
+ const listed = await foundBy(this.host, "the listing by name", byName(name), this.#timeouts, undefined, also);
866
871
  if (!listed.ok)
867
872
  return `; a machine named ${name} may be left (${listed.error.message}), which ends at its deadline`;
868
873
  found = listed.value.filter((machine) => ours(machine.labels, name));
@@ -1042,7 +1047,7 @@ export class HostedProvider {
1042
1047
  finally {
1043
1048
  await opened.value.close();
1044
1049
  }
1045
- const listed = await this.#waitListed(ref, signal);
1050
+ const listed = await this.#waitListed(ref, signal, nameAsk(this.host, spec));
1046
1051
  return listed.ok ? ok([...closed, ...dialNotes, ...notes, ...listed.value]) : listed;
1047
1052
  }
1048
1053
  /** What init wrote to its log (child) or the vendor's words of the machine (pid1): the end of it, or nothing. */
@@ -1344,14 +1349,14 @@ export class HostedProvider {
1344
1349
  * The polls are 150 ms apart at first, the pause doubling up to pollMs, so a vendor slow to list costs a few calls.
1345
1350
  * A listing that has not settled by listedMs is no failure alone (#unlisted): the computer is read by its id.
1346
1351
  */
1347
- async #waitListed(ref, signal) {
1352
+ async #waitListed(ref, signal, also) {
1348
1353
  const { listedMs, listMs, pollMs, listedStableMs } = this.#timeouts;
1349
1354
  const began = Date.now();
1350
1355
  const until = began + listedMs;
1351
1356
  let since;
1352
1357
  const seen = { polls: 0, shown: 0 };
1353
1358
  for (let hits = 0, delay = Math.min(LISTED_POLL_MS, pollMs);; delay = Math.min(delay * 2, pollMs)) {
1354
- const listed = await listedBy(this.host, "the listing by name", byName(ref.name), listMs, signal);
1359
+ const listed = await listedBy(this.host, "the listing by name", byName(ref.name), listMs, signal, also);
1355
1360
  if (!listed.ok)
1356
1361
  return listed;
1357
1362
  seen.polls += 1;
@@ -1767,6 +1772,18 @@ export class HostedProvider {
1767
1772
  }
1768
1773
  /** The labels a listing by one computer's name asks for. */
1769
1774
  const byName = (name) => ({ [COMPUTER_LABEL]: "1", [NAME_LABEL]: name });
1775
+ /**
1776
+ * What a listing by a create's name asks beside byName on a host whose names carry the run and epoch (facts.labels.named):
1777
+ * the spec's run and epoch, where it has both, so the host can look up the whole name. Only asked, never required: a
1778
+ * machine of the name is kept whatever its get says of them (a sandbox before its labels file, read by its name alone).
1779
+ * Only the sweeps for a machine this create made ask it (#waitListed, #deleteNamed): that machine's name is the whole
1780
+ * name. The first check and #converge look for any machine of the request, whatever run or epoch it was made with.
1781
+ */
1782
+ function nameAsk(host, spec) {
1783
+ const run = spec.labels?.[RUN_LABEL];
1784
+ const epoch = spec.labels?.[EPOCH_LABEL];
1785
+ return host.facts.labels?.named && typeof run === "string" && typeof epoch === "string" ? { [RUN_LABEL]: run, [EPOCH_LABEL]: epoch } : undefined;
1786
+ }
1770
1787
  /** The room of a host that keeps its labels packed (facts.labels.packed), or undefined. */
1771
1788
  function packedRoom(host) {
1772
1789
  const room = host.facts.labels;
@@ -1787,12 +1804,14 @@ function unpacked(host, machine) {
1787
1804
  * may answer more (MachineHost.list). A packed host is asked for PACKED_NAME alone, the name's where one is asked, and
1788
1805
  * its machines' labels unpacked. A listing by name on a host whose machines may also carry their labels as given
1789
1806
  * (facts.labels.packed.unpacked) asks both ways, one after the other within ms together, and answers every machine
1790
- * either finds: across an upgrade one request can make one machine of each form, and convergence must see both.
1807
+ * either finds: across an upgrade one request can make one machine of each form, and convergence must see both. `also`:
1808
+ * labels a host that doesn't pack them is asked beside these, which only narrow its search (nameAsk): never required of
1809
+ * a machine.
1791
1810
  */
1792
- export async function listedBy(host, what, labels, ms, signal) {
1811
+ export async function listedBy(host, what, labels, ms, signal, also) {
1793
1812
  const name = labels[NAME_LABEL];
1794
1813
  const room = packedRoom(host);
1795
- const asks = room === undefined ? [labels] : name === undefined ? [{}] : room.packed?.unpacked ? [{ [PACKED_NAME]: name }, labels] : [{ [PACKED_NAME]: name }];
1814
+ const asks = room === undefined ? [{ ...also, ...labels }] : name === undefined ? [{}] : room.packed?.unpacked ? [{ [PACKED_NAME]: name }, labels] : [{ [PACKED_NAME]: name }];
1796
1815
  const until = Date.now() + ms;
1797
1816
  const found = new Map();
1798
1817
  for (const asked of asks) {
@@ -1810,10 +1829,10 @@ const carries = (machine, labels) => Object.entries(labels).every(([key, value])
1810
1829
  /**
1811
1830
  * The listing finds, get answers (MachineHost.list): the machines the host's listing by labels names, each read now by
1812
1831
  * readMachine, within requestMs. One the vendor no longer has (not found) is dropped, and so is one whose get carries
1813
- * not every label. A get that fails fails the whole listing.
1832
+ * not every label. A get that fails fails the whole listing. `also`: as listedBy's.
1814
1833
  */
1815
- export async function foundBy(host, what, labels, { listMs, requestMs }, signal) {
1816
- const listed = await listedBy(host, what, labels, listMs, signal);
1834
+ export async function foundBy(host, what, labels, { listMs, requestMs }, signal, also) {
1835
+ const listed = await listedBy(host, what, labels, listMs, signal, also);
1817
1836
  if (!listed.ok)
1818
1837
  return listed;
1819
1838
  const reads = await Promise.all(listed.value.map(({ id }) => readMachine(host, id, requestMs, signal)));
package/dist/modal.js CHANGED
@@ -89,6 +89,15 @@ const CPU_REQUEST = 0.125;
89
89
  const MEMORY_REQUEST_MIB = 128;
90
90
  /** "1 core = 2 vCPUs" (guide/sandbox-resources): a spec's cpus are CPUs, Modal's cpu is physical cores. */
91
91
  const CPUS_PER_CORE = 2;
92
+ /**
93
+ * A sandbox's size, as its computer is priced: the limits its create set (`cpuLimit` in cores, as vCPUs, and
94
+ * `memoryLimitMiB`), read from the very params the create sends. Modal reads no size back, and bills a sandbox by
95
+ * max(request, use) up to those limits, so the limit is the most its time can cost (ComputerResources).
96
+ */
97
+ const sizeOf = (params) => ({
98
+ ...(params.cpuLimit === undefined ? {} : { cpus: params.cpuLimit * CPUS_PER_CORE }),
99
+ ...(params.memoryLimitMiB === undefined ? {} : { memoryMb: params.memoryLimitMiB }),
100
+ });
92
101
  /**
93
102
  * Modal's bounds over the adapter's: a create builds the image layer and waits for the sandbox to be scheduled, a
94
103
  * terminate is asynchronous, and the daemon is streamed in through exec.
@@ -121,6 +130,9 @@ class ModalHost {
121
130
  #appName;
122
131
  /** Each sandbox create or a read gave, by id: let go of at its delete. */
123
132
  #sandboxes = new Map();
133
+ /** Each sandbox's size, by id, from the limits its create set (sizeOf): this provider's creates alone, let go of at
134
+ * its delete. A sandbox another process made has none here, and is read with no size. */
135
+ #sizes = new Map();
124
136
  #app;
125
137
  constructor(sdk, app, connect) {
126
138
  this.#sdk = sdk;
@@ -230,12 +242,13 @@ class ModalHost {
230
242
  const image = base.dockerfileCommands([`ENV HOME=${WORK}`, `WORKDIR ${WORK}`]);
231
243
  const sandbox = await this.#sdk.sandboxes.create((await this.#theApp(true)), image, params);
232
244
  this.#sandboxes.set(sandbox.sandboxId, sandbox);
245
+ this.#sizes.set(sandbox.sandboxId, sizeOf(params));
233
246
  return { id: sandbox.sandboxId };
234
247
  }
235
248
  /**
236
- * The sandbox as a machine: running while poll reads null (sandbox.ts:2761-2771), its labels from its tags. One that
237
- * has finished, or that Modal no longer knows, is none: a finished sandbox cannot run again. Modal reads no network,
238
- * size or GPU back.
249
+ * The sandbox as a machine: running while poll reads null (sandbox.ts:2761-2771), its labels from its tags, its size
250
+ * the limits its create set (sizeOf) where this provider made it. One that has finished, or that Modal no longer
251
+ * knows, is none: a finished sandbox cannot run again. Modal reads no network, size or GPU back.
239
252
  */
240
253
  async get(id, ctx) {
241
254
  void ctx;
@@ -246,7 +259,8 @@ class ModalHost {
246
259
  try {
247
260
  if ((await sandbox.poll()) !== null)
248
261
  return undefined;
249
- return { id: sandbox.sandboxId, labels: await sandbox.getTags(), state: "running" };
262
+ const size = this.#sizes.get(sandbox.sandboxId);
263
+ return { id: sandbox.sandboxId, labels: await sandbox.getTags(), state: "running", ...(size === undefined ? {} : { resources: size }) };
250
264
  }
251
265
  catch (error) {
252
266
  if (codeOf(error) === "not_found")
@@ -290,7 +304,10 @@ class ModalHost {
290
304
  */
291
305
  async delete(id, ctx) {
292
306
  void ctx;
293
- const sandbox = await this.#sandbox(id).finally(() => this.#sandboxes.delete(id));
307
+ const sandbox = await this.#sandbox(id).finally(() => {
308
+ this.#sandboxes.delete(id);
309
+ this.#sizes.delete(id);
310
+ });
294
311
  try {
295
312
  await sandbox.terminate();
296
313
  }
@@ -618,7 +618,11 @@ export interface AppsInstallParams {
618
618
  export interface AppsLaunchParams {
619
619
  /** A bundle id or a package name: "com.apple.Notes", "com.android.settings". */
620
620
  id: string;
621
- /** Open this in the app: a deep link, or a page in a browser. */
621
+ /**
622
+ * Open this in the app: a deep link, or a page in a browser. On Linux, an absolute URL with a scheme (https://…,
623
+ * file:///…) or an absolute path (/…); anything else, such as a leading "-" or a relative path, is refused `invalid`
624
+ * and nothing starts.
625
+ */
622
626
  url?: string;
623
627
  /** Open it without bringing it to the front (feature apps.background). Without the feature, refused as `unsupported`. */
624
628
  background?: boolean;
@@ -300,7 +300,9 @@ export interface ReadBackSpec {
300
300
  export type ReadBackNotes = string[];
301
301
  /**
302
302
  * What a computer was given, as its vendor's own answer for it says (its get or create answer): the figures the vendor
303
- * bills by. Each field is absent where the vendor's answer does not say it, never guessed from what was asked.
303
+ * bills by. Each field is absent where the vendor's answer does not say it, never guessed from what was asked. One
304
+ * exception: a provider whose vendor reads no size back and bills a computer by its use, up to limits its create set
305
+ * (Modal), gives those limits, the most the computer's time can bill.
304
306
  */
305
307
  export interface ComputerResources {
306
308
  cpus?: number;
package/dist/render.js CHANGED
@@ -9,9 +9,14 @@
9
9
  // the machine's own token, which stays in the sandbox's env. The rest of the computer is the shared machine-host
10
10
  // adapter's (./hosted/provider.ts).
11
11
  //
12
- // Render's sandboxes carry no labels: a sandbox's name (computer-<12 hex>) gives the adapter's own two, and create writes
13
- // every label to a file in the sandbox, root's alone, which get and list read back through runs/sync where a label asked
14
- // is not the name's, and keep: a computer's labels never change (Render moves no timeout, so there is no extend).
12
+ // Render's sandboxes carry no labels: a sandbox's name (computer-<12 hex>-r<run hash>-e<epoch>) gives the adapter's own
13
+ // two and says whose run and epoch it may be, and create writes every label to a file in the sandbox, root's alone, which
14
+ // get and list read back through runs/sync where a label asked is not the name's, and keep for the whole process: a
15
+ // computer's labels never change (Render moves no timeout, so there is no extend). That read needs a healthy guest, so
16
+ // one that fails, or has no answer within the call's own bound, gives get the name's two: enough for release to find and
17
+ // terminate a wedged sandbox, never a reason it is left to bill to its timeout. A listing by a label beyond the name's
18
+ // fails closed on it instead, naming the sandbox: it can't tell whether that one is a match. A listing by run reads only
19
+ // the sandboxes whose name has the run's hash (and the epoch asked), so only the run's own can fail it.
15
20
  //
16
21
  // Every vendor fact below is from @renderinc/sdk 1.11.0's OpenAPI schema (dist/generated/schema.d.ts, S) or its client
17
22
  // (dist/sandboxes/index.js, C), a live probe (11-25: root, HOME=/root, a Render kernel, egress https, and a command
@@ -19,30 +24,108 @@
19
24
  // dial-conformance.mjs: the sandbox's env reaches a runs/sync command, root makes network namespaces in the microVM, the
20
25
  // builds API imports the public ghcr.io box image with no credential, and a process escaped with setsid ends with the
21
26
  // sandbox's release). One none of these settles says unverified.
27
+ import { createHash } from "node:crypto";
22
28
  import { boxImageRef, boxRecipeHash } from "./box-image.js";
23
29
  import { RENDER } from "./descriptors/render.js";
24
30
  import { COMPUTER_LABEL, DEFAULT_CPUS, DEFAULT_MEMORY_MB, show } from "./drift.js";
25
31
  import { HostError } from "./host.js";
26
- import { codeOfError, orThrow, pause, seconds, until } from "./hosted/process.js";
32
+ import { codeOfError, orThrow, pause, seconds, until, untilAborted } from "./hosted/process.js";
27
33
  import { HostedProvider, mayHaveMade, NAME_LABEL, timeoutsOf } from "./hosted/provider.js";
28
34
  import { allPages, jsonOf, rest } from "./hosted/rest.js";
29
35
  import { dialLaunch } from "./hosted/scripts.js";
30
36
  import { dateOf, isWhole } from "./hosted/values.js";
37
+ import { EPOCH_LABEL, RUN_LABEL, runHash } from "./labels.js";
31
38
  import { failFor, ok, vendorFail } from "./result.js";
39
+ /**
40
+ * The box build's find-or-import under way in this process, by workspace, key and box image (owner id, the key's
41
+ * keyTag, build name, image tag): every provider of the workspace and key joins it, one of another key (a wrong one's
42
+ * 401) never, and it is dropped once it settles. Render's own POST answers a build of the same name and digest already
43
+ * pending, running or succeeded (S, create-sandbox-build), so this saves the calls, not a second build.
44
+ */
45
+ const FLIGHTS = new Map();
46
+ /** A key as a map key: the first 16 hex digits of its sha256, never the key. */
47
+ const keyTag = (apiKey) => createHash("sha256").update(apiKey, "utf8").digest("hex").slice(0, 16);
48
+ /** Kept, by workspace (owner id). */
49
+ const KEPT = new Map();
50
+ function keptOf(owner) {
51
+ let kept = KEPT.get(owner);
52
+ if (kept === undefined)
53
+ KEPT.set(owner, (kept = { labels: new Map(), ending: new Set() }));
54
+ return kept;
55
+ }
32
56
  const API_URL = "https://api.render.com";
33
57
  /**
34
58
  * S: ownerId, a workspace id (tea-… for a team, usr-… for a person). Held to an id's characters alone, since it goes in
35
59
  * every query: whether it names a workspace the key reaches is Render's answer to the first call.
36
60
  */
37
61
  const OWNER_ID = /^[A-Za-z0-9_-]{1,64}$/;
38
- /** S: sandboxId, "sbx-1cd4gcph1rs3idesc73a2b2mg"; held to that form before it reaches a path. */
39
- const SANDBOX_ID = /^sbx-[a-z0-9]{10,40}$/;
40
62
  /** S: sandboxBuildId, sbb-…; a build's name may not start with sbb- (S, sandbox-groups/{id}/builds), so this reads as an id. */
41
63
  const BUILD_ID = /^sbb-[a-z0-9]{10,40}$/;
42
64
  /** A build's name, 1 to 255 characters (S); held to letters, digits, dots, underscores and hyphens, so an OCI path is not one. */
43
65
  const BUILD_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
44
- /** The name the adapter gives a computer (provider.ts computerName): only a sandbox named so is one of its computers. */
45
- const COMPUTER_NAME = /^computer-[0-9a-f]{12}$/;
66
+ /**
67
+ * A computer's sandbox name: the adapter's name for it (computer-<12 hex>, computerNameFor), then -r<its run's hash>
68
+ * and -e<its epoch> where its labels carry them, as Orgo's names do (orgo-names.ts): at most 57 characters of Render's 64
69
+ * (S, sandboxPOST name). Only a sandbox named so is one of its computers.
70
+ */
71
+ const SANDBOX_NAME = /^(computer-[0-9a-f]{12})(?:-r([a-z2-7]{16}))?(?:-e(0|[1-9][0-9]{0,15}))?$/;
72
+ /** The run's hash a sandbox of these labels is named with: "" for none. */
73
+ function runPart(labels) {
74
+ const run = labels[RUN_LABEL];
75
+ return typeof run === "string" && run !== "" ? runHash(run) : "";
76
+ }
77
+ /** The epoch a sandbox of these labels is named with: "" for none, or one that is not a whole number. */
78
+ function epochPart(labels) {
79
+ const epoch = labels[EPOCH_LABEL];
80
+ return typeof epoch === "string" && /^(?:0|[1-9][0-9]{0,15})$/.test(epoch) ? epoch : "";
81
+ }
82
+ /** A computer's sandbox name for create's request: its name, then its run label's hash and its epoch label where they are one. */
83
+ function sandboxName({ name, labels }) {
84
+ const run = runPart(labels);
85
+ const epoch = epochPart(labels);
86
+ return `${name}${run === "" ? "" : `-r${run}`}${epoch === "" ? "" : `-e${epoch}`}`;
87
+ }
88
+ /**
89
+ * The whole sandbox name a listing asks for, where it asks the adapter's name, a run and a whole-number epoch: Render's
90
+ * own exact name filter then finds it, no page of the workspace's other sandboxes read. Undefined where it asks less.
91
+ */
92
+ function wholeName(labels) {
93
+ const name = labels[NAME_LABEL];
94
+ if (name === undefined || runPart(labels) === "" || epochPart(labels) === "")
95
+ return undefined;
96
+ return sandboxName({ name, labels });
97
+ }
98
+ /**
99
+ * Where a labels file says another run or epoch than its sandbox's name, why, in words; undefined where it agrees. The
100
+ * name is Render's, set at create; the file is the guest's root's to rewrite, so one that disagrees is not read.
101
+ */
102
+ function misnamed(parts, file) {
103
+ const found = [];
104
+ if ((parts.run ?? "") !== runPart(file))
105
+ found.push(`run: the name's run hash ${show(parts.run)} is not the labels file's run ${show(file[RUN_LABEL])}`);
106
+ if ((parts.epoch ?? "") !== epochPart(file))
107
+ found.push(`epoch: the name says ${show(parts.epoch)}, the labels file ${show(file[EPOCH_LABEL])}`);
108
+ return found.length === 0 ? undefined : found.join("; ");
109
+ }
110
+ /** What a sandbox's name says: the adapter's name, the run's hash and the epoch; undefined for a sandbox not named as a computer. */
111
+ function nameParts(name) {
112
+ const match = typeof name === "string" ? SANDBOX_NAME.exec(name) : null;
113
+ if (match === null)
114
+ return undefined;
115
+ return { computer: match[1], ...(match[2] ? { run: match[2] } : {}), ...(match[3] !== undefined ? { epoch: match[3] } : {}) };
116
+ }
117
+ /**
118
+ * Whether a sandbox so named can carry these labels: one of a name, a run or an epoch other than those asked can't, so
119
+ * a listing never reads its guest, and a guest that can't answer refuses no listing it could not be in. A run's own
120
+ * sandboxes always have its hash, so a hash another run shares (16 base32 letters, 80 bits) only adds a sandbox to be
121
+ * read, whose file then says its run, or which fails the listing closed: it never leaves one of the run's out.
122
+ */
123
+ function mayCarry(parts, labels) {
124
+ const name = labels[NAME_LABEL];
125
+ const run = labels[RUN_LABEL];
126
+ const epoch = labels[EPOCH_LABEL];
127
+ return (name === undefined || parts.computer === name) && (run === undefined || parts.run === runHash(run)) && (epoch === undefined || parts.epoch === epoch);
128
+ }
46
129
  /** S, sandboxPlan: the sizes a sandbox takes, smallest first. */
47
130
  const PLANS = [
48
131
  { plan: "1c-2g", cpus: 1, memoryMb: 2048 },
@@ -57,6 +140,10 @@ const MAX_LIFETIME_MS = 24 * 60 * 60_000;
57
140
  /** One page of a listing (S, limitParam: 1 to 100). */
58
141
  const PAGE = 100;
59
142
  const MAX_PAGES = 100;
143
+ /** How many labels files a listing reads at once: each is a run token and a runs/sync call, and a workspace's runs are rate limited (S, 429RateLimit). */
144
+ const LABEL_READS = 4;
145
+ /** S, sandboxBuildStatus: a build of these has, or will have, the box image; failed is imported again. */
146
+ const BUILD_LIVE = ["succeeded", "pending", "running"];
60
147
  /** How long the box image's import may take (C's own wait for an image is 10 minutes; the box image is about 400 MB). */
61
148
  const BUILD_MS = 30 * 60_000;
62
149
  /** How long a failed create's terminate of the sandbox it made may take: create's own bound may be spent by then. */
@@ -139,11 +226,30 @@ function machineOf(found, labels) {
139
226
  ...resourcesOf(found.plan),
140
227
  };
141
228
  }
142
- /** An id held to Render's form before it reaches a path: not_found else. */
143
- function sandboxId(id) {
144
- if (!SANDBOX_ID.test(id))
229
+ /** Whether an id Render answered can be one path segment: any string but none, `.` and `..` (which a URL resolves away). */
230
+ const segmentable = (id) => typeof id === "string" && id !== "" && id !== "." && id !== "..";
231
+ /**
232
+ * A sandbox id as one path segment, encoded: Render's ids read sbx-… (S, sandboxId), but one of another form is still
233
+ * read and terminated by it, never left running because this host did not know the form. One that can't be a segment
234
+ * is no sandbox: not_found.
235
+ */
236
+ function sandboxPath(id) {
237
+ if (!segmentable(id))
145
238
  throw new HostError("not_found", `${JSON.stringify(id)} is not a Render sandbox id`);
146
- return id;
239
+ return encodeURIComponent(id);
240
+ }
241
+ /** Each of items through `each`, at most `most` at once, the answers in the items' order. */
242
+ async function eachAtMost(items, most, each) {
243
+ const answers = new Array(items.length);
244
+ let next = 0;
245
+ const worker = async () => {
246
+ while (next < items.length) {
247
+ const at = next++;
248
+ answers[at] = await each(items[at]);
249
+ }
250
+ };
251
+ await Promise.all(Array.from({ length: Math.min(most, items.length) }, worker));
252
+ return answers;
147
253
  }
148
254
  /** Render's error body (S, error): { id?, message?, code? }. */
149
255
  function explain({ status, bytes, what }) {
@@ -171,14 +277,18 @@ class RenderHost {
171
277
  // The sandbox dials the server: Render's runs take no stdin (S: runs/{sync,stream} take { command }), so there is
172
278
  // no exec and no upload here. Its descriptor's (connectOf).
173
279
  connect: RENDER.connect,
280
+ // A sandbox's name carries its run's hash and its epoch (sandboxName): a create's sweeps for the sandbox it made ask
281
+ // for both, so list asks Render for the whole name rather than reading the workspace's every page.
282
+ labels: { named: true },
174
283
  };
175
284
  #api;
176
285
  #apiKey;
177
286
  #owner;
178
287
  #fetch;
179
288
  #pollMs;
180
- /** Each computer's labels once known, by sandbox id: written by create, or read from the labels file once. */
181
- #labels = new Map();
289
+ /** What this process keeps of the workspace's sandboxes (KEPT): every provider of the workspace shares it. */
290
+ #labels;
291
+ #ending;
182
292
  /** The box build's name once Render read it succeeded: prepareImage asks no more. */
183
293
  #built;
184
294
  constructor(options) {
@@ -187,6 +297,7 @@ class RenderHost {
187
297
  this.#fetch = options.fetch;
188
298
  this.#pollMs = options.pollMs;
189
299
  this.#api = this.#client(API_URL, () => this.#apiKey);
300
+ ({ labels: this.#labels, ending: this.#ending } = keptOf(this.#owner));
190
301
  }
191
302
  /** A REST client whose every call carries `bearer()` as its Bearer token: the API key, or one run's token. */
192
303
  #client(base, bearer) {
@@ -207,7 +318,7 @@ class RenderHost {
207
318
  */
208
319
  async #run(id, command, ctx, once = false) {
209
320
  const end = Date.now() + ctx.timeoutMs;
210
- const minted = (await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxId(id)}/runs/sync/token`), { retry: true }, ctx));
321
+ const minted = (await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxPath(id)}/runs/sync/token`), { retry: true }, ctx));
211
322
  const { uri, token } = minted ?? {};
212
323
  if (typeof uri !== "string" || !uri.startsWith("https://") || typeof token !== "string" || token === "")
213
324
  throw new HostError("vendor", `Render answered no https run URL and token for the sandbox ${id}`);
@@ -219,33 +330,66 @@ class RenderHost {
219
330
  return { stdout: typeof answer.stdout === "string" ? answer.stdout : "", stderr: typeof answer.stderr === "string" ? answer.stderr : "", exit: answer.exit_code };
220
331
  }
221
332
  /**
222
- * A sandbox's labels: the ones this host knows, else its name's, else its labels file's, read once through runs/sync
223
- * and kept. `need`: a listing's labels; when the name's hold every one asked, no file is read. A sandbox not named as a
224
- * computer carries none; one not running, or with no file yet, its name's. A read that fails throws, so a listing
225
- * never answers as though the sandbox were not there.
333
+ * A sandbox's labels: the ones this process knows, else its name's, else its labels file's, read once through runs/sync
334
+ * and kept. `need`: a listing's labels; when the name's hold every one asked, no file is read. The name's are the
335
+ * computer's and its name, and, for a listing by the whole name (wholeName), the run and epoch asked, which that name
336
+ * is made of (the run by its 80-bit hash). A sandbox not named as a computer carries none; one not running, one
337
+ * terminated from this process, or one with no file yet, its name's. A file whose run or epoch is not the name's
338
+ * (misnamed) is not read: the guest's root rewrote it. The read is held to `end` (epoch ms, the call's own bound): one
339
+ * that fails, disagrees with the name, or has no answer by then gives the name's, kept for nothing, so the next read
340
+ * tries again, with `unread`, why: get answers the name's (release needs no more), and a listing fails closed on it.
341
+ * Only the caller's own abort throws.
226
342
  */
227
- async #labelsOf(found, ctx, need) {
228
- const name = found.name;
229
- if (typeof name !== "string" || !COMPUTER_NAME.test(name))
230
- return {};
343
+ async #labelsOf(found, ctx, end, need, whole = false) {
344
+ const parts = nameParts(found.name);
345
+ if (parts === undefined)
346
+ return { labels: {} };
231
347
  const known = this.#labels.get(found.id);
232
348
  if (known !== undefined)
233
- return known;
234
- const own = { [COMPUTER_LABEL]: "1", [NAME_LABEL]: name };
235
- if ((need !== undefined && Object.keys(need).every((key) => key in own)) || found.status !== "running")
236
- return own;
237
- const read = await this.#run(found.id, readFile(LABELS_FILE), ctx);
349
+ return { labels: known };
350
+ const own = { [COMPUTER_LABEL]: "1", [NAME_LABEL]: parts.computer, ...(whole && need ? { [RUN_LABEL]: need[RUN_LABEL], [EPOCH_LABEL]: need[EPOCH_LABEL] } : {}) };
351
+ if ((need !== undefined && Object.keys(need).every((key) => key in own)) || found.status !== "running" || this.#ending.has(found.id))
352
+ return { labels: own };
353
+ const late = { labels: own, unread: `no answer within ${seconds(ctx.timeoutMs)}` };
354
+ const left = end - Date.now();
355
+ if (left <= 0)
356
+ return late;
357
+ const bound = AbortSignal.timeout(left);
358
+ let file;
359
+ try {
360
+ file = await this.#labelsFile(found.id, { timeoutMs: left, signal: ctx.signal ? AbortSignal.any([ctx.signal, bound]) : bound });
361
+ }
362
+ catch (error) {
363
+ if (ctx.signal?.aborted)
364
+ throw error;
365
+ return bound.aborted ? late : { labels: own, unread: error instanceof Error ? error.message : String(error) };
366
+ }
367
+ if (file === undefined)
368
+ return { labels: own };
369
+ const differs = misnamed(parts, file);
370
+ if (differs !== undefined)
371
+ return { labels: own, unread: `the labels file of ${found.id} does not match its name ${found.name}: ${differs}` };
372
+ const labels = { ...file, ...own };
373
+ this.#labels.set(found.id, labels);
374
+ return { labels };
375
+ }
376
+ /** The labels file read through runs/sync: undefined when it is not there yet; a read that fails throws in words. */
377
+ async #labelsFile(id, ctx) {
378
+ const read = await this.#run(id, readFile(LABELS_FILE), ctx);
238
379
  if (read.exit === MISSING)
239
- return own;
380
+ return undefined;
240
381
  if (read.exit !== 0)
241
- throw new HostError("vendor", `reading the labels file of ${found.id} exited ${read.exit}: ${lastWords(read)}`);
382
+ throw new HostError("vendor", `reading the labels file of ${id} exited ${read.exit}: ${lastWords(read)}`);
242
383
  const parsed = jsonOf(new TextEncoder().encode(read.stdout));
243
384
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((value) => typeof value === "string")) {
244
- throw new HostError("vendor", `the labels file of ${found.id} is not a JSON map of strings`);
385
+ throw new HostError("vendor", `the labels file of ${id} is not a JSON map of strings`);
245
386
  }
246
- const labels = { ...parsed, ...own };
247
- this.#labels.set(found.id, labels);
248
- return labels;
387
+ return parsed;
388
+ }
389
+ /** A sandbox Render reads gone: its labels and its terminate are let go. */
390
+ #forget(id) {
391
+ this.#labels.delete(id);
392
+ this.#ending.delete(id);
249
393
  }
250
394
  /**
251
395
  * Any Render build by its name or id (S: buildName, "the newest successful build with this name in the sandbox
@@ -266,16 +410,17 @@ class RenderHost {
266
410
  return refusals;
267
411
  }
268
412
  /**
269
- * POST /v1/sandboxes (S, sandboxPOST): the workspace, the request's name, the smallest plan holding its size, the
270
- * lifetime as timeoutSeconds (at least 60), no idle suspension (0), egress allow-all (the sandbox must reach the
271
- * server; the computer's own programs keep to init's network), the boot env but AGENTRUN_ATTACH_URL as its env, and
272
- * the build. Only a 429, a refusal that made nothing, is sent again: a create that got no answer may have made a
273
- * sandbox, which the adapter finds by its name. Then, once the sandbox reads running within ctx.timeoutMs, one
274
- * runs/sync call writes the labels file and starts agentrun-dial, the URL in its launch script. A sandbox that errors
275
- * or ends first, a launch that fails, or a bound passed, throws: a create that made a machine to the adapter, which
276
- * deletes it by its name. A refusal after the sandbox exists (a run token's 429s past every retry, limit; a 401,
277
- * denied) the adapter reads as a create that made nothing (mayHaveMade), so this terminates the sandbox by its id
278
- * first and throws the refusal in its own code. req.backstopAt is left: Render's timeout ends the sandbox.
413
+ * POST /v1/sandboxes (S, sandboxPOST): the workspace, the request's name with its run's hash and epoch (sandboxName),
414
+ * the smallest plan holding its size, the lifetime as timeoutSeconds (at least 60), no idle suspension (0), egress
415
+ * allow-all (the sandbox must reach the server; the computer's own programs keep to init's network), the boot env but
416
+ * AGENTRUN_ATTACH_URL as its env, and the build. Only a 429, a refusal that made nothing, is sent again: a create that
417
+ * got no answer may have made a sandbox, which the adapter finds by its name. Then, once the sandbox reads running
418
+ * within ctx.timeoutMs, one runs/sync call writes the labels file and starts agentrun-dial, the URL in its launch
419
+ * script. A sandbox that errors or ends first, a launch that fails, or a bound passed, throws: a create that made a
420
+ * machine to the adapter, which deletes it by its name. A refusal after the sandbox exists (a run token's 429s past
421
+ * every retry, limit; a 401, denied) the adapter reads as a create that made nothing (mayHaveMade), so this terminates
422
+ * the sandbox by its id first and throws the refusal in its own code. req.backstopAt is left: Render's timeout ends the
423
+ * sandbox.
279
424
  */
280
425
  async create(req, ctx) {
281
426
  const end = Date.now() + ctx.timeoutMs;
@@ -287,7 +432,7 @@ class RenderHost {
287
432
  const made = (await this.#call("POST", "/v1/sandboxes", {
288
433
  json: {
289
434
  ownerId: this.#owner,
290
- name: req.name,
435
+ name: sandboxName(req),
291
436
  plan: planOf(req.cpus, req.memoryMb),
292
437
  timeoutSeconds: Math.max(LEAST_TIMEOUT_S, Math.ceil(req.lifetimeMs / 1000)),
293
438
  idleTimeoutSeconds: 0,
@@ -298,7 +443,7 @@ class RenderHost {
298
443
  retry: (status) => status === 429,
299
444
  }, ctx));
300
445
  const id = made?.id;
301
- if (typeof id !== "string" || !SANDBOX_ID.test(id))
446
+ if (!segmentable(id))
302
447
  throw new HostError("vendor", `POST /v1/sandboxes answered no sandbox id: ${show(id)}`);
303
448
  this.#labels.set(id, { ...req.labels });
304
449
  try {
@@ -339,29 +484,57 @@ class RenderHost {
339
484
  await pause(this.#pollMs, ctx.signal);
340
485
  if (ctx.signal?.aborted)
341
486
  throw new HostError("aborted", `the wait for the sandbox ${found.id} to run was aborted`);
342
- found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${found.id}`), { retry: true }, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }));
487
+ found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxPath(found.id)}`), { retry: true }, { ...ctx, timeoutMs: Math.max(1, end - Date.now()) }));
343
488
  }
344
489
  }
345
- /** GET /v1/sandboxes/{id}; 404 is not_found, which the adapter reads as none, and a terminated sandbox is none. */
490
+ /**
491
+ * GET /v1/sandboxes/{id}; 404 is not_found, which the adapter reads as none, and a terminated sandbox is none: either
492
+ * lets go of what this process kept of it. Its labels are read within this call's own bound (#labelsOf), and a read that
493
+ * fails gives the name's two: enough for the adapter to know its computer and release it.
494
+ */
346
495
  async get(id, ctx) {
347
- const found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxId(id)}`), { retry: true }, ctx));
496
+ const end = Date.now() + ctx.timeoutMs;
497
+ let found;
498
+ try {
499
+ found = (await this.#call("GET", this.#owned(`/v1/sandboxes/${sandboxPath(id)}`), { retry: true }, ctx));
500
+ }
501
+ catch (error) {
502
+ if (error instanceof HostError && error.code === "not_found")
503
+ this.#forget(id);
504
+ throw error;
505
+ }
348
506
  if (typeof found?.status !== "string")
349
507
  throw new HostError("vendor", `GET /v1/sandboxes/${id} answered no status`);
350
- if (found.status === "terminated")
508
+ if (found.status === "terminated") {
509
+ this.#forget(id);
351
510
  return undefined;
352
- return machineOf(found, await this.#labelsOf(found, ctx));
511
+ }
512
+ return machineOf(found, (await this.#labelsOf(found, ctx, end)).labels);
353
513
  }
354
514
  /**
355
- * GET /v1/sandboxes?ownerId (S, list-sandboxes: terminated ones left out unless asked), by name where the name is
356
- * asked ("exactly this name"), every page by its last item's cursor while a page is full. Only sandboxes named as
357
- * computers; a label asked that is not the name's is read from each running one's labels file (#labelsOf), and only
358
- * those that carry every label asked are answered. A file that can't be read fails the listing in words: a listing
359
- * that left the sandbox out would read as no such computer.
515
+ * GET /v1/sandboxes?ownerId (S, list-sandboxes: terminated ones left out unless asked), every page by its last item's
516
+ * cursor while a page is full. Render filters by an exact name alone, and a sandbox's name carries its run and epoch
517
+ * beside the adapter's: a listing that asks all three (wholeName, as a create's sweeps for the sandbox it made do) asks
518
+ * Render for that name, and the name's labels hold all three, so no file is read; any other is matched here, over
519
+ * every page (MAX_PAGES at most, then it fails). Only sandboxes named as computers whose name may carry the
520
+ * labels asked (mayCarry: the adapter's name, the run's hash and the epoch); a label asked that is not the name's is
521
+ * read from each running one's labels file (#labelsOf), LABEL_READS at once, all within this call's own bound, and only
522
+ * those that carry every label asked are answered. A file that can't be read by then fails the listing closed, once
523
+ * every read has ended, naming each such sandbox and why: the listing can't tell whether it carries the labels asked,
524
+ * and leaving it out would let a run's listing miss a newer epoch's fence or call a partial cleanup whole (janitor.ts
525
+ * releaseOlder). So only a sandbox that may be the run's can fail a listing by run: another run's is never read. A
526
+ * listing by the name alone reads no file, and a sandbox terminated from this process is never read, so neither fails
527
+ * so. What this process kept of a sandbox a listing of the whole workspace no longer shows is let go: Render ended it,
528
+ * at its timeout or by another's hand.
360
529
  */
361
530
  async list(labels, ctx) {
362
- const name = labels[NAME_LABEL];
531
+ const end = Date.now() + ctx.timeoutMs;
532
+ const whole = wholeName(labels);
533
+ // Only what was kept before the listing began is let go: a sandbox made while it ran may not be on its pages.
534
+ const kept = [...new Set([...this.#labels.keys(), ...this.#ending])];
363
535
  const listed = orThrow(await allPages(async (cursor) => {
364
- const page = await this.#api.json("GET", this.#api.url(this.#owned("/v1/sandboxes", { limit: String(PAGE), ...(name === undefined ? {} : { name }), ...(cursor === undefined ? {} : { cursor }) })), { retry: true, timeoutMs: ctx.timeoutMs }, ctx.signal);
536
+ const query = { limit: String(PAGE), ...(whole === undefined ? {} : { name: whole }), ...(cursor === undefined ? {} : { cursor }) };
537
+ const page = await this.#api.json("GET", this.#api.url(this.#owned("/v1/sandboxes", query)), { retry: true, timeoutMs: ctx.timeoutMs }, ctx.signal);
365
538
  if (!page.ok)
366
539
  return page;
367
540
  if (!Array.isArray(page.value))
@@ -371,17 +544,41 @@ class RenderHost {
371
544
  const last = rows.at(-1)?.cursor;
372
545
  return ok({ items, ...(rows.length === PAGE && typeof last === "string" ? { next: last } : {}) });
373
546
  }, MAX_PAGES, { vendor: RENDER.id, what: "Render's sandbox listing" }));
374
- const ours = listed.filter((found) => found.status !== "terminated" && typeof found.name === "string" && COMPUTER_NAME.test(found.name));
375
- const read = await Promise.all(ours.map(async (found) => {
376
- const carried = await this.#labelsOf(found, ctx, labels);
377
- return Object.entries(labels).every(([key, value]) => carried[key] === value) ? machineOf(found, carried) : undefined;
378
- }));
379
- return read.flatMap((machine) => machine ?? []);
547
+ const live = listed.filter((found) => found.status !== "terminated");
548
+ if (whole === undefined) {
549
+ const shown = new Set(live.map(({ id }) => id));
550
+ for (const id of kept)
551
+ if (!shown.has(id))
552
+ this.#forget(id);
553
+ }
554
+ const ours = live.filter((found) => {
555
+ const parts = nameParts(found.name);
556
+ return parts !== undefined && mayCarry(parts, labels);
557
+ });
558
+ const read = await eachAtMost(ours, LABEL_READS, async (found) => ({ found, ...(await this.#labelsOf(found, ctx, end, labels, whole !== undefined)) }));
559
+ const unread = read.flatMap(({ found, unread: why }) => (why === undefined ? [] : [`${found.id}: ${why}`]));
560
+ if (unread.length > 0) {
561
+ const asked = Object.entries(labels).filter(([key]) => key !== COMPUTER_LABEL && key !== NAME_LABEL);
562
+ const carry = unread.length === 1 ? "it carries" : "they carry";
563
+ throw new HostError("vendor", `could not read the labels of ${unread.join("; ")}; the listing can't tell whether ${carry} ${asked.map(([key, value]) => `${key}=${value}`).join(", ")}`);
564
+ }
565
+ return read.flatMap(({ found, labels: carried }) => (Object.entries(labels).every(([key, value]) => carried[key] === value) ? (machineOf(found, carried) ?? []) : []));
380
566
  }
381
- /** POST /v1/sandboxes/{id}/terminate (S: 204, also for one already terminated); a 404 is done to the adapter. */
567
+ /**
568
+ * POST /v1/sandboxes/{id}/terminate (S: 204, also for one already terminated); a 404 is done to the adapter. What this
569
+ * process kept of it stays until get reads it gone: Render may read it running a while yet, and its labels still
570
+ * answer. It is marked ending for every provider of the workspace, so none reads its guest meanwhile.
571
+ */
382
572
  async delete(id, ctx) {
383
- await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxId(id)}/terminate`), { retry: true }, ctx);
384
- this.#labels.delete(id);
573
+ try {
574
+ await this.#call("POST", this.#owned(`/v1/sandboxes/${sandboxPath(id)}/terminate`), { retry: true }, ctx);
575
+ }
576
+ catch (error) {
577
+ if (error instanceof HostError && error.code === "not_found")
578
+ this.#forget(id);
579
+ throw error;
580
+ }
581
+ this.#ending.add(id);
385
582
  }
386
583
  /** The end of what agentrun-dial wrote, through runs/sync; undefined where it was never started. */
387
584
  async dialLog(id, ctx) {
@@ -435,24 +632,84 @@ class RenderHost {
435
632
  }
436
633
  /**
437
634
  * The box image as a build of the workspace's default sandbox group (the group a create that names none uses, S),
438
- * named agentrun-box-<recipe hash>, so a new recipe is a new build: a succeeded one of that name is kept (GET
439
- * …/builds?name&status=succeeded), else POST …/builds { name, sourceImage } imports the box image's public tag (S: "converts
440
- * a container image into an image that sandboxes can use"), and Render's answer is read until it succeeded or failed.
441
- * `building` is told before the import. Render pulls the public ghcr.io image with no credential (the live Core run's
442
- * import took 104 s); a tag the release has not published yet is Render's 400, "source image unavailable".
635
+ * named agentrun-box-<recipe hash>, so a new recipe is a new build. Concurrent callers in this process share one
636
+ * find-or-import per workspace, key and box image (FLIGHTS), whichever provider they call through (serve makes one per
637
+ * claim), forgotten once it settles. `building` is told once, before the wait on an import, its own or one under way
638
+ * when it joined; a caller's signal ends its own wait alone: the import's wait goes on, within BUILD_MS, for the next
639
+ * caller.
443
640
  */
444
641
  async boxBuild(building, signal) {
445
642
  if (this.#built !== undefined)
446
643
  return this.#built;
644
+ if (signal?.aborted)
645
+ throw new HostError("aborted", "the wait for the box build was aborted before it began");
646
+ const key = JSON.stringify([this.#owner, keyTag(this.#apiKey), boxBuildName(), boxImageRef()]);
647
+ let flight = FLIGHTS.get(key);
648
+ if (flight === undefined) {
649
+ const started = this.#fly();
650
+ FLIGHTS.set(key, (flight = started));
651
+ void started.answer.then(() => {
652
+ if (FLIGHTS.get(key) === started)
653
+ FLIGHTS.delete(key);
654
+ });
655
+ }
656
+ const tell = () => {
657
+ try {
658
+ building();
659
+ }
660
+ catch {
661
+ // The caller's listener is its own: a throw changes nothing here.
662
+ }
663
+ };
664
+ if (flight.importing)
665
+ tell();
666
+ else
667
+ flight.toTell.add(tell);
668
+ try {
669
+ const settled = await untilAborted(flight.answer, [signal]);
670
+ if (settled === undefined)
671
+ throw new HostError("aborted", "the wait for the box build was aborted; its import goes on for the next caller");
672
+ if ("error" in settled)
673
+ throw settled.error;
674
+ return (this.#built = settled.name);
675
+ }
676
+ finally {
677
+ flight.toTell.delete(tell);
678
+ }
679
+ }
680
+ /** A find-or-import through this host's API key: it never rejects (its error is its answer). */
681
+ #fly() {
682
+ const flight = { answer: Promise.resolve({ error: undefined }), importing: false, toTell: new Set() };
683
+ const importing = () => {
684
+ flight.importing = true;
685
+ for (const tell of flight.toTell)
686
+ tell();
687
+ };
688
+ flight.answer = this.#findOrImport(importing).then((name) => ({ name }), (error) => ({ error }));
689
+ return flight;
690
+ }
691
+ /**
692
+ * The box build found or imported, held to no caller: a build of its name that succeeded is the answer; one pending
693
+ * or running (an import another call or process started, or a POST whose answer was lost) is waited for (GET
694
+ * …/builds?name&status=succeeded&status=pending&status=running, newest first; an array is one key per status, as C's
695
+ * openapi-fetch sends it). Else POST …/builds { name, sourceImage } imports the box image's public tag (S: "converts a
696
+ * container image into an image that sandboxes can use"), and Render's answer is read until it succeeded or failed.
697
+ * `importing` is told before either wait. Render pulls the public ghcr.io image with no credential (the live Core
698
+ * run's import took 104 s); a tag the release has not published yet is Render's 400, "source image unavailable".
699
+ */
700
+ async #findOrImport(importing) {
447
701
  const name = boxBuildName();
448
- const ctx = { timeoutMs: 30_000, ...(signal ? { signal } : {}) };
702
+ const ctx = { timeoutMs: 30_000 };
449
703
  const group = await this.#defaultGroup(ctx);
450
704
  const builds = `/v1/sandbox-groups/${group}/builds`;
451
- const found = await this.#call("GET", `${builds}?${new URLSearchParams({ name, status: "succeeded", limit: "1" })}`, { retry: true }, ctx);
452
- if (Array.isArray(found) && found.length > 0)
453
- return (this.#built = name);
454
- building();
455
- let build = (await this.#call("POST", builds, { json: { name, sourceImage: boxImageRef() }, retry: (status) => status === 429 }, ctx));
705
+ const query = new URLSearchParams([["name", name], ...BUILD_LIVE.map((status) => ["status", status]), ["limit", String(PAGE)]]);
706
+ const listed = await this.#call("GET", `${builds}?${query}`, { retry: true }, ctx);
707
+ const found = (Array.isArray(listed) ? listed : []).flatMap((row) => (row?.build ? [row.build] : []));
708
+ if (found.some(({ status }) => status === "succeeded"))
709
+ return name;
710
+ importing();
711
+ let build = found.find(({ id, status }) => (status === "pending" || status === "running") && typeof id === "string" && BUILD_ID.test(id));
712
+ build ??= (await this.#call("POST", builds, { json: { name, sourceImage: boxImageRef() }, retry: (status) => status === 429 }, ctx));
456
713
  const id = build?.id;
457
714
  if (typeof id !== "string" || !BUILD_ID.test(id))
458
715
  throw new HostError("vendor", `POST ${builds} answered no build id: ${show(id)}`);
@@ -464,8 +721,8 @@ class RenderHost {
464
721
  return undefined;
465
722
  };
466
723
  if (!settled(build))
467
- await until(`Render's build ${id}`, { end: Date.now() + BUILD_MS, pollMs: this.#pollMs, signal }, async () => settled((build = (await this.#call("GET", `${builds}/${id}`, { retry: true }, ctx)))));
468
- return (this.#built = name);
724
+ await until(`Render's build ${id}`, { end: Date.now() + BUILD_MS, pollMs: this.#pollMs }, async () => settled((build = (await this.#call("GET", `${builds}/${id}`, { retry: true }, ctx)))));
725
+ return name;
469
726
  }
470
727
  }
471
728
  /** The box image's build name: agentrun-box-<recipe hash>, as the box image's own tag is. */
@@ -431,6 +431,10 @@ export function createSurface(client, hello, { cwd } = {}) {
431
431
  case "apps.open": {
432
432
  if (typeof args.id !== "string" || args.id === "")
433
433
  throw new SurfaceError("invalid", "id is the app's bundle id or package name");
434
+ // A Linux computerd older than its own url check would put this into the app's argv as a flag (Chromium's
435
+ // --renderer-cmd-prefix runs a command); no platform takes one as a url.
436
+ if (typeof args.url === "string" && /^[ \t\r\n\v\f]*-/.test(args.url))
437
+ throw new SurfaceError("invalid", `url ${JSON.stringify(args.url)} starts with "-": the app would take it as a flag, not a url`);
434
438
  await call("apps.launch", { id: args.id, ...(typeof args.url === "string" ? { url: args.url } : {}), ...(args.background === true ? { background: true } : {}) }, signal);
435
439
  return { value: { id: args.id }, text: `opened ${args.id}`, images: [] };
436
440
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-computer",
3
- "version": "0.1.0-beta.62",
3
+ "version": "0.1.0-beta.64",
4
4
  "description": "The open platform's computer protocol: a daemon in every computer, and one provisioner per vendor, starting with Docker.",
5
5
  "keywords": [
6
6
  "agentrun",