|
1
|
+ |
import { spawn } from "node:child_process";
|
|
2
|
+ |
|
|
3
|
+ |
import type { DelegateEvent } from "./coder-delegate.js";
|
|
4
|
+ |
|
|
5
|
+ |
/**
|
|
6
|
+ |
* A Devin child over ACP, so the fleet can see it working.
|
|
7
|
+ |
*
|
|
8
|
+ |
* Devin's print mode (`devin -p`) is a black box. It writes nothing to stdout
|
|
9
|
+ |
* until the very end — measured: fourteen seconds of silence, then the whole
|
|
10
|
+ |
* answer at once — and `--export` is written at close too. A child doing four
|
|
11
|
+ |
* minutes of real work therefore reported no tool calls, no tokens, and no
|
|
12
|
+ |
* transcript, so the fleet showed `Initializing…` for the whole run and a
|
|
13
|
+ |
* reader could not tell it from a hang.
|
|
14
|
+ |
*
|
|
15
|
+ |
* `devin acp` is the same agent as an Agent Client Protocol server over stdio,
|
|
16
|
+ |
* and it streams: `tool_call` with a title, `tool_call_update` with a status,
|
|
17
|
+ |
* `usage_update` with real token counts, and `agent_message_chunk` for the
|
|
18
|
+ |
* answer. That is every event the fleet already knows how to draw.
|
|
19
|
+ |
*
|
|
20
|
+ |
* Newline-delimited JSON-RPC, and one server per child. A shared server would
|
|
21
|
+ |
* save a process per child and cost a lifecycle nobody asked for: a crash
|
|
22
|
+ |
* would take every child with it, and a child that hangs would hold the
|
|
23
|
+ |
* server's queue.
|
|
24
|
+ |
*
|
|
25
|
+ |
* Devin logs heavily to stderr and none of it is protocol. It is drained and
|
|
26
|
+ |
* dropped rather than parsed.
|
|
27
|
+ |
*/
|
|
28
|
+ |
|
|
29
|
+ |
/** What a running Devin child reports, normalized. */
|
|
30
|
+ |
export interface DevinAcpOptions {
|
|
31
|
+ |
readonly command?: string | undefined;
|
|
32
|
+ |
/**
|
|
33
|
+ |
* The session mode, which is Devin's own word for what the old harness passed
|
|
34
|
+ |
* as `--permission-mode`. `bypass` is the equivalent of `dangerous`.
|
|
35
|
+ |
*/
|
|
36
|
+ |
readonly mode?: string | undefined;
|
|
37
|
+ |
readonly env?: Record<string, string> | undefined;
|
|
38
|
+ |
/** Every protocol message, for the transcript. */
|
|
39
|
+ |
readonly record?: ((entry: Record<string, unknown>) => void) | undefined;
|
|
40
|
+ |
}
|
|
41
|
+ |
|
|
42
|
+ |
interface Pending {
|
|
43
|
+ |
readonly resolve: (result: Record<string, unknown>) => void;
|
|
44
|
+ |
readonly reject: (cause: Error) => void;
|
|
45
|
+ |
}
|
|
46
|
+ |
|
|
47
|
+ |
export async function* runDevinAcp(
|
|
48
|
+ |
input: { readonly prompt: string; readonly cwd: string },
|
|
49
|
+ |
options: DevinAcpOptions,
|
|
50
|
+ |
signal: AbortSignal,
|
|
51
|
+ |
): AsyncIterable<DelegateEvent> {
|
|
52
|
+ |
const command = options.command ?? "devin";
|
|
53
|
+ |
const child = spawn(command, ["acp"], {
|
|
54
|
+ |
cwd: input.cwd,
|
|
55
|
+ |
env: { ...process.env, ...options.env },
|
|
56
|
+ |
stdio: ["pipe", "pipe", "pipe"],
|
|
57
|
+ |
// Its own process group, so stopping a child stops what the child started.
|
|
58
|
+ |
detached: true,
|
|
59
|
+ |
});
|
|
60
|
+ |
|
|
61
|
+ |
// Devin's own logging. Not protocol, and it is a lot of it.
|
|
62
|
+ |
child.stderr.resume();
|
|
63
|
+ |
|
|
64
|
+ |
const events: DelegateEvent[] = [];
|
|
65
|
+ |
const pending = new Map<number, Pending>();
|
|
66
|
+ |
let wake: (() => void) | undefined;
|
|
67
|
+ |
let finished = false;
|
|
68
|
+ |
let failure: Error | undefined;
|
|
69
|
+ |
let sequence = 0;
|
|
70
|
+ |
let buffer = "";
|
|
71
|
+ |
let answer = "";
|
|
72
|
+ |
|
|
73
|
+ |
const nudge = () => {
|
|
74
|
+ |
wake?.();
|
|
75
|
+ |
wake = undefined;
|
|
76
|
+ |
};
|
|
77
|
+ |
|
|
78
|
+ |
const send = (method: string, params?: Record<string, unknown>) =>
|
|
79
|
+ |
new Promise<Record<string, unknown>>((resolve, reject) => {
|
|
80
|
+ |
const id = (sequence += 1);
|
|
81
|
+ |
pending.set(id, { resolve, reject });
|
|
82
|
+ |
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
|
|
83
|
+ |
});
|
|
84
|
+ |
|
|
85
|
+ |
const reply = (id: number, result: Record<string, unknown>) => {
|
|
86
|
+ |
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
|
|
87
|
+ |
};
|
|
88
|
+ |
|
|
89
|
+ |
child.stdout.setEncoding("utf8");
|
|
90
|
+ |
child.stdout.on("data", (chunk: string) => {
|
|
91
|
+ |
buffer += chunk;
|
|
92
|
+ |
for (;;) {
|
|
93
|
+ |
const at = buffer.indexOf("\n");
|
|
94
|
+ |
if (at === -1) break;
|
|
95
|
+ |
const line = buffer.slice(0, at).trim();
|
|
96
|
+ |
buffer = buffer.slice(at + 1);
|
|
97
|
+ |
if (line.length === 0) continue;
|
|
98
|
+ |
|
|
99
|
+ |
let message: Record<string, unknown>;
|
|
100
|
+ |
try {
|
|
101
|
+ |
message = JSON.parse(line) as Record<string, unknown>;
|
|
102
|
+ |
} catch {
|
|
103
|
+ |
// Not protocol. Devin writes plain lines too.
|
|
104
|
+ |
continue;
|
|
105
|
+ |
}
|
|
106
|
+ |
|
|
107
|
+ |
options.record?.(message);
|
|
108
|
+ |
handle(message);
|
|
109
|
+ |
}
|
|
110
|
+ |
nudge();
|
|
111
|
+ |
});
|
|
112
|
+ |
|
|
113
|
+ |
const handle = (message: Record<string, unknown>) => {
|
|
114
|
+ |
const id = message["id"];
|
|
115
|
+ |
|
|
116
|
+ |
// A reply to something asked for.
|
|
117
|
+ |
if (typeof id === "number" && message["method"] === undefined) {
|
|
118
|
+ |
const waiting = pending.get(id);
|
|
119
|
+ |
pending.delete(id);
|
|
120
|
+ |
if (waiting === undefined) return;
|
|
121
|
+ |
const error = message["error"];
|
|
122
|
+ |
if (error !== undefined) {
|
|
123
|
+ |
waiting.reject(new Error(`Devin refused ${JSON.stringify(error).slice(0, 200)}`));
|
|
124
|
+ |
} else {
|
|
125
|
+ |
waiting.resolve((message["result"] ?? {}) as Record<string, unknown>);
|
|
126
|
+ |
}
|
|
127
|
+ |
return;
|
|
128
|
+ |
}
|
|
129
|
+ |
|
|
130
|
+ |
const method = message["method"];
|
|
131
|
+ |
|
|
132
|
+ |
// A request from the agent. The only one that matters is permission, and a
|
|
133
|
+ |
// delegated child has no one to ask: it was launched to run unattended, so
|
|
134
|
+ |
// an unanswered request would hang it for as long as the reader left it.
|
|
135
|
+ |
if (typeof id === "number" && method === "session/request_permission") {
|
|
136
|
+ |
const params = record(message["params"]);
|
|
137
|
+ |
const chosen = firstAllowOption(params);
|
|
138
|
+ |
reply(id, {
|
|
139
|
+ |
outcome:
|
|
140
|
+ |
chosen === undefined
|
|
141
|
+ |
? { outcome: "cancelled" }
|
|
142
|
+ |
: { outcome: "selected", optionId: chosen },
|
|
143
|
+ |
});
|
|
144
|
+ |
return;
|
|
145
|
+ |
}
|
|
146
|
+ |
|
|
147
|
+ |
if (method !== "session/update") return;
|
|
148
|
+ |
|
|
149
|
+ |
const update = record(record(message["params"])["update"]);
|
|
150
|
+ |
const kind = update["sessionUpdate"];
|
|
151
|
+ |
|
|
152
|
+ |
if (kind === "tool_call") {
|
|
153
|
+ |
const callId = text(update["toolCallId"]) ?? `devin_${String(events.length)}`;
|
|
154
|
+ |
// Devin's `title` is already the phrase a person would read — "Ran ls",
|
|
155
|
+ |
// "Read src/a.ts" — so it is the activity rather than a name to look up.
|
|
156
|
+ |
events.push({
|
|
157
|
+ |
type: "tool",
|
|
158
|
+ |
callId,
|
|
159
|
+ |
name: text(update["kind"]) ?? "tool",
|
|
160
|
+ |
target: text(update["title"]),
|
|
161
|
+ |
});
|
|
162
|
+ |
return;
|
|
163
|
+ |
}
|
|
164
|
+ |
|
|
165
|
+ |
if (kind === "usage_update") {
|
|
166
|
+ |
const meta = record(update["_meta"]);
|
|
167
|
+ |
const input_tokens = number(meta["cognition.ai/inputTokens"]);
|
|
168
|
+ |
const output_tokens = number(meta["cognition.ai/outputTokens"]);
|
|
169
|
+ |
if (input_tokens !== undefined && output_tokens !== undefined) {
|
|
170
|
+ |
events.push({ type: "tokens", input: input_tokens, output: output_tokens });
|
|
171
|
+ |
}
|
|
172
|
+ |
return;
|
|
173
|
+ |
}
|
|
174
|
+ |
|
|
175
|
+ |
if (kind === "agent_message_chunk") {
|
|
176
|
+ |
const piece = text(record(update["content"])["text"]);
|
|
177
|
+ |
if (piece !== undefined) answer += piece;
|
|
178
|
+ |
}
|
|
179
|
+ |
};
|
|
180
|
+ |
|
|
181
|
+ |
child.on("error", (cause: Error) => {
|
|
182
|
+ |
failure =
|
|
183
|
+ |
(cause as NodeJS.ErrnoException).code === "ENOENT"
|
|
184
|
+ |
? new Error(`The \`${command}\` command is not on PATH.`)
|
|
185
|
+ |
: cause;
|
|
186
|
+ |
finished = true;
|
|
187
|
+ |
nudge();
|
|
188
|
+ |
});
|
|
189
|
+ |
|
|
190
|
+ |
child.on("close", () => {
|
|
191
|
+ |
finished = true;
|
|
192
|
+ |
for (const waiting of pending.values()) {
|
|
193
|
+ |
waiting.reject(new Error("The Devin agent exited before it answered."));
|
|
194
|
+ |
}
|
|
195
|
+ |
pending.clear();
|
|
196
|
+ |
nudge();
|
|
197
|
+ |
});
|
|
198
|
+ |
|
|
199
|
+ |
const stop = () => {
|
|
200
|
+ |
try {
|
|
201
|
+ |
process.kill(-child.pid!, "SIGKILL");
|
|
202
|
+ |
} catch {
|
|
203
|
+ |
child.kill("SIGKILL");
|
|
204
|
+ |
}
|
|
205
|
+ |
};
|
|
206
|
+ |
signal.addEventListener("abort", stop, { once: true });
|
|
207
|
+ |
|
|
208
|
+ |
// The conversation, driven from here while the generator yields whatever the
|
|
209
|
+ |
// agent has said since the last time it was asked.
|
|
210
|
+ |
const turn = (async () => {
|
|
211
|
+ |
await send("initialize", {
|
|
212
|
+ |
protocolVersion: 1,
|
|
213
|
+ |
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
|
|
214
|
+ |
});
|
|
215
|
+ |
|
|
216
|
+ |
const opened = await send("session/new", { cwd: input.cwd, mcpServers: [] });
|
|
217
|
+ |
const sessionId = text(opened["sessionId"]);
|
|
218
|
+ |
if (sessionId === undefined) throw new Error("Devin opened no session.");
|
|
219
|
+ |
events.push({ type: "session", sessionId });
|
|
220
|
+ |
|
|
221
|
+ |
const mode = options.mode;
|
|
222
|
+ |
if (mode !== undefined) {
|
|
223
|
+ |
// Best effort. A build of Devin without this mode should not lose the
|
|
224
|
+ |
// child over the name of a permission setting.
|
|
225
|
+ |
await send("session/set_mode", { sessionId, modeId: mode }).catch(() => ({}));
|
|
226
|
+ |
}
|
|
227
|
+ |
|
|
228
|
+ |
await send("session/prompt", {
|
|
229
|
+ |
sessionId,
|
|
230
|
+ |
prompt: [{ type: "text", text: input.prompt }],
|
|
231
|
+ |
});
|
|
232
|
+ |
})();
|
|
233
|
+ |
|
|
234
|
+ |
turn.catch((cause: unknown) => {
|
|
235
|
+ |
// Whichever failure came first. A missing binary raises `error` and then
|
|
236
|
+ |
// `close`, and the close rejects everything still pending — so taking the
|
|
237
|
+ |
// later one reports "the agent exited before it answered" for a command
|
|
238
|
+ |
// that was never there.
|
|
239
|
+ |
failure ??= cause instanceof Error ? cause : new Error(String(cause));
|
|
240
|
+ |
});
|
|
241
|
+ |
|
|
242
|
+ |
const settled = turn.then(
|
|
243
|
+ |
() => {
|
|
244
|
+ |
finished = true;
|
|
245
|
+ |
nudge();
|
|
246
|
+ |
},
|
|
247
|
+ |
() => {
|
|
248
|
+ |
finished = true;
|
|
249
|
+ |
nudge();
|
|
250
|
+ |
},
|
|
251
|
+ |
);
|
|
252
|
+ |
|
|
253
|
+ |
try {
|
|
254
|
+ |
for (;;) {
|
|
255
|
+ |
while (events.length > 0) {
|
|
256
|
+ |
const event = events.shift();
|
|
257
|
+ |
if (event !== undefined) yield event;
|
|
258
|
+ |
}
|
|
259
|
+ |
if (finished) break;
|
|
260
|
+ |
if (signal.aborted) return;
|
|
261
|
+ |
await new Promise<void>((resolve) => {
|
|
262
|
+ |
wake = resolve;
|
|
263
|
+ |
});
|
|
264
|
+ |
}
|
|
265
|
+ |
|
|
266
|
+ |
await settled;
|
|
267
|
+ |
|
|
268
|
+ |
// A stopped fleet is not a failed child. Killing the agent closes its
|
|
269
|
+ |
// stdio, which rejects everything still in flight, and reporting that as
|
|
270
|
+ |
// an error would make every `ctrl+x` look like a crash.
|
|
271
|
+ |
if (signal.aborted) return;
|
|
272
|
+ |
|
|
273
|
+ |
if (failure !== undefined) {
|
|
274
|
+ |
yield { type: "error", message: failure.message };
|
|
275
|
+ |
throw failure;
|
|
276
|
+ |
}
|
|
277
|
+ |
|
|
278
|
+ |
const said = answer.trim();
|
|
279
|
+ |
if (said.length > 0) yield { type: "text", value: said };
|
|
280
|
+ |
} finally {
|
|
281
|
+ |
signal.removeEventListener("abort", stop);
|
|
282
|
+ |
stop();
|
|
283
|
+ |
}
|
|
284
|
+ |
}
|
|
285
|
+ |
|
|
286
|
+ |
/** The option a permission request offers that lets the work continue. */
|
|
287
|
+ |
const firstAllowOption = (params: Record<string, unknown>): string | undefined => {
|
|
288
|
+ |
const options = params["options"];
|
|
289
|
+ |
if (!Array.isArray(options)) return undefined;
|
|
290
|
+ |
|
|
291
|
+ |
const ranked = options
|
|
292
|
+ |
.map((option) => record(option))
|
|
293
|
+ |
.filter((option) => text(option["optionId"]) !== undefined);
|
|
294
|
+ |
|
|
295
|
+ |
const allow = ranked.find((option) => String(option["kind"] ?? "").startsWith("allow"));
|
|
296
|
+ |
return text((allow ?? ranked[0] ?? {})["optionId"]);
|
|
297
|
+ |
};
|
|
298
|
+ |
|
|
299
|
+ |
const record = (value: unknown): Record<string, unknown> =>
|
|
300
|
+ |
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
301
|
+ |
? (value as Record<string, unknown>)
|
|
302
|
+ |
: {};
|
|
303
|
+ |
|
|
304
|
+ |
const text = (value: unknown): string | undefined =>
|
|
305
|
+ |
typeof value === "string" && value.length > 0 ? value : undefined;
|
|
306
|
+ |
|
|
307
|
+ |
const number = (value: unknown): number | undefined =>
|
|
308
|
+ |
typeof value === "number" && Number.isFinite(value) ? value : undefined;
|