@operad-io/harness-codex 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @operad-io/harness-codex
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The codex harness.** Starts your own `codex-acp` and talks ACP to it, to run a prompt as one agent step.
4
+
5
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
6
+
7
+ ## Documentation
8
+
9
+ - User guide: [docs/user/dev.md](https://github.com/operad-io/operad/blob/main/docs/user/dev.md)
10
+ - Website: <https://operad.io>
11
+ - Developer reference: `REFERENCE.md` in this directory
12
+
13
+ MIT licensed.
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@operad-io/harness-codex",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@operad-io/access-match": "0.1.0",
10
+ "@operad-io/engine": "0.1.0",
11
+ "@operad-io/harness-process": "0.1.0"
12
+ },
13
+ "description": "operad: the codex harness, a client of the codex-acp adapter",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/operad-io/operad.git",
17
+ "directory": "packages/harness/codex"
18
+ },
19
+ "license": "MIT",
20
+ "files": [
21
+ "src",
22
+ "README.md",
23
+ "LICENSE"
24
+ ]
25
+ }
package/src/access.ts ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The access profile applied to the calls codex asks permission for
3
+ * (ADR 0022 D4).
4
+ *
5
+ * codex-acp sends `session/request_permission` for a command that leaves the
6
+ * sandbox, a file change and a network request. The request describes the call
7
+ * by an ACP tool `kind`, `rawInput` and `locations`; `@operad-io/access-match`
8
+ * judges calls by lower-case tool names and the input fields `command` and
9
+ * `path`. `translate` is the one place that maps the two.
10
+ */
11
+
12
+ import { findGrant, match, type AccessProfile } from "@operad-io/access-match";
13
+ import { OPERAD_SERVER, type CallAnswer, type CallQuestion } from "@operad-io/harness-process";
14
+ import { isRecord } from "@operad-io/engine";
15
+
16
+ /** One call in the words `access-match` takes. */
17
+ export interface JudgedCall {
18
+ readonly tool: "bash" | "read" | "edit" | "grep";
19
+ readonly input: Record<string, unknown>;
20
+ }
21
+
22
+ export type Translated =
23
+ | { readonly kind: "calls"; readonly calls: readonly JudgedCall[] }
24
+ | { readonly kind: "missing"; readonly field: string }
25
+ | { readonly kind: "inert" }
26
+ | { readonly kind: "unmapped" };
27
+
28
+ function locations(toolCall: Readonly<Record<string, unknown>>): readonly string[] {
29
+ const list = toolCall["locations"];
30
+ if (!Array.isArray(list)) return [];
31
+ const paths: string[] = [];
32
+ for (const item of list) {
33
+ if (isRecord(item) && typeof item["path"] === "string" && item["path"].length > 0) paths.push(item["path"]);
34
+ }
35
+ return paths;
36
+ }
37
+
38
+ /** The command of an execute call: a string, or the words of an argv. */
39
+ export function commandOf(rawInput: unknown): string | undefined {
40
+ if (!isRecord(rawInput)) return undefined;
41
+ const command = rawInput["command"];
42
+ if (typeof command === "string" && command.trim().length > 0) return command;
43
+ if (Array.isArray(command) && command.length > 0 && command.every((word) => typeof word === "string")) {
44
+ return command.join(" ");
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ /**
50
+ * The calls the profile must judge for one permission request:
51
+ *
52
+ * - `execute` with a command is a `bash` call, even when it needs the network;
53
+ * with a `url` and no command it is a network request, which no rule names,
54
+ * so it is inert (the task needs the network and Codex's own sandbox asks
55
+ * before it leaves it);
56
+ * - `edit`, `delete` and `move` judge each path they touch as an `edit`;
57
+ * - `read` and `search` judge the path they name, if any;
58
+ * - `fetch` and `think`, and a request of operad's own MCP server, are inert.
59
+ *
60
+ * Anything else (an MCP tool of another server, a mode switch, extra sandbox
61
+ * permissions) is unmapped: it is allowed only when the profile has no
62
+ * `denyPaths` and no `denyCommands`, since a rule that could match it cannot
63
+ * be checked.
64
+ */
65
+ export function translate(toolCall: Readonly<Record<string, unknown>>): Translated {
66
+ const kind = toolCall["kind"];
67
+ const rawInput = toolCall["rawInput"];
68
+ if (isRecord(rawInput) && rawInput["serverName"] === OPERAD_SERVER) return { kind: "inert" };
69
+ switch (kind) {
70
+ case "execute": {
71
+ if (isRecord(rawInput) && rawInput["serverName"] !== undefined) return { kind: "unmapped" };
72
+ const command = commandOf(rawInput);
73
+ // A command that needs the network is judged as the command it is.
74
+ if (command !== undefined) return { kind: "calls", calls: [{ tool: "bash", input: { command } }] };
75
+ if (isRecord(rawInput) && typeof rawInput["url"] === "string") return { kind: "inert" };
76
+ return { kind: "missing", field: "command" };
77
+ }
78
+ case "edit":
79
+ case "delete":
80
+ case "move": {
81
+ const paths = locations(toolCall);
82
+ return paths.length === 0
83
+ ? { kind: "missing", field: "path" }
84
+ : { kind: "calls", calls: paths.map((path) => ({ tool: "edit" as const, input: { path } })) };
85
+ }
86
+ case "read":
87
+ case "search": {
88
+ const paths = locations(toolCall);
89
+ const tool = kind === "read" ? ("read" as const) : ("grep" as const);
90
+ return paths.length === 0
91
+ ? kind === "read"
92
+ ? { kind: "missing", field: "path" }
93
+ : { kind: "calls", calls: [{ tool, input: {} }] }
94
+ : { kind: "calls", calls: paths.map((path) => ({ tool, input: { path } })) };
95
+ }
96
+ case "fetch":
97
+ case "think":
98
+ return { kind: "inert" };
99
+ default:
100
+ return { kind: "unmapped" };
101
+ }
102
+ }
103
+
104
+ /** Whether the profile has a rule that an unchecked call could break. */
105
+ export function hasRules(profile: AccessProfile): boolean {
106
+ return (profile.denyPaths ?? []).length > 0 || (profile.denyCommands ?? []).length > 0;
107
+ }
108
+
109
+ export type AccessDecision =
110
+ | { readonly allow: true }
111
+ | {
112
+ readonly allow: false;
113
+ readonly reason: string;
114
+ /** The wait for a person ended; the run is about to be ended and holds the call. */
115
+ readonly stop?: true;
116
+ };
117
+
118
+ /** What the step gives the decision: the host's one-time permission use and a question to a person. */
119
+ export interface Deciders {
120
+ /** Asks the host to use up a one-time permission; without it no grant applies. */
121
+ readonly useGrant?: ((waitId: string) => Promise<boolean>) | undefined;
122
+ /** Asks a person about a call the profile says must ask; without it such a call is refused. */
123
+ readonly ask?: ((question: CallQuestion & { readonly shown: string }) => Promise<CallAnswer>) | undefined;
124
+ /** What a person reads for one call. */
125
+ readonly shown: (call: JudgedCall) => string;
126
+ }
127
+
128
+ /**
129
+ * Whether the call a permission request describes may run, by the same rules
130
+ * the other harnesses apply: a deny wins; a one-time permission covers one
131
+ * exact refused call and is used up through the host before it lets the call
132
+ * through; a call that must ask goes to a person.
133
+ */
134
+ export async function decideAccess(
135
+ profile: AccessProfile,
136
+ toolCall: Readonly<Record<string, unknown>>,
137
+ cwd: string,
138
+ deciders: Deciders,
139
+ ): Promise<AccessDecision> {
140
+ const translated = translate(toolCall);
141
+ if (translated.kind === "inert") return { allow: true };
142
+ if (translated.kind === "unmapped") {
143
+ if (!hasRules(profile)) return { allow: true };
144
+ return {
145
+ allow: false,
146
+ reason: "this call is not one the access profile can check; it is refused while denyPaths or denyCommands is set",
147
+ };
148
+ }
149
+ if (translated.kind === "missing") {
150
+ if (!hasRules(profile)) return { allow: true };
151
+ return {
152
+ allow: false,
153
+ reason: `this call has no ${translated.field}; it is refused while denyPaths or denyCommands is set`,
154
+ };
155
+ }
156
+ for (const judged of translated.calls) {
157
+ const call = { tool: judged.tool, input: judged.input, cwd };
158
+ const verdict = match(profile, call);
159
+ if (verdict.allow) continue;
160
+ // A one-time permission covers one exact call that would be refused. The
161
+ // host writes the fact before it answers, so a crash after it cannot give
162
+ // the permission twice.
163
+ const grant = findGrant(profile, call);
164
+ if (grant !== undefined && deciders.useGrant !== undefined) {
165
+ let used = false;
166
+ try {
167
+ used = await deciders.useGrant(grant.waitId);
168
+ } catch {
169
+ used = false;
170
+ }
171
+ if (used) continue;
172
+ }
173
+ if (verdict.ask === true && deciders.ask !== undefined) {
174
+ let answer: CallAnswer;
175
+ try {
176
+ answer = await deciders.ask({
177
+ kind: verdict.kind,
178
+ value: verdict.value,
179
+ ...(verdict.tool === undefined ? {} : { tool: verdict.tool }),
180
+ shown: deciders.shown(judged),
181
+ });
182
+ } catch {
183
+ answer = { decision: "deny", reason: "the question could not be asked" };
184
+ }
185
+ if (answer.decision === "allow") continue;
186
+ if (answer.decision === "stop") return { allow: false, reason: "waiting for an answer", stop: true };
187
+ return { allow: false, reason: `${verdict.reason}; ${answer.reason ?? "a person refused it"}` };
188
+ }
189
+ return { allow: false, reason: verdict.reason };
190
+ }
191
+ return { allow: true };
192
+ }
package/src/index.ts ADDED
@@ -0,0 +1,635 @@
1
+ /**
2
+ * The codex harness: one `agent` step that starts the user's `codex-acp` and
3
+ * talks ACP to it (ADR 0022 D2, D8), 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 pkg from "../package.json" with { type: "json" };
11
+ import { readProfile, secretValuesOf, summarizeCall, type AccessProfile } from "@operad-io/access-match";
12
+ import {
13
+ isRecord,
14
+ paramsObject,
15
+ defineFlow,
16
+ definePlugin,
17
+ type PluginStepResult,
18
+ type StepContext,
19
+ } from "@operad-io/engine";
20
+ import {
21
+ ALLOW_ALWAYS,
22
+ AcpClient,
23
+ accessWithAlwaysAllow,
24
+ alwaysAllowFromGrant,
25
+ appendAlwaysAllow,
26
+ askNote,
27
+ createCallAsker,
28
+ CONCURRENCY_SETTING,
29
+ deliverLine,
30
+ directoryError,
31
+ eventNote,
32
+ flagValue,
33
+ imageInputsOf,
34
+ JsonlLog,
35
+ mountedServersOf,
36
+ modelErrorOf,
37
+ modelLimit,
38
+ OPERAD_SERVER,
39
+ operadToolsOf,
40
+ optionalText,
41
+ parseStepFlags,
42
+ personStarted,
43
+ readAlwaysAllow,
44
+ readImage,
45
+ resultFor,
46
+ runAgent,
47
+ secs,
48
+ serverCommand,
49
+ standardUsage,
50
+ stringListParam,
51
+ systemClock,
52
+ text,
53
+ type AcpEnd,
54
+ type AcpError,
55
+ type AgentWorkerResult,
56
+ type CallAnswer,
57
+ type Clock,
58
+ type UsageSource,
59
+ } from "@operad-io/harness-process";
60
+ import { decideAccess, type JudgedCall } from "./access.ts";
61
+ import { codexCommand, commandOf, inspectCodex } from "./install.ts";
62
+ import { CodexLog } from "./log.ts";
63
+
64
+ /** How long an agent may run before the step stops it. */
65
+ export const DEFAULT_WALL_TIME_SECS = 3600;
66
+
67
+ /**
68
+ * How long an agent may go without a new output line while no tool call is
69
+ * open. An image generation is a tool call that may be silent for minutes; it
70
+ * is not counted here, only against the wall time.
71
+ */
72
+ export const DEFAULT_STALL_SECS = 600;
73
+
74
+ /** One run of the step may take this long; it is above every allowed wall time. */
75
+ export const STEP_TIMEOUT_SECS = 8 * 3600;
76
+
77
+ /** The longest wall time a run may ask for: the step timeout minus a margin. */
78
+ export const MAX_WALL_TIME_SECS = STEP_TIMEOUT_SECS - 300;
79
+
80
+ /** How long codex-acp has to answer `session/cancel` before the step ends it. */
81
+ export const CANCEL_GRACE_MS = 10_000;
82
+
83
+ /** The name the plugin goes by in usage and limit keys. */
84
+ const HARNESS = "codex";
85
+
86
+ /** The reasoning efforts Codex knows; codex-acp refuses one the chosen model does not support. */
87
+ export const EFFORT_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const;
88
+
89
+ /**
90
+ * The codex-acp session mode a run uses. `workspace-write` is Codex's own
91
+ * sandbox with write access to the task's worktree (the session's `cwd`) and
92
+ * no access outside it. Its network is off, but Codex asks before it leaves
93
+ * the sandbox: a command that needs the network arrives as a permission
94
+ * request, and the access profile answers it (a request for the network is
95
+ * allowed once, since the task needs it). The other modes are not used:
96
+ * `read-only` cannot write the worktree, `agent` lets Codex's own reviewer
97
+ * answer instead of the profile, and `agent-full-access` turns the sandbox off.
98
+ */
99
+ export const SESSION_MODE = "workspace-write";
100
+
101
+ /** The models and efforts a chat may pick with this agent: none; codex is a worker, not a chat harness. */
102
+ export const CODEX_MODELS = { list: [], default: null } as const;
103
+ export const CODEX_EFFORTS = { list: [], default: null, flag: "--effort" } as const;
104
+
105
+ /** The settings a config.json section may set for this plugin. */
106
+ export const PLUGIN_SETTINGS = {
107
+ type: "object" as const,
108
+ properties: {
109
+ model: {
110
+ type: "string" as const,
111
+ minLength: 1,
112
+ description: "The model name codex takes; unset uses Codex's own default.",
113
+ },
114
+ effort: {
115
+ type: "string" as const,
116
+ enum: EFFORT_LEVELS,
117
+ description: "The reasoning effort; unset uses Codex's own default.",
118
+ },
119
+ command: {
120
+ type: "array" as const,
121
+ minItems: 1,
122
+ items: { type: "string" as const, minLength: 1 },
123
+ description:
124
+ "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.",
125
+ },
126
+ wallTimeSecs: {
127
+ type: "number" as const,
128
+ minimum: 1,
129
+ maximum: MAX_WALL_TIME_SECS,
130
+ default: DEFAULT_WALL_TIME_SECS,
131
+ description: "The longest one agent run may take.",
132
+ },
133
+ stallSecs: {
134
+ type: "number" as const,
135
+ minimum: 1,
136
+ default: DEFAULT_STALL_SECS,
137
+ description: "How long an agent may be silent while no tool call is open.",
138
+ },
139
+ concurrency: CONCURRENCY_SETTING,
140
+ },
141
+ additionalProperties: false as const,
142
+ };
143
+
144
+ /** The spelling of this harness's step `args`. */
145
+ const STEP_FLAGS = { levelFlag: "--effort", levels: EFFORT_LEVELS, modelHint: "<name>" } as const;
146
+
147
+ /** What a test injects. */
148
+ export interface CodexHarnessOptions {
149
+ readonly clock?: Clock | undefined;
150
+ /** Milliseconds now, for tool call start times and durations. */
151
+ readonly now?: (() => number) | undefined;
152
+ /** The Codex command `plugin check` asks about the login; defaults to the `codex` of PATH. */
153
+ readonly codex?: readonly string[] | undefined;
154
+ }
155
+
156
+ /** The codex-acp error info of an error: a string, or the key of an object. */
157
+ function errorInfo(error: AcpError): string | undefined {
158
+ const data = error.data;
159
+ if (!isRecord(data)) return undefined;
160
+ const info = data["codexErrorInfo"];
161
+ if (typeof info === "string") return info;
162
+ if (isRecord(info)) return Object.keys(info)[0];
163
+ return undefined;
164
+ }
165
+
166
+ function errorText(error: AcpError): string {
167
+ const data = error.data;
168
+ if (isRecord(data) && typeof data["message"] === "string" && data["message"].length > 0) return data["message"];
169
+ return error.message;
170
+ }
171
+
172
+ /** How one ACP error ends the step: the reason, the message and, for a model that cannot serve, the model error. */
173
+ export interface Failure {
174
+ readonly reason: string;
175
+ readonly message: string;
176
+ readonly modelError?: { readonly kind: string };
177
+ }
178
+
179
+ /**
180
+ * Maps an error of codex-acp to the step's failure. An exhausted ChatGPT quota
181
+ * (`usageLimitExceeded`, a rate limit) is `usage_limit` and an unavailable
182
+ * model (a model the session refuses, an overloaded service) is `unavailable`,
183
+ * the model errors dev's `retry_wait` and pool's fallbacks act on.
184
+ */
185
+ export function failureOf(end: Extract<AcpEnd, { kind: "error" }>, model: string | undefined): Failure {
186
+ const info = errorInfo(end.error);
187
+ const message = errorText(end.error);
188
+ if (end.error.code === -32000) {
189
+ return { reason: "not_logged_in", message: "Codex is not logged in; run `codex login` first" };
190
+ }
191
+ if (info === "usageLimitExceeded" || info === "rateLimitExceeded") {
192
+ return { reason: "model_error", message, modelError: { kind: "usage_limit" } };
193
+ }
194
+ if (info === "serverOverloaded") {
195
+ return { reason: "model_error", message, modelError: { kind: "unavailable" } };
196
+ }
197
+ if (end.stage === "config") {
198
+ if (end.configId === "model") {
199
+ return {
200
+ reason: "model_error",
201
+ message: `codex-acp does not offer the model ${model ?? "asked for"}: ${message}`,
202
+ modelError: { kind: "unavailable" },
203
+ };
204
+ }
205
+ if (end.configId === "reasoning_effort") {
206
+ return { reason: "invalid_args", message: `codex-acp refused the reasoning effort: ${message}` };
207
+ }
208
+ return { reason: "config", message: `codex-acp refused a session setting (${end.configId ?? "unknown"}): ${message}` };
209
+ }
210
+ if (end.stage === "prompt") {
211
+ const mapped = modelErrorOf(message);
212
+ return {
213
+ reason: "model_error",
214
+ message,
215
+ modelError: { kind: String(mapped["kind"]) },
216
+ };
217
+ }
218
+ if (end.stage === "session" && /resume|load/i.test(message)) {
219
+ return { reason: "session_missing", message };
220
+ }
221
+ return { reason: "protocol", message: `codex-acp failed at ${end.stage}: ${message}` };
222
+ }
223
+
224
+ /** Creates the codex harness plugin. */
225
+ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
226
+ const clock = options.clock ?? systemClock;
227
+ const now = options.now ?? Date.now;
228
+
229
+ const promptFlow = defineFlow({
230
+ name: "codex:prompt",
231
+ entry: "agent",
232
+ steps: [
233
+ {
234
+ id: "agent",
235
+ kind: "plugin",
236
+ params: { use: "codex/agent", params: {} },
237
+ replay: "unsafe",
238
+ next: { done: "done", failed: "failed", interrupted: "cancelled", waiting: "person" },
239
+ },
240
+ {
241
+ // A question about a call ran out of grace. The answer sends the run
242
+ // back to the agent, which continues the session with it.
243
+ id: "person",
244
+ kind: "wait_person",
245
+ params: {
246
+ prompt: "The agent asked about a call.",
247
+ choices: ["allow_once", "reject_once"],
248
+ lateChoices: ["allow_always"],
249
+ },
250
+ replay: "safe",
251
+ next: {
252
+ allow_once: "agent",
253
+ allow_always: "agent",
254
+ reject_once: "agent",
255
+ interrupted: "cancelled",
256
+ },
257
+ },
258
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
259
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
260
+ { id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
261
+ ],
262
+ });
263
+
264
+ return definePlugin({
265
+ name: HARNESS,
266
+ kind: "harness",
267
+ version: pkg.version,
268
+ models: CODEX_MODELS,
269
+ efforts: CODEX_EFFORTS,
270
+ settings: PLUGIN_SETTINGS,
271
+ steps: [
272
+ {
273
+ name: "agent",
274
+ // A question's answer comes back as `resumeSession` and `askAnswer`.
275
+ resumable: true,
276
+ // `waiting`: a question about a call was not answered within the grace.
277
+ results: ["done", "failed", "interrupted", "waiting"],
278
+ // Applied to the calls codex-acp asks permission for. Codex's own
279
+ // sandbox runs the calls inside it without asking; those are bounded
280
+ // by the sandbox, not by these rules.
281
+ enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
282
+ timeoutSecs: STEP_TIMEOUT_SECS,
283
+ // The model the step uses: its `--model` argument, else the setting.
284
+ limit: modelLimit(HARNESS, (params, settings) => {
285
+ const fromArgs = isRecord(params) ? flagValue(params.args, "--model") : undefined;
286
+ const model = fromArgs ?? settings.model;
287
+ return typeof model === "string" && model.length > 0 ? model : undefined;
288
+ }),
289
+ async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
290
+ const at = "codex/agent";
291
+ const input = paramsObject(params, at);
292
+ const flow = isRecord(ctx.params) ? ctx.params : {};
293
+
294
+ const prompt = text(input.prompt ?? flow.prompt, `${at}: params.prompt`);
295
+ const note = eventNote(ctx.trigger);
296
+ const rawAskAnswer = input.askAnswer ?? flow.askAnswer;
297
+ const promptText = [prompt, note, askNote(rawAskAnswer)]
298
+ .filter((part): part is string => part !== undefined)
299
+ .join("\n\n");
300
+ const cwd = text(input.cwd ?? flow.cwd, `${at}: params.cwd`);
301
+ const rawArgs = input.args === undefined ? flow.args : input.args;
302
+ const flags = parseStepFlags(stringListParam(rawArgs, `${at}: params.args`), STEP_FLAGS);
303
+ const settingModel = typeof ctx.settings.model === "string" ? ctx.settings.model : undefined;
304
+ const knownModel =
305
+ typeof flags === "string" ? (flagValue(rawArgs, "--model") ?? settingModel) : (flags.model ?? settingModel);
306
+ // The cost of a subscription login is unknown, never 0.
307
+ const early: UsageSource = { harness: HARNESS, model: knownModel ?? null };
308
+ const refuse = async (reason: string, message: string): Promise<PluginStepResult> => {
309
+ const log = await ctx.logger.write(message);
310
+ return {
311
+ result: "failed",
312
+ data: {
313
+ reason,
314
+ message,
315
+ exitCode: null,
316
+ signal: null,
317
+ sessionId: null,
318
+ finalMessage: null,
319
+ usage: standardUsage(early, undefined, null),
320
+ log,
321
+ durationMs: 0,
322
+ stderr: [message],
323
+ imageGenCalls: 0,
324
+ },
325
+ };
326
+ };
327
+ if (typeof flags === "string") return refuse("invalid_args", `${at}: ${flags}`);
328
+
329
+ const resumeSession = optionalText(input.resumeSession ?? flow.resumeSession, `${at}: params.resumeSession`);
330
+ const wallTimeSecs = secs(
331
+ input.wallTimeSecs ?? ctx.settings.wallTimeSecs ?? DEFAULT_WALL_TIME_SECS,
332
+ `${at}: params.wallTimeSecs`,
333
+ );
334
+ if (wallTimeSecs > MAX_WALL_TIME_SECS) {
335
+ throw new Error(`${at}: params.wallTimeSecs: must be at most ${MAX_WALL_TIME_SECS}`);
336
+ }
337
+ const stallSecs = secs(
338
+ input.stallSecs ?? ctx.settings.stallSecs ?? DEFAULT_STALL_SECS,
339
+ `${at}: params.stallSecs`,
340
+ );
341
+ const model = flags.model ?? optionalText(ctx.settings.model, `${at}: settings.model`);
342
+ const effort = flags.level ?? optionalText(ctx.settings.effort, `${at}: settings.effort`);
343
+
344
+ const cwdProblem = await directoryError(cwd);
345
+ if (cwdProblem !== undefined) return refuse("cwd", cwdProblem);
346
+
347
+ let command: readonly string[];
348
+ try {
349
+ command = commandOf(ctx.settings.command);
350
+ } catch (error) {
351
+ return refuse("missing", error instanceof Error ? error.message : String(error));
352
+ }
353
+ const program = command[0] ?? "";
354
+
355
+ const operadTools = operadToolsOf(input.operadTools ?? flow.operadTools);
356
+ const mounted = mountedServersOf(input.mcpServers ?? flow.mcpServers);
357
+ const mcpServers: Record<string, unknown>[] = [];
358
+ if (operadTools !== undefined) {
359
+ const server = serverCommand(operadTools);
360
+ mcpServers.push({
361
+ name: OPERAD_SERVER,
362
+ command: server.command,
363
+ args: [...server.args],
364
+ env: [{ name: "OPERAD_HOME", value: operadTools.home }],
365
+ });
366
+ }
367
+ for (const [name, server] of Object.entries(mounted ?? {})) {
368
+ mcpServers.push({ name, command: server.command, args: [...server.args], env: [] });
369
+ }
370
+ const images = imageInputsOf(input.images ?? flow.images);
371
+ const imageBlocks: Record<string, unknown>[] = [];
372
+ for (const image of images) {
373
+ const read = await readImage(image);
374
+ imageBlocks.push({ type: "image", data: read.data, mimeType: read.mediaType });
375
+ }
376
+
377
+ const storeSecrets = await secretValuesOf(ctx.secrets);
378
+ const allowAlways = personStarted(ctx.trigger);
379
+ if (allowAlways && isRecord(rawAskAnswer) && rawAskAnswer["choice"] === ALLOW_ALWAYS) {
380
+ const entry = alwaysAllowFromGrant(ctx.access, cwd);
381
+ if (entry !== undefined) {
382
+ try {
383
+ await appendAlwaysAllow(ctx.home, entry);
384
+ } catch (error) {
385
+ await ctx.logger.write(
386
+ `allow_always could not be written to the user access file: ${String(error)}; this call runs once`,
387
+ );
388
+ }
389
+ }
390
+ }
391
+ let runAccess = accessWithAlwaysAllow(ctx.access, [], false);
392
+ if (allowAlways) {
393
+ const user = await readAlwaysAllow(ctx.home);
394
+ if (user.problem !== undefined) await ctx.logger.write(user.problem);
395
+ runAccess = accessWithAlwaysAllow(ctx.access, user.entries, true);
396
+ }
397
+ const read = readProfile(runAccess ?? {});
398
+ const profile: AccessProfile = read.ok ? read.profile : {};
399
+
400
+ const started = Date.now();
401
+ const jsonl = new JsonlLog(ctx.logger, clock);
402
+ const stopper = new AbortController();
403
+ const endRun = (): void => stopper.abort();
404
+
405
+ const asker = createCallAsker({
406
+ ask: (request) => ctx.ask(request),
407
+ onStop: endRun,
408
+ secrets: storeSecrets,
409
+ ...(allowAlways ? { alwaysAllow: { home: ctx.home, cwd } } : {}),
410
+ onLog: (message) => {
411
+ void ctx.logger.write(message);
412
+ },
413
+ });
414
+ let askId = 0;
415
+
416
+ // A full buffer makes the line reader wait for the disk.
417
+ let writing: Promise<void> | undefined;
418
+ const writeLine = (line: string): void => {
419
+ const pending = jsonl.push(line);
420
+ if (pending !== undefined) writing = pending;
421
+ deliverLine(ctx.receiver, line, storeSecrets);
422
+ };
423
+ let client: AcpClient | undefined;
424
+ const log = new CodexLog({
425
+ write: writeLine,
426
+ now,
427
+ cwd,
428
+ profile,
429
+ secrets: storeSecrets,
430
+ active: () => client?.prompting === true,
431
+ });
432
+
433
+ const shown = (call: JudgedCall): string =>
434
+ summarizeCall({}, call.tool, call.input, cwd, { secrets: storeSecrets, keepLines: true }) ?? call.tool;
435
+
436
+ const ask = (question: {
437
+ readonly kind: "command" | "path";
438
+ readonly value: string;
439
+ readonly tool?: string;
440
+ readonly shown: string;
441
+ }): Promise<CallAnswer> =>
442
+ new Promise<CallAnswer>((resolve) => {
443
+ askId += 1;
444
+ const line = JSON.stringify({
445
+ type: "ask_call",
446
+ id: askId,
447
+ kind: question.kind,
448
+ value: question.value,
449
+ ...(question.tool === undefined ? {} : { tool: question.tool }),
450
+ shown: question.shown,
451
+ session: client?.sessionId ?? null,
452
+ });
453
+ void asker.handle(line, (reply) => {
454
+ try {
455
+ const ack: unknown = JSON.parse(reply);
456
+ if (isRecord(ack) && (ack["decision"] === "allow" || ack["decision"] === "deny" || ack["decision"] === "stop")) {
457
+ resolve({
458
+ decision: ack["decision"],
459
+ ...(typeof ack["reason"] === "string" ? { reason: ack["reason"] } : {}),
460
+ });
461
+ return;
462
+ }
463
+ } catch {
464
+ // fall through to a refusal
465
+ }
466
+ resolve({ decision: "deny", reason: "the question could not be asked" });
467
+ });
468
+ });
469
+
470
+ const acp = new AcpClient({
471
+ cwd,
472
+ prompt: [{ type: "text", text: promptText }, ...imageBlocks],
473
+ ...(resumeSession === undefined ? {} : { resumeSession }),
474
+ config: [
475
+ { configId: "mode", value: SESSION_MODE },
476
+ ...(model === undefined ? [] : [{ configId: "model", value: model }]),
477
+ ...(effort === undefined ? [] : [{ configId: "reasoning_effort", value: effort }]),
478
+ ],
479
+ ...(mcpServers.length === 0 ? {} : { mcpServers }),
480
+ clientName: "operad",
481
+ onUpdate: (update) => log.handle(update),
482
+ async onPermission(request) {
483
+ const decision = await decideAccess(profile, request.toolCall, cwd, {
484
+ useGrant: (waitId) => ctx.useGrant(waitId),
485
+ ask,
486
+ shown,
487
+ });
488
+ if (!decision.allow) log.blocked(request.toolCall);
489
+ return decision.allow;
490
+ },
491
+ });
492
+ client = acp;
493
+
494
+ const state: { end: AcpEnd | undefined } = { end: undefined };
495
+ void acp.ended.then((value) => {
496
+ state.end = value;
497
+ endRun();
498
+ });
499
+
500
+ // A cancel asks codex-acp to stop the prompt and waits for its
501
+ // answer; an agent that does not answer within the grace is ended.
502
+ let graceTimer: unknown;
503
+ const onAbort = (): void => {
504
+ if (acp.finished) return;
505
+ if (!acp.cancel()) {
506
+ endRun();
507
+ return;
508
+ }
509
+ graceTimer = clock.setTimeout(endRun, CANCEL_GRACE_MS);
510
+ };
511
+ if (ctx.signal.aborted) endRun();
512
+ else ctx.signal.addEventListener("abort", onAbort, { once: true });
513
+
514
+ const outcome = await runAgent({
515
+ command: program,
516
+ args: command.slice(1),
517
+ cwd,
518
+ stdin: acp.first,
519
+ interactive: true,
520
+ wallMs: wallTimeSecs * 1000,
521
+ stallMs: stallSecs * 1000,
522
+ signal: stopper.signal,
523
+ clock,
524
+ toolEvent: (line) => log.toolEvent(line),
525
+ onLine(line, reply) {
526
+ acp.handleLine(line, reply);
527
+ return writing;
528
+ },
529
+ });
530
+ ctx.signal.removeEventListener("abort", onAbort);
531
+ if (graceTimer !== undefined) clock.clearTimeout(graceTimer);
532
+
533
+ // The grace passed with a question open: the program was ended on
534
+ // purpose. The kernel turns this into the result `waiting`, and the
535
+ // answer comes back with the session and a one-time grant.
536
+ const unanswered = asker.stopped();
537
+ if (unanswered !== undefined && !ctx.signal.aborted) {
538
+ await jsonl.end();
539
+ throw unanswered.error;
540
+ }
541
+
542
+ const sessionId = acp.sessionId ?? resumeSession ?? null;
543
+ let result: AgentWorkerResult | undefined;
544
+ const end = state.end;
545
+ if (end !== undefined) {
546
+ if (end.kind === "stopped") {
547
+ log.finish(end.stopReason, end.usage);
548
+ const usage = end.usage;
549
+ const counts = {
550
+ input: usage?.inputTokens,
551
+ output: usage?.outputTokens,
552
+ cache_read: usage?.cachedReadTokens ?? undefined,
553
+ cache_write: usage?.cachedWriteTokens ?? undefined,
554
+ };
555
+ const closing = log.finalText.trim().length > 0 ? log.finalText : null;
556
+ const base = { type: "result" as const, sessionId: end.sessionId, usage: counts, cost: null, finalMessage: closing, model: model ?? null };
557
+ if (end.stopReason === "cancelled") result = { ...base, result: "cancelled" };
558
+ else if (end.stopReason === "end_turn") result = { ...base, result: "done" };
559
+ else {
560
+ result = {
561
+ ...base,
562
+ result: "failed",
563
+ reason: end.stopReason === "refusal" ? "refusal" : "stop_reason",
564
+ message: `codex stopped the prompt: ${end.stopReason}`,
565
+ };
566
+ }
567
+ } else {
568
+ const failed = failureOf(end, model);
569
+ result = {
570
+ type: "result",
571
+ result: "failed",
572
+ sessionId: end.sessionId ?? resumeSession ?? null,
573
+ usage: {},
574
+ cost: null,
575
+ finalMessage: null,
576
+ model: model ?? null,
577
+ reason: failed.reason,
578
+ message: failed.message,
579
+ ...(failed.modelError === undefined ? {} : { modelError: failed.modelError }),
580
+ };
581
+ }
582
+ writeLine(
583
+ JSON.stringify({
584
+ type: "result",
585
+ result: result.result,
586
+ sessionId,
587
+ usage: result.usage,
588
+ cost: null,
589
+ imageGenCalls: log.imageGenerations,
590
+ }),
591
+ );
592
+ }
593
+ await jsonl.end();
594
+
595
+ // The run was ended on purpose once codex-acp had answered: the
596
+ // signal that did it is not the agent's.
597
+ const settled =
598
+ end === undefined ? outcome : { ...outcome, exitCode: 0, signal: null, cancelled: false };
599
+ const stepResult = resultFor(
600
+ { harness: HARNESS, model: model ?? null },
601
+ settled,
602
+ result,
603
+ ctx.logger.path,
604
+ Date.now() - started,
605
+ { wallTimeSecs, stallSecs },
606
+ program,
607
+ );
608
+ return {
609
+ ...stepResult,
610
+ data: { ...(stepResult.data ?? {}), imageGenCalls: log.imageGenerations, stopReason: end?.kind === "stopped" ? end.stopReason : null },
611
+ };
612
+ },
613
+ },
614
+ ],
615
+ flows: [promptFlow],
616
+ async check(ctx) {
617
+ let command: readonly string[];
618
+ try {
619
+ command = commandOf(ctx.settings.command);
620
+ } catch (error) {
621
+ throw new Error(error instanceof Error ? error.message : String(error));
622
+ }
623
+ const bun = Bun.which("bun") ?? process.execPath;
624
+ const codex = options.codex ?? codexCommand(bun);
625
+ const install = inspectCodex(command, codex);
626
+ return (
627
+ `codex-acp ${install.acpVersion} (${command.join(" ")}); ` +
628
+ `codex ${install.codexVersion ?? "not found on PATH"}; ` +
629
+ `login ${install.login ?? "unknown"}`
630
+ );
631
+ },
632
+ });
633
+ }
634
+
635
+ export default createCodexHarnessPlugin();
package/src/install.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The user's own `codex-acp` and Codex: found, never bundled
3
+ * (ADR 0022 D6, D8). `inspectCodex` is what
4
+ * `operad plugin check` runs: `codex-acp --version`, `codex --version` and
5
+ * `codex login status`. Credentials are the user's own Codex (ChatGPT) login;
6
+ * operad never reads or writes them.
7
+ */
8
+
9
+ import { readFileSync, realpathSync } from "node:fs";
10
+
11
+ /** How long one probe may take. */
12
+ const PROBE_TIMEOUT_MS = 30_000;
13
+
14
+ /** The check could not pass; the message says what to do. */
15
+ export class CodexInstallError extends Error {
16
+ constructor(message: string) {
17
+ super(message);
18
+ this.name = "CodexInstallError";
19
+ }
20
+ }
21
+
22
+ /**
23
+ * The command that starts codex-acp when the `command` setting is unset: the
24
+ * `bun` of PATH runs the real path of the `codex-acp` of PATH. codex-acp's
25
+ * shebang is `#!/usr/bin/env node`, which finds a node only in a shell that
26
+ * set one up (fnm), never in the process operad runs under.
27
+ */
28
+ export function defaultCommand(path: string | undefined = process.env.PATH): readonly string[] {
29
+ const bun = Bun.which("bun", { PATH: path ?? "" });
30
+ if (bun === null) throw new CodexInstallError("no `bun` was found on PATH; codex-acp is started with it");
31
+ const acp = Bun.which("codex-acp", { PATH: path ?? "" });
32
+ if (acp === null) {
33
+ throw new CodexInstallError(
34
+ "no `codex-acp` was found on PATH; install it (bun add -g @agentclientprotocol/codex-acp) or set the command setting",
35
+ );
36
+ }
37
+ return [bun, realpathSync(acp)];
38
+ }
39
+
40
+ /** The argv of the `command` setting, or the default one. */
41
+ export function commandOf(setting: unknown, path: string | undefined = process.env.PATH): readonly string[] {
42
+ if (setting === undefined) return defaultCommand(path);
43
+ if (!Array.isArray(setting) || setting.length === 0 || !setting.every((word) => typeof word === "string" && word.length > 0)) {
44
+ throw new CodexInstallError("settings.command: must be a non-empty list of strings: the program and its arguments");
45
+ }
46
+ return setting.filter((word): word is string => typeof word === "string");
47
+ }
48
+
49
+ interface Ran {
50
+ readonly exitCode: number | null;
51
+ readonly stdout: string;
52
+ }
53
+
54
+ function run(argv: readonly string[], args: readonly string[]): Ran {
55
+ try {
56
+ const ran = Bun.spawnSync([...argv, ...args], {
57
+ stdin: "ignore",
58
+ env: { ...process.env },
59
+ stdout: "pipe",
60
+ stderr: "ignore",
61
+ timeout: PROBE_TIMEOUT_MS,
62
+ });
63
+ return { exitCode: ran.exitCode, stdout: ran.stdout.toString("utf8") };
64
+ } catch {
65
+ return { exitCode: null, stdout: "" };
66
+ }
67
+ }
68
+
69
+ /** The Codex command: its script run by the same bun when its shebang names node. */
70
+ export function codexCommand(bun: string, path: string | undefined = process.env.PATH): readonly string[] | undefined {
71
+ const found = Bun.which("codex", { PATH: path ?? "" });
72
+ if (found === null) return undefined;
73
+ const real = realpathSync(found);
74
+ try {
75
+ const head = readFileSync(real, "utf8").slice(0, 120).split("\n")[0] ?? "";
76
+ if (head.startsWith("#!") && head.includes("node")) return [bun, real];
77
+ } catch {
78
+ // A native binary is not text.
79
+ }
80
+ return [real];
81
+ }
82
+
83
+ /** The last word-like token of a version line: `codex-cli 0.166.0` gives `0.166.0`. */
84
+ function versionOf(stdout: string): string | undefined {
85
+ const line = stdout.split("\n").find((text) => text.trim().length > 0)?.trim();
86
+ if (line === undefined) return undefined;
87
+ const found = /\d+\.\d+\.\d+\S*/.exec(line);
88
+ return found?.[0];
89
+ }
90
+
91
+ /** The login kind from `codex login status`: only the kind, never an account or a key. */
92
+ function loginKind(stdout: string): string {
93
+ const found = /^Logged in using ([A-Za-z0-9 ]{1,30}?)(?:\s+-|\s*$)/m.exec(stdout.trim());
94
+ return found?.[1] ?? "unknown login";
95
+ }
96
+
97
+ /** What `operad plugin check` learns about the install. */
98
+ export interface CodexInstall {
99
+ readonly acpVersion: string;
100
+ readonly codexVersion: string | undefined;
101
+ /** The login kind, such as `ChatGPT`; undefined when Codex could not be asked. */
102
+ readonly login: string | undefined;
103
+ }
104
+
105
+ /**
106
+ * Starts codex-acp with `--version` and asks Codex about the login. Throws
107
+ * `CodexInstallError` with what to do when codex-acp cannot start or Codex is
108
+ * not logged in. A Codex that cannot be asked is reported as unknown.
109
+ */
110
+ export function inspectCodex(command: readonly string[], codex: readonly string[] | undefined): CodexInstall {
111
+ const acp = run(command, ["--version"]);
112
+ if (acp.exitCode !== 0) {
113
+ throw new CodexInstallError(`\`${command.join(" ")} --version\` did not run; codex-acp cannot start`);
114
+ }
115
+ const acpVersion = versionOf(acp.stdout) ?? "unknown";
116
+ if (codex === undefined) return { acpVersion, codexVersion: undefined, login: undefined };
117
+ const version = run(codex, ["--version"]);
118
+ const codexVersion = version.exitCode === 0 ? versionOf(version.stdout) : undefined;
119
+ const status = run(codex, ["login", "status"]);
120
+ if (status.exitCode === null) return { acpVersion, codexVersion, login: undefined };
121
+ if (status.exitCode !== 0) {
122
+ throw new CodexInstallError("Codex is not logged in; run `codex login` first");
123
+ }
124
+ return { acpVersion, codexVersion, login: loginKind(status.stdout) };
125
+ }
package/src/log.ts ADDED
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Turns the `session/update` stream of codex-acp into the lines every harness
3
+ * writes to a step's log (`SharedLine` of `@operad-io/harness-process`), so a
4
+ * rework can read what the agent said and which tool calls it made, and counts
5
+ * the image generations of the run.
6
+ */
7
+
8
+ import { firstErrorLine, messageSummary, REFUSED_IN_LOG, summarizeCall, type AccessProfile } from "@operad-io/access-match";
9
+ import { isRecord } from "@operad-io/engine";
10
+ import {
11
+ capToolOutput,
12
+ maskSecrets,
13
+ type AcpUsage,
14
+ type ToolEvent,
15
+ } from "@operad-io/harness-process";
16
+ import { commandOf } from "./access.ts";
17
+
18
+ const IMAGE_GEN = /\bimage[ _-]?gen(?:eration)?\b/i;
19
+
20
+ /** The statuses after which an ACP tool call does not change again. */
21
+ function terminal(status: unknown): boolean {
22
+ return status === "completed" || status === "failed";
23
+ }
24
+
25
+ /** Whether a tool call is one of Codex's image generations. */
26
+ export function isImageGen(call: Readonly<Record<string, unknown>>): boolean {
27
+ const title = call["title"];
28
+ return typeof title === "string" && IMAGE_GEN.test(title);
29
+ }
30
+
31
+ /** The name a tool call goes by in the log and in the access profile's words. */
32
+ export function toolNameOf(call: Readonly<Record<string, unknown>>): string {
33
+ if (isImageGen(call)) return "image_gen";
34
+ switch (call["kind"]) {
35
+ case "execute":
36
+ return "bash";
37
+ case "read":
38
+ return "read";
39
+ case "edit":
40
+ case "delete":
41
+ case "move":
42
+ return "edit";
43
+ case "search":
44
+ return "grep";
45
+ case "fetch":
46
+ return "fetch";
47
+ case "think":
48
+ return "think";
49
+ default: {
50
+ const title = call["title"];
51
+ return typeof title === "string" && title.trim().length > 0 ? title.trim().slice(0, 60) : "tool";
52
+ }
53
+ }
54
+ }
55
+
56
+ function pathsOf(call: Readonly<Record<string, unknown>>): string[] {
57
+ const list = call["locations"];
58
+ if (!Array.isArray(list)) return [];
59
+ return list.flatMap((item) => (isRecord(item) && typeof item["path"] === "string" ? [item["path"]] : []));
60
+ }
61
+
62
+ /** The input of a call in the words `summarizeCall` takes. */
63
+ function inputOf(name: string, call: Readonly<Record<string, unknown>>): Record<string, unknown> {
64
+ if (name === "bash") {
65
+ const command = commandOf(call["rawInput"]);
66
+ return command === undefined ? {} : { command };
67
+ }
68
+ const raw = call["rawInput"];
69
+ const path = pathsOf(call)[0];
70
+ if (path !== undefined) return { path };
71
+ if (isRecord(raw)) {
72
+ for (const key of ["url", "query", "pattern", "path"]) {
73
+ const value = raw[key];
74
+ if (typeof value === "string" && value.length > 0) return { [key]: value };
75
+ }
76
+ }
77
+ const title = call["title"];
78
+ return typeof title === "string" && title.length > 0 ? { description: title } : {};
79
+ }
80
+
81
+ /** The text a tool call's content and raw output carry; images are not text and are left out. */
82
+ function outputText(update: Readonly<Record<string, unknown>>): string {
83
+ const parts: string[] = [];
84
+ const content = update["content"];
85
+ if (Array.isArray(content)) {
86
+ for (const item of content) {
87
+ if (!isRecord(item)) continue;
88
+ const inner = item["content"];
89
+ if (item["type"] === "content" && isRecord(inner)) {
90
+ if (inner["type"] === "text" && typeof inner["text"] === "string") parts.push(inner["text"]);
91
+ else if (inner["type"] === "resource_link" && typeof inner["uri"] === "string") parts.push(inner["uri"]);
92
+ } else if (item["type"] === "diff" && typeof item["path"] === "string") {
93
+ parts.push(`changed ${item["path"]}`);
94
+ }
95
+ }
96
+ }
97
+ const raw = update["rawOutput"];
98
+ if (isRecord(raw)) {
99
+ const saved = raw["savedPath"];
100
+ if (typeof saved === "string" && saved.length > 0) parts.push(`saved ${saved}`);
101
+ for (const key of ["aggregated_output", "stdout", "output"]) {
102
+ const value = raw[key];
103
+ if (typeof value === "string" && value.length > 0 && !parts.includes(value)) parts.push(value);
104
+ }
105
+ }
106
+ return parts.join("\n");
107
+ }
108
+
109
+ interface OpenCall {
110
+ readonly name: string;
111
+ readonly at: number;
112
+ denied: boolean;
113
+ output: string;
114
+ }
115
+
116
+ export interface CodexLogOptions {
117
+ /** Writes one log line. */
118
+ readonly write: (line: string) => void;
119
+ /** Milliseconds now, for start times and durations. */
120
+ readonly now: () => number;
121
+ readonly cwd: string;
122
+ readonly profile: AccessProfile;
123
+ readonly secrets: readonly string[];
124
+ /** True while the prompt is in flight: updates before it are a replayed history. */
125
+ readonly active: () => boolean;
126
+ }
127
+
128
+ export class CodexLog {
129
+ private readonly options: CodexLogOptions;
130
+ private readonly open = new Map<string, OpenCall>();
131
+ /** Ids of calls the stall timer is paused for. */
132
+ private readonly watching = new Set<string>();
133
+ private readonly seenImages = new Set<string>();
134
+ private text = "";
135
+
136
+ constructor(options: CodexLogOptions) {
137
+ this.options = options;
138
+ }
139
+
140
+ /** How many image generations the prompt started. */
141
+ get imageGenerations(): number {
142
+ return this.seenImages.size;
143
+ }
144
+
145
+ /** What the agent said after its last tool call: the closing message. */
146
+ get finalText(): string {
147
+ return this.text;
148
+ }
149
+
150
+ private line(value: Record<string, unknown>): void {
151
+ this.options.write(maskSecrets(JSON.stringify(value), this.options.secrets));
152
+ }
153
+
154
+ /**
155
+ * Classifies one raw line of the agent for the stall timer. A tool call that
156
+ * is open, and a permission request nobody has answered, are silence the
157
+ * agent is allowed: an image generation may print nothing for minutes. Only
158
+ * the wall limit watches them.
159
+ */
160
+ toolEvent(line: string): ToolEvent | undefined {
161
+ if (!this.options.active() || !line.includes("tool")) return undefined;
162
+ let message: unknown;
163
+ try {
164
+ message = JSON.parse(line);
165
+ } catch {
166
+ return undefined;
167
+ }
168
+ if (!isRecord(message) || !isRecord(message["params"])) return undefined;
169
+ const params = message["params"];
170
+ if (message["method"] === "session/request_permission") {
171
+ const id = isRecord(params["toolCall"]) ? params["toolCall"]["toolCallId"] : undefined;
172
+ if (typeof id !== "string" || this.watching.has(id)) return undefined;
173
+ this.watching.add(id);
174
+ return "tool-start";
175
+ }
176
+ if (message["method"] !== "session/update" || !isRecord(params["update"])) return undefined;
177
+ const update = params["update"];
178
+ const id = update["toolCallId"];
179
+ if (typeof id !== "string") return undefined;
180
+ if (update["sessionUpdate"] === "tool_call") {
181
+ if (terminal(update["status"]) || this.watching.has(id)) return undefined;
182
+ this.watching.add(id);
183
+ return "tool-start";
184
+ }
185
+ if (update["sessionUpdate"] === "tool_call_update" && terminal(update["status"]) && this.watching.delete(id)) {
186
+ return "tool-end";
187
+ }
188
+ return undefined;
189
+ }
190
+
191
+ /** Takes one `session/update` of the running prompt. */
192
+ handle(update: Readonly<Record<string, unknown>>): void {
193
+ const kind = update["sessionUpdate"];
194
+ if (kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
195
+ const content = update["content"];
196
+ if (!isRecord(content) || content["type"] !== "text" || typeof content["text"] !== "string") return;
197
+ if (content["text"].length === 0) return;
198
+ if (kind === "agent_message_chunk") {
199
+ this.text += content["text"];
200
+ this.line({ type: "text_delta", text: content["text"] });
201
+ } else {
202
+ this.line({ type: "thinking_delta", text: content["text"] });
203
+ }
204
+ return;
205
+ }
206
+ if (kind === "tool_call") this.start(update);
207
+ else if (kind === "tool_call_update") this.update(update);
208
+ }
209
+
210
+ /** Records that the access profile refused the call a permission request is about. */
211
+ blocked(toolCall: Readonly<Record<string, unknown>>): void {
212
+ const id = toolCall["toolCallId"];
213
+ const open = typeof id === "string" ? this.open.get(id) : undefined;
214
+ if (open !== undefined) open.denied = true;
215
+ this.line({ type: "blocked", toolName: open?.name ?? toolNameOf(toolCall), reason: REFUSED_IN_LOG });
216
+ }
217
+
218
+ private start(call: Readonly<Record<string, unknown>>): void {
219
+ const id = call["toolCallId"];
220
+ if (typeof id !== "string" || this.open.has(id)) return;
221
+ // What was said before a tool call is not the closing message.
222
+ this.text = "";
223
+ const name = toolNameOf(call);
224
+ if (name === "image_gen") this.seenImages.add(id);
225
+ const at = this.options.now();
226
+ const summary = summarizeCall(this.options.profile, name, inputOf(name, call), this.options.cwd, {
227
+ secrets: this.options.secrets,
228
+ keepLines: true,
229
+ });
230
+ const denied = summary?.includes(" denied by the access profile") === true;
231
+ this.open.set(id, { name, at, denied, output: "" });
232
+ this.line({
233
+ type: "tool_execution_start",
234
+ toolCallId: id,
235
+ toolName: name,
236
+ at,
237
+ ...(summary === undefined ? {} : { input: summary }),
238
+ });
239
+ // A call that arrives already settled is also over.
240
+ if (terminal(call["status"])) this.end(id, call);
241
+ }
242
+
243
+ private update(update: Readonly<Record<string, unknown>>): void {
244
+ const id = update["toolCallId"];
245
+ if (typeof id !== "string") return;
246
+ const call = this.open.get(id);
247
+ if (call === undefined) return;
248
+ const text = outputText(update);
249
+ if (text.length > 0) call.output = text;
250
+ if (terminal(update["status"])) this.end(id, update);
251
+ }
252
+
253
+ private end(id: string, update: Readonly<Record<string, unknown>>): void {
254
+ const call = this.open.get(id);
255
+ if (call === undefined) return;
256
+ this.open.delete(id);
257
+ const text = outputText(update).length > 0 ? outputText(update) : call.output;
258
+ const failed = update["status"] === "failed";
259
+ if (text.length > 0) {
260
+ const head = capToolOutput(maskSecrets(text, this.options.secrets));
261
+ this.line({
262
+ type: "tool_output",
263
+ toolCallId: id,
264
+ text: head.text,
265
+ ...(head.truncated ? { truncated: true } : {}),
266
+ });
267
+ }
268
+ const error =
269
+ failed && !call.denied
270
+ ? firstErrorLine(text.length > 0 ? text : "the call failed", { secrets: this.options.secrets })
271
+ : undefined;
272
+ this.line({
273
+ type: "tool_execution_end",
274
+ toolCallId: id,
275
+ toolName: call.name,
276
+ isError: failed,
277
+ durationMs: Math.max(0, this.options.now() - call.at),
278
+ ...(error === undefined ? {} : { error }),
279
+ });
280
+ }
281
+
282
+ /** Writes the closing `message_end` line of the prompt. */
283
+ finish(stopReason: string, usage: AcpUsage | null): void {
284
+ const said = messageSummary(this.text);
285
+ this.line({
286
+ type: "message_end",
287
+ role: "assistant",
288
+ ...(said === undefined ? {} : { text: said }),
289
+ stopReason,
290
+ usage: {
291
+ input: usage?.inputTokens ?? 0,
292
+ output: usage?.outputTokens ?? 0,
293
+ cache_read: usage?.cachedReadTokens ?? 0,
294
+ cache_write: usage?.cachedWriteTokens ?? 0,
295
+ },
296
+ cost: null,
297
+ });
298
+ }
299
+ }