@phren/cli 0.3.8 → 0.3.10
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/dist/bridge/claude-question-dialog.js +8 -4
- package/dist/bridge/codex-binary.d.ts +11 -0
- package/dist/bridge/codex-binary.js +58 -0
- package/dist/bridge/models.js +2 -1
- package/dist/bridge/questions.d.ts +4 -2
- package/dist/bridge/questions.js +12 -5
- package/dist/bridge/transcript-codex.d.ts +20 -0
- package/dist/bridge/transcript-codex.js +177 -2
- package/dist/bridge/transcripts.js +6 -1
- package/dist/bridge/usage.js +2 -1
- package/dist/bridge-hook.mjs +549 -349
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +4 -0
- package/starter/global/skills/fanout/SKILL.md +6 -0
|
@@ -95,6 +95,10 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
95
95
|
await sleep(120);
|
|
96
96
|
}
|
|
97
97
|
};
|
|
98
|
+
// After a key that answers, Claude may take seconds to redraw on a busy
|
|
99
|
+
// computer; the answer was taken, so wait for the redraw instead of
|
|
100
|
+
// calling it refused (the phone would say it was not confirmed).
|
|
101
|
+
const ANSWERED_MS = 8_000;
|
|
98
102
|
const initial = await settle(screen => screen);
|
|
99
103
|
if (!initial)
|
|
100
104
|
throw changed("The terminal is not showing Claude's question.");
|
|
@@ -146,7 +150,7 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
146
150
|
else {
|
|
147
151
|
await io.keys([String(screen.options[answer.options[0]].number)]);
|
|
148
152
|
}
|
|
149
|
-
if (!await settle(leaves(index)))
|
|
153
|
+
if (!await settle(leaves(index), ANSWERED_MS))
|
|
150
154
|
throw changed("The terminal did not take the answer.");
|
|
151
155
|
continue;
|
|
152
156
|
}
|
|
@@ -189,12 +193,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
189
193
|
// Tab from the typed row would stop on Next instead of leaving.
|
|
190
194
|
await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
|
|
191
195
|
}
|
|
192
|
-
if (!await settle(leaves(index)))
|
|
196
|
+
if (!await settle(leaves(index), ANSWERED_MS))
|
|
193
197
|
throw changed("The terminal did not move past the question.");
|
|
194
198
|
}
|
|
195
199
|
if (!submit)
|
|
196
200
|
return;
|
|
197
|
-
const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined);
|
|
201
|
+
const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined, ANSWERED_MS);
|
|
198
202
|
// A lone single-select question submits on its digit.
|
|
199
203
|
if (review === "gone")
|
|
200
204
|
return;
|
|
@@ -205,6 +209,6 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
|
|
|
205
209
|
throw changed("Not every question has an answer in the terminal.");
|
|
206
210
|
}
|
|
207
211
|
await io.keys(["1"]);
|
|
208
|
-
if (await settle(value => value === undefined ? "gone" : undefined) !== "gone")
|
|
212
|
+
if (await settle(value => value === undefined ? "gone" : undefined, ANSWERED_MS) !== "gone")
|
|
209
213
|
throw changed("The terminal did not submit the answers.");
|
|
210
214
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
|
|
2
|
+
* app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
|
|
3
|
+
* that runs phren's session-start hook before the real binary for every
|
|
4
|
+
* subcommand except a bare --help. That takes seconds (about 8 s on the Linux
|
|
5
|
+
* box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
|
|
6
|
+
* questions were reported as terminal-only, and each call opened a phren
|
|
7
|
+
* session. The Hook skips its own wrapper and runs the binary it names. */
|
|
8
|
+
export declare function codexExecutable(env?: NodeJS.ProcessEnv): string;
|
|
9
|
+
/** The real binary a phren session wrapper names, "" for a phren wrapper
|
|
10
|
+
* whose target cannot be read, undefined for anything else. */
|
|
11
|
+
export declare function phrenWrapperTarget(file: string): string | undefined;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { accessSync, closeSync, constants, openSync, readSync, statSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
/** The `codex` the Hook runs for its own helper calls (`codex queue`, `codex
|
|
4
|
+
* app-server`). `phren init` can put a session wrapper at ~/.local/bin/codex
|
|
5
|
+
* that runs phren's session-start hook before the real binary for every
|
|
6
|
+
* subcommand except a bare --help. That takes seconds (about 8 s on the Linux
|
|
7
|
+
* box), longer than the Hook's 5 s `codex queue --help` probe, so Codex async
|
|
8
|
+
* questions were reported as terminal-only, and each call opened a phren
|
|
9
|
+
* session. The Hook skips its own wrapper and runs the binary it names. */
|
|
10
|
+
export function codexExecutable(env = process.env) {
|
|
11
|
+
if (process.platform === "win32")
|
|
12
|
+
return "codex";
|
|
13
|
+
for (const directory of (env.PATH ?? "").split(path.delimiter)) {
|
|
14
|
+
if (!path.isAbsolute(directory))
|
|
15
|
+
continue;
|
|
16
|
+
const candidate = path.join(directory, "codex");
|
|
17
|
+
if (!executable(candidate))
|
|
18
|
+
continue;
|
|
19
|
+
const wrapped = phrenWrapperTarget(candidate);
|
|
20
|
+
if (wrapped === undefined)
|
|
21
|
+
return candidate;
|
|
22
|
+
if (wrapped && executable(wrapped))
|
|
23
|
+
return wrapped;
|
|
24
|
+
}
|
|
25
|
+
return "codex";
|
|
26
|
+
}
|
|
27
|
+
function executable(file) {
|
|
28
|
+
try {
|
|
29
|
+
return statSync(file).isFile() && (accessSync(file, constants.X_OK), true);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** The real binary a phren session wrapper names, "" for a phren wrapper
|
|
36
|
+
* whose target cannot be read, undefined for anything else. */
|
|
37
|
+
export function phrenWrapperTarget(file) {
|
|
38
|
+
let head = "";
|
|
39
|
+
try {
|
|
40
|
+
const fd = openSync(file, "r");
|
|
41
|
+
try {
|
|
42
|
+
const buffer = Buffer.alloc(4096);
|
|
43
|
+
head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
closeSync(fd);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:"))
|
|
53
|
+
return undefined;
|
|
54
|
+
// shellEscape in hooks.ts: single quotes, an embedded quote written '\''.
|
|
55
|
+
const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
|
|
56
|
+
const target = match?.[1].replace(/'\\''/g, "'");
|
|
57
|
+
return target && path.isAbsolute(target) ? target : "";
|
|
58
|
+
}
|
package/dist/bridge/models.js
CHANGED
|
@@ -4,8 +4,9 @@ import { homedir } from "node:os";
|
|
|
4
4
|
import { claudeConfigDir } from "../home-paths.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { object, objects } from "./protocol.js";
|
|
7
|
+
import { codexExecutable } from "./codex-binary.js";
|
|
7
8
|
/** Only initialize and list. Never a thread, a prompt, or a login. */
|
|
8
|
-
export function readCodexModels(executable =
|
|
9
|
+
export function readCodexModels(executable = codexExecutable()) {
|
|
9
10
|
return new Promise(resolve => {
|
|
10
11
|
const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
|
|
11
12
|
let pending = "", bytes = 0, initialized = false, done = false;
|
|
@@ -23,14 +23,16 @@ interface PendingQuestion {
|
|
|
23
23
|
export declare function pendingAsyncQuestions(file: string, targetID?: string): Promise<PendingQuestion[]>;
|
|
24
24
|
export declare function pendingAsyncQuestion(file: string, id: string): Promise<Question[]>;
|
|
25
25
|
export declare class CodexQuestions {
|
|
26
|
-
private
|
|
26
|
+
private readonly configured?;
|
|
27
27
|
private snapshots;
|
|
28
28
|
private failedSnapshots;
|
|
29
29
|
private inboxAvailable;
|
|
30
30
|
/** Feature discovery must never delay permission/status frames. */
|
|
31
31
|
get available(): boolean;
|
|
32
32
|
private probe?;
|
|
33
|
-
|
|
33
|
+
/** No executable: the real `codex` on PATH, past phren's session wrapper. */
|
|
34
|
+
constructor(configured?: string | undefined);
|
|
35
|
+
private get executable();
|
|
34
36
|
supported(): Promise<boolean>;
|
|
35
37
|
pending(target: Target): Promise<Json[]>;
|
|
36
38
|
answer(target: Target, data: Json): Promise<void>;
|
package/dist/bridge/questions.js
CHANGED
|
@@ -7,6 +7,7 @@ import { z } from "zod";
|
|
|
7
7
|
import { BridgeError, bridgeRoot, object, objects } from "./protocol.js";
|
|
8
8
|
import { paneIdentity, validateTarget } from "./herdr.js";
|
|
9
9
|
import { transcriptPath } from "./transcripts.js";
|
|
10
|
+
import { codexExecutable } from "./codex-binary.js";
|
|
10
11
|
import { withTranscriptIndex } from "./transcript-index.js";
|
|
11
12
|
const exec = promisify(execFile);
|
|
12
13
|
const text = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
@@ -68,7 +69,7 @@ const answersQuestions = (reply, questions) => questions.every(q => {
|
|
|
68
69
|
});
|
|
69
70
|
export async function pendingAsyncQuestions(file, targetID) {
|
|
70
71
|
return withTranscriptIndex(file, async (handle, index) => {
|
|
71
|
-
const replies = [], acknowledged = new Set(), resolved = new Set(), pending = [];
|
|
72
|
+
const replies = [], acknowledged = new Set(), resolved = new Set(), seen = new Set(), pending = [];
|
|
72
73
|
let bytes = 0;
|
|
73
74
|
for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - 10_000))) {
|
|
74
75
|
// An incomplete scan is not evidence that no questions remain. Status
|
|
@@ -106,11 +107,15 @@ export async function pendingAsyncQuestions(file, targetID) {
|
|
|
106
107
|
if (!id || !acknowledged.has(id))
|
|
107
108
|
continue;
|
|
108
109
|
const questions = asyncQuestion(raw, id);
|
|
109
|
-
|
|
110
|
+
// Codex 0.155 records one question twice under the same id: the
|
|
111
|
+
// request_user_input_async call and the AgentMessage delivered async.
|
|
112
|
+
if (questions && !seen.has(id) && !replies.some(reply => answersQuestions(reply, questions))) {
|
|
110
113
|
pending.push({ id, questions });
|
|
111
114
|
if (pending.length >= 64)
|
|
112
115
|
throw new BridgeError(413, "Too many pending questions to verify.");
|
|
113
116
|
}
|
|
117
|
+
if (questions)
|
|
118
|
+
seen.add(id);
|
|
114
119
|
if (targetID && questions && id === targetID)
|
|
115
120
|
return pending.filter(p => p.id === targetID);
|
|
116
121
|
}
|
|
@@ -126,16 +131,18 @@ export async function pendingAsyncQuestion(file, id) {
|
|
|
126
131
|
return pending.questions;
|
|
127
132
|
}
|
|
128
133
|
export class CodexQuestions {
|
|
129
|
-
|
|
134
|
+
configured;
|
|
130
135
|
snapshots = new Map();
|
|
131
136
|
failedSnapshots = new Map();
|
|
132
137
|
inboxAvailable = false;
|
|
133
138
|
/** Feature discovery must never delay permission/status frames. */
|
|
134
139
|
get available() { void this.supported(); return this.inboxAvailable; }
|
|
135
140
|
probe;
|
|
136
|
-
|
|
137
|
-
|
|
141
|
+
/** No executable: the real `codex` on PATH, past phren's session wrapper. */
|
|
142
|
+
constructor(configured) {
|
|
143
|
+
this.configured = configured;
|
|
138
144
|
}
|
|
145
|
+
get executable() { return this.configured ?? codexExecutable(); }
|
|
139
146
|
supported() {
|
|
140
147
|
if (!this.probe || Date.now() - this.probe.at > 300_000)
|
|
141
148
|
this.probe = { at: Date.now(), result: exec(this.executable, ["queue", "--help"], { timeout: 5000, maxBuffer: 65_536 })
|
|
@@ -8,6 +8,26 @@ export declare function childTranscriptBelongsTo(file: string, parent: string):
|
|
|
8
8
|
/** Codex rows the phone may see: public messages, tool calls and their
|
|
9
9
|
* outputs, the answering model, and turn/usage events. */
|
|
10
10
|
export declare function visibleCodexEvent(raw: Json): Json | undefined;
|
|
11
|
+
export interface CodeModeWrapper {
|
|
12
|
+
callId: string;
|
|
13
|
+
images: string[];
|
|
14
|
+
}
|
|
15
|
+
/** A numbered rollout's code-mode `exec` call whose every tool call is
|
|
16
|
+
* recorded as an item. A script that calls anything else stays as it is. */
|
|
17
|
+
export declare function codeModeWrapper(raw: Json): CodeModeWrapper | undefined;
|
|
18
|
+
/** The wrapper a numbered rollout's code-mode result answers, by call id. */
|
|
19
|
+
export declare function codeModeOutputCall(raw: Json): string | undefined;
|
|
20
|
+
/** A covered wrapper's result: an image viewer keeps only its pictures, a
|
|
21
|
+
* "Script completed"/"Script running" status is hidden (the items carry the
|
|
22
|
+
* actions), and a failure or abort is listed with the script it ended, whose
|
|
23
|
+
* own row was hidden, so the phone draws the pair. */
|
|
24
|
+
export declare function projectCodeModeOutput(raw: Json, call: Json | undefined): Json | undefined;
|
|
25
|
+
/** The wrapper call a result answers, found within the rows just before it
|
|
26
|
+
* (a script's own items sit between the two; 32 rows apart at most seen). */
|
|
27
|
+
export declare function findCodeModeCall(rows: (before: number, after: number) => AsyncIterable<{
|
|
28
|
+
line: number;
|
|
29
|
+
bytes?: Buffer;
|
|
30
|
+
}>, line: number, callId: string): Promise<Json | undefined>;
|
|
11
31
|
/** Codex 0.155 code mode: the model calls one generic tool whose input is
|
|
12
32
|
* JavaScript, and that source invokes `tools.apply_patch`/`tools.shell`/
|
|
13
33
|
* `tools.read`. The Hook resolves each invocation into the ordinary call the
|
|
@@ -90,8 +90,13 @@ export function visibleCodexEvent(raw) {
|
|
|
90
90
|
payload: { type: "error", ...(typeof p.message === "string" ? { message: p.message } : {}) } };
|
|
91
91
|
if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type)))
|
|
92
92
|
return raw;
|
|
93
|
+
if (raw.type === "event_msg" && p.type === "item_completed")
|
|
94
|
+
return itemCall(raw, object(p.item));
|
|
93
95
|
if (raw.type !== "response_item")
|
|
94
96
|
return undefined;
|
|
97
|
+
const wrapper = codeModeWrapper(raw);
|
|
98
|
+
if (wrapper)
|
|
99
|
+
return wrapper.images.length ? imageCall(raw, wrapper) : undefined;
|
|
95
100
|
if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
|
|
96
101
|
const text = typeof p.content === "string" ? p.content : objects(p.content).map(b => typeof b.text === "string" ? b.text : "").join("\n");
|
|
97
102
|
return p.role === "user" && harnessPreamble(text) ? undefined : raw;
|
|
@@ -100,6 +105,162 @@ export function visibleCodexEvent(raw) {
|
|
|
100
105
|
return raw;
|
|
101
106
|
return undefined;
|
|
102
107
|
}
|
|
108
|
+
/** Codex 0.155.1 and later number their rollout rows (`ordinal`) and record
|
|
109
|
+
* each action a code-mode script runs as its own `item_completed` row: the
|
|
110
|
+
* command and its output, the patch, the MCP call. The `exec` call wrapping
|
|
111
|
+
* those actions in JavaScript and its "Script completed" result only repeat
|
|
112
|
+
* them, so the phone reads the items as the ordinary calls it already draws. */
|
|
113
|
+
const OUTPUT_TAIL = 4_000, MCP_OUTPUT = 65_536, PATCH_FILE = 200_000, COMMAND = 16_384;
|
|
114
|
+
const WRAPPED_TOOL = /\btools\s*\.\s*([A-Za-z_$][\w$]*)\s*\(/g;
|
|
115
|
+
const VIEW_IMAGE = /\btools\s*\.\s*view_image\s*\(/g;
|
|
116
|
+
/** Tools whose every call Codex records as an item (`write_stdin` finishes
|
|
117
|
+
* the command it feeds; `view_image` has only a path item, so its picture is
|
|
118
|
+
* taken from the wrapper's own result). */
|
|
119
|
+
const ITEM_TOOLS = new Set(["exec_command", "write_stdin", "apply_patch", "view_image"]);
|
|
120
|
+
/** A numbered rollout's code-mode `exec` call whose every tool call is
|
|
121
|
+
* recorded as an item. A script that calls anything else stays as it is. */
|
|
122
|
+
export function codeModeWrapper(raw) {
|
|
123
|
+
const p = object(raw.payload), source = p.input, callId = p.call_id;
|
|
124
|
+
if (typeof raw.ordinal !== "number" || raw.type !== "response_item" || p.type !== "custom_tool_call" || p.name !== "exec")
|
|
125
|
+
return undefined;
|
|
126
|
+
if (typeof source !== "string" || typeof callId !== "string" || !callId || source.trimStart().startsWith("*** Begin Patch"))
|
|
127
|
+
return undefined;
|
|
128
|
+
const tools = [...source.matchAll(WRAPPED_TOOL)].map(match => match[1]);
|
|
129
|
+
if (!tools.length || !tools.every(tool => ITEM_TOOLS.has(tool) || /^mcp__\w+$/.test(tool)))
|
|
130
|
+
return undefined;
|
|
131
|
+
const images = [...source.matchAll(VIEW_IMAGE)].map(match => {
|
|
132
|
+
const args = callArguments(source, (match.index ?? 0) + match[0].length - 1);
|
|
133
|
+
return (args === undefined ? undefined : argumentString(args, source, ["path"])) ?? "";
|
|
134
|
+
});
|
|
135
|
+
return { callId, images };
|
|
136
|
+
}
|
|
137
|
+
/** A wrapper that viewed an image becomes the `view_image` call its result
|
|
138
|
+
* (the picture) pairs with; the ImageView item names only the path. */
|
|
139
|
+
function imageCall(raw, wrapper) {
|
|
140
|
+
const file = wrapper.images.find(Boolean);
|
|
141
|
+
return { type: "response_item", ...(raw.timestamp !== undefined ? { timestamp: raw.timestamp } : {}),
|
|
142
|
+
payload: { type: "function_call", name: "view_image", call_id: wrapper.callId, arguments: JSON.stringify(file ? { path: file.slice(0, 4_096) } : {}) } };
|
|
143
|
+
}
|
|
144
|
+
/** The wrapper a numbered rollout's code-mode result answers, by call id. */
|
|
145
|
+
export function codeModeOutputCall(raw) {
|
|
146
|
+
const p = object(raw.payload);
|
|
147
|
+
return typeof raw.ordinal === "number" && raw.type === "response_item" && p.type === "custom_tool_call_output"
|
|
148
|
+
&& typeof p.call_id === "string" && p.call_id ? p.call_id : undefined;
|
|
149
|
+
}
|
|
150
|
+
/** A covered wrapper's result: an image viewer keeps only its pictures, a
|
|
151
|
+
* "Script completed"/"Script running" status is hidden (the items carry the
|
|
152
|
+
* actions), and a failure or abort is listed with the script it ended, whose
|
|
153
|
+
* own row was hidden, so the phone draws the pair. */
|
|
154
|
+
export function projectCodeModeOutput(raw, call) {
|
|
155
|
+
const wrapper = call && codeModeWrapper(call);
|
|
156
|
+
if (!call || !wrapper)
|
|
157
|
+
return raw;
|
|
158
|
+
const p = object(raw.payload), blocks = Array.isArray(p.output) ? objects(p.output) : [];
|
|
159
|
+
const images = blocks.filter(block => ["input_image", "image"].includes(String(block.type)));
|
|
160
|
+
// The view_image call is already listed on the script's own row.
|
|
161
|
+
if (wrapper.images.length)
|
|
162
|
+
return images.length ? { ...raw, payload: { ...p, output: images } } : raw;
|
|
163
|
+
const text = typeof p.output === "string" ? p.output : blocks.map(block => typeof block.text === "string" ? block.text : "").join("\n");
|
|
164
|
+
if (/^Script (completed|running)\b/.test(text))
|
|
165
|
+
return undefined;
|
|
166
|
+
return { type: "response_item", ...(call.timestamp !== undefined ? { timestamp: call.timestamp } : {}),
|
|
167
|
+
payload: { type: "custom_tool_call", name: "exec", call_id: wrapper.callId, input: object(call.payload).input }, phren_item_output: raw };
|
|
168
|
+
}
|
|
169
|
+
/** The wrapper call a result answers, found within the rows just before it
|
|
170
|
+
* (a script's own items sit between the two; 32 rows apart at most seen). */
|
|
171
|
+
export async function findCodeModeCall(rows, line, callId) {
|
|
172
|
+
const needle = Buffer.from(JSON.stringify(callId));
|
|
173
|
+
for await (const row of rows(line, Math.max(0, line - 256))) {
|
|
174
|
+
if (!row.bytes?.includes(needle))
|
|
175
|
+
continue;
|
|
176
|
+
try {
|
|
177
|
+
const raw = object(JSON.parse(row.bytes.toString())), p = object(raw.payload);
|
|
178
|
+
if (raw.type === "response_item" && p.type === "custom_tool_call" && p.call_id === callId)
|
|
179
|
+
return raw;
|
|
180
|
+
}
|
|
181
|
+
catch { /* Not the call. */ }
|
|
182
|
+
}
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
/** A shell command as the terminal shows it: the script a `sh -lc` runs. */
|
|
186
|
+
function commandText(value) {
|
|
187
|
+
if (typeof value === "string")
|
|
188
|
+
return value;
|
|
189
|
+
const parts = Array.isArray(value) ? value.filter((part) => typeof part === "string") : [];
|
|
190
|
+
if (parts.length === 3 && ["-lc", "-c"].includes(parts[1]) && /(^|\/)(ba|z|da|fi|k)?sh$/.test(parts[0]))
|
|
191
|
+
return parts[2];
|
|
192
|
+
return parts.join(" ");
|
|
193
|
+
}
|
|
194
|
+
function localPath(value) {
|
|
195
|
+
if (typeof value !== "string" || !value)
|
|
196
|
+
return undefined;
|
|
197
|
+
// The URL names a path on the computer Codex ran on, which may not follow
|
|
198
|
+
// this platform's rules (fileURLToPath refuses `file:///work` on Windows).
|
|
199
|
+
if (value.startsWith("file://")) {
|
|
200
|
+
try {
|
|
201
|
+
const url = new URL(value);
|
|
202
|
+
if (url.host)
|
|
203
|
+
return undefined;
|
|
204
|
+
const pathname = decodeURIComponent(url.pathname);
|
|
205
|
+
return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return value.startsWith("/") ? value : undefined;
|
|
212
|
+
}
|
|
213
|
+
/** A FileChange's files as the apply_patch text the patch card draws. */
|
|
214
|
+
function changePatch(changes) {
|
|
215
|
+
const sections = Object.entries(object(changes)).slice(0, 50).map(([file, value]) => {
|
|
216
|
+
const change = object(value), kind = String(change.type ?? "update");
|
|
217
|
+
if (kind === "add") {
|
|
218
|
+
const content = typeof change.content === "string" ? change.content.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
219
|
+
return `*** Add File: ${file}\n` + content.split("\n").map(line => "+" + line).join("\n");
|
|
220
|
+
}
|
|
221
|
+
if (kind === "delete")
|
|
222
|
+
return `*** Delete File: ${file}`;
|
|
223
|
+
const moved = typeof change.move_path === "string" && change.move_path ? `\n*** Move to: ${change.move_path}` : "";
|
|
224
|
+
const diff = typeof change.unified_diff === "string" ? change.unified_diff.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
225
|
+
return `*** Update File: ${file}${moved}${diff ? "\n" + diff : ""}`;
|
|
226
|
+
});
|
|
227
|
+
return ["*** Begin Patch", ...sections, "*** End Patch"].join("\n");
|
|
228
|
+
}
|
|
229
|
+
/** An action item as the call the phone draws, carrying its result under
|
|
230
|
+
* `phren_item_output` for the reader to list right after it. Reasoning,
|
|
231
|
+
* messages (already rows of their own) and bookkeeping items stay hidden. */
|
|
232
|
+
function itemCall(raw, item) {
|
|
233
|
+
const id = typeof item.id === "string" && item.id ? item.id.slice(0, 200) : "";
|
|
234
|
+
if (!id)
|
|
235
|
+
return undefined;
|
|
236
|
+
const stamp = raw.timestamp !== undefined ? { timestamp: raw.timestamp } : {};
|
|
237
|
+
const row = (call, output) => ({ type: "response_item", ...stamp, payload: { ...call, call_id: id },
|
|
238
|
+
phren_item_output: { type: "response_item", ...stamp, payload: { ...output, call_id: id } } });
|
|
239
|
+
const status = typeof item.status === "string" ? item.status : "completed";
|
|
240
|
+
switch (item.type) {
|
|
241
|
+
case "CommandExecution": {
|
|
242
|
+
const workdir = localPath(item.cwd);
|
|
243
|
+
const text = [item.aggregated_output, item.formatted_output].find(v => typeof v === "string")
|
|
244
|
+
?? [item.stdout, item.stderr].filter(v => typeof v === "string").join("");
|
|
245
|
+
const tail = text.slice(-OUTPUT_TAIL);
|
|
246
|
+
const output = typeof item.exit_code === "number" ? JSON.stringify({ output: tail, exit_code: item.exit_code })
|
|
247
|
+
: `${tail}${tail && !tail.endsWith("\n") ? "\n" : ""}[${status}]`;
|
|
248
|
+
return row({ type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText(item.command).slice(0, COMMAND), ...(workdir ? { workdir } : {}) }) }, { type: "function_call_output", output });
|
|
249
|
+
}
|
|
250
|
+
case "FileChange": {
|
|
251
|
+
const said = [status === "completed" ? item.stdout : item.stderr, item.stdout, item.stderr].find(v => typeof v === "string" && v.trim());
|
|
252
|
+
return row({ type: "custom_tool_call", name: "apply_patch", input: changePatch(item.changes) }, { type: "custom_tool_call_output", output: (said ?? status).slice(-OUTPUT_TAIL) });
|
|
253
|
+
}
|
|
254
|
+
case "McpToolCall": {
|
|
255
|
+
const result = object(item.result), ok = object(result.Ok ?? result), error = result.Err ?? item.error;
|
|
256
|
+
const text = objects(ok.content).filter(block => block.type === "text" && typeof block.text === "string").map(block => String(block.text)).join("\n");
|
|
257
|
+
const output = text || (error !== undefined && error !== null ? (typeof error === "string" ? error : JSON.stringify(error)) : status);
|
|
258
|
+
const args = typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {});
|
|
259
|
+
return row({ type: "function_call", name: `mcp__${String(item.server ?? "mcp")}__${String(item.tool ?? "tool")}`, arguments: args.slice(0, 262_144) }, { type: "function_call_output", output: output.slice(0, MCP_OUTPUT) });
|
|
260
|
+
}
|
|
261
|
+
default: return undefined;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
103
264
|
const CODE_TOOL_CALL = /\btools\s*\.\s*(apply_patch|shell|read)\s*\(/g;
|
|
104
265
|
const JS_ESCAPES = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v", "0": "\0", "'": "'", '"': '"', "\\": "\\", "/": "/" };
|
|
105
266
|
function unescapeJs(value) {
|
|
@@ -167,7 +328,9 @@ function callArguments(source, open) {
|
|
|
167
328
|
}
|
|
168
329
|
return undefined;
|
|
169
330
|
}
|
|
170
|
-
|
|
331
|
+
/** A string argument: a literal, a string identifier, or one of `keys` in an
|
|
332
|
+
* object literal. */
|
|
333
|
+
function argumentString(expression, source, keys) {
|
|
171
334
|
const inline = resolveString(expression, source);
|
|
172
335
|
if (inline !== undefined)
|
|
173
336
|
return inline;
|
|
@@ -177,9 +340,12 @@ function shellCommand(expression, source) {
|
|
|
177
340
|
const body = inner.trim();
|
|
178
341
|
if (/^[A-Za-z_$][\w$]*$/.test(body))
|
|
179
342
|
return resolveString(body, source);
|
|
180
|
-
const property =
|
|
343
|
+
const property = new RegExp(`(?:^|[,{])\\s*(?:${keys.join("|")})\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|[A-Za-z_$][\\w$]*)`).exec(body);
|
|
181
344
|
return property ? resolveString(property[1], source) : undefined;
|
|
182
345
|
}
|
|
346
|
+
function shellCommand(expression, source) {
|
|
347
|
+
return argumentString(expression, source, ["command", "cmd"]);
|
|
348
|
+
}
|
|
183
349
|
/** Every recognized invocation in a code-mode source, in the order written. */
|
|
184
350
|
export function codeToolCalls(source) {
|
|
185
351
|
const calls = [], original = source.slice(0, 262_144);
|
|
@@ -253,6 +419,15 @@ function renameProjectedChanges(raw, base) {
|
|
|
253
419
|
export function projectCodexRow(raw) {
|
|
254
420
|
if (raw.type !== "response_item")
|
|
255
421
|
return { rows: [raw] };
|
|
422
|
+
if (raw.phren_item_output !== undefined) {
|
|
423
|
+
// An item's call and result, or a failed script listed with its result.
|
|
424
|
+
// Only the script is source to project; an item's patch text is not.
|
|
425
|
+
const { phren_item_output: output, ...call } = raw, result = object(output);
|
|
426
|
+
const expanded = object(call.payload).name === "exec" ? projectCodexRow(call) : { rows: [call] };
|
|
427
|
+
if (!expanded.base)
|
|
428
|
+
return { rows: [...expanded.rows, result] };
|
|
429
|
+
return { rows: [...expanded.rows, { ...result, payload: { ...object(result.payload), call_id: `${expanded.base}:1` } }] };
|
|
430
|
+
}
|
|
256
431
|
const payload = object(raw.payload), type = String(payload.type), callId = typeof payload.call_id === "string" ? payload.call_id : "";
|
|
257
432
|
if (type === "custom_tool_call" || type === "function_call") {
|
|
258
433
|
const source = codeToolSource(payload.input ?? payload.arguments);
|
|
@@ -9,7 +9,7 @@ import { materializeCodexThread, materializedRoot } from "./codex-threads.js";
|
|
|
9
9
|
import { namedPaths, SHELL_TOOLS, outputCallIds } from "./changes.js";
|
|
10
10
|
import { fanoutChildren } from "./fanouts.js";
|
|
11
11
|
import { claudeChildAgents, visibleClaudeEvent } from "./transcript-claude.js";
|
|
12
|
-
import { childTranscriptBelongsTo, directChildAgents, projectCodexRow, rewriteProjectedOutput, visibleCodexEvent } from "./transcript-codex.js";
|
|
12
|
+
import { childTranscriptBelongsTo, codeModeOutputCall, directChildAgents, findCodeModeCall, projectCodeModeOutput, projectCodexRow, rewriteProjectedOutput, visibleCodexEvent } from "./transcript-codex.js";
|
|
13
13
|
import { visibleCopilotEvent } from "./transcript-copilot.js";
|
|
14
14
|
import { visibleOpencodeEvent } from "./transcript-opencode.js";
|
|
15
15
|
export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
|
|
@@ -285,6 +285,11 @@ export class TranscriptReader {
|
|
|
285
285
|
const { isSidechain: _sidechain, ...own } = raw;
|
|
286
286
|
raw = own;
|
|
287
287
|
}
|
|
288
|
+
// A code-mode script's result follows from the script it answers,
|
|
289
|
+
// a few rows earlier: hidden when its items carry the actions.
|
|
290
|
+
const codeModeCall = raw && this.source === "codex" ? codeModeOutputCall(raw) : undefined;
|
|
291
|
+
if (raw && codeModeCall)
|
|
292
|
+
raw = projectCodeModeOutput(raw, await findCodeModeCall((upper, lower) => index.rows(handle, upper, lower, signal), row.line, codeModeCall));
|
|
288
293
|
if (raw) {
|
|
289
294
|
if (this.changes && this.imageLine === undefined) {
|
|
290
295
|
// A shell call's output carries what it changed on disk. While
|
package/dist/bridge/usage.js
CHANGED
|
@@ -8,6 +8,7 @@ import { promisify } from "node:util";
|
|
|
8
8
|
import { fanoutRoot } from "./fanouts.js";
|
|
9
9
|
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
10
10
|
import { stripTerminal } from "../terminal-text.js";
|
|
11
|
+
import { codexExecutable } from "./codex-binary.js";
|
|
11
12
|
const exec = promisify(execFile);
|
|
12
13
|
const claudeFile = () => path.join(bridgeRoot(), "usage", "claude.json");
|
|
13
14
|
const safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : undefined;
|
|
@@ -648,7 +649,7 @@ async function liveClaudeUsage(now) {
|
|
|
648
649
|
}
|
|
649
650
|
}
|
|
650
651
|
/** Only initialize and read limits. Never create a thread, prompt, or login. */
|
|
651
|
-
export function readCodexLimits(executable =
|
|
652
|
+
export function readCodexLimits(executable = codexExecutable()) {
|
|
652
653
|
return new Promise(resolve => {
|
|
653
654
|
const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
|
|
654
655
|
let pending = "", bytes = 0, initialized = false, done = false;
|