@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/src/install.ts ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The user's own `codex-acp` and Codex: found, never bundled
3
+ * (docs/backlog/operad-harness.md decisions 8 and 10). `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
+ }