@ai-sdk/harness-codex 0.0.0-6b196531-20260710185421
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/CHANGELOG.md +391 -0
- package/LICENSE +13 -0
- package/README.md +73 -0
- package/dist/bridge/host-tool-mcp.mjs +103 -0
- package/dist/bridge/host-tool-mcp.mjs.map +1 -0
- package/dist/bridge/index.mjs +1297 -0
- package/dist/bridge/index.mjs.map +1 -0
- package/dist/bridge/package.json +12 -0
- package/dist/bridge/pnpm-lock.yaml +879 -0
- package/dist/index.d.ts +75 -0
- package/dist/index.js +899 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
- package/src/bridge/cli-relay.ts +198 -0
- package/src/bridge/codex-step-tracker.ts +83 -0
- package/src/bridge/host-tool-mcp.ts +160 -0
- package/src/bridge/index.ts +746 -0
- package/src/bridge/package.json +12 -0
- package/src/bridge/pnpm-lock.yaml +879 -0
- package/src/bridge/tool-relay-auth.ts +195 -0
- package/src/codex-auth.ts +119 -0
- package/src/codex-bridge-protocol.ts +38 -0
- package/src/codex-harness.ts +1132 -0
- package/src/index.ts +13 -0
- package/src/version.ts +6 -0
|
@@ -0,0 +1,1132 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import {
|
|
6
|
+
commonTool,
|
|
7
|
+
HarnessCapabilityUnsupportedError,
|
|
8
|
+
harnessV1DiagnosticFromBridgeFrame,
|
|
9
|
+
type HarnessV1,
|
|
10
|
+
type HarnessV1Bootstrap,
|
|
11
|
+
type HarnessV1DebugConfig,
|
|
12
|
+
type HarnessV1BuiltinTool,
|
|
13
|
+
type HarnessV1ContinueTurnState,
|
|
14
|
+
type HarnessV1Prompt,
|
|
15
|
+
type HarnessV1PromptControl,
|
|
16
|
+
type HarnessV1ResumeSessionState,
|
|
17
|
+
type HarnessV1NetworkSandboxSession,
|
|
18
|
+
type HarnessV1PermissionMode,
|
|
19
|
+
type HarnessV1Session,
|
|
20
|
+
type HarnessV1Skill,
|
|
21
|
+
type HarnessV1StreamPart,
|
|
22
|
+
} from '@ai-sdk/harness';
|
|
23
|
+
import {
|
|
24
|
+
classifyDiskLog,
|
|
25
|
+
createBridgeErrorHandler,
|
|
26
|
+
createBridgeStartupError,
|
|
27
|
+
drainBridgeProcessStream,
|
|
28
|
+
forwardBridgeProcessStream,
|
|
29
|
+
markBridgeStarting,
|
|
30
|
+
resolveSandboxHomeDir,
|
|
31
|
+
SandboxChannel,
|
|
32
|
+
shellQuote,
|
|
33
|
+
waitForBridgeReady,
|
|
34
|
+
writeSkills as writeHarnessSkills,
|
|
35
|
+
} from '@ai-sdk/harness/utils';
|
|
36
|
+
import {
|
|
37
|
+
type Experimental_SandboxProcess,
|
|
38
|
+
type Experimental_SandboxSession,
|
|
39
|
+
} from '@ai-sdk/provider-utils';
|
|
40
|
+
import { WebSocket } from 'ws';
|
|
41
|
+
import { z } from 'zod/v4';
|
|
42
|
+
import { resolveCodexEnv, type CodexAuthOptions } from './codex-auth';
|
|
43
|
+
import {
|
|
44
|
+
outboundMessageSchema,
|
|
45
|
+
type InboundMessage,
|
|
46
|
+
type OutboundMessage,
|
|
47
|
+
} from './codex-bridge-protocol';
|
|
48
|
+
import { CLI_SHIM_FILENAME } from './bridge/cli-relay';
|
|
49
|
+
import { VERSION } from './version';
|
|
50
|
+
|
|
51
|
+
type CodexChannel = SandboxChannel<OutboundMessage, InboundMessage>;
|
|
52
|
+
type CodexRespawnStrategy = 'replay' | 'rerun';
|
|
53
|
+
|
|
54
|
+
type WriteSkillsResult = {
|
|
55
|
+
readonly homeDir: string;
|
|
56
|
+
readonly codexHomeDir: string;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/*
|
|
60
|
+
* The model the adapter pins when the consumer configures none. The Codex SDK
|
|
61
|
+
* does not report the model it resolves to at runtime (no model field on any
|
|
62
|
+
* event), and exposes no default-model constant, so we pin the latest
|
|
63
|
+
* codex-specialized model available for the bundled `@openai/codex@0.130.0`
|
|
64
|
+
* (published 2026-05-08): `gpt-5.3-codex` (released 2026-02). Keep this in sync
|
|
65
|
+
* when bumping the codex SDK/binary. Passing it explicitly makes the resolved
|
|
66
|
+
* model deterministic and the telemetry (`gen_ai.request.model`) accurate.
|
|
67
|
+
*/
|
|
68
|
+
const DEFAULT_CODEX_MODEL = 'gpt-5.3-codex';
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Value to use in User-Agent and `x-client-app` headers.
|
|
72
|
+
*/
|
|
73
|
+
const CODEX_CLIENT_APP = `ai-sdk/harness-codex/${VERSION}`;
|
|
74
|
+
|
|
75
|
+
export type CodexHarnessSettings = {
|
|
76
|
+
readonly auth?: CodexAuthOptions;
|
|
77
|
+
/**
|
|
78
|
+
* OpenAI model id the underlying `codex` CLI should use. Leaving this unset
|
|
79
|
+
* pins the adapter default (`DEFAULT_CODEX_MODEL`).
|
|
80
|
+
*/
|
|
81
|
+
readonly model?: string;
|
|
82
|
+
/**
|
|
83
|
+
* Reasoning effort for reasoning-capable models. Leaving this unset
|
|
84
|
+
* defers to the CLI's default.
|
|
85
|
+
*/
|
|
86
|
+
readonly reasoningEffort?: 'low' | 'medium' | 'high';
|
|
87
|
+
/**
|
|
88
|
+
* When `true`, allow the underlying runtime to use live web search.
|
|
89
|
+
*/
|
|
90
|
+
readonly webSearch?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Override the port the bridge binds inside the sandbox. By default the
|
|
93
|
+
* adapter uses the first port the sandbox declares via `sandbox.ports`.
|
|
94
|
+
* Only set this if the sandbox declares multiple ports and the first one
|
|
95
|
+
* is reserved for something else.
|
|
96
|
+
*/
|
|
97
|
+
readonly port?: number;
|
|
98
|
+
/** Maximum milliseconds to wait for the bridge to advertise its port. Defaults to 120000. */
|
|
99
|
+
readonly startupTimeoutMs?: number;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/*
|
|
103
|
+
* Every native tool the Codex CLI can invoke as a model-callable tool,
|
|
104
|
+
* declared as a `ToolSet` keyed by what the bridge emits as `toolName` on
|
|
105
|
+
* the wire (`commonName ?? nativeName`). Schemas reflect the `ThreadItem`
|
|
106
|
+
* union in `@openai/codex-sdk`'s `dist/index.d.ts`.
|
|
107
|
+
*
|
|
108
|
+
* Codex's other native operations (`apply_patch`, todo planning) surface
|
|
109
|
+
* only as side-effect events (`file_change`, `todo_list`) and are not
|
|
110
|
+
* model-callable tools — they don't appear here.
|
|
111
|
+
*/
|
|
112
|
+
const CODEX_BUILTIN_TOOLS = {
|
|
113
|
+
bash: commonTool('bash', {
|
|
114
|
+
nativeName: 'shell',
|
|
115
|
+
toolUseKind: 'bash',
|
|
116
|
+
description: 'Execute a shell command',
|
|
117
|
+
inputSchema: z.object({ command: z.string() }),
|
|
118
|
+
}),
|
|
119
|
+
webSearch: commonTool('webSearch', {
|
|
120
|
+
nativeName: 'web_search',
|
|
121
|
+
toolUseKind: 'readonly',
|
|
122
|
+
description: 'Search the web',
|
|
123
|
+
inputSchema: z.object({ query: z.string() }),
|
|
124
|
+
}),
|
|
125
|
+
} as const satisfies Record<string, HarnessV1BuiltinTool<any, any>>;
|
|
126
|
+
|
|
127
|
+
/*
|
|
128
|
+
* Bootstrap lives in /tmp because it's pure derived state — the harness can
|
|
129
|
+
* reinstall the CLI and bridge files on any fresh sandbox from the recipe.
|
|
130
|
+
* Persistence comes from the sandbox provider's snapshot, not the path.
|
|
131
|
+
*
|
|
132
|
+
* The session work dir (`startOpts.sessionWorkDir`) lives under the sandbox's
|
|
133
|
+
* default working directory — the provider's persistent mount — so any files
|
|
134
|
+
* the agent edits survive both detach -> attach and stop -> snapshot -> resume
|
|
135
|
+
* cycles. Harness infra derived from `sandboxSession.defaultWorkingDirectory`
|
|
136
|
+
* lives under `.agent-runs`, outside the agent workdir.
|
|
137
|
+
*/
|
|
138
|
+
const BOOTSTRAP_DIR = '/tmp/harness/codex';
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Live bridge coordinates returned by `doDetach()` and `doSuspendTurn()`. A
|
|
142
|
+
* future process uses them to reopen a socket to the still-running bridge
|
|
143
|
+
* (`attach`) instead of re-spawning it. Absent on a `doStop()` payload.
|
|
144
|
+
*/
|
|
145
|
+
const codexBridgeCoordsSchema = z.object({
|
|
146
|
+
port: z.number(),
|
|
147
|
+
token: z.string(),
|
|
148
|
+
lastSeenEventId: z.number(),
|
|
149
|
+
sandboxId: z.string().optional(),
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Schema for the adapter-specific lifecycle `data` payload Codex produces.
|
|
154
|
+
* `threadId` is what `codex.resumeThread(...)` requires for the replay/rerun
|
|
155
|
+
* rungs; the sandbox lookup is handled separately via
|
|
156
|
+
* `provider.resumeSession({ sessionId })`. `bridge` carries live coordinates
|
|
157
|
+
* for cross-process `attach` (present on `doDetach()` and `doSuspendTurn()`
|
|
158
|
+
* payloads).
|
|
159
|
+
*/
|
|
160
|
+
const codexResumeStateSchema = z.object({
|
|
161
|
+
threadId: z.string().optional(),
|
|
162
|
+
bridge: codexBridgeCoordsSchema.optional(),
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
type CodexBridgeCoords = z.infer<typeof codexBridgeCoordsSchema>;
|
|
166
|
+
|
|
167
|
+
export function createCodex(
|
|
168
|
+
settings: CodexHarnessSettings = {},
|
|
169
|
+
): HarnessV1<typeof CODEX_BUILTIN_TOOLS> {
|
|
170
|
+
let cachedBootstrap: HarnessV1Bootstrap | undefined;
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
specificationVersion: 'harness-v1',
|
|
174
|
+
harnessId: 'codex',
|
|
175
|
+
builtinTools: CODEX_BUILTIN_TOOLS,
|
|
176
|
+
supportsBuiltinToolApprovals: false,
|
|
177
|
+
lifecycleStateSchema: codexResumeStateSchema,
|
|
178
|
+
getBootstrap: async () => {
|
|
179
|
+
if (cachedBootstrap != null) return cachedBootstrap;
|
|
180
|
+
const [pkg, lock, bridge, hostToolMcp] = await Promise.all([
|
|
181
|
+
readBridgeAsset('package.json'),
|
|
182
|
+
readBridgeAsset('pnpm-lock.yaml'),
|
|
183
|
+
readBridgeAsset('index.mjs'),
|
|
184
|
+
readBridgeAsset('host-tool-mcp.mjs'),
|
|
185
|
+
]);
|
|
186
|
+
cachedBootstrap = {
|
|
187
|
+
harnessId: 'codex',
|
|
188
|
+
bootstrapDir: BOOTSTRAP_DIR,
|
|
189
|
+
files: [
|
|
190
|
+
{ path: `${BOOTSTRAP_DIR}/package.json`, content: pkg },
|
|
191
|
+
{ path: `${BOOTSTRAP_DIR}/pnpm-lock.yaml`, content: lock },
|
|
192
|
+
{ path: `${BOOTSTRAP_DIR}/bridge.mjs`, content: bridge },
|
|
193
|
+
{
|
|
194
|
+
path: `${BOOTSTRAP_DIR}/host-tool-mcp.mjs`,
|
|
195
|
+
content: hostToolMcp,
|
|
196
|
+
},
|
|
197
|
+
],
|
|
198
|
+
commands: [
|
|
199
|
+
{ command: `mkdir -p ${BOOTSTRAP_DIR}` },
|
|
200
|
+
{
|
|
201
|
+
command: `pnpm --dir ${BOOTSTRAP_DIR} install --frozen-lockfile --store-dir ${BOOTSTRAP_DIR}/.pnpm-store`,
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
};
|
|
205
|
+
return cachedBootstrap;
|
|
206
|
+
},
|
|
207
|
+
doStart: async startOpts => {
|
|
208
|
+
if (startOpts.builtinToolFiltering != null) {
|
|
209
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
210
|
+
message:
|
|
211
|
+
"Harness 'codex' does not support built-in tool filtering controls.",
|
|
212
|
+
harnessId: 'codex',
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
if (
|
|
216
|
+
startOpts.permissionMode != null &&
|
|
217
|
+
startOpts.permissionMode !== 'allow-all'
|
|
218
|
+
) {
|
|
219
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
220
|
+
message:
|
|
221
|
+
"Harness 'codex' does not support built-in tool approval requests; use permissionMode: 'allow-all'.",
|
|
222
|
+
harnessId: 'codex',
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const sandboxSession = startOpts.sandboxSession;
|
|
226
|
+
const session = sandboxSession.restricted();
|
|
227
|
+
const sandboxId = sandboxSession.id;
|
|
228
|
+
const lifecycleState = startOpts.continueFrom ?? startOpts.resumeFrom;
|
|
229
|
+
const isResume = lifecycleState != null;
|
|
230
|
+
const isContinue = startOpts.continueFrom != null;
|
|
231
|
+
const resumeData =
|
|
232
|
+
isResume && typeof lifecycleState?.data === 'object'
|
|
233
|
+
? (lifecycleState.data as {
|
|
234
|
+
threadId?: unknown;
|
|
235
|
+
bridge?: CodexBridgeCoords;
|
|
236
|
+
})
|
|
237
|
+
: undefined;
|
|
238
|
+
const resumeThreadId = resumeData?.threadId;
|
|
239
|
+
const resumeThreadIdString =
|
|
240
|
+
typeof resumeThreadId === 'string' && resumeThreadId.length > 0
|
|
241
|
+
? resumeThreadId
|
|
242
|
+
: undefined;
|
|
243
|
+
const coords = resumeData?.bridge;
|
|
244
|
+
|
|
245
|
+
const workDir = startOpts.sessionWorkDir;
|
|
246
|
+
const sessionDataDir = `${sandboxSession.defaultWorkingDirectory}/.agent-runs/${startOpts.sessionId}`;
|
|
247
|
+
const bridgeStateDir = `${sessionDataDir}/bridge`;
|
|
248
|
+
const cliShimDir = `${sessionDataDir}/codex`;
|
|
249
|
+
const cliShimPath = `${cliShimDir}/${CLI_SHIM_FILENAME}`;
|
|
250
|
+
const timeoutMs = settings.startupTimeoutMs ?? 120_000;
|
|
251
|
+
|
|
252
|
+
// Normalize each forwarded bridge diagnostics frame into the general
|
|
253
|
+
// `HarnessV1Diagnostic` and report it. The adapter does no telemetry work
|
|
254
|
+
// beyond this transport→emission mapping.
|
|
255
|
+
const report = startOpts.observability?.report;
|
|
256
|
+
const onDiagnostic = report
|
|
257
|
+
? (frame: Parameters<typeof harnessV1DiagnosticFromBridgeFrame>[0]) =>
|
|
258
|
+
report(
|
|
259
|
+
harnessV1DiagnosticFromBridgeFrame(frame, {
|
|
260
|
+
sessionId: startOpts.sessionId,
|
|
261
|
+
timestamp: Date.now(),
|
|
262
|
+
}),
|
|
263
|
+
)
|
|
264
|
+
: undefined;
|
|
265
|
+
const onBridgeError = createBridgeErrorHandler({
|
|
266
|
+
harnessId: 'codex',
|
|
267
|
+
sessionId: startOpts.sessionId,
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
/*
|
|
271
|
+
* Rung 1 — ATTACH. With live coordinates, reopen a socket to the
|
|
272
|
+
* still-running bridge. Parked between-turn sessions just attach and wait
|
|
273
|
+
* for the next `start`; suspended in-flight turns request replay of
|
|
274
|
+
* everything past the persisted cursor. No spawn, no fresh token. If the
|
|
275
|
+
* bridge is gone the open throws and we fall through to a spawn-based
|
|
276
|
+
* recovery.
|
|
277
|
+
*/
|
|
278
|
+
if (coords) {
|
|
279
|
+
try {
|
|
280
|
+
const attachUrl =
|
|
281
|
+
(await sandboxSession.getPortUrl({
|
|
282
|
+
port: coords.port,
|
|
283
|
+
protocol: 'ws',
|
|
284
|
+
})) + `?agent_bridge_token=${encodeURIComponent(coords.token)}`;
|
|
285
|
+
const attachChannel: CodexChannel = new SandboxChannel({
|
|
286
|
+
connect: () => openWebSocket(attachUrl),
|
|
287
|
+
outboundSchema: outboundMessageSchema,
|
|
288
|
+
initialLastSeenEventId: coords.lastSeenEventId,
|
|
289
|
+
onDiagnostic,
|
|
290
|
+
onBridgeError,
|
|
291
|
+
});
|
|
292
|
+
await attachChannel.open(isContinue ? { resume: true } : undefined);
|
|
293
|
+
return createSession({
|
|
294
|
+
sessionId: startOpts.sessionId,
|
|
295
|
+
channel: attachChannel,
|
|
296
|
+
cliShimPath,
|
|
297
|
+
// The live bridge was spawned by another process; no process handle.
|
|
298
|
+
proc: undefined,
|
|
299
|
+
model: settings.model ?? DEFAULT_CODEX_MODEL,
|
|
300
|
+
reasoningEffort: settings.reasoningEffort,
|
|
301
|
+
webSearch: settings.webSearch,
|
|
302
|
+
resumeThreadId: resumeThreadIdString,
|
|
303
|
+
isResume: true,
|
|
304
|
+
seedResumeThreadOnFirstPrompt: false,
|
|
305
|
+
rerunContinue: false,
|
|
306
|
+
bridgePort: coords.port,
|
|
307
|
+
bridgeToken: coords.token,
|
|
308
|
+
sandboxId,
|
|
309
|
+
debug: startOpts.observability?.debug,
|
|
310
|
+
permissionMode: startOpts.permissionMode,
|
|
311
|
+
});
|
|
312
|
+
} catch {
|
|
313
|
+
// Bridge no longer reachable — recover by respawning below.
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/*
|
|
318
|
+
* Rungs 2/3 — REPLAY vs RERUN. Respawn the bridge. `replay` is only sound
|
|
319
|
+
* for `continueFrom`: those coordinates include the cursor the on-disk
|
|
320
|
+
* log is replayed *from*. `resumeFrom` is a between-turn resume; even when
|
|
321
|
+
* it carries bridge coordinates, replaying the previous turn would
|
|
322
|
+
* re-deliver stale events into the next turn. Those resumes always `rerun`
|
|
323
|
+
* via `codex.resumeThread(threadId)` when attach is unavailable.
|
|
324
|
+
*/
|
|
325
|
+
let respawnStrategy: CodexRespawnStrategy | undefined = isResume
|
|
326
|
+
? 'rerun'
|
|
327
|
+
: undefined;
|
|
328
|
+
if (coords && isContinue) {
|
|
329
|
+
const logRaw = await Promise.resolve(
|
|
330
|
+
session.readTextFile({
|
|
331
|
+
path: `${bridgeStateDir}/event-log.ndjson`,
|
|
332
|
+
abortSignal: startOpts.abortSignal,
|
|
333
|
+
}),
|
|
334
|
+
).catch(() => null);
|
|
335
|
+
if ((await classifyDiskLog(logRaw)) === 'replay') {
|
|
336
|
+
respawnStrategy = 'replay';
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const port = resolveBridgePort(sandboxSession, settings.port);
|
|
341
|
+
const token = randomBytes(32).toString('hex');
|
|
342
|
+
const codexSkillSetup =
|
|
343
|
+
startOpts.skills && startOpts.skills.length > 0
|
|
344
|
+
? await writeCodexSkills({
|
|
345
|
+
sandbox: session,
|
|
346
|
+
skills: startOpts.skills,
|
|
347
|
+
abortSignal: startOpts.abortSignal,
|
|
348
|
+
})
|
|
349
|
+
: undefined;
|
|
350
|
+
const env = {
|
|
351
|
+
...resolveCodexEnv(settings.auth),
|
|
352
|
+
AI_SDK_HARNESS_CLIENT_APP: CODEX_CLIENT_APP,
|
|
353
|
+
BRIDGE_CHANNEL_TOKEN: token,
|
|
354
|
+
BRIDGE_WS_PORT: String(port),
|
|
355
|
+
...(codexSkillSetup
|
|
356
|
+
? {
|
|
357
|
+
HOME: codexSkillSetup.homeDir,
|
|
358
|
+
CODEX_HOME: codexSkillSetup.codexHomeDir,
|
|
359
|
+
}
|
|
360
|
+
: {}),
|
|
361
|
+
...(respawnStrategy === 'replay'
|
|
362
|
+
? { BRIDGE_REPLAY_FROM_DISK: '1' }
|
|
363
|
+
: {}),
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
if (respawnStrategy === undefined) {
|
|
367
|
+
await session.run({
|
|
368
|
+
command: `mkdir -p ${shellQuote(workDir)} ${shellQuote(bridgeStateDir)}`,
|
|
369
|
+
abortSignal: startOpts.abortSignal,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
await markBridgeStarting({
|
|
374
|
+
sandbox: session,
|
|
375
|
+
bridgeStateDir,
|
|
376
|
+
bridgeType: 'codex',
|
|
377
|
+
abortSignal: startOpts.abortSignal,
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
const proc = await session.spawn({
|
|
381
|
+
command: `node ${BOOTSTRAP_DIR}/bridge.mjs --workdir ${shellQuote(workDir)} --bridge-state-dir ${shellQuote(bridgeStateDir)} --bootstrap-dir ${shellQuote(BOOTSTRAP_DIR)} --cli-shim-dir ${shellQuote(cliShimDir)}`,
|
|
382
|
+
env,
|
|
383
|
+
abortSignal: startOpts.abortSignal,
|
|
384
|
+
});
|
|
385
|
+
const stderrTail: string[] = [];
|
|
386
|
+
const bridgeStderrDone = forwardBridgeProcessStream({
|
|
387
|
+
stream: proc.stderr,
|
|
388
|
+
streamName: 'stderr',
|
|
389
|
+
source: 'codex',
|
|
390
|
+
collectTail: stderrTail,
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
const { port: boundPort } = await waitForBridgeReady({
|
|
394
|
+
proc,
|
|
395
|
+
sandbox: session,
|
|
396
|
+
bridgeStateDir,
|
|
397
|
+
bridgeType: 'codex',
|
|
398
|
+
timeoutMs,
|
|
399
|
+
abortSignal: startOpts.abortSignal,
|
|
400
|
+
createTimeoutError: ({ proc, stdoutTail }) =>
|
|
401
|
+
createBridgeStartupError({
|
|
402
|
+
message: 'codex bridge did not become ready in time.',
|
|
403
|
+
proc,
|
|
404
|
+
stdoutTail,
|
|
405
|
+
stderrTail,
|
|
406
|
+
stderrDone: bridgeStderrDone,
|
|
407
|
+
}),
|
|
408
|
+
createExitError: ({ proc, stdoutTail }) =>
|
|
409
|
+
createBridgeStartupError({
|
|
410
|
+
message: 'codex bridge exited before becoming ready.',
|
|
411
|
+
proc,
|
|
412
|
+
stdoutTail,
|
|
413
|
+
stderrTail,
|
|
414
|
+
stderrDone: bridgeStderrDone,
|
|
415
|
+
}),
|
|
416
|
+
});
|
|
417
|
+
void drainBridgeProcessStream(proc.stdout);
|
|
418
|
+
|
|
419
|
+
const wsUrl =
|
|
420
|
+
(await sandboxSession.getPortUrl({
|
|
421
|
+
port: boundPort,
|
|
422
|
+
protocol: 'ws',
|
|
423
|
+
})) + `?agent_bridge_token=${encodeURIComponent(token)}`;
|
|
424
|
+
|
|
425
|
+
const channel: CodexChannel = new SandboxChannel({
|
|
426
|
+
connect: () => openWebSocket(wsUrl),
|
|
427
|
+
outboundSchema: outboundMessageSchema,
|
|
428
|
+
onDiagnostic,
|
|
429
|
+
onBridgeError,
|
|
430
|
+
// In replay mode the respawned bridge reloaded the finished turn from
|
|
431
|
+
// disk; seed the cursor and resume so it streams the tail (incl.
|
|
432
|
+
// `finish`).
|
|
433
|
+
...(respawnStrategy === 'replay'
|
|
434
|
+
? { initialLastSeenEventId: coords?.lastSeenEventId ?? 0 }
|
|
435
|
+
: {}),
|
|
436
|
+
});
|
|
437
|
+
await channel.open(
|
|
438
|
+
respawnStrategy === 'replay' ? { resume: true } : undefined,
|
|
439
|
+
);
|
|
440
|
+
|
|
441
|
+
return createSession({
|
|
442
|
+
sessionId: startOpts.sessionId,
|
|
443
|
+
channel,
|
|
444
|
+
cliShimPath,
|
|
445
|
+
proc,
|
|
446
|
+
model: settings.model ?? DEFAULT_CODEX_MODEL,
|
|
447
|
+
reasoningEffort: settings.reasoningEffort,
|
|
448
|
+
webSearch: settings.webSearch,
|
|
449
|
+
resumeThreadId: resumeThreadIdString,
|
|
450
|
+
isResume: respawnStrategy !== undefined,
|
|
451
|
+
seedResumeThreadOnFirstPrompt: respawnStrategy !== undefined,
|
|
452
|
+
rerunContinue: respawnStrategy === 'rerun',
|
|
453
|
+
bridgePort: boundPort,
|
|
454
|
+
bridgeToken: token,
|
|
455
|
+
sandboxId,
|
|
456
|
+
debug: startOpts.observability?.debug,
|
|
457
|
+
permissionMode: startOpts.permissionMode,
|
|
458
|
+
});
|
|
459
|
+
},
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function resolveBridgePort(
|
|
464
|
+
sandboxSession: HarnessV1NetworkSandboxSession,
|
|
465
|
+
override: number | undefined,
|
|
466
|
+
): number {
|
|
467
|
+
if (override !== undefined) return override;
|
|
468
|
+
if (sandboxSession.ports.length > 0) return sandboxSession.ports[0];
|
|
469
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
470
|
+
harnessId: 'codex',
|
|
471
|
+
message:
|
|
472
|
+
'The codex harness needs a TCP port exposed by the sandbox. ' +
|
|
473
|
+
'Create the sandbox with `ports: [<port>]` or pass `createCodex({ port })`.',
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function readBridgeAsset(name: string): Promise<string> {
|
|
478
|
+
const candidates = [
|
|
479
|
+
new URL(`./bridge/${name}`, import.meta.url),
|
|
480
|
+
new URL(`../bridge/${name}`, import.meta.url),
|
|
481
|
+
];
|
|
482
|
+
let lastErr: unknown;
|
|
483
|
+
for (const url of candidates) {
|
|
484
|
+
try {
|
|
485
|
+
return await readFile(fileURLToPath(url), 'utf8');
|
|
486
|
+
} catch (err) {
|
|
487
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
488
|
+
if (code !== 'ENOENT') throw err;
|
|
489
|
+
lastErr = err;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
throw lastErr ?? new Error(`bridge asset not found: ${name}`);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function writeCodexSkills({
|
|
496
|
+
sandbox,
|
|
497
|
+
skills,
|
|
498
|
+
abortSignal,
|
|
499
|
+
}: {
|
|
500
|
+
sandbox: Experimental_SandboxSession;
|
|
501
|
+
skills: ReadonlyArray<HarnessV1Skill>;
|
|
502
|
+
abortSignal?: AbortSignal;
|
|
503
|
+
}): Promise<WriteSkillsResult> {
|
|
504
|
+
const homeDir = await resolveSandboxHomeDir({ sandbox, abortSignal });
|
|
505
|
+
const codexHomeDir = path.posix.join(homeDir, '.codex');
|
|
506
|
+
await sandbox.run({
|
|
507
|
+
command: `mkdir -p ${shellQuote(codexHomeDir)}`,
|
|
508
|
+
abortSignal,
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
const rootDir = path.posix.join(homeDir, '.agents', 'skills');
|
|
512
|
+
await writeHarnessSkills({
|
|
513
|
+
sandbox,
|
|
514
|
+
rootDir,
|
|
515
|
+
skills,
|
|
516
|
+
abortSignal,
|
|
517
|
+
invalidSkillNameMessage: ({ name }) => `Invalid Codex skill name: ${name}`,
|
|
518
|
+
invalidSkillFilePathMessage: ({ skillName, filePath }) =>
|
|
519
|
+
`Invalid Codex skill file path for ${skillName}: ${filePath}`,
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
return {
|
|
523
|
+
homeDir,
|
|
524
|
+
codexHomeDir,
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function openWebSocket(url: string): Promise<WebSocket> {
|
|
529
|
+
return new Promise((resolve, reject) => {
|
|
530
|
+
const ws = new WebSocket(url);
|
|
531
|
+
const onOpen = () => {
|
|
532
|
+
ws.off('error', onError);
|
|
533
|
+
resolve(ws);
|
|
534
|
+
};
|
|
535
|
+
const onError = (err: Error) => {
|
|
536
|
+
ws.off('open', onOpen);
|
|
537
|
+
reject(err);
|
|
538
|
+
};
|
|
539
|
+
ws.once('open', onOpen);
|
|
540
|
+
ws.once('error', onError);
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function createSession({
|
|
545
|
+
sessionId,
|
|
546
|
+
channel,
|
|
547
|
+
cliShimPath,
|
|
548
|
+
proc,
|
|
549
|
+
model,
|
|
550
|
+
reasoningEffort,
|
|
551
|
+
webSearch,
|
|
552
|
+
resumeThreadId,
|
|
553
|
+
isResume,
|
|
554
|
+
seedResumeThreadOnFirstPrompt,
|
|
555
|
+
rerunContinue,
|
|
556
|
+
bridgePort,
|
|
557
|
+
bridgeToken,
|
|
558
|
+
sandboxId,
|
|
559
|
+
debug,
|
|
560
|
+
permissionMode,
|
|
561
|
+
}: {
|
|
562
|
+
sessionId: string;
|
|
563
|
+
channel: CodexChannel;
|
|
564
|
+
cliShimPath: string;
|
|
565
|
+
/** Undefined on `attach` — the live bridge was spawned by another process. */
|
|
566
|
+
proc: Experimental_SandboxProcess | undefined;
|
|
567
|
+
model: string | undefined;
|
|
568
|
+
reasoningEffort: 'low' | 'medium' | 'high' | undefined;
|
|
569
|
+
webSearch: boolean | undefined;
|
|
570
|
+
resumeThreadId: string | undefined;
|
|
571
|
+
isResume: boolean;
|
|
572
|
+
seedResumeThreadOnFirstPrompt: boolean;
|
|
573
|
+
rerunContinue: boolean;
|
|
574
|
+
bridgePort: number;
|
|
575
|
+
bridgeToken: string;
|
|
576
|
+
sandboxId: string;
|
|
577
|
+
debug: HarnessV1DebugConfig | undefined;
|
|
578
|
+
permissionMode: HarnessV1PermissionMode | undefined;
|
|
579
|
+
}): HarnessV1Session {
|
|
580
|
+
let stopped = false;
|
|
581
|
+
let stopPromise: Promise<void> | undefined;
|
|
582
|
+
/*
|
|
583
|
+
* Send the persisted threadId on the first prompt only when the bridge was
|
|
584
|
+
* respawned (rerun/replay) so it takes the `codex.resumeThread(...)` branch.
|
|
585
|
+
* An `attach`ed bridge already holds its threadState in memory and continues
|
|
586
|
+
* on its own, so it needs no seed.
|
|
587
|
+
*/
|
|
588
|
+
let pendingResumeThreadId = seedResumeThreadOnFirstPrompt
|
|
589
|
+
? resumeThreadId
|
|
590
|
+
: undefined;
|
|
591
|
+
/*
|
|
592
|
+
* Initial prompt guidance is prepended to the first user message of a fresh
|
|
593
|
+
* session only. A resumed session (attach/replay/rerun) already carried it
|
|
594
|
+
* in its original first message (preserved in the persisted thread), so it
|
|
595
|
+
* starts "applied".
|
|
596
|
+
*/
|
|
597
|
+
let instructionsApplied = isResume;
|
|
598
|
+
|
|
599
|
+
/*
|
|
600
|
+
* Latest codex thread id, cached from the bridge's `bridge-thread`
|
|
601
|
+
* announcements. Seeded from lifecycle state so `doDetach()` and `doStop()`
|
|
602
|
+
* can include a thread id even before this process has run a turn.
|
|
603
|
+
*/
|
|
604
|
+
let latestThreadId = resumeThreadId;
|
|
605
|
+
channel.on('bridge-thread', msg => {
|
|
606
|
+
latestThreadId = msg.threadId;
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
/*
|
|
610
|
+
* Wire the channel into one turn's worth of events and return the control
|
|
611
|
+
* surface. Shared by `doPromptTurn` (which sends a `start` afterwards) and
|
|
612
|
+
* `doContinueTurn` (which attaches to an already-running/replayed turn, or sends
|
|
613
|
+
* a rerun `start`). The only difference between the two entry points is the
|
|
614
|
+
* `start` message, not the listener/abort/settle plumbing.
|
|
615
|
+
*/
|
|
616
|
+
const wireTurn = (turnOpts: {
|
|
617
|
+
emit: (event: HarnessV1StreamPart) => void;
|
|
618
|
+
abortSignal?: AbortSignal;
|
|
619
|
+
}): {
|
|
620
|
+
control: HarnessV1PromptControl;
|
|
621
|
+
sendStart: (send: () => void) => void;
|
|
622
|
+
} => {
|
|
623
|
+
let pendingResolve: (() => void) | undefined;
|
|
624
|
+
let pendingReject: ((err: unknown) => void) | undefined;
|
|
625
|
+
const done = new Promise<void>((resolve, reject) => {
|
|
626
|
+
pendingResolve = resolve;
|
|
627
|
+
pendingReject = reject;
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
const unsubs: Array<() => void> = [];
|
|
631
|
+
const forward = (event: HarnessV1StreamPart) => {
|
|
632
|
+
try {
|
|
633
|
+
turnOpts.emit(event);
|
|
634
|
+
} catch {}
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
const eventTypes = [
|
|
638
|
+
'stream-start',
|
|
639
|
+
'text-start',
|
|
640
|
+
'text-delta',
|
|
641
|
+
'text-end',
|
|
642
|
+
'reasoning-start',
|
|
643
|
+
'reasoning-delta',
|
|
644
|
+
'reasoning-end',
|
|
645
|
+
'tool-call',
|
|
646
|
+
'tool-approval-request',
|
|
647
|
+
'tool-result',
|
|
648
|
+
'file-change',
|
|
649
|
+
'finish-step',
|
|
650
|
+
'raw',
|
|
651
|
+
] as const;
|
|
652
|
+
let isSettled = false;
|
|
653
|
+
const settleSuccess = () => {
|
|
654
|
+
if (isSettled) return;
|
|
655
|
+
isSettled = true;
|
|
656
|
+
for (const u of unsubs) u();
|
|
657
|
+
pendingResolve!();
|
|
658
|
+
};
|
|
659
|
+
const settleError = (err: unknown) => {
|
|
660
|
+
if (isSettled) return;
|
|
661
|
+
isSettled = true;
|
|
662
|
+
for (const u of unsubs) u();
|
|
663
|
+
pendingReject!(err);
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
for (const type of eventTypes) {
|
|
667
|
+
unsubs.push(
|
|
668
|
+
channel.on(type, msg => {
|
|
669
|
+
forward(msg);
|
|
670
|
+
}),
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
unsubs.push(
|
|
674
|
+
channel.on('finish', msg => {
|
|
675
|
+
forward(msg);
|
|
676
|
+
settleSuccess();
|
|
677
|
+
}),
|
|
678
|
+
);
|
|
679
|
+
unsubs.push(
|
|
680
|
+
channel.on('error', msg => {
|
|
681
|
+
forward(msg);
|
|
682
|
+
settleError(msg.error);
|
|
683
|
+
}),
|
|
684
|
+
);
|
|
685
|
+
|
|
686
|
+
/*
|
|
687
|
+
* A `'suspended'` close is a graceful slice-boundary freeze the host
|
|
688
|
+
* initiated (`doSuspendTurn`): the turn keeps running in the bridge and its
|
|
689
|
+
* tail is replayed to the next process, so wind this turn down cleanly
|
|
690
|
+
* rather than failing it. Any other close mid-turn is an unexpected drop.
|
|
691
|
+
*/
|
|
692
|
+
const onClose = (_code?: number, reason?: string) => {
|
|
693
|
+
if (isSettled) return;
|
|
694
|
+
if (reason === 'suspended') {
|
|
695
|
+
settleSuccess();
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
settleError(new Error('codex bridge closed before the turn finished.'));
|
|
699
|
+
};
|
|
700
|
+
channel.onClose(onClose);
|
|
701
|
+
|
|
702
|
+
const onAbort = () => {
|
|
703
|
+
if (isSettled) return;
|
|
704
|
+
try {
|
|
705
|
+
channel.send({ type: 'abort' });
|
|
706
|
+
} catch {}
|
|
707
|
+
settleError(
|
|
708
|
+
turnOpts.abortSignal?.reason ??
|
|
709
|
+
new DOMException('Aborted', 'AbortError'),
|
|
710
|
+
);
|
|
711
|
+
};
|
|
712
|
+
if (turnOpts.abortSignal) {
|
|
713
|
+
if (turnOpts.abortSignal.aborted) {
|
|
714
|
+
onAbort();
|
|
715
|
+
} else {
|
|
716
|
+
turnOpts.abortSignal.addEventListener('abort', onAbort, {
|
|
717
|
+
once: true,
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const control: HarnessV1PromptControl = {
|
|
723
|
+
submitToolResult: async input => {
|
|
724
|
+
channel.send({
|
|
725
|
+
type: 'tool-result',
|
|
726
|
+
toolCallId: input.toolCallId,
|
|
727
|
+
output: input.output,
|
|
728
|
+
isError: input.isError,
|
|
729
|
+
});
|
|
730
|
+
},
|
|
731
|
+
submitToolApproval: async input => {
|
|
732
|
+
channel.send({
|
|
733
|
+
type: 'tool-approval-response',
|
|
734
|
+
approvalId: input.approvalId,
|
|
735
|
+
approved: input.approved,
|
|
736
|
+
reason: input.reason,
|
|
737
|
+
});
|
|
738
|
+
},
|
|
739
|
+
submitUserMessage: async text => {
|
|
740
|
+
channel.send({ type: 'user-message', text });
|
|
741
|
+
},
|
|
742
|
+
done,
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
return {
|
|
746
|
+
control,
|
|
747
|
+
sendStart: send => {
|
|
748
|
+
/*
|
|
749
|
+
* Codex can complete short turns without using tools. Deferring the
|
|
750
|
+
* start frame gives the harness runner one event-loop turn to finish
|
|
751
|
+
* wiring the prompt control and stream output before Codex can settle.
|
|
752
|
+
*/
|
|
753
|
+
const timer = setTimeout(() => {
|
|
754
|
+
if (isSettled) return;
|
|
755
|
+
try {
|
|
756
|
+
send();
|
|
757
|
+
} catch (err) {
|
|
758
|
+
settleError(err);
|
|
759
|
+
}
|
|
760
|
+
}, 0);
|
|
761
|
+
timer.unref?.();
|
|
762
|
+
},
|
|
763
|
+
};
|
|
764
|
+
};
|
|
765
|
+
|
|
766
|
+
return {
|
|
767
|
+
sessionId,
|
|
768
|
+
isResume,
|
|
769
|
+
modelId: model,
|
|
770
|
+
doPromptTurn: async promptOpts => {
|
|
771
|
+
const turn = wireTurn({
|
|
772
|
+
emit: promptOpts.emit,
|
|
773
|
+
abortSignal: promptOpts.abortSignal,
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
const tools = (promptOpts.tools ?? []).map(t => ({
|
|
777
|
+
name: t.name,
|
|
778
|
+
description: t.description,
|
|
779
|
+
inputSchema: t.inputSchema,
|
|
780
|
+
}));
|
|
781
|
+
let promptText = extractUserText(promptOpts.prompt);
|
|
782
|
+
if (!instructionsApplied) {
|
|
783
|
+
const instructions =
|
|
784
|
+
(promptOpts.instructions ? promptOpts.instructions + '\n\n' : '') +
|
|
785
|
+
'Only respond with your `final` message once you have fully addressed the user request.';
|
|
786
|
+
promptText = frameInitialPromptGuidance({
|
|
787
|
+
instructions,
|
|
788
|
+
toolUsageBlock:
|
|
789
|
+
tools.length > 0
|
|
790
|
+
? composeToolUsageInstructions({
|
|
791
|
+
tools,
|
|
792
|
+
cliShimPath,
|
|
793
|
+
})
|
|
794
|
+
: undefined,
|
|
795
|
+
userText: promptText,
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
instructionsApplied = true;
|
|
799
|
+
|
|
800
|
+
const startMessage = {
|
|
801
|
+
type: 'start' as const,
|
|
802
|
+
prompt: promptText,
|
|
803
|
+
tools,
|
|
804
|
+
model,
|
|
805
|
+
reasoningEffort,
|
|
806
|
+
webSearch,
|
|
807
|
+
...(permissionMode ? { permissionMode } : {}),
|
|
808
|
+
...(pendingResumeThreadId
|
|
809
|
+
? { resumeThreadId: pendingResumeThreadId }
|
|
810
|
+
: {}),
|
|
811
|
+
...(debug ? { debug } : {}),
|
|
812
|
+
};
|
|
813
|
+
pendingResumeThreadId = undefined;
|
|
814
|
+
turn.sendStart(() => channel.send(startMessage));
|
|
815
|
+
|
|
816
|
+
return turn.control;
|
|
817
|
+
},
|
|
818
|
+
doContinueTurn: async continueOpts => {
|
|
819
|
+
const turn = wireTurn({
|
|
820
|
+
emit: continueOpts.emit,
|
|
821
|
+
abortSignal: continueOpts.abortSignal,
|
|
822
|
+
});
|
|
823
|
+
|
|
824
|
+
/*
|
|
825
|
+
* attach / replay: the still-running (or disk-replayed) turn streams into
|
|
826
|
+
* the wired listeners — `doStart` opened the channel with `{ resume: true }`
|
|
827
|
+
* so the bridge replays everything past the persisted cursor (including a
|
|
828
|
+
* `finish` if the turn ended during the gap). No `start` is sent: issuing
|
|
829
|
+
* one would clear the bridge's replay log and begin a new turn. Lossless.
|
|
830
|
+
*
|
|
831
|
+
* rerun: the bridge was respawned with no in-flight turn to attach to, so
|
|
832
|
+
* re-drive codex's own thread via `resumeThreadId`. Lossy — work in flight
|
|
833
|
+
* at the interruption is recomputed. This is the rare bridge-died
|
|
834
|
+
* fallback; the common slice path is `attach`.
|
|
835
|
+
*/
|
|
836
|
+
if (rerunContinue) {
|
|
837
|
+
const threadId = pendingResumeThreadId ?? latestThreadId;
|
|
838
|
+
pendingResumeThreadId = undefined;
|
|
839
|
+
turn.sendStart(() =>
|
|
840
|
+
channel.send({
|
|
841
|
+
type: 'start' as const,
|
|
842
|
+
/*
|
|
843
|
+
* A continuation nudge rather than an empty prompt: `resumeThreadId`
|
|
844
|
+
* rehydrates the prior thread, and this is the new user turn that
|
|
845
|
+
* drives it forward. Keeping it non-empty avoids handing the runtime
|
|
846
|
+
* an empty user message (and mirrors the claude-code adapter, where an
|
|
847
|
+
* empty text block trips the Anthropic API's `cache_control` rule).
|
|
848
|
+
*/
|
|
849
|
+
prompt: 'Continue.',
|
|
850
|
+
tools: (continueOpts.tools ?? []).map(t => ({
|
|
851
|
+
name: t.name,
|
|
852
|
+
description: t.description,
|
|
853
|
+
inputSchema: t.inputSchema,
|
|
854
|
+
})),
|
|
855
|
+
model,
|
|
856
|
+
reasoningEffort,
|
|
857
|
+
webSearch,
|
|
858
|
+
...(permissionMode ? { permissionMode } : {}),
|
|
859
|
+
...(threadId ? { resumeThreadId: threadId } : {}),
|
|
860
|
+
...(debug ? { debug } : {}),
|
|
861
|
+
}),
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
return turn.control;
|
|
866
|
+
},
|
|
867
|
+
doCompact: async () => {
|
|
868
|
+
/*
|
|
869
|
+
* Codex compacts its context automatically inside the core turn loop
|
|
870
|
+
* (~90% of the model context window), but the `codex exec` transport this
|
|
871
|
+
* adapter drives exposes no manual compaction trigger and emits no
|
|
872
|
+
* compaction event. Manual `compact()` is therefore unsupported; Codex's
|
|
873
|
+
* own auto-compaction continues to run regardless.
|
|
874
|
+
*/
|
|
875
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
876
|
+
message:
|
|
877
|
+
"Harness 'codex' does not support manual compaction; Codex auto-compacts its context internally.",
|
|
878
|
+
harnessId: 'codex',
|
|
879
|
+
});
|
|
880
|
+
},
|
|
881
|
+
doDetach: async () => {
|
|
882
|
+
if (stopped) {
|
|
883
|
+
throw new Error(
|
|
884
|
+
`codex session ${sessionId} is already stopped; cannot detach.`,
|
|
885
|
+
);
|
|
886
|
+
}
|
|
887
|
+
stopped = true;
|
|
888
|
+
const lastSeenEventId = await channel.suspend();
|
|
889
|
+
const payload: HarnessV1ResumeSessionState = {
|
|
890
|
+
type: 'resume-session',
|
|
891
|
+
harnessId: 'codex',
|
|
892
|
+
specificationVersion: 'harness-v1',
|
|
893
|
+
data: {
|
|
894
|
+
...(latestThreadId ? { threadId: latestThreadId } : {}),
|
|
895
|
+
bridge: {
|
|
896
|
+
port: bridgePort,
|
|
897
|
+
token: bridgeToken,
|
|
898
|
+
lastSeenEventId,
|
|
899
|
+
sandboxId,
|
|
900
|
+
},
|
|
901
|
+
},
|
|
902
|
+
};
|
|
903
|
+
return payload;
|
|
904
|
+
},
|
|
905
|
+
doDestroy: async () => {
|
|
906
|
+
if (stopped) return stopPromise;
|
|
907
|
+
stopped = true;
|
|
908
|
+
stopPromise = (async () => {
|
|
909
|
+
// Tell the channel we are tearing down so the bridge's post-shutdown
|
|
910
|
+
// socket close finalises instead of triggering a reconnect.
|
|
911
|
+
channel.beginClose();
|
|
912
|
+
try {
|
|
913
|
+
if (!channel.isClosed()) {
|
|
914
|
+
channel.send({ type: 'shutdown' });
|
|
915
|
+
}
|
|
916
|
+
} catch {}
|
|
917
|
+
let stopTimer: ReturnType<typeof setTimeout> | undefined;
|
|
918
|
+
try {
|
|
919
|
+
if (proc) {
|
|
920
|
+
await Promise.race([
|
|
921
|
+
proc.wait(),
|
|
922
|
+
new Promise<void>(resolve => {
|
|
923
|
+
stopTimer = setTimeout(resolve, 5000);
|
|
924
|
+
stopTimer.unref?.();
|
|
925
|
+
}),
|
|
926
|
+
]);
|
|
927
|
+
}
|
|
928
|
+
} finally {
|
|
929
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
930
|
+
try {
|
|
931
|
+
await proc?.kill();
|
|
932
|
+
} catch {}
|
|
933
|
+
channel.close();
|
|
934
|
+
}
|
|
935
|
+
})();
|
|
936
|
+
return stopPromise;
|
|
937
|
+
},
|
|
938
|
+
doStop: async () => {
|
|
939
|
+
if (stopped) {
|
|
940
|
+
throw new Error(
|
|
941
|
+
`codex session ${sessionId} is already stopped; cannot stop.`,
|
|
942
|
+
);
|
|
943
|
+
}
|
|
944
|
+
stopped = true;
|
|
945
|
+
/*
|
|
946
|
+
* If the bridge's channel already closed (e.g. mid-turn WS drop)
|
|
947
|
+
* there is no one to ack a `detach` message. Synthesize an empty
|
|
948
|
+
* payload — the workdir is still captured by the sandbox snapshot
|
|
949
|
+
* during the subsequent `sandboxSession.stop()`, so the next turn can
|
|
950
|
+
* resume the filesystem state. The trade-off: we lose
|
|
951
|
+
* `threadId`, so the codex CLI starts a fresh thread on the
|
|
952
|
+
* preserved workdir rather than resuming the prior conversation
|
|
953
|
+
* inside Codex's runtime. Ability to continue beats throwing.
|
|
954
|
+
*/
|
|
955
|
+
// Tell the channel we are tearing down so the bridge's post-detach
|
|
956
|
+
// socket close finalises instead of triggering a reconnect.
|
|
957
|
+
channel.beginClose();
|
|
958
|
+
const data: unknown = channel.isClosed()
|
|
959
|
+
? {}
|
|
960
|
+
: await new Promise<unknown>((resolve, reject) => {
|
|
961
|
+
const timer = setTimeout(() => {
|
|
962
|
+
unsub();
|
|
963
|
+
reject(
|
|
964
|
+
new Error(
|
|
965
|
+
`codex session ${sessionId} did not reply to detach within 5s.`,
|
|
966
|
+
),
|
|
967
|
+
);
|
|
968
|
+
}, 5000);
|
|
969
|
+
timer.unref?.();
|
|
970
|
+
const unsub = channel.on('bridge-detach', msg => {
|
|
971
|
+
clearTimeout(timer);
|
|
972
|
+
unsub();
|
|
973
|
+
resolve(msg.data);
|
|
974
|
+
});
|
|
975
|
+
try {
|
|
976
|
+
channel.send({ type: 'detach' });
|
|
977
|
+
} catch (err) {
|
|
978
|
+
clearTimeout(timer);
|
|
979
|
+
unsub();
|
|
980
|
+
reject(err);
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
|
|
984
|
+
let stopTimer: ReturnType<typeof setTimeout> | undefined;
|
|
985
|
+
try {
|
|
986
|
+
if (proc) {
|
|
987
|
+
await Promise.race([
|
|
988
|
+
proc.wait(),
|
|
989
|
+
new Promise<void>(resolve => {
|
|
990
|
+
stopTimer = setTimeout(resolve, 5000);
|
|
991
|
+
stopTimer.unref?.();
|
|
992
|
+
}),
|
|
993
|
+
]);
|
|
994
|
+
}
|
|
995
|
+
} finally {
|
|
996
|
+
if (stopTimer) clearTimeout(stopTimer);
|
|
997
|
+
try {
|
|
998
|
+
await proc?.kill();
|
|
999
|
+
} catch {}
|
|
1000
|
+
channel.close();
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
const payload: HarnessV1ResumeSessionState = {
|
|
1004
|
+
type: 'resume-session',
|
|
1005
|
+
harnessId: 'codex',
|
|
1006
|
+
specificationVersion: 'harness-v1',
|
|
1007
|
+
data: (data ?? {}) as HarnessV1ResumeSessionState['data'],
|
|
1008
|
+
};
|
|
1009
|
+
return payload;
|
|
1010
|
+
},
|
|
1011
|
+
doSuspendTurn: async () => {
|
|
1012
|
+
if (stopped) {
|
|
1013
|
+
throw new Error(
|
|
1014
|
+
`codex session ${sessionId} is stopped; cannot suspend.`,
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
stopped = true;
|
|
1018
|
+
/*
|
|
1019
|
+
* First ask the runtime to interrupt the active model turn, then freeze
|
|
1020
|
+
* the host at a precise cursor. `channel.suspend` stops processing
|
|
1021
|
+
* inbound frames (the cursor stops advancing exactly at the last
|
|
1022
|
+
* delivered event), drains what was already dispatched, then closes the
|
|
1023
|
+
* host socket with reason `'suspended'` — which `wireTurn`'s `onClose`
|
|
1024
|
+
* treats as a clean turn end. The bridge keeps the turn running and
|
|
1025
|
+
* accumulates events past the cursor for the next slice to replay. The
|
|
1026
|
+
* sandbox process is deliberately left alive (no `shutdown`/`detach`).
|
|
1027
|
+
*/
|
|
1028
|
+
await channel.interrupt();
|
|
1029
|
+
const lastSeenEventId = await channel.suspend();
|
|
1030
|
+
const payload: HarnessV1ContinueTurnState = {
|
|
1031
|
+
type: 'continue-turn',
|
|
1032
|
+
harnessId: 'codex',
|
|
1033
|
+
specificationVersion: 'harness-v1',
|
|
1034
|
+
data: {
|
|
1035
|
+
...(latestThreadId ? { threadId: latestThreadId } : {}),
|
|
1036
|
+
bridge: {
|
|
1037
|
+
port: bridgePort,
|
|
1038
|
+
token: bridgeToken,
|
|
1039
|
+
lastSeenEventId,
|
|
1040
|
+
sandboxId,
|
|
1041
|
+
},
|
|
1042
|
+
},
|
|
1043
|
+
};
|
|
1044
|
+
return payload;
|
|
1045
|
+
},
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/*
|
|
1050
|
+
* Frame session instructions, host-tool relay guidance, and the user's text so
|
|
1051
|
+
* Codex treats the prepended blocks as operating guidance rather than user
|
|
1052
|
+
* prose. Applied only to the first user message of a fresh session.
|
|
1053
|
+
*/
|
|
1054
|
+
function frameInitialPromptGuidance({
|
|
1055
|
+
instructions,
|
|
1056
|
+
toolUsageBlock,
|
|
1057
|
+
userText,
|
|
1058
|
+
}: {
|
|
1059
|
+
instructions: string | undefined;
|
|
1060
|
+
toolUsageBlock: string | undefined;
|
|
1061
|
+
userText: string;
|
|
1062
|
+
}): string {
|
|
1063
|
+
const blocks: string[] = [];
|
|
1064
|
+
if (instructions) {
|
|
1065
|
+
blocks.push(
|
|
1066
|
+
'<session-instructions>\n' +
|
|
1067
|
+
'The block below is operating guidance from the system, not a message from the user — follow it, but do not mention it or attribute it to the user.\n\n' +
|
|
1068
|
+
`${instructions}\n` +
|
|
1069
|
+
'</session-instructions>',
|
|
1070
|
+
);
|
|
1071
|
+
}
|
|
1072
|
+
if (toolUsageBlock) blocks.push(toolUsageBlock);
|
|
1073
|
+
if (blocks.length === 0) return userText;
|
|
1074
|
+
return `${blocks.join('\n\n')}\n\n<user-message>\n${userText}\n</user-message>`;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function composeToolUsageInstructions({
|
|
1078
|
+
tools,
|
|
1079
|
+
cliShimPath,
|
|
1080
|
+
}: {
|
|
1081
|
+
tools: ReadonlyArray<{
|
|
1082
|
+
name: string;
|
|
1083
|
+
description?: string;
|
|
1084
|
+
inputSchema?: unknown;
|
|
1085
|
+
}>;
|
|
1086
|
+
cliShimPath: string;
|
|
1087
|
+
}): string {
|
|
1088
|
+
const lines: string[] = [
|
|
1089
|
+
'<host-tool-instructions>',
|
|
1090
|
+
'You have access to the following host-provided tools. To use one, run the following command via your built-in `bash` tool:',
|
|
1091
|
+
'',
|
|
1092
|
+
` node ${cliShimPath} <toolName> '<jsonInput>'`,
|
|
1093
|
+
'',
|
|
1094
|
+
'The script prints the JSON result to stdout. Do not invent another way to call these tools — only this CLI invocation will work. Pass the JSON input as a single-quoted argument.',
|
|
1095
|
+
'For every user request that depends on a host-provided tool, run a separate CLI invocation for each needed tool call in the current turn before answering. Do not reuse previous tool results, and do not say you used a host tool unless the command has completed in the current turn.',
|
|
1096
|
+
'',
|
|
1097
|
+
];
|
|
1098
|
+
for (const toolSpec of tools) {
|
|
1099
|
+
lines.push(
|
|
1100
|
+
`- **${toolSpec.name}**${toolSpec.description ? ': ' + toolSpec.description : ''}`,
|
|
1101
|
+
);
|
|
1102
|
+
lines.push(
|
|
1103
|
+
` - Input schema: \`${JSON.stringify(toolSpec.inputSchema ?? {})}\``,
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
lines.push('</host-tool-instructions>');
|
|
1107
|
+
return lines.join('\n');
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/*
|
|
1111
|
+
* Reduce a `HarnessV1Prompt` to the plain user text the bridge forwards
|
|
1112
|
+
* to the Codex SDK. File and image parts on the message are not yet
|
|
1113
|
+
* supported by the underlying runtime — throw rather than silently drop
|
|
1114
|
+
* them so callers learn about the gap instead of seeing mysteriously
|
|
1115
|
+
* truncated prompts.
|
|
1116
|
+
*/
|
|
1117
|
+
function extractUserText(prompt: HarnessV1Prompt): string {
|
|
1118
|
+
if (typeof prompt === 'string') return prompt;
|
|
1119
|
+
const { content } = prompt;
|
|
1120
|
+
if (typeof content === 'string') return content;
|
|
1121
|
+
const parts: string[] = [];
|
|
1122
|
+
for (const part of content) {
|
|
1123
|
+
if (part.type !== 'text') {
|
|
1124
|
+
throw new HarnessCapabilityUnsupportedError({
|
|
1125
|
+
harnessId: 'codex',
|
|
1126
|
+
message: `The codex harness does not yet support user message parts of type '${part.type}'. Pass a string or a user message whose content contains only text parts.`,
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
parts.push(part.text);
|
|
1130
|
+
}
|
|
1131
|
+
return parts.join('\n\n');
|
|
1132
|
+
}
|