@operad-io/harness-codex 0.1.1 → 0.3.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/src/log.ts CHANGED
@@ -1,111 +1,184 @@
1
1
  /**
2
- * Turns the `session/update` stream of codex-acp into the lines every harness
2
+ * Turns the item stream of `codex app-server` into the lines every harness
3
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.
4
+ * rework can read what the agent said, what it thought and which tool calls it
5
+ * made, and counts the image generations of the run.
6
6
  */
7
7
 
8
8
  import { firstErrorLine, messageSummary, REFUSED_IN_LOG, summarizeCall, type AccessProfile } from "@operad-io/access-match";
9
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";
10
+ import { capToolOutput, maskSecrets, type ToolEvent } from "@operad-io/harness-process";
11
+ import type { AppServerUsage } from "./app-server.ts";
17
12
 
18
- const IMAGE_GEN = /\bimage[ _-]?gen(?:eration)?\b/i;
13
+ const TOOL_ITEMS = new Set([
14
+ "commandExecution",
15
+ "fileChange",
16
+ "mcpToolCall",
17
+ "dynamicToolCall",
18
+ "collabAgentToolCall",
19
+ "imageGeneration",
20
+ "webSearch",
21
+ "imageView",
22
+ ]);
19
23
 
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";
24
+ /** Whether an item is a tool call the log shows. */
25
+ export function isToolItem(item: Readonly<Record<string, unknown>>): boolean {
26
+ return typeof item["type"] === "string" && TOOL_ITEMS.has(item["type"]);
23
27
  }
24
28
 
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
+ /** Whether an item is one of Codex's image generations. */
30
+ export function isImageGen(item: Readonly<Record<string, unknown>>): boolean {
31
+ return item["type"] === "imageGeneration";
29
32
  }
30
33
 
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":
34
+ function textOf(value: unknown): string | undefined {
35
+ return typeof value === "string" && value.length > 0 ? value : undefined;
36
+ }
37
+
38
+ /** The name a tool item goes by in the log. */
39
+ export function toolNameOf(item: Readonly<Record<string, unknown>>): string {
40
+ switch (item["type"]) {
41
+ case "commandExecution":
36
42
  return "bash";
37
- case "read":
38
- return "read";
39
- case "edit":
40
- case "delete":
41
- case "move":
43
+ case "fileChange":
42
44
  return "edit";
43
- case "search":
44
- return "grep";
45
- case "fetch":
46
- return "fetch";
47
- case "think":
48
- return "think";
45
+ case "mcpToolCall": {
46
+ const server = textOf(item["server"]);
47
+ const tool = textOf(item["tool"]) ?? "tool";
48
+ return server === undefined ? tool : `mcp__${server}__${tool}`;
49
+ }
50
+ case "dynamicToolCall":
51
+ return textOf(item["tool"]) ?? "tool";
52
+ case "imageGeneration":
53
+ return "image_gen";
54
+ case "webSearch":
55
+ return "web_search";
56
+ case "imageView":
57
+ return "image_view";
58
+ case "collabAgentToolCall":
59
+ return "collab_agent";
49
60
  default: {
50
- const title = call["title"];
51
- return typeof title === "string" && title.trim().length > 0 ? title.trim().slice(0, 60) : "tool";
61
+ const type = textOf(item["type"]) ?? "tool";
62
+ return type.slice(0, 60);
52
63
  }
53
64
  }
54
65
  }
55
66
 
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"]] : []));
67
+ function changesOf(item: Readonly<Record<string, unknown>>): readonly Readonly<Record<string, unknown>>[] {
68
+ const changes = item["changes"];
69
+ return Array.isArray(changes) ? changes.filter((change): change is Readonly<Record<string, unknown>> => isRecord(change)) : [];
60
70
  }
61
71
 
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 };
72
+ /** The input of a tool item in the words `summarizeCall` takes. */
73
+ function inputOf(item: Readonly<Record<string, unknown>>): Record<string, unknown> {
74
+ switch (item["type"]) {
75
+ case "commandExecution": {
76
+ const command = textOf(item["command"]);
77
+ return command === undefined ? {} : { command };
78
+ }
79
+ case "fileChange": {
80
+ const path = textOf(changesOf(item)[0]?.["path"]);
81
+ return path === undefined ? {} : { path };
82
+ }
83
+ case "mcpToolCall":
84
+ return { description: `${textOf(item["server"]) ?? "mcp"} ${textOf(item["tool"]) ?? "tool"}` };
85
+ case "dynamicToolCall":
86
+ return { description: textOf(item["tool"]) ?? "tool" };
87
+ case "imageGeneration":
88
+ return { description: "Image generation" };
89
+ case "webSearch": {
90
+ const query = textOf(item["query"]);
91
+ return query === undefined ? {} : { query };
75
92
  }
93
+ case "imageView": {
94
+ const path = textOf(item["path"]);
95
+ return path === undefined ? {} : { path };
96
+ }
97
+ default:
98
+ return {};
76
99
  }
77
- const title = call["title"];
78
- return typeof title === "string" && title.length > 0 ? { description: title } : {};
79
100
  }
80
101
 
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 {
102
+ function contentText(value: unknown): string {
103
+ if (!Array.isArray(value)) return "";
83
104
  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"]}`);
105
+ for (const entry of value) {
106
+ if (!isRecord(entry)) continue;
107
+ const text = textOf(entry["text"]);
108
+ if (text !== undefined) parts.push(text);
109
+ }
110
+ return parts.join("\n");
111
+ }
112
+
113
+ /** The text a tool item carries; images are not text and are left out. */
114
+ function outputOf(item: Readonly<Record<string, unknown>>, accumulated: string, patches: unknown): string {
115
+ const parts: string[] = [];
116
+ switch (item["type"]) {
117
+ case "commandExecution": {
118
+ const aggregated = textOf(item["aggregatedOutput"]);
119
+ if (aggregated !== undefined) parts.push(aggregated);
120
+ break;
121
+ }
122
+ case "fileChange": {
123
+ const changes = Array.isArray(patches) ? patches : item["changes"];
124
+ if (Array.isArray(changes)) {
125
+ for (const change of changes) {
126
+ if (isRecord(change) && typeof change["path"] === "string") parts.push(`changed ${change["path"]}`);
127
+ }
94
128
  }
129
+ break;
95
130
  }
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);
131
+ case "mcpToolCall": {
132
+ const error = isRecord(item["error"]) ? textOf(item["error"]["message"]) : undefined;
133
+ if (error !== undefined) parts.push(error);
134
+ const result = isRecord(item["result"]) ? item["result"] : undefined;
135
+ if (result !== undefined) {
136
+ const content = contentText(result["content"]);
137
+ if (content.length > 0) parts.push(content);
138
+ }
139
+ break;
140
+ }
141
+ case "dynamicToolCall": {
142
+ const content = contentText(item["contentItems"]);
143
+ if (content.length > 0) parts.push(content);
144
+ break;
104
145
  }
146
+ case "imageGeneration": {
147
+ const saved = textOf(item["savedPath"]);
148
+ if (saved !== undefined) parts.push(`saved ${saved}`);
149
+ break;
150
+ }
151
+ case "imageView": {
152
+ const path = textOf(item["path"]);
153
+ if (path !== undefined) parts.push(`read ${path}`);
154
+ break;
155
+ }
156
+ default:
157
+ break;
105
158
  }
159
+ if (accumulated.length > 0 && !parts.includes(accumulated)) parts.push(accumulated);
106
160
  return parts.join("\n");
107
161
  }
108
162
 
163
+ /** Whether a terminal tool item reports a failure. */
164
+ function failedOf(item: Readonly<Record<string, unknown>>): boolean {
165
+ switch (item["type"]) {
166
+ case "commandExecution":
167
+ case "fileChange":
168
+ case "mcpToolCall":
169
+ case "dynamicToolCall":
170
+ return item["status"] === "failed" || item["status"] === "declined";
171
+ case "imageGeneration":
172
+ return isRecord(item["failure"]);
173
+ default:
174
+ return false;
175
+ }
176
+ }
177
+
178
+ function terminal(item: Readonly<Record<string, unknown>>): boolean {
179
+ return item["status"] === "completed" || item["status"] === "failed" || item["status"] === "declined";
180
+ }
181
+
109
182
  interface OpenCall {
110
183
  readonly name: string;
111
184
  readonly at: number;
@@ -121,23 +194,29 @@ export interface CodexLogOptions {
121
194
  readonly cwd: string;
122
195
  readonly profile: AccessProfile;
123
196
  readonly secrets: readonly string[];
124
- /** True while the prompt is in flight: updates before it are a replayed history. */
197
+ /** True while the turn is in flight: what a resumed thread replays is not this run. */
125
198
  readonly active: () => boolean;
126
199
  }
127
200
 
128
201
  export class CodexLog {
129
202
  private readonly options: CodexLogOptions;
130
203
  private readonly open = new Map<string, OpenCall>();
131
- /** Ids of calls the stall timer is paused for. */
204
+ /** Ids of tool calls the stall timer is paused for. */
132
205
  private readonly watching = new Set<string>();
133
206
  private readonly seenImages = new Set<string>();
207
+ /** The text each agent message item has streamed. */
208
+ private readonly messages = new Map<string, string>();
209
+ /** Output deltas of command items, kept for a completion that carries none. */
210
+ private readonly outputs = new Map<string, string>();
211
+ /** The latest patch of a file-change item. */
212
+ private readonly patches = new Map<string, unknown>();
134
213
  private text = "";
135
214
 
136
215
  constructor(options: CodexLogOptions) {
137
216
  this.options = options;
138
217
  }
139
218
 
140
- /** How many image generations the prompt started. */
219
+ /** How many image generations the turn started. */
141
220
  get imageGenerations(): number {
142
221
  return this.seenImages.size;
143
222
  }
@@ -152,78 +231,139 @@ export class CodexLog {
152
231
  }
153
232
 
154
233
  /**
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.
234
+ * Classifies one raw line of the app-server for the stall timer. A tool item
235
+ * that is open, and a permission request nobody has answered, are silence
236
+ * the agent is allowed: an image generation may print nothing for minutes.
237
+ * Only the wall limit watches them.
159
238
  */
160
239
  toolEvent(line: string): ToolEvent | undefined {
161
- if (!this.options.active() || !line.includes("tool")) return undefined;
240
+ if (!this.options.active() || !line.includes("item")) return undefined;
162
241
  let message: unknown;
163
242
  try {
164
243
  message = JSON.parse(line);
165
244
  } catch {
166
245
  return undefined;
167
246
  }
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;
247
+ if (!isRecord(message)) return undefined;
248
+ const method = message["method"];
249
+ const params = isRecord(message["params"]) ? message["params"] : undefined;
250
+ if (typeof method !== "string" || params === undefined) return undefined;
251
+ if (method === "item/started") {
252
+ const item = params["item"];
253
+ if (!isRecord(item) || !isToolItem(item)) return undefined;
254
+ const id = item["id"];
172
255
  if (typeof id !== "string" || this.watching.has(id)) return undefined;
173
256
  this.watching.add(id);
174
257
  return "tool-start";
175
258
  }
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;
259
+ if (method === "item/completed") {
260
+ const item = params["item"];
261
+ const id = isRecord(item) ? item["id"] : undefined;
262
+ if (typeof id === "string" && this.watching.delete(id)) return "tool-end";
263
+ return undefined;
264
+ }
265
+ if (method === "item/commandExecution/requestApproval" || method === "item/fileChange/requestApproval") {
266
+ const id = params["itemId"];
267
+ if (typeof id !== "string" || this.watching.has(id)) return undefined;
182
268
  this.watching.add(id);
183
269
  return "tool-start";
184
270
  }
185
- if (update["sessionUpdate"] === "tool_call_update" && terminal(update["status"]) && this.watching.delete(id)) {
186
- return "tool-end";
271
+ if (method === "execCommandApproval" || method === "applyPatchApproval") {
272
+ const id = params["callId"];
273
+ if (typeof id !== "string" || this.watching.has(id)) return undefined;
274
+ this.watching.add(id);
275
+ return "tool-start";
187
276
  }
188
277
  return undefined;
189
278
  }
190
279
 
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"] });
280
+ /** Takes one notification of the running turn. */
281
+ handle(method: string, params: Readonly<Record<string, unknown>>): void {
282
+ if (!this.options.active()) return;
283
+ switch (method) {
284
+ case "item/started": {
285
+ const item = params["item"];
286
+ if (!isRecord(item)) return;
287
+ const id = item["id"];
288
+ if (item["type"] === "agentMessage" && typeof id === "string" && !this.messages.has(id)) {
289
+ this.messages.set(id, "");
290
+ }
291
+ if (isToolItem(item)) this.start(item);
292
+ return;
293
+ }
294
+ case "item/completed": {
295
+ const item = params["item"];
296
+ if (!isRecord(item)) return;
297
+ if (item["type"] === "agentMessage") {
298
+ this.completeMessage(item);
299
+ return;
300
+ }
301
+ if (isToolItem(item)) this.end(item);
302
+ return;
303
+ }
304
+ case "item/agentMessage/delta": {
305
+ const delta = params["delta"];
306
+ if (typeof delta !== "string" || delta.length === 0) return;
307
+ const id = params["itemId"];
308
+ if (typeof id === "string") this.messages.set(id, (this.messages.get(id) ?? "") + delta);
309
+ this.text += delta;
310
+ this.line({ type: "text_delta", text: delta });
311
+ return;
312
+ }
313
+ case "item/reasoning/textDelta":
314
+ case "item/reasoning/summaryTextDelta": {
315
+ const delta = params["delta"];
316
+ if (typeof delta !== "string" || delta.length === 0) return;
317
+ this.line({ type: "thinking_delta", text: delta });
318
+ return;
203
319
  }
204
- return;
320
+ case "item/commandExecution/outputDelta": {
321
+ const delta = params["delta"];
322
+ const id = params["itemId"];
323
+ if (typeof delta !== "string" || typeof id !== "string") return;
324
+ this.outputs.set(id, (this.outputs.get(id) ?? "") + delta);
325
+ return;
326
+ }
327
+ case "item/fileChange/patchUpdated": {
328
+ const id = params["itemId"];
329
+ if (typeof id === "string" && Array.isArray(params["changes"])) this.patches.set(id, params["changes"]);
330
+ return;
331
+ }
332
+ default:
333
+ return;
205
334
  }
206
- if (kind === "tool_call") this.start(update);
207
- else if (kind === "tool_call_update") this.update(update);
208
335
  }
209
336
 
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;
337
+ /** Records that the access profile refused the call an approval request is about. */
338
+ blocked(toolCallId: string, toolName: string): void {
339
+ const open = this.open.get(toolCallId);
214
340
  if (open !== undefined) open.denied = true;
215
- this.line({ type: "blocked", toolName: open?.name ?? toolNameOf(toolCall), reason: REFUSED_IN_LOG });
341
+ this.line({ type: "blocked", toolName: open?.name ?? toolName, reason: REFUSED_IN_LOG });
342
+ }
343
+
344
+ private completeMessage(item: Readonly<Record<string, unknown>>): void {
345
+ const id = item["id"];
346
+ if (typeof id !== "string") return;
347
+ const seen = this.messages.get(id) ?? "";
348
+ const full = textOf(item["text"]);
349
+ // A server that did not stream the message gives it complete; do not repeat
350
+ // one that did.
351
+ if (seen.length === 0 && full !== undefined) {
352
+ this.text += full;
353
+ this.messages.set(id, full);
354
+ this.line({ type: "text_delta", text: full });
355
+ }
216
356
  }
217
357
 
218
- private start(call: Readonly<Record<string, unknown>>): void {
219
- const id = call["toolCallId"];
358
+ private start(item: Readonly<Record<string, unknown>>): void {
359
+ const id = item["id"];
220
360
  if (typeof id !== "string" || this.open.has(id)) return;
221
361
  // What was said before a tool call is not the closing message.
222
362
  this.text = "";
223
- const name = toolNameOf(call);
224
- if (name === "image_gen") this.seenImages.add(id);
363
+ const name = toolNameOf(item);
364
+ if (isImageGen(item)) this.seenImages.add(id);
225
365
  const at = this.options.now();
226
- const summary = summarizeCall(this.options.profile, name, inputOf(name, call), this.options.cwd, {
366
+ const summary = summarizeCall(this.options.profile, name, inputOf(item), this.options.cwd, {
227
367
  secrets: this.options.secrets,
228
368
  keepLines: true,
229
369
  });
@@ -237,27 +377,21 @@ export class CodexLog {
237
377
  ...(summary === undefined ? {} : { input: summary }),
238
378
  });
239
379
  // A call that arrives already settled is also over.
240
- if (terminal(call["status"])) this.end(id, call);
380
+ if (terminal(item)) this.end(item);
241
381
  }
242
382
 
243
- private update(update: Readonly<Record<string, unknown>>): void {
244
- const id = update["toolCallId"];
383
+ private end(item: Readonly<Record<string, unknown>>): void {
384
+ const id = item["id"];
245
385
  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
386
  const call = this.open.get(id);
255
387
  if (call === undefined) return;
256
388
  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));
389
+ const output = outputOf(item, this.outputs.get(id) ?? "", this.patches.get(id));
390
+ this.outputs.delete(id);
391
+ this.patches.delete(id);
392
+ const failed = failedOf(item);
393
+ if (output.length > 0) {
394
+ const head = capToolOutput(maskSecrets(output, this.options.secrets));
261
395
  this.line({
262
396
  type: "tool_output",
263
397
  toolCallId: id,
@@ -267,20 +401,21 @@ export class CodexLog {
267
401
  }
268
402
  const error =
269
403
  failed && !call.denied
270
- ? firstErrorLine(text.length > 0 ? text : "the call failed", { secrets: this.options.secrets })
404
+ ? firstErrorLine(output.length > 0 ? output : "the call failed", { secrets: this.options.secrets })
271
405
  : undefined;
406
+ const duration = item["durationMs"];
272
407
  this.line({
273
408
  type: "tool_execution_end",
274
409
  toolCallId: id,
275
410
  toolName: call.name,
276
411
  isError: failed,
277
- durationMs: Math.max(0, this.options.now() - call.at),
412
+ durationMs: typeof duration === "number" ? Math.max(0, duration) : Math.max(0, this.options.now() - call.at),
278
413
  ...(error === undefined ? {} : { error }),
279
414
  });
280
415
  }
281
416
 
282
- /** Writes the closing `message_end` line of the prompt. */
283
- finish(stopReason: string, usage: AcpUsage | null): void {
417
+ /** Writes the closing `message_end` line of the turn. */
418
+ finish(stopReason: string, usage: AppServerUsage | null): void {
284
419
  const said = messageSummary(this.text);
285
420
  this.line({
286
421
  type: "message_end",