@niwa-labs/harness-mcode 0.0.0-stage → 0.0.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.
@@ -0,0 +1,1840 @@
1
+ /**
2
+ * The control side for MiniMax Code.
3
+ *
4
+ * It speaks ACP — the Agent Client Protocol — over the child's stdin/stdout: a JSON-RPC
5
+ * conversation with `mcode acp`. It never scrapes stdout: the protocol names the session, the
6
+ * turns and the answers, and everything below is read off it.
7
+ *
8
+ * It owns every `mcode` child it starts, each in its own process group, and stops them itself:
9
+ * an in-protocol `session/cancel`, then SIGTERM to the group, then SIGKILL.
10
+ *
11
+ * The wire discipline: the handshake, the request/reply table, the turn accounting, `followUp`
12
+ * as a FULL `session/prompt` request (so delivery is confirmed), the FIFO queue of follow-ups,
13
+ * and the stop ladder: in-protocol cancel, then SIGTERM, a grace window, then SIGKILL to the
14
+ * group.
15
+ *
16
+ * The mcode-specific facts: the `acp` subcommand, the `initialize` protocol version (the
17
+ * integer 1), the extension gate in `clientCapabilities` (`minimax-code/extensions`, without
18
+ * which mcode offers no steer, no queue and no notifications), the `permissionMode` config
19
+ * option, and the model option's compact `m:<provider>:<model>:u` encoding.
20
+ */
21
+
22
+ import { spawnSync } from "node:child_process";
23
+ import { randomUUID } from "node:crypto";
24
+ import { z } from "zod";
25
+
26
+ import { assertNever, timestamp } from "@niwa-labs/core";
27
+ import type { Answer, Question } from "@niwa-labs/core";
28
+ import {
29
+ InputNotSent,
30
+ InputPossiblySent,
31
+ describeToolsMode,
32
+ modeOf,
33
+ requireLaunch,
34
+ Unavailable,
35
+ Unsupported,
36
+ DEFAULT_TURN_TIMEOUT_MS,
37
+ modelName,
38
+ unknownVariantSigns,
39
+ HarnessIdSchema,
40
+ sessionId as makeSessionId,
41
+ } from "@niwa-labs/harness";
42
+ import type {
43
+ Dispatch,
44
+ LaunchCapabilities,
45
+ SessionMode,
46
+ AskAnswer,
47
+ AskOptions,
48
+ DeliveryReceipt,
49
+ LifeEvent,
50
+ McpServerSpec,
51
+ ModelName,
52
+ PermissionMark,
53
+ Prompt,
54
+ ResumeOptions,
55
+ SendOptions,
56
+ SessionControl,
57
+ SessionState,
58
+ StartOptions,
59
+ StartedSession,
60
+ ToolsMode,
61
+ TurnOutcome,
62
+ VisibleActions,
63
+ SessionId,
64
+ ReverseHandler,
65
+ } from "@niwa-labs/harness";
66
+ import { LIVE_PROCESS_REFUSAL, spawnAgent } from "@niwa-labs/sandbox";
67
+ import type { AgentProcess } from "@niwa-labs/sandbox";
68
+
69
+ import { AcpClient, acpVariant, answerText, readVariant } from "@niwa-labs/acp";
70
+ import type { AgentNotification, AgentRequest, RequestId, RpcOutcome, UnknownVariant } from "@niwa-labs/acp";
71
+
72
+ import {
73
+ NCODE_ACP_PROTOCOL,
74
+ PERMISSION_MODE_META,
75
+ TURN_STATUS,
76
+ TurnStatusResult,
77
+ ncodeMarks,
78
+ refusesSessionMode,
79
+ } from "../ncode/protocol.ts";
80
+ import type {
81
+ NcodePermissionMark,
82
+ NcodeSessionMeta,
83
+ NcodeUpdateMarks,
84
+ TurnStatusResult as TurnStatus,
85
+ } from "../ncode/protocol.ts";
86
+ import { homeOfProfile } from "./paths.ts";
87
+ import { inputOpen, writeLine } from "./transport.ts";
88
+ import { formFields, formSteps, isQuestionnaire, permissionAsk } from "./reverse.ts";
89
+ import { Acp, EXTENSIONS_META, MCODE_ACP_PROTOCOL, McodeAgentNotification, McodeAgentRequest, McodeInitializeMeta } from "./protocol.ts";
90
+ import type { McodeMethod, McodePermissionMode } from "./protocol.ts";
91
+
92
+ /**
93
+ * What an mcode session takes at launch: a model and the `thinkingEffort` option, set on the
94
+ * session, and the `permissionMode` option for a working mode. Its own `auto` is a classifier that
95
+ * decides each tool call, so every working mode of niwa has one.
96
+ */
97
+ export const MCODE_LAUNCH: LaunchCapabilities = {
98
+ model: true,
99
+ effort: ["default", "low", "medium", "high", "xhigh", "max"],
100
+ modes: ["ask", "auto", "full"],
101
+ };
102
+
103
+ /** The `permissionMode` of an mcode session for each working mode. */
104
+ const PERMISSION_MODES = {
105
+ ask: "default",
106
+ auto: "auto",
107
+ full: "bypassPermissions",
108
+ } as const satisfies Record<SessionMode, McodePermissionMode>;
109
+
110
+ /**
111
+ * The two lineages of the harness, which share the wire and the files: `upstream` is the
112
+ * published `@minimax-ai/code`, `fork` is the owner's own build of it. The fork also takes the
113
+ * working mode in `session/new` and marks each tool call with the permission decision.
114
+ */
115
+ export type MinimaxLineage = "upstream" | "fork";
116
+
117
+ /** The program of each lineage when the caller names none: a bare name, resolved through PATH. */
118
+ export const DEFAULT_BINARIES: Readonly<Record<MinimaxLineage, string>> = {
119
+ upstream: "mcode",
120
+ fork: "ncode",
121
+ };
122
+
123
+ /**
124
+ * Whether the build of a lineage takes `--profile` on `mcode acp`. The published build exits with
125
+ * its usage text on it, so a profile named for it is refused, never passed on.
126
+ */
127
+ export const PROFILE_SUPPORT: Readonly<Record<MinimaxLineage, boolean>> = {
128
+ upstream: false,
129
+ fork: true,
130
+ };
131
+
132
+ export interface McodeControlOptions {
133
+ /** The harness instance id: half of a session's identity. */
134
+ readonly harness: string;
135
+ /** The lineage of the harness (`upstream` by default). */
136
+ readonly lineage?: MinimaxLineage;
137
+ /** The binary; a bare name is resolved through PATH. Each lineage has a default of its own. */
138
+ readonly binary?: string;
139
+ /** The working mode of sessions, when the caller does not choose one per start. */
140
+ readonly mode?: SessionMode;
141
+ /**
142
+ * What happens when a tool asks for permission, in a mode that can ask. `"allow"` (the default)
143
+ * grants every request, `"deny"` refuses every request. A function answers each request itself;
144
+ * a function that throws denies.
145
+ */
146
+ readonly permissions?: PermissionPolicy;
147
+ /** The model, when the caller does not choose one per start. */
148
+ readonly model?: string;
149
+ /** The thinking effort, when the caller does not choose one per start. */
150
+ readonly effort?: string;
151
+ /** The account profile, when the caller pins one. Each profile is a separate account. */
152
+ readonly profile?: string;
153
+ /** The directory the installation keeps its sessions in; the home of the profile when absent. */
154
+ readonly home?: string;
155
+ /** How long one call (the handshake, a config option, a turn status) waits, in milliseconds. */
156
+ readonly callTimeoutMs?: number;
157
+ /** How long the agent has to let a cancelled turn go, in milliseconds; the call timeout by default. */
158
+ readonly cancelGraceMs?: number;
159
+ /** How long a turn waits for its result, in milliseconds. */
160
+ readonly turnTimeoutMs?: number;
161
+ /** How long a graceful stop waits before the hard kill, in milliseconds. */
162
+ readonly stopGraceMs?: number;
163
+ }
164
+
165
+ /** A tool the agent asks to use. */
166
+ export interface PermissionRequest {
167
+ readonly tool: string;
168
+ readonly input: unknown;
169
+ }
170
+
171
+ /** What to do with a permission request. */
172
+ export type PermissionDecision =
173
+ | { readonly behavior: "allow" }
174
+ | { readonly behavior: "deny"; readonly message?: string };
175
+
176
+ /** How permission requests are answered. */
177
+ export type PermissionPolicy =
178
+ | "allow"
179
+ | "deny"
180
+ | ((request: PermissionRequest) => Promise<PermissionDecision>);
181
+
182
+ /** A `SessionControl` that can also stop what it started. */
183
+ export interface McodeSessionControl extends SessionControl {
184
+ /** Stops a session and lets it go: the contract's release of one session. */
185
+ close(id: SessionId): Promise<void>;
186
+
187
+ /** Stops a session and the process it owns. */
188
+ stop(id: SessionId): Promise<void>;
189
+ /** Stops every process this control side started, including a start still in progress. */
190
+ dispose(): Promise<void>;
191
+ }
192
+
193
+ /** A request that failed, and how far it got: only an `uncertain` one may have been done. */
194
+ class RequestFailed extends Error {
195
+ constructor(
196
+ message: string,
197
+ readonly dispatch: Dispatch,
198
+ ) {
199
+ super(message);
200
+ }
201
+ }
202
+
203
+ /** An error the agent answered with, as JSON-RPC, and the code it came with. */
204
+ class AgentRefusal extends RequestFailed {
205
+ constructor(
206
+ message: string,
207
+ readonly code: number | undefined,
208
+ dispatch: Dispatch,
209
+ ) {
210
+ super(message, dispatch);
211
+ }
212
+ }
213
+
214
+ const DEFAULT_CALL_TIMEOUT_MS = 60_000;
215
+ const DEFAULT_STOP_GRACE_MS = 5_000;
216
+ /** The most bytes one stdout line may hold. */
217
+ const MAX_LINE_BYTES = 16 * 1024 * 1024;
218
+ /** How much of stderr is kept to explain a death. */
219
+ const STDERR_TAIL_CHARS = 2_000;
220
+
221
+ /**
222
+ * The extension gate.
223
+ *
224
+ * Without it mcode offers no steer, no queue, no goal and no delegation methods or
225
+ * notifications (the extension version is read from the initialize reply's `_meta`).
226
+ */
227
+ const EXTENSION_META = { [EXTENSIONS_META]: { version: 1, notifications: true } } as const;
228
+
229
+ /** Whether an initialize reply advertises one of the extension methods (the fork's included). */
230
+ function servesMethod(reply: Record<string, unknown>, method: McodeMethod | typeof TURN_STATUS): boolean {
231
+ const meta = McodeInitializeMeta.safeParse(reply["_meta"]);
232
+ return meta.success && meta.data[EXTENSIONS_META].methods.includes(method);
233
+ }
234
+
235
+ /**
236
+ * The lineage an initialize reply gives away. The fork serves two requests the published build
237
+ * does not (`turn_status` and `session/history`); a reply that advertises the extensions without
238
+ * them is the published build's. A reply with no extension advertisement says nothing.
239
+ */
240
+ export function lineageOfReply(reply: Record<string, unknown>): MinimaxLineage | undefined {
241
+ const meta = McodeInitializeMeta.safeParse(reply["_meta"]);
242
+ if (!meta.success) return undefined;
243
+ const methods = meta.data[EXTENSIONS_META].methods;
244
+ return FORK_ONLY_METHODS.some((method) => methods.includes(method)) ? "fork" : "upstream";
245
+ }
246
+
247
+ /** The requests only the fork serves. */
248
+ const FORK_ONLY_METHODS: readonly string[] = [TURN_STATUS, "session/history"];
249
+
250
+ /** Whether an initialize reply advertises the steer request. */
251
+ export function servesSteer(reply: Record<string, unknown>): boolean {
252
+ return servesMethod(reply, "mcode/session/steer");
253
+ }
254
+
255
+ /** How often a turn this side did not send is asked about, in milliseconds. */
256
+ const FOREIGN_TURN_POLL_MS = 500;
257
+
258
+ /** The shape of an ACP model option value: `m:<provider>:<model>:<variant>`. */
259
+ const OPTION_VALUE = /^m:[^:]*:[^:]+:(?:u|v:.*)$/;
260
+
261
+ /**
262
+ * The ACP model option value.
263
+ *
264
+ * A model id is `provider/model` or `provider/model#variant`, and it travels as a compact
265
+ * record: `m:<provider>:<model>:<variant>`. The variant is `u` for "none selected" and
266
+ * `v:<variant>` when one is named.
267
+ *
268
+ * The agent refuses a value it does not advertise: the options it offers are read from the
269
+ * session, and a value outside them is "Model selection is not advertised". So the value is
270
+ * matched against what the session advertised, and the advertised one that fits the id wins.
271
+ *
272
+ * A value that is already an option value is the agent's own naming of a model (the model a
273
+ * session ran): it is taken as it is.
274
+ */
275
+ export function mcodeModelOptionValue(
276
+ modelId: string,
277
+ advertised?: readonly { value: string; name?: string }[],
278
+ ): string {
279
+ if (OPTION_VALUE.test(modelId)) return modelId;
280
+ const [modelPart = modelId, variant] = modelId.split("#", 2);
281
+ const separator = modelPart.indexOf("/");
282
+ const provider = separator === -1 ? "" : modelPart.slice(0, separator);
283
+ const model = separator === -1 ? modelPart : modelPart.slice(separator + 1);
284
+ const suffix =
285
+ variant === undefined || variant === "" ? "u" : `v:${encodeURIComponent(variant)}`;
286
+ const wanted = `m:${encodeURIComponent(provider)}:${encodeURIComponent(model)}:${suffix}`;
287
+
288
+ if (advertised !== undefined && advertised.length > 0) {
289
+ const exact = advertised.find((option) => option.value === wanted);
290
+ if (exact !== undefined) return exact.value;
291
+ // A variant that was named is the variant that is asked for: another one is another model's
292
+ // behaviour, so it is left to the agent to refuse.
293
+ if (suffix !== "u") return wanted;
294
+ // The agent offers the same model, of the provider that was named, with other variants. A
295
+ // variant that is empty (`v:`) means "no thinking", and some models — MiniMax-M3.1-Flash
296
+ // among them — refuse it with an internal error, so a named variant is preferred over an
297
+ // empty one.
298
+ const sameModel = advertised.filter((option) => {
299
+ const parts = option.value.split(":");
300
+ return (
301
+ parts.length >= 3 &&
302
+ parts[2] === encodeURIComponent(model) &&
303
+ (provider === "" || parts[1] === encodeURIComponent(provider))
304
+ );
305
+ });
306
+ const named = sameModel.find((option) => {
307
+ const parts = option.value.split(":");
308
+ const variant = parts.slice(3).join(":");
309
+ return variant.startsWith("v:") && variant.length > "v:".length;
310
+ });
311
+ if (named !== undefined) return named.value;
312
+ if (sameModel.length > 0) return sameModel[0]?.value ?? wanted;
313
+ }
314
+ return wanted;
315
+ }
316
+
317
+ /**
318
+ * The model an agent says a session runs: the current value of its `model` config option, as the
319
+ * agent names it. It is an option value, so asking for it again takes it as it is.
320
+ */
321
+ function currentModelOf(configOptions: unknown): ModelName | undefined {
322
+ if (!Array.isArray(configOptions)) return undefined;
323
+ for (const option of configOptions as Array<Record<string, unknown>>) {
324
+ const current = option["currentValue"];
325
+ if ((option["id"] === "model" || option["configId"] === "model") && typeof current === "string" && current !== "") {
326
+ return modelName(current);
327
+ }
328
+ }
329
+ return undefined;
330
+ }
331
+
332
+ // ---------------------------------------------------------------------------
333
+ // The wire
334
+ // ---------------------------------------------------------------------------
335
+
336
+ /** The fork's decision on a tool call, as niwa records it: without the fork's free-text reason. */
337
+ function permissionMarkOf(mark: NcodePermissionMark): PermissionMark {
338
+ return { decision: mark.decision, decidedBy: mark.decidedBy, ruleKind: mark.ruleKind, mode: mark.mode };
339
+ }
340
+
341
+ /** An upstream update carries no marks: its reading never looks at the fork's `_meta`. */
342
+ const UPSTREAM_MARKS: NcodeUpdateMarks = { informational: false, permission: undefined };
343
+
344
+ /** The people waiting for a turn to settle. */
345
+ interface TurnWaiters {
346
+ readonly resolve: (result: TurnResult) => void;
347
+ readonly reject: (error: Error) => void;
348
+ }
349
+
350
+ /** The result of a turn. */
351
+ interface TurnResult {
352
+ readonly stopReason: string;
353
+ readonly text: string;
354
+ }
355
+
356
+ /** A message that waits behind the running turn. */
357
+ interface QueuedMessage {
358
+ readonly text: string;
359
+ /** The turn this message will run as: the receipt named it. */
360
+ readonly turn: number;
361
+ /** A question waits for the answer of its turn; a plain message does not. */
362
+ readonly ask?: TurnWaiters;
363
+ }
364
+
365
+ /** How many turn signs are kept for the first watcher of a session. */
366
+ const UNWATCHED_LIMIT = 64;
367
+
368
+ /** A watcher gets the events, then `undefined` once when the child is gone. */
369
+ type Watcher = (event: LifeEvent | undefined) => void;
370
+
371
+ /** The stop reason that means the agent finished its turn. */
372
+ const STOP_TURN = "end_turn";
373
+
374
+ /** Whether a value is a JSON object. */
375
+ function isRecord(value: unknown): value is Record<string, unknown> {
376
+ return typeof value === "object" && value !== null && !Array.isArray(value);
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // One session
381
+ // ---------------------------------------------------------------------------
382
+
383
+ /** One ACP session: the child, the session id and the turn accounting. */
384
+ class AcpSession {
385
+ /** The last turn number handed out; a receipt names the number its turn will run as. */
386
+ turn = 0;
387
+ /** The turn that is running, when one is. */
388
+ current = 0;
389
+ /** Whether a turn is running. */
390
+ running = false;
391
+ /**
392
+ * Whether the agent said, in its initialize reply, that it serves `mcode/session/steer`: the
393
+ * request that lands a message in the turn that is running. Only a fork of mcode may, so
394
+ * nothing is assumed.
395
+ */
396
+ steerable = false;
397
+ /**
398
+ * Whether the agent serves `mcode/session/turn_status`: the read of the turn a session has
399
+ * active, whichever client started it.
400
+ */
401
+ statusable = false;
402
+ /** Whether the child is gone. */
403
+ ended = false;
404
+ /** Whether a stop was asked for: no more writes. */
405
+ stopping = false;
406
+ /** The native session id, once the agent has named it. */
407
+ nativeId = "";
408
+ /**
409
+ * What marks the MCP servers this agent was given.
410
+ *
411
+ * mcode does not start them itself: a long-lived daemon does, in a process group of its own,
412
+ * so neither the agent's group nor its children reach them. The mark is in their environment,
413
+ * and a stop finds them by it.
414
+ */
415
+ readonly mark = randomUUID();
416
+ /**
417
+ * Why the session takes no new work, while the agent holds a turn it did not let go of after its
418
+ * cancel and its grace: what is sent meanwhile would wait behind a turn that may never end.
419
+ */
420
+ held: string | undefined;
421
+ /** The last line written to the child, settled when its input has taken it or failed it. */
422
+ accepted: Promise<void> = Promise.resolve();
423
+ /** The text of the turn that is running. */
424
+ text = "";
425
+ /** The messages written while a turn ran; each becomes its turn when the previous one ends. */
426
+ readonly queued: QueuedMessage[] = [];
427
+ /** Where this session's reverse requests go, when it has been given a place for them. */
428
+ reverse: ReverseHandler | undefined;
429
+ /** The requests of the agent that wait for an answer, by the id the agent gave them. */
430
+ private readonly asking = new Map<AbortController, string>();
431
+
432
+ readonly watchers = new Set<Watcher>();
433
+ /**
434
+ * The turn signs before anyone watched: the first turn begins inside `start`, before the
435
+ * caller has the session to watch. The first watcher is given them; after it nothing is kept.
436
+ */
437
+ private unwatched: LifeEvent[] | undefined = [];
438
+ /** The connection to the agent: set as soon as the child is spawned, before anything is written. */
439
+ client!: AcpClient;
440
+ /** Who is waiting for the running turn to settle. */
441
+ turnWaiters: TurnWaiters | undefined;
442
+ /** Who is waiting for no turn to be running. */
443
+ private readonly idleWaiters: Array<() => void> = [];
444
+
445
+ /**
446
+ * Why the running turn is over its time, once it is: the turn was cancelled, and it ends as a
447
+ * failure when the agent answers the cancelled prompt.
448
+ */
449
+ overdue: Error | undefined;
450
+
451
+ /**
452
+ * Who follows a turn the agent did not let go of in time, when the agent can say when it is
453
+ * over (`turn_status`). Unset, such a turn fails at the end of the grace and what waits goes out.
454
+ */
455
+ follow: ((turn: number, cancelledAt: number) => void) | undefined;
456
+
457
+ constructor(
458
+ readonly child: AgentProcess,
459
+ readonly cwd: string,
460
+ readonly turnTimeoutMs: number,
461
+ /** How long a cancelled turn may take to answer before it is given up on. */
462
+ readonly cancelGraceMs: number,
463
+ ) {}
464
+
465
+ /** The agent named the session. */
466
+ named(nativeId: string): void {
467
+ if (this.nativeId !== "") return;
468
+ this.nativeId = nativeId;
469
+ }
470
+
471
+ /** Watch the signs of life; the first watcher also gets the turn signs that came before it. */
472
+ watch(watcher: Watcher): void {
473
+ const missed = this.unwatched ?? [];
474
+ this.unwatched = undefined;
475
+ for (const event of missed) watcher(event);
476
+ this.watchers.add(watcher);
477
+ }
478
+
479
+ /** Drop what waits behind the running turn; a question that waited is told why. */
480
+ dropQueue(reason: string): void {
481
+ for (const message of this.queued.splice(0)) message.ask?.reject(new Error(reason));
482
+ }
483
+
484
+ emit(event: LifeEvent): void {
485
+ if (this.unwatched !== undefined && event.kind !== "activity") {
486
+ this.unwatched.push(event);
487
+ if (this.unwatched.length > UNWATCHED_LIMIT) this.unwatched.shift();
488
+ }
489
+ for (const watcher of [...this.watchers]) {
490
+ try {
491
+ watcher(event);
492
+ } catch {
493
+ // A broken watcher must not break the session.
494
+ }
495
+ }
496
+ }
497
+
498
+ /** A request of the agent begins to wait: the signal is aborted when the agent stops waiting for it. */
499
+ startAsking(requestId: string): { readonly signal: AbortSignal; readonly done: () => void } {
500
+ const controller = new AbortController();
501
+ this.asking.set(controller, requestId);
502
+ return { signal: controller.signal, done: () => this.asking.delete(controller) };
503
+ }
504
+
505
+ /** The agent no longer waits for one request, or for any of them. */
506
+ cancelAsking(requestId?: string): void {
507
+ for (const [controller, asked] of [...this.asking]) {
508
+ if (requestId !== undefined && asked !== requestId) continue;
509
+ this.asking.delete(controller);
510
+ controller.abort();
511
+ }
512
+ }
513
+
514
+ /** Hand out the number of the next turn. */
515
+ reserveTurn(): number {
516
+ this.turn += 1;
517
+ return this.turn;
518
+ }
519
+
520
+ beginTurn(turn: number): void {
521
+ this.current = turn;
522
+ this.running = true;
523
+ this.overdue = undefined;
524
+ this.text = "";
525
+ this.emit({ kind: "turn-started", turn, at: Date.now() });
526
+ }
527
+
528
+ /** Resolves when no turn is running. */
529
+ whenIdle(): Promise<void> {
530
+ if (!this.running) return Promise.resolve();
531
+ return new Promise<void>((resolve) => {
532
+ this.idleWaiters.push(resolve);
533
+ });
534
+ }
535
+
536
+ /** The turn is over, however it ended: say how, and release those who wait for the idle. */
537
+ private settle(outcome: TurnOutcome): void {
538
+ this.running = false;
539
+ this.held = undefined;
540
+ // The turn is over: nothing it asked is waited for any more.
541
+ this.cancelAsking();
542
+ this.emit({ kind: "turn-ended", turn: this.current, at: Date.now(), outcome });
543
+ for (const waiter of this.idleWaiters.splice(0)) waiter();
544
+ }
545
+
546
+ /** The agent answered the prompt: the turn ended. */
547
+ endTurn(result: TurnResult): void {
548
+ // Only an answer that says the turn ended of itself completed it; a cancel, a refusal or a limit did not.
549
+ this.settle(result.stopReason === STOP_TURN ? "completed" : "failed");
550
+ const waiters = this.turnWaiters;
551
+ this.turnWaiters = undefined;
552
+ waiters?.resolve(result);
553
+ this.drain();
554
+ }
555
+
556
+ /**
557
+ * The turn did not end with an answer: the agent refused the prompt, or it ran out of time. It
558
+ * failed, unless nobody can tell what became of it.
559
+ */
560
+ failTurn(reason: Error, outcome: TurnOutcome = "failed"): void {
561
+ this.emit({ kind: "activity", at: Date.now(), detail: `the turn failed: ${reason.message}` });
562
+ this.settle(outcome);
563
+ const waiters = this.turnWaiters;
564
+ this.turnWaiters = undefined;
565
+ waiters?.reject(reason);
566
+ this.drain();
567
+ }
568
+
569
+ /** A message that waited becomes the next turn. */
570
+ private drain(): void {
571
+ if (this.ended || this.stopping) return;
572
+ const next = this.queued.shift();
573
+ if (next === undefined) return;
574
+ this.beginTurn(next.turn);
575
+ // The waiter for this turn goes in before the prompt goes out, or the reply that ends it
576
+ // would find nobody waiting. A question that waited gets the result of its turn; a plain
577
+ // message has nobody waiting: a failed turn is reported by the signs of life, and the next
578
+ // queued message drains itself.
579
+ const settled = this.awaitTurn();
580
+ if (next.ask === undefined) settled.catch(() => undefined);
581
+ else settled.then(next.ask.resolve, next.ask.reject);
582
+ this.sendPrompt(next.text);
583
+ }
584
+
585
+ /** The child is gone: everyone waiting is released, the watchers are told to finish. */
586
+ end(failure: string | undefined): void {
587
+ if (this.ended) return;
588
+ this.ended = true;
589
+ this.running = false;
590
+ this.cancelAsking();
591
+ const reason = new Error(failure ?? "the mcode process is gone");
592
+ this.dropQueue(reason.message);
593
+ this.client.close(reason.message);
594
+ const waiters = this.turnWaiters;
595
+ this.turnWaiters = undefined;
596
+ waiters?.reject(reason);
597
+ for (const waiter of this.idleWaiters.splice(0)) waiter();
598
+ for (const watcher of [...this.watchers]) watcher(undefined);
599
+ }
600
+
601
+ /**
602
+ * Register the waiter for the turn that is about to run.
603
+ *
604
+ * The waiter goes in first: the reply to `session/prompt` is what ends the turn, and it may
605
+ * arrive before the line that writes the prompt has returned. A turn that is not answered in
606
+ * time is cancelled, and it fails when the agent answers the cancelled prompt: until then the
607
+ * agent still holds the prompt and refuses the next one ("A prompt is already active"), so the
608
+ * next prompt is never a second prompt at once. An agent that does not answer the cancel
609
+ * within the grace has the turn failed all the same.
610
+ */
611
+ awaitTurn(): Promise<TurnResult> {
612
+ if (this.ended) return Promise.reject(new Error("the mcode process is gone"));
613
+ return new Promise<TurnResult>((resolve, reject) => {
614
+ let grace: ReturnType<typeof setTimeout> | undefined;
615
+ const timer = setTimeout(() => {
616
+ if (this.turnWaiters !== waiters) return;
617
+ const overdue = new Error("the turn did not end in time");
618
+ this.overdue = overdue;
619
+ const cancelledAt = Date.now();
620
+ this.notify("session/cancel", { sessionId: this.nativeId });
621
+ // A cancelled turn is answered with cancelled to what it still asks, as ACP wants.
622
+ this.cancelAsking();
623
+ this.emit({ kind: "activity", at: Date.now(), detail: "the turn did not end in time: it was cancelled" });
624
+ grace = setTimeout(() => {
625
+ if (this.turnWaiters !== waiters) return;
626
+ if (this.follow !== undefined) {
627
+ // The agent can say when the turn is over: whoever waited for it is told it failed,
628
+ // and the turn stays running until the agent lets it go, so nothing is sent into it.
629
+ this.turnWaiters = undefined;
630
+ waiters.reject(overdue);
631
+ this.emit({ kind: "activity", at: Date.now(), detail: "the cancelled turn was not let go: it is followed" });
632
+ this.follow(this.current, cancelledAt);
633
+ return;
634
+ }
635
+ this.failTurn(overdue);
636
+ }, this.cancelGraceMs);
637
+ }, this.turnTimeoutMs);
638
+ const waiters: TurnWaiters = {
639
+ resolve: (result) => {
640
+ clearTimeout(timer);
641
+ clearTimeout(grace);
642
+ resolve(result);
643
+ },
644
+ reject: (error) => {
645
+ clearTimeout(timer);
646
+ clearTimeout(grace);
647
+ reject(error);
648
+ },
649
+ };
650
+ this.turnWaiters = waiters;
651
+ });
652
+ }
653
+
654
+ /** Send a notification; a child that is stopping or gone is not written to. */
655
+ notify(method: string, params: Record<string, unknown>): void {
656
+ this.client.notify(method, params);
657
+ }
658
+
659
+ /**
660
+ * Send one `session/prompt` for the running turn.
661
+ *
662
+ * The reply to it is what ends the turn: it carries the stop reason, and the text that was
663
+ * streamed while it ran. The reason is returned when the line could not be written at all.
664
+ */
665
+ sendPrompt(text: string): { readonly dispatch: Dispatch; readonly error: string } | undefined {
666
+ const turn = this.current;
667
+ let failed: { readonly dispatch: Dispatch; readonly error: string } | undefined;
668
+ this.client.send(
669
+ "session/prompt",
670
+ { sessionId: this.nativeId, prompt: [{ type: "text", text }] },
671
+ (outcome) => {
672
+ // A line the child's input refused, or failed on, is told before `send` returns.
673
+ if (!outcome.ok && (outcome.dispatch === "unsent" || (outcome.dispatch === "uncertain" && outcome.code === undefined && outcome.timedOut === undefined))) {
674
+ failed = { dispatch: outcome.dispatch, error: outcome.error };
675
+ }
676
+ this.promptAnswered(turn, outcome);
677
+ },
678
+ { timeoutMs: null },
679
+ );
680
+ return failed;
681
+ }
682
+
683
+ /**
684
+ * The answer to the prompt of `turn`. Only the answer of the turn that is running ends a turn:
685
+ * the late answer of a turn that was given up on says nothing about the one that came after it.
686
+ */
687
+ promptAnswered(turn: number, outcome: RpcOutcome): void {
688
+ if (turn !== this.current || !this.running) return;
689
+ if (!outcome.ok) {
690
+ // A prompt the agent answered with an error is not a turn that ended.
691
+ this.failTurn(outcome.code === undefined ? new Error(outcome.error) : new AgentRefusal(outcome.error, outcome.code, outcome.dispatch));
692
+ return;
693
+ }
694
+ if (this.overdue !== undefined) {
695
+ // The answer to a prompt that was cancelled for its time: the turn is over now, and it failed.
696
+ this.failTurn(this.overdue);
697
+ return;
698
+ }
699
+ const result = isRecord(outcome.result) ? outcome.result : {};
700
+ this.endTurn({ stopReason: typeof result["stopReason"] === "string" ? result["stopReason"] : "", text: this.text });
701
+ }
702
+ }
703
+
704
+ // ---------------------------------------------------------------------------
705
+ // The control side
706
+ // ---------------------------------------------------------------------------
707
+
708
+ export function mcodeControl(options: McodeControlOptions): McodeSessionControl {
709
+ const lineage = options.lineage ?? "upstream";
710
+ const binary = options.binary ?? DEFAULT_BINARIES[lineage];
711
+ const permissions = options.permissions ?? "allow";
712
+ const callTimeoutMs = options.callTimeoutMs ?? DEFAULT_CALL_TIMEOUT_MS;
713
+ const cancelGraceMs = options.cancelGraceMs ?? callTimeoutMs;
714
+ const turnTimeoutMs = options.turnTimeoutMs ?? DEFAULT_TURN_TIMEOUT_MS;
715
+ const stopGraceMs = options.stopGraceMs ?? DEFAULT_STOP_GRACE_MS;
716
+ const defaultModel = options.model;
717
+ const defaultEffort = options.effort;
718
+ const harnessId = HarnessIdSchema.parse(options.harness);
719
+ const home = options.home ?? homeOfProfile(options.profile);
720
+
721
+ /** The sessions reachable by id. */
722
+ const sessions = new Map<string, AcpSession>();
723
+ /** Every child this side started and has not seen close, so none can be forgotten. */
724
+ const owned = new Set<AcpSession>();
725
+ /** The processes being started: not owned yet, so a dispose waits for them. */
726
+ const launching = new Set<Promise<AcpSession>>();
727
+ let disposed = false;
728
+
729
+ /**
730
+ * mcode's ACP has no way to switch one of its tools off for a session, so a session that asks
731
+ * for it is refused by name, never started with the tools silently left on.
732
+ */
733
+ function refuseDisabledTools(
734
+ ability: string,
735
+ visible: VisibleActions | undefined,
736
+ tools?: ToolsMode,
737
+ ): void {
738
+ if (tools !== undefined && tools !== "all") {
739
+ throw new Unsupported(
740
+ harnessId,
741
+ "control",
742
+ ability,
743
+ `${describeToolsMode(tools)}: mcode's ACP takes no tool flag, and its --permission policy belongs to \`mcode exec\``,
744
+ );
745
+ }
746
+ const disabled = visible?.disabledTools ?? [];
747
+ if (disabled.length === 0) return;
748
+ throw new Unsupported(
749
+ harnessId,
750
+ "control",
751
+ ability,
752
+ `mcode cannot switch off its tools (${disabled.map((tool) => `"${tool}"`).join(", ")})`,
753
+ );
754
+ }
755
+
756
+ function unavailable(ability: string, detail: string): Unavailable {
757
+ return new Unavailable(harnessId, "control", ability, detail);
758
+ }
759
+
760
+ /** A failure of the wire, as the refusal the contract names. */
761
+ function refusal(ability: string, error: unknown): Unavailable {
762
+ if (error instanceof Unavailable) return error;
763
+ return unavailable(ability, error instanceof Error ? error.message : String(error));
764
+ }
765
+
766
+ // -- the wire -------------------------------------------------------------
767
+
768
+ /** A line of the child's stdout that is not JSON: a warning, never a crash. */
769
+ function handleGarbage(session: AcpSession, line: string): void {
770
+ session.emit({
771
+ kind: "activity",
772
+ at: Date.now(),
773
+ detail: `a line of the agent's output could not be read: ${line.slice(0, 200)}`,
774
+ });
775
+ }
776
+
777
+ /** The protocol of this side's lineage, as the unknowns it records name it. */
778
+ const protocol = lineage === "fork" ? NCODE_ACP_PROTOCOL : MCODE_ACP_PROTOCOL;
779
+
780
+ /** A message the snapshot of the protocol does not know: recorded as it came, never a crash. */
781
+ function emitUnknown(session: AcpSession, unknown: UnknownVariant): void {
782
+ for (const sign of unknownVariantSigns(Date.now(), unknown.protocol, unknown.variant, unknown.raw)) session.emit(sign);
783
+ }
784
+
785
+ /** Refuse a request of the agent, so it never waits on this side. */
786
+ function refuse(session: AcpSession, requestId: RequestId, method: string): void {
787
+ session.client.refuse(requestId, -32601, `niwa does not serve ${method}`);
788
+ }
789
+
790
+ /** Refuse a request of a known method whose params do not fit it, with the fields that do not. */
791
+ function refuseParams(session: AcpSession, requestId: RequestId, method: string, invalid: string): void {
792
+ session.client.refuse(requestId, -32602, `invalid params of ${method}: ${invalid}`);
793
+ }
794
+
795
+ /** A request of the agent: a permission or a questionnaire is answered, anything else refused. */
796
+ function answerRequest(session: AcpSession, requestId: RequestId, message: AgentRequest): void {
797
+ const read = readVariant(McodeAgentRequest, message, protocol, acpVariant);
798
+ if (!read.ok) {
799
+ emitUnknown(session, read.unknown);
800
+ if (read.invalid === undefined) refuse(session, requestId, read.unknown.variant);
801
+ else refuseParams(session, requestId, read.unknown.variant, read.invalid);
802
+ return;
803
+ }
804
+ const asked = read.value;
805
+ // The params as they came, with what the snapshot of the protocol does not name.
806
+ const params = isRecord(message.params) ? message.params : undefined;
807
+ switch (asked.method) {
808
+ case "session/request_permission":
809
+ void answerPermission(session, requestId, asked.params, params);
810
+ return;
811
+ case "elicitation/create":
812
+ if (session.reverse === undefined) refuse(session, requestId, asked.method);
813
+ else void answerElicitation(session, requestId, params, session.reverse);
814
+ return;
815
+ // The client advertises no file system, no terminal and no MCP transport, and mcode asks for none.
816
+ case "fs/read_text_file":
817
+ case "fs/write_text_file":
818
+ case "terminal/create":
819
+ case "terminal/kill":
820
+ case "terminal/output":
821
+ case "terminal/release":
822
+ case "terminal/wait_for_exit":
823
+ case "mcp/connect":
824
+ case "mcp/disconnect":
825
+ case "mcp/message":
826
+ refuse(session, requestId, asked.method);
827
+ return;
828
+ default:
829
+ assertNever(asked, "mcode ACP request");
830
+ }
831
+ }
832
+
833
+ /** A notification: each one is a sign of life, so a silent run and a hung run do not look the same. */
834
+ function handleNotification(session: AcpSession, message: AgentNotification): void {
835
+ const read = readVariant(McodeAgentNotification, message, protocol, acpVariant);
836
+ if (!read.ok) {
837
+ emitUnknown(session, read.unknown);
838
+ return;
839
+ }
840
+ const notification = read.value;
841
+ const at = Date.now();
842
+ switch (notification.method) {
843
+ case "session/update": {
844
+ const update = notification.params.update;
845
+ handleUpdate(session, update, lineage === "fork" ? ncodeMarks(update) : UPSTREAM_MARKS, at);
846
+ return;
847
+ }
848
+ case "$/cancel_request": {
849
+ // The agent stopped waiting for the answer to one of its requests.
850
+ const requestId = notification.params.requestId;
851
+ if (requestId !== null) session.cancelAsking(String(requestId));
852
+ return;
853
+ }
854
+ // The end of a questionnaire niwa answers in one reply, a message of an MCP transport niwa does
855
+ // not offer, and the session, queue, goal and delegation news of the extensions: niwa keeps its
856
+ // own queue and turns, so each is only a sign of life.
857
+ case "elicitation/complete":
858
+ case "mcp/message":
859
+ case "mcode/session/current_session_update":
860
+ case "mcode/session/queue_update":
861
+ case "mcode/session/goal_update":
862
+ case "mcode/session/delegation_update":
863
+ session.emit({ kind: "activity", at, detail: notification.method });
864
+ return;
865
+ default:
866
+ assertNever(notification, "mcode ACP notification");
867
+ }
868
+ }
869
+
870
+ /** One `session/update`, with what the fork marked it with (nothing, for upstream). */
871
+ function handleUpdate(session: AcpSession, update: Acp.SessionUpdate, marks: NcodeUpdateMarks, at: number): void {
872
+ switch (update.sessionUpdate) {
873
+ case "agent_message_chunk":
874
+ // Service speech rides the same channel as the answer: it must never end up in the
875
+ // text the caller reads.
876
+ if (marks.informational) {
877
+ session.emit({ kind: "activity", at, detail: "informational" });
878
+ return;
879
+ }
880
+ session.text += answerText(update.content);
881
+ session.emit({ kind: "activity", at, detail: "text" });
882
+ return;
883
+ case "tool_call":
884
+ case "tool_call_update": {
885
+ const permission = marks.permission === undefined ? undefined : permissionMarkOf(marks.permission);
886
+ session.emit({ kind: "activity", at, detail: update.sessionUpdate, ...(permission === undefined ? {} : { permission }) });
887
+ return;
888
+ }
889
+ // The replayed history, the thinking, the plan, the commands, the mode, the config, the
890
+ // session's title and the usage: none is part of the answer, each a sign of life.
891
+ case "user_message_chunk":
892
+ case "agent_thought_chunk":
893
+ case "plan":
894
+ case "plan_update":
895
+ case "plan_removed":
896
+ case "available_commands_update":
897
+ case "current_mode_update":
898
+ case "config_option_update":
899
+ case "session_info_update":
900
+ case "usage_update":
901
+ session.emit({ kind: "activity", at, detail: update.sessionUpdate });
902
+ return;
903
+ default:
904
+ assertNever(update, "mcode session update");
905
+ }
906
+ }
907
+
908
+ /**
909
+ * Answer the agent's permission request.
910
+ *
911
+ * A session with a place for its reverse requests sends the request there, as a question; any
912
+ * other session answers by its policy. The agent offers its options and this side picks one of
913
+ * them, always a once-only one: an id the agent did not offer is not a choice. When nothing
914
+ * fits the decision, the request is cancelled.
915
+ */
916
+ async function answerPermission(
917
+ session: AcpSession,
918
+ requestId: RequestId,
919
+ asked: Acp.RequestPermissionRequest,
920
+ params: Record<string, unknown> | undefined,
921
+ ): Promise<void> {
922
+ if (session.reverse !== undefined) {
923
+ const ask = permissionAsk(params);
924
+ const [answer] = (await reverseAnswer(session, session.reverse, requestId, [ask.question], "session/request_permission", params)) ?? [];
925
+ replyTo(session, requestId, { outcome: answer === undefined ? { outcome: "cancelled" } : ask.outcomeOf(answer) });
926
+ return;
927
+ }
928
+
929
+ // A question for a person is not a tool to be allowed: with nobody to ask, it ends as cancelled.
930
+ if (isQuestionnaire(params)) {
931
+ session.emit({ kind: "activity", at: Date.now(), detail: "a question was left unanswered: the session has nowhere to ask it" });
932
+ replyTo(session, requestId, { outcome: { outcome: "cancelled" } });
933
+ return;
934
+ }
935
+ const toolCall = asked.toolCall;
936
+ const tool = toolCall.title ?? "";
937
+ let decision: PermissionDecision = { behavior: "allow" };
938
+ if (permissions === "deny") {
939
+ decision = { behavior: "deny", message: "niwa denied this request" };
940
+ } else if (typeof permissions === "function") {
941
+ try {
942
+ decision = await permissions({ tool, input: toolCall.rawInput });
943
+ } catch {
944
+ decision = { behavior: "deny", message: "niwa denied this request" };
945
+ }
946
+ }
947
+ const wanted = decision.behavior === "allow" ? "allow_once" : "reject_once";
948
+ const picked = asked.options.find((option) => option.kind === wanted)?.optionId;
949
+ replyTo(session, requestId, {
950
+ outcome: picked === undefined ? { outcome: "cancelled" } : { outcome: "selected", optionId: picked },
951
+ });
952
+ }
953
+
954
+ /**
955
+ * Answer the questionnaire of the agent (`elicitation/create`), one niwa question for each of
956
+ * its steps. A step left without an answer ends the questionnaire: the agent is told it was
957
+ * cancelled, and nothing is answered for the person.
958
+ */
959
+ async function answerElicitation(
960
+ session: AcpSession,
961
+ requestId: RequestId,
962
+ params: Record<string, unknown> | undefined,
963
+ handler: ReverseHandler,
964
+ ): Promise<void> {
965
+ const steps = formSteps(params);
966
+ if (steps === undefined) {
967
+ session.client.refuse(requestId, -32602, "the questionnaire is not a form niwa can ask");
968
+ return;
969
+ }
970
+ const answers = await reverseAnswer(session, handler, requestId, steps.map((step) => step.question), "elicitation/create", params);
971
+ const content: Record<string, string | string[]> = {};
972
+ for (const [index, step] of steps.entries()) {
973
+ const answer = answers?.[index];
974
+ const fields = answer === undefined ? undefined : formFields(step, answer);
975
+ if (fields === undefined) {
976
+ replyTo(session, requestId, { action: "cancel" });
977
+ return;
978
+ }
979
+ Object.assign(content, fields);
980
+ }
981
+ replyTo(session, requestId, { action: "accept", content });
982
+ }
983
+
984
+ /**
985
+ * Hand questions to the place a session's reverse requests go, one after the other, and wait for
986
+ * the answers. The agent's wait is the request's: when the agent stops waiting (a cancel, the
987
+ * end of the turn, the end of the process) the questions are aborted and nothing is returned.
988
+ * A handler that fails, or answers nothing, ends the wait as no answer.
989
+ */
990
+ async function reverseAnswer(
991
+ session: AcpSession,
992
+ handler: ReverseHandler,
993
+ requestId: RequestId,
994
+ questions: readonly Question[],
995
+ method: string,
996
+ raw: unknown,
997
+ ): Promise<Answer[] | undefined> {
998
+ const asking = session.startAsking(String(requestId));
999
+ try {
1000
+ const answers: Answer[] = [];
1001
+ for (const question of questions) {
1002
+ if (asking.signal.aborted) return undefined;
1003
+ const answer = await handler(makeSessionId(harnessId, session.nativeId), {
1004
+ question,
1005
+ raw: { method, params: raw },
1006
+ signal: asking.signal,
1007
+ });
1008
+ if ("cancelled" in answer) return undefined;
1009
+ answers.push(answer);
1010
+ }
1011
+ return asking.signal.aborted ? undefined : answers;
1012
+ } catch {
1013
+ return undefined;
1014
+ } finally {
1015
+ asking.done();
1016
+ }
1017
+ }
1018
+
1019
+ /** Answer a request of the agent, once. */
1020
+ function replyTo(session: AcpSession, requestId: RequestId, result: Record<string, unknown>): void {
1021
+ session.client.reply(requestId, result);
1022
+ }
1023
+
1024
+ // -- the child ------------------------------------------------------------
1025
+
1026
+ /** The id of a session that is gone no longer names it, unless a newer process of the same session took the id. */
1027
+ function forget(session: AcpSession): void {
1028
+ if (sessions.get(session.nativeId) === session) sessions.delete(session.nativeId);
1029
+ }
1030
+
1031
+ /** Signal the child's process group: the child leads it, so the signal reaches what it started. */
1032
+ function signalGroup(session: AcpSession, signal: NodeJS.Signals): void {
1033
+ signalChild(session.child, signal);
1034
+ }
1035
+
1036
+ function signalChild(child: AgentProcess, signal: NodeJS.Signals): void {
1037
+ const pid = child.pid;
1038
+ if (pid === undefined) return;
1039
+ try {
1040
+ process.kill(-pid, signal);
1041
+ } catch {
1042
+ try {
1043
+ child.kill(signal);
1044
+ } catch {
1045
+ // The group is already gone.
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ /**
1051
+ * Spawn one agent and wire its streams. Process mode (`MCODE_SERVER_MODE=off`): the agent lives
1052
+ * in this process of its own, with the environment of its session, not in the shared daemon
1053
+ * `mcoded`, which no wrapper reaches and which could not tell one session's environment from
1054
+ * another's.
1055
+ */
1056
+ async function startProcess(cwd: string, plan: Pick<StartOptions, "env" | "box">): Promise<AcpSession> {
1057
+ if (options.profile !== undefined && !PROFILE_SUPPORT[lineage]) {
1058
+ throw new Unsupported(
1059
+ harnessId,
1060
+ "control",
1061
+ "profile",
1062
+ `the ${lineage} build of MiniMax Code takes no --profile (it would exit on it); drop the profile "${options.profile}" or use the fork`,
1063
+ );
1064
+ }
1065
+ const launch = launchProcess(cwd, plan);
1066
+ launching.add(launch);
1067
+ try {
1068
+ return await launch;
1069
+ } finally {
1070
+ launching.delete(launch);
1071
+ }
1072
+ }
1073
+
1074
+ async function launchProcess(cwd: string, plan: Pick<StartOptions, "env" | "box">): Promise<AcpSession> {
1075
+ const args = ["acp"];
1076
+ if (options.profile !== undefined) args.push("--profile", options.profile);
1077
+ const child = await spawnAgent({
1078
+ harness: harnessId,
1079
+ program: binary,
1080
+ args,
1081
+ cwd,
1082
+ env: { MCODE_DISABLE_TELEMETRY: "1", MCODE_SERVER_MODE: "off", ...plan.env },
1083
+ detached: true,
1084
+ box: plan.box,
1085
+ });
1086
+ if (disposed) {
1087
+ // The control side was closed while the process was being started: nothing owns it yet, so it goes here.
1088
+ const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
1089
+ signalChild(child, "SIGKILL");
1090
+ await Promise.race([closed, sleep(stopGraceMs)]);
1091
+ throw unavailable("start", "the control side is closed");
1092
+ }
1093
+ const session = new AcpSession(child, cwd, turnTimeoutMs, cancelGraceMs);
1094
+ owned.add(session);
1095
+
1096
+ // A write to a dead child is reported by the closing child, not thrown as an unhandled event.
1097
+ child.stdin?.on("error", () => undefined);
1098
+
1099
+ session.client = new AcpClient({
1100
+ write: (line) => {
1101
+ // A session that is stopping or gone is not written to, and neither is a closed input: the
1102
+ // line is certainly unsent then. A line the stream took is accepted, and the stream's own
1103
+ // report of it (its callback) is kept for whoever must know the line went out.
1104
+ const stdin = child.stdin;
1105
+ if (session.ended || session.stopping || !inputOpen(stdin)) return "unsent";
1106
+ // A stream that throws on the write leaves it unknown what became of the line: the client says so.
1107
+ const taken = writeLine(stdin, line);
1108
+ taken.catch(() => undefined);
1109
+ session.accepted = taken;
1110
+ return "accepted";
1111
+ },
1112
+ onRequest: (request) => answerRequest(session, request.id, request),
1113
+ onNotification: (notification) => handleNotification(session, notification),
1114
+ onUnreadable: (line) => handleGarbage(session, line),
1115
+ onOverflow: () => {
1116
+ // One line longer than the budget is a transport failure, not a session.
1117
+ session.end("a line of the agent's output was longer than the frame budget");
1118
+ void stopSession(session);
1119
+ },
1120
+ callTimeoutMs,
1121
+ maxLineBytes: MAX_LINE_BYTES,
1122
+ });
1123
+ child.stdout?.setEncoding("utf8");
1124
+ child.stdout?.on("data", (chunk: string) => session.client.feed(chunk));
1125
+
1126
+ let stderr = "";
1127
+ child.stderr?.setEncoding("utf8");
1128
+ child.stderr?.on("data", (chunk: string) => {
1129
+ stderr = (stderr + chunk).slice(-STDERR_TAIL_CHARS);
1130
+ });
1131
+
1132
+ child.once("close", (code: number | null) => {
1133
+ owned.delete(session);
1134
+ forget(session);
1135
+ // Whatever the agent started may outlive it; the group is the unit of cleanup, and the MCP
1136
+ // servers it was given, which are in no group of its own, go by their mark.
1137
+ signalGroup(session, "SIGKILL");
1138
+ // A stop that is under way reaps them itself.
1139
+ if (!session.stopping) void stopMarked(session.mark);
1140
+ session.end(
1141
+ `${binary} exited with code ${String(code)}${stderr.trim() === "" ? "" : `: ${stderr.trim()}`}`,
1142
+ );
1143
+ });
1144
+ child.once("error", (error: Error) => {
1145
+ owned.delete(session);
1146
+ if (!session.stopping) void stopMarked(session.mark);
1147
+ session.end(`${binary} could not be run: ${error.message}`);
1148
+ });
1149
+
1150
+ return session;
1151
+ }
1152
+
1153
+ /**
1154
+ * Send a request and wait for its reply. A failure is a `RequestFailed` that says how far the
1155
+ * request got: an error of the agent is an `AgentRefusal` with its code, and refused only when the
1156
+ * code says nothing ran; an answer that did not come in time is uncertain, since whether the
1157
+ * agent acted on the request is unknown.
1158
+ */
1159
+ async function request(
1160
+ session: AcpSession,
1161
+ method: string,
1162
+ params: Record<string, unknown>,
1163
+ label: string,
1164
+ ): Promise<Record<string, unknown>> {
1165
+ if (session.ended || session.stopping) throw new RequestFailed("the agent process is gone", "unsent");
1166
+ const outcome = await session.client.request(method, params);
1167
+ if (outcome.ok) return isRecord(outcome.result) ? outcome.result : {};
1168
+ if (outcome.code !== undefined) throw new AgentRefusal(outcome.error, outcome.code, outcome.dispatch);
1169
+ if (outcome.timedOut === true) throw new RequestFailed(`${label} did not finish in time`, "uncertain");
1170
+ throw new RequestFailed(outcome.error, outcome.dispatch);
1171
+ }
1172
+
1173
+ /** The refusal of an old daemon, which cannot take the mode of a session, as an error that says what to do. */
1174
+ function withModeSupport(error: unknown, method: string): unknown {
1175
+ if (error instanceof AgentRefusal && refusesSessionMode(error.code, error.message)) {
1176
+ return new Error(
1177
+ `${method} was refused: the running mcode daemon cannot take a permission mode per session; restart mcoded (the agent said: ${error.message})`,
1178
+ );
1179
+ }
1180
+ return error;
1181
+ }
1182
+
1183
+ /** The handshake: initialize, then session/new or session/load, then the config options. */
1184
+ async function handshake(
1185
+ session: AcpSession,
1186
+ model: string | undefined,
1187
+ effort: string | undefined,
1188
+ mode: SessionMode,
1189
+ existing: string | undefined,
1190
+ servers: readonly McpServerSpec[] | undefined,
1191
+ ): Promise<string> {
1192
+ const initialized = await request(
1193
+ session,
1194
+ "initialize",
1195
+ {
1196
+ protocolVersion: 1,
1197
+ clientInfo: { name: "niwa", version: "0.1.0" },
1198
+ // A session that has a place for its reverse requests can be asked a questionnaire as a form.
1199
+ clientCapabilities: {
1200
+ _meta: EXTENSION_META,
1201
+ ...(session.reverse === undefined ? {} : { elicitation: { form: {} } }),
1202
+ },
1203
+ },
1204
+ "the initialize handshake",
1205
+ );
1206
+ // Executables can be overridden or installed under aliases. Refuse a binary that answers
1207
+ // with the other lineage before sending it a session request.
1208
+ const answered = lineageOfReply(initialized);
1209
+ if (lineage === "fork" ? answered !== "fork" : answered === "fork") {
1210
+ throw unavailable(
1211
+ existing === undefined ? "start" : "resume",
1212
+ `${binary} answered as ${answered === "fork" ? "the fork" : answered === undefined ? "a build that names no lineage" : "the published build"}, and this side speaks to ${lineage === "fork" ? "the fork" : "the published build"}`,
1213
+ );
1214
+ }
1215
+ session.steerable = servesSteer(initialized);
1216
+ session.statusable = servesMethod(initialized, TURN_STATUS);
1217
+ if (session.statusable) {
1218
+ session.follow = (turn, cancelledAt) => void followForeignTurn(session, turn, cancelledAt);
1219
+ }
1220
+
1221
+ const permissionMode = PERMISSION_MODES[mode];
1222
+ const params: Record<string, unknown> = { cwd: session.cwd, mcpServers: mcpServersOf(servers, session.mark) };
1223
+ const method = existing === undefined ? "session/new" : "session/load";
1224
+ if (existing !== undefined) params["sessionId"] = existing;
1225
+ // The fork binds the mode of a session on each open: a load that names none opens it in
1226
+ // `default`, not in the mode it had before.
1227
+ if (lineage === "fork") params["_meta"] = { [PERMISSION_MODE_META]: permissionMode } satisfies NcodeSessionMeta;
1228
+ const result = await request(session, method, params, method).catch((error: unknown) => {
1229
+ throw lineage === "fork" ? withModeSupport(error, method) : error;
1230
+ });
1231
+ // ACP `session/load` answers without a session id (the session is the one that was asked
1232
+ // for); only `session/new` names one.
1233
+ const reported = existing !== undefined ? existing : result["sessionId"];
1234
+ if (typeof reported !== "string" || reported === "") {
1235
+ throw new Error(`${method} did not return a session id`);
1236
+ }
1237
+ if (existing !== undefined && typeof result["sessionId"] === "string" && result["sessionId"] !== existing) {
1238
+ throw new Error("the agent named another session than the one that was resumed");
1239
+ }
1240
+ session.named(reported);
1241
+
1242
+ // The model and the permission mode are config options, applied after the session opens.
1243
+ // The model must be one the session advertises: the agent refuses anything else.
1244
+ const settings: Array<{ configId: string; value: unknown }> = [];
1245
+ settings.push({ configId: "permissionMode", value: permissionMode });
1246
+ if (model !== undefined) {
1247
+ const advertised = (
1248
+ (result["configOptions"] as Array<Record<string, unknown>> | undefined) ?? []
1249
+ )
1250
+ .filter((option) => option["id"] === "model" || option["configId"] === "model")
1251
+ .flatMap((option) => (option["options"] as Array<Record<string, unknown>> | undefined) ?? [])
1252
+ .map((option) => ({
1253
+ value: String(option["value"] ?? ""),
1254
+ name: typeof option["name"] === "string" ? option["name"] : undefined,
1255
+ }));
1256
+ settings.push({ configId: "model", value: mcodeModelOptionValue(model, advertised) });
1257
+ }
1258
+ // The agent refuses an effort the selected model does not advertise, and the start fails.
1259
+ if (effort !== undefined && effort !== "") settings.push({ configId: "thinkingEffort", value: effort });
1260
+ // Each answer to a setting lists the options as they stand: the last one that does says the model the session runs.
1261
+ let listed: unknown = result["configOptions"];
1262
+ for (const setting of settings) {
1263
+ const applied = await request(
1264
+ session,
1265
+ "session/set_config_option",
1266
+ { sessionId: reported, configId: setting.configId, value: setting.value },
1267
+ "session/set_config_option",
1268
+ );
1269
+ listed = applied["configOptions"] ?? listed;
1270
+ }
1271
+ const running = currentModelOf(listed);
1272
+ if (running !== undefined) session.emit({ kind: "model", model: running });
1273
+ return reported;
1274
+ }
1275
+
1276
+ /** The text of a prompt: the sections, in the order they are sent. */
1277
+ function promptText(prompt: Prompt): string {
1278
+ return prompt.sections.map((section) => section.text).join("\n\n");
1279
+ }
1280
+
1281
+ /** The session of an id, or a refusal. */
1282
+ function sessionOf(id: SessionId, ability: string): AcpSession {
1283
+ const session = sessions.get(id.native);
1284
+ if (session === undefined || session.ended || session.stopping) {
1285
+ throw unavailable(ability, `there is no running session "${id.native}"`);
1286
+ }
1287
+ return session;
1288
+ }
1289
+
1290
+ /**
1291
+ * The MCP servers of a session, in the dialect of mcode.
1292
+ *
1293
+ * mcode takes the environment of a server as a list of pairs, each with its name and its
1294
+ * value: the same environment niwa names, carried the way this protocol carries it.
1295
+ */
1296
+ function mcpServersOf(
1297
+ servers: readonly McpServerSpec[] | undefined,
1298
+ mark: string,
1299
+ ): Array<Record<string, unknown>> {
1300
+ return (servers ?? []).map((server) => ({
1301
+ name: server.name,
1302
+ command: server.command,
1303
+ args: [...server.args],
1304
+ env: Object.entries({ ...server.env, [MARK_ENV]: mark }).map(([name, value]) => ({ name, value })),
1305
+ }));
1306
+ }
1307
+
1308
+ /**
1309
+ * Run one turn and wait for its end.
1310
+ *
1311
+ * The turn ends at the agent's answer and nowhere else: a turn that was refused, cut off or
1312
+ * out of time did not end, it failed, and that is a refusal here.
1313
+ */
1314
+ async function runTurn(session: AcpSession, text: string, ability: string): Promise<TurnResult> {
1315
+ if (session.running) throw unavailable(ability, "a turn is already running");
1316
+ session.beginTurn(session.reserveTurn());
1317
+ // The waiter goes in first: the reply can arrive before the write returns.
1318
+ const settled = session.awaitTurn();
1319
+ session.sendPrompt(text);
1320
+ try {
1321
+ return await settled;
1322
+ } catch (error) {
1323
+ throw refusal(ability, error);
1324
+ }
1325
+ }
1326
+
1327
+ /**
1328
+ * A turn behind what runs and what already waits: the text is queued, and its result is waited
1329
+ * for. A turn that failed is a refusal here.
1330
+ */
1331
+ async function queueTurn(session: AcpSession, text: string, ability: string): Promise<TurnResult> {
1332
+ try {
1333
+ return await new Promise<TurnResult>((resolve, reject) => {
1334
+ session.queued.push({ text, turn: session.reserveTurn(), ask: { resolve, reject } });
1335
+ });
1336
+ } catch (error) {
1337
+ throw refusal(ability, error);
1338
+ }
1339
+ }
1340
+
1341
+ /**
1342
+ * A turn on a running session, or behind the turn that runs: a prompt never goes into a session
1343
+ * that is busy, because mcode refuses it ("local_session_busy").
1344
+ */
1345
+ function turnOn(session: AcpSession, text: string, ability: string): Promise<TurnResult> {
1346
+ if (session.held !== undefined) return Promise.reject(unavailable(ability, session.held));
1347
+ return session.running ? queueTurn(session, text, ability) : runTurn(session, text, ability);
1348
+ }
1349
+
1350
+ /**
1351
+ * Take on the turn a loaded session already has active.
1352
+ *
1353
+ * The turns of mcode run in its daemon, not in the process this side talks to: a turn whose
1354
+ * client died (the host was killed, its child with it) runs on, and the session refuses a new
1355
+ * prompt until it ends. A loaded session learns of it from `turn_status`. Such a turn is a turn
1356
+ * of this session like any other: it has a number, it starts and ends in the signs of life, and
1357
+ * what is sent meanwhile waits behind it. Its end is not a reply to a prompt of ours, so it is
1358
+ * read off `turn_status` until no turn is active; then what waits goes out. An agent that does
1359
+ * not serve `turn_status` cannot say, and nothing is assumed.
1360
+ */
1361
+ /** The fork's `turn_status` of a session; a reply not of the shape fails like a refusal. */
1362
+ async function turnStatus(session: AcpSession): Promise<TurnStatus> {
1363
+ return TurnStatusResult.parse(await request(session, TURN_STATUS, { sessionId: session.nativeId }, "the turn status"));
1364
+ }
1365
+
1366
+ async function adoptActiveTurn(session: AcpSession): Promise<void> {
1367
+ if (!session.statusable) return;
1368
+ let status: TurnStatus;
1369
+ try {
1370
+ status = await turnStatus(session);
1371
+ } catch (error) {
1372
+ // An agent that advertises the request and cannot answer it is one that cannot say: the
1373
+ // resume goes on without it, and nothing is assumed.
1374
+ if (session.ended || session.stopping) throw error;
1375
+ session.emit({
1376
+ kind: "activity",
1377
+ at: Date.now(),
1378
+ detail: `the turn status could not be read, so no active turn is assumed: ${error instanceof Error ? error.message : String(error)}`,
1379
+ });
1380
+ return;
1381
+ }
1382
+ if (status.activeTurn === null) return;
1383
+ const turn = session.reserveTurn();
1384
+ session.beginTurn(turn);
1385
+ void followForeignTurn(session, turn);
1386
+ }
1387
+
1388
+ /**
1389
+ * Follow a turn this side did not send until the agent says no turn is active.
1390
+ *
1391
+ * A turn that runs past the turn timeout is cancelled once, and it is still followed: it is over
1392
+ * only when the agent says so, or the next prompt would be refused. A turn the agent still holds
1393
+ * a grace after its cancel is held: what waits behind it is dropped, and a question that waited
1394
+ * is told which turn holds the session, so nobody waits for it without end. The session stays
1395
+ * running, so nothing is sent into it. A status that cannot be read fails the turn, and the
1396
+ * child that dies ends it.
1397
+ */
1398
+ async function followForeignTurn(session: AcpSession, turn: number, cancelledAt?: number): Promise<void> {
1399
+ const deadline = Date.now() + turnTimeoutMs;
1400
+ let cancelled = cancelledAt;
1401
+ let dropped = false;
1402
+ const mine = (): boolean => !session.ended && !session.stopping && session.running && session.current === turn;
1403
+ for (;;) {
1404
+ await sleep(FOREIGN_TURN_POLL_MS);
1405
+ if (!mine()) return;
1406
+ let status: TurnStatus;
1407
+ try {
1408
+ status = await turnStatus(session);
1409
+ } catch (error) {
1410
+ if (!mine()) return;
1411
+ session.failTurn(
1412
+ new Error(`the turn status could not be read: ${error instanceof Error ? error.message : String(error)}`),
1413
+ "unknown",
1414
+ );
1415
+ return;
1416
+ }
1417
+ if (!mine()) return;
1418
+ // Any active turn makes the session busy, a compaction included: mcode refuses a prompt into
1419
+ // either ("local_session_busy").
1420
+ if (status.activeTurn === null) {
1421
+ // A turn that was cancelled for its time was not answered: it is over, and it failed.
1422
+ if (cancelled !== undefined) session.failTurn(new Error("the turn did not end in time"));
1423
+ else session.endTurn({ stopReason: STOP_TURN, text: "" });
1424
+ return;
1425
+ }
1426
+ if (cancelled === undefined && Date.now() >= deadline) {
1427
+ cancelled = Date.now();
1428
+ session.notify("session/cancel", { sessionId: session.nativeId });
1429
+ session.emit({ kind: "activity", at: Date.now(), detail: "the turn did not end in time: it was cancelled" });
1430
+ }
1431
+ if (!dropped && cancelled !== undefined && Date.now() >= cancelled + cancelGraceMs) {
1432
+ dropped = true;
1433
+ const reason = `the agent holds turn "${status.activeTurn.turnId}" of the session and did not let it go after it was cancelled`;
1434
+ session.emit({ kind: "activity", at: Date.now(), detail: reason });
1435
+ session.held = reason;
1436
+ session.dropQueue(reason);
1437
+ }
1438
+ }
1439
+ }
1440
+
1441
+ /**
1442
+ * Deliver a message the way a send does, and say what became of it.
1443
+ *
1444
+ * A busy session queues the message behind the running turn, with the turn it will run as; an
1445
+ * idle one begins a turn with it. Nothing waits for the turn to end: its end and its failure
1446
+ * are signs of life.
1447
+ */
1448
+ async function deliver(session: AcpSession, text: string): Promise<DeliveryReceipt> {
1449
+ const at = Date.now();
1450
+ const turn = session.reserveTurn();
1451
+ if (session.running) {
1452
+ // The session is busy: the message waits for the current turn to end, and it goes out
1453
+ // as a full session/prompt request, so its delivery is confirmed. The queue is a FIFO.
1454
+ session.queued.push({ text, turn });
1455
+ return { status: "queued", turn, at };
1456
+ }
1457
+ session.beginTurn(turn);
1458
+ // The waiter for this turn goes in before the prompt goes out: the reply to
1459
+ // `session/prompt` is what ends the turn, and it may arrive before this line returns.
1460
+ session.awaitTurn().catch(() => undefined);
1461
+ const failed = session.sendPrompt(text);
1462
+ if (failed !== undefined) {
1463
+ if (failed.dispatch === "unsent") throw new InputNotSent(harnessId, "send", failed.error);
1464
+ throw new InputPossiblySent(harnessId, "send", failed.error);
1465
+ }
1466
+ // An agent that does not read its input leaves a large line waiting in the pipe: the wait is bounded,
1467
+ // and what is written of it may still be read, so it is not said to be unsent.
1468
+ let accepted: "taken" | "slow";
1469
+ try {
1470
+ accepted = await Promise.race([session.accepted.then(() => "taken" as const), sleep(callTimeoutMs).then(() => "slow" as const)]);
1471
+ } catch (error) {
1472
+ // The input took the line and failed it: the message did not go out, and the turn it began never ran.
1473
+ const reason = error instanceof Error ? error.message : String(error);
1474
+ if (session.running && session.current === turn) session.failTurn(new Error(`the prompt could not be written: ${reason}`));
1475
+ throw new InputNotSent(harnessId, "send", reason);
1476
+ }
1477
+ if (accepted === "slow") {
1478
+ throw new InputPossiblySent(harnessId, "send", `the agent's input did not take the message within ${callTimeoutMs} ms; part of it may have been read`);
1479
+ }
1480
+ return { status: "started", turn, at };
1481
+ }
1482
+
1483
+
1484
+ /** The cold resumes in progress, by native session id: a session has one process, however many ask for it. */
1485
+ const resuming = new Map<string, Promise<void>>();
1486
+
1487
+ async function resume(id: SessionId, resumeOptions?: ResumeOptions): Promise<void> {
1488
+ for (;;) {
1489
+ if (disposed) throw unavailable("resume", "the control side is closed");
1490
+ refuseDisabledTools("resume", resumeOptions?.visible, resumeOptions?.tools);
1491
+ const session = sessions.get(id.native);
1492
+ const text = resumeOptions?.prompt === undefined ? "" : promptText(resumeOptions.prompt);
1493
+ // A session that is still live is resumed by resuming its own process: the agent keeps
1494
+ // its context, and the prompt is another turn of it.
1495
+ if (session !== undefined && !session.ended && !session.stopping) {
1496
+ if (resumeOptions?.box !== undefined) {
1497
+ throw new Unsupported(harnessId, "control", "resume", LIVE_PROCESS_REFUSAL);
1498
+ }
1499
+ // The one who resumes names where its reverse requests go from now on.
1500
+ if (resumeOptions?.reverse !== undefined) session.reverse = resumeOptions.reverse;
1501
+ if (text.length === 0) return;
1502
+ if (session.held !== undefined) throw unavailable("resume", session.held);
1503
+ if (session.running) {
1504
+ session.queued.push({ text, turn: session.reserveTurn() });
1505
+ return;
1506
+ }
1507
+ await runTurn(session, text, "resume");
1508
+ return;
1509
+ }
1510
+ // A resume of this session is already bringing its process up: wait for it, then resume what
1511
+ // it brought up, with this caller's own prompt and reverse handler. If it failed, this one tries.
1512
+ const inflight = resuming.get(id.native);
1513
+ if (inflight !== undefined) {
1514
+ await inflight.catch(() => undefined);
1515
+ continue;
1516
+ }
1517
+ const work = resumeCold(id, resumeOptions, session?.cwd, text);
1518
+ resuming.set(id.native, work);
1519
+ try {
1520
+ await work;
1521
+ } finally {
1522
+ if (resuming.get(id.native) === work) resuming.delete(id.native);
1523
+ }
1524
+ return;
1525
+ }
1526
+ }
1527
+
1528
+ /** Bring a session whose process is gone back up in a new one. */
1529
+ async function resumeCold(
1530
+ id: SessionId,
1531
+ resumeOptions: ResumeOptions | undefined,
1532
+ lastCwd: string | undefined,
1533
+ text: string,
1534
+ ): Promise<void> {
1535
+ const mode = modeOf(resumeOptions?.mode, options.mode, MCODE_LAUNCH);
1536
+ requireLaunch(harnessId, MCODE_LAUNCH, { mode });
1537
+ const fresh = await startProcess(resumeOptions?.cwd ?? lastCwd ?? process.cwd(), resumeOptions ?? {});
1538
+ fresh.reverse = resumeOptions?.reverse;
1539
+ try {
1540
+ const nativeId = await handshake(fresh, resumeOptions?.model ?? defaultModel, defaultEffort, mode, id.native, resumeOptions?.servers);
1541
+ // The session may still have a turn running: the one that was cut off with the process
1542
+ // that sent it. What comes next waits behind it.
1543
+ await adoptActiveTurn(fresh);
1544
+ sessions.set(nativeId, fresh);
1545
+ if (text.length > 0) await turnOn(fresh, text, "resume");
1546
+ } catch (error) {
1547
+ await stopSession(fresh);
1548
+ throw refusal("resume", error);
1549
+ }
1550
+ }
1551
+
1552
+ // -- the control side -----------------------------------------------------
1553
+
1554
+ return {
1555
+ async start(startOptions: StartOptions): Promise<StartedSession> {
1556
+ if (disposed) throw unavailable("start", "the control side is closed");
1557
+ refuseDisabledTools("start", startOptions.visible, startOptions.tools);
1558
+ const model = startOptions.model ?? defaultModel;
1559
+ const effort = startOptions.effort ?? defaultEffort;
1560
+ const mode = modeOf(startOptions.mode, options.mode, MCODE_LAUNCH);
1561
+ requireLaunch(harnessId, MCODE_LAUNCH, { model, effort, mode });
1562
+ const cwd = startOptions.cwd ?? process.cwd();
1563
+ const session = await startProcess(cwd, startOptions);
1564
+ session.reverse = startOptions.reverse;
1565
+ let nativeId: string;
1566
+ try {
1567
+ nativeId = await handshake(
1568
+ session,
1569
+ model,
1570
+ effort,
1571
+ mode,
1572
+ undefined,
1573
+ startOptions.servers,
1574
+ );
1575
+ } catch (error) {
1576
+ // A session whose start failed is not handed to anyone, so nobody could stop it later.
1577
+ await stopSession(session);
1578
+ throw refusal("start", error);
1579
+ }
1580
+ sessions.set(nativeId, session);
1581
+ const id = makeSessionId(harnessId, nativeId);
1582
+ // The caller knows the session before its prompt goes: a start cut off while its first turn
1583
+ // is on the way still finds it. A session whose name could not be kept is given no work.
1584
+ try {
1585
+ await startOptions.named?.(id);
1586
+ } catch (error) {
1587
+ await stopSession(session);
1588
+ throw error;
1589
+ }
1590
+ // The session exists once the agent has named it. The prompt is its first turn, delivered
1591
+ // like a send: the start does not wait for the agent to finish it.
1592
+ const text = promptText(startOptions.prompt);
1593
+ if (text.length === 0) return { session: id, mode };
1594
+ try {
1595
+ return { session: id, first: await deliver(session, text), mode };
1596
+ } catch (error) {
1597
+ // A start whose first message did not go out is not a start: nobody holds the id to stop it.
1598
+ await stopSession(session);
1599
+ throw error instanceof InputNotSent ? unavailable("start", `the first message could not be written: ${error.message}`) : error;
1600
+ }
1601
+ },
1602
+
1603
+ resume,
1604
+
1605
+ async send(id: SessionId, message: string, sendOptions?: SendOptions): Promise<DeliveryReceipt> {
1606
+ const session = sessions.get(id.native);
1607
+ if (session === undefined || session.ended || session.stopping) {
1608
+ throw new InputNotSent(harnessId, "send", `there is no running session "${id.native}"`);
1609
+ }
1610
+ if (session.held !== undefined) throw new InputNotSent(harnessId, "send", session.held);
1611
+ const at = Date.now();
1612
+ if (sendOptions?.into === "turn" && session.running && session.steerable) {
1613
+ // Into the running turn: mcode joins the text to the turn between its tool calls and
1614
+ // answers with the turn it joined. If it refuses (the turn ended in the meantime, say),
1615
+ // the message goes the ordinary way below, which starts a turn or queues behind one. That
1616
+ // is so only for a refusal that says the message was not taken: any other failure may
1617
+ // have come after mcode took it, and the message is not sent again on a guess.
1618
+ const turn = session.current;
1619
+ try {
1620
+ await request(session, "mcode/session/steer", { sessionId: session.nativeId, text: message }, "the steer");
1621
+ return { status: "delivered", turn, at };
1622
+ } catch (error) {
1623
+ // The process went with the steer on its way, no reply came at all, or the steer failed
1624
+ // in a way that does not say it was not taken: mcode may have taken the message.
1625
+ if (session.ended || session.stopping) throw new InputPossiblySent(harnessId, "send", refusal("send", error).message);
1626
+ if (!(error instanceof RequestFailed) || error.dispatch === "uncertain") {
1627
+ const reason = error instanceof Error ? error.message : String(error);
1628
+ throw new InputPossiblySent(harnessId, "send", `${reason}; whether the message reached the turn is unknown`);
1629
+ }
1630
+ }
1631
+ }
1632
+ return await deliver(session, message);
1633
+ },
1634
+
1635
+ async interrupt(id: SessionId): Promise<void> {
1636
+ const session = sessionOf(id, "interrupt");
1637
+ if (!session.running) throw unavailable("interrupt", "no turn is running");
1638
+ // An explicit stop drops what waited behind the turn: firing it would be a surprise.
1639
+ session.dropQueue("the turn was interrupted");
1640
+ // The cancel is a hint; only the agent ending the turn proves it.
1641
+ session.notify("session/cancel", { sessionId: session.nativeId });
1642
+ // A cancelled turn is answered with cancelled to what it still asks, as ACP wants.
1643
+ session.cancelAsking();
1644
+ const confirmed = await Promise.race([
1645
+ session.whenIdle().then(() => true),
1646
+ sleep(cancelGraceMs).then(() => false),
1647
+ ]);
1648
+ if (!confirmed) throw unavailable("interrupt", "the agent did not confirm the cancel");
1649
+ },
1650
+
1651
+ async ask<T>(id: SessionId, askOptions: AskOptions<T>): Promise<AskAnswer<T>> {
1652
+ const session = sessionOf(id, "ask");
1653
+ const schema = askOptions.schema;
1654
+ // The schema travels to the agent as a JSON schema, and the answer is checked against
1655
+ // the zod schema here: an answer that does not pass is not an answer.
1656
+ const jsonSchema = z.toJSONSchema(schema, { io: "output", unrepresentable: "any" }) as Record<
1657
+ string,
1658
+ unknown
1659
+ >;
1660
+ const instruction = [
1661
+ promptText(askOptions.prompt),
1662
+ "",
1663
+ "Answer with JSON only, matching this schema exactly:",
1664
+ JSON.stringify(jsonSchema),
1665
+ ].join("\n");
1666
+
1667
+ // A busy session takes the question after what runs and what already waits, as its own
1668
+ // turn: the question is a queued turn whose answer is waited for.
1669
+ const result = await turnOn(session, instruction, "ask");
1670
+ if (result.stopReason !== STOP_TURN) {
1671
+ throw unavailable("ask", `the agent ended the question with "${result.stopReason}"`);
1672
+ }
1673
+ const checked = schema.safeParse(parseJson(result.text));
1674
+ if (!checked.success) {
1675
+ throw unavailable(
1676
+ "ask",
1677
+ `the answer did not pass the schema: ${checked.error.issues.map((issue) => issue.path.join(".")).join(", ")}`,
1678
+ );
1679
+ }
1680
+ return { session: id, value: checked.data, at: timestamp(Date.now()) };
1681
+ },
1682
+
1683
+ async *life(id: SessionId): AsyncIterable<LifeEvent> {
1684
+ const session = sessionOf(id, "life");
1685
+ // The stream carries what happens from now on: a watcher that arrives after a turn
1686
+ // began does not see that turn.
1687
+ const queue: LifeEvent[] = [];
1688
+ let done = false;
1689
+ let wake: (() => void) | undefined;
1690
+ const watcher: Watcher = (event) => {
1691
+ if (event === undefined) {
1692
+ done = true;
1693
+ } else {
1694
+ queue.push(event);
1695
+ }
1696
+ wake?.();
1697
+ };
1698
+ session.watch(watcher);
1699
+ try {
1700
+ for (;;) {
1701
+ const event = queue.shift();
1702
+ if (event !== undefined) {
1703
+ yield event;
1704
+ continue;
1705
+ }
1706
+ if (done) return;
1707
+ await new Promise<void>((resolve) => {
1708
+ wake = resolve;
1709
+ });
1710
+ wake = undefined;
1711
+ }
1712
+ } finally {
1713
+ // Only this reader's watcher goes: the others keep theirs.
1714
+ session.watchers.delete(watcher);
1715
+ }
1716
+ },
1717
+
1718
+ async state(id: SessionId): Promise<SessionState> {
1719
+ const session = sessions.get(id.native);
1720
+ // A session not held, or whose child is gone, proves nothing about now.
1721
+ if (session === undefined || session.ended || session.stopping) return "unknown";
1722
+ return session.running ? "running" : "idle";
1723
+ },
1724
+
1725
+ /** The release the shared contract names: stops this session's process and no other. */
1726
+ async close(id: SessionId): Promise<void> {
1727
+ const session = sessions.get(id.native);
1728
+ if (session === undefined) return;
1729
+ await stopSession(session);
1730
+ },
1731
+
1732
+ async stop(id: SessionId): Promise<void> {
1733
+ const session = sessions.get(id.native);
1734
+ if (session === undefined) return;
1735
+ await stopSession(session);
1736
+ },
1737
+
1738
+ async dispose(): Promise<void> {
1739
+ disposed = true;
1740
+ // A start that is still launching its process reaps it itself once the process exists.
1741
+ await Promise.allSettled([...launching]);
1742
+ await Promise.all([...owned].map((session) => stopSession(session)));
1743
+ owned.clear();
1744
+ sessions.clear();
1745
+ },
1746
+ };
1747
+
1748
+ /** Stop one child: an in-protocol cancel, then SIGTERM to the group, then SIGKILL. */
1749
+ async function stopSession(session: AcpSession): Promise<void> {
1750
+ owned.delete(session);
1751
+ forget(session);
1752
+ const child = session.child;
1753
+ const gone = (): boolean => child.exitCode !== null || child.signalCode !== null;
1754
+ if (!gone() && !session.stopping) {
1755
+ // The polite way first, while writes still go out: the agent stops the turn itself.
1756
+ if (session.nativeId !== "") session.notify("session/cancel", { sessionId: session.nativeId });
1757
+ session.stopping = true;
1758
+ }
1759
+ // Everyone waiting is released now: a stop does not leave a call hanging.
1760
+ session.end(undefined);
1761
+ if (child.pid === undefined) return;
1762
+ if (!gone()) {
1763
+ const closed = new Promise<void>((resolve) => {
1764
+ child.once("close", () => resolve());
1765
+ });
1766
+ signalGroup(session, "SIGTERM");
1767
+ await Promise.race([closed, sleep(stopGraceMs)]);
1768
+ }
1769
+ // The agent's own children may outlive the leader, so the group gets the last word.
1770
+ signalGroup(session, "SIGKILL");
1771
+ // The MCP servers the agent was given are not in its group: they go by their mark.
1772
+ await stopMarked(session.mark);
1773
+ }
1774
+ }
1775
+
1776
+ /** The environment variable that marks the MCP servers of one agent. */
1777
+ const MARK_ENV = "NIWA_MCP_OWNER";
1778
+
1779
+ /** The pids of the processes that carry a mark in their environment. */
1780
+ function markedPids(mark: string): number[] {
1781
+ // "ps e" shows the environment of the processes of the same user after the command. With every
1782
+ // environment the list easily passes the default 1 MB, and a list cut there misses the servers.
1783
+ const listed = spawnSync("ps", ["eww", "-ax", "-o", "pid=,command="], {
1784
+ encoding: "utf8",
1785
+ maxBuffer: Number.POSITIVE_INFINITY,
1786
+ }).stdout;
1787
+ const found: number[] = [];
1788
+ for (const line of listed.split("\n")) {
1789
+ if (!line.includes(`${MARK_ENV}=${mark}`)) continue;
1790
+ const pid = Number(/^\s*(\d+)/.exec(line)?.[1]);
1791
+ if (Number.isInteger(pid) && pid !== process.pid) found.push(pid);
1792
+ }
1793
+ return found;
1794
+ }
1795
+
1796
+ /** Stop the processes that carry a mark: SIGTERM, then SIGKILL for what stays. */
1797
+ async function stopMarked(mark: string): Promise<void> {
1798
+ const signalAll = (signal: NodeJS.Signals): number[] => {
1799
+ const pids = markedPids(mark);
1800
+ for (const pid of pids) {
1801
+ try {
1802
+ process.kill(pid, signal);
1803
+ } catch {
1804
+ // Already gone.
1805
+ }
1806
+ }
1807
+ return pids;
1808
+ };
1809
+ if (signalAll("SIGTERM").length === 0) return;
1810
+ await sleep(200);
1811
+ signalAll("SIGKILL");
1812
+ }
1813
+
1814
+ /** A wait that does not hold the loop open. */
1815
+ function sleep(ms: number): Promise<void> {
1816
+ return new Promise<void>((resolve) => {
1817
+ setTimeout(resolve, ms).unref();
1818
+ });
1819
+ }
1820
+
1821
+ /** The JSON in an answer, or the answer itself when it is not JSON. */
1822
+ function parseJson(text: string | undefined): unknown {
1823
+ if (text === undefined) return undefined;
1824
+ const trimmed = text.trim();
1825
+ if (trimmed.length === 0) return undefined;
1826
+ // The agent may wrap the JSON in a fence; the first object or array in it is the answer.
1827
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(trimmed);
1828
+ const body = fenced === null ? trimmed : fenced[1]?.trim() ?? trimmed;
1829
+ try {
1830
+ return JSON.parse(body);
1831
+ } catch {
1832
+ const start = body.search(/[[{]/);
1833
+ if (start === -1) return body;
1834
+ try {
1835
+ return JSON.parse(body.slice(start));
1836
+ } catch {
1837
+ return body;
1838
+ }
1839
+ }
1840
+ }