@a-dray/aglib 0.6.7 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/harness/adapters/claude-agent-sdk/index.d.ts +55 -0
- package/dist/harness/adapters/claude-agent-sdk/index.js +267 -0
- package/dist/harness/adapters/claude-agent-sdk/index.js.map +1 -0
- package/dist/harness/adapters/codex/index.d.ts +80 -0
- package/dist/harness/adapters/codex/index.js +373 -0
- package/dist/harness/adapters/codex/index.js.map +1 -0
- package/dist/harness/adapters/vendor.d.ts +98 -0
- package/dist/harness/adapters/vendor.js +217 -0
- package/dist/harness/adapters/vendor.js.map +1 -0
- package/dist/model/adapters/openai-compatible/index.js +7 -3
- package/dist/model/adapters/openai-compatible/index.js.map +1 -1
- package/dist/model/adapters/openai-responses/index.d.ts +2 -0
- package/dist/model/adapters/openai-responses/index.js +5 -4
- package/dist/model/adapters/openai-responses/index.js.map +1 -1
- package/dist/run.js +62 -13
- package/dist/run.js.map +1 -1
- package/dist/store/adapters/sqlite.js +42 -6
- package/dist/store/adapters/sqlite.js.map +1 -1
- package/dist/store/conformance.d.ts +1 -1
- package/dist/store/conformance.js +19 -0
- package/dist/store/conformance.js.map +1 -1
- package/dist/store/store.d.ts +26 -12
- package/dist/store/store.js.map +1 -1
- package/package.json +16 -3
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { textOf } from "../../../content.js";
|
|
3
|
+
import { err, ok } from "../../../result.js";
|
|
4
|
+
import { arrivals, createToolRunner, described, opening, openingInputs, sessionState, toolFingerprint } from "../vendor.js";
|
|
5
|
+
const provider = "codex-app-server";
|
|
6
|
+
/**
|
|
7
|
+
* Codex's own built-in tools, switched off by name.
|
|
8
|
+
*
|
|
9
|
+
* Every one of them would run on the host this process runs on, which is the
|
|
10
|
+
* application's server rather than any sandbox of ours, so none may stay on.
|
|
11
|
+
* The names are Codex's feature flags as of the version this was measured
|
|
12
|
+
* against; a feature it adds later is caught at run time instead — any item
|
|
13
|
+
* that is not one of our calls fails the turn (`ownItems`).
|
|
14
|
+
*/
|
|
15
|
+
const disabled = [
|
|
16
|
+
"shell_tool", "unified_exec", "view_image", "multi_agent", "goals", "apps", "image_generation",
|
|
17
|
+
"computer_use", "browser_use", "skill_search", "tool_suggest", "sleep_tool", "code_mode_host", "auth_elicitation",
|
|
18
|
+
];
|
|
19
|
+
const settings = {
|
|
20
|
+
web_search: '"disabled"',
|
|
21
|
+
"skills.include_instructions": "false",
|
|
22
|
+
"tools.experimental_request_user_input.enabled": "false",
|
|
23
|
+
};
|
|
24
|
+
/** The MCP server Codex serves an account's ChatGPT connectors from. */
|
|
25
|
+
const appsServer = "codex_apps";
|
|
26
|
+
/** Thread items that mean Codex did something itself. */
|
|
27
|
+
const ownItems = new Set(["commandExecution", "fileChange", "mcpToolCall", "collabAgentToolCall", "subAgentActivity", "webSearch", "imageView", "imageGeneration"]);
|
|
28
|
+
/**
|
|
29
|
+
* OpenAI's Codex loop, running our tools and nothing of its own.
|
|
30
|
+
*
|
|
31
|
+
* Codex is the program a ChatGPT plan is sold for, and its app server is the
|
|
32
|
+
* protocol its own clients speak, so this is how a subscriber spends their plan
|
|
33
|
+
* from an agent of their own: sign Codex in (`signInToCodex`), and let it run
|
|
34
|
+
* the loop. An API key works the same way, through Codex's own configuration.
|
|
35
|
+
*
|
|
36
|
+
* What it keeps: our instructions as the thread's base instructions, our tools
|
|
37
|
+
* as its whole tool list (declared as dynamic tools, which Codex calls back for
|
|
38
|
+
* rather than running), every call through our executor and into our log. What
|
|
39
|
+
* it gives up is what `createClaudeAgentSdkHarness` gives up: the context is
|
|
40
|
+
* Codex's and is compacted by Codex, an interrupted activation is over, and a
|
|
41
|
+
* later one resumes the thread the log names or starts a new one from a
|
|
42
|
+
* transcript. Codex fixes a thread's tools when it starts, so a thread is
|
|
43
|
+
* resumed only while the tool list is the one it was started with.
|
|
44
|
+
*/
|
|
45
|
+
export function createCodexHarness(options) {
|
|
46
|
+
return {
|
|
47
|
+
id: `${provider}:${options.model}`,
|
|
48
|
+
recovery: "none",
|
|
49
|
+
async run(context) {
|
|
50
|
+
const fingerprint = toolFingerprint(context);
|
|
51
|
+
const first = await runTurn(options, context, opening(context, provider, { fingerprint }), fingerprint);
|
|
52
|
+
if (first.status === "failed" && first.error.code === "session-missing") {
|
|
53
|
+
return runTurn(options, context, opening(context, provider, { fresh: true, fingerprint }), fingerprint);
|
|
54
|
+
}
|
|
55
|
+
return first;
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async function runTurn(options, context, start, fingerprint) {
|
|
60
|
+
const rpc = open(options);
|
|
61
|
+
const runner = createToolRunner(context);
|
|
62
|
+
const shown = openingInputs(context);
|
|
63
|
+
const startedAt = new Date().toISOString();
|
|
64
|
+
let usage;
|
|
65
|
+
let turnId;
|
|
66
|
+
let threadId = start.resume ?? "";
|
|
67
|
+
let finished;
|
|
68
|
+
const done = new Promise((resolve) => { finished = resolve; });
|
|
69
|
+
const fail = (code, message) => finished?.({ status: "failed", error: { code, message, retryable: false } });
|
|
70
|
+
rpc.onRequest("item/tool/call", async (params) => {
|
|
71
|
+
const name = String(field(params, "tool") ?? "");
|
|
72
|
+
const callId = String(field(params, "callId") ?? `call_${crypto.randomUUID()}`);
|
|
73
|
+
const result = await runner.run({ callId, name, arguments: JSON.stringify(field(params, "arguments") ?? {}) });
|
|
74
|
+
// Our boundary for `turn` input, as in the native loop: results are in.
|
|
75
|
+
if (await context.drain?.() && turnId) {
|
|
76
|
+
for (const input of arrivals(context, shown)) {
|
|
77
|
+
void rpc.request("turn/steer", { threadId, expectedTurnId: turnId, input: encodeInput(input) });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return ok(encodeResult(result));
|
|
81
|
+
});
|
|
82
|
+
// Nothing of Codex's own runs, so nothing of its own is approved or answered.
|
|
83
|
+
for (const method of ["item/commandExecution/requestApproval", "item/fileChange/requestApproval", "execCommandApproval", "applyPatchApproval"]) {
|
|
84
|
+
rpc.onRequest(method, async () => ok({ decision: "decline" }));
|
|
85
|
+
}
|
|
86
|
+
rpc.onRequest("item/tool/requestUserInput", async () => ok({ answers: {} }));
|
|
87
|
+
rpc.onRequest("mcpServer/elicitation/request", async () => ok({ action: "decline", content: null, _meta: null }));
|
|
88
|
+
rpc.onNotify("item/agentMessage/delta", (params) => context.emit({ type: "text.delta", text: String(field(params, "delta") ?? ""), runId: context.runId }));
|
|
89
|
+
rpc.onNotify("item/reasoning/textDelta", (params) => context.emit({ type: "reasoning.delta", text: String(field(params, "delta") ?? ""), runId: context.runId }));
|
|
90
|
+
const connector = (item) => options.connectors === true && field(item, "type") === "mcpToolCall" && field(item, "server") === appsServer;
|
|
91
|
+
rpc.onNotify("item/started", (params) => {
|
|
92
|
+
const type = String(field(field(params, "item"), "type") ?? "");
|
|
93
|
+
if (ownItems.has(type) && !connector(field(params, "item"))) {
|
|
94
|
+
void rpc.request("turn/interrupt", { threadId, turnId: String(field(params, "turnId") ?? turnId ?? "") });
|
|
95
|
+
fail("unsupported", `Codex started a ${type} of its own, which this harness does not allow. Its built-in tools are disabled by name; this Codex has one the list does not know.`);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
rpc.onNotify("item/completed", (params) => {
|
|
99
|
+
const item = field(params, "item");
|
|
100
|
+
if (field(item, "type") === "agentMessage")
|
|
101
|
+
runner.say(String(field(item, "text") ?? ""));
|
|
102
|
+
if (connector(item)) {
|
|
103
|
+
const failure = field(field(item, "error"), "message");
|
|
104
|
+
const content = field(field(item, "result"), "content");
|
|
105
|
+
const text = Array.isArray(content) ? content.map((part) => field(part, "type") === "text" ? String(field(part, "text") ?? "") : `[${String(field(part, "type") ?? "part")}]`).join("\n") : "";
|
|
106
|
+
void runner.note({ name: `${appsServer}.${String(field(item, "tool") ?? "")}`, arguments: field(item, "arguments") ?? {}, result: typeof failure === "string" ? failure : text, ...(typeof failure === "string" ? { isError: true } : {}) });
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
let baseline;
|
|
110
|
+
rpc.onNotify("thread/tokenUsage/updated", (params) => {
|
|
111
|
+
if (field(params, "turnId") !== turnId)
|
|
112
|
+
return;
|
|
113
|
+
const total = counts(field(field(params, "tokenUsage"), "total"));
|
|
114
|
+
baseline ??= minus(total, counts(field(field(params, "tokenUsage"), "last")));
|
|
115
|
+
usage = decodeUsage(minus(total, baseline));
|
|
116
|
+
});
|
|
117
|
+
rpc.onNotify("turn/completed", (params) => {
|
|
118
|
+
const turn = field(params, "turn");
|
|
119
|
+
if (turnId && field(turn, "id") !== turnId)
|
|
120
|
+
return;
|
|
121
|
+
const status = String(field(turn, "status") ?? "");
|
|
122
|
+
if (status === "completed")
|
|
123
|
+
finished?.({ status: "completed", output: "" });
|
|
124
|
+
else if (status === "interrupted")
|
|
125
|
+
finished?.({ status: "cancelled" });
|
|
126
|
+
else
|
|
127
|
+
fail("provider", `Codex stopped: ${String(field(field(turn, "error"), "message") ?? status)}`);
|
|
128
|
+
});
|
|
129
|
+
rpc.onClose((reason) => fail("provider", `Codex exited: ${reason}`));
|
|
130
|
+
const cancel = () => {
|
|
131
|
+
if (turnId)
|
|
132
|
+
void rpc.request("turn/interrupt", { threadId, turnId });
|
|
133
|
+
finished?.({ status: "cancelled" });
|
|
134
|
+
};
|
|
135
|
+
context.signal.addEventListener("abort", cancel, { once: true });
|
|
136
|
+
try {
|
|
137
|
+
const ready = await initialize(rpc);
|
|
138
|
+
if (!ready.ok)
|
|
139
|
+
return { status: "failed", error: ready.error };
|
|
140
|
+
const thread = {
|
|
141
|
+
model: options.model, cwd: options.cwd, approvalPolicy: "never", sandbox: "read-only",
|
|
142
|
+
baseInstructions: [textOf(context.instructions), ...(context.context?.run ? [context.context.run] : [])].join("\n\n"),
|
|
143
|
+
};
|
|
144
|
+
const opened = start.resume
|
|
145
|
+
? await rpc.request("thread/resume", { ...thread, threadId: start.resume })
|
|
146
|
+
: await rpc.request("thread/start", { ...thread, dynamicTools: (context.tools?.list() ?? []).map((tool) => ({ type: "function", name: tool.name, description: tool.description, inputSchema: tool.parameters })) });
|
|
147
|
+
if (!opened.ok) {
|
|
148
|
+
if (start.resume)
|
|
149
|
+
return { status: "failed", error: { code: "session-missing", message: opened.error.message, retryable: true } };
|
|
150
|
+
return { status: "failed", error: opened.error };
|
|
151
|
+
}
|
|
152
|
+
threadId = String(field(field(opened.value, "thread"), "id") ?? threadId);
|
|
153
|
+
const turned = await rpc.request("turn/start", { threadId, input: encodeInput(start.prompt), ...(options.effort ? { effort: options.effort } : {}) });
|
|
154
|
+
if (!turned.ok)
|
|
155
|
+
return { status: "failed", error: turned.error };
|
|
156
|
+
turnId = String(field(field(turned.value, "turn"), "id") ?? "");
|
|
157
|
+
const ended = await done;
|
|
158
|
+
if (ended.status !== "completed")
|
|
159
|
+
return ended;
|
|
160
|
+
if (usage)
|
|
161
|
+
runner.spent(usage);
|
|
162
|
+
const output = await runner.finish(sessionState(provider, threadId, fingerprint), { id: turnId, startedAt, model: options.model });
|
|
163
|
+
return { status: "completed", output };
|
|
164
|
+
}
|
|
165
|
+
finally {
|
|
166
|
+
context.signal.removeEventListener("abort", cancel);
|
|
167
|
+
rpc.close();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/** Whether Codex is signed in, and as whom. */
|
|
171
|
+
export async function codexAccount(process_) {
|
|
172
|
+
const rpc = open(process_);
|
|
173
|
+
try {
|
|
174
|
+
const ready = await initialize(rpc);
|
|
175
|
+
if (!ready.ok)
|
|
176
|
+
return ready;
|
|
177
|
+
const read = await rpc.request("account/read", {});
|
|
178
|
+
if (!read.ok)
|
|
179
|
+
return read;
|
|
180
|
+
const account = field(read.value, "account");
|
|
181
|
+
if (!account)
|
|
182
|
+
return ok({ signedIn: false });
|
|
183
|
+
const email = field(account, "email"), plan = field(account, "planType");
|
|
184
|
+
return ok({ signedIn: true, kind: String(field(account, "type") ?? ""), ...(typeof email === "string" ? { email } : {}), ...(typeof plan === "string" ? { plan } : {}) });
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
rpc.close();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Sign Codex in to a ChatGPT plan with a device code: the person opens
|
|
192
|
+
* `verificationUrl`, signs in to OpenAI there, and enters `userCode`.
|
|
193
|
+
*
|
|
194
|
+
* OpenAI's own flow, run by Codex itself, so no credential passes through the
|
|
195
|
+
* caller; Codex keeps the grant in `CODEX_HOME` and refreshes it. The process
|
|
196
|
+
* stays up until `completed` settles or `cancel` is called.
|
|
197
|
+
*/
|
|
198
|
+
export async function signInToCodex(process_) {
|
|
199
|
+
const rpc = open(process_);
|
|
200
|
+
const ready = await initialize(rpc);
|
|
201
|
+
if (!ready.ok) {
|
|
202
|
+
rpc.close();
|
|
203
|
+
return ready;
|
|
204
|
+
}
|
|
205
|
+
let settle;
|
|
206
|
+
const completed = new Promise((resolve) => { settle = resolve; });
|
|
207
|
+
rpc.onNotify("account/login/completed", (params) => {
|
|
208
|
+
settle(field(params, "success") === true ? ok(undefined) : err({ code: "auth", message: String(field(params, "error") ?? "Sign-in did not complete."), retryable: true }));
|
|
209
|
+
});
|
|
210
|
+
rpc.onClose((reason) => settle(err({ code: "provider", message: `Codex exited: ${reason}`, retryable: true })));
|
|
211
|
+
const started = await rpc.request("account/login/start", { type: "chatgptDeviceCode" });
|
|
212
|
+
if (!started.ok) {
|
|
213
|
+
rpc.close();
|
|
214
|
+
return started;
|
|
215
|
+
}
|
|
216
|
+
const loginId = String(field(started.value, "loginId") ?? "");
|
|
217
|
+
void completed.finally(() => rpc.close());
|
|
218
|
+
return ok({
|
|
219
|
+
verificationUrl: String(field(started.value, "verificationUrl") ?? ""),
|
|
220
|
+
userCode: String(field(started.value, "userCode") ?? ""),
|
|
221
|
+
completed,
|
|
222
|
+
cancel() { void rpc.request("account/login/cancel", { loginId }).finally(() => settle(err({ code: "cancelled", message: "Sign-in cancelled.", retryable: false }))); },
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const initialize = async (rpc) => {
|
|
226
|
+
// Dynamic tools are an experimental field, and Codex leaves them out unless asked.
|
|
227
|
+
const ready = await rpc.request("initialize", { clientInfo: { name: "aglib", title: null, version: "0" }, capabilities: { experimentalApi: true } });
|
|
228
|
+
if (ready.ok)
|
|
229
|
+
rpc.notify("initialized");
|
|
230
|
+
return ready;
|
|
231
|
+
};
|
|
232
|
+
/** A JSON-RPC client over one connection, answering the server's requests from handlers. */
|
|
233
|
+
function open(process_) {
|
|
234
|
+
const argv = [...(process_.command ?? ["codex", "app-server"])];
|
|
235
|
+
for (const feature of disabled)
|
|
236
|
+
if (!(process_.connectors && feature === "apps"))
|
|
237
|
+
argv.push("--disable", feature);
|
|
238
|
+
for (const [key, value] of Object.entries({ ...settings, ...process_.config }))
|
|
239
|
+
argv.push("-c", `${key}=${value}`);
|
|
240
|
+
const connection = (process_.connect ?? spawnConnection)(argv, process_.env);
|
|
241
|
+
const pending = new Map();
|
|
242
|
+
const requests = new Map();
|
|
243
|
+
const notices = new Map();
|
|
244
|
+
const closers = [];
|
|
245
|
+
let next = 0;
|
|
246
|
+
let closed = false;
|
|
247
|
+
void (async () => {
|
|
248
|
+
let reason = "its output ended";
|
|
249
|
+
try {
|
|
250
|
+
for await (const message of connection.messages) {
|
|
251
|
+
const id = field(message, "id");
|
|
252
|
+
const method = field(message, "method");
|
|
253
|
+
if (typeof method !== "string") {
|
|
254
|
+
const reply = pending.get(Number(id));
|
|
255
|
+
pending.delete(Number(id));
|
|
256
|
+
const error = field(message, "error");
|
|
257
|
+
reply?.(error ? err({ code: "protocol", message: String(field(error, "message") ?? "Codex refused the request."), retryable: false }) : ok(field(message, "result") ?? null));
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (id === undefined) {
|
|
261
|
+
notices.get(method)?.(field(message, "params"));
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
// Answered without holding up the reader: a tool call can take minutes,
|
|
265
|
+
// and the notifications and replies behind it still need reading.
|
|
266
|
+
const handler = requests.get(method);
|
|
267
|
+
void (handler ? handler(field(message, "params")) : Promise.resolve(err({ code: "unsupported", message: `No handler for ${method}.`, retryable: false })))
|
|
268
|
+
.then((answered) => { if (!closed)
|
|
269
|
+
connection.send(answered.ok ? { id, result: answered.value } : { id, error: { code: -32601, message: answered.error.message } }); });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
274
|
+
}
|
|
275
|
+
if (closed)
|
|
276
|
+
return;
|
|
277
|
+
closed = true;
|
|
278
|
+
const said = connection.stderr?.().trim();
|
|
279
|
+
if (said)
|
|
280
|
+
reason = `${reason}: ${said}`;
|
|
281
|
+
for (const reply of pending.values())
|
|
282
|
+
reply(err({ code: "provider", message: `Codex exited: ${reason}`, retryable: true }));
|
|
283
|
+
pending.clear();
|
|
284
|
+
for (const close of closers)
|
|
285
|
+
close(reason);
|
|
286
|
+
})();
|
|
287
|
+
return {
|
|
288
|
+
request(method, params) {
|
|
289
|
+
if (closed)
|
|
290
|
+
return Promise.resolve(err({ code: "provider", message: "Codex is not running.", retryable: true }));
|
|
291
|
+
next += 1;
|
|
292
|
+
const id = next;
|
|
293
|
+
return new Promise((resolve) => { pending.set(id, resolve); connection.send({ id, method, params }); });
|
|
294
|
+
},
|
|
295
|
+
notify(method) { connection.send({ method }); },
|
|
296
|
+
onRequest(method, handler) { requests.set(method, handler); },
|
|
297
|
+
onNotify(method, handler) { notices.set(method, handler); },
|
|
298
|
+
onClose(handler) { closers.push(handler); },
|
|
299
|
+
close() { if (!closed) {
|
|
300
|
+
closed = true;
|
|
301
|
+
connection.close();
|
|
302
|
+
} },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function spawnConnection(argv, env) {
|
|
306
|
+
const child = spawn(argv[0], argv.slice(1), { env: { ...env }, stdio: ["pipe", "pipe", "pipe"] });
|
|
307
|
+
const spawned = new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
|
|
308
|
+
let stderr = "";
|
|
309
|
+
child.stderr.on("data", (chunk) => { stderr = `${stderr}${String(chunk)}`.slice(-2_000); });
|
|
310
|
+
return {
|
|
311
|
+
stderr: () => stderr,
|
|
312
|
+
send(message) { if (child.stdin.writable)
|
|
313
|
+
child.stdin.write(`${JSON.stringify(message)}\n`); },
|
|
314
|
+
messages: (async function* () {
|
|
315
|
+
await spawned;
|
|
316
|
+
let buffer = "";
|
|
317
|
+
for await (const chunk of child.stdout) {
|
|
318
|
+
buffer += String(chunk);
|
|
319
|
+
for (let cut = buffer.indexOf("\n"); cut >= 0; cut = buffer.indexOf("\n")) {
|
|
320
|
+
const line = buffer.slice(0, cut).trim();
|
|
321
|
+
buffer = buffer.slice(cut + 1);
|
|
322
|
+
if (!line)
|
|
323
|
+
continue;
|
|
324
|
+
try {
|
|
325
|
+
yield JSON.parse(line);
|
|
326
|
+
}
|
|
327
|
+
catch { /* a log line on stdout is not a message */ }
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
})(),
|
|
331
|
+
close() { child.stdin.end(); child.kill(); },
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function encodeInput(content) {
|
|
335
|
+
if (typeof content === "string")
|
|
336
|
+
return [{ type: "text", text: content, text_elements: [] }];
|
|
337
|
+
const out = [];
|
|
338
|
+
for (const part of content) {
|
|
339
|
+
if (part.type === "image")
|
|
340
|
+
out.push({ type: "image", url: part.source.kind === "inline" ? `data:${part.mediaType};base64,${part.source.data}` : part.source.url });
|
|
341
|
+
else if (part.type === "text" || part.type === "file")
|
|
342
|
+
out.push({ type: "text", text: described([part]), text_elements: [] });
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
}
|
|
346
|
+
function encodeResult(result) {
|
|
347
|
+
const items = typeof result.content === "string"
|
|
348
|
+
? [{ type: "inputText", text: result.content }]
|
|
349
|
+
: result.content.flatMap((part) => {
|
|
350
|
+
if (part.type === "image")
|
|
351
|
+
return [{ type: "inputImage", imageUrl: part.source.kind === "inline" ? `data:${part.mediaType};base64,${part.source.data}` : part.source.url }];
|
|
352
|
+
if (part.type === "text" || part.type === "file")
|
|
353
|
+
return [{ type: "inputText", text: described([part]) }];
|
|
354
|
+
return [];
|
|
355
|
+
});
|
|
356
|
+
return { contentItems: items.length ? items : [{ type: "inputText", text: "" }], success: !result.isError };
|
|
357
|
+
}
|
|
358
|
+
function counts(value) {
|
|
359
|
+
const number = (key) => { const found = field(value, key); return typeof found === "number" ? found : 0; };
|
|
360
|
+
return { input: number("inputTokens"), cached: number("cachedInputTokens"), written: number("cacheWriteInputTokens"), output: number("outputTokens") };
|
|
361
|
+
}
|
|
362
|
+
const minus = (a, b) => ({ input: a.input - b.input, cached: a.cached - b.cached, written: a.written - b.written, output: a.output - b.output });
|
|
363
|
+
/** OpenAI counts cached input inside `inputTokens`; `Usage` keeps the three disjoint. */
|
|
364
|
+
function decodeUsage(turn) {
|
|
365
|
+
return {
|
|
366
|
+
inputTokens: Math.max(0, turn.input - turn.cached - turn.written),
|
|
367
|
+
outputTokens: turn.output,
|
|
368
|
+
cacheReadTokens: turn.cached,
|
|
369
|
+
...(turn.written ? { cacheWriteTokens: turn.written } : {}),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
const field = (value, key) => value !== null && typeof value === "object" && !Array.isArray(value) ? value[key] : undefined;
|
|
373
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/harness/adapters/codex/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAG3C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,GAAG,EAAE,EAAE,EAA6B,MAAM,oBAAoB,CAAC;AAExE,OAAO,EA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CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AAEzK,yFAAyF;AACzF,SAAS,WAAW,CAAC,IAAY;IAC/B,OAAO;QACL,WAAW,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC;QACjE,YAAY,EAAE,IAAI,CAAC,MAAM;QACzB,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC5D,CAAC;AACJ,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,KAA4B,EAAE,GAAW,EAAyB,EAAE,CACjF,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAE,KAAmC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC","sourcesContent":["import { spawn } from \"node:child_process\";\nimport type { Harness, HarnessContext, HarnessResult } from \"../../harness.js\";\nimport type { Content } from \"../../../content.js\";\nimport { textOf } from \"../../../content.js\";\nimport type { ToolResult, Usage } from \"../../../session/entry.js\";\nimport { err, ok, type Failure, type Result } from \"../../../result.js\";\nimport type { JsonValue } from \"../../../json.js\";\nimport { arrivals, createToolRunner, described, opening, openingInputs, sessionState, toolFingerprint } from \"../vendor.js\";\n\n/** How to start Codex's app server: argv and its whole environment. */\nexport interface CodexProcess {\n /** Defaults to `[\"codex\", \"app-server\"]`. */\n command?: readonly string[];\n /**\n * The process's whole environment, which replaces the server's. `CODEX_HOME`\n * is where Codex keeps its sign-in and the threads a later activation\n * resumes; `PATH` and `HOME` it needs as any program does.\n */\n env: Readonly<Record<string, string>>;\n /** Further `-c key=value` overrides, the value in TOML. */\n config?: Readonly<Record<string, string>>;\n /**\n * Leave Codex's apps on: the connectors on the signed-in ChatGPT account,\n * beside our tools. A connector call runs in OpenAI's cloud, not through our\n * executor, and is recorded as a note. Every other tool of Codex's own stays\n * off, and still fails the turn if one appears.\n */\n connectors?: boolean;\n /** Injectable for tests; the default spawns `command`. */\n connect?: (argv: readonly string[], env: Readonly<Record<string, string>>) => CodexConnection;\n}\n\nexport interface CodexHarnessOptions extends CodexProcess {\n model: string;\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** The thread's working directory. Codex runs no tools of its own here, so this only needs to exist. */\n cwd: string;\n}\n\n/** One JSON-RPC peer over newline-delimited JSON. */\nexport interface CodexConnection {\n send(message: JsonValue): void;\n readonly messages: AsyncIterable<JsonValue>;\n close(): void;\n /** The last of what the process wrote to stderr, said when it exits: the reason is there. */\n stderr?(): string;\n}\n\nconst provider = \"codex-app-server\";\n\n/**\n * Codex's own built-in tools, switched off by name.\n *\n * Every one of them would run on the host this process runs on, which is the\n * application's server rather than any sandbox of ours, so none may stay on.\n * The names are Codex's feature flags as of the version this was measured\n * against; a feature it adds later is caught at run time instead — any item\n * that is not one of our calls fails the turn (`ownItems`).\n */\nconst disabled = [\n \"shell_tool\", \"unified_exec\", \"view_image\", \"multi_agent\", \"goals\", \"apps\", \"image_generation\",\n \"computer_use\", \"browser_use\", \"skill_search\", \"tool_suggest\", \"sleep_tool\", \"code_mode_host\", \"auth_elicitation\",\n];\nconst settings: Readonly<Record<string, string>> = {\n web_search: '\"disabled\"',\n \"skills.include_instructions\": \"false\",\n \"tools.experimental_request_user_input.enabled\": \"false\",\n};\n/** The MCP server Codex serves an account's ChatGPT connectors from. */\nconst appsServer = \"codex_apps\";\n/** Thread items that mean Codex did something itself. */\nconst ownItems = new Set([\"commandExecution\", \"fileChange\", \"mcpToolCall\", \"collabAgentToolCall\", \"subAgentActivity\", \"webSearch\", \"imageView\", \"imageGeneration\"]);\n\n/**\n * OpenAI's Codex loop, running our tools and nothing of its own.\n *\n * Codex is the program a ChatGPT plan is sold for, and its app server is the\n * protocol its own clients speak, so this is how a subscriber spends their plan\n * from an agent of their own: sign Codex in (`signInToCodex`), and let it run\n * the loop. An API key works the same way, through Codex's own configuration.\n *\n * What it keeps: our instructions as the thread's base instructions, our tools\n * as its whole tool list (declared as dynamic tools, which Codex calls back for\n * rather than running), every call through our executor and into our log. What\n * it gives up is what `createClaudeAgentSdkHarness` gives up: the context is\n * Codex's and is compacted by Codex, an interrupted activation is over, and a\n * later one resumes the thread the log names or starts a new one from a\n * transcript. Codex fixes a thread's tools when it starts, so a thread is\n * resumed only while the tool list is the one it was started with.\n */\nexport function createCodexHarness(options: CodexHarnessOptions): Harness {\n return {\n id: `${provider}:${options.model}`,\n recovery: \"none\",\n async run(context) {\n const fingerprint = toolFingerprint(context);\n const first = await runTurn(options, context, opening(context, provider, { fingerprint }), fingerprint);\n if (first.status === \"failed\" && first.error.code === \"session-missing\") {\n return runTurn(options, context, opening(context, provider, { fresh: true, fingerprint }), fingerprint);\n }\n return first;\n },\n };\n}\n\nasync function runTurn(options: CodexHarnessOptions, context: HarnessContext, start: { resume?: string; prompt: Content }, fingerprint: string): Promise<HarnessResult> {\n const rpc = open(options);\n const runner = createToolRunner(context);\n const shown = openingInputs(context);\n const startedAt = new Date().toISOString();\n let usage: Usage | undefined;\n let turnId: string | undefined;\n let threadId = start.resume ?? \"\";\n let finished: ((result: HarnessResult) => void) | undefined;\n const done = new Promise<HarnessResult>((resolve) => { finished = resolve; });\n const fail = (code: string, message: string) => finished?.({ status: \"failed\", error: { code, message, retryable: false } });\n\n rpc.onRequest(\"item/tool/call\", async (params) => {\n const name = String(field(params, \"tool\") ?? \"\");\n const callId = String(field(params, \"callId\") ?? `call_${crypto.randomUUID()}`);\n const result = await runner.run({ callId, name, arguments: JSON.stringify(field(params, \"arguments\") ?? {}) });\n // Our boundary for `turn` input, as in the native loop: results are in.\n if (await context.drain?.() && turnId) {\n for (const input of arrivals(context, shown)) {\n void rpc.request(\"turn/steer\", { threadId, expectedTurnId: turnId, input: encodeInput(input) });\n }\n }\n return ok(encodeResult(result));\n });\n // Nothing of Codex's own runs, so nothing of its own is approved or answered.\n for (const method of [\"item/commandExecution/requestApproval\", \"item/fileChange/requestApproval\", \"execCommandApproval\", \"applyPatchApproval\"]) {\n rpc.onRequest(method, async () => ok({ decision: \"decline\" }));\n }\n rpc.onRequest(\"item/tool/requestUserInput\", async () => ok({ answers: {} }));\n rpc.onRequest(\"mcpServer/elicitation/request\", async () => ok({ action: \"decline\", content: null, _meta: null }));\n\n rpc.onNotify(\"item/agentMessage/delta\", (params) => context.emit({ type: \"text.delta\", text: String(field(params, \"delta\") ?? \"\"), runId: context.runId }));\n rpc.onNotify(\"item/reasoning/textDelta\", (params) => context.emit({ type: \"reasoning.delta\", text: String(field(params, \"delta\") ?? \"\"), runId: context.runId }));\n const connector = (item: JsonValue | undefined) => options.connectors === true && field(item, \"type\") === \"mcpToolCall\" && field(item, \"server\") === appsServer;\n rpc.onNotify(\"item/started\", (params) => {\n const type = String(field(field(params, \"item\"), \"type\") ?? \"\");\n if (ownItems.has(type) && !connector(field(params, \"item\"))) {\n void rpc.request(\"turn/interrupt\", { threadId, turnId: String(field(params, \"turnId\") ?? turnId ?? \"\") });\n fail(\"unsupported\", `Codex started a ${type} of its own, which this harness does not allow. Its built-in tools are disabled by name; this Codex has one the list does not know.`);\n }\n });\n rpc.onNotify(\"item/completed\", (params) => {\n const item = field(params, \"item\");\n if (field(item, \"type\") === \"agentMessage\") runner.say(String(field(item, \"text\") ?? \"\"));\n if (connector(item)) {\n const failure = field(field(item, \"error\"), \"message\");\n const content = field(field(item, \"result\"), \"content\");\n const text = Array.isArray(content) ? content.map((part) => field(part, \"type\") === \"text\" ? String(field(part, \"text\") ?? \"\") : `[${String(field(part, \"type\") ?? \"part\")}]`).join(\"\\n\") : \"\";\n void runner.note({ name: `${appsServer}.${String(field(item, \"tool\") ?? \"\")}`, arguments: field(item, \"arguments\") ?? {}, result: typeof failure === \"string\" ? failure : text, ...(typeof failure === \"string\" ? { isError: true } : {}) });\n }\n });\n let baseline: Counts | undefined;\n rpc.onNotify(\"thread/tokenUsage/updated\", (params) => {\n if (field(params, \"turnId\") !== turnId) return;\n const total = counts(field(field(params, \"tokenUsage\"), \"total\"));\n baseline ??= minus(total, counts(field(field(params, \"tokenUsage\"), \"last\")));\n usage = decodeUsage(minus(total, baseline));\n });\n rpc.onNotify(\"turn/completed\", (params) => {\n const turn = field(params, \"turn\");\n if (turnId && field(turn, \"id\") !== turnId) return;\n const status = String(field(turn, \"status\") ?? \"\");\n if (status === \"completed\") finished?.({ status: \"completed\", output: \"\" });\n else if (status === \"interrupted\") finished?.({ status: \"cancelled\" });\n else fail(\"provider\", `Codex stopped: ${String(field(field(turn, \"error\"), \"message\") ?? status)}`);\n });\n rpc.onClose((reason) => fail(\"provider\", `Codex exited: ${reason}`));\n\n const cancel = () => {\n if (turnId) void rpc.request(\"turn/interrupt\", { threadId, turnId });\n finished?.({ status: \"cancelled\" });\n };\n context.signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const ready = await initialize(rpc);\n if (!ready.ok) return { status: \"failed\", error: ready.error };\n\n const thread = {\n model: options.model, cwd: options.cwd, approvalPolicy: \"never\", sandbox: \"read-only\",\n baseInstructions: [textOf(context.instructions), ...(context.context?.run ? [context.context.run] : [])].join(\"\\n\\n\"),\n };\n const opened = start.resume\n ? await rpc.request(\"thread/resume\", { ...thread, threadId: start.resume })\n : await rpc.request(\"thread/start\", { ...thread, dynamicTools: (context.tools?.list() ?? []).map((tool) => ({ type: \"function\", name: tool.name, description: tool.description, inputSchema: tool.parameters })) } as JsonValue);\n if (!opened.ok) {\n if (start.resume) return { status: \"failed\", error: { code: \"session-missing\", message: opened.error.message, retryable: true } };\n return { status: \"failed\", error: opened.error };\n }\n threadId = String(field(field(opened.value, \"thread\"), \"id\") ?? threadId);\n\n const turned = await rpc.request(\"turn/start\", { threadId, input: encodeInput(start.prompt), ...(options.effort ? { effort: options.effort } : {}) } as JsonValue);\n if (!turned.ok) return { status: \"failed\", error: turned.error };\n turnId = String(field(field(turned.value, \"turn\"), \"id\") ?? \"\");\n\n const ended = await done;\n if (ended.status !== \"completed\") return ended;\n if (usage) runner.spent(usage);\n const output = await runner.finish(sessionState(provider, threadId, fingerprint), { id: turnId, startedAt, model: options.model });\n return { status: \"completed\", output };\n } finally {\n context.signal.removeEventListener(\"abort\", cancel);\n rpc.close();\n }\n}\n\n/** Whether Codex is signed in, and as whom. */\nexport async function codexAccount(process_: CodexProcess): Promise<Result<{ signedIn: false } | { signedIn: true; kind: string; email?: string; plan?: string }, Failure>> {\n const rpc = open(process_);\n try {\n const ready = await initialize(rpc);\n if (!ready.ok) return ready;\n const read = await rpc.request(\"account/read\", {});\n if (!read.ok) return read;\n const account = field(read.value, \"account\");\n if (!account) return ok({ signedIn: false });\n const email = field(account, \"email\"), plan = field(account, \"planType\");\n return ok({ signedIn: true, kind: String(field(account, \"type\") ?? \"\"), ...(typeof email === \"string\" ? { email } : {}), ...(typeof plan === \"string\" ? { plan } : {}) });\n } finally {\n rpc.close();\n }\n}\n\n/**\n * Sign Codex in to a ChatGPT plan with a device code: the person opens\n * `verificationUrl`, signs in to OpenAI there, and enters `userCode`.\n *\n * OpenAI's own flow, run by Codex itself, so no credential passes through the\n * caller; Codex keeps the grant in `CODEX_HOME` and refreshes it. The process\n * stays up until `completed` settles or `cancel` is called.\n */\nexport async function signInToCodex(process_: CodexProcess): Promise<Result<{ verificationUrl: string; userCode: string; completed: Promise<Result<void, Failure>>; cancel(): void }, Failure>> {\n const rpc = open(process_);\n const ready = await initialize(rpc);\n if (!ready.ok) { rpc.close(); return ready; }\n let settle!: (result: Result<void, Failure>) => void;\n const completed = new Promise<Result<void, Failure>>((resolve) => { settle = resolve; });\n rpc.onNotify(\"account/login/completed\", (params) => {\n settle(field(params, \"success\") === true ? ok(undefined) : err({ code: \"auth\", message: String(field(params, \"error\") ?? \"Sign-in did not complete.\"), retryable: true }));\n });\n rpc.onClose((reason) => settle(err({ code: \"provider\", message: `Codex exited: ${reason}`, retryable: true })));\n const started = await rpc.request(\"account/login/start\", { type: \"chatgptDeviceCode\" });\n if (!started.ok) { rpc.close(); return started; }\n const loginId = String(field(started.value, \"loginId\") ?? \"\");\n void completed.finally(() => rpc.close());\n return ok({\n verificationUrl: String(field(started.value, \"verificationUrl\") ?? \"\"),\n userCode: String(field(started.value, \"userCode\") ?? \"\"),\n completed,\n cancel() { void rpc.request(\"account/login/cancel\", { loginId }).finally(() => settle(err({ code: \"cancelled\", message: \"Sign-in cancelled.\", retryable: false }))); },\n });\n}\n\nconst initialize = async (rpc: ReturnType<typeof open>) => {\n // Dynamic tools are an experimental field, and Codex leaves them out unless asked.\n const ready = await rpc.request(\"initialize\", { clientInfo: { name: \"aglib\", title: null, version: \"0\" }, capabilities: { experimentalApi: true } });\n if (ready.ok) rpc.notify(\"initialized\");\n return ready;\n};\n\n/** A JSON-RPC client over one connection, answering the server's requests from handlers. */\nfunction open(process_: CodexProcess) {\n const argv = [...(process_.command ?? [\"codex\", \"app-server\"])];\n for (const feature of disabled) if (!(process_.connectors && feature === \"apps\")) argv.push(\"--disable\", feature);\n for (const [key, value] of Object.entries({ ...settings, ...process_.config })) argv.push(\"-c\", `${key}=${value}`);\n const connection = (process_.connect ?? spawnConnection)(argv, process_.env);\n const pending = new Map<number, (result: Result<JsonValue, Failure>) => void>();\n const requests = new Map<string, (params: JsonValue | undefined) => Promise<Result<JsonValue, Failure>>>();\n const notices = new Map<string, (params: JsonValue | undefined) => void>();\n const closers: ((reason: string) => void)[] = [];\n let next = 0;\n let closed = false;\n\n void (async () => {\n let reason = \"its output ended\";\n try {\n for await (const message of connection.messages) {\n const id = field(message, \"id\");\n const method = field(message, \"method\");\n if (typeof method !== \"string\") {\n const reply = pending.get(Number(id));\n pending.delete(Number(id));\n const error = field(message, \"error\");\n reply?.(error ? err({ code: \"protocol\", message: String(field(error, \"message\") ?? \"Codex refused the request.\"), retryable: false }) : ok(field(message, \"result\") ?? null));\n continue;\n }\n if (id === undefined) { notices.get(method)?.(field(message, \"params\")); continue; }\n // Answered without holding up the reader: a tool call can take minutes,\n // and the notifications and replies behind it still need reading.\n const handler = requests.get(method);\n void (handler ? handler(field(message, \"params\")) : Promise.resolve(err<Failure>({ code: \"unsupported\", message: `No handler for ${method}.`, retryable: false })))\n .then((answered) => { if (!closed) connection.send(answered.ok ? { id, result: answered.value } : { id, error: { code: -32601, message: answered.error.message } }); });\n }\n } catch (error) {\n reason = error instanceof Error ? error.message : String(error);\n }\n if (closed) return;\n closed = true;\n const said = connection.stderr?.().trim();\n if (said) reason = `${reason}: ${said}`;\n for (const reply of pending.values()) reply(err({ code: \"provider\", message: `Codex exited: ${reason}`, retryable: true }));\n pending.clear();\n for (const close of closers) close(reason);\n })();\n\n return {\n request(method: string, params: JsonValue): Promise<Result<JsonValue, Failure>> {\n if (closed) return Promise.resolve(err({ code: \"provider\", message: \"Codex is not running.\", retryable: true }));\n next += 1;\n const id = next;\n return new Promise((resolve) => { pending.set(id, resolve); connection.send({ id, method, params }); });\n },\n notify(method: string) { connection.send({ method }); },\n onRequest(method: string, handler: (params: JsonValue | undefined) => Promise<Result<JsonValue, Failure>>) { requests.set(method, handler); },\n onNotify(method: string, handler: (params: JsonValue | undefined) => void) { notices.set(method, handler); },\n onClose(handler: (reason: string) => void) { closers.push(handler); },\n close() { if (!closed) { closed = true; connection.close(); } },\n };\n}\n\nfunction spawnConnection(argv: readonly string[], env: Readonly<Record<string, string>>): CodexConnection {\n const child = spawn(argv[0]!, argv.slice(1), { env: { ...env }, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n const spawned = new Promise<void>((resolve, reject) => { child.once(\"spawn\", resolve); child.once(\"error\", reject); });\n let stderr = \"\";\n child.stderr.on(\"data\", (chunk) => { stderr = `${stderr}${String(chunk)}`.slice(-2_000); });\n return {\n stderr: () => stderr,\n send(message) { if (child.stdin.writable) child.stdin.write(`${JSON.stringify(message)}\\n`); },\n messages: (async function* () {\n await spawned;\n let buffer = \"\";\n for await (const chunk of child.stdout) {\n buffer += String(chunk);\n for (let cut = buffer.indexOf(\"\\n\"); cut >= 0; cut = buffer.indexOf(\"\\n\")) {\n const line = buffer.slice(0, cut).trim();\n buffer = buffer.slice(cut + 1);\n if (!line) continue;\n try { yield JSON.parse(line) as JsonValue; } catch { /* a log line on stdout is not a message */ }\n }\n }\n })(),\n close() { child.stdin.end(); child.kill(); },\n };\n}\n\nfunction encodeInput(content: Content): JsonValue[] {\n if (typeof content === \"string\") return [{ type: \"text\", text: content, text_elements: [] }];\n const out: JsonValue[] = [];\n for (const part of content) {\n if (part.type === \"image\") out.push({ type: \"image\", url: part.source.kind === \"inline\" ? `data:${part.mediaType};base64,${part.source.data}` : part.source.url });\n else if (part.type === \"text\" || part.type === \"file\") out.push({ type: \"text\", text: described([part]), text_elements: [] });\n }\n return out;\n}\n\nfunction encodeResult(result: ToolResult): JsonValue {\n const items: JsonValue[] = typeof result.content === \"string\"\n ? [{ type: \"inputText\", text: result.content }]\n : result.content.flatMap((part): JsonValue[] => {\n if (part.type === \"image\") return [{ type: \"inputImage\", imageUrl: part.source.kind === \"inline\" ? `data:${part.mediaType};base64,${part.source.data}` : part.source.url }];\n if (part.type === \"text\" || part.type === \"file\") return [{ type: \"inputText\", text: described([part]) }];\n return [];\n });\n return { contentItems: items.length ? items : [{ type: \"inputText\", text: \"\" }], success: !result.isError };\n}\n\n/**\n * Codex reports the thread's running total and the last request's counts, once\n * per request. The turn's spend is the total now less the total before its\n * first request, which stays right if an update is repeated or one is missed.\n */\ntype Counts = { input: number; cached: number; written: number; output: number };\n\nfunction counts(value: JsonValue | undefined): Counts {\n const number = (key: string) => { const found = field(value, key); return typeof found === \"number\" ? found : 0; };\n return { input: number(\"inputTokens\"), cached: number(\"cachedInputTokens\"), written: number(\"cacheWriteInputTokens\"), output: number(\"outputTokens\") };\n}\n\nconst minus = (a: Counts, b: Counts): Counts => ({ input: a.input - b.input, cached: a.cached - b.cached, written: a.written - b.written, output: a.output - b.output });\n\n/** OpenAI counts cached input inside `inputTokens`; `Usage` keeps the three disjoint. */\nfunction decodeUsage(turn: Counts): Usage {\n return {\n inputTokens: Math.max(0, turn.input - turn.cached - turn.written),\n outputTokens: turn.output,\n cacheReadTokens: turn.cached,\n ...(turn.written ? { cacheWriteTokens: turn.written } : {}),\n };\n}\n\nconst field = (value: JsonValue | undefined, key: string): JsonValue | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, JsonValue>)[key] : undefined;\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { HarnessContext } from "../harness.js";
|
|
2
|
+
import type { Content } from "../../content.js";
|
|
3
|
+
import type { ToolCall, ToolResult, Usage } from "../../session/entry.js";
|
|
4
|
+
import type { Message } from "../../session/messages.js";
|
|
5
|
+
import type { JsonValue } from "../../json.js";
|
|
6
|
+
/**
|
|
7
|
+
* What a vendor-loop harness shares: an agent process that owns its own
|
|
8
|
+
* context and model calls, running *our* tools and nothing of its own.
|
|
9
|
+
*
|
|
10
|
+
* Two facts hold for every such adapter and are why this file exists rather
|
|
11
|
+
* than two copies of it. The vendor's conversation lives in the vendor's own
|
|
12
|
+
* session store, so continuing it means naming that session; and our log has
|
|
13
|
+
* to say what happened in a shape a native model could take over from, because
|
|
14
|
+
* an owner who switches an instance from a subscription to an API key expects
|
|
15
|
+
* the conversation to carry on.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The vendor session a run continues, recorded on the run's final assistant
|
|
19
|
+
* entry. `fingerprint` names what the session was opened with that cannot be
|
|
20
|
+
* changed on resume — a vendor that fixes the tool list at session start is
|
|
21
|
+
* resumed only while the list is the same.
|
|
22
|
+
*/
|
|
23
|
+
export declare function sessionState(provider: string, session: string, fingerprint?: string): {
|
|
24
|
+
provider: string;
|
|
25
|
+
items: JsonValue[];
|
|
26
|
+
};
|
|
27
|
+
/** A stable name for a tool list, by what the model is shown of it. */
|
|
28
|
+
export declare function toolFingerprint(context: HarnessContext): string;
|
|
29
|
+
/**
|
|
30
|
+
* Where this activation starts: the vendor session to resume, and the words to
|
|
31
|
+
* open it with.
|
|
32
|
+
*
|
|
33
|
+
* A session is resumed only when the latest assistant entry in the log was
|
|
34
|
+
* written by this provider and names it. Any later assistant entry means
|
|
35
|
+
* another model spoke since, so the vendor's copy is missing part of the
|
|
36
|
+
* conversation and resuming it would answer from a past that is not the log's.
|
|
37
|
+
* Then the session starts fresh, opened with the conversation so far rendered
|
|
38
|
+
* as text: the vendor cannot be handed our messages as its own, and a summary
|
|
39
|
+
* of them is the honest substitute. `fresh` asks for that start whatever the
|
|
40
|
+
* log says, for a session the log names and the vendor no longer has; a
|
|
41
|
+
* `fingerprint` that differs from the recorded one asks for it too.
|
|
42
|
+
*/
|
|
43
|
+
export declare function opening(context: HarnessContext, provider: string, options?: {
|
|
44
|
+
fresh?: boolean;
|
|
45
|
+
fingerprint?: string;
|
|
46
|
+
}): {
|
|
47
|
+
resume?: string;
|
|
48
|
+
prompt: Content;
|
|
49
|
+
};
|
|
50
|
+
/** Inputs folded into this run by `drain` that the vendor has not been shown yet. */
|
|
51
|
+
export declare function arrivals(context: HarnessContext, shown: Set<number>): Content[];
|
|
52
|
+
/** Seqs of this run's inputs that `opening` already put in the prompt. */
|
|
53
|
+
export declare function openingInputs(context: HarnessContext): Set<number>;
|
|
54
|
+
/** A readable transcript. Tool output is cut, because the next turns can read again what matters. */
|
|
55
|
+
export declare function transcriptText(messages: readonly Message[]): string;
|
|
56
|
+
/** Text, with media named rather than dropped silently. */
|
|
57
|
+
export declare function described(content: Content): string;
|
|
58
|
+
/**
|
|
59
|
+
* Runs our tools for a vendor's loop, one call at a time, through the log.
|
|
60
|
+
*
|
|
61
|
+
* Each call is committed the way the native loop commits one — the assistant
|
|
62
|
+
* turn that asked for it with the text said before it, then `tool.started`,
|
|
63
|
+
* then `tool.finished` with the call's deliveries — so the log projects to a
|
|
64
|
+
* conversation any model can continue. Calls are serialised: a vendor may run
|
|
65
|
+
* several at once, and interleaving their entries would leave an assistant turn
|
|
66
|
+
* whose calls are answered out of order.
|
|
67
|
+
*/
|
|
68
|
+
export declare function createToolRunner(context: HarnessContext): {
|
|
69
|
+
/** A block of text the vendor said, since the last call or the start. */
|
|
70
|
+
say(text: string): void;
|
|
71
|
+
/** Usage to carry on the next committed assistant entry. */
|
|
72
|
+
spent(next: Usage): void;
|
|
73
|
+
/**
|
|
74
|
+
* A call the vendor made through one of its own account connectors, which
|
|
75
|
+
* ran in the vendor's cloud rather than through our executor. It is
|
|
76
|
+
* recorded as a note — what was said before it, then the call and what it
|
|
77
|
+
* returned — not as a tool call, because a model that takes the session
|
|
78
|
+
* over has no such tool, and a provider may refuse a history that calls a
|
|
79
|
+
* tool the request does not declare.
|
|
80
|
+
*/
|
|
81
|
+
note(call: {
|
|
82
|
+
name: string;
|
|
83
|
+
arguments: unknown;
|
|
84
|
+
result: string;
|
|
85
|
+
isError?: boolean;
|
|
86
|
+
}): Promise<void>;
|
|
87
|
+
run(call: ToolCall): Promise<ToolResult>;
|
|
88
|
+
/** The final assistant entry: what was said after the last call, and where the vendor's session is. */
|
|
89
|
+
finish(providerState: {
|
|
90
|
+
provider: string;
|
|
91
|
+
items: JsonValue[];
|
|
92
|
+
}, generation: {
|
|
93
|
+
id: string;
|
|
94
|
+
model?: string;
|
|
95
|
+
startedAt: string;
|
|
96
|
+
}): Promise<string>;
|
|
97
|
+
};
|
|
98
|
+
export declare function addUsage(a: Usage | undefined, b: Usage): Usage;
|