@parcha/agentrun-harness-acp 0.0.0-stage → 0.1.0-beta.47

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,779 @@
1
+ // One ACP agent driven over the session's records. Written for AgentRun.
2
+ //
3
+ // The agent is one process per kernel Drive (one per runner's hold of the session), started at the drive's first turn
4
+ // and ended with it: a turn after another goes to the same agent session, as a person's would. A drive:
5
+ // 1. makes the session's private HOME fresh and gives it back what the records mirrored of the agent's own session
6
+ // store (state.ts), then the recipe's own files;
7
+ // 2. starts the agent (host/agent.ts: the environment allowlist, its own process group) and the adapter's MCP server
8
+ // (host/mcp.ts: the host's tools, nothing else), and checks initialize against the recipe's declares;
9
+ // 3. gives the agent back its session (session/load, its replayed history kept off the timeline), or a new one, whose
10
+ // first prompt carries the conversation so far when the agent cannot load (a context note);
11
+ // 4. runs the turn a crash cut off (the kernel's recovery note, as a user message), then each pending submission, one per
12
+ // session/prompt;
13
+ // 5. sends each call of our tools through the kernel's tool bridge under the agent's own tool call id, and each
14
+ // permission request for a tool of the agent's own through the host's gate, both journaled.
15
+ // ACP's own report of a tool call (its status, its content) is never trusted: what ran is what the bridge recorded.
16
+ import { randomBytes, randomUUID } from "node:crypto";
17
+ import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
18
+ import { dirname, isAbsolute, join, normalize } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+ import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
21
+ import { askGate, journalRecords, NativeJournal, openTurn, placeSubmissions, recoveryNote, resumeUnstartedCalls, toolBridge, toolKey, transcriptOf } from "@parcha/agentrun-kernel/process";
22
+ import { CallIds, MCP_SERVER, ourTool, permissionCallId } from "./calls.js";
23
+ import { ACP_CODES } from "./facts.js";
24
+ import { homePath } from "./recipe.js";
25
+ import { restoreState, STATE_STREAM, StateMirror } from "./state.js";
26
+ import { startAgent } from "./host/agent.js";
27
+ import { startMcpServer } from "./host/mcp.js";
28
+ /** The agent's session id, one record each time a new agent session is opened. */
29
+ export const SESSION_STREAM = "acp.session";
30
+ /** One record per session/prompt sent (written just before it): the turns a plan-billed run counts. */
31
+ export const PROMPT_STREAM = "acp.prompt";
32
+ /** Our tools' calls as the MCP server took them (`seen`, before the gate) and as they ended (`answered`). */
33
+ export const CALL_STREAM = "acp.call";
34
+ /** The permission requests for the agent's own tools: `asked` before the gate is, `answered` with what it said. */
35
+ export const PERMISSION_STREAM = "acp.permission";
36
+ /** One record per tool call the agent announced (or MCP call it made unannounced): the calls a plan-billed run counts. */
37
+ export const TOOLS_STREAM = "acp.tools";
38
+ /** The model chosen for the agent's session (recipe.model, as the agent lists it), one record each time one is chosen. */
39
+ export const MODEL_STREAM = "acp.model";
40
+ /** How long a session waits for the agent to start and answer initialize, or open its session. */
41
+ export const START_MS = 60_000;
42
+ /** How long an MCP call waits for the agent's tool_call that announces it. */
43
+ export const CALL_ID_WAIT_MS = 10_000;
44
+ /** How long a drive's end waits for the agent's process to go. */
45
+ const EXIT_WAIT_MS = 5_000;
46
+ /** How long an agent past the plan's limit of tool calls has to end its turn after session/cancel before its process is
47
+ * ended: past the limit, each moment it goes on is spent on the owner's plan. */
48
+ export const LIMIT_STOP_MS = 3_000;
49
+ /** How long a turn's end waits for the calls of ours still running in it to stop, once their signal is aborted. */
50
+ export const CALL_STOP_MS = 5_000;
51
+ /** The most of an earlier call's input, and of its result or error, a context note quotes. */
52
+ export const NOTE_INPUT_CHARS = 1_000;
53
+ export const NOTE_RESULT_CHARS = 2_000;
54
+ /** The stdio MCP bridge the agent starts when it takes no MCP over HTTP. */
55
+ const STDIO_BRIDGE = fileURLToPath(new URL("./host/mcp-stdio.js", import.meta.url));
56
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
57
+ const message = (error) => String(error?.message ?? error);
58
+ const clip = (text, max) => (text.length <= max ? text : `${text.slice(0, max)}… [${text.length - max} more characters]`);
59
+ const indent = (text) => text.split("\n").map((line) => ` ${line}`).join("\n");
60
+ /** A tool's recorded output as text: its text, never the bytes of an image it returned. */
61
+ const outputText = (output) => {
62
+ if (typeof output === "string")
63
+ return output;
64
+ const text = output?.text;
65
+ return typeof text === "string" ? text : (JSON.stringify(output) ?? String(output));
66
+ };
67
+ /** Whether every promise in `running` settled within `ms`. */
68
+ async function settledWithin(running, ms) {
69
+ if (running.size === 0)
70
+ return true;
71
+ let timer;
72
+ const late = new Promise((resolve) => (timer = setTimeout(() => resolve(false), ms)));
73
+ return Promise.race([Promise.allSettled([...running]).then(() => true), late]).finally(() => clearTimeout(timer));
74
+ }
75
+ /** The submissions a drive marked as sent to the agent (PROMPT_STREAM), with those a recovery's send carried. */
76
+ export function sentSubmissions(state) {
77
+ const ids = journalRecords(state, PROMPT_STREAM).flatMap((r) => [r.data?.submission, ...(Array.isArray(r.data?.covers) ? r.data.covers : [])]);
78
+ return new Set(ids.filter((s) => typeof s === "string"));
79
+ }
80
+ /** `promise`, or a rejection once `ms` passed. */
81
+ function within(promise, ms, what) {
82
+ let timer;
83
+ const late = new Promise((_, reject) => (timer = setTimeout(() => reject(new Error(`${what} took longer than ${ms} ms`)), ms)));
84
+ return Promise.race([promise, late]).finally(() => clearTimeout(timer));
85
+ }
86
+ /** `promise`, or the signal's reason once it aborts. */
87
+ function unlessAborted(promise, signal) {
88
+ if (signal.aborted)
89
+ return Promise.reject(signal.reason);
90
+ return new Promise((resolve, reject) => {
91
+ const stop = () => reject(signal.reason);
92
+ signal.addEventListener("abort", stop, { once: true });
93
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
94
+ });
95
+ }
96
+ /** The conversation before the open turn (all of it with none open), as a new agent session reads it: each user
97
+ * message, each answer and each call of ours with its input and how it ended (its result, or its error), each cut to a
98
+ * bound (NOTE_INPUT_CHARS, NOTE_RESULT_CHARS) that says how much was left out. The inputs and results are quoted as
99
+ * the session's records hold them, as the kernel's recovery note quotes them. Empty when there is none. */
100
+ export function contextNote(state) {
101
+ const since = openTurn(state)?.since;
102
+ const lines = [];
103
+ state.effectOrder.forEach((effect, at) => {
104
+ if (since !== undefined && at > since)
105
+ return;
106
+ if (effect.name.startsWith("tool.")) {
107
+ const head = `- ${effect.name.slice("tool.".length)}(${clip(JSON.stringify(effect.input ?? {}) ?? "{}", NOTE_INPUT_CHARS)}), call ${effect.key.slice("tool:".length)}:`;
108
+ const line = effect.status === "completed"
109
+ ? `${head} completed. Its result:\n${indent(clip(outputText(effect.output), NOTE_RESULT_CHARS))}`
110
+ : effect.status === "failed" && !effect.error?.interrupted
111
+ ? `${head} failed: ${clip(effect.error?.message || "the tool failed with no message", NOTE_RESULT_CHARS).replace(/\n/g, "\n ")}`
112
+ : effect.status === "failed"
113
+ ? `${head} interrupted before it reported a result; it may have taken effect.`
114
+ : `${head} never ended; it may have taken effect.`;
115
+ lines.push({ at, line });
116
+ return;
117
+ }
118
+ if (effect.placed.length === 0 || effect.name === "chaos")
119
+ return;
120
+ for (const id of effect.placed) {
121
+ const submission = state.submissions.find((s) => s.id === id);
122
+ if (!submission?.text || (submission.kind !== "prompt" && submission.kind !== "followUp" && submission.kind !== "steer"))
123
+ continue;
124
+ lines.push({ at, line: `- user: ${clip(submission.text, 2000).replace(/\n/g, "\n ")}` });
125
+ }
126
+ });
127
+ for (const record of transcriptOf(state)) {
128
+ if (since !== undefined && record.at > since)
129
+ continue;
130
+ const entry = record.data;
131
+ if (entry?.type === "message" && entry.role === "assistant" && entry.text)
132
+ lines.push({ at: record.at, line: `- assistant: ${clip(entry.text, 2000).replace(/\n/g, "\n ")}` });
133
+ }
134
+ if (lines.length === 0)
135
+ return undefined;
136
+ lines.sort((a, b) => a.at - b.at);
137
+ return [
138
+ "[Context] This conversation began in an earlier session of yours, which this one does not hold. What was said and done so far:",
139
+ ...lines.map((l) => l.line),
140
+ "",
141
+ "Carry on from there.",
142
+ ].join("\n");
143
+ }
144
+ /** The ACP harness. `control` is told of each drive call's stop hook while it runs. */
145
+ export function acpHarness(options, control) {
146
+ const log = options.log ?? (() => { });
147
+ const recipe = options.recipe;
148
+ const plan = recipe.billing.kind === "plan" ? recipe.billing : undefined;
149
+ const listed = options.tools.filter((tool) => !tool.deferred);
150
+ const names = new Set(listed.map((tool) => tool.name));
151
+ let runtime;
152
+ /** The recipe's refusal `text` (the agent's stderr, an error it answered) says, as `<code>: <words>`; undefined when it
153
+ * says none of them. */
154
+ const refusalIn = (text) => {
155
+ const refusal = recipe.refusals?.find((r) => text.includes(r.says));
156
+ return refusal && `${refusal.code}: ${refusal.words}`;
157
+ };
158
+ /** `text` (the agent's stderr, or an error carrying it) as a failure's words: the terminal's escapes out, and every
159
+ * line holding words the recipe calls quiet (recipe.quiet) left out, the last 300 characters of what is left. */
160
+ // eslint-disable-next-line no-control-regex
161
+ const ESCAPES = /\u001b\[[0-9;?]*[A-Za-z]/g;
162
+ const lastWords = (text) => text
163
+ .replace(ESCAPES, "")
164
+ .split("\n")
165
+ .filter((line) => !(recipe.quiet ?? []).some((words) => line.includes(words)))
166
+ .join("\n")
167
+ .trim()
168
+ .slice(-300);
169
+ /** Why an agent that ended did: its last words on stderr, else the error's, else that it said nothing. */
170
+ const whyEnded = (agent, error) => lastWords(agent.stderrTail()) || lastWords(message(error)) || "it said nothing";
171
+ /** Mirror the agent's session store into `journal` (the caller flushes). A failure is said and never thrown: the next
172
+ * point takes the mirror again, and a turn's outcome is never lost to it. */
173
+ const mirrorInto = (rt, journal) => {
174
+ // A HOME removed with its process holds nothing to take: read now, it would say the agent deleted its whole store.
175
+ if (rt.wiped)
176
+ return;
177
+ try {
178
+ rt.mirror.take(journal);
179
+ }
180
+ catch (error) {
181
+ log("acp: the mirror of the agent's session store failed; the next point takes it again", { error: message(error).slice(0, 300) });
182
+ }
183
+ };
184
+ /** The open turn's limit of tool calls, counted from the records: past it, the turn is cancelled with a named reason. */
185
+ const countCall = (rt, cur, toolCallId) => {
186
+ if (rt.counted.has(toolCallId))
187
+ return cur.turn?.limitHit;
188
+ rt.counted.add(toolCallId);
189
+ cur.journal.append(TOOLS_STREAM, { toolCallId });
190
+ if (!plan || cur.journal.length(TOOLS_STREAM) <= plan.maxToolCalls)
191
+ return undefined;
192
+ const turn = cur.turn;
193
+ if (turn && !turn.limitHit) {
194
+ turn.limitHit = `${ACP_CODES.toolCallLimit}: the plan's limit of ${plan.maxToolCalls} tool calls is reached; the turn was cancelled`;
195
+ log("acp: a plan-billed run reached its limit of tool calls", { limit: plan.maxToolCalls });
196
+ turn.stop.abort();
197
+ void rt.agent.connection.agent.notify("session/cancel", { sessionId: rt.sessionId }).catch(() => { });
198
+ }
199
+ return turn?.limitHit ?? `${ACP_CODES.toolCallLimit}: the plan's limit of ${plan.maxToolCalls} tool calls is reached`;
200
+ };
201
+ const onUpdate = (rt, notification) => {
202
+ if (rt.loading || notification.sessionId !== rt.sessionId)
203
+ return;
204
+ const cur = rt.current;
205
+ const update = notification.update;
206
+ switch (update.sessionUpdate) {
207
+ case "agent_message_chunk": {
208
+ const turn = cur?.turn;
209
+ if (!cur || !turn || update.content.type !== "text")
210
+ return;
211
+ turn.final += update.content.text;
212
+ cur.ctx.live({ type: "text", delta: update.content.text });
213
+ return;
214
+ }
215
+ case "tool_call": {
216
+ if (!cur)
217
+ return;
218
+ if (cur.turn)
219
+ cur.turn.final = "";
220
+ countCall(rt, cur, update.toolCallId);
221
+ if (typeof update.kind === "string")
222
+ rt.kinds.set(update.toolCallId, update.kind);
223
+ // Only a call whose kind has no effects of its own can be ours (ourTool): a shell titled as our tool never takes an
224
+ // MCP call's id, and never passes the permission shortcut below.
225
+ const tool = ourTool(update, names);
226
+ if (tool)
227
+ rt.calls.add(update.toolCallId, tool, update.rawInput);
228
+ return;
229
+ }
230
+ case "tool_call_update": {
231
+ if (!cur)
232
+ return;
233
+ // A call the agent named only after announcing it (Cursor's MCP calls: a tool_call titled "MCP: tool" with no
234
+ // input, then this update titled `agentrun: <tool>` with {providerIdentifier, toolName, args}): taken as ours
235
+ // here, under the id its tool_call already counted. Its kind is the tool_call's, which ourTool already let
236
+ // through, or this update's own when it names one.
237
+ if (!rt.calls.has(update.toolCallId)) {
238
+ // Held to both kinds, the tool_call's and the update's: a shell renamed by a later update is never ours.
239
+ const title = update.title ?? null;
240
+ const announcedAs = ourTool({ title, kind: rt.kinds.get(update.toolCallId) ?? null }, names);
241
+ const tool = announcedAs && ourTool({ title, kind: update.kind ?? null }, names) === announcedAs ? announcedAs : undefined;
242
+ if (tool) {
243
+ const raw = update.rawInput;
244
+ const args = raw && raw.toolName === tool && typeof raw.args === "object" && raw.args !== null && !Array.isArray(raw.args) ? raw.args : raw;
245
+ rt.calls.add(update.toolCallId, tool, args);
246
+ }
247
+ }
248
+ // Its status is the agent's word only: what it changes is the mirror of the agent's session store.
249
+ if (update.status !== "completed" && update.status !== "failed")
250
+ return;
251
+ mirrorInto(rt, cur.journal);
252
+ void cur.journal.flush().catch(() => { });
253
+ return;
254
+ }
255
+ default:
256
+ return;
257
+ }
258
+ };
259
+ const onPermission = async (rt, request, connection) => {
260
+ const choose = (kind) => {
261
+ const option = request.options.find((o) => o.kind === kind);
262
+ return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
263
+ };
264
+ const cancelled = { outcome: { outcome: "cancelled" } };
265
+ // Said for every request, ours or the agent's own: ACP makes them optional, so a host (harness-check) reports whether
266
+ // this agent asks at all.
267
+ log("acp: the agent asked permission", { toolCallId: request.toolCall.toolCallId, kind: request.toolCall.kind ?? null });
268
+ const cur = rt.current;
269
+ const turn = cur?.turn;
270
+ if (!cur || !turn || turn.stop.signal.aborted)
271
+ return turn?.limitHit ? choose("reject_once") : cancelled;
272
+ if (turn.limitHit)
273
+ return choose("reject_once");
274
+ // Our own tool: the gate is the bridge's, asked at the MCP call itself. Allowed once, never always. The title is the
275
+ // agent's text, so it takes both: a request whose kind has no effects of its own and whose name is ours, for the
276
+ // tool_call the agent announced as that same tool of ours under the request's own id. Anything else is the agent's
277
+ // own call: the host's gate, journaled.
278
+ const mine = ourTool(request.toolCall, names);
279
+ if (mine && rt.calls.announced(request.toolCall.toolCallId) === mine)
280
+ return choose("allow_once");
281
+ const call = request.toolCall;
282
+ const kind = typeof call.kind === "string" && call.kind ? call.kind : "other";
283
+ const title = typeof call.title === "string" ? call.title : kind;
284
+ const input = call.rawInput ?? null;
285
+ // The request's id is the open turn's: the turn, what it asks, and which of the turn's requests that ask the same it
286
+ // is. The records hold the ids the turn's requests took (another runner's agent process asked some of them): this
287
+ // process's request takes, of those it has not taken itself, the first one still waiting for its answer (the one a
288
+ // swap left parked), else the first one answered (the agent asking again for what it was answered), else a new one.
289
+ const opened = openTurn(cur.ctx.state());
290
+ const turnId = opened?.placed[0] ?? "";
291
+ const all = cur.journal.records(PERMISSION_STREAM).map((r) => r.data);
292
+ const askedIds = new Set(all.filter((r) => r?.type === "asked").map((r) => r.callId));
293
+ const answeredIds = new Set(all.filter((r) => r?.type === "answered").map((r) => r.callId));
294
+ let callId;
295
+ let firstAnswered;
296
+ for (let nth = 0; callId === undefined; nth++) {
297
+ const id = permissionCallId(turnId, { title, kind, rawInput: input }, nth);
298
+ if (rt.claimed.has(id))
299
+ continue;
300
+ if (!askedIds.has(id))
301
+ callId = firstAnswered ?? id;
302
+ else if (!answeredIds.has(id))
303
+ callId = id;
304
+ else
305
+ firstAnswered ??= id;
306
+ }
307
+ rt.claimed.add(callId);
308
+ const records = all.filter((r) => r?.callId === callId);
309
+ const answered = records.find((r) => r.type === "answered");
310
+ if (answered)
311
+ return choose(answered.answer === "allow" ? "allow_once" : "reject_once");
312
+ if (!records.some((r) => r.type === "asked")) {
313
+ cur.journal.append(PERMISSION_STREAM, { type: "asked", callId, toolCallId: call.toolCallId, title, kind, input });
314
+ await cur.journal.flush();
315
+ }
316
+ let refused;
317
+ if (options.gate) {
318
+ try {
319
+ refused = await askGate(options.gate, { callId, tool: `acp_${kind.replace(/[^A-Za-z0-9_]/g, "_")}`, args: { title, kind, input } }, AbortSignal.any([cur.signal, connection, turn.stop.signal]));
320
+ }
321
+ catch {
322
+ // Parked, and the session let go (or the turn was cancelled): nothing is answered, nothing recorded.
323
+ return cancelled;
324
+ }
325
+ }
326
+ cur.journal.append(PERMISSION_STREAM, { type: "answered", callId, answer: refused ? "deny" : "allow", ...(refused ? { words: refused.deny } : {}) });
327
+ await cur.journal.flush();
328
+ return choose(refused ? "reject_once" : "allow_once");
329
+ };
330
+ const onMcpCall = async (rt, name, args, callSignal) => {
331
+ const cur = rt.current;
332
+ const turn = cur?.turn;
333
+ if (!cur || !turn)
334
+ return { text: "acp: no turn is running to take this call", isError: true };
335
+ if (turn.limitHit)
336
+ return { text: turn.limitHit, isError: true };
337
+ // The call stops with its MCP request, the drive, or the turn (a cancel, the plan's limit): an agent that answers its
338
+ // prompt `cancelled` and leaves the request open does not keep the tool running. The turn's end waits for it.
339
+ const running = runMcpCall(rt, cur, name, args, AbortSignal.any([callSignal, cur.signal, turn.stop.signal]));
340
+ cur.inflight.add(running);
341
+ try {
342
+ return await running;
343
+ }
344
+ finally {
345
+ cur.inflight.delete(running);
346
+ }
347
+ };
348
+ const runMcpCall = async (rt, cur, name, args, signal) => {
349
+ let callId = recipe.quirks?.mcpCall === "mint" ? undefined : await rt.calls.take(name, args, signal, options.callIdWaitMs ?? CALL_ID_WAIT_MS);
350
+ if (!callId) {
351
+ callId = `acp-${randomUUID()}`;
352
+ countCall(rt, cur, callId);
353
+ }
354
+ if (cur.turn?.limitHit)
355
+ return { text: cur.turn.limitHit, isError: true };
356
+ // A new agent session counts its calls afresh: an id an earlier session's call took is another call.
357
+ if (rt.fresh && !rt.ownIds.has(callId) && cur.ctx.state().effects.has(toolKey(callId)))
358
+ callId = `${callId}@${rt.sessionId.slice(-12)}`;
359
+ rt.ownIds.add(callId);
360
+ if (!cur.journal.has(`seen:${callId}`))
361
+ cur.journal.append(CALL_STREAM, { type: "seen", callId, tool: name, args }, { id: `seen:${callId}` });
362
+ const result = await cur.bridge.call(name, args, callId, signal);
363
+ if (!cur.journal.has(`answered:${callId}`))
364
+ cur.journal.append(CALL_STREAM, { type: "answered", callId, text: result.text, isError: result.isError, ...(result.refused ? { refused: true } : {}) }, { id: `answered:${callId}` });
365
+ await cur.journal.flush();
366
+ return { text: result.text, isError: result.isError, ...(result.images?.length ? { images: result.images } : {}) };
367
+ };
368
+ /** Start the agent for `ctx` and open its session. */
369
+ const start = async (ctx, journal) => {
370
+ const base = normalize(options.dir);
371
+ if (!isAbsolute(base))
372
+ throw new Error("acp: the session directory must be an absolute path");
373
+ if (options.cwd !== undefined && !isAbsolute(options.cwd))
374
+ throw new Error("acp: the working directory must be an absolute path");
375
+ const root = options.cwd === undefined ? join(base, "work") : normalize(options.cwd);
376
+ const home = join(base, "home");
377
+ const tmp = join(base, "tmp");
378
+ // The recipe's keys, read by name from the host's environment (a host may hold them readable by name alone), refused
379
+ // before anything starts when one is not there.
380
+ const hostEnv = options.env ?? process.env;
381
+ const keyEnv = {};
382
+ const absent = [];
383
+ for (const name of recipe.keys ?? []) {
384
+ const value = hostEnv[name];
385
+ if (typeof value === "string" && value !== "")
386
+ keyEnv[name] = value;
387
+ else
388
+ absent.push(name);
389
+ }
390
+ if (absent.length)
391
+ throw new Error(`${ACP_CODES.keyMissing}: ${recipe.label ?? recipe.id} runs on ${absent.join(" and ")}, which this host does not hold; the agent was not started`);
392
+ mkdirSync(base, { recursive: true, mode: 0o700 });
393
+ // Everything the agent kept goes: what it starts with is the session's records, never an earlier process's files.
394
+ for (const dir of [home, tmp]) {
395
+ rmSync(dir, { recursive: true, force: true });
396
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
397
+ }
398
+ mkdirSync(root, { recursive: true, mode: 0o700 });
399
+ const records = (await journal.read(STATE_STREAM)).map((r) => r.data);
400
+ restoreState(home, records);
401
+ const own = new Set();
402
+ for (const [path, text] of Object.entries(recipe.files ?? {})) {
403
+ const clean = homePath(path);
404
+ const file = join(home, clean);
405
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
406
+ writeFileSync(file, text, { mode: 0o600 });
407
+ own.add(clean.split("\\").join("/"));
408
+ }
409
+ // The credentials the recipe names are never written: each path is an empty folder the agent cannot write a file at,
410
+ // so an agent that tolerates a failed save (Cursor 2026.11.13 says so on stderr and runs on the key in its env) holds
411
+ // its credential in memory alone, and a hard kill leaves none on disk. Nor are they mirrored, whatever their names and
412
+ // wherever the recipe's state paths reach.
413
+ for (const path of recipe.credentials ?? []) {
414
+ const clean = homePath(path);
415
+ mkdirSync(join(home, clean), { recursive: true, mode: 0o700 });
416
+ chmodSync(join(home, clean), 0o500);
417
+ own.add(clean.split("\\").join("/"));
418
+ }
419
+ const stopped = new AbortController();
420
+ const signal = AbortSignal.any([ctx.signal, stopped.signal]);
421
+ const key = randomBytes(32).toString("base64url");
422
+ const rt = { ctx, loading: false, fresh: true, wiped: false, firstBlocks: [], calls: new CallIds(), counted: new Set(), claimed: new Set(), ownIds: new Set(), kinds: new Map(), sessionId: "", mirror: new StateMirror(home, (recipe.state ?? []).map((p) => homePath(p)), own, records, log) };
423
+ const mcp = await startMcpServer({ tools: listed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), key, log, call: (name, args, callSignal) => onMcpCall(rt, name, args, callSignal) });
424
+ let proxy;
425
+ let agent;
426
+ let disposed;
427
+ /** Close the proxy this start holds, once: whoever comes first (the drive's end, or a start the stop overtook). */
428
+ const closeProxy = async () => {
429
+ const open = proxy;
430
+ proxy = undefined;
431
+ await open?.close().catch(() => { });
432
+ };
433
+ rt.mcp = mcp;
434
+ rt.dispose = () => (disposed ??= (async () => {
435
+ stopped.abort(new Error("the agent's drive ended"));
436
+ if (agent)
437
+ await Promise.race([agent.exited, sleep(EXIT_WAIT_MS)]);
438
+ await mcp.close().catch(() => { });
439
+ await closeProxy();
440
+ // A recipe that names a credential the agent derives from its key (Cursor's auth.json): its HOME and tmp go with
441
+ // its process, whole, so no credential outlives the drive. What the next start needs comes back from the records.
442
+ if (recipe.credentials?.length) {
443
+ rt.wiped = true;
444
+ for (const dir of [home, tmp]) {
445
+ try {
446
+ rmSync(dir, { recursive: true, force: true });
447
+ }
448
+ catch (error) {
449
+ log("acp: the agent's private HOME could not be removed", { dir, error: message(error).slice(0, 300) });
450
+ }
451
+ }
452
+ }
453
+ })());
454
+ ctx.signal.addEventListener("abort", () => void rt.dispose(), { once: true });
455
+ try {
456
+ if (options.beforeStart)
457
+ await unlessAborted(options.beforeStart(recipe.command), signal);
458
+ if (recipe.billing.kind === "proxy") {
459
+ if (!options.proxy)
460
+ throw new Error("acp: proxy billing needs the adapter's proxy option");
461
+ proxy = await options.proxy({ halt: (reason) => ctx.halt?.(reason) });
462
+ // A stop while the proxy started: the drive's end ran before there was a proxy to close. It is closed here, and
463
+ // the agent is never started.
464
+ if (signal.aborted) {
465
+ await closeProxy();
466
+ throw signal.reason ?? new Error("acp: the drive ended while the proxy started");
467
+ }
468
+ }
469
+ agent = startAgent({
470
+ command: recipe.command,
471
+ args: recipe.args ?? [],
472
+ cwd: root,
473
+ env: {
474
+ ...(recipe.env ?? {}),
475
+ ...keyEnv,
476
+ ...(proxy?.env ?? {}),
477
+ HOME: home,
478
+ TMPDIR: tmp,
479
+ XDG_CONFIG_HOME: join(home, ".config"),
480
+ XDG_DATA_HOME: join(home, ".local", "share"),
481
+ XDG_CACHE_HOME: join(home, ".cache"),
482
+ XDG_STATE_HOME: join(home, ".local", "state"),
483
+ GIT_CEILING_DIRECTORIES: base,
484
+ },
485
+ ...(options.env ? { from: options.env } : {}),
486
+ ...(options.confine ? { confine: options.confine } : {}),
487
+ ...(options.parentWatch ? { parentWatch: options.parentWatch } : {}),
488
+ signal,
489
+ onUpdate: (notification) => onUpdate(rt, notification),
490
+ onPermission: (request, connection) => onPermission(rt, request, connection),
491
+ });
492
+ rt.agent = agent;
493
+ const live = agent;
494
+ const startMs = options.startMs ?? START_MS;
495
+ const ask = (what, run) => within(unlessAborted(run(), signal), startMs, what).catch(async (error) => {
496
+ if (signal.aborted)
497
+ throw signal.reason;
498
+ // An agent that says why on its way out: its stderr is read once it has ended.
499
+ if (!live.alive() || live.connection.signal.aborted)
500
+ await Promise.race([live.exited, sleep(500)]);
501
+ const named = refusalIn(`${live.stderrTail()}\n${message(error)}`);
502
+ if (named)
503
+ throw new Error(named);
504
+ if (!live.alive() || live.connection.signal.aborted)
505
+ throw new Error(`${ACP_CODES.agentExited}: the agent ended during ${what}: ${whyEnded(live, error)}`);
506
+ throw new Error(`acp: ${what} failed: ${message(error).slice(0, 300)}`);
507
+ });
508
+ const init = await ask("initialize", () => live.connection.agent.request("initialize", { protocolVersion: PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "agentrun", version: "1" } }));
509
+ if (init.protocolVersion !== PROTOCOL_VERSION)
510
+ throw new Error(`${ACP_CODES.protocolMismatch}: the agent speaks ACP version ${String(init.protocolVersion)}, the adapter version ${PROTOCOL_VERSION}`);
511
+ const caps = init.agentCapabilities ?? {};
512
+ const missing = [];
513
+ if (recipe.declares.load && !caps.loadSession)
514
+ missing.push("session/load (agentCapabilities.loadSession)");
515
+ if (recipe.declares.mcp === "http" && !caps.mcpCapabilities?.http)
516
+ missing.push("MCP over http (agentCapabilities.mcpCapabilities.http)");
517
+ if (missing.length)
518
+ throw new Error(`${ACP_CODES.capabilityMismatch}: the recipe declares ${missing.join(" and ")}, which the agent's initialize does not advertise`);
519
+ const server = recipe.declares.mcp === "http"
520
+ ? { type: "http", name: MCP_SERVER, url: mcp.url, headers: [{ name: "Authorization", value: `Bearer ${key}` }] }
521
+ : { name: MCP_SERVER, command: process.execPath, args: [STDIO_BRIDGE], env: [{ name: "AGENTRUN_MCP_URL", value: mcp.url }, { name: "AGENTRUN_MCP_KEY", value: key }] };
522
+ const instructions = options.instructions?.trim() ? options.instructions : undefined;
523
+ const systemPrompt = instructions && caps.sessionCapabilities?.systemPrompt ? { mode: "append", content: [{ type: "text", text: instructions }] } : undefined;
524
+ const last = journalRecords(ctx.state(), SESSION_STREAM).map((r) => r.data?.sessionId).filter((id) => typeof id === "string").at(-1);
525
+ /** What session/load or session/new answered: the models it lists, for one. */
526
+ let opening;
527
+ if (recipe.declares.load && last) {
528
+ // The agent's history comes back as session/update notifications before the answer: kept off the timeline.
529
+ rt.loading = true;
530
+ try {
531
+ opening = await ask("session/load", () => live.connection.agent.request("session/load", { sessionId: last, cwd: root, mcpServers: [server], ...(systemPrompt ? { systemPrompt } : {}) }));
532
+ rt.sessionId = last;
533
+ rt.fresh = false;
534
+ }
535
+ catch (error) {
536
+ if (signal.aborted || !live.alive())
537
+ throw error;
538
+ log("acp: the agent did not load its session; a new one starts with the conversation so far", { error: message(error).slice(0, 300) });
539
+ }
540
+ finally {
541
+ rt.loading = false;
542
+ }
543
+ }
544
+ if (rt.fresh) {
545
+ const opened = await ask("session/new", () => live.connection.agent.request("session/new", { cwd: root, mcpServers: [server], ...(systemPrompt ? { systemPrompt } : {}) }));
546
+ rt.sessionId = opened.sessionId;
547
+ journal.append(SESSION_STREAM, { sessionId: opened.sessionId });
548
+ mirrorInto(rt, journal);
549
+ await journal.flush();
550
+ if (instructions && !systemPrompt)
551
+ rt.firstBlocks.push(`Instructions for this session, from the host that runs you:\n\n${instructions}`);
552
+ const context = contextNote(ctx.state());
553
+ if (context)
554
+ rt.firstBlocks.push(context);
555
+ opening = opened;
556
+ }
557
+ if (recipe.model !== undefined) {
558
+ // The run's model, among those the agent lists for its key: by its id, else by its name before the brackets.
559
+ // A loaded session that lists none keeps the one chosen for it before (MODEL_STREAM).
560
+ const models = opening?.models?.availableModels;
561
+ const ids = Array.isArray(models) ? models.map((m) => m?.modelId).filter((id) => typeof id === "string") : undefined;
562
+ const before = journalRecords(ctx.state(), MODEL_STREAM).map((r) => r.data?.modelId).filter((id) => typeof id === "string").at(-1);
563
+ const wanted = recipe.model;
564
+ const chosen = ids ? (ids.find((id) => id === wanted) ?? ids.find((id) => id.split("[")[0] === wanted)) : rt.fresh ? undefined : before;
565
+ if (!chosen) {
566
+ const said = ids?.length ? `it lists ${ids.join(", ")}` : "it lists none";
567
+ throw new Error(`${ACP_CODES.modelUnlisted}: the model ${JSON.stringify(wanted)} is not one ${recipe.label ?? recipe.id} lists for this key (${said}); no prompt was sent`);
568
+ }
569
+ await ask("session/set_model", () => live.connection.agent.request("session/set_model", { sessionId: rt.sessionId, modelId: chosen }));
570
+ if (chosen !== before) {
571
+ journal.append(MODEL_STREAM, { modelId: chosen });
572
+ await journal.flush();
573
+ }
574
+ }
575
+ log("acp: the agent's session is open", { sessionId: rt.sessionId, loaded: !rt.fresh, pid: live.pid });
576
+ return rt;
577
+ }
578
+ catch (error) {
579
+ await rt.dispose();
580
+ throw error;
581
+ }
582
+ };
583
+ /** The calls of ours the open turn's records saw and never answered, in the order they were seen. */
584
+ const danglingCalls = (state) => {
585
+ const since = openTurn(state)?.since ?? Number.POSITIVE_INFINITY;
586
+ const records = journalRecords(state, CALL_STREAM);
587
+ const answered = new Set(records.filter((r) => r.data?.type === "answered").map((r) => r.data.callId));
588
+ return records
589
+ .filter((r) => r.at > since && r.data?.type === "seen" && !answered.has(r.data.callId) && typeof r.data.tool === "string")
590
+ .map((r) => ({ callId: r.data.callId, tool: r.data.tool, args: r.data.args ?? {} }));
591
+ };
592
+ async function driveOnce(ctx) {
593
+ const journal = new NativeJournal(ctx);
594
+ const gate = options.gate;
595
+ // The gate is asked once the call's `seen` record is in the log: a call the gate parks is found again on a resume.
596
+ const bridge = toolBridge(ctx, options.tools, {
597
+ ...(gate ? { gate: async (call) => (await journal.flush(), gate(call)) } : {}),
598
+ beforeNever: () => journal.flush(),
599
+ });
600
+ const cur = { ctx, journal, bridge, signal: ctx.signal, inflight: new Set() };
601
+ // A resumed session: each call of ours the agent made and the records never answered goes through the bridge before
602
+ // the agent starts again. One that never reached its intent (a park held it) runs now, gate first; one whose end the
603
+ // records hold is read back; one cut off is left to the recovery note. A refused one has no effect, so the note says
604
+ // it here.
605
+ const refusedLines = [];
606
+ await resumeUnstartedCalls(ctx, bridge, danglingCalls(ctx.state()), async (call, outcome) => {
607
+ journal.append(CALL_STREAM, { type: "answered", callId: call.callId, text: outcome.text, isError: outcome.isError }, { id: `answered:${call.callId}` });
608
+ await journal.flush();
609
+ if (!ctx.state().effects.has(toolKey(call.callId)))
610
+ refusedLines.push(`- ${call.tool}(${clip(JSON.stringify(call.args) ?? "{}", 300)}), call ${call.callId}: refused by the host. Its answer:`, indent(clip(outcome.text, 1500)));
611
+ });
612
+ let rt = runtime;
613
+ if (!rt || rt.ctx !== ctx || !rt.agent.alive()) {
614
+ if (rt)
615
+ await rt.dispose();
616
+ runtime = undefined;
617
+ try {
618
+ rt = await start(ctx, journal);
619
+ }
620
+ catch (error) {
621
+ if (ctx.signal.aborted)
622
+ throw ctx.signal.reason ?? error;
623
+ // The session cannot start: the turn ends here, in the records, saying why.
624
+ await placeSubmissions(ctx, ctx.pending());
625
+ journal.message({ type: "turn", status: "failed", error: message(error).slice(0, 1000) });
626
+ await journal.flush();
627
+ return;
628
+ }
629
+ runtime = rt;
630
+ }
631
+ const agent = rt;
632
+ let interrupting = false;
633
+ agent.current = cur;
634
+ control?.({
635
+ async interrupt(ms) {
636
+ const turn = cur.turn;
637
+ if (!turn || !agent.agent.alive())
638
+ return false;
639
+ interrupting = true;
640
+ // The turn's stop aborts the calls of ours running in it; its end waits for them to stop (runTurn), so true says
641
+ // both the agent and our tools let go: none writes through this drive's journal after it.
642
+ turn.stop.abort();
643
+ await agent.agent.connection.agent.notify("session/cancel", { sessionId: agent.sessionId }).catch(() => { });
644
+ return Promise.race([turn.ended.then(() => true), sleep(ms).then(() => false)]);
645
+ },
646
+ });
647
+ const runTurn = async (body, submission, covers = []) => {
648
+ if (ctx.signal.aborted)
649
+ throw ctx.signal.reason;
650
+ // A plan-billed run counts its session/prompt turns from the records, across runners.
651
+ if (plan && journal.length(PROMPT_STREAM) >= plan.maxTurns) {
652
+ const refused = { status: "failed", error: `${ACP_CODES.turnLimit}: the plan's limit of ${plan.maxTurns} turns is reached; no more prompts are sent` };
653
+ journal.message({ type: "turn", ...refused });
654
+ await journal.flush();
655
+ return refused;
656
+ }
657
+ // The send's mark, in the log first: a crash between the two reads "marked, maybe sent", never sent twice.
658
+ journal.append(PROMPT_STREAM, { submission, ...(covers.length ? { covers: [...covers] } : {}) });
659
+ await journal.flush();
660
+ const prompt = [...agent.firstBlocks.splice(0), ...body].map((text) => ({ type: "text", text }));
661
+ let ended;
662
+ const turn = { final: "", stop: new AbortController(), ended: new Promise((resolve) => (ended = resolve)) };
663
+ cur.turn = turn;
664
+ let answer;
665
+ let failure;
666
+ // Past the plan's limit of tool calls the turn is cancelled (countCall); an agent that goes on anyway has
667
+ // LIMIT_STOP_MS, then its process is ended.
668
+ let limitTimer;
669
+ const pastLimit = new Promise((resolve) => turn.stop.signal.addEventListener("abort", () => void (turn.limitHit && (limitTimer = setTimeout(() => resolve("past limit"), LIMIT_STOP_MS))), { once: true }));
670
+ try {
671
+ const asked = agent.agent.connection.agent.request("session/prompt", { sessionId: agent.sessionId, prompt });
672
+ asked.catch(() => { });
673
+ const result = await unlessAborted(Promise.race([asked, pastLimit]), ctx.signal);
674
+ if (result === "past limit") {
675
+ log("acp: the agent went on past the plan's limit after session/cancel; its process is ended", { waitedMs: LIMIT_STOP_MS });
676
+ // Its store is taken before its process ends: a recipe with a credential loses its HOME with it.
677
+ mirrorInto(agent, journal);
678
+ await agent.dispose();
679
+ if (runtime === agent)
680
+ runtime = undefined;
681
+ }
682
+ else
683
+ answer = result;
684
+ }
685
+ catch (error) {
686
+ failure = error;
687
+ }
688
+ finally {
689
+ clearTimeout(limitTimer);
690
+ cur.turn = undefined;
691
+ turn.stop.abort();
692
+ // The calls of ours still running were told to stop (the turn's signal): the turn ends once they did, so none
693
+ // writes to the records after it.
694
+ if (!(await settledWithin(cur.inflight, CALL_STOP_MS)))
695
+ log("acp: a call of ours did not stop with its turn", { waitedMs: CALL_STOP_MS });
696
+ ended();
697
+ }
698
+ if (ctx.signal.aborted)
699
+ throw ctx.signal.reason;
700
+ mirrorInto(agent, journal);
701
+ // Cancelled by the session's interrupt: no end is written, the turn stays open (its host settles it).
702
+ if (interrupting) {
703
+ await journal.flush();
704
+ return { status: "interrupted" };
705
+ }
706
+ let outcome;
707
+ if (turn.limitHit)
708
+ outcome = { status: "failed", error: turn.limitHit };
709
+ else if (failure !== undefined) {
710
+ const named = refusalIn(`${agent.agent.stderrTail()}\n${message(failure)}`);
711
+ outcome = { status: "failed", error: named ?? (agent.agent.alive() && !agent.agent.connection.signal.aborted ? `acp: session/prompt failed: ${message(failure).slice(0, 300)}` : `${ACP_CODES.agentExited}: the agent ended during the turn: ${whyEnded(agent.agent, failure)}`) };
712
+ }
713
+ else {
714
+ const reason = answer?.stopReason;
715
+ if (reason === "end_turn")
716
+ outcome = { status: "completed" };
717
+ else if (reason === "max_tokens")
718
+ outcome = { status: "completed", stopReason: "length" };
719
+ else if (reason === "cancelled")
720
+ outcome = { status: "interrupted" };
721
+ else if (reason === "refusal")
722
+ outcome = { status: "failed", error: `${ACP_CODES.refusal}: the agent refused to go on` };
723
+ else if (reason === "max_turn_requests")
724
+ outcome = { status: "failed", error: `${ACP_CODES.agentTurnRequests}: the agent stopped the turn at its own limit of requests` };
725
+ else
726
+ outcome = { status: "failed", error: `acp: the agent ended the turn with an unknown stop reason ${JSON.stringify(reason)}` };
727
+ }
728
+ if (turn.final)
729
+ journal.message({ type: "message", role: "assistant", text: turn.final });
730
+ journal.message({ type: "turn", ...outcome });
731
+ await journal.flush();
732
+ return outcome;
733
+ };
734
+ try {
735
+ // A turn a crash cut off: the kernel's note (quoting the turn's prompts, which a new agent session never saw), as a
736
+ // user message, with the pending messages it carries.
737
+ const note = recoveryNote(ctx.state(), { prompts: true });
738
+ if (note) {
739
+ const text = refusedLines.length ? `${note.text}\n\nThe host answered these calls of yours since:\n${refusedLines.join("\n")}` : note.text;
740
+ journal.message({ type: "message", role: "user", text, synthetic: "recovery" });
741
+ await placeSubmissions(ctx, note.pending);
742
+ await runTurn([text], `recovery:${transcriptOf(ctx.state()).length}`, [...note.turn.placed, ...note.pending.map((s) => s.id)]);
743
+ // Interrupted, or the agent's process ended (past the plan's limit): the next turn is the next drive's.
744
+ if (interrupting || !agent.agent.alive())
745
+ return;
746
+ }
747
+ // The inbox: one submission per turn.
748
+ for (;;) {
749
+ await ctx.refresh();
750
+ const [submission] = ctx.pending();
751
+ if (!submission)
752
+ break;
753
+ await placeSubmissions(ctx, [submission]);
754
+ await runTurn([submission.text ?? ""], submission.id);
755
+ if (interrupting || !agent.agent.alive())
756
+ return;
757
+ }
758
+ }
759
+ finally {
760
+ control?.(undefined);
761
+ if (agent.current === cur)
762
+ agent.current = undefined;
763
+ }
764
+ }
765
+ return {
766
+ name: "acp",
767
+ async drive(ctx) {
768
+ if (!recoveryNote(ctx.state()) && ctx.pending().length === 0)
769
+ return;
770
+ await driveOnce(ctx);
771
+ },
772
+ /** End the agent's process and its MCP server. */
773
+ async close() {
774
+ const rt = runtime;
775
+ runtime = undefined;
776
+ await rt?.dispose();
777
+ },
778
+ };
779
+ }