neurastream 0.3.26 → 0.3.28
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/package.json +1 -1
- package/src/adapters/agy/adapter.ts +661 -0
- package/src/adapters/claude/adapter.ts +545 -0
- package/src/adapters/codex/adapter.ts +589 -0
- package/src/adapters/hook-bridge.ts +429 -0
- package/src/adapters/index.ts +44 -6
- package/src/adapters/omp/adapter.ts +8 -0
- package/src/adapters/omp/index.ts +24 -9
- package/src/adapters/omp/launch.ts +5 -1
- package/src/adapters/omp/limit-wake.ts +4 -18
- package/src/adapters/omp/sessions.ts +6 -2
- package/src/adapters/omp/types.ts +19 -2
- package/src/adapters/shared.ts +1318 -0
- package/src/cli/commands.ts +109 -6
- package/src/cli/config-set.ts +26 -4
- package/src/cli/dispatch.ts +80 -7
- package/src/cli/recall.ts +5 -2
- package/src/cli/spawn.ts +629 -0
- package/src/core/adapter.ts +53 -0
- package/src/core/config-edit.ts +9 -1
- package/src/core/config.ts +79 -0
- package/src/core/guards/spawn.ts +47 -10
- package/src/core/guards/state.ts +23 -0
- package/src/core/guards/stop.ts +10 -8
- package/src/core/guards/tool.ts +65 -9
- package/src/core/provider-state.ts +406 -19
- package/src/core/runner.ts +223 -0
- package/src/runners/herdr/index.ts +293 -0
- package/src/runners/index.ts +36 -0
- package/templates/AGENTS.md +1 -0
- package/templates/config.yml +10 -1
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
// Codex CLI (`codex`) harness adapter: subagent launch spec, rollout JSONL RunSource/TraceSource,
|
|
2
|
+
// sandbox-safe hooks.json installer (SessionStart + PreToolUse + Stop), and doctor checks.
|
|
3
|
+
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import type { OwnerTurn, Run, RunSource, TraceEvent, TraceRun, TraceSource, TraceUsage } from "../../core/adapter.ts";
|
|
6
|
+
import type { Config } from "../../core/config.ts";
|
|
7
|
+
import type { SpawnProfile } from "../../core/runner.ts";
|
|
8
|
+
import { extractPatchPaths, LEGACY_PRE_TOOL_CMD, LEGACY_STOP_CMD } from "../hook-bridge.ts";
|
|
9
|
+
import type { HarnessAdapter } from "../index.ts";
|
|
10
|
+
import {
|
|
11
|
+
addUsageTotals,
|
|
12
|
+
asObj,
|
|
13
|
+
buildRunRecord,
|
|
14
|
+
collectOwnerTurns,
|
|
15
|
+
collectTraceRuns,
|
|
16
|
+
createTraceSource,
|
|
17
|
+
createTranscriptRunSource,
|
|
18
|
+
defaultAdapterStubs,
|
|
19
|
+
findFiles,
|
|
20
|
+
handleStandardHook,
|
|
21
|
+
installGroupedHooksJson,
|
|
22
|
+
isNum,
|
|
23
|
+
num,
|
|
24
|
+
parseIsoSec,
|
|
25
|
+
parseJsonlRecords,
|
|
26
|
+
runAdapterDoctorCli,
|
|
27
|
+
runAdapterInstallCli,
|
|
28
|
+
runHookDoctorChecks,
|
|
29
|
+
spawnHarnessMain,
|
|
30
|
+
statMtimeSec,
|
|
31
|
+
str,
|
|
32
|
+
subagentLaunchSpecFrom,
|
|
33
|
+
} from "../shared.ts";
|
|
34
|
+
|
|
35
|
+
/** Hook command wired into Codex CLI's SessionStart lifecycle. */
|
|
36
|
+
export const CODEX_SESSION_START_CMD = "neurastream adapter hook codex session-start";
|
|
37
|
+
|
|
38
|
+
/** Hook command wired into Codex CLI's UserPromptSubmit lifecycle. */
|
|
39
|
+
export const CODEX_USER_PROMPT_CMD = "neurastream adapter hook codex user-prompt";
|
|
40
|
+
|
|
41
|
+
/** Hook command wired into Codex CLI's PreToolUse lifecycle. */
|
|
42
|
+
export const CODEX_PRE_TOOL_CMD = "neurastream adapter hook codex pre-tool";
|
|
43
|
+
|
|
44
|
+
/** Hook command wired into Codex CLI's Stop lifecycle. */
|
|
45
|
+
export const CODEX_STOP_CMD = "neurastream adapter hook codex stop";
|
|
46
|
+
|
|
47
|
+
const CODEX_TOOL_MAP: Record<string, string> = {
|
|
48
|
+
shell_command: "bash",
|
|
49
|
+
exec_command: "bash",
|
|
50
|
+
shell: "bash",
|
|
51
|
+
Bash: "bash",
|
|
52
|
+
write_file: "write",
|
|
53
|
+
Write: "write",
|
|
54
|
+
apply_patch: "edit",
|
|
55
|
+
edit_file: "edit",
|
|
56
|
+
Edit: "edit",
|
|
57
|
+
read_file: "read",
|
|
58
|
+
Read: "read",
|
|
59
|
+
Grep: "grep",
|
|
60
|
+
Glob: "glob",
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Returns the path to Codex CLI's hooks configuration file under `home`.
|
|
65
|
+
*
|
|
66
|
+
* Args:
|
|
67
|
+
* home (string): Sandbox or caller HOME directory
|
|
68
|
+
*
|
|
69
|
+
* Returns:
|
|
70
|
+
* string: Path to `$HOME/.codex/hooks.json`
|
|
71
|
+
*/
|
|
72
|
+
export function codexHooksFile(home: string): string {
|
|
73
|
+
return join(home, ".codex", "hooks.json");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Returns the default Codex CLI sessions root containing rollout JSONL files.
|
|
78
|
+
*
|
|
79
|
+
* Args:
|
|
80
|
+
* home (string): Sandbox or caller HOME directory
|
|
81
|
+
*
|
|
82
|
+
* Returns:
|
|
83
|
+
* string: Path to `$HOME/.codex/sessions`
|
|
84
|
+
*/
|
|
85
|
+
export function codexSessionsRoot(home: string): string {
|
|
86
|
+
return join(home, ".codex", "sessions");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function codexRoot(cfg: Config): string {
|
|
90
|
+
return cfg.adapter?.name === "codex" && cfg.adapter.sessions ? cfg.adapter.sessions : codexSessionsRoot(cfg.paths.home);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Recursively discovers `*.jsonl` rollout logs beneath `root`.
|
|
95
|
+
*
|
|
96
|
+
* Args:
|
|
97
|
+
* root (string): Root directory to search
|
|
98
|
+
* maxDepth (number): Maximum recursion depth
|
|
99
|
+
*
|
|
100
|
+
* Returns:
|
|
101
|
+
* string[]: Sorted list of discovered rollout file paths
|
|
102
|
+
*/
|
|
103
|
+
export function findCodexTranscripts(root: string, maxDepth = 5): string[] {
|
|
104
|
+
return findFiles(root, (name) => name.endsWith(".jsonl"), maxDepth);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Derives a stable run id from a Codex rollout JSONL file path (falling back to the file stem).
|
|
109
|
+
*
|
|
110
|
+
* Args:
|
|
111
|
+
* file (string): Full path to a `.jsonl` rollout file
|
|
112
|
+
* _root (string): Sessions root directory
|
|
113
|
+
*
|
|
114
|
+
* Returns:
|
|
115
|
+
* string: Session/run identifier
|
|
116
|
+
*/
|
|
117
|
+
export function codexRunIdFromPath(file: string, _root?: string): string {
|
|
118
|
+
const stem = basename(file, ".jsonl");
|
|
119
|
+
return stem && stem !== "." ? stem : "codex";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function codexRunId(records: Record<string, unknown>[], file: string): string {
|
|
123
|
+
for (const rec of records) {
|
|
124
|
+
if (rec.type === "session_meta") {
|
|
125
|
+
const payload = asObj(rec.payload);
|
|
126
|
+
const id = str(payload?.id) ?? str(payload?.session_id);
|
|
127
|
+
if (id) return id;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return codexRunIdFromPath(file);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function formatModel(provider: string | undefined, model: string | undefined): string | undefined {
|
|
134
|
+
if (provider && model) return model.includes("/") ? model : `${provider}/${model}`;
|
|
135
|
+
return model;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function normalizeCodexUsage(u: Record<string, unknown>): TraceUsage {
|
|
139
|
+
const rawInput = num(u.input_tokens ?? u.input);
|
|
140
|
+
const output = num(u.output_tokens ?? u.output);
|
|
141
|
+
const cacheRead = num(u.cached_input_tokens ?? u.cache_read_input_tokens ?? u.cacheRead);
|
|
142
|
+
const cacheWrite = num(u.cache_creation_input_tokens ?? u.cacheWrite);
|
|
143
|
+
const hasTotal = isNum(u.total_tokens) || isNum(u.totalTokens);
|
|
144
|
+
const explicitTotal = num(u.total_tokens ?? u.totalTokens);
|
|
145
|
+
// OpenAI/Codex `input_tokens` typically includes `cached_input_tokens` when `total_tokens === input_tokens + output_tokens`.
|
|
146
|
+
const input = hasTotal && cacheRead > 0 && rawInput >= cacheRead && rawInput + output === explicitTotal ? rawInput - cacheRead : rawInput;
|
|
147
|
+
const totalTokens = hasTotal ? explicitTotal : input + output + cacheRead + cacheWrite;
|
|
148
|
+
const costObj = asObj(u.cost);
|
|
149
|
+
const cost = costObj ? num(costObj.total) : num(u.cost);
|
|
150
|
+
return { input, output, cacheRead, cacheWrite, totalTokens, cost };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface CodexTokenTracker {
|
|
154
|
+
lastCumulativeTotal: number | null;
|
|
155
|
+
prevTotals: { input: number; output: number; cacheRead: number; cacheWrite: number; totalTokens: number; cost: number } | null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function extractTokenCountUsage(payload: Record<string, unknown>, tracker: CodexTokenTracker): TraceUsage | undefined {
|
|
159
|
+
const info = asObj(payload.info);
|
|
160
|
+
const totalObj = info ? asObj(info.total_token_usage) : null;
|
|
161
|
+
const lastObj = info ? asObj(info.last_token_usage) : null;
|
|
162
|
+
|
|
163
|
+
if (totalObj) {
|
|
164
|
+
const cumTotal = num(totalObj.total_tokens);
|
|
165
|
+
if (tracker.lastCumulativeTotal !== null && cumTotal === tracker.lastCumulativeTotal) return undefined;
|
|
166
|
+
tracker.lastCumulativeTotal = cumTotal;
|
|
167
|
+
if (lastObj) {
|
|
168
|
+
tracker.prevTotals = normalizeCodexUsage(totalObj);
|
|
169
|
+
return normalizeCodexUsage(lastObj);
|
|
170
|
+
}
|
|
171
|
+
const current = normalizeCodexUsage(totalObj);
|
|
172
|
+
const prev = tracker.prevTotals;
|
|
173
|
+
tracker.prevTotals = current;
|
|
174
|
+
if (!prev) return current;
|
|
175
|
+
return {
|
|
176
|
+
input: Math.max(0, current.input - prev.input),
|
|
177
|
+
output: Math.max(0, current.output - prev.output),
|
|
178
|
+
cacheRead: Math.max(0, current.cacheRead - prev.cacheRead),
|
|
179
|
+
cacheWrite: Math.max(0, current.cacheWrite - prev.cacheWrite),
|
|
180
|
+
totalTokens: Math.max(0, current.totalTokens - prev.totalTokens),
|
|
181
|
+
cost: Math.max(0, current.cost - prev.cost),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (lastObj) return normalizeCodexUsage(lastObj);
|
|
186
|
+
|
|
187
|
+
const direct =
|
|
188
|
+
asObj(payload.usage) ?? (isNum(payload.input_tokens) || isNum(payload.output_tokens) || isNum(payload.total_tokens) ? payload : null);
|
|
189
|
+
return direct ? normalizeCodexUsage(direct) : undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function parseCodexToolArgs(payload: Record<string, unknown>): Record<string, unknown> {
|
|
193
|
+
const raw = payload.arguments ?? payload.args ?? payload.input;
|
|
194
|
+
if (typeof raw === "string") {
|
|
195
|
+
try {
|
|
196
|
+
const parsed = asObj(JSON.parse(raw));
|
|
197
|
+
if (parsed) return parsed;
|
|
198
|
+
} catch {
|
|
199
|
+
// keep non-JSON string under raw
|
|
200
|
+
}
|
|
201
|
+
return raw.trim() ? { raw } : {};
|
|
202
|
+
}
|
|
203
|
+
return asObj(raw) ?? {};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function textFromCodexContent(content: unknown): string {
|
|
207
|
+
if (typeof content === "string") return content;
|
|
208
|
+
if (!Array.isArray(content)) return "";
|
|
209
|
+
const parts: string[] = [];
|
|
210
|
+
for (const item of content) {
|
|
211
|
+
const obj = asObj(item);
|
|
212
|
+
if (!obj) continue;
|
|
213
|
+
if (typeof obj.text === "string" && obj.text) parts.push(obj.text);
|
|
214
|
+
else if (typeof obj.content === "string" && obj.content) parts.push(obj.content);
|
|
215
|
+
}
|
|
216
|
+
return parts.join("\n");
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function statusFromCodexRecords(records: Record<string, unknown>[]): { status: Run["status"]; detail: string } {
|
|
220
|
+
let status: Run["status"] = "done";
|
|
221
|
+
let detail = "done";
|
|
222
|
+
for (const rec of records) {
|
|
223
|
+
if (rec.type !== "event_msg") continue;
|
|
224
|
+
const payload = asObj(rec.payload);
|
|
225
|
+
const evType = str(payload?.type);
|
|
226
|
+
if (!evType) continue;
|
|
227
|
+
if (evType === "turn_aborted" || evType === "error" || evType === "task_failed") {
|
|
228
|
+
status = "died";
|
|
229
|
+
detail = "DIED: error";
|
|
230
|
+
} else if (evType === "task_started" || evType === "turn_started") {
|
|
231
|
+
status = "running";
|
|
232
|
+
detail = "RUNNING";
|
|
233
|
+
} else if (evType === "turn_complete" || evType === "task_complete") {
|
|
234
|
+
const rawStatus = typeof payload?.status === "string" ? payload.status.toUpperCase() : "";
|
|
235
|
+
if (rawStatus === "ERROR" || rawStatus === "FAILED") {
|
|
236
|
+
status = "died";
|
|
237
|
+
detail = "DIED: error";
|
|
238
|
+
} else {
|
|
239
|
+
status = "done";
|
|
240
|
+
detail = "done";
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return { status, detail };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function buildRunFromCodexFile(file: string, since: number): Run | null {
|
|
248
|
+
const mtimeSec = statMtimeSec(file);
|
|
249
|
+
if (mtimeSec === null) return null;
|
|
250
|
+
const records = parseJsonlRecords(file);
|
|
251
|
+
const tracker: CodexTokenTracker = { lastCumulativeTotal: null, prevTotals: null };
|
|
252
|
+
|
|
253
|
+
let startedAt: number | null = null;
|
|
254
|
+
let lastTs: number | null = null;
|
|
255
|
+
let provider: string | undefined;
|
|
256
|
+
let modelName: string | undefined;
|
|
257
|
+
let calls = 0;
|
|
258
|
+
const totals = { tokens: 0, cacheRead: 0, cost: 0, inputTokens: 0, prefillTokens: 0 };
|
|
259
|
+
|
|
260
|
+
for (const rec of records) {
|
|
261
|
+
const payload = asObj(rec.payload);
|
|
262
|
+
const ts = parseIsoSec(rec.timestamp) ?? parseIsoSec(payload?.timestamp);
|
|
263
|
+
if (ts !== null) {
|
|
264
|
+
if (startedAt === null) startedAt = ts;
|
|
265
|
+
lastTs = ts;
|
|
266
|
+
}
|
|
267
|
+
if ((rec.type === "session_meta" || rec.type === "turn_context") && payload) {
|
|
268
|
+
provider = str(payload.model_provider) ?? provider;
|
|
269
|
+
modelName = str(payload.model) ?? modelName;
|
|
270
|
+
} else if (rec.type === "event_msg" && payload && payload.type === "token_count") {
|
|
271
|
+
const usage = extractTokenCountUsage(payload, tracker);
|
|
272
|
+
if (usage) {
|
|
273
|
+
calls++;
|
|
274
|
+
addUsageTotals(totals, usage);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const lastWriteAt = lastTs ?? mtimeSec;
|
|
280
|
+
if (lastWriteAt < since) return null;
|
|
281
|
+
const { status, detail } = statusFromCodexRecords(records);
|
|
282
|
+
return buildRunRecord({
|
|
283
|
+
id: codexRunId(records, file),
|
|
284
|
+
model: formatModel(provider, modelName) ?? "?",
|
|
285
|
+
calls,
|
|
286
|
+
...totals,
|
|
287
|
+
status,
|
|
288
|
+
detail,
|
|
289
|
+
startedAt,
|
|
290
|
+
lastWriteAt,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Parses a Codex CLI rollout JSONL file into core `TraceEvent` items.
|
|
296
|
+
*
|
|
297
|
+
* Args:
|
|
298
|
+
* file (string): Path to the `.jsonl` rollout file
|
|
299
|
+
* runId (string): Run identifier assigned to emitted events
|
|
300
|
+
*
|
|
301
|
+
* Returns:
|
|
302
|
+
* TraceEvent[]: Normalized trace events in file order
|
|
303
|
+
*/
|
|
304
|
+
export function parseCodexTraceFile(file: string, runId: string): TraceEvent[] {
|
|
305
|
+
const records = parseJsonlRecords(file);
|
|
306
|
+
const events: TraceEvent[] = [];
|
|
307
|
+
const toolByCallId = new Map<string, string>();
|
|
308
|
+
const tracker: CodexTokenTracker = { lastCumulativeTotal: null, prevTotals: null };
|
|
309
|
+
|
|
310
|
+
let provider: string | undefined;
|
|
311
|
+
let modelName: string | undefined;
|
|
312
|
+
|
|
313
|
+
for (const rec of records) {
|
|
314
|
+
const payload = asObj(rec.payload);
|
|
315
|
+
if (!payload) continue;
|
|
316
|
+
const ts = parseIsoSec(rec.timestamp) ?? parseIsoSec(payload.timestamp);
|
|
317
|
+
const type = typeof rec.type === "string" ? rec.type : "";
|
|
318
|
+
|
|
319
|
+
if (type === "session_meta") {
|
|
320
|
+
provider = str(payload.model_provider) ?? provider;
|
|
321
|
+
modelName = str(payload.model) ?? modelName;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (type === "turn_context") {
|
|
326
|
+
const nextProvider = str(payload.model_provider) ?? provider;
|
|
327
|
+
const nextModel = str(payload.model);
|
|
328
|
+
if (nextModel && (nextModel !== modelName || nextProvider !== provider)) {
|
|
329
|
+
events.push({ kind: "modelChange", ts, runId, model: nextModel, provider: nextProvider });
|
|
330
|
+
}
|
|
331
|
+
provider = nextProvider;
|
|
332
|
+
modelName = nextModel ?? modelName;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (type === "event_msg") {
|
|
337
|
+
if (payload.type === "token_count") {
|
|
338
|
+
const usage = extractTokenCountUsage(payload, tracker);
|
|
339
|
+
if (usage) events.push({ kind: "usage", ts, runId, model: modelName, provider, usage });
|
|
340
|
+
}
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (type === "response_item") {
|
|
345
|
+
const itemType = str(payload.type);
|
|
346
|
+
if (itemType === "message") {
|
|
347
|
+
if (payload.role !== "assistant") continue;
|
|
348
|
+
const text = textFromCodexContent(payload.content);
|
|
349
|
+
if (text.trim()) events.push({ kind: "assistantText", ts, runId, text, model: modelName, provider });
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (itemType === "function_call" || itemType === "custom_tool_call") {
|
|
353
|
+
const tool = str(payload.name) ?? "?";
|
|
354
|
+
const callId = str(payload.call_id) ?? str(payload.id);
|
|
355
|
+
if (callId) toolByCallId.set(callId, tool);
|
|
356
|
+
events.push({ kind: "toolCall", ts, runId, tool, args: parseCodexToolArgs(payload), callId, model: modelName, provider });
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (itemType === "function_call_output" || itemType === "custom_tool_call_output") {
|
|
360
|
+
const callId = str(payload.call_id) ?? str(payload.id);
|
|
361
|
+
const tool = str(payload.name) ?? (callId ? toolByCallId.get(callId) : undefined);
|
|
362
|
+
const rawOut = payload.output ?? payload.content;
|
|
363
|
+
const text = typeof rawOut === "string" ? rawOut : textFromCodexContent(rawOut);
|
|
364
|
+
const isError = payload.is_error === true || payload.status === "error";
|
|
365
|
+
events.push({ kind: "toolResult", ts, runId, tool, callId, isError, text });
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return events;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Creates a `RunSource` backed by Codex CLI rollout JSONL files under `cfg`.
|
|
374
|
+
*
|
|
375
|
+
* Args:
|
|
376
|
+
* cfg (Config): Loaded neurastream configuration
|
|
377
|
+
*
|
|
378
|
+
* Returns:
|
|
379
|
+
* RunSource: RunSource reading Codex CLI rollout sessions
|
|
380
|
+
*/
|
|
381
|
+
export function codexRunSource(cfg: Config): RunSource {
|
|
382
|
+
const root = codexRoot(cfg);
|
|
383
|
+
return createTranscriptRunSource(() => findCodexTranscripts(root), buildRunFromCodexFile);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Lists Codex CLI trace runs discovered under `root`.
|
|
388
|
+
*
|
|
389
|
+
* Args:
|
|
390
|
+
* root (string): Codex sessions root directory
|
|
391
|
+
*
|
|
392
|
+
* Returns:
|
|
393
|
+
* TraceRun[]: Discovered trace runs sorted by run id
|
|
394
|
+
*/
|
|
395
|
+
export function codexTraceRuns(root: string): TraceRun[] {
|
|
396
|
+
return collectTraceRuns(findCodexTranscripts(root), (file) => codexRunId(parseJsonlRecords(file), file));
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Creates a `TraceSource` over Codex CLI rollout JSONL files under `root`.
|
|
401
|
+
*
|
|
402
|
+
* Args:
|
|
403
|
+
* root (string): Codex sessions root directory
|
|
404
|
+
*
|
|
405
|
+
* Returns:
|
|
406
|
+
* TraceSource: TraceSource returning events for a requested run id
|
|
407
|
+
*/
|
|
408
|
+
export function codexTraceSource(root: string): TraceSource {
|
|
409
|
+
return createTraceSource(root, codexTraceRuns, parseCodexTraceFile);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Extracts owner prompts (`role === "user"`) and Main replies (`role === "assistant"`) from Codex
|
|
414
|
+
* CLI `response_item` message records at or after `since`.
|
|
415
|
+
*
|
|
416
|
+
* Args:
|
|
417
|
+
* cfg (Config): Loaded neurastream configuration
|
|
418
|
+
* since (number): Minimum Unix timestamp in seconds
|
|
419
|
+
*
|
|
420
|
+
* Returns:
|
|
421
|
+
* OwnerTurn[]: Extracted turns sorted ascending by timestamp
|
|
422
|
+
*/
|
|
423
|
+
export function codexOwnerTurns(cfg: Config, since: number): OwnerTurn[] {
|
|
424
|
+
return collectOwnerTurns(findCodexTranscripts(codexRoot(cfg)), since, (rec, cutoff): OwnerTurn | null => {
|
|
425
|
+
if (rec.type !== "response_item") return null;
|
|
426
|
+
const payload = asObj(rec.payload);
|
|
427
|
+
if (!payload || str(payload.type) !== "message") return null;
|
|
428
|
+
const at = parseIsoSec(rec.timestamp) ?? parseIsoSec(payload.timestamp);
|
|
429
|
+
if (at === null || at < cutoff) return null;
|
|
430
|
+
const role = payload.role === "user" ? "owner" : payload.role === "assistant" ? "main" : null;
|
|
431
|
+
if (!role) return null;
|
|
432
|
+
const text = textFromCodexContent(payload.content).trim();
|
|
433
|
+
return text ? { at, role, text } : null;
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Translates Codex CLI `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` hook payloads
|
|
439
|
+
* into core guard calls and Codex hook JSON.
|
|
440
|
+
*
|
|
441
|
+
* Args:
|
|
442
|
+
* event (string): Hook lifecycle event (`"session-start"`, `"user-prompt"`, `"pre-tool"`, or `"stop"`)
|
|
443
|
+
* stdinText (string): Raw JSON payload from Codex CLI
|
|
444
|
+
* cfg (Config | undefined): Loaded config when active; undefined on inactive fast-path
|
|
445
|
+
* env (NodeJS.ProcessEnv): Process environment variables
|
|
446
|
+
*
|
|
447
|
+
* Returns:
|
|
448
|
+
* { code: number; stdout: string }: Exit code and Codex hook JSON (empty on allow/inactive)
|
|
449
|
+
*/
|
|
450
|
+
export function handleCodexHook(
|
|
451
|
+
event: string,
|
|
452
|
+
stdinText: string,
|
|
453
|
+
cfg: Config | undefined,
|
|
454
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
455
|
+
): { code: number; stdout: string } {
|
|
456
|
+
return handleStandardHook({
|
|
457
|
+
event,
|
|
458
|
+
stdinText,
|
|
459
|
+
cfg,
|
|
460
|
+
env,
|
|
461
|
+
defaultId: "codex",
|
|
462
|
+
toolMap: CODEX_TOOL_MAP,
|
|
463
|
+
nativeSpawnTools: ["spawn_agent"],
|
|
464
|
+
extraPaths: extractPatchPaths,
|
|
465
|
+
fallbackSessionId: (payload) => str(payload.session_id) ?? str(payload.thread_id),
|
|
466
|
+
formatPreToolDeny: (reason) => JSON.stringify({ decision: "deny", reason }),
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Idempotently merges `SessionStart`, `UserPromptSubmit`, `PreToolUse`, and `Stop` hooks into
|
|
472
|
+
* `$HOME/.codex/hooks.json`, upgrading legacy `neurastream guard ...` entries and detecting both
|
|
473
|
+
* flat `{ command }` and grouped `{ hooks: [...] }` forms while preserving all existing entries.
|
|
474
|
+
*
|
|
475
|
+
* Args:
|
|
476
|
+
* home (string): Sandbox or caller HOME directory
|
|
477
|
+
*
|
|
478
|
+
* Returns:
|
|
479
|
+
* { hooksFile: string; changed: boolean }: Hooks path and whether the file changed
|
|
480
|
+
*/
|
|
481
|
+
export function installCodex(home: string): { hooksFile: string; changed: boolean } {
|
|
482
|
+
return installGroupedHooksJson({
|
|
483
|
+
file: codexHooksFile(home),
|
|
484
|
+
label: "codex install",
|
|
485
|
+
legacyPreToolCmd: LEGACY_PRE_TOOL_CMD,
|
|
486
|
+
legacyStopCmd: LEGACY_STOP_CMD,
|
|
487
|
+
cmds: {
|
|
488
|
+
sessionStart: CODEX_SESSION_START_CMD,
|
|
489
|
+
userPrompt: CODEX_USER_PROMPT_CMD,
|
|
490
|
+
preTool: CODEX_PRE_TOOL_CMD,
|
|
491
|
+
stop: CODEX_STOP_CMD,
|
|
492
|
+
},
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Checks Codex CLI (`codex`) binary availability on `PATH` and hook wiring under `home`.
|
|
498
|
+
*
|
|
499
|
+
* Args:
|
|
500
|
+
* home (string): Sandbox or caller HOME directory
|
|
501
|
+
* env (NodeJS.ProcessEnv): Environment whose `PATH` is inspected
|
|
502
|
+
*
|
|
503
|
+
* Returns:
|
|
504
|
+
* { ok: string[]; problems: string[] }: Diagnostic status lines
|
|
505
|
+
*/
|
|
506
|
+
export function doctorCodex(home: string, env: NodeJS.ProcessEnv = process.env): { ok: string[]; problems: string[] } {
|
|
507
|
+
return runHookDoctorChecks({
|
|
508
|
+
name: "codex",
|
|
509
|
+
bin: "codex",
|
|
510
|
+
hooksFile: codexHooksFile(home),
|
|
511
|
+
env,
|
|
512
|
+
cmds: {
|
|
513
|
+
sessionStart: CODEX_SESSION_START_CMD,
|
|
514
|
+
userPrompt: CODEX_USER_PROMPT_CMD,
|
|
515
|
+
preTool: CODEX_PRE_TOOL_CMD,
|
|
516
|
+
stop: CODEX_STOP_CMD,
|
|
517
|
+
},
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* CLI handler for `neurastream adapter install codex`.
|
|
523
|
+
*
|
|
524
|
+
* Args:
|
|
525
|
+
* args (string[]): Arguments passed to `neurastream adapter`
|
|
526
|
+
*
|
|
527
|
+
* Returns:
|
|
528
|
+
* number: Process exit code
|
|
529
|
+
*/
|
|
530
|
+
export function runCodexInstall(args: string[]): number {
|
|
531
|
+
return runAdapterInstallCli(args, "codex", installCodex);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* CLI handler for `neurastream doctor` when `harness: codex`.
|
|
536
|
+
*
|
|
537
|
+
* Returns:
|
|
538
|
+
* number: 0 if healthy, 1 if problems were found
|
|
539
|
+
*/
|
|
540
|
+
export function runCodexDoctor(): number {
|
|
541
|
+
return runAdapterDoctorCli("codex", doctorCodex);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Builds the `herdr` subagent launch specification for `codex`, prepending `-a never` and
|
|
546
|
+
* `--dangerously-bypass-hook-trust` unless equivalent flags are already present in `profile.args`.
|
|
547
|
+
*
|
|
548
|
+
* Args:
|
|
549
|
+
* profile (SpawnProfile): Resolved subagent spawn profile
|
|
550
|
+
*
|
|
551
|
+
* Returns:
|
|
552
|
+
* { kind: string; args: string[]; env?: Record<string, string> }: Subagent launch spec
|
|
553
|
+
*/
|
|
554
|
+
export function codexSubagentLaunchSpec(profile: SpawnProfile): { kind: string; args: string[]; env?: Record<string, string> } {
|
|
555
|
+
const hasApproval = profile.args.some(
|
|
556
|
+
(arg) => arg === "-a" || arg.startsWith("-a=") || arg === "--ask-for-approval" || arg.startsWith("--ask-for-approval="),
|
|
557
|
+
);
|
|
558
|
+
const hasBypassTrust = profile.args.includes("--dangerously-bypass-hook-trust");
|
|
559
|
+
const defaultArgs = [
|
|
560
|
+
...(hasApproval ? [] : ["-a", "never"]),
|
|
561
|
+
...(hasBypassTrust ? [] : ["--dangerously-bypass-hook-trust"]),
|
|
562
|
+
];
|
|
563
|
+
return subagentLaunchSpecFrom("codex", profile, true, defaultArgs);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Registered Codex CLI (`codex`) HarnessAdapter. */
|
|
567
|
+
export const codexAdapter: HarnessAdapter = {
|
|
568
|
+
...defaultAdapterStubs("codex"),
|
|
569
|
+
name: "codex",
|
|
570
|
+
bin: "codex",
|
|
571
|
+
runSource: codexRunSource,
|
|
572
|
+
ownerTurns: codexOwnerTurns,
|
|
573
|
+
scoreTraces: (cfg) => codexTraceSource(codexRoot(cfg)),
|
|
574
|
+
traceRuns: codexTraceRuns,
|
|
575
|
+
traceSource: codexTraceSource,
|
|
576
|
+
traceStart(file: string): number | null {
|
|
577
|
+
for (const rec of parseJsonlRecords(file)) {
|
|
578
|
+
const payload = asObj(rec.payload);
|
|
579
|
+
const sec = parseIsoSec(rec.timestamp) ?? parseIsoSec(payload?.timestamp);
|
|
580
|
+
if (sec !== null) return Math.round(sec * 1000);
|
|
581
|
+
}
|
|
582
|
+
return null;
|
|
583
|
+
},
|
|
584
|
+
launchMain: (args, cfg) => spawnHarnessMain("codex", args, cfg),
|
|
585
|
+
install: runCodexInstall,
|
|
586
|
+
doctor: runCodexDoctor,
|
|
587
|
+
subagentLaunchSpec: codexSubagentLaunchSpec,
|
|
588
|
+
handleHook: handleCodexHook,
|
|
589
|
+
};
|