@parcha/agentrun-harness-acp 0.1.0-beta.46 → 0.1.0-beta.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/NOTICE +2 -0
- package/README.md +1 -1
- package/dist/adapter.d.ts +43 -0
- package/dist/adapter.js +201 -0
- package/dist/calls.d.ts +39 -0
- package/dist/calls.js +138 -0
- package/dist/cursor-facts.d.ts +27 -0
- package/dist/cursor-facts.js +55 -0
- package/dist/cursor.d.ts +35 -0
- package/dist/cursor.js +53 -0
- package/dist/facts.d.ts +39 -0
- package/dist/facts.js +34 -0
- package/dist/goose-facts.d.ts +6 -0
- package/dist/goose-facts.js +32 -0
- package/dist/goose.d.ts +29 -0
- package/dist/goose.js +63 -0
- package/dist/harness.d.ts +80 -0
- package/dist/harness.js +786 -0
- package/dist/host/agent.d.ts +34 -0
- package/dist/host/agent.js +75 -0
- package/dist/host/child.d.ts +14 -0
- package/dist/host/child.js +32 -0
- package/dist/host/goose-proxy.d.ts +57 -0
- package/dist/host/goose-proxy.js +332 -0
- package/dist/host/key-cut.d.ts +10 -0
- package/dist/host/key-cut.js +29 -0
- package/dist/host/mcp-stdio.d.ts +1 -0
- package/dist/host/mcp-stdio.js +76 -0
- package/dist/host/mcp.d.ts +40 -0
- package/dist/host/mcp.js +210 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/pinned-binary.d.ts +73 -0
- package/dist/pinned-binary.js +160 -0
- package/dist/recipe.d.ts +75 -0
- package/dist/recipe.js +71 -0
- package/dist/state.d.ts +33 -0
- package/dist/state.js +157 -0
- package/dist/testing.d.ts +16 -0
- package/dist/testing.js +26 -0
- package/package.json +7 -2
- package/recipes/cursor.json +21 -0
- package/testing/fake-acp-agent.mjs +388 -0
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A stand-in ACP agent for the adapter's tests and the conformance suite: a stdio agent on the official SDK whose "model"
|
|
3
|
+
// is a script. No binary, no model, no network beyond loopback. Its one argument is a JSON config file:
|
|
4
|
+
// script: the model's steps, the conformance suite's ScriptStep ({call, args} | {say, cut} | {sayLastSteer} |
|
|
5
|
+
// {sayLastResult}) plus {native: kind, title, input}, a tool of the agent's own (a shell, an edit);
|
|
6
|
+
// load: advertise session/load and keep sessions in $HOME/.fake-acp/sessions (default true);
|
|
7
|
+
// advertiseLoad / advertiseHttp: what initialize says, when it should differ from what the agent does;
|
|
8
|
+
// http: advertise MCP over HTTP (default true); the client then picks the transport;
|
|
9
|
+
// style: "goose" (titles agentrun__<tool>, every tool asks permission, allow_always offered first) or "cursor"
|
|
10
|
+
// (titles agentrun-<tool>: <tool>; MCP and execute ask, edits do not; a refused native call still reports
|
|
11
|
+
// completed), or "goose-1.59" (as "goose", but titled as Goose 1.59.2 titles a call of an extension's tool:
|
|
12
|
+
// `agentrun: <tool, its underscores as spaces>`);
|
|
13
|
+
// askMcp: ask permission before an MCP call (default: by style); askNative: the native kinds that ask;
|
|
14
|
+
// nativeLog: a file each native call that runs appends its title to;
|
|
15
|
+
// countFile: a file each event (new, load, prompt, cancel, mcp, permission) is appended to, one JSON line;
|
|
16
|
+
// systemPrompt: advertise sessionCapabilities.systemPrompt;
|
|
17
|
+
// ignoreCancel: log session/cancel and go on as if it never came (an agent that keeps spending);
|
|
18
|
+
// keepMcpOnCancel: on session/cancel, answer the prompt `cancelled` at once and leave an MCP call in flight open;
|
|
19
|
+
// announce: "late" (with style "cursor"): an MCP call as Cursor 2026.11.13 announces it, a tool_call titled
|
|
20
|
+
// "MCP: tool" with no input, then a tool_call_update titled `agentrun: <tool>` whose rawInput is
|
|
21
|
+
// {providerIdentifier, toolName, args}; its permission request is titled `agentrun-<tool>: <tool>`;
|
|
22
|
+
// models: the models session/new and session/load list ({modelId, name}), the first current; session/set_model
|
|
23
|
+
// takes one of them and refuses any other;
|
|
24
|
+
// writeAuth: at session/new and session/load, write $HOME/.config/cursor/auth.json holding the sha256 of the
|
|
25
|
+
// CURSOR_API_KEY it was handed (a credential derived from the key, as Cursor writes one); authFile: that
|
|
26
|
+
// file's path in HOME instead. A write that fails (the path is a folder) is said on stderr and the session
|
|
27
|
+
// goes on, as Cursor's does;
|
|
28
|
+
// leak: {path, what}: at the same points, also write `path` (under HOME) holding what a release that saves its key
|
|
29
|
+
// elsewhere would: "key" the CURSOR_API_KEY as is, "base64" it in base64, "token" a JWT-shaped token (made
|
|
30
|
+
// here, no real one). For the key walk's red: a leak its guard must see;
|
|
31
|
+
// failNew: at session/new, print these words on stderr and exit 1 (Cursor's own refusals, the team admin's switch);
|
|
32
|
+
// cursorDirs: keep sessions and read the CLI config where Cursor 2026.11.13 does (cursor-config/dist/paths.js): its
|
|
33
|
+
// config directory is $CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else $HOME/.cursor; sessions in
|
|
34
|
+
// <dir>/acp-sessions, and an edit, write, delete or move refused unasked when <dir>/cli-config.json denies
|
|
35
|
+
// Write(**) (Cursor reports it completed all the same).
|
|
36
|
+
// A script step {hang: true} is a model that never answers (until a cancel the agent heeds).
|
|
37
|
+
// The step the model takes is the number it took before: its session's history (calls, native calls, answers), plus the
|
|
38
|
+
// calls a recovery or context note names that its history does not hold, as a resumed model reads its conversation.
|
|
39
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
40
|
+
import { spawn } from "node:child_process";
|
|
41
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
42
|
+
import { dirname, join } from "node:path";
|
|
43
|
+
import { createInterface } from "node:readline";
|
|
44
|
+
import { Readable, Writable } from "node:stream";
|
|
45
|
+
import { agent, ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
|
|
46
|
+
|
|
47
|
+
const config = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
48
|
+
const script = config.script ?? [];
|
|
49
|
+
const style = config.style ?? "goose";
|
|
50
|
+
const loads = config.load ?? true;
|
|
51
|
+
const askMcp = config.askMcp ?? true;
|
|
52
|
+
const askNative = new Set(config.askNative ?? (style === "cursor" ? ["execute"] : ["execute", "edit", "delete", "move", "fetch", "other"]));
|
|
53
|
+
const home = process.env.HOME ?? "/nonexistent";
|
|
54
|
+
/** Cursor's config directory, by its own rule (cursorDirs). */
|
|
55
|
+
const cursorDir = process.env.CURSOR_CONFIG_DIR?.trim() || (process.env.XDG_CONFIG_HOME?.trim() ? join(process.env.XDG_CONFIG_HOME, "cursor") : join(home, ".cursor"));
|
|
56
|
+
const store = config.cursorDirs ? join(cursorDir, "acp-sessions") : join(home, ".fake-acp", "sessions");
|
|
57
|
+
/** Whether Cursor's CLI config, where Cursor reads it, denies every Write (read at start, as Cursor reads it). */
|
|
58
|
+
const deniesWrite = (() => {
|
|
59
|
+
if (!config.cursorDirs) return false;
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(readFileSync(join(cursorDir, "cli-config.json"), "utf8")).permissions?.deny?.includes("Write(**)") === true;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
})();
|
|
66
|
+
const EDITS = new Set(["edit", "delete", "move"]);
|
|
67
|
+
|
|
68
|
+
const said = (event) => config.countFile && appendFileSync(config.countFile, `${JSON.stringify({ at: Date.now(), pid: process.pid, ...event })}\n`);
|
|
69
|
+
const save = (session) => {
|
|
70
|
+
if (!loads) return;
|
|
71
|
+
mkdirSync(store, { recursive: true });
|
|
72
|
+
writeFileSync(join(store, `${session.id}.json`), JSON.stringify({ id: session.id, history: session.history }));
|
|
73
|
+
};
|
|
74
|
+
const sessions = new Map();
|
|
75
|
+
// What it was started with: the names in its environment (never their values), its HOME and its directory.
|
|
76
|
+
const pgid = (() => {
|
|
77
|
+
try {
|
|
78
|
+
return Number(readFileSync("/proc/self/stat", "utf8").replace(/^.*\) /s, "").split(" ")[2]);
|
|
79
|
+
} catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
})();
|
|
83
|
+
said({ type: "start", env: Object.keys(process.env).sort(), home, cwd: process.cwd(), pgid, ...(config.cursorDirs ? { cursorDir, deniesWrite } : {}) });
|
|
84
|
+
const titleOf = (tool) => (style === "cursor" ? `agentrun-${tool}: ${tool}` : style === "goose-1.59" ? `agentrun: ${tool.replace(/_/g, " ")}` : `agentrun__${tool}`);
|
|
85
|
+
const late = style === "cursor" && config.announce === "late";
|
|
86
|
+
const models = config.models ? { currentModelId: config.models[0].modelId, availableModels: config.models } : undefined;
|
|
87
|
+
/** The credential Cursor derives from its key, in its private HOME: here the key's sha256, never the key. */
|
|
88
|
+
function writeAuth() {
|
|
89
|
+
if (config.leak) {
|
|
90
|
+
const key = process.env.CURSOR_API_KEY ?? "";
|
|
91
|
+
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
92
|
+
const held = { key, base64: Buffer.from(key).toString("base64"), token: `${part({ alg: "HS256", typ: "JWT" })}.${part({ sub: "fake", exp: 4102444800 })}.${part({ fake: "signature" })}` }[config.leak.what];
|
|
93
|
+
const file = join(home, config.leak.path);
|
|
94
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
95
|
+
writeFileSync(file, JSON.stringify({ held }));
|
|
96
|
+
}
|
|
97
|
+
if (!config.writeAuth) return;
|
|
98
|
+
const file = join(home, config.authFile ?? ".config/cursor/auth.json");
|
|
99
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
100
|
+
const keySha = createHash("sha256").update(process.env.CURSOR_API_KEY ?? "").digest("hex");
|
|
101
|
+
try {
|
|
102
|
+
writeFileSync(file, JSON.stringify({ keySha }));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
// As Cursor 2026.11.13 does (src/utils/credential-persistence.ts): a credential it cannot save is said on stderr, and
|
|
105
|
+
// the session goes on with the one it holds in memory.
|
|
106
|
+
process.stderr.write(`\u001b[33m⚠ Cursor couldn't save your credentials. This session continues with the credentials it already has.\u001b[0m\nError: ${error.code}: illegal operation on a directory, open '${file}'\n`);
|
|
107
|
+
said({ type: "auth", file, keySha, saved: false, code: error.code });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
said({ type: "auth", file, keySha, saved: true });
|
|
111
|
+
}
|
|
112
|
+
const steps = (history) => history.filter((h) => h.kind === "call" || h.kind === "native" || h.kind === "say").length;
|
|
113
|
+
const text = (blocks) => blocks.filter((b) => b.type === "text").map((b) => b.text);
|
|
114
|
+
|
|
115
|
+
/** The calls a note names (`- name(...), call <id>:`), a nested one's (`<id>/<key>`) left out. */
|
|
116
|
+
const namedCalls = (note) => [...note.matchAll(/, call ([^\s:/]+):/g)].map((m) => m[1]);
|
|
117
|
+
/** A note's answers said so far (`- assistant: …`, a context note's). */
|
|
118
|
+
const notedAnswers = (note) => note.split("\n").filter((line) => line.startsWith("- assistant: ")).length;
|
|
119
|
+
/** The last quoted message in a note (`> ` lines). */
|
|
120
|
+
function lastQuote(note) {
|
|
121
|
+
const groups = [];
|
|
122
|
+
let current;
|
|
123
|
+
for (const line of note.split("\n")) {
|
|
124
|
+
if (line.startsWith("> ") || line === ">") {
|
|
125
|
+
if (!current) groups.push((current = []));
|
|
126
|
+
current.push(line.replace(/^> ?/, ""));
|
|
127
|
+
} else current = undefined;
|
|
128
|
+
}
|
|
129
|
+
return groups.at(-1)?.join("\n");
|
|
130
|
+
}
|
|
131
|
+
/** The last call's result in a recovery note: the 4-space lines under its head, or what follows `failed: `. */
|
|
132
|
+
function lastNotedResult(note) {
|
|
133
|
+
const lines = note.split("\n");
|
|
134
|
+
let result;
|
|
135
|
+
for (let i = 0; i < lines.length; i++) {
|
|
136
|
+
const head = /^- .*, call [^\s:]+: (.*)$/.exec(lines[i]);
|
|
137
|
+
if (!head) continue;
|
|
138
|
+
const body = [];
|
|
139
|
+
for (let j = i + 1; j < lines.length && lines[j].startsWith(" "); j++) body.push(lines[j].slice(4));
|
|
140
|
+
result = body.length ? body.join("\n") : head[1].replace(/^failed: /, "");
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** One MCP connection: streamable HTTP, or a stdio server the agent starts. */
|
|
146
|
+
async function mcpClient(server) {
|
|
147
|
+
let next = 1;
|
|
148
|
+
if (server.type === "http") {
|
|
149
|
+
const headers = Object.fromEntries((server.headers ?? []).map((h) => [h.name, h.value]));
|
|
150
|
+
const post = async (body, signal) => {
|
|
151
|
+
const response = await fetch(server.url, { method: "POST", headers: { ...headers, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify(body), signal });
|
|
152
|
+
if (response.status === 202) return undefined;
|
|
153
|
+
const raw = await response.text();
|
|
154
|
+
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
155
|
+
const messages = raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6)));
|
|
156
|
+
return messages.find((m) => m.id === body.id);
|
|
157
|
+
}
|
|
158
|
+
return JSON.parse(raw);
|
|
159
|
+
};
|
|
160
|
+
const request = async (method, params, signal) => {
|
|
161
|
+
const answer = await post({ jsonrpc: "2.0", id: next++, method, params }, signal);
|
|
162
|
+
if (answer?.error) throw new Error(answer.error.message);
|
|
163
|
+
return answer?.result;
|
|
164
|
+
};
|
|
165
|
+
await request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "fake-acp", version: "1" } });
|
|
166
|
+
await post({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
167
|
+
return { request, close() {} };
|
|
168
|
+
}
|
|
169
|
+
const child = spawn(server.command, server.args ?? [], { env: { ...Object.fromEntries((server.env ?? []).map((e) => [e.name, e.value])), PATH: process.env.PATH ?? "" }, stdio: ["pipe", "pipe", "inherit"] });
|
|
170
|
+
const waiting = new Map();
|
|
171
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
172
|
+
let message;
|
|
173
|
+
try {
|
|
174
|
+
message = JSON.parse(line);
|
|
175
|
+
} catch {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
waiting.get(message.id)?.(message);
|
|
179
|
+
waiting.delete(message.id);
|
|
180
|
+
});
|
|
181
|
+
const request = (method, params, signal) => new Promise((resolve, reject) => {
|
|
182
|
+
const id = next++;
|
|
183
|
+
waiting.set(id, (m) => (m.error ? reject(new Error(m.error.message)) : resolve(m.result)));
|
|
184
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
|
|
185
|
+
signal?.addEventListener("abort", () => {
|
|
186
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id } })}\n`);
|
|
187
|
+
waiting.delete(id);
|
|
188
|
+
reject(new Error("cancelled"));
|
|
189
|
+
}, { once: true });
|
|
190
|
+
});
|
|
191
|
+
await request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "fake-acp", version: "1" } });
|
|
192
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
|
|
193
|
+
return { request, close: () => child.kill() };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function openSession(id, params, history) {
|
|
197
|
+
const servers = params.mcpServers ?? [];
|
|
198
|
+
const server = servers.find((s) => s.name === "agentrun") ?? servers[0];
|
|
199
|
+
const mcp = server ? await mcpClient(server) : undefined;
|
|
200
|
+
const session = { id, history, mcp, turn: undefined, system: params.systemPrompt ? text(params.systemPrompt.content ?? []).join("\n") : undefined };
|
|
201
|
+
sessions.set(id, session);
|
|
202
|
+
return session;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Ask the client about a call; true when it allowed it once. */
|
|
206
|
+
async function permitted(client, session, update) {
|
|
207
|
+
const options = style === "cursor"
|
|
208
|
+
? [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }, { optionId: "allow-always", name: "Always allow", kind: "allow_always" }, { optionId: "reject-once", name: "Reject", kind: "reject_once" }]
|
|
209
|
+
: [{ optionId: "allow_always", name: "Always Allow", kind: "allow_always" }, { optionId: "allow_once", name: "Allow Once", kind: "allow_once" }, { optionId: "reject_once", name: "Deny Once", kind: "reject_once" }, { optionId: "reject_always", name: "Always Deny", kind: "reject_always" }];
|
|
210
|
+
const answer = await client.request("session/request_permission", { sessionId: session.id, toolCall: update, options });
|
|
211
|
+
const chosen = answer.outcome.outcome === "selected" ? options.find((o) => o.optionId === answer.outcome.optionId) : undefined;
|
|
212
|
+
said({ type: "permission", toolCallId: update.toolCallId, title: update.title, outcome: answer.outcome.outcome, kind: chosen?.kind });
|
|
213
|
+
return chosen?.kind === "allow_once" || chosen?.kind === "allow_always";
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function takeTurn(client, session, prompt, signal) {
|
|
217
|
+
const blocks = text(prompt);
|
|
218
|
+
const said_ = blocks.at(-1) ?? "";
|
|
219
|
+
const notes = blocks.filter((b) => b.includes("[Recovery]") || b.includes("[Context]")).join("\n");
|
|
220
|
+
const known = new Set(session.history.filter((h) => h.kind === "call").map((h) => h.id));
|
|
221
|
+
const extra = [...new Set(namedCalls(notes))].filter((id) => !known.has(id));
|
|
222
|
+
let step = steps(session.history) + extra.length + notedAnswers(notes);
|
|
223
|
+
session.history.push({ kind: "user", text: said_ });
|
|
224
|
+
save(session);
|
|
225
|
+
const notify = (update) => client.notify("session/update", { sessionId: session.id, update });
|
|
226
|
+
let lastResult = lastNotedResult(notes) ?? [...session.history].reverse().find((h) => (h.kind === "call" || h.kind === "native") && h.result !== undefined)?.result;
|
|
227
|
+
for (;;) {
|
|
228
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
229
|
+
const s = script[step];
|
|
230
|
+
if (!s) return { stopReason: "end_turn" };
|
|
231
|
+
step++;
|
|
232
|
+
if ("call" in s) {
|
|
233
|
+
const id = `call_${step - 1}`;
|
|
234
|
+
const args = s.args ?? {};
|
|
235
|
+
const update = { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending", rawInput: args };
|
|
236
|
+
const entry = { kind: "call", id, tool: s.call, args, status: "pending" };
|
|
237
|
+
session.history.push(entry);
|
|
238
|
+
save(session);
|
|
239
|
+
if (late) {
|
|
240
|
+
// Cursor 2026.11.13: the call is announced with no name, then named by an update, then asked about by its own title.
|
|
241
|
+
await notify({ sessionUpdate: "tool_call", toolCallId: id, title: "MCP: tool", kind: "other", status: "pending", rawInput: {} });
|
|
242
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, title: `agentrun: ${s.call}`, rawInput: { providerIdentifier: "agentrun", toolName: s.call, args } });
|
|
243
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "in_progress" });
|
|
244
|
+
} else await notify({ sessionUpdate: "tool_call", ...update });
|
|
245
|
+
if (askMcp && !(await permitted(client, session, late ? { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending" } : update))) {
|
|
246
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
247
|
+
entry.status = "failed";
|
|
248
|
+
entry.result = "the client refused the call";
|
|
249
|
+
lastResult = entry.result;
|
|
250
|
+
save(session);
|
|
251
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "failed" });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
said({ type: "mcp", tool: s.call, toolCallId: id });
|
|
255
|
+
let answer;
|
|
256
|
+
try {
|
|
257
|
+
if (config.keepMcpOnCancel) {
|
|
258
|
+
// The prompt's answer does not wait for the call: a cancel ends the turn with the MCP request still open.
|
|
259
|
+
const call = session.mcp.request("tools/call", { name: s.call, arguments: args, _meta: { progressToken: id } });
|
|
260
|
+
call.catch(() => {});
|
|
261
|
+
const cancelled = new Promise((resolve) => (signal.aborted ? resolve("cancelled") : signal.addEventListener("abort", () => resolve("cancelled"), { once: true })));
|
|
262
|
+
answer = await Promise.race([call, cancelled]);
|
|
263
|
+
if (answer === "cancelled") return { stopReason: "cancelled" };
|
|
264
|
+
} else answer = await session.mcp.request("tools/call", { name: s.call, arguments: args, _meta: { progressToken: id } }, signal);
|
|
265
|
+
} catch (error) {
|
|
266
|
+
entry.status = "failed";
|
|
267
|
+
save(session);
|
|
268
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "failed" });
|
|
269
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
270
|
+
lastResult = String(error?.message ?? error);
|
|
271
|
+
entry.result = lastResult;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const result = (answer?.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("");
|
|
275
|
+
entry.status = answer?.isError ? "failed" : "completed";
|
|
276
|
+
entry.result = result;
|
|
277
|
+
lastResult = result;
|
|
278
|
+
save(session);
|
|
279
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: entry.status, content: [{ type: "content", content: { type: "text", text: result } }] });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if ("native" in s) {
|
|
283
|
+
const id = `native_${step - 1}`;
|
|
284
|
+
const update = { toolCallId: id, title: s.title ?? s.native, kind: s.native, status: "pending", rawInput: s.input ?? {} };
|
|
285
|
+
const entry = { kind: "native", id, title: update.title, status: "pending" };
|
|
286
|
+
session.history.push(entry);
|
|
287
|
+
save(session);
|
|
288
|
+
await notify({ sessionUpdate: "tool_call", ...update });
|
|
289
|
+
const allowed = deniesWrite && EDITS.has(s.native) ? false : askNative.has(s.native) ? await permitted(client, session, update) : true;
|
|
290
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
291
|
+
if (allowed && config.nativeLog) appendFileSync(config.nativeLog, `${update.title}\n`);
|
|
292
|
+
entry.status = allowed ? "completed" : "failed";
|
|
293
|
+
entry.result = allowed ? `ran ${update.title}` : "the client refused the call";
|
|
294
|
+
lastResult = entry.result;
|
|
295
|
+
save(session);
|
|
296
|
+
// Cursor reports a refused call completed: the client must never trust it.
|
|
297
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: style === "cursor" ? "completed" : entry.status });
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if ("die" in s) {
|
|
301
|
+
// Killed mid-turn (SIGKILL), as a host's kill takes it: no answer, no exit of its own.
|
|
302
|
+
said({ type: "die" });
|
|
303
|
+
process.kill(process.pid, "SIGKILL");
|
|
304
|
+
}
|
|
305
|
+
if ("hang" in s) {
|
|
306
|
+
said({ type: "hang" });
|
|
307
|
+
await new Promise((resolve) => (signal.aborted ? resolve() : signal.addEventListener("abort", resolve, { once: true })));
|
|
308
|
+
return { stopReason: "cancelled" };
|
|
309
|
+
}
|
|
310
|
+
let words;
|
|
311
|
+
if ("say" in s) words = s.say;
|
|
312
|
+
else if ("sayLastResult" in s) words = lastResult ?? "";
|
|
313
|
+
else if ("sayLastSteer" in s) words = (notes.includes("[Recovery]") ? lastQuote(blocks.find((b) => b.includes("[Recovery]"))) : undefined) ?? said_;
|
|
314
|
+
else words = "";
|
|
315
|
+
session.history.push({ kind: "say", text: words });
|
|
316
|
+
save(session);
|
|
317
|
+
if (words) await notify({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: words } });
|
|
318
|
+
return { stopReason: s.cut ? "max_tokens" : "end_turn" };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const app = agent({ name: "fake-acp" })
|
|
323
|
+
.onRequest("initialize", () => ({
|
|
324
|
+
protocolVersion: 1,
|
|
325
|
+
agentCapabilities: {
|
|
326
|
+
loadSession: config.advertiseLoad ?? loads,
|
|
327
|
+
mcpCapabilities: { http: config.advertiseHttp ?? config.http ?? true, sse: false },
|
|
328
|
+
...(config.systemPrompt ? { sessionCapabilities: { systemPrompt: {} } } : {}),
|
|
329
|
+
},
|
|
330
|
+
agentInfo: { name: "fake-acp", version: "1.0.0" },
|
|
331
|
+
}))
|
|
332
|
+
.onRequest("session/new", async ({ params }) => {
|
|
333
|
+
if (config.failNew) {
|
|
334
|
+
process.stderr.write(`${config.failNew}\n`);
|
|
335
|
+
process.exit(1);
|
|
336
|
+
}
|
|
337
|
+
const id = `sess_${randomUUID()}`;
|
|
338
|
+
const session = await openSession(id, params, []);
|
|
339
|
+
save(session);
|
|
340
|
+
writeAuth();
|
|
341
|
+
said({ type: "new", sessionId: id, mcp: params.mcpServers.map((s) => s.type ?? "stdio"), system: session.system });
|
|
342
|
+
return { sessionId: id, ...(models ? { models } : {}) };
|
|
343
|
+
})
|
|
344
|
+
// Not in the SDK's stable methods: Cursor's own (unstable ACP) method, so its params are taken as they come.
|
|
345
|
+
.onRequest("session/set_model", (params) => params ?? {}, async ({ params }) => {
|
|
346
|
+
if (!models?.availableModels.some((m) => m.modelId === params.modelId)) throw RequestError.invalidParams({ modelId: params.modelId });
|
|
347
|
+
said({ type: "set_model", sessionId: params.sessionId, modelId: params.modelId });
|
|
348
|
+
return {};
|
|
349
|
+
})
|
|
350
|
+
.onRequest("session/load", async ({ params, client }) => {
|
|
351
|
+
const file = join(store, `${params.sessionId}.json`);
|
|
352
|
+
if (!loads || !existsSync(file)) throw RequestError.resourceNotFound(params.sessionId);
|
|
353
|
+
const { history } = JSON.parse(readFileSync(file, "utf8"));
|
|
354
|
+
const session = await openSession(params.sessionId, params, history);
|
|
355
|
+
said({ type: "load", sessionId: params.sessionId, steps: steps(history) });
|
|
356
|
+
// The history goes back to the client as it happened: a client keeps it off its timeline.
|
|
357
|
+
for (const h of history) {
|
|
358
|
+
if (h.kind === "user") await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "user_message_chunk", content: { type: "text", text: h.text } } });
|
|
359
|
+
if (h.kind === "say" && h.text) await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: h.text } } });
|
|
360
|
+
if (h.kind === "call" || h.kind === "native") {
|
|
361
|
+
await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "tool_call", toolCallId: h.id, title: h.kind === "call" ? titleOf(h.tool) : h.title, status: "pending", rawInput: h.args ?? {} } });
|
|
362
|
+
await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "tool_call_update", toolCallId: h.id, status: h.status === "pending" ? "failed" : h.status } });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
writeAuth();
|
|
366
|
+
return models ? { models } : {};
|
|
367
|
+
})
|
|
368
|
+
.onRequest("session/prompt", async ({ params, client }) => {
|
|
369
|
+
const session = sessions.get(params.sessionId);
|
|
370
|
+
if (!session) throw RequestError.resourceNotFound(params.sessionId);
|
|
371
|
+
const controller = new AbortController();
|
|
372
|
+
session.turn = controller;
|
|
373
|
+
said({ type: "prompt", sessionId: session.id, text: text(params.prompt) });
|
|
374
|
+
try {
|
|
375
|
+
return await takeTurn(client, session, params.prompt, controller.signal);
|
|
376
|
+
} finally {
|
|
377
|
+
session.turn = undefined;
|
|
378
|
+
}
|
|
379
|
+
})
|
|
380
|
+
.onNotification("session/cancel", ({ params }) => {
|
|
381
|
+
said({ type: "cancel", sessionId: params.sessionId });
|
|
382
|
+
if (!config.ignoreCancel) sessions.get(params.sessionId)?.turn?.abort(new Error("cancelled"));
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
const connection = app.connect(ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
|
|
386
|
+
await connection.closed;
|
|
387
|
+
for (const session of sessions.values()) session.mcp?.close();
|
|
388
|
+
process.exit(0);
|