@parcha/agentrun-computer 0.1.0-beta.39 → 0.1.0-beta.40

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.
@@ -85,9 +85,12 @@ function whenAborted(signal) {
85
85
  */
86
86
  export async function runConformance(provider, options) {
87
87
  // Given no cases, the run takes its computer's suite: a browser's own cases, as the CLI does, else the suite's.
88
- const { image, only, kind, signal, cases = casesFor(provider.capabilities().kind), drifted, planted, mountFor, onResult, notes, caseTimeoutMs = 180_000, patience = 30_000, cleanupTimeoutMs = 60_000, fixture, gpu } = options;
88
+ const { image, only, kind, signal, cases = casesFor(provider.capabilities().kind), drifted, planted, mountFor, onResult, notes, caseTimeoutMs = 180_000, patience = 30_000, cleanupTimeoutMs = 60_000, fixture, gpu, long = false, concurrency } = options;
89
89
  if (kind !== undefined && only !== undefined)
90
90
  throw new TypeError("a run takes kind and only apart: a kind runs its own cases");
91
+ if (concurrency !== undefined && !(Number.isSafeInteger(concurrency) && concurrency >= 1))
92
+ throw new TypeError(`concurrency is a whole number of computers, 1 or more; got ${concurrency}`);
93
+ const cap = concurrency ?? Infinity;
91
94
  // What the provider declares of itself: as given, else the kind registry's entry for its id (health.declared), its
92
95
  // parked configurations with its offered ones: a parked one built for the suite is held to its own declaration.
93
96
  const entry = PROVIDERS.find((one) => one.id === provider.id);
@@ -97,7 +100,6 @@ export async function runConformance(provider, options) {
97
100
  throw new TypeError(kindProblem);
98
101
  const fetcher = options.fetch ?? ((url, init) => fetch(url, init));
99
102
  const dialer = options.cdp ?? dialCdp;
100
- const clock = options.clock ?? { now: () => Date.now(), sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) };
101
103
  const run = randomBytes(6).toString("hex");
102
104
  const runLabels = { [RUN_LABEL]: run };
103
105
  const capabilities = provider.capabilities();
@@ -119,6 +121,7 @@ export async function runConformance(provider, options) {
119
121
  core: "fail",
120
122
  undeclared: [],
121
123
  cleanup: { deleted: [], left: [], errors: [], late: [] },
124
+ computers: { peak: 0, ...(concurrency === undefined ? {} : { cap: concurrency }) },
122
125
  ...(notes !== undefined && notes.length > 0 ? { notes: [...notes] } : {}),
123
126
  };
124
127
  const deleted = new Set();
@@ -143,17 +146,111 @@ export async function runConformance(provider, options) {
143
146
  ...extra,
144
147
  labels: { ...extra.labels, ...runLabels },
145
148
  });
149
+ /**
150
+ * The computers alive now, by the request that makes each (its retries share it), with its role: held from the
151
+ * request's first create until its computer is deleted, or until its creates settle with none made. One whose delete
152
+ * failed is `lost`: it may still be there, so it is never freed. A create past the cap waits for one to go.
153
+ */
154
+ const alive = new Map();
155
+ /** Each computer the run made, by name: the request that made it. */
156
+ const madeBy = new Map();
157
+ /** The providers built with planted secrets: their creates are not capped (attempt). */
158
+ const plantedBy = new WeakSet();
159
+ /** The creates of each request still unanswered. */
160
+ const flying = new Map();
161
+ const waiting = [];
162
+ const free = (request) => {
163
+ if (alive.delete(request))
164
+ for (const wake of waiting.splice(0))
165
+ wake();
166
+ };
167
+ /** Deletes the computer, its errors in the report; true once it is deleted. */
146
168
  const release = async (ref, by = provider) => {
169
+ let gone = false;
147
170
  try {
148
171
  const released = await within(by.release(ref, "delete"), cleanupTimeoutMs, `release ${ref.name}`);
149
172
  if (released.ok)
150
173
  deleted.add(ref.name);
151
174
  else
152
175
  report.cleanup.errors.push(`release ${ref.name}: ${released.error.code}: ${released.error.message}`);
176
+ gone = released.ok;
153
177
  }
154
178
  catch (error) {
155
179
  report.cleanup.errors.push(words(error).startsWith(`release ${ref.name}`) ? words(error) : `release ${ref.name} threw: ${words(error)}`);
156
180
  }
181
+ const request = madeBy.get(ref.name);
182
+ if (request !== undefined) {
183
+ madeBy.delete(ref.name);
184
+ if (gone)
185
+ free(request);
186
+ else if (alive.has(request))
187
+ alive.get(request).lost = true;
188
+ }
189
+ return gone;
190
+ };
191
+ /** Whether the case running now uses the run's computer: while it does, the run's computer is not deleted for room. */
192
+ let usingShared = false;
193
+ /**
194
+ * Room for `request`'s computer, of `role`, under the cap; a retry of a request that holds room already has it. While
195
+ * there is none, the run's computer makes way when the case running doesn't use it (and nothing more is made when it
196
+ * can't be deleted); a case whose own computers, the run's computer it uses and those that could not be deleted fill
197
+ * the cap fails in words; else the create waits for a computer to be deleted, or for `signal`.
198
+ */
199
+ const hold = async (request, role, signal) => {
200
+ while (!alive.has(request) && alive.size >= cap) {
201
+ if (sharedRef !== undefined && !usingShared) {
202
+ const ref = sharedRef;
203
+ [shared, sharedRef] = [undefined, undefined];
204
+ if (!(await release(ref)))
205
+ throw new Error(`the run's computer ${ref.name} could not be deleted to make room, so --concurrency ${cap} lets no other be made`);
206
+ continue;
207
+ }
208
+ const held = [...alive.values()];
209
+ if (held.every((one) => one.lost || one.role === role || (one.role === "shared" && usingShared))) {
210
+ const lost = held.filter((one) => one.lost).length;
211
+ throw new Error(lost > 0
212
+ ? `--concurrency ${cap} is full: ${lost} of the run's computers could not be deleted, so no other is made`
213
+ : `this case needs more than ${cap} ${cap === 1 ? "computer" : "computers"} alive at once, and --concurrency ${cap} caps them`);
214
+ }
215
+ signal?.throwIfAborted();
216
+ await new Promise((resolve) => {
217
+ const wake = () => {
218
+ signal?.removeEventListener("abort", wake);
219
+ resolve();
220
+ };
221
+ waiting.push(wake);
222
+ signal?.addEventListener("abort", wake, { once: true });
223
+ });
224
+ signal?.throwIfAborted();
225
+ }
226
+ if (alive.has(request))
227
+ return;
228
+ alive.set(request, { role });
229
+ report.computers.peak = Math.max(report.computers.peak, alive.size);
230
+ };
231
+ /**
232
+ * A create of `request`, under the cap (hold): the room it holds is the computer's it made until that computer's
233
+ * delete, or is freed once every create of the request has answered with none made.
234
+ */
235
+ const capped = async (request, role, signal, create) => {
236
+ flying.set(request, (flying.get(request) ?? 0) + 1);
237
+ try {
238
+ await hold(request, role, signal);
239
+ const created = await create();
240
+ if (created.ok && !madeBy.has(created.value.name))
241
+ madeBy.set(created.value.name, request);
242
+ return created;
243
+ }
244
+ finally {
245
+ const left = flying.get(request) - 1;
246
+ if (left > 0)
247
+ flying.set(request, left);
248
+ else {
249
+ flying.delete(request);
250
+ if (![...madeBy.values()].includes(request))
251
+ free(request);
252
+ }
253
+ }
157
254
  };
158
255
  /** Each computer the run made, by name: its role, "shared" or the id of the case that made it. */
159
256
  const roles = new Map();
@@ -185,14 +282,21 @@ export async function runConformance(provider, options) {
185
282
  return;
186
283
  report.daemons.push({ computer, role: roles.get(computer) ?? role, version: hello.version, os: hello.os, arch: hello.arch, ...(hello.fence === undefined ? {} : { fence: hello.fence }) });
187
284
  };
188
- /** The run's shared computer, made the first time a case needs it or the daemon's hello. */
285
+ /**
286
+ * The run's shared computer, made the first time a case needs it or the daemon's hello, and again after it made way
287
+ * for a case's own under the cap (hold); `hello` is its first one's.
288
+ */
189
289
  let shared;
190
290
  let sharedRef;
291
+ let hello;
292
+ let made = 0;
191
293
  const getShared = () => (shared ??= (async () => {
192
294
  // The run's signal ends the wait at once (Ctrl-C during setup) and reaches the create; a computer that arrives
193
295
  // after it is deleted as it lands (lateCreate).
194
296
  const stop = new AbortController();
195
- const creating = provider.create(spec(), { signal: signal ? AbortSignal.any([signal, stop.signal]) : stop.signal, requestId: `${run}/shared` });
297
+ const both = signal ? AbortSignal.any([signal, stop.signal]) : stop.signal;
298
+ const requestId = `${run}/shared${++made > 1 ? `/${made}` : ""}`;
299
+ const creating = capped(requestId, "shared", both, () => provider.create(spec(), { signal: both, requestId }));
196
300
  let created;
197
301
  try {
198
302
  created = await within(creating, caseTimeoutMs, "create", signal);
@@ -219,6 +323,7 @@ export async function runConformance(provider, options) {
219
323
  return { error: `connect: ${connected.error.code}: ${connected.error.message}` };
220
324
  await bounded(connected.value.close(), CLOSE_MS);
221
325
  sawHello(created.value.name, connected.value.hello, "shared");
326
+ hello ??= connected.value.hello;
222
327
  return { ref: created.value, hello: connected.value.hello };
223
328
  })().catch((error) => ({ error: `the provider threw: ${words(error)}` })));
224
329
  /** Why a case cannot run here, or undefined when everything it needs is declared. */
@@ -232,7 +337,8 @@ export async function runConformance(provider, options) {
232
337
  else if (GROUP_NAMES.has(need)) {
233
338
  if (!groups.includes(need))
234
339
  return `the provider does not declare ${need}`;
235
- const got = await getShared();
340
+ // The run's first computer's hello: one that made way under the cap is not made again to be read.
341
+ const got = hello === undefined ? await getShared() : { hello };
236
342
  if ("hello" in got && !(Array.isArray(got.hello.groups) && got.hello.groups.includes(need))) {
237
343
  return `the ${capabilities.daemon === "none" ? "computer's" : "daemon's"} hello does not declare ${need}`;
238
344
  }
@@ -282,6 +388,7 @@ export async function runConformance(provider, options) {
282
388
  });
283
389
  if (signal?.aborted)
284
390
  return result("fail", "not run: the run was aborted");
391
+ usingShared = (c.computer ?? "shared") === "shared";
285
392
  const why = await missing(c.needs);
286
393
  if (why !== undefined) {
287
394
  const lacking = [];
@@ -348,9 +455,13 @@ export async function runConformance(provider, options) {
348
455
  };
349
456
  /** Each create of the case is its own request: the run, the case and the create's count. */
350
457
  let creates = 0;
351
- /** create through by, kept: what it gives is deleted when the case ends, or as it comes after that. */
458
+ /**
459
+ * create through by, kept: what it gives is deleted when the case ends, or as it comes after that. A create with
460
+ * planted secrets is outside the cap: it can't use the account, so it holds no room (one it makes anyway fails its case).
461
+ */
352
462
  const attempt = (whole, by = provider, requestId = `${run}/${c.id}/${++creates}`) => {
353
- const creating = by.create(whole, { signal: caseSignal, requestId }).then((created) => {
463
+ const make = () => by.create(whole, { signal: caseSignal, requestId });
464
+ const creating = (plantedBy.has(by) ? make() : capped(requestId, c.id, caseSignal, make)).then((created) => {
354
465
  noteCreated(created, c.id);
355
466
  // A retry of one request answers the computer the first attempt made: it is tracked once.
356
467
  if (created.ok && !refs.some((one) => one.ref.id === created.value.id))
@@ -443,7 +554,8 @@ export async function runConformance(provider, options) {
443
554
  sockets.push(socket);
444
555
  return socket;
445
556
  },
446
- clock,
557
+ // The wall clock's wait ends with the case (its timeout, or the run's abort), so no timer outlives the run.
558
+ clock: options.clock ?? { now: () => Date.now(), sleep: (ms) => sleep(ms, undefined, { signal: caseSignal }).catch(() => undefined) },
447
559
  async drifted() {
448
560
  if (drifted === undefined)
449
561
  return t.skip("no drifted provider was given: a provider module exports createDriftedProvider() for the drift cases");
@@ -453,7 +565,9 @@ export async function runConformance(provider, options) {
453
565
  async planted() {
454
566
  if (planted === undefined)
455
567
  return t.skip("no provider with planted secrets was given: the provider takes no secret, or its module lists none in ENV");
456
- return await planted();
568
+ const got = await planted();
569
+ plantedBy.add(got.provider);
570
+ return got;
457
571
  },
458
572
  async runFolder(kind) {
459
573
  const none = `the run was given no run folder for mount kind ${kind}`;
@@ -474,6 +588,10 @@ export async function runConformance(provider, options) {
474
588
  return t.skip("the run named no GPU: give --gpu <type>[:<count>] (or options.gpu), one the provider declares in capabilities().gpu");
475
589
  return { type: gpu.type, count: gpu.count };
476
590
  },
591
+ long(what) {
592
+ if (!long)
593
+ t.skip(`a long case (${what}): run with --long (or options.long), as the live sweep does`);
594
+ },
477
595
  async exec(argv, extra = {}, client = t.client) {
478
596
  const ran = unwrap(await client.call("exec.run", { argv, timeoutMs: patience, ...extra }, { signal: caseSignal }), `exec.run ${show(argv)}`);
479
597
  const decode = (base64) => Buffer.from(base64, "base64").toString("utf8");
@@ -97,6 +97,8 @@ export interface CaseContext {
97
97
  runFolder(kind: MountKind): Promise<RunFolder>;
98
98
  /** The GPU the run pays for (options.gpu, the CLI's --gpu); skips the case when the run names none. */
99
99
  gpu(): GpuSpec;
100
+ /** Skips the case, saying what makes it long, unless the run takes long cases (options.long, the CLI's --long). */
101
+ long(what: string): void;
100
102
  /**
101
103
  * Starts the run's fixture in the case's computer and waits until it is up: an app that logs each input event it
102
104
  * gets, so a case checks what an action did with no model. It is stopped when the case ends. Skips the case when the
@@ -218,6 +220,14 @@ export interface ConformanceReport {
218
220
  leftAlone: number;
219
221
  };
220
222
  };
223
+ /**
224
+ * The most computers the run had alive at once, each counted from its create's call until it was released or its
225
+ * create made none, and the cap the run was given (concurrency), when it was.
226
+ */
227
+ computers: {
228
+ peak: number;
229
+ cap?: number;
230
+ };
221
231
  /** What the provider module says of its configuration, for whoever reads the report; absent when it says nothing. */
222
232
  notes?: string[];
223
233
  /**
@@ -301,6 +311,12 @@ export interface ConformanceOptions {
301
311
  patience?: number;
302
312
  /** The longest each cleanup call (release, the sweep, list) may take; default 60 s. */
303
313
  cleanupTimeoutMs?: number;
314
+ /**
315
+ * The most computers alive at once, for a vendor plan or rate limit that keeps fewer: a create waits for one to be
316
+ * released, the run's computer is deleted while a case that doesn't use it needs room (and made again for the next
317
+ * case that does), and a case that needs more at once than this fails in words. Default no cap.
318
+ */
319
+ concurrency?: number;
304
320
  /**
305
321
  * The fixture on this machine, for the cases that check what input did: computerd-fixture for a desktop, the
306
322
  * fixture APK for an Android phone. Without it those cases skip, and Core cannot pass where kind requires them.
@@ -311,6 +327,11 @@ export interface ConformanceOptions {
311
327
  * the one it pays for; without it the case skips in words.
312
328
  */
313
329
  gpu?: GpuSpec;
330
+ /**
331
+ * Run the long cases, which wait minutes on a vendor's timer (lifetime.idle leaves a computer quiet 6 min): the CLI's
332
+ * --long, which the live sweep gives. Without it they skip in words.
333
+ */
334
+ long?: boolean;
314
335
  /** fetch for screen.stream; default the global one. */
315
336
  fetch?: CaseContext["fetch"];
316
337
  /** How the browser cases open a CDP socket; default a WebSocket (dialCdp). Tests give a fake browser's. */
package/dist/daytona.js CHANGED
@@ -167,7 +167,8 @@ class DaytonaHost {
167
167
  * no public port, and network none (block-all), the one network check() takes. A GPU
168
168
  * computer is made from the GPU snapshot in region earth, ephemeral (its stop deletes it). Never cancelled: the adapter
169
169
  * races it, and deletes by name one whose answer never comes. A name Daytona already holds (409) made nothing: exists,
170
- * and the adapter adopts the sandbox the name lists, as a retry does.
170
+ * and the adapter adopts the sandbox the name lists, as a retry does. req.backstopAt is left: the TTL is Daytona's own
171
+ * timer at the deadline (lifetime "vendor"), and autoDeleteInterval counts from a stop, not from create.
171
172
  */
172
173
  async create(req, ctx) {
173
174
  const gpu = req.gpu !== undefined;
@@ -403,7 +404,8 @@ class DaytonaHost {
403
404
  bound.clear();
404
405
  }
405
406
  // Input: whole lines, one call after another; the rest of a line waits for its end (or end()).
406
- const utf8 = new TextDecoder();
407
+ // ignoreBOM: a U+FEFF that starts stdin is text, never a mark to drop.
408
+ const utf8 = new TextDecoder("utf-8", { ignoreBOM: true });
407
409
  let queued = "";
408
410
  let sending = Promise.resolve();
409
411
  const send = (data) => {
package/dist/host.d.ts CHANGED
@@ -23,7 +23,8 @@ export interface MachineHost {
23
23
  * carries req.name where the vendor can find it again by listing: the vendor's native name, or a label. A native name
24
24
  * the vendor already has throws exists (a REST host's named call: hosted/rest.ts), and the adapter adopts the machine
25
25
  * the name lists, as a retry does. An answer that never comes is not a machine the adapter forgets: it lists by
26
- * req.labels and deletes what it finds.
26
+ * req.labels and deletes what it finds. A host with facts.labels "machine" keeps neither: req.name is its native
27
+ * name where it has one (Machine.name), and the adapter writes req.labels into the machine itself.
27
28
  */
28
29
  create(req: MachineRequest, ctx: HostCall): Promise<{
29
30
  id: string;
@@ -37,7 +38,8 @@ export interface MachineHost {
37
38
  * timer moved: E2B's). It may answer more machines than carry all the labels (a vendor that filters by some, or
38
39
  * none): the adapter keeps those whose get does. A listing may lag a create: two creates of one request on two
39
40
  * provider instances can then both make a machine, and the adapter deletes every one but the oldest (createdAt), so
40
- * a vendor may see a second create deleted.
41
+ * a vendor may see a second create deleted. With facts.labels "machine" it lists by req.name where the vendor lists by
42
+ * name, else every machine: the adapter keeps those of the name, then reads each one's labels from inside it.
41
43
  */
42
44
  list(labels: Record<string, string>, ctx: HostCall): Promise<Machine[]>;
43
45
  /**
@@ -51,21 +53,25 @@ export interface MachineHost {
51
53
  *
52
54
  * exec is the whole protocol: the adapter installs and starts its daemon through it, then talks to the daemon over
53
55
  * one exec'd process's stdin and stdout for the computer's whole life (the stdio bridge, spec/computer/stdio.md). So:
54
- * - Two-way and live. Each write() reaches the process's stdin as it is written, and stdout and stderr bytes come
55
- * back as the process writes them, while it runs. Not request and response, never held until the process exits.
56
- * - Byte-exact. Every byte value 0-255, both ways: no UTF-8 decode or encode, no newline translation, no terminal,
57
- * nothing added or dropped. A client that hands output over as text breaks this (E2B's commands.run does).
56
+ * - Two-way and live. Each write() reaches the process's stdin as it is written, and stdout and stderr come back as
57
+ * the process writes them, while it runs. Not request and response, never held until the process exits.
58
+ * - Text intact. UTF-8 text both ways, every code point as it was: long lines, \r and \r\n kept (no terminal, no
59
+ * newline translation), nothing added or dropped. Everything the adapter sends or reads is text (the bridge's JSON
60
+ * lines, its upload in base64), and each write() holds whole characters. An exec that carries bytes carries this.
58
61
  * - No timeout. The process runs until it exits or kill() ends it: a vendor's command timeout, and any idle timeout
59
62
  * on the stream, are off.
60
- * - stdout and stderr stay apart. wait() answers the process's own exit code. kill() ends the process itself.
61
- * The process reads what write() gives until end(); the adapter ends stdin at once where it gives none. The exec
62
- * pre-check (conformance --exec-stream, src/conformance/exec-stream.ts) checks each of these on a machine made by
63
- * hand, with exec alone.
63
+ * - stdout and stderr stay apart. wait() answers the process's own exit code. kill() ends the process in the
64
+ * machine, not only its streams.
65
+ * end() ends stdin where the vendor can (the adapter calls it at once for a command it gives no input); where it
66
+ * can't, end() does nothing, and nothing the adapter runs waits for it: its upload and its label file's write read a
67
+ * length, a root command's input is one line, its bridge ends by kill(). A vendor whose exec comes in pieces (a start, an event stream, a call per write, no end or no kill) builds
68
+ * this from them with framedExec (./hosted/framed-exec.ts). The exec pre-check (conformance --exec-stream,
69
+ * src/conformance/exec-stream.ts) checks each of these on a machine made by hand, with exec alone.
64
70
  */
65
71
  exec(id: string, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
66
72
  /**
67
73
  * Puts bytes at path in the machine, as root. Optional: a vendor with no file API leaves it out, and the adapter
68
- * streams the file through exec's stdin.
74
+ * streams the file through exec's stdin as base64 text, which root decodes (`base64 -d`, in coreutils and busybox).
69
75
  */
70
76
  upload?(id: string, path: string, bytes: Uint8Array, ctx: HostCall): Promise<void>;
71
77
  /**
@@ -79,16 +85,27 @@ export interface MachineHost {
79
85
  * vendor's own timer (facts.lifetime "vendor"), or the janitor's deadline label (facts.lifetime "janitor"). A refusal
80
86
  * (a HostError limit, in words) when no end the vendor takes lands there without moving it earlier than it is or past
81
87
  * the most: nothing moves then. The adapter reads the end back with get (deadlineOf, the deadline label: a vendor that
82
- * keeps no label change reads its moved timer as that label), and init's deadline follows it. Optional: a host without
83
- * it has no extend.
88
+ * keeps no label change reads its moved timer as that label), and init's deadline follows it. With facts.labels
89
+ * "machine", the adapter then moves the deadline label in the machine itself. Optional: a host without it has no extend.
84
90
  */
85
91
  extend?(id: string, endsAt: Date, ctx: HostCall): Promise<void>;
92
+ /**
93
+ * The vendor's cheapest call that restarts its idle timer (facts.idleMs) on the machine: Cube's or E2B's setTimeout,
94
+ * Railway's heartbeat. The adapter calls it every idleMs / 3 from create, or attach, until release; one that fails is
95
+ * told through onNote and the next one tries again. Required with facts.idleMs; a host with no idle timer leaves it out.
96
+ */
97
+ keepalive?(id: string, ctx: HostCall): Promise<void>;
86
98
  /**
87
99
  * The vendor's own rules of a spec, over the adapter's shared ones: an image name it takes, a GPU's image. No call. The
88
100
  * spec is an object, as the caller gave it: its fields are not checked yet (an image may be a number).
89
101
  */
90
102
  check?(spec: Partial<ComputerSpec>): Refusal[];
91
103
  }
104
+ /**
105
+ * How far past the most a deadline may reach MachineRequest.backstopAt is: the janitor ends the machine first while the
106
+ * server runs, and the vendor's clock may be off from the server's.
107
+ */
108
+ export declare const BACKSTOP_MARGIN_MS = 300000;
92
109
  /** A host's failure whose code it knows: thrown by a host member, read by the adapter as that code, in these words. */
93
110
  export declare class HostError extends Error {
94
111
  readonly code: ComputerErrorCode;
@@ -112,6 +129,12 @@ export interface MachineRequest {
112
129
  labels: Record<string, string>;
113
130
  /** The spec's lifetime: the vendor's timer (facts.lifetime "vendor"); a janitor's host may leave it. */
114
131
  lifetimeMs: number;
132
+ /**
133
+ * An ISO time a margin past the most the machine's deadline may reach: create + maxLifetimeMs + BACKSTOP_MARGIN_MS. A
134
+ * janitor's host whose vendor has a delete or stop timer of its own sets it here (facts.backstop), so the machine still
135
+ * ends when the server that made it is gone. A vendor-lifetime host ignores it.
136
+ */
137
+ backstopAt: string;
115
138
  /**
116
139
  * Whether the machine reaches out: true for an Archil computer's root, which reaches Archil, and for a network open
117
140
  * or a list, whose egress proxy init starts outside its tools' network (./hosted/network.ts). Its tools' own network
@@ -133,14 +156,19 @@ export interface MachineRequest {
133
156
  */
134
157
  export interface Machine {
135
158
  id: string;
136
- /** Every label it carries, the adapter's own included. */
159
+ /** Every label it carries, the adapter's own included; with facts.labels "machine", none (the adapter reads them). */
137
160
  labels: Record<string, string>;
161
+ /**
162
+ * With facts.labels "machine": the vendor's native name, the MachineRequest.name create gave it, where the vendor
163
+ * keeps one. A machine of a request's name whose labels are not written yet is the request's (provider.md).
164
+ */
165
+ name?: string;
138
166
  /**
139
167
  * starting: not yet running; stopped: there, not running, and not being deleted (paused, asleep): listed, so the
140
168
  * janitor still ends it; gone: being deleted, ended, or failed (why says how).
141
169
  */
142
170
  state: "starting" | "running" | "stopped" | "gone";
143
- /** With facts.lifetime "vendor": when the vendor's timer ends it. */
171
+ /** With facts.lifetime "vendor", or facts.backstop: when the vendor's timer ends it. */
144
172
  endsAt?: Date;
145
173
  /**
146
174
  * When the vendor made it, by its clock, where it says. Two creates of one request on two provider instances can each
@@ -154,9 +182,9 @@ export interface Machine {
154
182
  export interface MachineProcess {
155
183
  stdout: AsyncIterable<Uint8Array>;
156
184
  stderr: AsyncIterable<Uint8Array>;
157
- /** Writes to its stdin, in order; rejects once the process has ended. */
185
+ /** Writes UTF-8 text to its stdin, in order, whole characters each; rejects once the process has ended. */
158
186
  write(bytes: Uint8Array): Promise<void>;
159
- /** Ends its stdin, so it reads end of file. */
187
+ /** Ends its stdin, so it reads end of file, where the vendor can; else nothing (exec's doc). */
160
188
  end(): Promise<void>;
161
189
  /** Its exit code once it has ended. */
162
190
  wait(): Promise<number>;
@@ -182,8 +210,18 @@ export interface HostFacts {
182
210
  isolation: ComputerCapabilities["isolation"];
183
211
  /** Who ends a machine at its deadline: the vendor's timer, or the janitor by label. */
184
212
  lifetime: "vendor" | "janitor";
213
+ /**
214
+ * A janitor's host claims its create sets the vendor's own delete or stop timer from req.backstopAt, and get reads it
215
+ * back as endsAt (the Core case provider.backstop checks it). Only this lets a janitor's host keep labels "machine".
216
+ */
217
+ backstop?: true;
185
218
  /** The vendor's hard cap of a machine's life; the adapter's maxLifetimeMs may only lower it. */
186
219
  maxLifetimeMs: number;
220
+ /**
221
+ * Where the vendor ends or pauses a machine no call reaches for a while (an idle timer that can't be switched off): that
222
+ * window, in whole ms. The adapter then calls keepalive every idleMs / 3 while it holds the machine. Default none.
223
+ */
224
+ idleMs?: number;
187
225
  arch: "amd64" | "arm64";
188
226
  /** The TCP ports the vendor's own agent listens on inside the machine (E2B's envd 49983). */
189
227
  vendorAgentPorts: number[];
@@ -196,7 +234,10 @@ export interface HostFacts {
196
234
  * value together, the adapter's at their longest. Past either, check() refuses, and so create, before any host call.
197
235
  * Absent: no bound. packed: the host stores the labels as packLabels packs them (./hosted/values.ts: one name to
198
236
  * list by, the map in parts of at most valueBytes each) and get answers unpackLabels' map; count and bytes are then
199
- * the packed labels'.
237
+ * the packed labels'. "machine": the vendor keeps no labels, so the adapter writes them as JSON to a root-only file in
238
+ * the machine (LABEL_FILE, ./hosted/scripts.ts) right after it runs, and reads them back from it: at most 64 KiB as
239
+ * JSON, what a run's output keeps (OUTPUT_MAX, ./hosted/process.ts). Only with
240
+ * lifetime "vendor" or backstop: a machine whose labels were never written is ended by the vendor's timer alone.
200
241
  */
201
242
  labels?: {
202
243
  count?: number;
@@ -204,7 +245,7 @@ export interface HostFacts {
204
245
  packed?: {
205
246
  valueBytes?: number;
206
247
  };
207
- };
248
+ } | "machine";
208
249
  /**
209
250
  * Paths of the vendor's image that root runs or reads and whose permissions its template build sets wider than
210
251
  * root's: create makes each root's alone (owned by root, writable by no group or other user), and everything under a
package/dist/host.js CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * How far past the most a deadline may reach MachineRequest.backstopAt is: the janitor ends the machine first while the
3
+ * server runs, and the vendor's clock may be off from the server's.
4
+ */
5
+ export const BACKSTOP_MARGIN_MS = 300_000;
1
6
  /** A host's failure whose code it knows: thrown by a host member, read by the adapter as that code, in these words. */
2
7
  export class HostError extends Error {
3
8
  code;
@@ -0,0 +1,49 @@
1
+ import type { HostCall, MachineProcess } from "../host.js";
2
+ /** One event of a process: output on stdout or stderr, as text or as the base64 of its bytes; or its exit code. */
3
+ export type FramedEvent = {
4
+ stream: "stdout" | "stderr";
5
+ text: string;
6
+ } | {
7
+ stream: "stdout" | "stderr";
8
+ base64: string;
9
+ } | {
10
+ exit: number;
11
+ };
12
+ /** A vendor's exec, as calls about one process: P is what start answers, the vendor's own handle on it (an id). */
13
+ export interface ExecPieces<P> {
14
+ /** Starts argv in the machine as root, within ctx, and answers once it has started. */
15
+ start(argv: readonly string[], ctx: HostCall): Promise<P>;
16
+ /** The process's events from its start, in order; an end with no exit event is an exit the vendor never read (-1). */
17
+ events(handle: P): AsyncIterable<FramedEvent>;
18
+ /** One call that hands text to the process's stdin, answered once the vendor took it. */
19
+ write(handle: P, text: string): Promise<void>;
20
+ /**
21
+ * Ends the process's stdin. Leave it out where the vendor has no end of file: end() then does nothing. The cost: a
22
+ * command that reads stdin to its end (cat, a sh reading its script) never ends, and only kill() stops it. Nothing
23
+ * the adapter runs does (its upload reads a length, a root command's input is one line, its bridge ends by kill).
24
+ */
25
+ end?(handle: P): Promise<void>;
26
+ /**
27
+ * Ends the process in the machine. Leave it out where the vendor has none: the process then starts under a sh that
28
+ * writes its pid and its start time on stderr first (framedExec reads that line and passes on the rest), and kill()
29
+ * starts a sh that kills that pid, and every process under it, only while that pid still has that start time.
30
+ */
31
+ kill?(handle: P): Promise<void>;
32
+ }
33
+ /**
34
+ * The sh a process starts under when the vendor has no kill: one line on stderr, its pid and its start time (field 22
35
+ * of /proc/<pid>/stat, counted past the command's name in parentheses, which may hold spaces), then the command in its
36
+ * place, which keeps both.
37
+ */
38
+ export declare const PID_WRAPPER: string[];
39
+ /**
40
+ * The sh kill() starts, given the pid and start time: a pid whose process has ended, and may be another's now, is let
41
+ * be. Otherwise it kills the process and every process under it (an upload's head and base64 would wait on the open
42
+ * stdin, and hold stderr open, past their sh): each is stopped as it is found, so none forks away, by its parent pid
43
+ * (field 4 of its stat) until a pass over /proc finds no more, and then all are killed.
44
+ */
45
+ export declare const PID_KILL: string;
46
+ /** argv started through a vendor's pieces, as the MachineProcess exec answers. */
47
+ export declare function framedExec<P>(pieces: ExecPieces<P>, argv: readonly string[], ctx: HostCall): Promise<MachineProcess>;
48
+ /** The JSON value of each line of a body of newline-delimited JSON, as the lines come; a line that is not JSON throws. */
49
+ export declare function ndjson(body: AsyncIterable<Uint8Array>): AsyncIterable<unknown>;