Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat(engine): keep the 2.x engine's own fields in the uploaded trace

Samrat Talukdar1479b68688d1
diff --git a/apps/server/src/collector-observer.ts b/apps/server/src/collector-observer.ts
index 7c6c9da1..cdea8c62 100644
--- a/apps/server/src/collector-observer.ts
+++ b/apps/server/src/collector-observer.ts
@@ -183,10 +183,12 @@ function turnModelFromMessages(messages: unknown): CollectorSessionModel | null
const providerId = optionalTraceString(info.providerID) ?? optionalTraceString(model.providerID);
const modelId = optionalTraceString(info.modelID) ?? optionalTraceString(model.modelID) ?? optionalTraceString(model.id);
if (!providerId && !modelId) continue;
+ // The 2.x engine's own model record says "default" when no variant was picked (1.x wrote none).
+ const nativeVariant = optionalTraceString(model.variant);
return {
provider_id: providerId,
model_id: modelId,
- variant: optionalTraceString(info.variant) ?? optionalTraceString(model.variant) ?? userVariant,
+ variant: optionalTraceString(info.variant) ?? (nativeVariant === "default" ? null : nativeVariant) ?? userVariant,
agent: optionalTraceString(info.agent) ?? optionalTraceString(info.mode) ?? userAgent,
};
}
diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.ts
index 46d118ec..81ba3e14 100644
--- a/apps/server/src/engine2/facade.ts
+++ b/apps/server/src/engine2/facade.ts
@@ -194,12 +194,25 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
const url = new URL(`${upstream}${path}`);
if (init.directory) url.searchParams.set("location[directory]", init.directory);
for (const [key, value] of Object.entries(init.query ?? {})) if (value !== undefined) url.searchParams.set(key, value);
- const response = await fetchImpl(url, {
+ const send = () => fetchImpl(url, {
method,
headers: { authorization: upstreamAuth, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
signal: init.signal,
});
+ // Reads are retried through a transient engine failure (a 5xx or a dropped connection).
+ let response: Response | undefined;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ response = await send();
+ if (method !== "GET" || response.status < 500 || attempt >= 2) break;
+ log("engine read failed, retrying", { path, status: response.status });
+ await response.body?.cancel().catch(() => undefined);
+ } catch (error) {
+ if (method !== "GET" || attempt >= 2 || init.signal?.aborted) throw error;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 150 * (attempt + 1)));
+ }
const text = await response.text();
let payload: unknown = undefined;
if (text) {
@@ -289,17 +302,33 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
return all;
};
- // One read of a session's history serves the page reads that follow it for a moment (the
- // turn observer and the renderer page a long history newest-first, one request per page).
- const messageCache = new Map<string, { at: number; value: Promise<V1Message[]> }>();
+ // The turn observer and the renderer page a long history newest-first, one request per page.
+ // A history read is reused while the session's newest message is the same completed record
+ // (and the session's busy state is unchanged): one small read instead of the whole history.
+ const messageCache = new Map<string, { key: string; value: V1Message[] }>();
+ const inflight = new Map<string, Promise<V1Message[]>>();
const sessionMessages = async (sessionID: string): Promise<V1Message[]> => {
- const cached = messageCache.get(sessionID);
- if (cached && Date.now() - cached.at < 1_500) return cached.value;
- const value = readSessionMessages(sessionID);
- messageCache.set(sessionID, { at: Date.now(), value });
- if (messageCache.size > 64) messageCache.delete(messageCache.keys().next().value as string);
- value.catch(() => messageCache.delete(sessionID));
- return value;
+ const pending = inflight.get(sessionID);
+ if (pending) return pending;
+ const run = (async () => {
+ const newest = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/message`, { query: { order: "desc", limit: "1" } }).catch(() => undefined);
+ const head = arr(newest, "data")[0];
+ const completed = isRecord(head) && (str(head, "type") !== "assistant" || num(record(head, "time"), "completed") !== undefined);
+ const key = isRecord(head) && completed ? `${str(head, "id")}|${translator.statusOf(sessionID)?.type ?? "idle"}` : "";
+ const cached = messageCache.get(sessionID);
+ if (key && cached?.key === key) return cached.value;
+ const value = await readSessionMessages(sessionID);
+ if (key) messageCache.set(sessionID, { key, value });
+ else messageCache.delete(sessionID);
+ if (messageCache.size > 64) messageCache.delete(messageCache.keys().next().value as string);
+ return value;
+ })();
+ inflight.set(sessionID, run);
+ try {
+ return await run;
+ } finally {
+ inflight.delete(sessionID);
+ }
};
const readSessionMessages = async (sessionID: string): Promise<V1Message[]> => {
const info = await sessionInfo(sessionID).catch(() => null);
@@ -1225,6 +1254,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E
return;
}
if (error instanceof UpstreamError) {
+ if (error.status >= 500) log("engine request failed", { url: req.url, status: error.status });
const body = error.body;
const message = isRecord(body) ? str(body, "message") ?? str(record(body, "data"), "message") ?? JSON.stringify(body) : String(body ?? error.message);
const name = isRecord(body) ? str(body, "name") ?? str(body, "_tag") ?? str(body, "code") ?? "EngineError" : "EngineError";
diff --git a/apps/server/src/engine2/native.ts b/apps/server/src/engine2/native.ts
new file mode 100644
index 00000000..80e61cba
--- /dev/null
+++ b/apps/server/src/engine2/native.ts
@@ -0,0 +1,199 @@
+/**
+ * The 2.x engine's own fields, kept next to the 1.x shape.
+ *
+ * engine2/shapes.ts writes every message and part in the 1.x shape the app,
+ * the viewer, the admin converter and the CLI's trace format read. The 2.x
+ * engine records more than 1.x did (provider response ids and service tier,
+ * raw finish reasons, the step's snapshots and changed files, stream timing,
+ * whether a tool ran provider-side, structured tool content, native tool
+ * names and inputs, agent/model switches, turn outcomes, …). This module adds
+ * all of it to the same records, additively:
+ *
+ * - a 2.x field whose name the 1.x record does not use is added under that
+ * name, as-is (`info.rawFinish`, `info.providerState`, `part.executed`,
+ * `part.time.ran`, `state.content`, …);
+ * - a 2.x field whose 1.x counterpart has the same value is not repeated;
+ * - objects both engines write (`time`, `tokens`, `error`, tool `state` and
+ * `metadata`) are merged key by key, so the 2.x keys sit next to the 1.x ones;
+ * - a 2.x value under a name the 1.x record already uses with another value
+ * or shape (a patch's native file list, a streaming tool's status) goes
+ * under `v2.<name>` on the same record, so the 1.x value keeps its place;
+ * a tool's native input keeps there only the entries the 1.x input lacks
+ * (`state.v2.input.path` next to `state.input.filePath`);
+ * - 2.x records 1.x never listed (agent/model/location switches, system
+ * context, idle markers with the turn outcome) become parts of the nearest
+ * conversation message, typed by their 2.x type (`"model-switched"`, …);
+ * - a `data:` URI the 1.x record already carries byte for byte (an image
+ * prompt's file part, a tool attachment) is written once: the 2.x copy
+ * says `sameAs:<where>` instead of repeating the bytes.
+ */
+import type { V1Message } from "./shapes.js";
+import { isRecord, type JsonRecord } from "./util.js";
+
+/** Where a 2.x value goes when its name is taken on the 1.x record by another value. */
+export const NATIVE_COLLISIONS = "v2";
+
+function deepEqual(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (typeof a !== typeof b || a === null || b === null || typeof a !== "object") return false;
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
+ if (Array.isArray(a)) {
+ const other = b as unknown[];
+ return a.length === other.length && a.every((item, index) => deepEqual(item, other[index]));
+ }
+ const ka = Object.keys(a as object);
+ const kb = Object.keys(b as object);
+ return ka.length === kb.length && ka.every((key) => deepEqual((a as JsonRecord)[key], (b as JsonRecord)[key]));
+}
+
+/**
+ * Adds `native`'s fields to `target` (see the module comment). `nested` names
+ * the keys whose objects are merged key by key; its value gives the keys to
+ * merge one level further down. Objects in `target` are copied before they
+ * change, so a 1.x value shared between records is never altered.
+ */
+export function mergeNative(target: JsonRecord, native: JsonRecord, nested: Record<string, Record<string, unknown>> = {}): JsonRecord {
+ for (const [key, value] of Object.entries(native)) {
+ if (value === undefined || key === NATIVE_COLLISIONS) continue;
+ if (!(key in target)) {
+ target[key] = value;
+ continue;
+ }
+ const current = target[key];
+ if (deepEqual(current, value)) continue;
+ if (key in nested && isRecord(current) && isRecord(value)) {
+ target[key] = mergeNative({ ...current }, value, nested[key] as Record<string, Record<string, unknown>>);
+ continue;
+ }
+ const bucket: JsonRecord = isRecord(target[NATIVE_COLLISIONS]) ? { ...(target[NATIVE_COLLISIONS] as JsonRecord) } : {};
+ bucket[key] = value;
+ target[NATIVE_COLLISIONS] = bucket;
+ }
+ return target;
+}
+
+/** `value`, with `data:` URIs the 1.x record already holds (`known`: uri → where) written as `sameAs:<where>`. */
+function elideKnownDataUris(value: unknown, known: Map<string, string>): unknown {
+ if (known.size === 0) return value;
+ if (typeof value === "string") return value.startsWith("data:") && known.has(value) ? `sameAs:${known.get(value)}` : value;
+ if (Array.isArray(value)) return value.map((item) => elideKnownDataUris(item, known));
+ if (!isRecord(value)) return value;
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, elideKnownDataUris(item, known)]));
+}
+
+function without(record: JsonRecord, ...keys: string[]): JsonRecord {
+ const copy = { ...record };
+ for (const key of keys) delete copy[key];
+ return copy;
+}
+
+const STATE_NESTED = { metadata: {}, time: {} };
+const INFO_NESTED = { time: {}, tokens: { cache: {} }, error: { data: {} } };
+
+/** Adds a 2.x content entry's own fields to the 1.x part built from it. */
+function enrichPart(part: JsonRecord, entry: JsonRecord): void {
+ if (part.type === "tool") {
+ const state = isRecord(part.state) ? part.state : undefined;
+ const known = new Map<string, string>();
+ const attachments = state && Array.isArray(state.attachments) ? state.attachments : [];
+ attachments.forEach((attachment, index) => {
+ if (isRecord(attachment) && typeof attachment.url === "string") known.set(attachment.url, `state.attachments[${index}].url`);
+ });
+ const native = elideKnownDataUris(entry, known) as JsonRecord;
+ // The call id is the 1.x `callID`; the part keeps its own id.
+ const { id: callID, state: nativeState, ...rest } = native;
+ mergeNative(part, rest);
+ if (callID !== part.callID) mergeNative(part, { id: callID });
+ if (state && isRecord(nativeState)) {
+ const merged = mergeNative({ ...state }, nativeState, STATE_NESTED);
+ // A native input differs from the 1.x one by its key names (`path` for `filePath`, `agent` for
+ // `subagent_type`): only the native entries the 1.x input lacks are kept, so no value is written twice.
+ const bucket = isRecord(merged[NATIVE_COLLISIONS]) ? (merged[NATIVE_COLLISIONS] as JsonRecord) : undefined;
+ if (bucket && isRecord(bucket.input) && isRecord(state.input)) {
+ const v1Input = state.input as JsonRecord;
+ bucket.input = Object.fromEntries(Object.entries(bucket.input).filter(([key, value]) => !deepEqual(v1Input[key], value)));
+ }
+ part.state = merged;
+ }
+ return;
+ }
+ mergeNative(part, entry, { time: {} });
+}
+
+/** A 2.x assistant message's fields (and those of its content entries) on its 1.x message. */
+export function enrichAssistant(message: V1Message, native: JsonRecord): void {
+ message.info = mergeNative({ ...message.info }, without(native, "content"), INFO_NESTED);
+ const content = Array.isArray(native.content) ? native.content.filter(isRecord) : [];
+ const ordinals = { text: 0, reasoning: 0 };
+ const byId = new Map(message.parts.map((part) => [String(part.id), part]));
+ const core = String(message.info.id).replace(/^msg_/, "");
+ for (const entry of content) {
+ let id: string | undefined;
+ if (entry.type === "text") id = `prt_${core}_t${ordinals.text++}`;
+ else if (entry.type === "reasoning") id = `prt_${core}_r${ordinals.reasoning++}`;
+ else if (entry.type === "tool" && typeof entry.id === "string") id = `prt_${core}_c_${entry.id}`;
+ const part = id ? byId.get(id) : undefined;
+ if (part) enrichPart(part, entry);
+ }
+}
+
+/** A 2.x user (or synthetic) message's fields on its 1.x message; native file entries on the file parts. */
+export function enrichPrompt(message: V1Message, native: JsonRecord): void {
+ const known = new Map<string, string>();
+ message.parts.forEach((part, index) => {
+ if (part.type === "file" && typeof part.url === "string") known.set(part.url, `parts[${index}].url`);
+ });
+ message.info = mergeNative({ ...message.info }, elideKnownDataUris(native, known) as JsonRecord, INFO_NESTED);
+ const files = Array.isArray(native.files) ? native.files : [];
+ const fileParts = message.parts.filter((part) => part.type === "file");
+ files.forEach((file, index) => {
+ const part = fileParts[index];
+ if (!part || !isRecord(file)) return;
+ const { uri, ...rest } = file;
+ mergeNative(part, rest);
+ if (uri !== part.url) mergeNative(part, { uri });
+ });
+}
+
+/** 2.x records the 1.x engine never listed, as parts of the nearest conversation message. */
+const CONTEXT_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);
+
+export function isContextRecord(native: JsonRecord): boolean {
+ return CONTEXT_TYPES.has(String(native.type));
+}
+
+/**
+ * Adds the 2.x fields to the 1.x messages mapped from `natives` (`mapped`
+ * names the 1.x messages each native message became) and places the context
+ * records: an idle marker closes the message before it, every other record
+ * joins the message after it (the last message when none follows).
+ */
+export function withNativeFields(messages: V1Message[], natives: JsonRecord[], mapped: Map<JsonRecord, V1Message[]>, sessionID: string): V1Message[] {
+ const pending: JsonRecord[] = [];
+ let previous: V1Message | undefined;
+ const attach = (host: V1Message, record: JsonRecord, atEnd: boolean) => {
+ const part = { ...record, sessionID, messageID: host.info.id };
+ host.parts = atEnd ? [...host.parts, part] : [part, ...host.parts];
+ };
+ for (const native of natives) {
+ if (isContextRecord(native)) {
+ if (native.type === "idle" && previous) attach(previous, native, true);
+ else pending.push(native);
+ continue;
+ }
+ const targets = mapped.get(native) ?? [];
+ if (targets.length === 0) continue;
+ const type = String(native.type);
+ if (type === "assistant") enrichAssistant(targets[0]!, native);
+ else if (type === "user" || type === "synthetic" || type === "skill") enrichPrompt(targets[0]!, native);
+ else {
+ // shell and compaction became a prompt and a reply: the reply carries the record's fields.
+ const reply = targets[targets.length - 1]!;
+ reply.info = mergeNative({ ...reply.info }, native, INFO_NESTED);
+ }
+ for (const record of pending.splice(0).reverse()) attach(targets[0]!, record, false);
+ previous = targets[targets.length - 1];
+ }
+ if (pending.length && messages.length) for (const record of pending) attach(messages[messages.length - 1]!, record, true);
+ return messages;
+}
diff --git a/apps/server/src/engine2/shapes.test.ts b/apps/server/src/engine2/shapes.test.ts
index 3e7866c1..a3f17534 100644
--- a/apps/server/src/engine2/shapes.test.ts
+++ b/apps/server/src/engine2/shapes.test.ts
@@ -22,20 +22,32 @@ function typeOf(value: unknown): string {
return typeof value;
}
-/** Every key path whose presence or value type differs between two JSON values. */
+/** Part types only the 2.x engine records (context records carried as parts, engine2/native.ts). */
+const NATIVE_PART_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);
+
+/**
+ * Every 1.x key path the adapter's record lacks or writes with another value
+ * type ("only in 1.x" / type mismatches), and the key paths it adds (the 2.x
+ * engine's own fields, "only in adapter"). Parts are paired after leaving out
+ * the 2.x-only part types.
+ */
function shapeDiff(a: unknown, b: unknown, path = "$", out: string[] = []): string[] {
if (typeOf(a) !== typeOf(b)) {
out.push(`${path}: ${typeOf(a)} != ${typeOf(b)}`);
return out;
}
if (Array.isArray(a) && Array.isArray(b)) {
+ let right = b;
if (path.endsWith(".parts")) {
+ const native = b.filter((part) => NATIVE_PART_TYPES.has(String((part as { type?: string }).type)));
+ for (const part of native) out.push(`${path}[type=${(part as { type: string }).type}]: only in adapter`);
+ right = b.filter((part) => !native.includes(part));
const ta = a.map((part) => (part as { type?: string }).type).join(",");
- const tb = b.map((part) => (part as { type?: string }).type).join(",");
+ const tb = right.map((part) => (part as { type?: string }).type).join(",");
if (ta !== tb) out.push(`${path}: part types [${ta}] != [${tb}]`);
}
- if (a.length !== b.length) out.push(`${path}: length ${a.length} != ${b.length}`);
- for (let index = 0; index < Math.min(a.length, b.length); index++) shapeDiff(a[index], b[index], `${path}[${index}]`, out);
+ if (a.length !== right.length) out.push(`${path}: length ${a.length} != ${right.length}`);
+ for (let index = 0; index < Math.min(a.length, right.length); index++) shapeDiff(a[index], right[index], `${path}[${index}]`, out);
return out;
}
if (a && b && typeof a === "object") {
@@ -48,6 +60,13 @@ function shapeDiff(a: unknown, b: unknown, path = "$", out: string[] = []): stri
return out;
}
+function pick(value: Record<string, unknown>, keys: string[]): Record<string, unknown> {
+ return Object.fromEntries(keys.filter((key) => key in value).map((key) => [key, value[key]]));
+}
+
+/** The 1.x problems of a diff: whatever is not an addition. */
+const regressions = (diff: string[]) => diff.filter((line) => !line.endsWith(": only in adapter"));
+
function mapTree(tree: Tree, parentModel?: { providerID: string; modelID: string }): { messages: V1Message[]; children: Array<ReturnType<typeof mapTree>> } {
const session = tree.session as { id: string; parentID?: string; location?: { directory?: string } };
const messages = v1Messages(tree.messages, {
@@ -79,16 +98,17 @@ function compareTrees(v1: Tree, mapped: Mapped, path: string, out: string[]): vo
describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
for (const scenario of ["p1", "sub", "nest", "patch", "tools"]) {
- test(`${scenario}: every message, part and field the 1.x engine wrote, and no other`, () => {
+ test(`${scenario}: every message, part and field the 1.x engine wrote, in its place and shape`, () => {
const out: string[] = [];
compareTrees(fixture(`v1-${scenario}`), mapTree(fixture(`v2-${scenario}`)), "root", out);
- expect(out).toEqual([]);
+ expect(regressions(out)).toEqual([]);
});
}
test("p1: the uploaded messages, field for field", () => {
const [user, first, second, third, answer] = mapTree(fixture("v2-p1")).messages;
- expect(user!.info).toEqual({
+ // 1.x fields, exactly; the 2.x engine's own fields sit next to them (next test).
+ expect(pick(user!.info, ["id", "sessionID", "role", "time", "summary", "agent", "model"])).toEqual({
id: "msg_0e0eb02300010Ie6K3lQAqUici",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
role: "user",
@@ -97,18 +117,18 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
agent: "build",
model: { providerID: "mock", modelID: "mock-model" },
});
- expect(user!.parts).toEqual([{
+ expect(user!.parts.map((part) => pick(part, ["id", "sessionID", "messageID", "type", "text"]))).toEqual([{
id: "prt_0e0eb02300010Ie6K3lQAqUici_u0",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
messageID: "msg_0e0eb02300010Ie6K3lQAqUici",
type: "text",
text: "PARITY-1 create the notes file",
}]);
- expect(first!.info).toEqual({
+ expect(pick(first!.info, ["id", "sessionID", "role", "time", "parentID", "modelID", "providerID", "mode", "agent", "path", "cost", "tokens", "finish"])).toEqual({
id: "msg_0e0eb029c001Gb432955hHZq2J",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
role: "assistant",
- time: { created: 1790479893170, completed: 1790479893443 },
+ time: { created: 1790479893170, completed: 1790479893443, streamed: 1790479893305 },
parentID: "msg_0e0eb02300010Ie6K3lQAqUici",
modelID: "mock-model",
providerID: "mock",
@@ -120,7 +140,7 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
finish: "tool-calls",
});
expect(first!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "tool", "step-finish"]);
- expect(first!.parts[2]).toEqual({
+ expect(pick(first!.parts[2]!, ["id", "sessionID", "messageID", "type", "callID", "tool", "state"])).toEqual({
id: "prt_0e0eb029c001Gb432955hHZq2J_c_call_2_0",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
messageID: "msg_0e0eb029c001Gb432955hHZq2J",
@@ -132,8 +152,9 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
input: { command: "ls -a", description: "List files" },
output: ".\n..\n",
title: "List files",
- metadata: { output: ".\n..\n", truncated: false, exit: 0 },
+ metadata: { output: ".\n..\n", truncated: false, exit: 0, status: "completed" },
time: { start: 1790479893299, end: 1790479893435 },
+ content: [{ type: "text", text: ".\n..\n" }],
},
});
expect(first!.parts[3]).toEqual({
@@ -148,14 +169,15 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
const write = second!.parts.find((part) => part.type === "tool") as { tool: string; state: { input: unknown; metadata: unknown; title: string } };
expect(write.tool).toBe("write");
expect(write.state.input).toEqual({ filePath: "/work/proj/notes.md", content: "# Notes\nline one\n" });
- expect(write.state.metadata).toEqual({ diagnostics: {}, filepath: "/work/proj/notes.md", exists: false, truncated: false });
+ expect(pick(write.state.metadata as Record<string, unknown>, ["diagnostics", "filepath", "exists", "truncated"])).toEqual({ diagnostics: {}, filepath: "/work/proj/notes.md", exists: false, truncated: false });
expect(write.state.title).toBe("work/proj/notes.md");
const edit = third!.parts.find((part) => part.type === "tool") as { tool: string; state: { input: unknown; metadata: Record<string, unknown> } };
expect(edit.tool).toBe("edit");
expect(edit.state.input).toEqual({ filePath: "/work/proj/notes.md", oldString: "line one", newString: "line one\nline two" });
- expect(Object.keys(edit.state.metadata)).toEqual(["diagnostics", "diff", "filediff", "truncated"]);
+ expect(Object.keys(edit.state.metadata)).toEqual(["diagnostics", "diff", "filediff", "truncated", "files"]);
expect(edit.state.metadata.filediff).toMatchObject({ file: "/work/proj/notes.md", additions: 1, deletions: 0 });
- expect(answer!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "text", "step-finish"]);
+ // The turn's 2.x idle marker (its outcome) closes the last reply as a part of its own type.
+ expect(answer!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "text", "step-finish", "idle"]);
expect(answer!.info.finish).toBe("stop");
});
@@ -187,6 +209,101 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
});
});
+describe("the 2.x engine's own fields ride along (additive)", () => {
+ test("p1: step, tool and turn records keep what 2.x recorded", () => {
+ const [user, first, , third, answer] = mapTree(fixture("v2-p1")).messages;
+ expect(user!.info).toMatchObject({ type: "user", text: "PARITY-1 create the notes file" });
+ expect(first!.info).toMatchObject({
+ type: "assistant",
+ model: { id: "mock-model", providerID: "mock" },
+ rawFinish: "tool_calls",
+ time: { created: 1790479893170, streamed: 1790479893305, completed: 1790479893443 },
+ });
+ const shell = first!.parts[2] as Record<string, any>;
+ expect(shell).toMatchObject({
+ tool: "bash",
+ name: "shell",
+ executed: false,
+ time: { created: 1790479893236, ran: 1790479893299, completed: 1790479893435 },
+ state: { content: [{ type: "text", text: ".\n..\n" }], metadata: { status: "completed" } },
+ });
+ const reasoning = first!.parts[1] as Record<string, any>;
+ expect(reasoning).toMatchObject({ state: { reasoningField: "reasoning_content" }, time: { created: 1790479893188, completed: 1790479893285 } });
+ const edit = third!.parts.find((part) => part.type === "tool") as Record<string, any>;
+ // Native input keys the 1.x input names differently, and the native file list.
+ expect(edit.state.v2).toEqual({ input: { path: "/work/proj/notes.md" } });
+ expect(edit.state.metadata.files[0]).toMatchObject({ file: "notes.md", status: "modified", additions: 1, deletions: 0 });
+ // The turn's idle marker, with its outcome.
+ expect(answer!.parts.at(-1)).toEqual({
+ id: "msg_0e0eb0600001Z6P4VHgDiDmR03",
+ time: { created: 1790479894016 },
+ type: "idle",
+ outcome: "succeeded",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ messageID: answer!.info.id,
+ });
+ });
+
+ test("patch: the model switch before the prompt and the native patch file list", () => {
+ const [user, reply] = mapTree(fixture("v2-patch")).messages;
+ expect(user!.parts[0]).toMatchObject({ type: "model-switched", model: { id: "gpt-5.1-mock", providerID: "mock" }, messageID: user!.info.id });
+ const patch = reply!.parts.find((part) => part.type === "tool") as Record<string, any>;
+ expect(patch.name).toBe("patch");
+ expect(patch.state.metadata.files.map((file: Record<string, unknown>) => file.relativePath)).toEqual(["work/proj/notes.md", "work/proj/extra.md"]);
+ expect(patch.state.metadata.v2.files.map((file: Record<string, unknown>) => [file.file, file.status])).toEqual([["notes.md", "modified"], ["extra.md", "added"]]);
+ expect(reply!.info).toMatchObject({ model: { id: "gpt-5.1-mock", providerID: "mock", variant: "default" } });
+ expect(reply!.info.variant).toBeUndefined();
+ });
+
+ test("provider state, snapshots and errors: 1.x values in place, 2.x values next to them", () => {
+ const [message] = v1Messages([{
+ id: "msg_x",
+ type: "assistant",
+ agent: "build",
+ model: { id: "gpt-6-astra", providerID: "omnirush", variant: "default" },
+ snapshot: { start: "aaa", end: "bbb", files: ["math.js"] },
+ providerState: { responseId: "resp_1", serviceTier: "default" },
+ error: { type: "provider.rate-limit", message: "slow down", status: 429 },
+ retry: { attempt: 1, at: 5, error: { type: "provider.rate-limit", message: "slow down" } },
+ content: [
+ { type: "text", text: "hi", state: { itemId: "msg_item", phase: "final_answer" } },
+ {
+ type: "tool", id: "call_1", name: "browser_observe", executed: true, providerState: { itemId: "fc_1" }, providerResultState: { ok: 1 },
+ state: { status: "completed", input: {}, content: [{ type: "text", text: "seen" }, { type: "file", uri: "data:image/png;base64,QUJD", mime: "image/png" }], metadata: {} },
+ time: { created: 1, ran: 2, completed: 3 },
+ },
+ ],
+ finish: "stop",
+ time: { created: 1, completed: 4 },
+ }], { sessionID: "ses_1", directory: "/work", root: "/work" });
+ expect(message!.info).toMatchObject({
+ error: { name: "APIError", data: { message: "slow down", statusCode: 429, isRetryable: true }, type: "provider.rate-limit", message: "slow down", status: 429 },
+ snapshot: { start: "aaa", end: "bbb", files: ["math.js"] },
+ providerState: { responseId: "resp_1", serviceTier: "default" },
+ retry: { attempt: 1 },
+ });
+ const text = message!.parts.find((part) => part.type === "text")!;
+ expect(text).toMatchObject({ metadata: { openai: { itemId: "msg_item", phase: "final_answer" } }, state: { itemId: "msg_item", phase: "final_answer" } });
+ const tool = message!.parts.find((part) => part.type === "tool") as Record<string, any>;
+ expect(tool).toMatchObject({ metadata: { openai: { itemId: "fc_1" } }, providerState: { itemId: "fc_1" }, providerResultState: { ok: 1 }, executed: true });
+ // The screenshot's bytes are in state.attachments once; the native content points at them.
+ expect(tool.state.attachments[0].url).toBe("data:image/png;base64,QUJD");
+ expect(tool.state.content[1]).toEqual({ type: "file", uri: "sameAs:state.attachments[0].url", mime: "image/png" });
+ expect(message!.parts.map((part) => part.type)).toEqual(["step-start", "text", "tool", "step-finish", "patch"]);
+ });
+
+ test("a prompt's image is written once; the native file entry keeps its other fields", () => {
+ const [message] = v1Messages([{
+ id: "msg_u", type: "user", text: "look", time: { created: 1 },
+ files: [{ uri: "data:image/png;base64,QUJD", name: "a.png", mention: { start: 0, end: 4 } }],
+ }], { sessionID: "ses_1" });
+ const file = message!.parts.find((part) => part.type === "file")!;
+ expect(file).toMatchObject({ url: "data:image/png;base64,QUJD", filename: "a.png", name: "a.png", mention: { start: 0, end: 4 } });
+ expect(file.uri).toBeUndefined();
+ expect(message!.info).toMatchObject({ type: "user", text: "look", files: [{ uri: "sameAs:parts[1].url", name: "a.png" }] });
+ });
+});
+
describe("live events and read-back agree", () => {
test("parts built from the 2.x stream carry the ids and fields of the same parts read back", async () => {
const tree = fixture("v2-sub");
@@ -208,7 +325,7 @@ describe("live events and read-back agree", () => {
}
const read = mapTree(tree, { providerID: "mock", modelID: "mock-model" });
const all = [read, ...read.children].flatMap((node) => node.messages.flatMap((message) => message.parts));
- const assistantParts = all.filter((part) => part.type !== "text" || !String(part.id).endsWith("_u0"));
+ const assistantParts = all.filter((part) => String(part.id).startsWith("prt_") && (part.type !== "text" || !String(part.id).endsWith("_u0")));
expect(assistantParts.length).toBeGreaterThan(10);
for (const part of assistantParts) {
const seen = live.get(String(part.id));
diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.ts
index 627ea77c..cc96818f 100644
--- a/apps/server/src/engine2/shapes.ts
+++ b/apps/server/src/engine2/shapes.ts
@@ -24,6 +24,7 @@
* `_c<callID>`, …) so a part read from a message list and the same part built from live events
* (engine2/events.ts) agree.
*/
+import { withNativeFields } from "./native.js";
import { arr, isRecord, num, omitUndefined, record, str, unwrap, type JsonRecord } from "./util.js";
export type V1Message = { info: JsonRecord; parts: JsonRecord[] };
@@ -701,6 +702,11 @@ function v1CompactionMessages(message: JsonRecord, ctx: MessageContext, model: M
export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[] {
const list = messages.filter(isRecord);
const out: V1Message[] = [];
+ const mappedFrom = new Map<JsonRecord, V1Message[]>();
+ const emit = (message: JsonRecord, mapped: V1Message[]) => {
+ mappedFrom.set(message, mapped);
+ out.push(...mapped);
+ };
let agent = ctx.agent ?? "build";
let model = ctx.model;
let lastUserId = "";
@@ -743,12 +749,12 @@ export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[
{ system: str(sent, "system"), tools: record(sent, "tools") },
);
lastUserId = String(mapped.info.id);
- out.push(mapped);
+ emit(message, [mapped]);
return;
}
case "skill": {
const mapped = v1UserMessage(message, ctx, str(message, "text") ?? "", [], true, agent, model);
- out.push(mapped);
+ emit(message, [mapped]);
return;
}
case "assistant": {
@@ -756,21 +762,22 @@ export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[
agent = String(mapped.info.agent ?? agent);
const stepModel = modelRef(message.model);
if (stepModel) model = { ...stepModel, ...(model?.variant && !stepModel.variant ? { variant: model.variant } : {}) };
- out.push(mapped);
+ emit(message, [mapped]);
return;
}
case "shell":
- out.push(...v1ShellMessages(message, ctx, agent, model));
+ emit(message, v1ShellMessages(message, ctx, agent, model));
return;
case "compaction":
- out.push(...v1CompactionMessages(message, ctx, model));
+ emit(message, v1CompactionMessages(message, ctx, model));
return;
default:
- // system, location-switched, idle: context records the 1.x engine never listed.
+ // system, location-switched, idle: context records the 1.x engine never listed
+ // (withNativeFields adds them as parts of the nearest message).
return;
}
});
- return out;
+ return withNativeFields(out, list, mappedFrom, ctx.sessionID);
}
export type SessionShapeOptions = {
diff --git a/apps/server/src/engine2/trace-parity.test.ts b/apps/server/src/engine2/trace-parity.test.ts
index 490000bb..a82c0e52 100644
--- a/apps/server/src/engine2/trace-parity.test.ts
+++ b/apps/server/src/engine2/trace-parity.test.ts
@@ -24,21 +24,28 @@ function typeOf(value: unknown): string {
return typeof value;
}
+const NATIVE_PART_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);
+
+/**
+ * What the 2.x trace lacks or changes against the 1.x trace (the 2.x
+ * engine's own fields and parts are additions, engine2/native.ts, and are
+ * not reported).
+ */
function shapeDiff(a: unknown, b: unknown, path = "$", out: string[] = []): string[] {
if (typeOf(a) !== typeOf(b)) {
out.push(`${path}: ${typeOf(a)} != ${typeOf(b)}`);
return out;
}
if (Array.isArray(a) && Array.isArray(b)) {
- if (a.length !== b.length) out.push(`${path}: length ${a.length} != ${b.length}`);
- for (let index = 0; index < Math.min(a.length, b.length); index++) shapeDiff(a[index], b[index], `${path}[${index}]`, out);
+ const right = path.endsWith(".parts") ? b.filter((part) => !NATIVE_PART_TYPES.has(String((part as { type?: string }).type))) : b;
+ if (a.length !== right.length) out.push(`${path}: length ${a.length} != ${right.length}`);
+ for (let index = 0; index < Math.min(a.length, right.length); index++) shapeDiff(a[index], right[index], `${path}[${index}]`, out);
return out;
}
if (a && b && typeof a === "object") {
const ka = Object.keys(a as object);
const kb = Object.keys(b as object);
for (const key of ka) if (!kb.includes(key)) out.push(`${path}.${key}: only on 1.x`);
- for (const key of kb) if (!ka.includes(key)) out.push(`${path}.${key}: only on 2.x`);
for (const key of ka) if (kb.includes(key)) shapeDiff((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], `${path}.${key}`, out);
}
return out;
@@ -176,6 +183,8 @@ describe("the uploaded trace over the 2.x engine matches the 1.x engine's", () =
test("two parallel sub-agents: same events, messages and sub-agent sessions", async () => {
const v1 = fixture("v1-sub");
const v2 = fixture("v2-sub");
+ // As the engine records it in the app: no variant picked reads as "default" on each step.
+ for (const node of flatten(v2)) for (const message of node.messages) if (message.type === "assistant" && message.model && typeof message.model === "object") (message.model as Record<string, unknown>).variant = "default";
const before = await observe(startV1Engine(v1), String(v1.session.id));
const after = await observe(await startV2Engine(v2), String(v2.session.id));
const labels = (collector: RecordingCollector) => collector.entries.map((entry) => (entry.kind === "trace" ? entry.type : entry.kind));
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index 1818a59a..583bb99c 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -248,6 +248,7 @@ async function startManagedEngine2Server(
v1ConfigPath: launch.v1ConfigPath,
writeEngineConfig: launch.writeEngineConfig,
plugins: launch.plugins,
+ log: (message, attributes) => console.warn(`[engine-adapter] ${message}`, attributes ? JSON.stringify(attributes) : ""),
});
} catch (error) {
await processLifecycle.close();
diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.ts
index 7e02729d..2f39f0cb 100644
--- a/apps/server/src/omnirush-swarm.ts
+++ b/apps/server/src/omnirush-swarm.ts
@@ -8,9 +8,10 @@
* coordinating through one `.omnirush/swarm.md` board. Only a swarm gets a
* board: the procedure is the on-demand omnirush-swarm skill, and the
* always-on prompt only says when to load it. The bundled engine (opencode
- * 1.18.32) counts sub-agent layers from the main session through `parentID`
- * and refuses the task tool at `subagent_depth`; it has no fan-out limit of
- * its own, so the plugin adds one.
+ * 2.x) counts sub-agent layers from the main session through `parentID` and
+ * refuses the subagent tool (the 1.x task tool) at
+ * `experimental.subagent_depth`; it has no fan-out limit of its own, so the
+ * plugin adds one.
*
* Kept dependency-free: the engine plugin bundle imports it.
*/
diff --git a/apps/server/src/opencode-config-compat.ts b/apps/server/src/opencode-config-compat.ts
index a8c39b69..73562aa7 100644
--- a/apps/server/src/opencode-config-compat.ts
+++ b/apps/server/src/opencode-config-compat.ts
@@ -1,7 +1,9 @@
/**
- * Pre-flight compatibility check for user-owned OpenCode config files.
+ * Pre-flight compatibility check for user-owned OpenCode config files, for a
+ * 1.x engine (OMNIRUSH_OPENCODE_BIN). The bundled 2.x engine reads both
+ * `permission` and `permissions`, so the server skips this check for it.
*
- * The bundled engine (OpenCode V1, pinned in constants.json) lowers V2-style
+ * A 1.x engine (OpenCode V1) lowers V2-style
* config on load (packages/opencode/src/config/v2-compat.ts). Most V2 keys
* degrade to a "configuration compatibility diagnostic" warning, but a
* `permissions` key — top-level, or under `agent`/`agents`/`mode.<name>` — is
diff --git a/docs/skills-and-mcp.md b/docs/skills-and-mcp.md
index 169c1cb9..0cc4a97c 100644
--- a/docs/skills-and-mcp.md
+++ b/docs/skills-and-mcp.md
@@ -151,12 +151,12 @@ The engine caches its skill catalog per project instance and needs an instance r
**Removing an MCP server left tools behind in a running session.**
The engine drops the registration immediately, but a session that already started a turn keeps its captured tool set until the turn ends.
-**The app reports "Configuration is invalid at … V2 permissions are not supported by OpenCode V1", or a workspace answers `opencode_config_invalid`.**
-The bundled engine is OpenCode V1 (pinned in `constants.json`). Since engine 1.18.32 a `permissions` key in a user-owned `opencode.json(c)` — top level, or under `agent`, `agents` or `mode.<name>` — is rejected instead of ignored (the older 1.18.18 engine served such files normally). The server checks those files before spawning the engine: a `permissions` key in the global file (`~/.config/opencode/opencode.json(c)`, `config.json`, or the `OPENCODE_CONFIG_DIR` directory) stops startup with the message above naming the file; a `permissions` key in `<workspace>/.opencode/opencode.json(c)` or `<workspace>/opencode.json(c)` is logged as a warning, the engine still starts, server routes that read the engine for that workspace return `422 opencode_config_invalid` with the engine's message and the file path in `details`, and the native engine proxy passes the engine's own `400 ConfigInvalidError` body through unchanged. Other V2-only keys (`plugins`, `providers`, `websearch`, `warming`, …) are dropped with a "configuration compatibility diagnostic" warning in the engine log and do not block anything. Fix: rename `permissions` to `permission` (V1 rules) or remove it, then restart OmniRush.ai.
+**Which engine does the app run, and what happened to `permissions` in my `opencode.json`?**
+The bundled engine is opencode 2.x (pinned in `constants.json`, published on npm as `@opencode/cli`). OmniRush.ai's server starts it on a private loopback port and serves the 1.x engine API the app is written against in front of it (the engine adapter, `apps/server/src/engine2/`), so sessions, sub-agents, permissions, MCP and the uploaded traces keep their 1.x shape. The engine reads both the 1.x `permission` rules and the 2.x `permissions` list, so a `permissions` key in a user-owned `opencode.json(c)` no longer stops startup. The runtime config OmniRush.ai renders for the engine is written to `engine2/opencode.json` next to `runtime-opencode-config.json`; OmniRush.ai's engine plugins load through `engine2/omnirush-plugin/`. MCP servers defined in a project's own config offer their tools directly (`<server>_<tool>`), not through the engine's code mode. The first start after the upgrade migrates the 1.x engine's sessions in `~/.local/share/opencode/opencode.db` in place. With `OMNIRUSH_OPENCODE_BIN` pointing at a 1.x binary the server talks to it directly, as before, and keeps the 1.x `permissions` pre-flight check.
**Where are the files?**
-- Server state directory: `~/.config/omnirush/` (or the directory of `OMNIRUSH_SERVER_CONFIG`), containing `runtime.sqlite` (runtime DB), `runtime-opencode-config.json` (engine-visible config) and the managed MCP vault.
-- Engine data: `~/.local/share/opencode/` (logs under `log/`).
+- Server state directory: `~/.config/omnirush/` (or the directory of `OMNIRUSH_SERVER_CONFIG`), containing `runtime.sqlite` (runtime DB), `runtime-opencode-config.json` (the engine config in 1.x keys), `engine2/opencode.json` (the same config as the 2.x engine reads it) and the managed MCP vault.
+- Engine data: `~/.local/share/opencode/` (the `opencode.db` session database, logs under `log/`).
- Audit log: `<workspace>/.opencode/` audit entries record every skill and MCP change with the actor.
## API summary