@runuai/host 0.9.71 → 0.9.72

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/lib/agent-cli.ts CHANGED
@@ -130,6 +130,42 @@ export function writeAgentCli(
130
130
  }
131
131
  }
132
132
 
133
+ /**
134
+ * ADR-121: the same CLI materialization, but through the environment's own
135
+ * transport — machine workspaces are not host-reachable via taskWorkspaceDir.
136
+ * Same no-token invariant: uai.json carries the apiUrl only.
137
+ */
138
+ export async function writeAgentCliViaEnvironment(
139
+ environment: {
140
+ readonly descriptor: { workspacePath: string };
141
+ writeWorkspaceFile(path: string, bytes: Uint8Array): Promise<void>;
142
+ },
143
+ roster: RosterAgent[],
144
+ apiUrl: string | null,
145
+ allowPermissionless = false,
146
+ ): Promise<boolean> {
147
+ if (
148
+ !apiUrl ||
149
+ (rosterPermissions(roster).length === 0 && !allowPermissionless)
150
+ ) {
151
+ return false;
152
+ }
153
+ try {
154
+ const root = environment.descriptor.workspacePath;
155
+ await environment.writeWorkspaceFile(
156
+ `${root}/.uai/uai.json`,
157
+ Buffer.from(`${JSON.stringify({ apiUrl }, null, 2)}\n`),
158
+ );
159
+ await environment.writeWorkspaceFile(
160
+ `${root}/.uai/cli.mjs`,
161
+ Buffer.from(CLI_SOURCE),
162
+ );
163
+ return true;
164
+ } catch {
165
+ return false;
166
+ }
167
+ }
168
+
133
169
  /**
134
170
  * Per-agent env for the `docker exec` that spawns one agent (ADR-048): its OWN
135
171
  * task token (carrying only ITS permissions) + the API url. Empty when the agent
@@ -0,0 +1,492 @@
1
+ /**
2
+ * ADR-121 + ADR-061: durable agent sessions for MACHINE-backed tasks.
3
+ *
4
+ * The container path's DurableProcess polls the session files on a host
5
+ * bind mount — a machine shares no filesystem with the host, so this
6
+ * variant speaks the same runner protocol over the environment transport:
7
+ *
8
+ * outbox one long-lived `tail -c +<offset+1> -F` streamed over ssh;
9
+ * byte offset = initial + bytes received (append-only file).
10
+ * A dropped ssh stream is respawned from the current offset.
11
+ * inbox chained one-shot appends (`cat >> inbox.jsonl` with stdin).
12
+ * liveness periodic heartbeat mtime probe via exec; the runner beats
13
+ * every 5s, so >25s of silence without an exit meta = dead.
14
+ *
15
+ * The runner itself (runner.mjs) is dependency-free Node and runs on the
16
+ * machine unchanged; it is delivered per-session via writeWorkspaceFile so
17
+ * it can never skew against this host's version.
18
+ */
19
+
20
+ import { readFileSync } from "node:fs";
21
+ import { posix } from "node:path";
22
+
23
+ import type {
24
+ TaskEnvironmentHandle,
25
+ TaskEnvironmentProcess,
26
+ } from "../task-environment/types";
27
+ import { runnerScriptPath } from "./durable-proc";
28
+ import type { ExitHandler, LineHandler } from "./proc";
29
+ import type { LineTransport } from "./transport";
30
+
31
+ /** Runner beats every 5 s; 25 s of silence without an exit meta = dead. */
32
+ const HEARTBEAT_STALE_MS = 25_000;
33
+ const HEARTBEAT_PROBE_MS = 10_000;
34
+ const CLOSE_GRACE_MS = 8_000;
35
+ const STEP_TIMEOUT_MS = 30_000;
36
+ const STEP_OUTPUT_BYTES = 64 * 1024;
37
+ const TAIL_RESPAWN_DELAY_MS = 1_000;
38
+
39
+ interface RunnerMeta {
40
+ __uai: string;
41
+ code?: number | null;
42
+ stderrTail?: string;
43
+ }
44
+
45
+ /** The handle ops this transport needs beyond the session surface. */
46
+ export type MachineSessionEnvironment = Pick<
47
+ TaskEnvironmentHandle<unknown>,
48
+ | "descriptor"
49
+ | "exec"
50
+ | "spawnSession"
51
+ | "writeWorkspaceFile"
52
+ | "launchDetachedSession"
53
+ >;
54
+
55
+ async function execStep(
56
+ environment: MachineSessionEnvironment,
57
+ argv: readonly [string, ...string[]],
58
+ stdin?: Uint8Array,
59
+ ): Promise<{ exitCode: number | null; stdout: string; stderr: string }> {
60
+ const result = await environment.exec({
61
+ argv,
62
+ ...(stdin ? { stdin } : {}),
63
+ timeoutMs: STEP_TIMEOUT_MS,
64
+ maxOutputBytes: STEP_OUTPUT_BYTES,
65
+ });
66
+ return {
67
+ exitCode: result.exitCode,
68
+ stdout: Buffer.from(result.stdout).toString("utf8"),
69
+ stderr: Buffer.from(result.stderr).toString("utf8"),
70
+ };
71
+ }
72
+
73
+ /** Append bytes to an environment file (creating parents), via exec stdin. */
74
+ export async function appendEnvironmentFile(
75
+ environment: MachineSessionEnvironment,
76
+ path: string,
77
+ bytes: string,
78
+ ): Promise<void> {
79
+ const result = await execStep(
80
+ environment,
81
+ [
82
+ "/bin/sh",
83
+ "-c",
84
+ 'mkdir -p "$(dirname "$1")" && cat >> "$1"',
85
+ "append",
86
+ path,
87
+ ],
88
+ Buffer.from(bytes),
89
+ );
90
+ if (result.exitCode !== 0) {
91
+ throw new Error(`environment append to ${path} exited ${result.exitCode}`);
92
+ }
93
+ }
94
+
95
+ /** Heartbeat freshness of an environment-side session dir (attach check). */
96
+ export async function machineHeartbeatFresh(
97
+ environment: MachineSessionEnvironment,
98
+ sessionDir: string,
99
+ freshMs: number,
100
+ ): Promise<boolean> {
101
+ try {
102
+ const result = await execStep(environment, [
103
+ "/bin/sh",
104
+ "-c",
105
+ 'stat -c %Y "$1/heartbeat"',
106
+ "stat",
107
+ sessionDir,
108
+ ]);
109
+ if (result.exitCode !== 0) return false;
110
+ const mtimeSeconds = Number(result.stdout.trim());
111
+ if (!Number.isFinite(mtimeSeconds)) return false;
112
+ return Date.now() - mtimeSeconds * 1000 < freshMs;
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+
118
+ export interface MachineDurableOptions {
119
+ environment: MachineSessionEnvironment;
120
+ /** Environment-absolute session dir (inside the workspace). */
121
+ sessionDir: string;
122
+ /** Resume consumption from this outbox byte offset (attach path). */
123
+ initialOutboxOffset?: number;
124
+ onOffsetAdvance?: (offset: number) => void;
125
+ onCloseRequested?: () => void;
126
+ /** Provider-owned detached launch. Omit to attach to a live runner. */
127
+ launch?: () => Promise<{ exitCode: number | null; stderr: Uint8Array }>;
128
+ debugLabel?: string;
129
+ }
130
+
131
+ export class MachineDurableProcess implements LineTransport {
132
+ readonly #environment: MachineSessionEnvironment;
133
+ readonly #sessionDir: string;
134
+ readonly #outboxPath: string;
135
+ readonly #inboxPath: string;
136
+
137
+ readonly #lineHandlers = new Set<LineHandler>();
138
+ readonly #exitHandlers = new Set<ExitHandler>();
139
+
140
+ #offset: number;
141
+ #lineBuf = "";
142
+ #stderrBuf = "";
143
+ #closed = false;
144
+ #detached = false;
145
+ #sawSpawnMeta = false;
146
+ readonly #startedAt = Date.now();
147
+ #tail: TaskEnvironmentProcess | null = null;
148
+ #tailGeneration = 0;
149
+ #heartbeatTimer: ReturnType<typeof setInterval> | null = null;
150
+ #closeTimer: ReturnType<typeof setTimeout> | null = null;
151
+ #respawnTimer: ReturnType<typeof setTimeout> | null = null;
152
+ #probing = false;
153
+ #inboxChain: Promise<void> = Promise.resolve();
154
+ readonly #onOffsetAdvance: ((offset: number) => void) | null;
155
+ readonly #onCloseRequested: (() => void) | null;
156
+ readonly #debug: string | null;
157
+
158
+ constructor(opts: MachineDurableOptions) {
159
+ this.#environment = opts.environment;
160
+ this.#sessionDir = opts.sessionDir;
161
+ this.#outboxPath = posix.join(opts.sessionDir, "outbox.jsonl");
162
+ this.#inboxPath = posix.join(opts.sessionDir, "inbox.jsonl");
163
+ this.#offset = opts.initialOutboxOffset ?? 0;
164
+ this.#onOffsetAdvance = opts.onOffsetAdvance ?? null;
165
+ this.#onCloseRequested = opts.onCloseRequested ?? null;
166
+ this.#debug =
167
+ opts.debugLabel && process.env.UAI_DEBUG_AGENTS ? opts.debugLabel : null;
168
+
169
+ if (opts.launch) {
170
+ void opts.launch().then(
171
+ (result) => {
172
+ const stderr = Buffer.from(result.stderr).toString("utf8");
173
+ if (stderr) this.#stderrBuf = (this.#stderrBuf + stderr).slice(-8192);
174
+ if (result.exitCode !== 0) this.#finish(null);
175
+ },
176
+ (error: unknown) => {
177
+ this.#stderrBuf = (
178
+ this.#stderrBuf +
179
+ (error instanceof Error ? error.message : String(error))
180
+ ).slice(-8192);
181
+ this.#finish(null);
182
+ },
183
+ );
184
+ } else {
185
+ this.#sawSpawnMeta = true; // attach: the runner pre-exists
186
+ // The container path pre-checks heartbeat freshness with a sync stat;
187
+ // over ssh that check is async, so attach optimistically and probe
188
+ // NOW — a dead runner finishes within a round-trip instead of a
189
+ // full probe interval, and the orchestrator respawns fresh.
190
+ void this.#probeLiveness();
191
+ }
192
+
193
+ void this.#spawnTail();
194
+ this.#heartbeatTimer = setInterval(() => {
195
+ void this.#probeLiveness();
196
+ }, HEARTBEAT_PROBE_MS);
197
+ }
198
+
199
+ #log(message: string): void {
200
+ console.error(`[uai-agent ${this.#debug}] ${message}`);
201
+ }
202
+
203
+ // ---- outbox tail over ssh ------------------------------------------------
204
+
205
+ async #spawnTail(): Promise<void> {
206
+ if (this.#closed || this.#detached) return;
207
+ const generation = ++this.#tailGeneration;
208
+ let tail: TaskEnvironmentProcess;
209
+ try {
210
+ // spawnSession, deliberately: a session request carries NO timeoutMs,
211
+ // and the streaming runner only arms its kill timer when one exists —
212
+ // the tail must live as long as the runner does.
213
+ tail = await this.#environment.spawnSession({
214
+ // -c +N is 1-based (start AT byte N): resume just past the consumed
215
+ // prefix. -F survives the outbox not existing yet; its chatter goes
216
+ // to stderr, never the byte stream.
217
+ argv: [
218
+ "/bin/sh",
219
+ "-c",
220
+ 'exec tail -c +"$1" -F "$2" 2>/dev/null',
221
+ "tail",
222
+ String(this.#offset + 1),
223
+ this.#outboxPath,
224
+ ],
225
+ maxOutputBytes: 8 * 1024 * 1024,
226
+ });
227
+ } catch {
228
+ this.#scheduleTailRespawn(generation);
229
+ return;
230
+ }
231
+ if (this.#closed || this.#detached || generation !== this.#tailGeneration) {
232
+ await tail.terminate().catch(() => {});
233
+ return;
234
+ }
235
+ this.#tail = tail;
236
+ void (async () => {
237
+ try {
238
+ for await (const chunk of tail.stdout) {
239
+ if (this.#closed || this.#detached) break;
240
+ if (generation !== this.#tailGeneration) break;
241
+ const text = Buffer.from(chunk);
242
+ this.#offset += text.byteLength;
243
+ this.#lineBuf += text.toString("utf8");
244
+ this.#drainLines();
245
+ if (this.#onOffsetAdvance && !this.#closed) {
246
+ try {
247
+ this.#onOffsetAdvance(this.#offset);
248
+ } catch {
249
+ // Persistence hiccup — the next batch retries larger.
250
+ }
251
+ }
252
+ }
253
+ } catch {
254
+ // Stream error — the respawn below re-establishes the tail.
255
+ }
256
+ // The ssh stream ended (drop, machine restart, terminate). If the
257
+ // session is still live, come back from the current offset.
258
+ if (!this.#closed && !this.#detached && generation === this.#tailGeneration) {
259
+ this.#scheduleTailRespawn(generation);
260
+ }
261
+ })();
262
+ }
263
+
264
+ #scheduleTailRespawn(generation: number): void {
265
+ if (this.#closed || this.#detached) return;
266
+ if (generation !== this.#tailGeneration) return;
267
+ if (this.#respawnTimer) return;
268
+ this.#respawnTimer = setTimeout(() => {
269
+ this.#respawnTimer = null;
270
+ void this.#spawnTail();
271
+ }, TAIL_RESPAWN_DELAY_MS);
272
+ }
273
+
274
+ #drainLines(): void {
275
+ let nl: number;
276
+ while ((nl = this.#lineBuf.indexOf("\n")) >= 0) {
277
+ const line = this.#lineBuf.slice(0, nl).trim();
278
+ this.#lineBuf = this.#lineBuf.slice(nl + 1);
279
+ if (line.length === 0) continue;
280
+ if (line.startsWith('{"__uai"')) {
281
+ this.#handleMeta(line);
282
+ continue;
283
+ }
284
+ if (this.#debug) this.#log(`<- ${line.slice(0, 1000)}`);
285
+ for (const handler of this.#lineHandlers) {
286
+ try {
287
+ handler(line);
288
+ } catch {
289
+ // A broken handler must not wedge the tail loop.
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ #handleMeta(line: string): void {
296
+ let meta: RunnerMeta;
297
+ try {
298
+ meta = JSON.parse(line) as RunnerMeta;
299
+ } catch {
300
+ return;
301
+ }
302
+ if (meta.__uai === "spawn") {
303
+ this.#sawSpawnMeta = true;
304
+ } else if (meta.__uai === "exit") {
305
+ if (typeof meta.stderrTail === "string" && meta.stderrTail) {
306
+ this.#stderrBuf = meta.stderrTail.slice(-8192);
307
+ }
308
+ if (this.#debug) this.#log(`exit meta: code ${meta.code ?? null}`);
309
+ this.#finish(typeof meta.code === "number" ? meta.code : null);
310
+ }
311
+ }
312
+
313
+ // ---- liveness ------------------------------------------------------------
314
+
315
+ async #probeLiveness(): Promise<void> {
316
+ if (this.#closed || this.#detached || this.#probing) return;
317
+ this.#probing = true;
318
+ try {
319
+ if (!this.#sawSpawnMeta) {
320
+ if (Date.now() - this.#startedAt > HEARTBEAT_STALE_MS) this.#finish(null);
321
+ return;
322
+ }
323
+ const fresh = await machineHeartbeatFresh(
324
+ this.#environment,
325
+ this.#sessionDir,
326
+ HEARTBEAT_STALE_MS,
327
+ );
328
+ if (this.#closed || this.#detached) return;
329
+ if (!fresh) this.#finish(null);
330
+ } finally {
331
+ this.#probing = false;
332
+ }
333
+ }
334
+
335
+ #finish(code: number | null): void {
336
+ if (this.#closed) return;
337
+ this.#closed = true;
338
+ this.#stopTimers();
339
+ const tail = this.#tail;
340
+ this.#tail = null;
341
+ if (tail) void tail.terminate().catch(() => {});
342
+ for (const handler of this.#exitHandlers) handler(code);
343
+ }
344
+
345
+ #stopTimers(): void {
346
+ if (this.#heartbeatTimer) clearInterval(this.#heartbeatTimer);
347
+ if (this.#closeTimer) clearTimeout(this.#closeTimer);
348
+ if (this.#respawnTimer) clearTimeout(this.#respawnTimer);
349
+ this.#heartbeatTimer = null;
350
+ this.#closeTimer = null;
351
+ this.#respawnTimer = null;
352
+ }
353
+
354
+ // ---- LineProcess-compatible surface ---------------------------------------
355
+
356
+ onLine(handler: LineHandler): void {
357
+ this.#lineHandlers.add(handler);
358
+ }
359
+
360
+ onExit(handler: ExitHandler): void {
361
+ this.#exitHandlers.add(handler);
362
+ }
363
+
364
+ /** `__uai` MUST stay the first key: both runner and host filter meta lines
365
+ * with a byte-prefix check, not a parse (see DurableProcess.writeLine). */
366
+ writeLine(value: unknown): void {
367
+ if (this.#closed || this.#detached) return;
368
+ const json = JSON.stringify(value);
369
+ const inputMeta = JSON.stringify({ __uai: "input", ts: Date.now() });
370
+ if (this.#debug) this.#log(`-> ${json.slice(0, 1000)}`);
371
+ this.#inboxChain = this.#inboxChain
372
+ .then(() =>
373
+ appendEnvironmentFile(
374
+ this.#environment,
375
+ this.#inboxPath,
376
+ `${inputMeta}\n${json}\n`,
377
+ ),
378
+ )
379
+ .catch(() => {
380
+ // Transport error — liveness probes will surface a dead session.
381
+ });
382
+ }
383
+
384
+ get stderrTail(): string {
385
+ return this.#stderrBuf;
386
+ }
387
+
388
+ get isClosed(): boolean {
389
+ return this.#closed;
390
+ }
391
+
392
+ get outboxOffset(): number {
393
+ return this.#offset;
394
+ }
395
+
396
+ /** Stop consuming WITHOUT touching the runner (host restart in miniature). */
397
+ detach(): void {
398
+ if (this.#detached || this.#closed) return;
399
+ this.#detached = true;
400
+ this.#stopTimers();
401
+ const tail = this.#tail;
402
+ this.#tail = null;
403
+ if (tail) void tail.terminate().catch(() => {});
404
+ }
405
+
406
+ /** Real teardown: ask the runner to stop its CLI, then observe the exit. */
407
+ async close(): Promise<void> {
408
+ if (this.#closed || this.#detached) return;
409
+ try {
410
+ this.#onCloseRequested?.();
411
+ } catch {
412
+ // Bookkeeping only.
413
+ }
414
+ try {
415
+ await this.#inboxChain;
416
+ await appendEnvironmentFile(
417
+ this.#environment,
418
+ this.#inboxPath,
419
+ '{"__uai":"stop"}\n',
420
+ );
421
+ } catch {
422
+ // Inbox unwritable — fall through to the grace timer.
423
+ }
424
+ this.#closeTimer = setTimeout(() => this.#finish(null), CLOSE_GRACE_MS);
425
+ }
426
+ }
427
+
428
+ // ---------------------------------------------------------------------------
429
+ // Session-dir plumbing shared with the transport layer.
430
+ // ---------------------------------------------------------------------------
431
+
432
+ export function machineSessionDir(
433
+ workspacePath: string,
434
+ agentId: string,
435
+ ): string {
436
+ return posix.join(
437
+ workspacePath,
438
+ ".uai",
439
+ "sessions",
440
+ agentId,
441
+ `${String(Date.now())}-${process.pid}`,
442
+ );
443
+ }
444
+
445
+ /** Deliver this host's runner into the environment session dir. */
446
+ export async function deployRunner(
447
+ environment: MachineSessionEnvironment,
448
+ sessionDir: string,
449
+ ): Promise<string> {
450
+ const runnerPath = posix.join(sessionDir, "runner.mjs");
451
+ await environment.writeWorkspaceFile(
452
+ runnerPath,
453
+ readFileSync(runnerScriptPath()),
454
+ );
455
+ return runnerPath;
456
+ }
457
+
458
+ /** Environment-side `current` pointer (agents read the path from their
459
+ * preamble). Best-effort: failure must never kill a session. */
460
+ export async function publishMachineCurrentSession(
461
+ environment: MachineSessionEnvironment,
462
+ sessionDir: string,
463
+ ): Promise<void> {
464
+ try {
465
+ await execStep(environment, [
466
+ "/bin/sh",
467
+ "-c",
468
+ 'ln -sfn "$(basename "$1")" "$(dirname "$1")/current"',
469
+ "publish",
470
+ sessionDir,
471
+ ]);
472
+ } catch {
473
+ // Diagnostic pointer only.
474
+ }
475
+ }
476
+
477
+ /** Ask a (possibly dead) predecessor runner to stop — same gesture as the
478
+ * host-FS append, over the transport, and just as harmless when it's gone. */
479
+ export async function stopMachinePredecessor(
480
+ environment: MachineSessionEnvironment,
481
+ sessionDir: string,
482
+ ): Promise<void> {
483
+ try {
484
+ await appendEnvironmentFile(
485
+ environment,
486
+ posix.join(sessionDir, "inbox.jsonl"),
487
+ '{"__uai":"stop"}\n',
488
+ );
489
+ } catch {
490
+ // Dir gone / runner dead — nothing to stop.
491
+ }
492
+ }
@@ -23,6 +23,7 @@
23
23
 
24
24
  import {
25
25
  copyFileSync,
26
+ readFileSync,
26
27
  mkdirSync,
27
28
  renameSync,
28
29
  rmSync,
@@ -39,6 +40,14 @@ import { taskWorkspaceDir } from "../env";
39
40
  import { requireContainerRuntimeOperational } from "../runtime-guard";
40
41
  import type { TaskEnvironmentAgentSessionSurface } from "../task-environment/types";
41
42
  import { DurableProcess, runnerScriptPath } from "./durable-proc";
43
+ import {
44
+ MachineDurableProcess,
45
+ deployRunner,
46
+ machineSessionDir,
47
+ publishMachineCurrentSession,
48
+ stopMachinePredecessor,
49
+ type MachineSessionEnvironment,
50
+ } from "./machine-durable";
42
51
  import {
43
52
  AGENT_SESSION_OUTPUT_BUFFER_BYTES,
44
53
  EnvironmentLineProcess,
@@ -93,9 +102,13 @@ const ATTACH_HEARTBEAT_FRESH_MS = 20_000;
93
102
  * the feed, multiplicity growing by one per errored turn. Enforcing the
94
103
  * invariant here covers every replacement path, including future ones.
95
104
  */
96
- const liveTails = new Map<string, DurableProcess>();
105
+ interface DetachableTail extends LineTransport {
106
+ detach(): void;
107
+ }
97
108
 
98
- function claimTail(key: string, proc: DurableProcess): DurableProcess {
109
+ const liveTails = new Map<string, DetachableTail>();
110
+
111
+ function claimTail<T extends DetachableTail>(key: string, proc: T): T {
99
112
  liveTails.get(key)?.detach();
100
113
  liveTails.set(key, proc);
101
114
  return proc;
@@ -106,14 +119,16 @@ function durableEnabled(): boolean {
106
119
  }
107
120
 
108
121
  export function createAgentTransport(opts: AgentTransportOptions): LineTransport {
109
- // ADR-121: machine-backed sessions ride the environment's own transport
110
- // (ssh streaming) directly. The container-runtime preflight is a
111
- // docker/apple concern a machine task must not trip over, and durable
112
- // sessions poll host-FS files a machine does not share they return for
113
- // machines with an ssh-tail backend.
122
+ // ADR-121: machine-backed sessions ride the environment's own transport
123
+ // the container-runtime preflight is a docker/apple concern a machine task
124
+ // must not trip over, and the host-FS durable flow below polls files a
125
+ // machine does not share. Machine durability uses the ssh-tail backend.
114
126
  if (opts.environment.descriptor.locator.provider === "machine") {
115
- clearCurrentSession(opts.taskId, opts.agentId);
116
- return directEnvironmentTransport(opts);
127
+ if (!durableEnabled()) {
128
+ clearCurrentSession(opts.taskId, opts.agentId);
129
+ return directEnvironmentTransport(opts);
130
+ }
131
+ return machineDurableTransport(opts);
117
132
  }
118
133
  // Session creation can happen after channel/task lifecycle queues drain, well
119
134
  // after the command-level runtime preflight. Recheck at the actual attach or
@@ -286,6 +301,166 @@ export function createAgentTransport(opts: AgentTransportOptions): LineTransport
286
301
  return claimTail(tailKey, proc);
287
302
  }
288
303
 
304
+ /**
305
+ * ADR-121: durable machine sessions. Same DB row + attach/replace semantics
306
+ * as the container flow; the session files live in the MACHINE's workspace
307
+ * and are reached over the environment transport (MachineDurableProcess).
308
+ * Degrades to direct pipes when the handle lacks the wider ops or the runner
309
+ * asset is missing — sessions work, they just don't survive host restarts.
310
+ */
311
+ function machineDurableTransport(opts: AgentTransportOptions): LineTransport {
312
+ const surface = opts.environment;
313
+ const capable =
314
+ "exec" in surface && "spawnSession" in surface && "writeWorkspaceFile" in surface;
315
+ let runnerSource: Buffer | null = null;
316
+ if (capable) {
317
+ try {
318
+ runnerSource = readFileSync(runnerScriptPath());
319
+ } catch (err) {
320
+ console.warn(
321
+ `[transport] runner unavailable (${err instanceof Error ? err.message : err}) — falling back to direct pipes for ${opts.agentId}`,
322
+ );
323
+ }
324
+ }
325
+ if (!capable || runnerSource === null) {
326
+ clearCurrentSession(opts.taskId, opts.agentId);
327
+ return directEnvironmentTransport(opts);
328
+ }
329
+ const environment = surface as unknown as MachineSessionEnvironment &
330
+ TaskEnvironmentAgentSessionSurface;
331
+
332
+ const db = getDb();
333
+ const row = db
334
+ .select()
335
+ .from(schema.hostAgentSessions)
336
+ .where(
337
+ and(
338
+ eq(schema.hostAgentSessions.taskId, opts.taskId),
339
+ eq(schema.hostAgentSessions.agentId, opts.agentId),
340
+ ),
341
+ )
342
+ .get();
343
+ const persistOffset = (offset: number): void => {
344
+ db.update(schema.hostAgentSessions)
345
+ .set({ outboxOffset: offset, updatedAt: Date.now() })
346
+ .where(
347
+ and(
348
+ eq(schema.hostAgentSessions.taskId, opts.taskId),
349
+ eq(schema.hostAgentSessions.agentId, opts.agentId),
350
+ ),
351
+ )
352
+ .run();
353
+ };
354
+ const markClosed = (): void => {
355
+ db.update(schema.hostAgentSessions)
356
+ .set({ status: "closed", updatedAt: Date.now() })
357
+ .where(
358
+ and(
359
+ eq(schema.hostAgentSessions.taskId, opts.taskId),
360
+ eq(schema.hostAgentSessions.agentId, opts.agentId),
361
+ ),
362
+ )
363
+ .run();
364
+ };
365
+ const tailKey = `${opts.taskId}:${opts.agentId}`;
366
+
367
+ // ---- Attach: a previous host process left this machine's runner alive. --
368
+ // Freshness cannot be a sync stat over ssh; MachineDurableProcess probes
369
+ // the heartbeat immediately on attach and finishes fast when it is stale.
370
+ if (
371
+ opts.allowAttach &&
372
+ row &&
373
+ row.status === "running" &&
374
+ row.containerName === environment.durableIdentity &&
375
+ (row.attachCompatibilityKey ?? null) ===
376
+ (opts.attachCompatibilityKey ?? null)
377
+ ) {
378
+ const proc = new MachineDurableProcess({
379
+ environment,
380
+ sessionDir: row.sessionDir,
381
+ initialOutboxOffset: row.outboxOffset,
382
+ onOffsetAdvance: persistOffset,
383
+ onCloseRequested: markClosed,
384
+ debugLabel: opts.debugLabel,
385
+ });
386
+ proc.onExit(markClosed);
387
+ return claimTail(tailKey, proc);
388
+ }
389
+
390
+ // ---- Spawn a fresh runner, asking any predecessor to stop. --------------
391
+ const staleMachineSession =
392
+ row && row.containerName === environment.durableIdentity
393
+ ? row.sessionDir
394
+ : null;
395
+ const sessionDir = machineSessionDir(
396
+ environment.descriptor.workspacePath,
397
+ opts.agentId,
398
+ );
399
+ const proc = new MachineDurableProcess({
400
+ environment,
401
+ sessionDir,
402
+ onOffsetAdvance: persistOffset,
403
+ onCloseRequested: markClosed,
404
+ debugLabel: opts.debugLabel,
405
+ launch: async () => {
406
+ // Unconditional stop of a same-machine predecessor (see the container
407
+ // flow): a runner falsely marked closed may still be alive, and a stop
408
+ // appended to a dead session's inbox is harmless.
409
+ if (staleMachineSession) {
410
+ await stopMachinePredecessor(environment, staleMachineSession);
411
+ }
412
+ const runnerPath = await deployRunner(environment, sessionDir);
413
+ await publishMachineCurrentSession(environment, sessionDir);
414
+ const result = await environment.launchDetachedSession({
415
+ argv: [
416
+ "node",
417
+ runnerPath,
418
+ sessionDir,
419
+ "--",
420
+ opts.cli,
421
+ ...opts.cliArgs,
422
+ ],
423
+ inheritEnv: opts.passEnv ?? [],
424
+ env: opts.explicitEnv ?? {},
425
+ launchTimeoutMs: 30_000,
426
+ maxOutputBytes: 256 * 1024,
427
+ });
428
+ return { exitCode: result.exitCode, stderr: result.stderr };
429
+ },
430
+ });
431
+
432
+ const now = Date.now();
433
+ db.insert(schema.hostAgentSessions)
434
+ .values({
435
+ taskId: opts.taskId,
436
+ agentId: opts.agentId,
437
+ sessionDir,
438
+ containerName: environment.durableIdentity,
439
+ kind: opts.kind,
440
+ attachCompatibilityKey: opts.attachCompatibilityKey ?? null,
441
+ outboxOffset: 0,
442
+ status: "running",
443
+ createdAt: now,
444
+ updatedAt: now,
445
+ })
446
+ .onConflictDoUpdate({
447
+ target: [schema.hostAgentSessions.taskId, schema.hostAgentSessions.agentId],
448
+ set: {
449
+ sessionDir,
450
+ containerName: environment.durableIdentity,
451
+ kind: opts.kind,
452
+ attachCompatibilityKey: opts.attachCompatibilityKey ?? null,
453
+ outboxOffset: 0,
454
+ status: "running",
455
+ updatedAt: now,
456
+ },
457
+ })
458
+ .run();
459
+
460
+ proc.onExit(markClosed);
461
+ return claimTail(tailKey, proc);
462
+ }
463
+
289
464
  function directEnvironmentTransport(opts: AgentTransportOptions): LineTransport {
290
465
  return new EnvironmentLineProcess({
291
466
  environment: opts.environment,
@@ -96,6 +96,7 @@ import {
96
96
  apiUrlFromCloudUrl,
97
97
  loadTaskCliSecret,
98
98
  writeAgentCli,
99
+ writeAgentCliViaEnvironment,
99
100
  } from "./agent-cli";
100
101
  import {
101
102
  DEFAULT_CODEX_HOME,
@@ -1370,6 +1371,13 @@ export class Orchestrator {
1370
1371
 
1371
1372
  for (const agent of missing) channel.spawning.add(agent.id);
1372
1373
  try {
1374
+ // ADR-121: machine workspaces are only reachable through the
1375
+ // environment handle — the docker-exec cold-start default would
1376
+ // dial a container that does not exist. Settle the handle first.
1377
+ if (task.environmentProvider === "machine") {
1378
+ await this.agentEnvironment(channel).catch(() => {});
1379
+ if (!this.isActiveChannel(channel)) return;
1380
+ }
1373
1381
  // Same per-agent materialisation the initial start does. Browser setup
1374
1382
  // is awaited before EVERY missing-session spawn: that reasserts configs
1375
1383
  // clobbered by resume/auth injection and covers roster generation.
@@ -1402,8 +1410,8 @@ export class Orchestrator {
1402
1410
 
1403
1411
  const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
1404
1412
  const cliSecret = loadTaskCliSecret(channel.taskId);
1405
- const cliWritten = writeAgentCli(
1406
- channel.taskId,
1413
+ const cliWritten = await materializeAgentCli(
1414
+ task,
1407
1415
  roster,
1408
1416
  apiUrl,
1409
1417
  channel.mode === "secretary",
@@ -1698,6 +1706,14 @@ export class Orchestrator {
1698
1706
  // browser/MCP configuration, or runner creation can execute in Docker.
1699
1707
  await agentClisReady;
1700
1708
  if (!this.isActiveChannel(channel)) return false;
1709
+ // ADR-121: machine workspaces are only reachable through the environment
1710
+ // handle. Settle it before any materialization step below, so identity,
1711
+ // skills, browser, and MCP writes all ride the provider surface instead
1712
+ // of dialing a compose container that does not exist.
1713
+ if (task.environmentProvider === "machine") {
1714
+ await this.agentEnvironment(channel).catch(() => {});
1715
+ if (!this.isActiveChannel(channel)) return false;
1716
+ }
1701
1717
  // Freeze the generation before any slow docker work. A roster add while
1702
1718
  // setup awaits must reconcile under its own engine-aware browser pass,
1703
1719
  // not slip into this factory loop under the old generation's config.
@@ -1777,8 +1793,8 @@ export class Orchestrator {
1777
1793
  // are actually enforced. Best-effort, host-side.
1778
1794
  const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
1779
1795
  const cliSecret = loadTaskCliSecret(channel.taskId);
1780
- const cliWritten = writeAgentCli(
1781
- channel.taskId,
1796
+ const cliWritten = await materializeAgentCli(
1797
+ task,
1782
1798
  channel.roster,
1783
1799
  apiUrl,
1784
1800
  channel.mode === "secretary",
@@ -5619,6 +5635,35 @@ async function quarantineWritableAppleRuntimeContainers(options: {
5619
5635
 
5620
5636
  /** Dispatch one durable row through its provider. Generic boot orchestration
5621
5637
  * owns DB/lifecycle sequencing but never derives a Compose/container identity. */
5638
+ /**
5639
+ * ADR-121: materialize the in-task uai CLI through whichever surface owns the
5640
+ * workspace — host FS for container tasks, the environment transport for
5641
+ * machine tasks (their workspace is not host-reachable). Best-effort like the
5642
+ * host-side writer.
5643
+ */
5644
+ async function materializeAgentCli(
5645
+ task: typeof schema.hostTasks.$inferSelect,
5646
+ roster: RosterAgent[],
5647
+ apiUrl: string | null,
5648
+ allowPermissionless: boolean,
5649
+ ): Promise<boolean> {
5650
+ if (task.environmentProvider === "machine") {
5651
+ try {
5652
+ const environment = await reconstructPersistedTaskEnvironment(task);
5653
+ if (environment === null) return false;
5654
+ return await writeAgentCliViaEnvironment(
5655
+ environment,
5656
+ roster,
5657
+ apiUrl,
5658
+ allowPermissionless,
5659
+ );
5660
+ } catch {
5661
+ return false;
5662
+ }
5663
+ }
5664
+ return writeAgentCli(task.taskId, roster, apiUrl, allowPermissionless);
5665
+ }
5666
+
5622
5667
  async function recoverPersistedTaskEnvironment(
5623
5668
  task: typeof schema.hostTasks.$inferSelect,
5624
5669
  maintenanceReady: Promise<void>,
@@ -31,6 +31,11 @@ export function getHostTask(taskId: string): HostTask | null {
31
31
 
32
32
  /** Remove a provisional first-seen row when admission loses a lifecycle gate. */
33
33
  export function deleteHostTask(taskId: string): void {
34
+ // Row deletions are rare and load-bearing; a silent one cost a live
35
+ // machine-task forensic session (2026-08-27). Name the caller.
36
+ console.warn(
37
+ `[runtime-state] deleting host task row ${taskId}\n${(new Error().stack ?? "").split("\n").slice(2, 5).join("\n")}`,
38
+ );
34
39
  getDb()
35
40
  .delete(schema.hostTasks)
36
41
  .where(eq(schema.hostTasks.taskId, taskId))
@@ -41,6 +46,7 @@ export function deleteHostTask(taskId: string): void {
41
46
  * happen before this transaction; a SQLite failure leaves every task-owned
42
47
  * row intact rather than acknowledging a partial metadata deletion. */
43
48
  export function purgeHostTaskState(taskId: string): void {
49
+ console.warn(`[runtime-state] purging all host state for task ${taskId}`);
44
50
  getDb().transaction((tx) => {
45
51
  tx.delete(schema.hostAgentSessions)
46
52
  .where(eq(schema.hostAgentSessions.taskId, taskId))
@@ -26,7 +26,10 @@ import { createAwsMachineProvider } from "../machine-provider-aws";
26
26
  import { createLocalMachineProvider } from "../machine-provider-local";
27
27
  import { ensureMachineKeyPair } from "../machine-keys";
28
28
  import { requestAccessToken } from "../github-tokens";
29
- import { createMachineTaskEnvironmentProvider } from "./machine";
29
+ import {
30
+ createMachineTaskEnvironmentProvider,
31
+ MACHINE_TASK_ENVIRONMENT_PROVIDER,
32
+ } from "./machine";
30
33
  import { createMachineHostTaskEnvironmentProvider } from "./machine-task-up";
31
34
  import { TaskEnvironmentRegistry } from "./registry";
32
35
  import {
@@ -307,6 +310,9 @@ export function persistedTaskEnvironmentsMatchMachine(
307
310
  };
308
311
  }
309
312
  if (locator === null) continue;
313
+ // ADR-121: machine locators name an ephemeral VM, not a container
314
+ // daemon — no container-runtime identity claim to verify.
315
+ if (locator.provider === MACHINE_TASK_ENVIRONMENT_PROVIDER) continue;
310
316
  try {
311
317
  const persisted = locatorMachineIdentity(locator);
312
318
  if (
@@ -375,6 +381,8 @@ export function hostTaskEnvironmentsAllowMachineSelection(
375
381
  if (locator.provider !== task.environmentProvider) {
376
382
  throw new Error("task environment provider does not match its locator");
377
383
  }
384
+ // ADR-121: machine rows make no container-runtime claim.
385
+ if (locator.provider === MACHINE_TASK_ENVIRONMENT_PROVIDER) continue;
378
386
  const persisted = locatorMachineIdentity(locator);
379
387
  if (
380
388
  persisted.backend !== machine.backend ||
@@ -166,6 +166,12 @@ function legacyCandidate(
166
166
  // 2026-08-15): a crash-preserved prepared apple locator made adoption —
167
167
  // and with it runtime selection — fail closed, so the task could not
168
168
  // even be settled.
169
+ // ADR-121: machine-backed rows are not container-runtime residents at
170
+ // all — their locator names an ephemeral VM, not a docker/apple daemon.
171
+ // They must never wedge container-runtime selection (live 2026-08-27:
172
+ // the first machine task quarantined the whole VM runtime on reconnect,
173
+ // collapsing every host command into a retry storm).
174
+ if (locator.provider === "machine") return null;
169
175
  let persistedMachine: HostMachineIdentity;
170
176
  if (locator.provider === "docker-compose") {
171
177
  persistedMachine = parseDockerTaskEnvironmentLocator(locator).machine;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runuai/host",
3
- "version": "0.9.71",
3
+ "version": "0.9.72",
4
4
  "description": "Uai host — runs ephemeral AI tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Uai Tech <team@runuai.com>",
package/src/index.ts CHANGED
@@ -957,6 +957,17 @@ export const hostCommands: HostCommands = {
957
957
  }
958
958
  const result = await wrapAgent(ctx, "taskDown", async () => {
959
959
  if (environment === null) return agent.taskDown(input);
960
+ // ADR-121: an ordinary stop of a machine task must keep the machine's
961
+ // disk — the workspace lives THERE, not on a host worktree the way
962
+ // compose teardown preserves it. Stop is the resumable gesture
963
+ // (provision restarts a stopped machine); only orphan GC terminates.
964
+ if (
965
+ !orphanGc &&
966
+ environment.descriptor.locator.provider === "machine"
967
+ ) {
968
+ await environment.stop();
969
+ return taskDownResultForInput(input, { status: "stopped" });
970
+ }
960
971
  return taskDownResultForInput(input, await environment.teardown());
961
972
  });
962
973
  if (result.ok) {