@phren/cli
Version:
Knowledge layer for AI agents - CLI, MCP server, and data layer
687 lines (686 loc) • 34.8 kB
JavaScript
import { createHash } from "node:crypto";
import { statSync } from "node:fs";
import { mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
import { codexHome } from "../home-paths.js";
import path from "node:path";
import { atomic, bridgeRoot, object, objects, sessionId } from "./protocol.js";
/** Codex 0.155 keeps a thread's history in `thread_history_1.sqlite` and no
* longer writes the rollout file its `state_5.sqlite` still names. The Hook
* materializes such a thread into a rollout-shaped JSONL of its own, append
* only, so every reader of Codex transcripts keeps working unchanged. */
const OUTPUT_TAIL = 4_000;
const STALLED_AFTER_MS = 10 * 60 * 1_000;
export function materializedRoot() { return path.join(bridgeRoot(), "codex-threads"); }
export function materializedPath(session) { return path.join(materializedRoot(), `${session}.jsonl`); }
const historyFile = () => path.join(codexHome(), "thread_history_1.sqlite");
async function openReadOnly(file) {
try {
const sqlite = await import("node:sqlite");
return new sqlite.DatabaseSync(file, { readOnly: true });
}
catch {
return undefined;
}
}
// Windows reports no usable inode and opens without FILE_SHARE_DELETE, so the file cannot be replaced while cached.
function fileIdentity(file) {
try {
const info = statSync(file);
return info.ino === 0 ? undefined : `${info.dev}:${info.ino}`;
}
catch {
return undefined;
}
}
/** The read-only Codex stores one request shares across every thread it
* discovers or materializes. Opening the same SQLite file per thread is a real
* per-item cost, especially on Windows. A replaced or rotated file is
* detected once per get() and reopened rather than read through the old handle. */
class ReadOnlyConnections {
connections = new Map();
opening = new Map();
async get(file) {
const identity = fileIdentity(file);
const cached = this.connections.get(file);
if (cached && (identity === undefined || cached.identity === identity))
return cached.db;
if (cached) {
cached.db?.close();
this.connections.delete(file);
}
let opening = this.opening.get(file);
if (!opening) {
opening = openReadOnly(file).then(db => ({ identity, db }));
this.opening.set(file, opening);
}
const opened = await opening;
this.opening.delete(file);
const current = this.connections.get(file);
if (current && (identity === undefined || current.identity === identity))
return current.db;
current?.db?.close();
this.connections.set(file, opened);
return opened.db;
}
async close() {
const opening = [...this.opening.values()];
this.opening.clear();
for (const { db } of this.connections.values())
db?.close();
this.connections.clear();
for (const { db } of await Promise.all(opening))
db?.close();
}
}
async function sessionsFrom(history, limit, after) {
if (!history)
return [];
try {
return objects(history.prepare(`select distinct thread_id from thread_items
where thread_id > ? order by thread_id limit ?`).all(after, limit))
.map(row => String(row.thread_id));
}
catch {
return [];
}
}
/** Codex 0.155 threads the SQLite store knows, by stable thread identity. Search
* uses this to discover threads that have no rollout file to glob. */
export async function codexThreadSessions(limit = 5_000, after = "") {
const connections = new ReadOnlyConnections();
try {
return await sessionsFrom(await connections.get(historyFile()), limit, after);
}
finally {
await connections.close();
}
}
async function turnSettledFrom(history, session, turn) {
if (!history || !turn)
return undefined;
try {
const row = object(history.prepare("select status from thread_turns where thread_id = ? and turn_id = ?").get(session, turn));
return typeof row.status === "string" ? row.status !== "inProgress" : undefined;
}
catch {
return undefined;
}
}
/** The materialized row retains its original turn, independently of whichever
* turn happens to be active when search catches up. */
export async function codexTurnSettled(session, turn) {
const connections = new ReadOnlyConnections();
try {
return await turnSettledFrom(await connections.get(historyFile()), session, turn);
}
finally {
await connections.close();
}
}
export function openCodexThreadStore() {
const connections = new ReadOnlyConnections();
return {
sessions: async (limit = 5_000, after = "") => sessionsFrom(await connections.get(historyFile()), limit, after),
turnSettled: async (session, turn) => turnSettledFrom(await connections.get(historyFile()), session, turn),
materialize: (session, deadline = Infinity, maxItems = Infinity) => runMaterialization(session, deadline, maxItems, connections),
close: () => connections.close(),
};
}
/** A working pane whose projection cursor stopped at an unfinished turn can
* keep accepting input even though none of it will be readable again. */
export async function threadHealth(session, agentStatus) {
if (!sessionId.safeParse(session).success || !["working", "blocked", "waiting"].includes(String(agentStatus)))
return { stalled: false };
const stateFile = materializedPath(session) + ".state.json";
let cursor, cursorMtime;
try {
cursor = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {}, ...object(JSON.parse(await readFile(stateFile, "utf8"))) };
cursorMtime = (await stat(stateFile)).mtimeMs;
}
catch {
return { stalled: false };
}
if (Date.now() - cursorMtime < STALLED_AFTER_MS)
return { stalled: false };
const history = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
if (!history)
return { stalled: false };
try {
const summary = object(history.prepare("select count(*) as n, max(rollout_ordinal) as last, max(updated_at_ordinal) as updated from thread_items where thread_id = ?").get(session));
// The store may have advanced just before the materializer catches up.
if (cursor.count !== Number(summary.n) || cursor.lastOrdinal !== Number(summary.last) || cursor.maxUpdated !== Number(summary.updated))
return { stalled: false };
const turn = object(history.prepare("select status, rollout_end_ordinal from thread_turns where thread_id = ? order by rollout_ordinal desc limit 1").get(session));
if (turn.status !== "inProgress" || turn.rollout_end_ordinal !== null)
return { stalled: false };
return { stalled: true, since: new Date(cursorMtime).toISOString() };
}
catch {
return { stalled: false };
}
finally {
history.close();
}
}
const materializations = new Map();
/** The thread store accumulates agent-message deltas in place. Only text
* from the newest unfinished message is public; reasoning is never read out. */
function pendingMessage(history, session) {
const turn = object(history.prepare("select turn_id, status, started_at from thread_turns where thread_id = ? order by rollout_ordinal desc limit 1").get(session));
if (turn.status !== "inProgress")
return undefined;
// Queued steering can be appended while the current reply is still growing.
// It does not finish that reply or make its partial text safe to persist.
const row = object(history.prepare(`select item_json from thread_items where thread_id = ? and turn_id = ?
and not (item_type = 'userMessage' and case when json_valid(item_json)
then coalesce(json_extract(item_json, '$.status'), '') else '' end = 'queued')
order by rollout_ordinal desc limit 1`).get(session, turn.turn_id));
let item;
try {
item = object(JSON.parse(String(row.item_json)));
}
catch {
return undefined;
}
if (item.type !== "agentMessage" || finished(item) || item.delivery === "async")
return undefined;
const started = Number(turn.started_at);
if (!Number.isFinite(started) || started <= 0)
return undefined;
return { id: String(item.id), turnStartedAt: new Date(started > 1e12 ? started : started * 1000).toISOString(),
text: typeof item.text === "string" ? item.text.slice(0, 32_768) : "" };
}
export async function codexThreadPreview(session) {
if (!sessionId.safeParse(session).success)
return undefined;
const history = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
if (!history)
return undefined;
try {
const pending = pendingMessage(history, session);
return pending?.text ? { turnStartedAt: pending.turnStartedAt, text: pending.text } : undefined;
}
catch {
return undefined;
}
finally {
history.close();
}
}
async function runMaterialization(session, deadline, maxItems, shared) {
if (!sessionId.safeParse(session).success)
return undefined;
const key = materializedPath(session);
const pending = materializations.get(key);
if (pending)
return pending;
const connections = shared ?? new ReadOnlyConnections();
const work = materializeThread(session, deadline, maxItems, connections)
.finally(() => shared ? undefined : connections.close());
materializations.set(key, work);
try {
return await work;
}
finally {
materializations.delete(key);
}
}
/** Bring the materialized file up to date with the store. Returns the file
* when the thread exists there, undefined otherwise. Safe to call often:
* an unchanged thread costs one aggregate query. */
export async function materializeCodexThread(session, deadline = Infinity, maxItems = Infinity) {
return runMaterialization(session, deadline, maxItems);
}
async function materializeThread(session, deadline, maxItems, connections) {
if (!sessionId.safeParse(session).success)
return undefined;
const history = await connections.get(historyFile());
if (!history)
return undefined;
try {
const summary = object(history.prepare("select count(*) as n, max(rollout_ordinal) as last, max(updated_at_ordinal) as updated from thread_items where thread_id = ?").get(session));
if (!Number(summary.n))
return undefined;
const file = materializedPath(session), stateFile = file + ".state.json";
await mkdir(materializedRoot(), { recursive: true, mode: 0o700 });
let state = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {} };
try {
state = { ...state, ...object(JSON.parse(await readFile(stateFile, "utf8"))) };
}
catch { /* first time */ }
// Older projections lack complete turn identities or update cursors. Rebuild the cache
// beside the live file, then replace it atomically; the transcript reader
// observes the new inode and resets its revision and row numbers together.
const upgrading = state.version !== 2 && (state.count > 0 || state.scanOrdinal !== undefined);
const outputFile = upgrading ? file + ".building" : file;
const progressFile = upgrading ? outputFile + ".state.json" : stateFile;
if (upgrading) {
if (!state.upgrading)
await atomic(stateFile, JSON.stringify({ ...state, upgrading: true }));
state = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {} };
try {
state = { ...state, ...object(JSON.parse(await readFile(progressFile, "utf8"))) };
}
catch { /* first upgrade batch */ }
if (state.version !== 2) {
state = { lastOrdinal: -1, maxUpdated: -1, count: 0, done: {} };
await rm(outputFile, { force: true });
}
}
state.version = 2;
const fresh = state.count === 0 && state.scanOrdinal === undefined;
let turn = {};
try {
turn = object(history.prepare("select turn_id, status from thread_turns where thread_id = ? order by rollout_ordinal desc limit 1").get(session));
}
catch { /* legacy store without turn metadata */ }
const turnSignature = JSON.stringify(turn);
if (Number(summary.last) > (state.scanOrdinal ?? -1))
state.forwardDone = false;
if (!upgrading && !Object.keys(state.deferred ?? {}).length && state.forwardDone && state.updateTarget === undefined && !fresh && state.count === Number(summary.n)
&& state.lastOrdinal === Number(summary.last) && state.maxUpdated === Number(summary.updated) && state.turnSignature === turnSignature)
return file;
let pending;
try {
pending = pendingMessage(history, session);
}
catch { /* legacy store without item turn identities */ }
state.deferred ??= {};
const columns = new Set(objects(history.prepare("PRAGMA table_info(thread_items)").all()).map(row => String(row.name)));
const stamps = new Map();
const lines = [];
if (fresh) {
const meta = await threadMeta(session, connections);
lines.push(JSON.stringify({ type: "session_meta", payload: { id: session, ...(meta.cwd ? { cwd: meta.cwd } : {}),
source: meta.spawn ? { subagent: { thread_spawn: meta.spawn } } : "codex-thread-store" } }));
if (meta.model)
lines.push(JSON.stringify({ type: "turn_context", payload: { model: meta.model } }));
}
const emit = (row) => {
if (typeof row.turn_id === "string" && !stamps.has(String(row.turn_id))) {
let turn = {};
try {
turn = object(history.prepare("select started_at from thread_turns where thread_id = ? and turn_id = ?").get(session, row.turn_id));
}
catch { /* unavailable in legacy stores */ }
stamps.set(String(row.turn_id), epochMs(turn.started_at) ?? 0);
}
let item;
try {
item = object(JSON.parse(String(row.item_json)));
}
catch {
return;
}
const id = String(item.id ?? `ordinal-${row.rollout_ordinal}`), emitted = state.done[id];
if (item.type === "agentMessage" && id === pending?.id) {
state.deferred[id] = String(row.item_id);
return;
}
delete state.deferred[id];
const calls = callRows(item), output = outputRow(item);
// Preserve only queue state actually recorded by the harness. The
// append-only transcript pairs the queued user row with a content-free
// consumption marker when that same item leaves the queue.
if (emitted === "queued" && item.type === "userMessage" && item.status !== "queued") {
lines.push(JSON.stringify({ type: "phren_queue_consumed", key: queueKey(session, id), phrenTurnId: row.turn_id }));
state.done[id] = "done";
return;
}
if (!emitted) {
if (calls) {
for (const call of calls)
lines.push(JSON.stringify(call));
state.done[id] = "call";
}
else if (subAgentRow(item)) {
// A child Codex agent (spawn, interaction, completion) rides along
// as the event the rollout carried before 0.155, so the child
// agent tree keeps finding native subagents.
lines.push(JSON.stringify(subAgentRow(item)));
state.done[id] = "done";
return;
}
else if (messageRow(item)) {
const at = rowTime(row, item, stamps);
const message = { ...messageRow(item), phrenTurnId: row.turn_id, ...(at ? { timestamp: at } : {}) };
const queued = item.type === "userMessage" && item.status === "queued";
lines.push(JSON.stringify(queued ? { ...message, phrenQueued: true, phrenQueueKey: queueKey(session, id) } : message));
// A question the agent asked (delivered async) rides along as the
// same event the rollout would carry, so the pending scan sees it.
const asked = questionEvent(item);
if (asked)
lines.push(JSON.stringify(asked));
state.done[id] = queued ? "queued" : "done";
return;
}
else if (isQueuedQuestionItem(item)) {
// The queued follow-up question reads in the transcript as the
// asking sentence; the Hook answers it from the store, not by
// quoting a reply, so no async event rides along here.
const title = questionTitle(objects(item.questions));
if (title)
lines.push(JSON.stringify({ type: "response_item", phrenTurnId: row.turn_id, timestamp: rowTime(row, item, stamps), payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: title }] } }));
state.done[id] = "done";
return;
}
else
return;
}
if (state.done[id] === "call" && output) {
lines.push(JSON.stringify(output));
state.done[id] = "done";
}
};
let processed = 0;
// Skipped streaming replies are retried independently of forward progress,
// including completion signalled only in thread_turns (no item update).
for (const [id, item] of Object.entries(state.deferred)) {
if (processed >= Math.min(16, maxItems) || Date.now() >= deadline)
break;
processed++;
const row = itemById(history, session, columns, item);
if (row)
emit(row);
else
delete state.deferred[id];
}
// Freeze each update pass at its own high watermark. Ongoing writes start
// another pass afterward; they never rewind the historical forward cursor.
if (state.updateTarget === undefined && Number(summary.updated) > state.maxUpdated)
state.updateTarget = Number(summary.updated);
const updateLimit = maxItems === Infinity ? Infinity : Math.min(maxItems, processed + 32);
while (state.updateTarget !== undefined && processed < updateLimit && Date.now() < deadline) {
const rows = itemRows(history, session, columns, state, true);
if (!rows.length) {
state.maxUpdated = state.updateTarget;
delete state.updateTarget;
delete state.updateAt;
delete state.updateOrdinal;
delete state.updateItem;
break;
}
for (const row of rows) {
if (processed >= updateLimit || Date.now() >= deadline)
break;
processed++;
emit(row);
state.updateAt = Number(row.updated_at_ordinal);
state.updateOrdinal = Number(row.rollout_ordinal);
state.updateItem = String(row.item_id);
}
}
while (processed < maxItems && Date.now() < deadline) {
const rows = itemRows(history, session, columns, state, false);
if (!rows.length) {
state.forwardDone = true;
state.count = Number(summary.n);
state.lastOrdinal = Number(summary.last);
break;
}
state.forwardDone = false;
for (const row of rows) {
if (processed >= maxItems || Date.now() >= deadline)
break;
processed++;
emit(row);
state.scanOrdinal = Number(row.rollout_ordinal);
state.scanItem = String(row.item_id);
}
}
state.turnSignature = turnSignature;
if (lines.length) {
const handle = await open(outputFile, "a", 0o600);
try {
await handle.appendFile(lines.join("\n") + "\n");
}
finally {
await handle.close();
}
}
await atomic(progressFile, JSON.stringify(state));
if (upgrading && state.forwardDone && state.updateTarget === undefined) {
await rename(outputFile, file);
await atomic(stateFile, JSON.stringify(state));
await rm(progressFile, { force: true });
}
return file;
}
catch {
return undefined;
}
}
/** The thread's items in order, with when each was created where the store records it (`created_at_ms`, absent
* from some stores) and its turn. */
function itemProjection(columns) {
const key = columns.has("item_id") ? "item_id" : "CAST(rollout_ordinal AS TEXT)";
return { key, fields: `rollout_ordinal, ${key} AS item_id, item_type, item_json, updated_at_ordinal,
${columns.has("turn_id") ? "turn_id" : "NULL AS turn_id"}, ${columns.has("created_at_ms") ? "created_at_ms" : "NULL AS created_at_ms"}` };
}
function itemRows(history, session, columns, state, updates) {
const { key, fields } = itemProjection(columns);
return objects(updates
? history.prepare(`SELECT ${fields} FROM thread_items WHERE thread_id = ? AND updated_at_ordinal > ? AND updated_at_ordinal <= ?
AND (updated_at_ordinal, rollout_ordinal, ${key}) > (?, ?, ?)
ORDER BY updated_at_ordinal, rollout_ordinal, ${key} LIMIT 128`)
.all(session, state.maxUpdated, state.updateTarget, state.updateAt ?? -1, state.updateOrdinal ?? -1, state.updateItem ?? "")
: history.prepare(`SELECT ${fields} FROM thread_items WHERE thread_id = ? AND (rollout_ordinal, ${key}) > (?, ?)
ORDER BY rollout_ordinal, ${key} LIMIT 128`).all(session, state.scanOrdinal ?? -1, state.scanItem ?? ""));
}
function itemById(history, session, columns, item) {
const { key, fields } = itemProjection(columns);
const row = history.prepare(`SELECT ${fields} FROM thread_items WHERE thread_id = ? AND ${key} = ? LIMIT 1`).get(session, item);
return row ? object(row) : undefined;
}
/** Seconds or milliseconds since the epoch, as milliseconds; undefined for anything else. */
function epochMs(value) {
const number = Number(value);
if (value === null || value === undefined || !Number.isFinite(number) || number <= 0)
return undefined;
return number > 1e12 ? number : number * 1000;
}
/**
* A materialized row's `timestamp`, as a rollout row carries one: when its item was created. The Hook settles a
* phone message only from rows stamped after it was typed, so an older identical message (an earlier "yes") is
* never taken for a new one. A user row the store keeps no creation time for has no stamp: its turn's start
* would be older than a steer typed during the turn, which the scan would then drop; unstamped, its position
* after the message's cursor decides, as before. An assistant row falls back to its turn's start.
*/
function rowTime(row, item, turns) {
const at = epochMs(row.created_at_ms) ?? (item.type === "userMessage" || row.turn_id === undefined ? undefined : turns.get(String(row.turn_id)));
return at ? new Date(at).toISOString() : undefined;
}
/** Codex 0.155 stores a child agent's lifecycle as `subAgentActivity` items
* with camelCase fields; the rollout shape the child tree parses is the
* `SubAgentActivity` event with snake_case fields. */
function subAgentRow(item) {
if (item.type !== "subAgentActivity")
return undefined;
const kind = String(item.kind ?? ""), child = String(item.agentThreadId ?? item.agent_thread_id ?? "");
if (!child)
return undefined;
return { type: "event_msg", payload: { type: "item_completed", item: {
type: "SubAgentActivity", id: String(item.id ?? ""), kind,
agent_thread_id: child, agent_path: String(item.agentPath ?? item.agent_path ?? ""),
} } };
}
async function threadMeta(session, connections) {
const db = await connections.get(path.join(codexHome(), "state_5.sqlite"));
if (!db)
return {};
try {
const row = object(db.prepare("select model, cwd from threads where id = ?").get(session));
let spawn;
try {
// Older stores have no `source` column; a child thread's names its parent there.
const source = object(db.prepare("select source from threads where id = ?").get(session)).source;
if (typeof source === "string" && source.startsWith("{")) {
const parsed = object(object(JSON.parse(source)).subagent).thread_spawn;
if (parsed && typeof parsed === "object" && Object.keys(parsed).length)
spawn = parsed;
}
}
catch { /* no source column or plain text */ }
return { ...(typeof row.model === "string" && row.model ? { model: row.model } : {}), ...(typeof row.cwd === "string" && row.cwd ? { cwd: row.cwd } : {}), ...(spawn ? { spawn } : {}) };
}
catch {
return {};
}
}
function finished(item) { return ["completed", "failed", "declined", "error"].includes(String(item.status)) || item.exitCode !== undefined && item.exitCode !== null; }
function queueKey(session, id) {
return createHash("sha256").update(`${session}\0${id}`).digest("hex");
}
/** A message row, for the two message kinds. */
function messageRow(item) {
if (item.type === "userMessage") {
const text = objects(item.content).filter(b => b.type === "text" && typeof b.text === "string").map(b => String(b.text)).join("\n");
return text ? { type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text }] } } : undefined;
}
if (item.type === "agentMessage" && typeof item.text === "string" && item.text) {
return { type: "response_item", payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: item.text }] } };
}
return undefined;
}
/** Codex 0.155 asks through an agent message with `questions` attached. */
function questionEvent(item) {
if (item.type !== "agentMessage" || item.delivery !== "async" || !Array.isArray(item.questions) || !item.questions.length)
return undefined;
return { type: "event_msg", payload: { type: "item_completed", item: { type: "AgentMessage", id: String(item.id ?? ""),
content: [{ type: "Text", text: String(item.text ?? "") }], delivery: "async", questions: objects(item.questions).slice(0, 8) } } };
}
/** Codex 0.155 records a queued follow-up question as its own thread item
* (`question` or `requestUserInput`), not as a delivered async agent message.
* It sits under the terminal's "Queued follow-up inputs" until alt+up opens
* it, so the Hook reads its text and options straight from the store. */
const QUEUED_QUESTION_TYPES = new Set(["question", "requestUserInput"]);
function isQueuedQuestionItem(item) { return QUEUED_QUESTION_TYPES.has(String(item.type)); }
function questionAnswered(item) {
if (item.answers !== undefined && item.answers !== null)
return true;
return ["answered", "completed", "resolved", "cancelled", "canceled", "error", "declined"].includes(String(item.status ?? ""));
}
function questionTitle(questions) {
return questions.map(raw => {
const q = object(raw);
const text = [q.question, q.title].find(v => typeof v === "string" && v.trim());
return typeof text === "string" ? text.trim() : "";
}).filter(Boolean).join("\n\n").slice(0, 4_000);
}
function questionOptionLabels(questions) {
const first = object(questions[0]);
const raw = first.options;
if (!Array.isArray(raw))
return [];
return raw.map(option => {
if (typeof option === "string")
return option.trim();
const label = object(option).label;
return typeof label === "string" ? label.trim() : "";
}).filter(Boolean).slice(0, 12);
}
/** The pending queued question as the pane's choice shape: the asking
* sentence and one numbered option per choice (Codex answers with number
* keys once alt+up has opened the queue). Undefined when nothing answerable
* remains. */
export async function queuedQuestion(session) {
if (!sessionId.safeParse(session).success)
return undefined;
const db = await openReadOnly(path.join(codexHome(), "thread_history_1.sqlite"));
if (!db)
return undefined;
try {
const rows = objects(db.prepare("select item_json from thread_items where thread_id = ? and item_type in ('question', 'requestUserInput') order by rollout_ordinal desc limit 32").all(session));
for (const row of rows) {
let item;
try {
item = object(JSON.parse(String(row.item_json)));
}
catch {
continue;
}
if (questionAnswered(item))
continue;
const questions = objects(item.questions);
const title = questionTitle(questions);
if (!title)
continue;
const labels = questionOptionLabels(questions);
return { title, options: labels.map((label, index) => ({ label, key: String(index + 1) })) };
}
return undefined;
}
catch {
return undefined;
}
finally {
db.close();
}
}
/** Codex 0.155 code mode stores a generic tool call whose input is JavaScript;
* whichever key holds it, the Hook projects the source in the rollout reader. */
function codeModeInput(item) {
for (const key of ["input", "code", "script"]) {
const value = item[key];
if (typeof value === "string")
return value;
if (value && typeof value === "object" && ["code", "source", "script"].some(k => typeof object(value)[k] === "string"))
return value;
}
return undefined;
}
/** The call row(s) an item starts with; tool inputs, not reasoning. */
function callRows(item) {
const id = String(item.id ?? "");
switch (item.type) {
case "commandExecution":
return [{ type: "response_item", payload: { type: "function_call", name: "shell", call_id: id, arguments: JSON.stringify({ command: String(item.command ?? "").slice(0, 4000), ...(typeof item.cwd === "string" ? { workdir: item.cwd } : {}) }) } }];
case "fileChange":
return [{ type: "response_item", payload: { type: "function_call", name: "apply_patch", call_id: id, arguments: JSON.stringify({ files: objects(item.changes).slice(0, 50).map(c => ({ path: String(c.path ?? ""), kind: String(object(c.kind).type ?? c.kind ?? "") })) }) } }];
case "mcpToolCall":
return [{ type: "response_item", payload: { type: "function_call", name: `mcp__${String(item.server ?? "mcp")}__${String(item.tool ?? "tool")}`, call_id: id, arguments: JSON.stringify(object(item.arguments)) } }];
case "webSearch":
return [{ type: "response_item", payload: { type: "function_call", name: "web_search", call_id: id, arguments: JSON.stringify({ query: String(item.query ?? "").slice(0, 2000) }) } }];
default: {
const input = codeModeInput(item);
if (input === undefined)
return undefined;
return [{ type: "response_item", payload: { type: "custom_tool_call", name: String(item.name ?? item.tool ?? "exec"), call_id: id, input } }];
}
}
}
/** The output row once the item finished. */
function outputRow(item) {
if (!finished(item))
return undefined;
const id = String(item.id ?? "");
switch (item.type) {
case "commandExecution": {
const text = typeof item.aggregatedOutput === "string" ? item.aggregatedOutput.slice(-OUTPUT_TAIL) : "";
const status = typeof item.exitCode === "number" ? `[exit ${item.exitCode}]` : `[${String(item.status)}]`;
return { type: "response_item", payload: { type: "function_call_output", call_id: id, output: `${text}${text && !text.endsWith("\n") ? "\n" : ""}${status}` } };
}
case "fileChange": {
const changes = objects(item.changes).slice(0, 50);
const kind = (c) => { const t = String(object(c.kind).type ?? c.kind ?? "update"); return t === "add" ? "A" : t === "delete" ? "D" : "M"; };
const files = changes.map(c => ({ path: String(c.path ?? ""), status: kind(c), ...(typeof c.diff === "string" ? { patch: c.diff.slice(0, 200_000) } : {}) }));
const output = changes.length ? `${changes.length} file(s) changed\n${files.map(f => f.path).join("\n")}` : "0 file(s) changed";
return { type: "response_item", payload: { type: "function_call_output", call_id: id, output }, ...(files.length ? { phren_changes: { [id]: files } } : {}) };
}
case "mcpToolCall": {
const parts = objects(object(item.result).content).filter(b => b.type === "text" && typeof b.text === "string").map(b => String(b.text));
const output = parts.length ? parts.join("\n").slice(-OUTPUT_TAIL) : typeof item.error === "string" ? item.error.slice(0, 2000) : String(item.status);
return { type: "response_item", payload: { type: "function_call_output", call_id: id, output } };
}
case "webSearch": {
const results = objects(item.results).slice(0, 10).map(r => [r.title, r.snippet].filter(v => typeof v === "string" && v).join(": ")).join("\n");
return { type: "response_item", payload: { type: "function_call_output", call_id: id, output: results || "searched" } };
}
default: {
if (codeModeInput(item) === undefined)
return undefined;
const text = [item.aggregatedOutput, item.output, item.result].find(v => typeof v === "string" && v);
return { type: "response_item", payload: { type: "custom_tool_call_output", call_id: id, output: (text ?? String(item.status ?? "completed")).slice(-OUTPUT_TAIL) } };
}
}
}