|
1
|
+ |
import { appendFileSync } from "node:fs";
|
|
2
|
+ |
|
|
3
|
+ |
import { accumulate, frames, parse, parseArguments } from "./coder-thread.js";
|
|
4
|
+ |
import type { ChildGrant } from "./coder-child-gateway.js";
|
|
5
|
+ |
import type { DelegateEvent, DelegateHarness } from "./coder-delegate.js";
|
|
6
|
+ |
import { boundedResult } from "./coder-thread.js";
|
|
7
|
+ |
import type { CoderTool } from "./coder-tools.js";
|
|
8
|
+ |
import { shellTool } from "./coder-tools.js";
|
|
9
|
+ |
import { Redacted } from "effect";
|
|
10
|
+ |
|
|
11
|
+ |
/**
|
|
12
|
+ |
* Children run by this process, on the account's own thread grant.
|
|
13
|
+ |
*
|
|
14
|
+ |
* The lane this replaces is `opencode`: a second coding agent, installed
|
|
15
|
+ |
* separately, with its own credentials, its own model catalog, its own tool
|
|
16
|
+ |
* loop, and its own idea of what a coding agent is. It worked, and it cost a
|
|
17
|
+ |
* process per child and an unbounded amount of behaviour nobody here chose —
|
|
18
|
+ |
* a child answering from whichever model that install happened to have, with
|
|
19
|
+ |
* whichever tools that version happened to ship.
|
|
20
|
+ |
*
|
|
21
|
+ |
* A self-hosted child is the same loop the parent session already runs,
|
|
22
|
+ |
* smaller: the grant the server minted for children, pinned to Ox Alpha, a
|
|
23
|
+ |
* short and deliberate toolset, and this process's own turn loop. No second
|
|
24
|
+ |
* agent to install, no second credential, and the model is the one the
|
|
25
|
+ |
* conversation asked for rather than the one the harness had.
|
|
26
|
+ |
*
|
|
27
|
+ |
* The proxy is the only thing it talks to, so no provider key reaches this
|
|
28
|
+ |
* process (RELEASE-002). `ox-alpha` is what the child thread's grant pins, and
|
|
29
|
+ |
* the server routes that to OpenRouter's `stealth/ox-alpha`.
|
|
30
|
+ |
*
|
|
31
|
+ |
* `opencode` stays as the fallback for a session with no grant to spend, and
|
|
32
|
+ |
* for a reader who names it.
|
|
33
|
+ |
*/
|
|
34
|
+ |
|
|
35
|
+ |
/** How many rounds of tool calls one child may take. */
|
|
36
|
+ |
const MAX_ROUNDS = 60;
|
|
37
|
+ |
|
|
38
|
+ |
/** What a child is told it is, and what it may do. */
|
|
39
|
+ |
const SYSTEM = (cwd: string, tools: ReadonlyArray<CoderTool>) =>
|
|
40
|
+ |
[
|
|
41
|
+ |
"You are a delegated child agent of `openagents coder`, working in a terminal.",
|
|
42
|
+ |
"",
|
|
43
|
+ |
"You were given one task by a parent agent, and you cannot ask it anything: it is not",
|
|
44
|
+ |
"waiting on you and there is nobody to answer. Everything you need is in the task, or is",
|
|
45
|
+ |
"on this machine, or is not available — say so plainly rather than guessing.",
|
|
46
|
+ |
"",
|
|
47
|
+ |
`The working directory is ${cwd}.`,
|
|
48
|
+ |
"",
|
|
49
|
+ |
`You have ${String(tools.length)} tool${tools.length === 1 ? "" : "s"}, and no others:`,
|
|
50
|
+ |
...tools.map((tool) => `- \`${tool.name}\``),
|
|
51
|
+ |
"",
|
|
52
|
+ |
// The parent counts on this: a child's answer is read by an agent, not a
|
|
53
|
+ |
// person, and a child that stops mid-task without saying so is reported as
|
|
54
|
+ |
// having succeeded.
|
|
55
|
+ |
"That list is complete. You cannot delegate further — you are the child. When you are",
|
|
56
|
+ |
"done, your final message is the whole of what the parent receives, so it has to carry",
|
|
57
|
+ |
"the answer rather than point at work you did. If you could not finish, say what you did,",
|
|
58
|
+ |
"what stopped you, and what remains.",
|
|
59
|
+ |
].join("\n");
|
|
60
|
+ |
|
|
61
|
+ |
export interface SelfHarnessOptions {
|
|
62
|
+ |
readonly grant: ChildGrant;
|
|
63
|
+ |
/** Overrides the tools a child gets. For tests. */
|
|
64
|
+ |
readonly tools?: (cwd: string) => ReadonlyArray<CoderTool>;
|
|
65
|
+ |
}
|
|
66
|
+ |
|
|
67
|
+ |
type WireMessage =
|
|
68
|
+ |
| { readonly role: "system"; readonly content: string }
|
|
69
|
+ |
| { readonly role: "user"; readonly content: string }
|
|
70
|
+ |
| {
|
|
71
|
+ |
readonly role: "assistant";
|
|
72
|
+ |
readonly content: string;
|
|
73
|
+ |
readonly tool_calls?: ReadonlyArray<Record<string, unknown>>;
|
|
74
|
+ |
}
|
|
75
|
+ |
| { readonly role: "tool"; readonly tool_call_id: string; readonly content: string };
|
|
76
|
+ |
|
|
77
|
+ |
export class SelfHarness implements DelegateHarness {
|
|
78
|
+ |
readonly agent = "openagents";
|
|
79
|
+ |
readonly model: string;
|
|
80
|
+ |
|
|
81
|
+ |
/**
|
|
82
|
+ |
* Live children's transcripts, by session.
|
|
83
|
+ |
*
|
|
84
|
+ |
* What makes a retry resume rather than restart. A child whose provider
|
|
85
|
+ |
* dropped after twenty tool calls carries on from its own transcript instead
|
|
86
|
+ |
* of re-reading and re-editing everything.
|
|
87
|
+ |
*/
|
|
88
|
+ |
private readonly sessions = new Map<string, WireMessage[]>();
|
|
89
|
+ |
private sequence = 0;
|
|
90
|
+ |
|
|
91
|
+ |
constructor(private readonly options: SelfHarnessOptions) {
|
|
92
|
+ |
this.model = options.grant.model;
|
|
93
|
+ |
}
|
|
94
|
+ |
|
|
95
|
+ |
/**
|
|
96
|
+ |
* The toolset a child gets, which is deliberately shorter than the parent's.
|
|
97
|
+ |
*
|
|
98
|
+ |
* `shell` is the whole of it. It reads, writes, searches, lists, and runs
|
|
99
|
+ |
* tests, which is the work a child is given; the parent's other tools are
|
|
100
|
+ |
* either the parent's own business (`delegate` — a child that delegates is a
|
|
101
|
+ |
* fan-out nobody asked for) or a way of reaching the account (`openagents`),
|
|
102
|
+ |
* which is not a child's to spend.
|
|
103
|
+ |
*/
|
|
104
|
+ |
private toolsFor(cwd: string): ReadonlyArray<CoderTool> {
|
|
105
|
+ |
return this.options.tools?.(cwd) ?? [shellTool(cwd)];
|
|
106
|
+ |
}
|
|
107
|
+ |
|
|
108
|
+ |
async *run(
|
|
109
|
+ |
input: {
|
|
110
|
+ |
readonly prompt: string;
|
|
111
|
+ |
readonly cwd: string;
|
|
112
|
+ |
readonly transcriptPath: string;
|
|
113
|
+ |
readonly resumeSessionId?: string | undefined;
|
|
114
|
+ |
},
|
|
115
|
+ |
signal: AbortSignal,
|
|
116
|
+ |
): AsyncIterable<DelegateEvent> {
|
|
117
|
+ |
const tools = this.toolsFor(input.cwd);
|
|
118
|
+ |
|
|
119
|
+ |
const resumed =
|
|
120
|
+ |
input.resumeSessionId === undefined
|
|
121
|
+ |
? undefined
|
|
122
|
+ |
: this.sessions.get(input.resumeSessionId);
|
|
123
|
+ |
|
|
124
|
+ |
const sessionId = input.resumeSessionId ?? this.mintSession();
|
|
125
|
+ |
const transcript: WireMessage[] = resumed ?? [
|
|
126
|
+ |
{ role: "system", content: SYSTEM(input.cwd, tools) },
|
|
127
|
+ |
{ role: "user", content: input.prompt },
|
|
128
|
+ |
];
|
|
129
|
+ |
|
|
130
|
+ |
if (resumed !== undefined) {
|
|
131
|
+ |
transcript.push({
|
|
132
|
+ |
role: "user",
|
|
133
|
+ |
content:
|
|
134
|
+ |
"The previous attempt stopped when the model provider became unavailable. " +
|
|
135
|
+ |
"Continue from where you left off and finish the task.",
|
|
136
|
+ |
});
|
|
137
|
+ |
}
|
|
138
|
+ |
|
|
139
|
+ |
this.sessions.set(sessionId, transcript);
|
|
140
|
+ |
yield { type: "session", sessionId };
|
|
141
|
+ |
|
|
142
|
+ |
const record = (entry: Record<string, unknown>) => {
|
|
143
|
+ |
// Written as it happens, not at the end, so a child that is killed still
|
|
144
|
+ |
// leaves everything it had done behind.
|
|
145
|
+ |
try {
|
|
146
|
+ |
appendFileSync(input.transcriptPath, `${JSON.stringify(entry)}\n`);
|
|
147
|
+ |
} catch {
|
|
148
|
+ |
// A transcript that cannot be written must not end the child's work.
|
|
149
|
+ |
}
|
|
150
|
+ |
};
|
|
151
|
+ |
|
|
152
|
+ |
record({ type: "session", sessionId, model: this.model, cwd: input.cwd });
|
|
153
|
+ |
|
|
154
|
+ |
for (let round = 0; round < MAX_ROUNDS; round += 1) {
|
|
155
|
+ |
if (signal.aborted) return;
|
|
156
|
+ |
|
|
157
|
+ |
const calls = new Map<number, { id: string; name: string; args: string }>();
|
|
158
|
+ |
let said = "";
|
|
159
|
+ |
|
|
160
|
+ |
const body = await this.call(transcript, tools, signal);
|
|
161
|
+ |
if (body === undefined || signal.aborted) return;
|
|
162
|
+ |
|
|
163
|
+ |
for await (const frame of frames(body, signal)) {
|
|
164
|
+ |
if (signal.aborted) return;
|
|
165
|
+ |
if (frame === "[DONE]") break;
|
|
166
|
+ |
|
|
167
|
+ |
const payload = parse(frame);
|
|
168
|
+ |
if (payload === undefined) continue;
|
|
169
|
+ |
|
|
170
|
+ |
const usage = payload["usage"];
|
|
171
|
+ |
if (typeof usage === "object" && usage !== null) {
|
|
172
|
+ |
const counts = usage as Record<string, unknown>;
|
|
173
|
+ |
const input_tokens = counts["prompt_tokens"];
|
|
174
|
+ |
const output_tokens = counts["completion_tokens"];
|
|
175
|
+ |
if (typeof input_tokens === "number" && typeof output_tokens === "number") {
|
|
176
|
+ |
yield { type: "tokens", input: input_tokens, output: output_tokens };
|
|
177
|
+ |
}
|
|
178
|
+ |
}
|
|
179
|
+ |
|
|
180
|
+ |
const choices = payload["choices"];
|
|
181
|
+ |
if (!Array.isArray(choices)) continue;
|
|
182
|
+ |
|
|
183
|
+ |
for (const choice of choices) {
|
|
184
|
+ |
const delta = (choice as Record<string, unknown>)["delta"];
|
|
185
|
+ |
if (typeof delta !== "object" || delta === null) continue;
|
|
186
|
+ |
const parts = delta as Record<string, unknown>;
|
|
187
|
+ |
|
|
188
|
+ |
const content = parts["content"];
|
|
189
|
+ |
if (typeof content === "string") said += content;
|
|
190
|
+ |
|
|
191
|
+ |
const asked = parts["tool_calls"];
|
|
192
|
+ |
if (Array.isArray(asked)) accumulate(calls, asked);
|
|
193
|
+ |
}
|
|
194
|
+ |
}
|
|
195
|
+ |
|
|
196
|
+ |
const wanted = [...calls.values()];
|
|
197
|
+ |
|
|
198
|
+ |
if (wanted.length === 0) {
|
|
199
|
+ |
if (said.length > 0) transcript.push({ role: "assistant", content: said });
|
|
200
|
+ |
record({ type: "text", value: said });
|
|
201
|
+ |
yield { type: "text", value: said };
|
|
202
|
+ |
this.sessions.delete(sessionId);
|
|
203
|
+ |
return;
|
|
204
|
+ |
}
|
|
205
|
+ |
|
|
206
|
+ |
transcript.push({
|
|
207
|
+ |
role: "assistant",
|
|
208
|
+ |
content: said,
|
|
209
|
+ |
tool_calls: wanted.map((call) => ({
|
|
210
|
+ |
id: call.id,
|
|
211
|
+ |
type: "function",
|
|
212
|
+ |
function: { name: call.name, arguments: call.args },
|
|
213
|
+ |
})),
|
|
214
|
+ |
});
|
|
215
|
+ |
|
|
216
|
+ |
for (const call of wanted) {
|
|
217
|
+ |
if (signal.aborted) return;
|
|
218
|
+ |
|
|
219
|
+ |
const args = parseArguments(call.args);
|
|
220
|
+ |
yield {
|
|
221
|
+ |
type: "tool",
|
|
222
|
+ |
callId: call.id,
|
|
223
|
+ |
name: call.name,
|
|
224
|
+ |
target: targetOf(args),
|
|
225
|
+ |
};
|
|
226
|
+ |
record({ type: "tool", callId: call.id, name: call.name, arguments: args });
|
|
227
|
+ |
|
|
228
|
+ |
const tool = tools.find((candidate) => candidate.name === call.name);
|
|
229
|
+ |
const output =
|
|
230
|
+ |
tool === undefined
|
|
231
|
+ |
? `No tool called ${call.name} is available to a child agent.`
|
|
232
|
+ |
: await tool
|
|
233
|
+ |
.run(args, signal)
|
|
234
|
+ |
.catch((cause: unknown) => `The tool failed: ${String(cause)}`);
|
|
235
|
+ |
|
|
236
|
+ |
transcript.push({
|
|
237
|
+ |
role: "tool",
|
|
238
|
+ |
tool_call_id: call.id,
|
|
239
|
+ |
content: boundedResult(output),
|
|
240
|
+ |
});
|
|
241
|
+ |
record({ type: "tool_result", callId: call.id, output });
|
|
242
|
+ |
}
|
|
243
|
+ |
}
|
|
244
|
+ |
|
|
245
|
+ |
yield {
|
|
246
|
+ |
type: "error",
|
|
247
|
+ |
message: `The child stopped after ${String(MAX_ROUNDS)} rounds of tool calls.`,
|
|
248
|
+ |
};
|
|
249
|
+ |
}
|
|
250
|
+ |
|
|
251
|
+ |
/** One call to the proxy on the child's grant. */
|
|
252
|
+ |
private async call(
|
|
253
|
+ |
transcript: ReadonlyArray<WireMessage>,
|
|
254
|
+ |
tools: ReadonlyArray<CoderTool>,
|
|
255
|
+ |
signal: AbortSignal,
|
|
256
|
+ |
): Promise<ReadableStream<Uint8Array> | undefined> {
|
|
257
|
+ |
const response = await fetch(this.options.grant.proxyUrl, {
|
|
258
|
+ |
method: "POST",
|
|
259
|
+ |
signal,
|
|
260
|
+ |
headers: {
|
|
261
|
+ |
authorization: `Bearer ${Redacted.value(this.options.grant.token)}`,
|
|
262
|
+ |
"content-type": "application/json",
|
|
263
|
+ |
accept: "text/event-stream, application/json",
|
|
264
|
+ |
},
|
|
265
|
+ |
body: JSON.stringify({
|
|
266
|
+ |
model: this.options.grant.model,
|
|
267
|
+ |
stream: true,
|
|
268
|
+ |
messages: transcript,
|
|
269
|
+ |
tools: tools.map((tool) => ({
|
|
270
|
+ |
type: "function",
|
|
271
|
+ |
function: {
|
|
272
|
+ |
name: tool.name,
|
|
273
|
+ |
description: tool.description,
|
|
274
|
+ |
parameters: tool.parameters,
|
|
275
|
+ |
},
|
|
276
|
+ |
})),
|
|
277
|
+ |
}),
|
|
278
|
+ |
}).catch((cause: unknown) => {
|
|
279
|
+ |
if (signal.aborted) return undefined;
|
|
280
|
+ |
// Thrown rather than yielded, so the fleet's retry sees it: the words
|
|
281
|
+ |
// matter, because that is what `transientProviderFailure` reads.
|
|
282
|
+ |
throw new Error(`Upstream request failed: ${String(cause)}`);
|
|
283
|
+ |
});
|
|
284
|
+ |
|
|
285
|
+ |
if (response === undefined || signal.aborted) return undefined;
|
|
286
|
+ |
|
|
287
|
+ |
if (!response.ok) {
|
|
288
|
+ |
const detail = (await response.text().catch(() => "")).slice(0, 300);
|
|
289
|
+ |
throw new Error(
|
|
290
|
+ |
`The inference proxy refused the child's call (${String(response.status)})` +
|
|
291
|
+ |
(detail.length === 0 ? "." : `: ${detail}`),
|
|
292
|
+ |
);
|
|
293
|
+ |
}
|
|
294
|
+ |
|
|
295
|
+ |
return response.body ?? undefined;
|
|
296
|
+ |
}
|
|
297
|
+ |
|
|
298
|
+ |
private mintSession(): string {
|
|
299
|
+ |
this.sequence += 1;
|
|
300
|
+ |
return `s${Date.now().toString(36)}${this.sequence.toString(36).padStart(2, "0")}`;
|
|
301
|
+ |
}
|
|
302
|
+ |
}
|
|
303
|
+ |
|
|
304
|
+ |
/** The one argument worth showing in a fleet row, if there is one. */
|
|
305
|
+ |
function targetOf(args: Record<string, unknown>): string | undefined {
|
|
306
|
+ |
for (const key of ["command", "path", "file", "pattern"]) {
|
|
307
|
+ |
const value = args[key];
|
|
308
|
+ |
if (typeof value === "string" && value.length > 0) return value;
|
|
309
|
+ |
}
|
|
310
|
+ |
return undefined;
|
|
311
|
+ |
}
|