@operad-io/harness-codex 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +106 -2
- package/package.json +23 -4
- package/src/access.ts +192 -0
- package/src/index.ts +634 -0
- package/src/install.ts +125 -0
- package/src/log.ts +299 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The codex harness: one `agent` step that starts the user's `codex-acp` and
|
|
3
|
+
* talks ACP to it (docs/backlog/operad-harness.md decisions 2 and 10), plus the
|
|
4
|
+
* `codex:prompt` flow. The step has the params, result names and facts of
|
|
5
|
+
* `pi/agent` and `claude/agent`, so a flow changes harness by changing `use`.
|
|
6
|
+
* The ACP client is `AcpClient` of `@operad-io/harness-process`; `runAgent`
|
|
7
|
+
* owns the process, the wall time and the stall limit.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readProfile, secretValuesOf, summarizeCall, type AccessProfile } from "@operad-io/access-match";
|
|
11
|
+
import {
|
|
12
|
+
isRecord,
|
|
13
|
+
paramsObject,
|
|
14
|
+
defineFlow,
|
|
15
|
+
definePlugin,
|
|
16
|
+
type PluginStepResult,
|
|
17
|
+
type StepContext,
|
|
18
|
+
} from "@operad-io/engine";
|
|
19
|
+
import {
|
|
20
|
+
ALLOW_ALWAYS,
|
|
21
|
+
AcpClient,
|
|
22
|
+
accessWithAlwaysAllow,
|
|
23
|
+
alwaysAllowFromGrant,
|
|
24
|
+
appendAlwaysAllow,
|
|
25
|
+
askNote,
|
|
26
|
+
createCallAsker,
|
|
27
|
+
CONCURRENCY_SETTING,
|
|
28
|
+
deliverLine,
|
|
29
|
+
directoryError,
|
|
30
|
+
eventNote,
|
|
31
|
+
flagValue,
|
|
32
|
+
imageInputsOf,
|
|
33
|
+
JsonlLog,
|
|
34
|
+
mountedServersOf,
|
|
35
|
+
modelErrorOf,
|
|
36
|
+
modelLimit,
|
|
37
|
+
OPERAD_SERVER,
|
|
38
|
+
operadToolsOf,
|
|
39
|
+
optionalText,
|
|
40
|
+
parseStepFlags,
|
|
41
|
+
personStarted,
|
|
42
|
+
readAlwaysAllow,
|
|
43
|
+
readImage,
|
|
44
|
+
resultFor,
|
|
45
|
+
runAgent,
|
|
46
|
+
secs,
|
|
47
|
+
serverCommand,
|
|
48
|
+
standardUsage,
|
|
49
|
+
stringListParam,
|
|
50
|
+
systemClock,
|
|
51
|
+
text,
|
|
52
|
+
type AcpEnd,
|
|
53
|
+
type AcpError,
|
|
54
|
+
type AgentWorkerResult,
|
|
55
|
+
type CallAnswer,
|
|
56
|
+
type Clock,
|
|
57
|
+
type UsageSource,
|
|
58
|
+
} from "@operad-io/harness-process";
|
|
59
|
+
import { decideAccess, type JudgedCall } from "./access.ts";
|
|
60
|
+
import { codexCommand, commandOf, inspectCodex } from "./install.ts";
|
|
61
|
+
import { CodexLog } from "./log.ts";
|
|
62
|
+
|
|
63
|
+
/** How long an agent may run before the step stops it. */
|
|
64
|
+
export const DEFAULT_WALL_TIME_SECS = 3600;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* How long an agent may go without a new output line while no tool call is
|
|
68
|
+
* open. An image generation is a tool call that may be silent for minutes; it
|
|
69
|
+
* is not counted here, only against the wall time.
|
|
70
|
+
*/
|
|
71
|
+
export const DEFAULT_STALL_SECS = 600;
|
|
72
|
+
|
|
73
|
+
/** One run of the step may take this long; it is above every allowed wall time. */
|
|
74
|
+
export const STEP_TIMEOUT_SECS = 8 * 3600;
|
|
75
|
+
|
|
76
|
+
/** The longest wall time a run may ask for: the step timeout minus a margin. */
|
|
77
|
+
export const MAX_WALL_TIME_SECS = STEP_TIMEOUT_SECS - 300;
|
|
78
|
+
|
|
79
|
+
/** How long codex-acp has to answer `session/cancel` before the step ends it. */
|
|
80
|
+
export const CANCEL_GRACE_MS = 10_000;
|
|
81
|
+
|
|
82
|
+
/** The name the plugin goes by in usage and limit keys. */
|
|
83
|
+
const HARNESS = "codex";
|
|
84
|
+
|
|
85
|
+
/** The reasoning efforts Codex knows; codex-acp refuses one the chosen model does not support. */
|
|
86
|
+
export const EFFORT_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The codex-acp session mode a run uses. `workspace-write` is Codex's own
|
|
90
|
+
* sandbox with write access to the task's worktree (the session's `cwd`) and
|
|
91
|
+
* no access outside it. Its network is off, but Codex asks before it leaves
|
|
92
|
+
* the sandbox: a command that needs the network arrives as a permission
|
|
93
|
+
* request, and the access profile answers it (a request for the network is
|
|
94
|
+
* allowed once, since the task needs it). The other modes are not used:
|
|
95
|
+
* `read-only` cannot write the worktree, `agent` lets Codex's own reviewer
|
|
96
|
+
* answer instead of the profile, and `agent-full-access` turns the sandbox off.
|
|
97
|
+
*/
|
|
98
|
+
export const SESSION_MODE = "workspace-write";
|
|
99
|
+
|
|
100
|
+
/** The models and efforts a chat may pick with this agent: none; codex is a worker, not a chat harness. */
|
|
101
|
+
export const CODEX_MODELS = { list: [], default: null } as const;
|
|
102
|
+
export const CODEX_EFFORTS = { list: [], default: null, flag: "--effort" } as const;
|
|
103
|
+
|
|
104
|
+
/** The settings a config.json section may set for this plugin. */
|
|
105
|
+
export const PLUGIN_SETTINGS = {
|
|
106
|
+
type: "object" as const,
|
|
107
|
+
properties: {
|
|
108
|
+
model: {
|
|
109
|
+
type: "string" as const,
|
|
110
|
+
minLength: 1,
|
|
111
|
+
description: "The model name codex takes; unset uses Codex's own default.",
|
|
112
|
+
},
|
|
113
|
+
effort: {
|
|
114
|
+
type: "string" as const,
|
|
115
|
+
enum: EFFORT_LEVELS,
|
|
116
|
+
description: "The reasoning effort; unset uses Codex's own default.",
|
|
117
|
+
},
|
|
118
|
+
command: {
|
|
119
|
+
type: "array" as const,
|
|
120
|
+
minItems: 1,
|
|
121
|
+
items: { type: "string" as const, minLength: 1 },
|
|
122
|
+
description:
|
|
123
|
+
"The program and arguments that start codex-acp, such as [\"/opt/homebrew/bin/bun\", \"/Users/me/.bun/bin/codex-acp\"]. Unset runs the bun of PATH on the codex-acp of PATH.",
|
|
124
|
+
},
|
|
125
|
+
wallTimeSecs: {
|
|
126
|
+
type: "number" as const,
|
|
127
|
+
minimum: 1,
|
|
128
|
+
maximum: MAX_WALL_TIME_SECS,
|
|
129
|
+
default: DEFAULT_WALL_TIME_SECS,
|
|
130
|
+
description: "The longest one agent run may take.",
|
|
131
|
+
},
|
|
132
|
+
stallSecs: {
|
|
133
|
+
type: "number" as const,
|
|
134
|
+
minimum: 1,
|
|
135
|
+
default: DEFAULT_STALL_SECS,
|
|
136
|
+
description: "How long an agent may be silent while no tool call is open.",
|
|
137
|
+
},
|
|
138
|
+
concurrency: CONCURRENCY_SETTING,
|
|
139
|
+
},
|
|
140
|
+
additionalProperties: false as const,
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** The spelling of this harness's step `args`. */
|
|
144
|
+
const STEP_FLAGS = { levelFlag: "--effort", levels: EFFORT_LEVELS, modelHint: "<name>" } as const;
|
|
145
|
+
|
|
146
|
+
/** What a test injects. */
|
|
147
|
+
export interface CodexHarnessOptions {
|
|
148
|
+
readonly clock?: Clock | undefined;
|
|
149
|
+
/** Milliseconds now, for tool call start times and durations. */
|
|
150
|
+
readonly now?: (() => number) | undefined;
|
|
151
|
+
/** The Codex command `plugin check` asks about the login; defaults to the `codex` of PATH. */
|
|
152
|
+
readonly codex?: readonly string[] | undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The codex-acp error info of an error: a string, or the key of an object. */
|
|
156
|
+
function errorInfo(error: AcpError): string | undefined {
|
|
157
|
+
const data = error.data;
|
|
158
|
+
if (!isRecord(data)) return undefined;
|
|
159
|
+
const info = data["codexErrorInfo"];
|
|
160
|
+
if (typeof info === "string") return info;
|
|
161
|
+
if (isRecord(info)) return Object.keys(info)[0];
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function errorText(error: AcpError): string {
|
|
166
|
+
const data = error.data;
|
|
167
|
+
if (isRecord(data) && typeof data["message"] === "string" && data["message"].length > 0) return data["message"];
|
|
168
|
+
return error.message;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** How one ACP error ends the step: the reason, the message and, for a model that cannot serve, the model error. */
|
|
172
|
+
export interface Failure {
|
|
173
|
+
readonly reason: string;
|
|
174
|
+
readonly message: string;
|
|
175
|
+
readonly modelError?: { readonly kind: string };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Maps an error of codex-acp to the step's failure. An exhausted ChatGPT quota
|
|
180
|
+
* (`usageLimitExceeded`, a rate limit) is `usage_limit` and an unavailable
|
|
181
|
+
* model (a model the session refuses, an overloaded service) is `unavailable`,
|
|
182
|
+
* the model errors dev's `retry_wait` and pool's fallbacks act on.
|
|
183
|
+
*/
|
|
184
|
+
export function failureOf(end: Extract<AcpEnd, { kind: "error" }>, model: string | undefined): Failure {
|
|
185
|
+
const info = errorInfo(end.error);
|
|
186
|
+
const message = errorText(end.error);
|
|
187
|
+
if (end.error.code === -32000) {
|
|
188
|
+
return { reason: "not_logged_in", message: "Codex is not logged in; run `codex login` first" };
|
|
189
|
+
}
|
|
190
|
+
if (info === "usageLimitExceeded" || info === "rateLimitExceeded") {
|
|
191
|
+
return { reason: "model_error", message, modelError: { kind: "usage_limit" } };
|
|
192
|
+
}
|
|
193
|
+
if (info === "serverOverloaded") {
|
|
194
|
+
return { reason: "model_error", message, modelError: { kind: "unavailable" } };
|
|
195
|
+
}
|
|
196
|
+
if (end.stage === "config") {
|
|
197
|
+
if (end.configId === "model") {
|
|
198
|
+
return {
|
|
199
|
+
reason: "model_error",
|
|
200
|
+
message: `codex-acp does not offer the model ${model ?? "asked for"}: ${message}`,
|
|
201
|
+
modelError: { kind: "unavailable" },
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
if (end.configId === "reasoning_effort") {
|
|
205
|
+
return { reason: "invalid_args", message: `codex-acp refused the reasoning effort: ${message}` };
|
|
206
|
+
}
|
|
207
|
+
return { reason: "config", message: `codex-acp refused a session setting (${end.configId ?? "unknown"}): ${message}` };
|
|
208
|
+
}
|
|
209
|
+
if (end.stage === "prompt") {
|
|
210
|
+
const mapped = modelErrorOf(message);
|
|
211
|
+
return {
|
|
212
|
+
reason: "model_error",
|
|
213
|
+
message,
|
|
214
|
+
modelError: { kind: String(mapped["kind"]) },
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
if (end.stage === "session" && /resume|load/i.test(message)) {
|
|
218
|
+
return { reason: "session_missing", message };
|
|
219
|
+
}
|
|
220
|
+
return { reason: "protocol", message: `codex-acp failed at ${end.stage}: ${message}` };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Creates the codex harness plugin. */
|
|
224
|
+
export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
|
|
225
|
+
const clock = options.clock ?? systemClock;
|
|
226
|
+
const now = options.now ?? Date.now;
|
|
227
|
+
|
|
228
|
+
const promptFlow = defineFlow({
|
|
229
|
+
name: "codex:prompt",
|
|
230
|
+
entry: "agent",
|
|
231
|
+
steps: [
|
|
232
|
+
{
|
|
233
|
+
id: "agent",
|
|
234
|
+
kind: "plugin",
|
|
235
|
+
params: { use: "codex/agent", params: {} },
|
|
236
|
+
replay: "unsafe",
|
|
237
|
+
next: { done: "done", failed: "failed", interrupted: "cancelled", waiting: "person" },
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
// A question about a call ran out of grace. The answer sends the run
|
|
241
|
+
// back to the agent, which continues the session with it.
|
|
242
|
+
id: "person",
|
|
243
|
+
kind: "wait_person",
|
|
244
|
+
params: {
|
|
245
|
+
prompt: "The agent asked about a call.",
|
|
246
|
+
choices: ["allow_once", "reject_once"],
|
|
247
|
+
lateChoices: ["allow_always"],
|
|
248
|
+
},
|
|
249
|
+
replay: "safe",
|
|
250
|
+
next: {
|
|
251
|
+
allow_once: "agent",
|
|
252
|
+
allow_always: "agent",
|
|
253
|
+
reject_once: "agent",
|
|
254
|
+
interrupted: "cancelled",
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
{ id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
|
|
258
|
+
{ id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
|
|
259
|
+
{ id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
|
|
260
|
+
],
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
return definePlugin({
|
|
264
|
+
name: HARNESS,
|
|
265
|
+
kind: "harness",
|
|
266
|
+
version: "0.0.0",
|
|
267
|
+
models: CODEX_MODELS,
|
|
268
|
+
efforts: CODEX_EFFORTS,
|
|
269
|
+
settings: PLUGIN_SETTINGS,
|
|
270
|
+
steps: [
|
|
271
|
+
{
|
|
272
|
+
name: "agent",
|
|
273
|
+
// A question's answer comes back as `resumeSession` and `askAnswer`.
|
|
274
|
+
resumable: true,
|
|
275
|
+
// `waiting`: a question about a call was not answered within the grace.
|
|
276
|
+
results: ["done", "failed", "interrupted", "waiting"],
|
|
277
|
+
// Applied to the calls codex-acp asks permission for. Codex's own
|
|
278
|
+
// sandbox runs the calls inside it without asking; those are bounded
|
|
279
|
+
// by the sandbox, not by these rules.
|
|
280
|
+
enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
|
|
281
|
+
timeoutSecs: STEP_TIMEOUT_SECS,
|
|
282
|
+
// The model the step uses: its `--model` argument, else the setting.
|
|
283
|
+
limit: modelLimit(HARNESS, (params, settings) => {
|
|
284
|
+
const fromArgs = isRecord(params) ? flagValue(params.args, "--model") : undefined;
|
|
285
|
+
const model = fromArgs ?? settings.model;
|
|
286
|
+
return typeof model === "string" && model.length > 0 ? model : undefined;
|
|
287
|
+
}),
|
|
288
|
+
async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
|
|
289
|
+
const at = "codex/agent";
|
|
290
|
+
const input = paramsObject(params, at);
|
|
291
|
+
const flow = isRecord(ctx.params) ? ctx.params : {};
|
|
292
|
+
|
|
293
|
+
const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
|
|
294
|
+
const note = eventNote(ctx.trigger);
|
|
295
|
+
const rawAskAnswer = input.askAnswer ?? flow.askAnswer;
|
|
296
|
+
const promptText = [prompt, note, askNote(rawAskAnswer)]
|
|
297
|
+
.filter((part): part is string => part !== undefined)
|
|
298
|
+
.join("\n\n");
|
|
299
|
+
const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
|
|
300
|
+
const rawArgs = input.args === undefined ? flow.args : input.args;
|
|
301
|
+
const flags = parseStepFlags(stringListParam(rawArgs, `${at}: params.args`), STEP_FLAGS);
|
|
302
|
+
const settingModel = typeof ctx.settings.model === "string" ? ctx.settings.model : undefined;
|
|
303
|
+
const knownModel =
|
|
304
|
+
typeof flags === "string" ? (flagValue(rawArgs, "--model") ?? settingModel) : (flags.model ?? settingModel);
|
|
305
|
+
// The cost of a subscription login is unknown, never 0.
|
|
306
|
+
const early: UsageSource = { harness: HARNESS, model: knownModel ?? null };
|
|
307
|
+
const refuse = async (reason: string, message: string): Promise<PluginStepResult> => {
|
|
308
|
+
const log = await ctx.logger.write(message);
|
|
309
|
+
return {
|
|
310
|
+
result: "failed",
|
|
311
|
+
data: {
|
|
312
|
+
reason,
|
|
313
|
+
message,
|
|
314
|
+
exitCode: null,
|
|
315
|
+
signal: null,
|
|
316
|
+
sessionId: null,
|
|
317
|
+
finalMessage: null,
|
|
318
|
+
usage: standardUsage(early, undefined, null),
|
|
319
|
+
log,
|
|
320
|
+
durationMs: 0,
|
|
321
|
+
stderr: [message],
|
|
322
|
+
imageGenCalls: 0,
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
};
|
|
326
|
+
if (typeof flags === "string") return refuse("invalid_args", `${at}: ${flags}`);
|
|
327
|
+
|
|
328
|
+
const resumeSession = optionalText(input.resumeSession ?? flow.resumeSession, `${at}: params.resumeSession`);
|
|
329
|
+
const wallTimeSecs = secs(
|
|
330
|
+
input.wallTimeSecs ?? ctx.settings.wallTimeSecs ?? DEFAULT_WALL_TIME_SECS,
|
|
331
|
+
`${at}: params.wallTimeSecs`,
|
|
332
|
+
);
|
|
333
|
+
if (wallTimeSecs > MAX_WALL_TIME_SECS) {
|
|
334
|
+
throw new Error(`${at}: params.wallTimeSecs: must be at most ${MAX_WALL_TIME_SECS}`);
|
|
335
|
+
}
|
|
336
|
+
const stallSecs = secs(
|
|
337
|
+
input.stallSecs ?? ctx.settings.stallSecs ?? DEFAULT_STALL_SECS,
|
|
338
|
+
`${at}: params.stallSecs`,
|
|
339
|
+
);
|
|
340
|
+
const model = flags.model ?? optionalText(ctx.settings.model, `${at}: settings.model`);
|
|
341
|
+
const effort = flags.level ?? optionalText(ctx.settings.effort, `${at}: settings.effort`);
|
|
342
|
+
|
|
343
|
+
const cwdProblem = await directoryError(cwd);
|
|
344
|
+
if (cwdProblem !== undefined) return refuse("cwd", cwdProblem);
|
|
345
|
+
|
|
346
|
+
let command: readonly string[];
|
|
347
|
+
try {
|
|
348
|
+
command = commandOf(ctx.settings.command);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
return refuse("missing", error instanceof Error ? error.message : String(error));
|
|
351
|
+
}
|
|
352
|
+
const program = command[0] ?? "";
|
|
353
|
+
|
|
354
|
+
const operadTools = operadToolsOf(input.operadTools ?? flow.operadTools);
|
|
355
|
+
const mounted = mountedServersOf(input.mcpServers ?? flow.mcpServers);
|
|
356
|
+
const mcpServers: Record<string, unknown>[] = [];
|
|
357
|
+
if (operadTools !== undefined) {
|
|
358
|
+
const server = serverCommand(operadTools);
|
|
359
|
+
mcpServers.push({
|
|
360
|
+
name: OPERAD_SERVER,
|
|
361
|
+
command: server.command,
|
|
362
|
+
args: [...server.args],
|
|
363
|
+
env: [{ name: "OPERAD_HOME", value: operadTools.home }],
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
for (const [name, server] of Object.entries(mounted ?? {})) {
|
|
367
|
+
mcpServers.push({ name, command: server.command, args: [...server.args], env: [] });
|
|
368
|
+
}
|
|
369
|
+
const images = imageInputsOf(input.images ?? flow.images);
|
|
370
|
+
const imageBlocks: Record<string, unknown>[] = [];
|
|
371
|
+
for (const image of images) {
|
|
372
|
+
const read = await readImage(image);
|
|
373
|
+
imageBlocks.push({ type: "image", data: read.data, mimeType: read.mediaType });
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const storeSecrets = await secretValuesOf(ctx.secrets);
|
|
377
|
+
const allowAlways = personStarted(ctx.trigger);
|
|
378
|
+
if (allowAlways && isRecord(rawAskAnswer) && rawAskAnswer["choice"] === ALLOW_ALWAYS) {
|
|
379
|
+
const entry = alwaysAllowFromGrant(ctx.access, cwd);
|
|
380
|
+
if (entry !== undefined) {
|
|
381
|
+
try {
|
|
382
|
+
await appendAlwaysAllow(ctx.home, entry);
|
|
383
|
+
} catch (error) {
|
|
384
|
+
await ctx.logger.write(
|
|
385
|
+
`allow_always could not be written to the user access file: ${String(error)}; this call runs once`,
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
let runAccess = accessWithAlwaysAllow(ctx.access, [], false);
|
|
391
|
+
if (allowAlways) {
|
|
392
|
+
const user = await readAlwaysAllow(ctx.home);
|
|
393
|
+
if (user.problem !== undefined) await ctx.logger.write(user.problem);
|
|
394
|
+
runAccess = accessWithAlwaysAllow(ctx.access, user.entries, true);
|
|
395
|
+
}
|
|
396
|
+
const read = readProfile(runAccess ?? {});
|
|
397
|
+
const profile: AccessProfile = read.ok ? read.profile : {};
|
|
398
|
+
|
|
399
|
+
const started = Date.now();
|
|
400
|
+
const jsonl = new JsonlLog(ctx.logger, clock);
|
|
401
|
+
const stopper = new AbortController();
|
|
402
|
+
const endRun = (): void => stopper.abort();
|
|
403
|
+
|
|
404
|
+
const asker = createCallAsker({
|
|
405
|
+
ask: (request) => ctx.ask(request),
|
|
406
|
+
onStop: endRun,
|
|
407
|
+
secrets: storeSecrets,
|
|
408
|
+
...(allowAlways ? { alwaysAllow: { home: ctx.home, cwd } } : {}),
|
|
409
|
+
onLog: (message) => {
|
|
410
|
+
void ctx.logger.write(message);
|
|
411
|
+
},
|
|
412
|
+
});
|
|
413
|
+
let askId = 0;
|
|
414
|
+
|
|
415
|
+
// A full buffer makes the line reader wait for the disk.
|
|
416
|
+
let writing: Promise<void> | undefined;
|
|
417
|
+
const writeLine = (line: string): void => {
|
|
418
|
+
const pending = jsonl.push(line);
|
|
419
|
+
if (pending !== undefined) writing = pending;
|
|
420
|
+
deliverLine(ctx.receiver, line, storeSecrets);
|
|
421
|
+
};
|
|
422
|
+
let client: AcpClient | undefined;
|
|
423
|
+
const log = new CodexLog({
|
|
424
|
+
write: writeLine,
|
|
425
|
+
now,
|
|
426
|
+
cwd,
|
|
427
|
+
profile,
|
|
428
|
+
secrets: storeSecrets,
|
|
429
|
+
active: () => client?.prompting === true,
|
|
430
|
+
});
|
|
431
|
+
|
|
432
|
+
const shown = (call: JudgedCall): string =>
|
|
433
|
+
summarizeCall({}, call.tool, call.input, cwd, { secrets: storeSecrets, keepLines: true }) ?? call.tool;
|
|
434
|
+
|
|
435
|
+
const ask = (question: {
|
|
436
|
+
readonly kind: "command" | "path";
|
|
437
|
+
readonly value: string;
|
|
438
|
+
readonly tool?: string;
|
|
439
|
+
readonly shown: string;
|
|
440
|
+
}): Promise<CallAnswer> =>
|
|
441
|
+
new Promise<CallAnswer>((resolve) => {
|
|
442
|
+
askId += 1;
|
|
443
|
+
const line = JSON.stringify({
|
|
444
|
+
type: "ask_call",
|
|
445
|
+
id: askId,
|
|
446
|
+
kind: question.kind,
|
|
447
|
+
value: question.value,
|
|
448
|
+
...(question.tool === undefined ? {} : { tool: question.tool }),
|
|
449
|
+
shown: question.shown,
|
|
450
|
+
session: client?.sessionId ?? null,
|
|
451
|
+
});
|
|
452
|
+
void asker.handle(line, (reply) => {
|
|
453
|
+
try {
|
|
454
|
+
const ack: unknown = JSON.parse(reply);
|
|
455
|
+
if (isRecord(ack) && (ack["decision"] === "allow" || ack["decision"] === "deny" || ack["decision"] === "stop")) {
|
|
456
|
+
resolve({
|
|
457
|
+
decision: ack["decision"],
|
|
458
|
+
...(typeof ack["reason"] === "string" ? { reason: ack["reason"] } : {}),
|
|
459
|
+
});
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
} catch {
|
|
463
|
+
// fall through to a refusal
|
|
464
|
+
}
|
|
465
|
+
resolve({ decision: "deny", reason: "the question could not be asked" });
|
|
466
|
+
});
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
const acp = new AcpClient({
|
|
470
|
+
cwd,
|
|
471
|
+
prompt: [{ type: "text", text: promptText }, ...imageBlocks],
|
|
472
|
+
...(resumeSession === undefined ? {} : { resumeSession }),
|
|
473
|
+
config: [
|
|
474
|
+
{ configId: "mode", value: SESSION_MODE },
|
|
475
|
+
...(model === undefined ? [] : [{ configId: "model", value: model }]),
|
|
476
|
+
...(effort === undefined ? [] : [{ configId: "reasoning_effort", value: effort }]),
|
|
477
|
+
],
|
|
478
|
+
...(mcpServers.length === 0 ? {} : { mcpServers }),
|
|
479
|
+
clientName: "operad",
|
|
480
|
+
onUpdate: (update) => log.handle(update),
|
|
481
|
+
async onPermission(request) {
|
|
482
|
+
const decision = await decideAccess(profile, request.toolCall, cwd, {
|
|
483
|
+
useGrant: (waitId) => ctx.useGrant(waitId),
|
|
484
|
+
ask,
|
|
485
|
+
shown,
|
|
486
|
+
});
|
|
487
|
+
if (!decision.allow) log.blocked(request.toolCall);
|
|
488
|
+
return decision.allow;
|
|
489
|
+
},
|
|
490
|
+
});
|
|
491
|
+
client = acp;
|
|
492
|
+
|
|
493
|
+
const state: { end: AcpEnd | undefined } = { end: undefined };
|
|
494
|
+
void acp.ended.then((value) => {
|
|
495
|
+
state.end = value;
|
|
496
|
+
endRun();
|
|
497
|
+
});
|
|
498
|
+
|
|
499
|
+
// A cancel asks codex-acp to stop the prompt and waits for its
|
|
500
|
+
// answer; an agent that does not answer within the grace is ended.
|
|
501
|
+
let graceTimer: unknown;
|
|
502
|
+
const onAbort = (): void => {
|
|
503
|
+
if (acp.finished) return;
|
|
504
|
+
if (!acp.cancel()) {
|
|
505
|
+
endRun();
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
graceTimer = clock.setTimeout(endRun, CANCEL_GRACE_MS);
|
|
509
|
+
};
|
|
510
|
+
if (ctx.signal.aborted) endRun();
|
|
511
|
+
else ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
512
|
+
|
|
513
|
+
const outcome = await runAgent({
|
|
514
|
+
command: program,
|
|
515
|
+
args: command.slice(1),
|
|
516
|
+
cwd,
|
|
517
|
+
stdin: acp.first,
|
|
518
|
+
interactive: true,
|
|
519
|
+
wallMs: wallTimeSecs * 1000,
|
|
520
|
+
stallMs: stallSecs * 1000,
|
|
521
|
+
signal: stopper.signal,
|
|
522
|
+
clock,
|
|
523
|
+
toolEvent: (line) => log.toolEvent(line),
|
|
524
|
+
onLine(line, reply) {
|
|
525
|
+
acp.handleLine(line, reply);
|
|
526
|
+
return writing;
|
|
527
|
+
},
|
|
528
|
+
});
|
|
529
|
+
ctx.signal.removeEventListener("abort", onAbort);
|
|
530
|
+
if (graceTimer !== undefined) clock.clearTimeout(graceTimer);
|
|
531
|
+
|
|
532
|
+
// The grace passed with a question open: the program was ended on
|
|
533
|
+
// purpose. The kernel turns this into the result `waiting`, and the
|
|
534
|
+
// answer comes back with the session and a one-time grant.
|
|
535
|
+
const unanswered = asker.stopped();
|
|
536
|
+
if (unanswered !== undefined && !ctx.signal.aborted) {
|
|
537
|
+
await jsonl.end();
|
|
538
|
+
throw unanswered.error;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const sessionId = acp.sessionId ?? resumeSession ?? null;
|
|
542
|
+
let result: AgentWorkerResult | undefined;
|
|
543
|
+
const end = state.end;
|
|
544
|
+
if (end !== undefined) {
|
|
545
|
+
if (end.kind === "stopped") {
|
|
546
|
+
log.finish(end.stopReason, end.usage);
|
|
547
|
+
const usage = end.usage;
|
|
548
|
+
const counts = {
|
|
549
|
+
input: usage?.inputTokens,
|
|
550
|
+
output: usage?.outputTokens,
|
|
551
|
+
cache_read: usage?.cachedReadTokens ?? undefined,
|
|
552
|
+
cache_write: usage?.cachedWriteTokens ?? undefined,
|
|
553
|
+
};
|
|
554
|
+
const closing = log.finalText.trim().length > 0 ? log.finalText : null;
|
|
555
|
+
const base = { type: "result" as const, sessionId: end.sessionId, usage: counts, cost: null, finalMessage: closing, model: model ?? null };
|
|
556
|
+
if (end.stopReason === "cancelled") result = { ...base, result: "cancelled" };
|
|
557
|
+
else if (end.stopReason === "end_turn") result = { ...base, result: "done" };
|
|
558
|
+
else {
|
|
559
|
+
result = {
|
|
560
|
+
...base,
|
|
561
|
+
result: "failed",
|
|
562
|
+
reason: end.stopReason === "refusal" ? "refusal" : "stop_reason",
|
|
563
|
+
message: `codex stopped the prompt: ${end.stopReason}`,
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
} else {
|
|
567
|
+
const failed = failureOf(end, model);
|
|
568
|
+
result = {
|
|
569
|
+
type: "result",
|
|
570
|
+
result: "failed",
|
|
571
|
+
sessionId: end.sessionId ?? resumeSession ?? null,
|
|
572
|
+
usage: {},
|
|
573
|
+
cost: null,
|
|
574
|
+
finalMessage: null,
|
|
575
|
+
model: model ?? null,
|
|
576
|
+
reason: failed.reason,
|
|
577
|
+
message: failed.message,
|
|
578
|
+
...(failed.modelError === undefined ? {} : { modelError: failed.modelError }),
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
writeLine(
|
|
582
|
+
JSON.stringify({
|
|
583
|
+
type: "result",
|
|
584
|
+
result: result.result,
|
|
585
|
+
sessionId,
|
|
586
|
+
usage: result.usage,
|
|
587
|
+
cost: null,
|
|
588
|
+
imageGenCalls: log.imageGenerations,
|
|
589
|
+
}),
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
await jsonl.end();
|
|
593
|
+
|
|
594
|
+
// The run was ended on purpose once codex-acp had answered: the
|
|
595
|
+
// signal that did it is not the agent's.
|
|
596
|
+
const settled =
|
|
597
|
+
end === undefined ? outcome : { ...outcome, exitCode: 0, signal: null, cancelled: false };
|
|
598
|
+
const stepResult = resultFor(
|
|
599
|
+
{ harness: HARNESS, model: model ?? null },
|
|
600
|
+
settled,
|
|
601
|
+
result,
|
|
602
|
+
ctx.logger.path,
|
|
603
|
+
Date.now() - started,
|
|
604
|
+
{ wallTimeSecs, stallSecs },
|
|
605
|
+
program,
|
|
606
|
+
);
|
|
607
|
+
return {
|
|
608
|
+
...stepResult,
|
|
609
|
+
data: { ...(stepResult.data ?? {}), imageGenCalls: log.imageGenerations, stopReason: end?.kind === "stopped" ? end.stopReason : null },
|
|
610
|
+
};
|
|
611
|
+
},
|
|
612
|
+
},
|
|
613
|
+
],
|
|
614
|
+
flows: [promptFlow],
|
|
615
|
+
async check(ctx) {
|
|
616
|
+
let command: readonly string[];
|
|
617
|
+
try {
|
|
618
|
+
command = commandOf(ctx.settings.command);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
throw new Error(error instanceof Error ? error.message : String(error));
|
|
621
|
+
}
|
|
622
|
+
const bun = Bun.which("bun") ?? process.execPath;
|
|
623
|
+
const codex = options.codex ?? codexCommand(bun);
|
|
624
|
+
const install = inspectCodex(command, codex);
|
|
625
|
+
return (
|
|
626
|
+
`codex-acp ${install.acpVersion} (${command.join(" ")}); ` +
|
|
627
|
+
`codex ${install.codexVersion ?? "not found on PATH"}; ` +
|
|
628
|
+
`login ${install.login ?? "unknown"}`
|
|
629
|
+
);
|
|
630
|
+
},
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export default createCodexHarnessPlugin();
|