@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/index.ts CHANGED
@@ -1,105 +1,115 @@
1
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`
2
+ * The codex harness: one `agent` step that starts the user's own
3
+ * `codex app-server` and speaks its JSON-RPC over stdio (ADR 0022 D3, D8),
4
+ * plus the `codex:prompt` flow. The step has the params, result names and
5
+ * facts of `pi/agent` and `claude/agent`, so a flow changes harness by
6
+ * changing `use`. The client is this package's `AppServerClient`; `runAgent`
7
7
  * owns the process, the wall time and the stall limit.
8
8
  */
9
9
 
10
+ import { messageOf } from "@operad-io/engine";
10
11
  import pkg from "../package.json" with { type: "json" };
11
- import { readProfile, secretValuesOf, summarizeCall, type AccessProfile } from "@operad-io/access-match";
12
+ import { liveAccess, readProfile, summarizeCall, type AccessProfile } from "@operad-io/access-match";
12
13
  import {
13
14
  isRecord,
14
- paramsObject,
15
- defineFlow,
16
15
  definePlugin,
16
+ type OutwardWrite,
17
17
  type PluginStepResult,
18
18
  type StepContext,
19
19
  } from "@operad-io/engine";
20
20
  import {
21
- ALLOW_ALWAYS,
22
- AcpClient,
23
- accessWithAlwaysAllow,
24
- alwaysAllowFromGrant,
25
- appendAlwaysAllow,
21
+ answerFor,
26
22
  askNote,
23
+ askQuestions,
24
+ askedForm,
25
+ isSkipped,
27
26
  createCallAsker,
28
27
  CONCURRENCY_SETTING,
28
+ createCachedProbe,
29
+ DEFAULT_STALL_SECS,
30
+ DEFAULT_WALL_TIME_SECS,
29
31
  deliverLine,
30
- directoryError,
31
32
  eventNote,
32
33
  flagValue,
33
34
  imageInputsOf,
35
+ inboxOf,
34
36
  JsonlLog,
37
+ MAX_WALL_TIME_SECS,
35
38
  mountedServersOf,
36
39
  modelErrorOf,
37
40
  modelLimit,
38
41
  OPERAD_SERVER,
39
42
  operadToolsOf,
40
- optionalText,
41
43
  parseStepFlags,
42
- personStarted,
43
- readAlwaysAllow,
44
- readImage,
44
+ promptFlowOf,
45
+ promptWithSkills,
46
+ readAgentStep,
45
47
  resultFor,
46
48
  runAgent,
47
- secs,
49
+ skippedLineRecord,
48
50
  serverCommand,
49
- standardUsage,
51
+ STALL_SETTING,
52
+ STEP_TIMEOUT_SECS,
50
53
  stringListParam,
51
54
  systemClock,
52
55
  text,
53
- type AcpEnd,
54
- type AcpError,
56
+ WALL_TIME_SETTING,
57
+ withTimings,
55
58
  type AgentWorkerResult,
56
59
  type CallAnswer,
57
60
  type Clock,
58
- type UsageSource,
59
61
  } from "@operad-io/harness-process";
60
62
  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;
63
+ import {
64
+ AppServerClient,
65
+ personQuestions,
66
+ type AppServerEnd,
67
+ type AppServerError,
68
+ type AppServerMcpServer,
69
+ } from "./app-server.ts";
70
+ import { CODEX_FLOOR, codexCommand, codexModels, codexSignedIn, commandOf, inspectCodex, refreshCodexModels } from "./install.ts";
71
+ import { CodexLog, toolNameOf } from "./log.ts";
72
+
73
+ export {
74
+ DEFAULT_STALL_SECS,
75
+ DEFAULT_WALL_TIME_SECS,
76
+ MAX_WALL_TIME_SECS,
77
+ STEP_TIMEOUT_SECS,
78
+ };
76
79
 
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;
80
+ /** How long the answer of `codex login status` is kept before it is asked again. */
81
+ export const SIGNED_IN_CACHE_MS = 30_000;
79
82
 
80
- /** How long codex-acp has to answer `session/cancel` before the step ends it. */
83
+ /** How long `codex app-server` has to answer `turn/interrupt` before the step ends it. */
81
84
  export const CANCEL_GRACE_MS = 10_000;
82
85
 
83
86
  /** The name the plugin goes by in usage and limit keys. */
84
87
  const HARNESS = "codex";
85
88
 
86
- /** The reasoning efforts Codex knows; codex-acp refuses one the chosen model does not support. */
89
+ /** The reasoning efforts Codex knows; a model the chosen model does not support refuses it. */
87
90
  export const EFFORT_LEVELS = ["minimal", "low", "medium", "high", "xhigh"] as const;
88
91
 
89
92
  /**
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.
93
+ * The sandbox a run uses. `workspace-write` is Codex's own sandbox with write
94
+ * access to the task's worktree (the thread's `cwd`) and no access outside it.
95
+ * Its network is off, but Codex asks before it leaves the sandbox: a command
96
+ * that needs the network arrives as an approval request, and the access
97
+ * profile answers it (a request for the network is allowed once, since the
98
+ * task needs it). `read-only` cannot write the worktree; `danger-full-access`
99
+ * turns the sandbox off.
100
+ */
101
+ export const SANDBOX_MODE = "workspace-write";
102
+
103
+ /**
104
+ * The approval policy that makes Codex ask operad instead of deciding:
105
+ * `on-request` sends a request when Codex wants to leave its sandbox or needs
106
+ * more permission, and `approvalsReviewer: "user"` routes it to this client
107
+ * rather than Codex's own reviewer. `never` would let Codex decide, and `auto_review`
108
+ * would put a subagent in the access profile's place.
98
109
  */
99
- export const SESSION_MODE = "workspace-write";
110
+ export const APPROVAL_POLICY = "on-request";
100
111
 
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;
112
+ /** The efforts a chat may pick with this agent: none; Codex's own default is used. */
103
113
  export const CODEX_EFFORTS = { list: [], default: null, flag: "--effort" } as const;
104
114
 
105
115
  /** The settings a config.json section may set for this plugin. */
@@ -108,34 +118,26 @@ export const PLUGIN_SETTINGS = {
108
118
  properties: {
109
119
  model: {
110
120
  type: "string" as const,
121
+ title: "Model",
111
122
  minLength: 1,
112
123
  description: "The model name codex takes; unset uses Codex's own default.",
113
124
  },
114
125
  effort: {
115
126
  type: "string" as const,
127
+ title: "Effort",
116
128
  enum: EFFORT_LEVELS,
117
129
  description: "The reasoning effort; unset uses Codex's own default.",
118
130
  },
119
131
  command: {
120
132
  type: "array" as const,
133
+ title: "Codex command",
121
134
  minItems: 1,
122
135
  items: { type: "string" as const, minLength: 1 },
123
136
  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.",
137
+ "The program and arguments that start codex app-server, such as [\"codex\", \"app-server\"]. Unset finds the codex of PATH and starts its app-server.",
138
138
  },
139
+ wallTimeSecs: WALL_TIME_SETTING,
140
+ stallSecs: STALL_SETTING,
139
141
  concurrency: CONCURRENCY_SETTING,
140
142
  },
141
143
  additionalProperties: false as const,
@@ -153,8 +155,8 @@ export interface CodexHarnessOptions {
153
155
  readonly codex?: readonly string[] | undefined;
154
156
  }
155
157
 
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
+ /** The Codex error info of an error: a string, or the key of an object. */
159
+ function errorInfo(error: AppServerError): string | undefined {
158
160
  const data = error.data;
159
161
  if (!isRecord(data)) return undefined;
160
162
  const info = data["codexErrorInfo"];
@@ -163,110 +165,152 @@ function errorInfo(error: AcpError): string | undefined {
163
165
  return undefined;
164
166
  }
165
167
 
166
- function errorText(error: AcpError): string {
168
+ function errorText(error: AppServerError): string {
167
169
  const data = error.data;
168
170
  if (isRecord(data) && typeof data["message"] === "string" && data["message"].length > 0) return data["message"];
169
171
  return error.message;
170
172
  }
171
173
 
172
- /** How one ACP error ends the step: the reason, the message and, for a model that cannot serve, the model error. */
174
+ /** How one app-server error ends the step: the reason, the message and, for a model that cannot serve, the model error. */
173
175
  export interface Failure {
174
176
  readonly reason: string;
175
177
  readonly message: string;
176
- readonly modelError?: { readonly kind: string };
178
+ readonly modelError?: NonNullable<AgentWorkerResult["modelError"]>;
179
+ }
180
+
181
+ /** A model error of one kind, carrying the status and wait its message names. */
182
+ function modelErrorFrom(
183
+ kind: string,
184
+ message: string,
185
+ ): NonNullable<AgentWorkerResult["modelError"]> {
186
+ const byText = modelErrorOf(message);
187
+ return {
188
+ kind,
189
+ status: typeof byText["status"] === "number" ? byText["status"] : null,
190
+ retry_after_secs:
191
+ typeof byText["retry_after_secs"] === "number"
192
+ ? byText["retry_after_secs"]
193
+ : null,
194
+ };
195
+ }
196
+
197
+ /** The model error of an app-server error kind, or undefined when it is not a model error. */
198
+ function modelFailure(info: string | undefined, message: string): Failure | undefined {
199
+ if (info === "usageLimitExceeded" || info === "rateLimitExceeded" || info === "contextWindowExceeded" || info === "sessionBudgetExceeded") {
200
+ return { reason: "model_error", message, modelError: modelErrorFrom("usage_limit", message) };
201
+ }
202
+ if (
203
+ info === "serverOverloaded" ||
204
+ info === "modelNotFound" ||
205
+ info === "flexUnavailable" ||
206
+ info === "policyCapacityUnavailable"
207
+ ) {
208
+ return { reason: "model_error", message, modelError: modelErrorFrom("unavailable", message) };
209
+ }
210
+ if (info === "unauthorized") {
211
+ return { reason: "not_logged_in", message: "Codex is not logged in; run `codex login` first" };
212
+ }
213
+ return undefined;
177
214
  }
178
215
 
179
216
  /**
180
- * Maps an error of codex-acp to the step's failure. An exhausted ChatGPT quota
217
+ * Maps an app-server failure to the step's failure. An exhausted ChatGPT quota
181
218
  * (`usageLimitExceeded`, a rate limit) is `usage_limit` and an unavailable
182
- * model (a model the session refuses, an overloaded service) is `unavailable`,
219
+ * model (a model the server refuses, an overloaded service) is `unavailable`,
183
220
  * the model errors dev's `retry_wait` and pool's fallbacks act on.
184
221
  */
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") {
222
+ export function failureOf(end: AppServerEnd, model: string | undefined): Failure {
223
+ if (end.kind === "error") {
224
+ const info = errorInfo(end.error);
225
+ const message = errorText(end.error);
226
+ const mapped = modelFailure(info, message);
227
+ if (mapped !== undefined) {
228
+ if (mapped.reason === "model_error" && end.stage === "session" && model !== undefined) {
229
+ return { ...mapped, message: `Codex does not offer the model ${model}: ${message}` };
230
+ }
231
+ return mapped;
232
+ }
233
+ if (end.stage === "session") {
234
+ if (/resume|thread|session/i.test(message)) return { reason: "session_missing", message };
235
+ return { reason: "protocol", message: `Codex failed to start a thread: ${message}` };
236
+ }
237
+ if (end.stage === "prompt") {
238
+ if (/effort|reasoning/i.test(message)) {
239
+ return { reason: "invalid_args", message: `Codex refused the reasoning effort: ${message}` };
240
+ }
241
+ const byText = modelErrorOf(message);
199
242
  return {
200
243
  reason: "model_error",
201
- message: `codex-acp does not offer the model ${model ?? "asked for"}: ${message}`,
202
- modelError: { kind: "unavailable" },
244
+ message,
245
+ modelError: modelErrorFrom(String(byText["kind"]), message),
203
246
  };
204
247
  }
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}` };
248
+ return { reason: "protocol", message: `Codex failed at ${end.stage}: ${message}` };
209
249
  }
210
- if (end.stage === "prompt") {
211
- const mapped = modelErrorOf(message);
250
+ const error = end.error;
251
+ if (error !== null) {
252
+ const info = errorInfo(error);
253
+ const message = errorText(error);
254
+ const mapped = modelFailure(info, message);
255
+ if (mapped !== undefined) return mapped;
256
+ const byText = modelErrorOf(message);
212
257
  return {
213
258
  reason: "model_error",
214
259
  message,
215
- modelError: { kind: String(mapped["kind"]) },
260
+ modelError: modelErrorFrom(String(byText["kind"]), message),
216
261
  };
217
262
  }
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}` };
263
+ return { reason: "stop_reason", message: `Codex stopped the turn: ${end.stopReason}` };
222
264
  }
223
265
 
224
266
  /** Creates the codex harness plugin. */
225
267
  export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
226
268
  const clock = options.clock ?? systemClock;
227
269
  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
- ],
270
+ // `codex login status` runs a child process, so its answer is kept for a
271
+ // short time and asked without blocking serve. The key is known before the
272
+ // command is found, so a cached answer does no file work.
273
+ const signedInProbe = createCachedProbe<boolean | undefined>({
274
+ now,
275
+ ttlMs: SIGNED_IN_CACHE_MS,
262
276
  });
263
277
 
278
+ async function codexSignedInCached(): Promise<boolean | undefined> {
279
+ const key = options.codex?.join("\u0000") ?? `PATH:${process.env.PATH ?? ""}`;
280
+ return await signedInProbe(key, async () => {
281
+ const bun = Bun.which("bun") ?? process.execPath;
282
+ return await codexSignedIn(options.codex ?? codexCommand(bun));
283
+ });
284
+ }
285
+
286
+ const promptFlow = promptFlowOf("codex:prompt", "codex/agent");
287
+
264
288
  return definePlugin({
265
289
  name: HARNESS,
266
290
  kind: "harness",
267
291
  version: pkg.version,
268
- models: CODEX_MODELS,
292
+ // The app-server's own model list, kept for a short time; a chat may pick
293
+ // any of them and the step's `--model` still wins.
294
+ models: (settings) => {
295
+ try {
296
+ return codexModels(commandOf(settings.command));
297
+ } catch {
298
+ return { list: [], default: null };
299
+ }
300
+ },
301
+ // A first reply may wait for the one refresh the cache already shares.
302
+ modelsReady: async (settings) => {
303
+ try {
304
+ const command = commandOf(settings.command);
305
+ const kept = codexModels(command);
306
+ return kept.list.length > 0 ? kept : await refreshCodexModels(command);
307
+ } catch {
308
+ return { list: [], default: null };
309
+ }
310
+ },
269
311
  efforts: CODEX_EFFORTS,
312
+ capabilities: { takesMessagesMidRun: true },
313
+ signedIn: (_settings: Readonly<Record<string, unknown>>) => codexSignedInCached(),
270
314
  settings: PLUGIN_SETTINGS,
271
315
  steps: [
272
316
  {
@@ -275,7 +319,7 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
275
319
  resumable: true,
276
320
  // `waiting`: a question about a call was not answered within the grace.
277
321
  results: ["done", "failed", "interrupted", "waiting"],
278
- // Applied to the calls codex-acp asks permission for. Codex's own
322
+ // Applied to the calls the app-server asks operad about. Codex's own
279
323
  // sandbox runs the calls inside it without asking; those are bounded
280
324
  // by the sandbox, not by these rules.
281
325
  enforces: ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "alwaysAllow"],
@@ -288,117 +332,73 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
288
332
  }),
289
333
  async run(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
290
334
  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
- }
335
+ let promptText = "";
336
+ let skills: readonly string[] = [];
337
+ let command: readonly string[] = [];
338
+ let program = "";
339
+ let mcpServers: AppServerMcpServer[] = [];
340
+ let inputEntries: Record<string, unknown>[] = [];
341
+
342
+ const step = await readAgentStep(ctx, params, {
343
+ at,
344
+ harness: HARNESS,
345
+ flags: STEP_FLAGS,
346
+ defaultWallTimeSecs: DEFAULT_WALL_TIME_SECS,
347
+ defaultStallSecs: DEFAULT_STALL_SECS,
348
+ maxWallTimeSecs: MAX_WALL_TIME_SECS,
349
+ levelSetting: "effort",
350
+ now,
351
+ refusalExtra: { imageGenCalls: 0 },
352
+ early(input, flow) {
353
+ skills = stringListParam(
354
+ input.skills === undefined ? flow.skills : input.skills,
355
+ `${at}: params.skills`,
356
+ );
357
+ },
358
+ afterDirectory(read) {
359
+ promptText = [promptWithSkills(read.prompt, skills), read.note, read.answerNote]
360
+ .filter((part): part is string => part !== undefined)
361
+ .join("\n\n");
376
362
 
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
363
  try {
383
- await appendAlwaysAllow(ctx.home, entry);
364
+ command = commandOf(ctx.settings.command);
384
365
  } 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
- );
366
+ return read.refuse("missing", messageOf(error));
388
367
  }
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
- }
368
+ program = command[0] ?? "";
369
+
370
+ const operadTools = operadToolsOf(read.input.operadTools ?? read.flow.operadTools);
371
+ const mounted = mountedServersOf(read.input.mcpServers ?? read.flow.mcpServers);
372
+ mcpServers = [];
373
+ if (operadTools !== undefined) {
374
+ const server = serverCommand(operadTools);
375
+ mcpServers.push({
376
+ name: OPERAD_SERVER,
377
+ command: server.command,
378
+ args: [...server.args],
379
+ env: { OPERAD_HOME: operadTools.home },
380
+ });
381
+ }
382
+ for (const [name, server] of Object.entries(mounted ?? {})) {
383
+ mcpServers.push({ name, command: server.command, args: [...server.args] });
384
+ }
385
+ const images = imageInputsOf(read.input.images ?? read.flow.images);
386
+ inputEntries = [{ type: "text", text: promptText, text_elements: [] }];
387
+ for (const image of images) {
388
+ // Codex reads the file itself; the harness sends the path.
389
+ inputEntries.push({ type: "localImage", path: image.path });
390
+ }
391
+ },
392
+ });
393
+ if ("refused" in step) return step.refused;
394
+
395
+ const { values, access } = step;
396
+ const { timings, cwd, resumeSession, wallTimeSecs, stallSecs, model, level: effort } = values;
397
+ const { runAccess, allowAlways, secrets: storeSecrets } = access;
397
398
  const read = readProfile(runAccess ?? {});
398
- const profile: AccessProfile = read.ok ? read.profile : {};
399
+ const startProfile: AccessProfile = read.ok ? read.profile : {};
399
400
 
400
- const started = Date.now();
401
- const jsonl = new JsonlLog(ctx.logger, clock);
401
+ const jsonl = new JsonlLog(ctx.logger, clock, now);
402
402
  const stopper = new AbortController();
403
403
  const endRun = (): void => stopper.abort();
404
404
 
@@ -407,6 +407,7 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
407
407
  onStop: endRun,
408
408
  secrets: storeSecrets,
409
409
  ...(allowAlways ? { alwaysAllow: { home: ctx.home, cwd } } : {}),
410
+ ...(ctx.flow === undefined ? {} : { targetGrants: { home: ctx.home, flow: ctx.flow } }),
410
411
  onLog: (message) => {
411
412
  void ctx.logger.write(message);
412
413
  },
@@ -416,27 +417,34 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
416
417
  // A full buffer makes the line reader wait for the disk.
417
418
  let writing: Promise<void> | undefined;
418
419
  const writeLine = (line: string): void => {
419
- const pending = jsonl.push(line);
420
+ const received = jsonl.stamp(line);
421
+ timings.record(received.value, received.at);
422
+ const pending = jsonl.pushStamped(received);
420
423
  if (pending !== undefined) writing = pending;
421
- deliverLine(ctx.receiver, line, storeSecrets);
424
+ deliverLine(ctx.receiver, received.text, storeSecrets);
422
425
  };
423
- let client: AcpClient | undefined;
426
+ let client: AppServerClient | undefined;
424
427
  const log = new CodexLog({
425
428
  write: writeLine,
426
429
  now,
427
430
  cwd,
428
- profile,
431
+ profile: startProfile,
429
432
  secrets: storeSecrets,
430
- active: () => client?.prompting === true,
433
+ active: () => client?.active === true,
431
434
  });
432
435
 
433
436
  const shown = (call: JudgedCall): string =>
434
- summarizeCall({}, call.tool, call.input, cwd, { secrets: storeSecrets, keepLines: true }) ?? call.tool;
437
+ summarizeCall({}, call.tool, call.input, cwd, {
438
+ secrets: storeSecrets,
439
+ keepLines: true,
440
+ forQuestion: true,
441
+ }) ?? call.tool;
435
442
 
436
443
  const ask = (question: {
437
444
  readonly kind: "command" | "path";
438
445
  readonly value: string;
439
446
  readonly tool?: string;
447
+ readonly outward?: OutwardWrite | undefined;
440
448
  readonly shown: string;
441
449
  }): Promise<CallAnswer> =>
442
450
  new Promise<CallAnswer>((resolve) => {
@@ -447,6 +455,7 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
447
455
  kind: question.kind,
448
456
  value: question.value,
449
457
  ...(question.tool === undefined ? {} : { tool: question.tool }),
458
+ ...(question.outward === undefined ? {} : { outward: question.outward }),
450
459
  shown: question.shown,
451
460
  session: client?.sessionId ?? null,
452
461
  });
@@ -467,42 +476,109 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
467
476
  });
468
477
  });
469
478
 
470
- const acp = new AcpClient({
479
+ const server = new AppServerClient({
471
480
  cwd,
472
- prompt: [{ type: "text", text: promptText }, ...imageBlocks],
481
+ prompt: inputEntries,
473
482
  ...(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
- ],
483
+ ...(model === undefined ? {} : { model }),
484
+ ...(effort === undefined ? {} : { effort }),
485
+ approvalPolicy: APPROVAL_POLICY,
486
+ sandbox: SANDBOX_MODE,
479
487
  ...(mcpServers.length === 0 ? {} : { mcpServers }),
480
488
  clientName: "operad",
481
- onUpdate: (update) => log.handle(update),
489
+ clientVersion: pkg.version,
490
+ onNotification: (method, params) => log.handle(method, params),
491
+ async onQuestion(request) {
492
+ // A secret answer would be kept in the pending item and the
493
+ // fact log, so its question is answered empty and never asked.
494
+ const answers: Record<string, readonly string[]> = {};
495
+ for (const question of request.questions) {
496
+ if (question.isSecret === true) answers[question.id] = [];
497
+ }
498
+ const asked = personQuestions(request);
499
+ const questions = askQuestions(
500
+ asked.map((question) => ({
501
+ id: question.id,
502
+ text: question.question,
503
+ ...(question.header === undefined ? {} : { header: question.header }),
504
+ ...(question.options === undefined ? {} : { choices: question.options }),
505
+ ...(question.isOther === true ? { freeText: true } : {}),
506
+ })),
507
+ );
508
+ if (questions.length === 0) return answers;
509
+ askId += 1;
510
+ const got = await askedForm(asker, askId, {
511
+ questions,
512
+ session: client?.sessionId ?? null,
513
+ });
514
+ if (got.decision === "stop") {
515
+ // The grace passed: the host ends this program, and the answer
516
+ // comes back to a resumed session as text.
517
+ return answers;
518
+ }
519
+ for (const question of questions) {
520
+ const answer = answerFor(got.answers, question.id);
521
+ answers[question.id] = isSkipped(answer)
522
+ ? []
523
+ : [...(answer?.choices ?? []), ...(answer?.text === undefined ? [] : [answer.text])];
524
+ }
525
+ return answers;
526
+ },
482
527
  async onPermission(request) {
483
- const decision = await decideAccess(profile, request.toolCall, cwd, {
528
+ const decision = await decideAccess(liveAccess(startProfile), request.method, request.params, request.item, cwd, {
484
529
  useGrant: (waitId) => ctx.useGrant(waitId),
485
530
  ask,
486
531
  shown,
487
532
  });
488
- if (!decision.allow) log.blocked(request.toolCall);
533
+ if (!decision.allow) {
534
+ const name =
535
+ request.item !== undefined
536
+ ? toolNameOf(request.item)
537
+ : request.method === "item/fileChange/requestApproval" || request.method === "applyPatchApproval"
538
+ ? "edit"
539
+ : "bash";
540
+ log.blocked(request.toolCallId, name);
541
+ }
489
542
  return decision.allow;
490
543
  },
491
544
  });
492
- client = acp;
545
+ client = server;
546
+ // The thread is open and the turn is about to be asked for.
547
+ void server.started.then(() => {
548
+ const opened = server.sessionId;
549
+ if (opened !== null) writeLine(JSON.stringify({ type: "session", sessionId: opened }));
550
+ });
493
551
 
494
- const state: { end: AcpEnd | undefined } = { end: undefined };
495
- void acp.ended.then((value) => {
552
+ // A message from the host steers the turn. Nothing is handed over
553
+ // before the turn id is known: the inbox keeps it until then, so a
554
+ // failed `turn/start` leaves the message for the next round instead
555
+ // of dropping it.
556
+ const inbox = inboxOf(params);
557
+ let stopInbox: (() => void) | undefined;
558
+ let inboxClosed = false;
559
+ if (inbox !== undefined) {
560
+ inbox.begin?.(wallTimeSecs * 1000);
561
+ void server.turnKnown.then(() => {
562
+ if (inboxClosed || server.finished) return;
563
+ stopInbox = inbox.listen((message) => {
564
+ if (server.finished) return false;
565
+ return server.steer(message);
566
+ });
567
+ });
568
+ }
569
+
570
+ const state: { end: AppServerEnd | undefined } = { end: undefined };
571
+ void server.ended.then((value) => {
496
572
  state.end = value;
497
573
  endRun();
498
574
  });
499
575
 
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.
576
+ // A cancel asks the app-server to interrupt the turn and waits for
577
+ // its answer; a server that does not answer within the grace is ended.
502
578
  let graceTimer: unknown;
503
579
  const onAbort = (): void => {
504
- if (acp.finished) return;
505
- if (!acp.cancel()) {
580
+ if (server.finished) return;
581
+ if (!server.cancel()) {
506
582
  endRun();
507
583
  return;
508
584
  }
@@ -515,18 +591,21 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
515
591
  command: program,
516
592
  args: command.slice(1),
517
593
  cwd,
518
- stdin: acp.first,
594
+ stdin: server.first,
519
595
  interactive: true,
520
596
  wallMs: wallTimeSecs * 1000,
521
597
  stallMs: stallSecs * 1000,
522
598
  signal: stopper.signal,
523
599
  clock,
524
600
  toolEvent: (line) => log.toolEvent(line),
601
+ onSkipped: (chars) => writeLine(skippedLineRecord(chars)),
525
602
  onLine(line, reply) {
526
- acp.handleLine(line, reply);
603
+ server.handleLine(line, reply);
527
604
  return writing;
528
605
  },
529
606
  });
607
+ inboxClosed = true;
608
+ stopInbox?.();
530
609
  ctx.signal.removeEventListener("abort", onAbort);
531
610
  if (graceTimer !== undefined) clock.clearTimeout(graceTimer);
532
611
 
@@ -539,7 +618,7 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
539
618
  throw unanswered.error;
540
619
  }
541
620
 
542
- const sessionId = acp.sessionId ?? resumeSession ?? null;
621
+ const sessionId = server.sessionId ?? resumeSession ?? null;
543
622
  let result: AgentWorkerResult | undefined;
544
623
  const end = state.end;
545
624
  if (end !== undefined) {
@@ -553,15 +632,40 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
553
632
  cache_write: usage?.cachedWriteTokens ?? undefined,
554
633
  };
555
634
  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 {
635
+ const context =
636
+ usage === null || usage === undefined
637
+ ? undefined
638
+ : {
639
+ used:
640
+ (usage.inputTokens ?? 0) +
641
+ (usage.cachedReadTokens ?? 0) +
642
+ (usage.cachedWriteTokens ?? 0),
643
+ ...(usage.modelContextWindow !== undefined && usage.modelContextWindow > 0
644
+ ? { window: usage.modelContextWindow }
645
+ : {}),
646
+ };
647
+ const base = {
648
+ type: "result" as const,
649
+ sessionId: end.sessionId.length > 0 ? end.sessionId : sessionId,
650
+ usage: counts,
651
+ cost: null,
652
+ finalMessage: closing,
653
+ model: model ?? null,
654
+ ...(context === undefined ? {} : { context }),
655
+ };
656
+ if (end.stopReason === "interrupted") {
657
+ result = { ...base, result: "cancelled" };
658
+ } else if (end.stopReason === "completed") {
659
+ result = { ...base, result: "done" };
660
+ } else {
661
+ const failed = failureOf(end, model);
560
662
  result = {
561
663
  ...base,
562
664
  result: "failed",
563
- reason: end.stopReason === "refusal" ? "refusal" : "stop_reason",
564
- message: `codex stopped the prompt: ${end.stopReason}`,
665
+ finalMessage: null,
666
+ reason: failed.reason,
667
+ message: failed.message,
668
+ ...(failed.modelError === undefined ? {} : { modelError: failed.modelError }),
565
669
  };
566
670
  }
567
671
  } else {
@@ -586,29 +690,31 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
586
690
  sessionId,
587
691
  usage: result.usage,
588
692
  cost: null,
693
+ ...(result.context === undefined ? {} : { context: result.context }),
589
694
  imageGenCalls: log.imageGenerations,
590
695
  }),
591
696
  );
592
697
  }
593
698
  await jsonl.end();
594
699
 
595
- // The run was ended on purpose once codex-acp had answered: the
700
+ // The run was ended on purpose once the app-server had answered: the
596
701
  // signal that did it is not the agent's.
597
702
  const settled =
598
703
  end === undefined ? outcome : { ...outcome, exitCode: 0, signal: null, cancelled: false };
704
+ const timing = timings.finish();
599
705
  const stepResult = resultFor(
600
706
  { harness: HARNESS, model: model ?? null },
601
707
  settled,
602
708
  result,
603
709
  ctx.logger.path,
604
- Date.now() - started,
710
+ timing.totalMs,
605
711
  { wallTimeSecs, stallSecs },
606
712
  program,
607
713
  );
608
- return {
714
+ return withTimings({
609
715
  ...stepResult,
610
716
  data: { ...(stepResult.data ?? {}), imageGenCalls: log.imageGenerations, stopReason: end?.kind === "stopped" ? end.stopReason : null },
611
- };
717
+ }, timing);
612
718
  },
613
719
  },
614
720
  ],
@@ -618,15 +724,14 @@ export function createCodexHarnessPlugin(options: CodexHarnessOptions = {}) {
618
724
  try {
619
725
  command = commandOf(ctx.settings.command);
620
726
  } catch (error) {
621
- throw new Error(error instanceof Error ? error.message : String(error));
727
+ throw new Error(messageOf(error));
622
728
  }
623
729
  const bun = Bun.which("bun") ?? process.execPath;
624
730
  const codex = options.codex ?? codexCommand(bun);
625
731
  const install = inspectCodex(command, codex);
626
732
  return (
627
- `codex-acp ${install.acpVersion} (${command.join(" ")}); ` +
628
- `codex ${install.codexVersion ?? "not found on PATH"}; ` +
629
- `login ${install.login ?? "unknown"}`
733
+ `codex ${install.codexVersion ?? "not found on PATH"} (${command.join(" ")}; ` +
734
+ `app-server, built against ${CODEX_FLOOR}); login ${install.login ?? "unknown"}`
630
735
  );
631
736
  },
632
737
  });