@yaag/runtime 0.31.0 → 0.32.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -23,8 +23,8 @@ const ThinkingLevelSchema = Type.Union(THINKING_LEVELS.map((level) => Type.Liter
23
23
  * concatenates across the layers, it does not concatenate: the last layer that
24
24
  * states it wins (ADR-0052).
25
25
  *
26
- * `hc.peekTerminals` switches on the Peek Terminals in hc (ADR-0072). Like
27
- * `profile`, it is last-layer-wins.
26
+ * `hc.agentTerminals` turns Agent Terminals inside hc on or off; the key is
27
+ * last-layer-wins (ADR-0072).
28
28
  */
29
29
  export const YaagConfigSchema = Type.Object(
30
30
  {
@@ -60,7 +60,7 @@ export const YaagConfigSchema = Type.Object(
60
60
  ),
61
61
  hc: Type.Optional(
62
62
  Type.Object(
63
- { peekTerminals: Type.Optional(Type.Boolean()) },
63
+ { agentTerminals: Type.Optional(Type.Boolean()) },
64
64
  { additionalProperties: false },
65
65
  ),
66
66
  ),
@@ -60,9 +60,15 @@ export interface EffectiveConfig {
60
60
  */
61
61
  readonly askUserSummary?: QuestionSummaryConfig;
62
62
  /**
63
- * The last layer that set `hc.peekTerminals` (ADR-0072); absent means `false`.
63
+ * `hc.agentTerminals` of the last layer that set it (ADR-0072); absent when no
64
+ * layer set it. Read it through `agentTerminalsOf`, which applies the default.
64
65
  */
65
- readonly hcPeekTerminals?: boolean;
66
+ readonly hcAgentTerminals?: boolean;
67
+ }
68
+
69
+ /** Whether Agent Terminals are on for one config; the default is `true` (ADR-0072). */
70
+ export function agentTerminalsOf(config: EffectiveConfig | undefined): boolean {
71
+ return config?.hcAgentTerminals ?? true;
66
72
  }
67
73
 
68
74
  /** What to discover and read. */
@@ -153,16 +159,16 @@ function mergeLayers(found: readonly LoadedLayer[]): EffectiveConfig {
153
159
  (last, { layer }) => layer.document.profile ?? last,
154
160
  undefined,
155
161
  );
156
- const hcPeekTerminals = found.reduce<boolean | undefined>(
157
- (last, { layer }) => layer.document.hc?.peekTerminals ?? last,
162
+ const hcAgentTerminals = found.reduce<boolean | undefined>(
163
+ (last, { layer }) => layer.document.hc?.agentTerminals ?? last,
158
164
  undefined,
159
165
  );
160
166
  return Object.freeze({
161
167
  extensions: Object.freeze(extensions),
162
168
  files: Object.freeze(found.map(({ layer }) => layer.file)),
163
169
  ...(profile === undefined ? {} : { profile }),
164
- ...(hcPeekTerminals === undefined ? {} : { hcPeekTerminals }),
165
170
  askUserSummary: mergeQuestionSummary(found),
171
+ ...(hcAgentTerminals === undefined ? {} : { hcAgentTerminals }),
166
172
  });
167
173
  }
168
174
 
@@ -14,6 +14,7 @@ export {
14
14
  } from "./config-paths.ts";
15
15
  export type { YaagConfigDocument } from "./config-schema.ts";
16
16
  export {
17
+ agentTerminalsOf,
17
18
  type ConfigExtension,
18
19
  type ConfigLayerName,
19
20
  DEFAULT_QUESTION_SUMMARY,
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The transport composition of one Run: replay, or the live side with its
3
+ * worktree, skill restriction, and resume wrappers.
4
+ */
5
+ import {
6
+ type Cassette,
7
+ type CassetteSink,
8
+ recordingTransport,
9
+ replayTransport,
10
+ resumeTransport,
11
+ } from "../cassette/index.ts";
12
+ import { agentTerminalsOf } from "../config/index.ts";
13
+ import {
14
+ liveSkillProbe,
15
+ liveTransportFor,
16
+ skillRestrictionTransport,
17
+ type TransportFactory,
18
+ worktreeTransport,
19
+ } from "../transport/index.ts";
20
+ import type { AnswerLedger } from "./answers.ts";
21
+ import type { RunOptions } from "./run.ts";
22
+
23
+ /**
24
+ * Inputs that select the Run's transport composition. The collector receives
25
+ * every frame from every Run. Replay and resume hold the loaded Cassettes, or
26
+ * null when the Run does not use them.
27
+ */
28
+ export interface FactorySelection {
29
+ readonly options: RunOptions;
30
+ /** Receives every frame; wrapped so Ask boundaries flush the Checkpoint (ADR-0031). */
31
+ readonly collector: CassetteSink;
32
+ readonly replay: Cassette | null;
33
+ readonly resume: Cassette | null;
34
+ /** The answers of this resume; a recorded parked Ask reads its own here. */
35
+ readonly answers?: AnswerLedger;
36
+ }
37
+
38
+ /**
39
+ * Composes the Run's transport. Strict replay deliberately bypasses the
40
+ * worktree wrapper; resume retains its worktree-wrapped live side for unmatched
41
+ * spawns (ADR-0013). The live order is worktree → skill restriction → live, so
42
+ * skill discovery occurs in the resolved worktree cwd.
43
+ *
44
+ * The recorder is the outermost wrapper of every composition, replay included:
45
+ * it observes only, and never changes delegation (ADR-0013/0021).
46
+ */
47
+ export function selectFactory(selection: FactorySelection): TransportFactory {
48
+ const base =
49
+ selection.replay !== null ? replayTransport(selection.replay) : selectLiveFactory(selection);
50
+ return recordingTransport(base, selection.collector);
51
+ }
52
+
53
+ function selectLiveFactory(selection: FactorySelection): TransportFactory {
54
+ const restricted = skillRestrictionTransport(
55
+ selection.options.transport ?? defaultLiveTransport(selection.options),
56
+ selection.options.skillProbe ?? liveSkillProbe,
57
+ );
58
+ const live = worktreeTransport(restricted);
59
+ if (selection.resume === null) return live;
60
+ const answers = selection.answers;
61
+ return resumeTransport(selection.resume, live, {
62
+ answerFor: (questionId) => answers?.take(questionId),
63
+ });
64
+ }
65
+
66
+ /**
67
+ * The live transport of one Run: Agent Terminals inside hc when the config
68
+ * allows them, the direct launcher otherwise (ADR-0072). One factory per Run.
69
+ */
70
+ function defaultLiveTransport(options: RunOptions): TransportFactory {
71
+ const runId = options.runId;
72
+ return liveTransportFor({
73
+ agentTerminals: agentTerminalsOf(options.config),
74
+ ...(runId ? { runId } : {}),
75
+ });
76
+ }
package/src/run/run.ts CHANGED
@@ -7,7 +7,6 @@ import {
7
7
  assertReplayProfile,
8
8
  type Cassette,
9
9
  CassetteCollector,
10
- type CassetteSink,
11
10
  checkpointFileName,
12
11
  cleanStaleCheckpointTemp,
13
12
  createCheckpoint,
@@ -18,12 +17,9 @@ import {
18
17
  profileIdentityWarning,
19
18
  programIdentityWarning,
20
19
  readableCassette,
21
- recordingTransport,
22
- replayTransport,
23
20
  resolveCheckpointDirectory,
24
21
  resolveRunIdentity,
25
22
  restoreSessionAnswers,
26
- resumeTransport,
27
23
  writeRecordingDiagnostic,
28
24
  } from "../cassette/index.ts";
29
25
  import {
@@ -37,19 +33,13 @@ import type { EventSink, LifecycleEvent, RunOutcome, StampedEventSink } from "..
37
33
  import { selectProfile } from "../profile/index.ts";
38
34
  import { summarizeQuestions } from "../question-summary/index.ts";
39
35
  import { applyEvent, initialSummary, type RunSummary } from "../summary/index.ts";
40
- import type { TransportFactory } from "../transport/index.ts";
41
- import {
42
- liveSkillProbe,
43
- liveTransport,
44
- type SkillProbeFactory,
45
- skillRestrictionTransport,
46
- worktreeTransport,
47
- } from "../transport/index.ts";
36
+ import type { SkillProbeFactory, TransportFactory } from "../transport/index.ts";
48
37
  import type { Group } from "../types.ts";
49
38
  import { createAgentQuestions, seedFromResume } from "./agent-questions.ts";
50
39
  import { type AnswerLedger, createAnswerLedger, emptyAnswerLedger } from "./answers.ts";
51
40
  import { validateArgs } from "./args-validation.ts";
52
41
  import { type OrchestrationProgram, programDefinition } from "./define-run.ts";
42
+ import { selectFactory } from "./factory-selection.ts";
53
43
  import { createGroups } from "./groups.ts";
54
44
  import { adoptedHostSource, type HostSessionOptions, prepareHostSource } from "./host-session.ts";
55
45
  import { createPauseRequests } from "./pause-questions.ts";
@@ -119,6 +109,8 @@ export interface RunOptions {
119
109
  * (ADR-0052).
120
110
  */
121
111
  readonly profile?: string;
112
+ /** The Run id of the launch (`--run-id`); only labels Agent Terminals (ADR-0072). */
113
+ readonly runId?: string;
122
114
  }
123
115
 
124
116
  /**
@@ -488,49 +480,6 @@ function assertArgs<Args>(schema: TSchema | undefined, value: unknown): asserts
488
480
  if (schema !== undefined) validateArgs(schema, value);
489
481
  }
490
482
 
491
- /**
492
- * Inputs that select the Run's transport composition. The collector receives
493
- * every frame from every Run. Replay and resume hold the loaded Cassettes, or
494
- * null when the Run does not use them.
495
- */
496
- export interface FactorySelection {
497
- readonly options: RunOptions;
498
- /** Receives every frame; wrapped so Ask boundaries flush the Checkpoint (ADR-0031). */
499
- readonly collector: CassetteSink;
500
- readonly replay: Cassette | null;
501
- readonly resume: Cassette | null;
502
- /** The answers of this resume; a recorded parked Ask reads its own here. */
503
- readonly answers?: AnswerLedger;
504
- }
505
-
506
- /**
507
- * Composes the Run's transport. Strict replay deliberately bypasses the
508
- * worktree wrapper; resume retains its worktree-wrapped live side for unmatched
509
- * spawns (ADR-0013). The live order is worktree → skill restriction → live, so
510
- * skill discovery occurs in the resolved worktree cwd.
511
- *
512
- * The recorder is the outermost wrapper of every composition, replay included:
513
- * it observes only, and never changes delegation (ADR-0013/0021).
514
- */
515
- export function selectFactory(selection: FactorySelection): TransportFactory {
516
- const base =
517
- selection.replay !== null ? replayTransport(selection.replay) : selectLiveFactory(selection);
518
- return recordingTransport(base, selection.collector);
519
- }
520
-
521
- function selectLiveFactory(selection: FactorySelection): TransportFactory {
522
- const restricted = skillRestrictionTransport(
523
- selection.options.transport ?? liveTransport,
524
- selection.options.skillProbe ?? liveSkillProbe,
525
- );
526
- const live = worktreeTransport(restricted);
527
- if (selection.resume === null) return live;
528
- const answers = selection.answers;
529
- return resumeTransport(selection.resume, live, {
530
- answerFor: (questionId) => answers?.take(questionId),
531
- });
532
- }
533
-
534
483
  interface ReapOptions {
535
484
  readonly agents: readonly Agent[];
536
485
  readonly emit: EventSink;
@@ -0,0 +1,294 @@
1
+ /**
2
+ * The three FIFOs of one Agent Terminal (ADR-0072): `stdin`, `stdout`, and
3
+ * `stderr` in a private temporary directory.
4
+ *
5
+ * POSIX only: the FIFOs are made with `mkfifo`, like the Lifecycle Event pipe
6
+ * of ADR-0067.
7
+ *
8
+ * Reads and writes wait on poll readiness (`Bun.file(fd).stream()` and a
9
+ * FileSink), so an idle Agent Terminal holds no async fs pool thread.
10
+ *
11
+ * The open deadline is a hard limit: it does not wait for an open call that is
12
+ * still in the queue of the async fs pool, and the FIFO directory is made and
13
+ * removed with sync calls, so a full pool cannot stop the fallback.
14
+ */
15
+
16
+ import {
17
+ chmodSync,
18
+ closeSync,
19
+ constants,
20
+ mkdtempSync,
21
+ open as nodeOpen,
22
+ openSync,
23
+ rmSync,
24
+ } from "node:fs";
25
+ import { tmpdir } from "node:os";
26
+ import { join } from "node:path";
27
+ import type { ProcessInput } from "./process-launcher.ts";
28
+
29
+ /** The one time limit for the open of all three FIFO ends. */
30
+ export const FIFO_OPEN_DEADLINE_MS = 5000;
31
+ const POLL_MS = 10;
32
+
33
+ /** The Orchestrator ends of the three FIFOs. */
34
+ export interface FifoEnds {
35
+ readonly stdin: ProcessInput & { close(): void };
36
+ readonly stdout: ReadableStream<Uint8Array>;
37
+ readonly stderr: ReadableStream<Uint8Array>;
38
+ /** Closes every end. Idempotent, never throws. */
39
+ close(): void;
40
+ }
41
+
42
+ /** Opens the Orchestrator ends in `dir`. Injectable, so unit tests can fake it. */
43
+ export type FifoOpener = (
44
+ dir: string,
45
+ deadlineMs: number,
46
+ signal?: AbortSignal,
47
+ ) => Promise<FifoEnds>;
48
+
49
+ /** Makes a `0700` directory under `root` with the FIFOs `stdin`, `stdout`, and `stderr`. A failed `mkfifo` removes it. */
50
+ export async function makeFifoDir(root: string = tmpdir()): Promise<string> {
51
+ const dir = mkdtempSync(join(root, "yaag-agent-"));
52
+ chmodSync(dir, 0o700);
53
+ const made = Bun.spawnSync(["mkfifo", ...["stdin", "stdout", "stderr"].map((n) => join(dir, n))]);
54
+ if (made.exitCode !== 0) {
55
+ removeFifoDir(dir);
56
+ throw new Error("mkfifo failed for an Agent Terminal");
57
+ }
58
+ return dir;
59
+ }
60
+
61
+ /** Removes a FIFO directory with a sync call, so a full async fs pool cannot delay it. Never throws. */
62
+ export function removeFifoDir(dir: string): void {
63
+ try {
64
+ rmSync(dir, { recursive: true, force: true });
65
+ } catch {
66
+ // Best effort.
67
+ }
68
+ }
69
+
70
+ /** Opens `path` with a blocking open on the async fs pool and gives the raw fd. Tests replace it. */
71
+ export type FdOpen = (path: string, flags: number) => Promise<number>;
72
+
73
+ const poolOpen: FdOpen = (path, flags) =>
74
+ new Promise((resolve, reject) => {
75
+ nodeOpen(path, flags, (error, fd) => (error ? reject(error) : resolve(fd)));
76
+ });
77
+
78
+ function fifoTimeout(): Error {
79
+ return new Error("the Agent Terminal did not open its FIFOs in time");
80
+ }
81
+
82
+ function closeFd(fd: number): void {
83
+ try {
84
+ closeSync(fd);
85
+ } catch {
86
+ // Already closed.
87
+ }
88
+ }
89
+
90
+ function errorCode(error: unknown): unknown {
91
+ return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
92
+ }
93
+
94
+ /**
95
+ * Opens a FIFO end with a blocking open on the thread pool. At the deadline it
96
+ * opens the opposite end non-blocking, so a blocked or queued open returns at
97
+ * once, and rejects without a wait for that open. A late open is closed when
98
+ * it settles; the opposite end stays open until then. A probe of the opposite
99
+ * end must already be open for the non-blocking open to work.
100
+ */
101
+ async function openBlocking(step: {
102
+ readonly path: string;
103
+ readonly flags: number;
104
+ readonly opposite: number;
105
+ readonly at: number;
106
+ readonly signal?: AbortSignal | undefined;
107
+ readonly openFd: FdOpen;
108
+ }): Promise<number> {
109
+ const { path, flags, opposite, at, signal, openFd } = step;
110
+ const pending = openFd(path, flags);
111
+ let timer: ReturnType<typeof setTimeout> | undefined;
112
+ let onAbort = (): void => {};
113
+ const late = new Promise<"late">((resolve) => {
114
+ onAbort = () => resolve("late");
115
+ timer = setTimeout(onAbort, Math.max(0, at - Date.now()));
116
+ if (signal?.aborted) onAbort();
117
+ else signal?.addEventListener("abort", onAbort, { once: true });
118
+ });
119
+ const first = await Promise.race([pending, late]);
120
+ clearTimeout(timer);
121
+ signal?.removeEventListener("abort", onAbort);
122
+ if (first !== "late") return first;
123
+ let unblock = -1;
124
+ try {
125
+ unblock = openSync(path, opposite | constants.O_NONBLOCK);
126
+ } catch {
127
+ // No peer to free: the open is not blocked on one.
128
+ }
129
+ void pending
130
+ .then(closeFd, () => undefined)
131
+ .finally(() => {
132
+ if (unblock >= 0) closeFd(unblock);
133
+ });
134
+ throw fifoTimeout();
135
+ }
136
+
137
+ /** Polls a non-blocking write open until a reader (sh) is present. */
138
+ async function waitForReader(path: string, at: number, signal?: AbortSignal): Promise<number> {
139
+ for (;;) {
140
+ try {
141
+ return openSync(path, constants.O_WRONLY | constants.O_NONBLOCK);
142
+ } catch (error) {
143
+ if (errorCode(error) !== "ENXIO") throw error;
144
+ }
145
+ if (Date.now() >= at || signal?.aborted) throw fifoTimeout();
146
+ await Bun.sleep(POLL_MS);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Opens the Orchestrator ends without blocking the event loop.
152
+ *
153
+ * Order: read probes on `stdout` and `stderr`, so the writes of `sh` do not
154
+ * block; a poll until `sh` reads `stdin`; then blocking opens of all three on
155
+ * the thread pool, which return at once because each peer is present.
156
+ * An abort of `signal` ends the open like the deadline does. `openFd` replaces
157
+ * the blocking open step in tests.
158
+ */
159
+ export function createFifoOpener(options: { readonly openFd?: FdOpen } = {}): FifoOpener {
160
+ const openFd = options.openFd ?? poolOpen;
161
+ return async (dir, deadlineMs, signal) => {
162
+ const at = Date.now() + deadlineMs;
163
+ const paths = { in: join(dir, "stdin"), out: join(dir, "stdout"), err: join(dir, "stderr") };
164
+ const read = constants.O_RDONLY;
165
+ const write = constants.O_WRONLY;
166
+ const held: number[] = [];
167
+ const opened: number[] = [];
168
+ try {
169
+ held.push(openSync(paths.out, read | constants.O_NONBLOCK));
170
+ held.push(openSync(paths.err, read | constants.O_NONBLOCK));
171
+ held.push(await waitForReader(paths.in, at, signal));
172
+ const results = await Promise.allSettled([
173
+ openBlocking({ path: paths.in, flags: write, opposite: read, at, signal, openFd }),
174
+ openBlocking({ path: paths.out, flags: read, opposite: write, at, signal, openFd }),
175
+ openBlocking({ path: paths.err, flags: read, opposite: write, at, signal, openFd }),
176
+ ]);
177
+ for (const result of results) if (result.status === "fulfilled") opened.push(result.value);
178
+ const failed = results.find((result) => result.status === "rejected");
179
+ if (failed !== undefined) throw failed.reason;
180
+ const [inFd, outFd, errFd] = opened;
181
+ if (inFd === undefined || outFd === undefined || errFd === undefined) {
182
+ throw new Error("the Agent Terminal FIFOs did not open");
183
+ }
184
+ return endsOf({ inFd, outFd, errFd });
185
+ } catch (error) {
186
+ for (const fd of opened) closeFd(fd);
187
+ throw error;
188
+ } finally {
189
+ for (const fd of held) closeFd(fd);
190
+ }
191
+ };
192
+ }
193
+
194
+ /** The opener with the real blocking open on the async fs pool. */
195
+ export const openFifoEnds: FifoOpener = createFifoOpener();
196
+
197
+ function endsOf(fds: {
198
+ readonly inFd: number;
199
+ readonly outFd: number;
200
+ readonly errFd: number;
201
+ }): FifoEnds {
202
+ const stdin = fifoWriter(fds.inFd);
203
+ const out = fifoReader(fds.outFd);
204
+ const err = fifoReader(fds.errFd);
205
+ return {
206
+ stdin,
207
+ stdout: out.stream,
208
+ stderr: err.stream,
209
+ close: () => {
210
+ stdin.close();
211
+ out.close();
212
+ err.close();
213
+ },
214
+ };
215
+ }
216
+
217
+ /**
218
+ * A read end. Bun polls a FIFO and keeps its own copy of the fd, so our fd
219
+ * closes at once. In Bun 1.3.14 a `node:fs` stream on a FIFO holds an async fs
220
+ * pool thread for each waiting read (spec D1, ADR-0072).
221
+ */
222
+ function fifoReader(fd: number): { stream: ReadableStream<Uint8Array>; close(): void } {
223
+ const reader = Bun.file(fd).stream().getReader();
224
+ closeFd(fd);
225
+ const stop = (): void => {
226
+ void reader.cancel().catch(() => undefined);
227
+ };
228
+ let finished = false;
229
+ const stream = new ReadableStream<Uint8Array>({
230
+ async pull(controller) {
231
+ if (finished) return;
232
+ let result: { done: boolean; value?: Uint8Array | undefined };
233
+ try {
234
+ result = await reader.read();
235
+ } catch {
236
+ result = { done: true, value: undefined };
237
+ }
238
+ if (finished) return;
239
+ if (result.done || result.value === undefined) {
240
+ finished = true;
241
+ controller.close();
242
+ return;
243
+ }
244
+ controller.enqueue(result.value);
245
+ },
246
+ cancel() {
247
+ finished = true;
248
+ stop();
249
+ },
250
+ });
251
+ return { stream, close: stop };
252
+ }
253
+
254
+ /** EPIPE after pi exits: a write stays best-effort, as with a pipe. */
255
+ function quiet(result: number | Promise<number>): number | Promise<number> {
256
+ if (result instanceof Promise) result.catch(() => undefined);
257
+ return result;
258
+ }
259
+
260
+ /** The write end: a Bun FileSink, which waits on poll readiness. Our fd closes at once. */
261
+ function fifoWriter(fd: number): ProcessInput & { close(): void } {
262
+ const sink = Bun.file(fd).writer();
263
+ closeFd(fd);
264
+ let ended = false;
265
+ const end = (): void => {
266
+ if (ended) return;
267
+ ended = true;
268
+ try {
269
+ quiet(sink.end());
270
+ } catch {
271
+ // The reader is gone.
272
+ }
273
+ };
274
+ return {
275
+ write: (chunk: string) => {
276
+ if (ended) return false;
277
+ try {
278
+ return quiet(sink.write(chunk));
279
+ } catch {
280
+ return false;
281
+ }
282
+ },
283
+ flush: () => {
284
+ if (ended) return undefined;
285
+ try {
286
+ return quiet(sink.flush());
287
+ } catch {
288
+ return undefined;
289
+ }
290
+ },
291
+ end,
292
+ close: end,
293
+ };
294
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Activation of Agent Terminals (ADR-0072): the one place that picks the hc
3
+ * launcher or the direct launcher for a Run.
4
+ */
5
+
6
+ import { directLauncher } from "./direct-launcher.ts";
7
+ import type { HcCalls } from "./hc-call.ts";
8
+ import { createHcConnectCalls } from "./hc-connect.ts";
9
+ import { withDirectFallback } from "./hc-fallback-launcher.ts";
10
+ import { createHcLauncher } from "./hc-launcher.ts";
11
+ import { createLiveTransport } from "./live-transport.ts";
12
+ import type { ProcessLauncher } from "./process-launcher.ts";
13
+ import type { TransportFactory } from "./transport.ts";
14
+
15
+ /** What activation reads. Every seam except `agentTerminals` has a production default. */
16
+ export interface AgentLauncherOptions {
17
+ /** `agentTerminalsOf(config)`: false turns Agent Terminals off. */
18
+ readonly agentTerminals: boolean;
19
+ /** The Run id for the `yaag.run` label. */
20
+ readonly runId?: string;
21
+ readonly env?: Readonly<Record<string, string | undefined>>;
22
+ /** Resolves a binary on `PATH`; null when it is missing. */
23
+ readonly which?: (binary: string) => string | null;
24
+ /** Builds the hc call interface; called only when all conditions hold. */
25
+ readonly calls?: (hcPath: string) => HcCalls;
26
+ /** Takes the one hc fallback warning line; stderr by default. */
27
+ readonly warn?: (line: string) => void;
28
+ }
29
+
30
+ /**
31
+ * Gives the hc launcher only when the key is not false, `HC_TERMINAL_ID` is
32
+ * set, and `hc` resolves on `PATH`. Otherwise it gives the direct launcher and
33
+ * builds no hc client. Inside hc, the first hc failure writes one warning
34
+ * and the launcher uses the direct launcher for the rest of the Run.
35
+ */
36
+ export function selectAgentLauncher(options: AgentLauncherOptions): ProcessLauncher {
37
+ if (options.agentTerminals === false) return directLauncher;
38
+ const env = options.env ?? process.env;
39
+ const hostTerminal = env.HC_TERMINAL_ID;
40
+ if (hostTerminal === undefined || hostTerminal === "") return directLauncher;
41
+ const hcPath = (options.which ?? Bun.which)("hc");
42
+ if (hcPath === null) return directLauncher;
43
+ const calls = (options.calls ?? createHcConnectCalls)(hcPath);
44
+ return withDirectFallback({
45
+ hc: createHcLauncher({
46
+ calls,
47
+ hostTerminal,
48
+ ...(options.runId === undefined ? {} : { runId: options.runId }),
49
+ }),
50
+ direct: directLauncher,
51
+ ...(options.warn === undefined ? {} : { warn: options.warn }),
52
+ });
53
+ }
54
+
55
+ /** The live transport over the launcher `selectAgentLauncher` picks. */
56
+ export function liveTransportFor(options: AgentLauncherOptions): TransportFactory {
57
+ return createLiveTransport(selectAgentLauncher(options));
58
+ }