A desktop coding agent with free access to frontier models.
TypeScript
fix(engine): trace parity with the 1.x engine for patches, snapshots, provider metadata and sub-agents
Samrat Talukdarbfba380211a3
diff --git a/apps/server/src/engine2/events.ts b/apps/server/src/engine2/events.tsindex 3e8bd95d..f6e64a39 100644--- a/apps/server/src/engine2/events.ts+++ b/apps/server/src/engine2/events.ts@@ -67,8 +67,9 @@ function modelRef(value: unknown): ModelRef | undefined {const providerID = str(value, "providerID");const modelID = str(value, "id") ?? str(value, "modelID");if (!providerID || !modelID) return undefined;+ // 2.x records "default" when no variant was picked; 1.x left the field out.const variant = str(value, "variant");- return variant ? { providerID, modelID, variant } : { providerID, modelID };+ return variant && variant !== "default" ? { providerID, modelID, variant } : { providerID, modelID };}export class EventTranslator {@@ -346,6 +347,7 @@ export class EventTranslator {message: omitUndefined({id,type: "assistant",+ snapshot: str(data, "snapshot") ? { start: str(data, "snapshot") } : undefined,agent,model: model ? { id: model.modelID, providerID: model.providerID, variant: state.model?.variant } : undefined,content: [],@@ -363,10 +365,13 @@ export class EventTranslator {live.message.cost = num(data, "cost") ?? 0;live.message.tokens = record(data, "tokens") ?? live.message.tokens;const snapshot = str(data, "snapshot");- if (snapshot) live.message.snapshot = snapshot;+ const files = arr(data, "files").filter((file) => typeof file === "string");+ const previous = record(live.message, "snapshot") ?? {};+ if (snapshot || files.length) live.message.snapshot = omitUndefined({ ...previous, end: snapshot ?? str(previous, "end"), files: files.length ? files : undefined });live.message.time = { ...(record(live.message, "time") ?? {}), completed: num(raw, "created") ?? this.now() };this.live.delete(str(live.message, "id") ?? "");const out = this.assistantEvents(live, partId(String(live.message.id), "f0"), false);+ out.push(...this.assistantEvents(live, partId(String(live.message.id), "p0"), false));out.push(...this.assistantEvents(live, "", true).filter((item) => item.event.type === "message.updated"));return out;}@@ -388,6 +393,7 @@ export class EventTranslator {const ordinal = num(data, "ordinal") ?? 0;const entry = this.contentEntry(live, kind, ordinal);entry.time = { created: num(raw, "created") ?? this.now() };+ if (isRecord(data.state)) entry.state = data.state;return this.assistantEvents(live, partId(String(live.message.id), `${kind === "text" ? "t" : "r"}${ordinal}`), false);}case "session.text.delta":@@ -420,6 +426,7 @@ export class EventTranslator {const ordinal = num(data, "ordinal") ?? 0;const entry = this.contentEntry(live, kind, ordinal);if (typeof data.text === "string") entry.text = data.text;+ if (isRecord(data.state)) entry.state = data.state;entry.time = { ...(record(entry, "time") ?? {}), completed: num(raw, "created") ?? this.now() };return this.assistantEvents(live, partId(String(live.message.id), `${kind === "text" ? "t" : "r"}${ordinal}`), false);}@@ -454,6 +461,7 @@ export class EventTranslator {if (!live || !callID) return [];const entry = this.toolEntry(live, callID, str(data, "name"));entry.state = { status: "running", input: data.input ?? {}, metadata: {} };+ if (isRecord(data.providerState)) entry.providerState = data.providerState;entry.time = { ...(record(entry, "time") ?? {}), ran: num(raw, "created") ?? this.now() };return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);}diff --git a/apps/server/src/engine2/facade.test.ts b/apps/server/src/engine2/facade.test.tsindex fd72e9ee..05728e21 100644--- a/apps/server/src/engine2/facade.test.ts+++ b/apps/server/src/engine2/facade.test.ts@@ -137,7 +137,13 @@ describe("1.x engine adapter over the 2.x engine", () => {expect(recorded[0]!.body).toEqual({ model: { providerID: "omnirush", id: "gpt-6-astra", variant: "high" } });expect(recorded[1]!.body).toEqual({ agent: "omnirush" });expect(recorded[2]!.body).toEqual({ value: "Extra system" });- expect(recorded[3]!.body).toEqual({ id: "msg_client_1", text: "hello", files: [{ uri: "data:image/png;base64,AAAA", name: "a.png" }] });+ expect(recorded[3]!.body).toEqual({+ id: "msg_client_1",+ text: "hello",+ files: [{ uri: "data:image/png;base64,AAAA", name: "a.png" }],+ // The 1.x user message fields 2.x does not keep travel as message metadata.+ metadata: { omnirush: { agent: "omnirush", model: { providerID: "omnirush", modelID: "gpt-6-astra", variant: "high" }, system: "Extra system" } },+ });// The same selection is not sent again.recorded.length = 0;await post(`/session/${SESSION}/prompt_async`, { model: { providerID: "omnirush", modelID: "gpt-6-astra" }, variant: "high", agent: "omnirush", system: "Extra system", parts: [{ type: "text", text: "again" }] });diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.tsindex d73aa346..46d118ec 100644--- a/apps/server/src/engine2/facade.ts+++ b/apps/server/src/engine2/facade.ts@@ -18,7 +18,9 @@*/import http from "node:http";import { spawn } from "node:child_process";+import { existsSync } from "node:fs";import { readFile } from "node:fs/promises";+import { dirname as parentDir, join as joinPath } from "node:path";import { homedir } from "node:os";import { buildEngine2Config, v2Mcp } from "./config.js";import { EventTranslator, v1EventEnvelope, type ScopedV1Event, type V1Event } from "./events.js";@@ -89,6 +91,28 @@ function openInBrowser(url: string): void {}}+const roots = new Map<string, string>();+/** The worktree root 1.x reported in `path.root` / relative paths: the enclosing git root, else "/". */+export function worktreeRoot(directory: string | undefined): string {+ if (!directory) return "/";+ const known = roots.get(directory);+ if (known) return known;+ let current = directory;+ let root = "/";+ for (let depth = 0; depth < 64; depth++) {+ if (existsSync(joinPath(current, ".git"))) {+ root = current;+ break;+ }+ const parent = parentDir(current);+ if (parent === current) break;+ current = parent;+ }+ if (roots.size > 256) roots.clear();+ roots.set(directory, root);+ return root;+}+class UpstreamError extends Error {constructor(readonly status: number, readonly body: unknown) {super(`engine answered ${status}`);@@ -160,6 +184,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E/** Session model/agent last sent to the engine, to skip redundant switch records. */const selected = new Map<string, { model?: string; agent?: string; system?: string }>();const archived = new Map<string, number>();+ const todos = new Map<string, JsonRecord[]>();const call = async (method: string,@@ -190,6 +215,7 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Econst translator = new EventTranslator({version: options.version,+ rootFor: worktreeRoot,lookupSession: (sessionID) => call("GET", `/api/session/${encodeURIComponent(sessionID)}`),});@@ -215,6 +241,14 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eif (!info) return null;const archivedAt = archived.get(sessionID) ?? num(record(info, "metadata"), "omnirushArchivedAt");if (archivedAt) info.time = { ...(record(info, "time") ?? {}), archived: archivedAt };+ const picked = selected.get(sessionID);+ if (picked?.model) {+ // The model and agent this adapter last selected for the session (its next step runs on them).+ const [ref, variant] = picked.model.split("#");+ const slash = ref!.indexOf("/");+ info.model = { id: ref!.slice(slash + 1), providerID: ref!.slice(0, slash), variant: variant || "default" };+ }+ if (picked?.agent) info.agent = picked.agent;if (!info.agent || !info.model) {// 2.x records the agent and model on each step, not on the session: take the latest step's.const recent = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/message`, { query: { order: "desc", limit: "20" } }).catch(() => undefined);@@ -255,20 +289,64 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Ereturn 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[]> }>();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 readSessionMessages = async (sessionID: string): Promise<V1Message[]> => {const info = await sessionInfo(sessionID).catch(() => null);const directory = info ? String(info.directory || "") || undefined : undefined;+ const variant = str(info?.model, "variant");const model = isRecord(info?.model) && str(info!.model, "id")- ? { providerID: String(str(info!.model, "providerID")), modelID: String(str(info!.model, "id")), variant: str(info!.model, "variant") }+ ? omitUndefined({ providerID: String(str(info!.model, "providerID")), modelID: String(str(info!.model, "id")), variant: variant && variant !== "default" ? variant : undefined }): undefined;- return v1Messages(await rawMessages(sessionID), {+ const mapped = v1Messages(await rawMessages(sessionID), {sessionID,directory,- root: "/",+ root: worktreeRoot(directory),agent: info ? str(info, "agent") : undefined,model,child: Boolean(info && str(info, "parentID")),});+ await attachTurnDiffs(sessionID, mapped);+ return mapped;+ };++ // 1.x put each prompt's turn diff (whole-file patches) on the user message as `summary.diffs`.+ const turnDiffs = new Map<string, JsonRecord[]>();+ const attachTurnDiffs = async (sessionID: string, messages: V1Message[]): Promise<void> => {+ const busy = translator.statusOf(sessionID)?.type === "busy";+ const prompts = messages.filter((message) => message.info.role === "user" && !message.parts.some((part) => part.synthetic === true));+ for (const [index, message] of prompts.entries()) {+ const id = String(message.info.id);+ const key = `${sessionID}\u0000${id}`;+ let diffs = turnDiffs.get(key);+ const current = index === prompts.length - 1;+ if (!diffs && !(current && busy)) {+ const payload = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/diff`, { query: { from: id } }).catch(() => undefined);+ const list = unwrap(payload);+ if (Array.isArray(list)) {+ diffs = list.filter(isRecord).map((diff) => omitUndefined({+ file: str(diff, "file"),+ patch: str(diff, "patch"),+ additions: num(diff, "additions") ?? 0,+ deletions: num(diff, "deletions") ?? 0,+ status: str(diff, "status"),+ }));+ if (!current) turnDiffs.set(key, diffs);+ if (turnDiffs.size > 4096) turnDiffs.delete(turnDiffs.keys().next().value as string);+ }+ }+ if (diffs) message.info.summary = { diffs };+ }};const listSessions = async (directory: string | undefined, query: URLSearchParams, rootsOnly: boolean): Promise<JsonRecord[]> => {@@ -358,11 +436,21 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Eelse if (type === "agent" && typeof part.name === "string") agents.push({ id: part.name });else if (type === "subtask" && typeof part.prompt === "string") texts.push(part.prompt);}+ // The 1.x user message fields 2.x does not keep (system prompt, agent and model as picked,+ // tool switches) travel in the message metadata, so reads return them field for field.+ const model = modelRefFromBody(body);+ const v1 = omitUndefined({+ agent: str(body, "agent"),+ model: model ? omitUndefined({ providerID: model.providerID, modelID: model.modelID, variant: model.variant && model.variant !== "default" ? model.variant : undefined }) : undefined,+ system: str(body, "system"),+ tools: isRecord(body.tools) ? body.tools : undefined,+ });return omitUndefined({id: str(body, "messageID"),text: texts.join("\n\n"),files: files.length ? files : undefined,agents: agents.length ? agents : undefined,+ metadata: Object.keys(v1).length ? { omnirush: v1 } : undefined,resume: body.noReply === true ? false : undefined,});};@@ -488,6 +576,8 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Elet streamStarted = false;const dispatch = (items: ScopedV1Event[]) => {for (const item of items) {+ const touched = str(item.event.properties, "sessionID") ?? str(record(item.event.properties, "info"), "sessionID") ?? str(record(item.event.properties, "part"), "sessionID");+ if (touched) messageCache.delete(touched);for (const subscriber of subscribers) {if (!subscriber.global && subscriber.directory && item.directory && item.directory !== subscriber.directory) continue;subscriber.write(item.event, item.directory);@@ -771,9 +861,17 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<Ejson(res, 200, v1Session(created, { version: options.version, directory }));return;}- case "todo":- json(res, 200, []);+ case "todo": {+ if (!todos.has(sessionID)) {+ // Rebuilt from the session's last todo list call when the adapter has not seen one yet.+ const messages = await sessionMessages(sessionID).catch(() => []);+ const last = messages.flatMap((message) => message.parts).filter((part) => part.type === "tool" && part.tool === "todowrite").at(-1);+ const input = record(record(last, "state"), "input");+ todos.set(sessionID, arr(input, "todos").filter(isRecord));+ }+ json(res, 200, todos.get(sessionID) ?? []);return;+ }case "diff":json(res, 200, []);return;@@ -1028,6 +1126,18 @@ export async function startEngineFacade(options: EngineFacadeOptions): Promise<E}}}+ if (method === "POST" && path === "/omnirush/todos") {+ // The plugin bridge's todo list tool: remembered per session and announced as the 1.x event.+ const body = ((await readBody(req)) ?? {}) as JsonRecord;+ const sessionID = str(body, "sessionID");+ if (sessionID) {+ const list = arr(body, "todos").filter(isRecord);+ todos.set(sessionID, list);+ dispatch([{ directory: translator.directoryOf(sessionID), event: { type: "todo.updated", properties: { sessionID, todos: list } } }]);+ }+ json(res, 200, true);+ return;+ }if (method === "POST" && path === "/omnirush/engine-tools") {// The plugin bridge reports the tools the engine offers (1.x names) for the tool listing routes.const body = ((await readBody(req)) ?? {}) as JsonRecord;diff --git a/apps/server/src/engine2/fixtures/v1-patch.json b/apps/server/src/engine2/fixtures/v1-patch.jsonnew file mode 100644index 00000000..8d9d564c--- /dev/null+++ b/apps/server/src/engine2/fixtures/v1-patch.json@@ -0,0 +1,236 @@+{+ "session": {+ "id": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "slug": "quiet-sailor",+ "projectID": "global",+ "directory": "/work/proj",+ "path": "work/proj",+ "summary": {+ "additions": 0,+ "deletions": 0,+ "files": 0+ },+ "cost": 0,+ "tokens": {+ "input": 405,+ "output": 80,+ "reasoning": 0,+ "cache": {+ "read": 2000,+ "write": 0+ }+ },+ "title": "Parity session title",+ "agent": "build",+ "model": {+ "id": "gpt-5.1-mock",+ "providerID": "mock",+ "variant": "default"+ },+ "version": "1.18.32",+ "time": {+ "created": 1790482272785,+ "updated": 1790482276533+ }+ },+ "messages": [+ {+ "info": {+ "id": "msg_0e10f52a1001SiLMvcNLzPM1nJ",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "role": "user",+ "time": {+ "created": 1790482272929+ },+ "summary": {+ "diffs": []+ },+ "agent": "build",+ "model": {+ "providerID": "mock",+ "modelID": "gpt-5.1-mock"+ }+ },+ "parts": [+ {+ "id": "prt_0e10f52b4001NblUWTBupEiTXV",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f52a1001SiLMvcNLzPM1nJ",+ "type": "text",+ "text": "PARITY-PATCH patch it"+ }+ ]+ },+ {+ "info": {+ "id": "msg_0e10f588c001DqiHIAVcBbfTc0",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "role": "assistant",+ "time": {+ "created": 1790482274444,+ "completed": 1790482276278+ },+ "parentID": "msg_0e10f52a1001SiLMvcNLzPM1nJ",+ "modelID": "gpt-5.1-mock",+ "providerID": "mock",+ "mode": "build",+ "agent": "build",+ "path": {+ "cwd": "/work/proj",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 1242,+ "input": 202,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ },+ "finish": "tool-calls"+ },+ "parts": [+ {+ "id": "prt_0e10f5f1b001rp6sQuvmATowun",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f588c001DqiHIAVcBbfTc0",+ "type": "step-start"+ },+ {+ "id": "prt_0e10f5f27001N6pmzc2qvbVB6p",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f588c001DqiHIAVcBbfTc0",+ "type": "tool",+ "callID": "call_2_0",+ "tool": "apply_patch",+ "state": {+ "status": "completed",+ "input": {+ "patchText": "*** Begin Patch\n*** Update File: notes.md\n@@\n # Notes\n-line one\n+line one (patched)\n*** Add File: extra.md\n+# Extra\n+added by patch\n*** End Patch"+ },+ "output": "Success. Updated the following files:\nM work/proj/notes.md\nA work/proj/extra.md",+ "title": "Success. Updated the following files:\nM work/proj/notes.md\nA work/proj/extra.md",+ "metadata": {+ "diff": "Index: /work/proj/notes.md\n===================================================================\n--- /work/proj/notes.md\n+++ /work/proj/notes.md\n@@ -1,3 +1,3 @@\n # Notes\n-line one\n+line one (patched)\n line two\n\nIndex: /work/proj/extra.md\n===================================================================\n--- /work/proj/extra.md\n+++ /work/proj/extra.md\n@@ -0,0 +1,2 @@\n+# Extra\n+added by patch\n\n",+ "files": [+ {+ "filePath": "/work/proj/notes.md",+ "relativePath": "work/proj/notes.md",+ "type": "update",+ "patch": "Index: /work/proj/notes.md\n===================================================================\n--- /work/proj/notes.md\n+++ /work/proj/notes.md\n@@ -1,3 +1,3 @@\n # Notes\n-line one\n+line one (patched)\n line two\n",+ "additions": 1,+ "deletions": 1+ },+ {+ "filePath": "/work/proj/extra.md",+ "relativePath": "work/proj/extra.md",+ "type": "add",+ "patch": "Index: /work/proj/extra.md\n===================================================================\n--- /work/proj/extra.md\n+++ /work/proj/extra.md\n@@ -0,0 +1,2 @@\n+# Extra\n+added by patch\n",+ "additions": 2,+ "deletions": 0+ }+ ],+ "diagnostics": {},+ "truncated": false+ },+ "time": {+ "start": 1790482276168,+ "end": 1790482276259+ }+ }+ },+ {+ "id": "prt_0e10f5fab001ArFbDOdbbOq0t5",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f588c001DqiHIAVcBbfTc0",+ "type": "step-finish",+ "reason": "tool-calls",+ "cost": 0,+ "tokens": {+ "total": 1242,+ "input": 202,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ }+ ]+ },+ {+ "info": {+ "id": "msg_0e10f5fbd001D4MaLmLLR4Dkt3",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "role": "assistant",+ "time": {+ "created": 1790482276285,+ "completed": 1790482276523+ },+ "parentID": "msg_0e10f52a1001SiLMvcNLzPM1nJ",+ "modelID": "gpt-5.1-mock",+ "providerID": "mock",+ "mode": "build",+ "agent": "build",+ "path": {+ "cwd": "/work/proj",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 1243,+ "input": 203,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ },+ "finish": "stop"+ },+ "parts": [+ {+ "id": "prt_0e10f606b001a9Rr6364lC3CS3",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f5fbd001D4MaLmLLR4Dkt3",+ "type": "step-start"+ },+ {+ "id": "prt_0e10f60710016t92zGHB6wjILn",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f5fbd001D4MaLmLLR4Dkt3",+ "type": "text",+ "text": "Patched.",+ "time": {+ "start": 1790482276465,+ "end": 1790482276476+ }+ },+ {+ "id": "prt_0e10f60a1001lnb5A41avmsWFl",+ "sessionID": "ses_f1ef0adefffe1mLGRXHvrnGDh8",+ "messageID": "msg_0e10f5fbd001D4MaLmLLR4Dkt3",+ "type": "step-finish",+ "reason": "stop",+ "cost": 0,+ "tokens": {+ "total": 1243,+ "input": 203,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ }+ ]+ }+ ],+ "children": []+}\ No newline at end of filediff --git a/apps/server/src/engine2/fixtures/v1-tools.json b/apps/server/src/engine2/fixtures/v1-tools.jsonnew file mode 100644index 00000000..2ad1995a--- /dev/null+++ b/apps/server/src/engine2/fixtures/v1-tools.json@@ -0,0 +1,242 @@+{+ "session": {+ "id": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "slug": "crisp-eagle",+ "projectID": "global",+ "directory": "/work/proj",+ "path": "work/proj",+ "summary": {+ "additions": 0,+ "deletions": 0,+ "files": 0+ },+ "cost": 0,+ "tokens": {+ "input": 405,+ "output": 80,+ "reasoning": 0,+ "cache": {+ "read": 2000,+ "write": 0+ }+ },+ "title": "Parity session title",+ "agent": "build",+ "model": {+ "id": "mock-model",+ "providerID": "mock",+ "variant": "default"+ },+ "version": "1.18.32",+ "time": {+ "created": 1790483385510,+ "updated": 1790483386553+ }+ },+ "messages": [+ {+ "info": {+ "id": "msg_0e1204cfc001iHkVyVS9ZNihHJ",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "role": "user",+ "time": {+ "created": 1790483385596+ },+ "summary": {+ "diffs": []+ },+ "agent": "build",+ "model": {+ "providerID": "mock",+ "modelID": "mock-model"+ }+ },+ "parts": [+ {+ "id": "prt_0e1204d0b001MohuznaygGdzKP",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204cfc001iHkVyVS9ZNihHJ",+ "type": "text",+ "text": "PARITY-TOOLS find md files"+ }+ ]+ },+ {+ "info": {+ "id": "msg_0e1204d2c001fw6CAsiyNhOjP5",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "role": "assistant",+ "time": {+ "created": 1790483385644,+ "completed": 1790483386257+ },+ "parentID": "msg_0e1204cfc001iHkVyVS9ZNihHJ",+ "modelID": "mock-model",+ "providerID": "mock",+ "mode": "build",+ "agent": "build",+ "path": {+ "cwd": "/work/proj",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 1242,+ "input": 202,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ },+ "finish": "tool-calls"+ },+ "parts": [+ {+ "id": "prt_0e1204ec0001HEE5kxKzcEWUhW",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204d2c001fw6CAsiyNhOjP5",+ "type": "step-start"+ },+ {+ "id": "prt_0e1204eca001yNjmk8Z2sqvYM0",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204d2c001fw6CAsiyNhOjP5",+ "type": "tool",+ "callID": "call_2_0",+ "tool": "glob",+ "state": {+ "status": "completed",+ "input": {+ "pattern": "*.md"+ },+ "output": "/work/proj/extra.md\n/work/proj/notes.md",+ "title": "work/proj",+ "metadata": {+ "count": 2,+ "truncated": false+ },+ "time": {+ "start": 1790483386079,+ "end": 1790483386184+ }+ }+ },+ {+ "id": "prt_0e1204ee7001l37M07L5JAFEFa",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204d2c001fw6CAsiyNhOjP5",+ "type": "tool",+ "callID": "call_2_1",+ "tool": "grep",+ "state": {+ "status": "completed",+ "input": {+ "pattern": "line",+ "include": "*.md"+ },+ "output": "Found 2 matches\n/work/proj/notes.md:\n Line 2: line one (patched)\n\n Line 3: line two\n",+ "title": "line",+ "metadata": {+ "matches": 2,+ "truncated": false+ },+ "time": {+ "start": 1790483386105,+ "end": 1790483386223+ }+ }+ },+ {+ "id": "prt_0e1204f78001fVqfUImW3mnra1",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204d2c001fw6CAsiyNhOjP5",+ "type": "step-finish",+ "reason": "tool-calls",+ "cost": 0,+ "tokens": {+ "total": 1242,+ "input": 202,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ }+ ]+ },+ {+ "info": {+ "id": "msg_0e1204fa1001M9po9cdFLR0pUg",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "role": "assistant",+ "time": {+ "created": 1790483386273,+ "completed": 1790483386543+ },+ "parentID": "msg_0e1204cfc001iHkVyVS9ZNihHJ",+ "modelID": "mock-model",+ "providerID": "mock",+ "mode": "build",+ "agent": "build",+ "path": {+ "cwd": "/work/proj",+ "root": "/"+ },+ "cost": 0,+ "tokens": {+ "total": 1243,+ "input": 203,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ },+ "finish": "stop"+ },+ "parts": [+ {+ "id": "prt_0e120504a001iBzCXT70LCaRPt",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204fa1001M9po9cdFLR0pUg",+ "type": "step-start"+ },+ {+ "id": "prt_0e1205051001QLrb3u4nGL2ZvL",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204fa1001M9po9cdFLR0pUg",+ "type": "text",+ "text": "Found them.",+ "time": {+ "start": 1790483386449,+ "end": 1790483386514+ }+ },+ {+ "id": "prt_0e120509c001EDIIwI6Qr2xNVM",+ "sessionID": "ses_f1edfb359ffey4j1DUiVnxf2Wi",+ "messageID": "msg_0e1204fa1001M9po9cdFLR0pUg",+ "type": "step-finish",+ "reason": "stop",+ "cost": 0,+ "tokens": {+ "total": 1243,+ "input": 203,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ }+ ]+ }+ ],+ "children": []+}\ No newline at end of filediff --git a/apps/server/src/engine2/fixtures/v2-patch.json b/apps/server/src/engine2/fixtures/v2-patch.jsonnew file mode 100644index 00000000..c18a1237--- /dev/null+++ b/apps/server/src/engine2/fixtures/v2-patch.json@@ -0,0 +1,165 @@+{+ "session": {+ "id": "ses_f1eef747affejcuId07xwqSRnl",+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",+ "model": {+ "id": "gpt-5.1-mock",+ "providerID": "mock",+ "variant": "default"+ },+ "cost": 0,+ "tokens": {+ "input": 624,+ "output": 120,+ "reasoning": 0,+ "cache": {+ "read": 3000,+ "write": 0+ }+ },+ "outcome": "succeeded",+ "time": {+ "created": 1790482353036,+ "updated": 1790482353247,+ "idle": 1790482353447+ },+ "title": "Parity session title",+ "location": {+ "directory": "/work/proj"+ }+ },+ "messages": [+ {+ "id": "msg_0e1108bad0012No5STds62tAnP",+ "time": {+ "created": 1790482353069+ },+ "type": "model-switched",+ "model": {+ "id": "gpt-5.1-mock",+ "providerID": "mock"+ }+ },+ {+ "id": "msg_0e1108bbb001de5s1Hv3CaXTlq",+ "time": {+ "created": 1790482353124+ },+ "text": "PARITY-PATCH patch it",+ "type": "user"+ },+ {+ "id": "msg_0e1108c03001LO0iCneNBc6MVL",+ "time": {+ "created": 1790482353181,+ "streamed": 1790482353270,+ "completed": 1790482353298+ },+ "type": "assistant",+ "agent": "build",+ "model": {+ "id": "gpt-5.1-mock",+ "providerID": "mock",+ "variant": "default"+ },+ "content": [+ {+ "type": "tool",+ "id": "call_8_0",+ "name": "patch",+ "executed": false,+ "state": {+ "status": "completed",+ "input": {+ "patchText": "*** Begin Patch\n*** Update File: notes.md\n@@\n # Notes\n-line one\n+line one (patched)\n*** Add File: extra.md\n+# Extra\n+added by patch\n*** End Patch"+ },+ "content": [+ {+ "type": "text",+ "text": "Success. Updated the following files:\nM notes.md\nA extra.md"+ }+ ],+ "metadata": {+ "files": [+ {+ "file": "notes.md",+ "patch": "Index: /work/proj/notes.md\n===================================================================\n--- /work/proj/notes.md\n+++ /work/proj/notes.md\n@@ -1,3 +1,3 @@\n # Notes\n-line one\n+line one (patched)\n line two\n",+ "status": "modified",+ "additions": 1,+ "deletions": 1+ },+ {+ "file": "extra.md",+ "patch": "Index: /work/proj/extra.md\n===================================================================\n--- /work/proj/extra.md\n+++ /work/proj/extra.md\n@@ -0,0 +1,2 @@\n+# Extra\n+added by patch\n",+ "status": "added",+ "additions": 2,+ "deletions": 0+ }+ ],+ "truncated": false+ }+ },+ "time": {+ "created": 1790482353196,+ "ran": 1790482353262,+ "completed": 1790482353291+ }+ }+ ],+ "finish": "tool-calls",+ "rawFinish": "tool_calls",+ "cost": 0,+ "tokens": {+ "input": 208,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ },+ {+ "id": "msg_0e1108ca9001YQpGQphgQaVTkb",+ "time": {+ "created": 1790482353348,+ "streamed": 1790482353431,+ "completed": 1790482353437+ },+ "type": "assistant",+ "agent": "build",+ "model": {+ "id": "gpt-5.1-mock",+ "providerID": "mock",+ "variant": "default"+ },+ "content": [+ {+ "type": "text",+ "text": "Patched."+ }+ ],+ "finish": "stop",+ "rawFinish": "stop",+ "cost": 0,+ "tokens": {+ "input": 209,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ },+ {+ "id": "msg_0e1108d27001EdHTWY68B3ZmPM",+ "time": {+ "created": 1790482353447+ },+ "type": "idle",+ "outcome": "succeeded"+ }+ ],+ "children": []+}\ No newline at end of filediff --git a/apps/server/src/engine2/fixtures/v2-tools.json b/apps/server/src/engine2/fixtures/v2-tools.jsonnew file mode 100644index 00000000..124b132e--- /dev/null+++ b/apps/server/src/engine2/fixtures/v2-tools.json@@ -0,0 +1,160 @@+{+ "session": {+ "id": "ses_f1edf9e51ffeFpOjh7F1D1wA30",+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",+ "cost": 0,+ "tokens": {+ "input": 615,+ "output": 120,+ "reasoning": 0,+ "cache": {+ "read": 3000,+ "write": 0+ }+ },+ "outcome": "succeeded",+ "time": {+ "created": 1790483390905,+ "updated": 1790483391147,+ "idle": 1790483391438+ },+ "title": "Parity session title",+ "location": {+ "directory": "/work/proj"+ }+ },+ "messages": [+ {+ "id": "msg_0e12061dd001yN4fM9kLBKKuF4",+ "time": {+ "created": 1790483391009+ },+ "text": "PARITY-TOOLS find md files",+ "type": "user"+ },+ {+ "id": "msg_0e120624d001JQ5eNDVTSXQ9MQ",+ "time": {+ "created": 1790483391088,+ "streamed": 1790483391189,+ "completed": 1790483391266+ },+ "type": "assistant",+ "agent": "build",+ "model": {+ "id": "mock-model",+ "providerID": "mock"+ },+ "content": [+ {+ "type": "tool",+ "id": "call_5_0",+ "name": "glob",+ "executed": false,+ "state": {+ "status": "completed",+ "input": {+ "pattern": "*.md"+ },+ "content": [+ {+ "type": "text",+ "text": "/work/proj/extra.md\n/work/proj/notes.md"+ }+ ],+ "metadata": {+ "count": 2,+ "truncated": false+ }+ },+ "time": {+ "created": 1790483391113,+ "ran": 1790483391167,+ "completed": 1790483391257+ }+ },+ {+ "type": "tool",+ "id": "call_5_1",+ "name": "grep",+ "executed": false,+ "state": {+ "status": "completed",+ "input": {+ "pattern": "line",+ "include": "*.md"+ },+ "content": [+ {+ "type": "text",+ "text": "Found 2 matches\n/work/proj/notes.md:\n Line 2: line one (patched)\n\n Line 3: line two\n"+ }+ ],+ "metadata": {+ "matches": 2,+ "truncated": false+ }+ },+ "time": {+ "created": 1790483391125,+ "ran": 1790483391182,+ "completed": 1790483391247+ }+ }+ ],+ "finish": "tool-calls",+ "rawFinish": "tool_calls",+ "cost": 0,+ "tokens": {+ "input": 205,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ },+ {+ "id": "msg_0e12063420011ZeWOYCJRtpmdu",+ "time": {+ "created": 1790483391321,+ "streamed": 1790483391420,+ "completed": 1790483391427+ },+ "type": "assistant",+ "agent": "build",+ "model": {+ "id": "mock-model",+ "providerID": "mock"+ },+ "content": [+ {+ "type": "text",+ "text": "Found them."+ }+ ],+ "finish": "stop",+ "rawFinish": "stop",+ "cost": 0,+ "tokens": {+ "input": 206,+ "output": 40,+ "reasoning": 0,+ "cache": {+ "read": 1000,+ "write": 0+ }+ }+ },+ {+ "id": "msg_0e12063ce001mIBxZYd8sE1KbV",+ "time": {+ "created": 1790483391438+ },+ "type": "idle",+ "outcome": "succeeded"+ }+ ],+ "children": []+}\ No newline at end of filediff --git a/apps/server/src/engine2/shapes.test.ts b/apps/server/src/engine2/shapes.test.tsindex c2c75f70..3e7866c1 100644--- a/apps/server/src/engine2/shapes.test.ts+++ b/apps/server/src/engine2/shapes.test.ts@@ -10,7 +10,8 @@ import { partId, v1Messages, v1PermissionRequest, v1QuestionRequest, v1Session,* and on the 2.x engine (2.0.18), read back with each engine's own API* (`v1-*.json`: `/session/:id/message`, `v2-*.json`: `/api/session/:id/message`),* machine paths replaced by /work. p1: shell, write, edit and a text answer;- * sub: two parallel sub-agents; nest: sub-agents three layers deep.+ * sub: two parallel sub-agents; nest: sub-agents three layers deep; patch: a GPT-style+ * apply_patch (2.x `patch`) that updates one file and adds another; tools: glob and grep.*/type Tree = { session: Record<string, unknown>; messages: unknown[]; children: Tree[] };const fixture = (name: string): Tree => JSON.parse(readFileSync(join(import.meta.dir, "fixtures", `${name}.json`), "utf8"));@@ -77,7 +78,7 @@ 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"]) {+ for (const scenario of ["p1", "sub", "nest", "patch", "tools"]) {test(`${scenario}: every message, part and field the 1.x engine wrote, and no other`, () => {const out: string[] = [];compareTrees(fixture(`v1-${scenario}`), mapTree(fixture(`v2-${scenario}`)), "root", out);diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.tsindex 74e86b8b..627ea77c 100644--- a/apps/server/src/engine2/shapes.ts+++ b/apps/server/src/engine2/shapes.ts@@ -73,8 +73,11 @@ export function v1ToolInput(name: string, raw: unknown): JsonRecord {return { filePath: path, ...rest };}case "subagent": {- if (typeof input.agent !== "string" || "subagent_type" in input) return input;- const { agent, ...rest } = input;+ // Sub-agents always run in the foreground here (the plugin bridge keeps `background` off),+ // as the 1.x task tool did; the flag is not part of the 1.x input.+ const { background: _background, ...withoutBackground } = input;+ if (typeof withoutBackground.agent !== "string" || "subagent_type" in withoutBackground) return withoutBackground;+ const { agent, ...rest } = withoutBackground;return { subagent_type: agent, ...rest };}default:@@ -154,11 +157,30 @@ function v1ToolTitle(name: string, input: JsonRecord, ctx: ToolContext): stringreturn String(input.query ?? "");case "skill":return String(input.id ?? input.name ?? "");+ case "todowrite": {+ const todos = Array.isArray(input.todos) ? input.todos : [];+ return `${todos.filter((todo) => !isRecord(todo) || todo.status !== "completed").length} todos`;+ }default:return v1ToolName(name);}}+/** A 2.x patch file entry (`{file, patch, status, additions, deletions}`) as the 1.x apply_patch one. */+function v1PatchFile(entry: JsonRecord, ctx: ToolContext): JsonRecord {+ const file = absoluteFrom(ctx.directory, String(entry.file ?? entry.filePath ?? ""));+ const status = str(entry, "status");+ return omitUndefined({+ filePath: file,+ relativePath: relativeTo(ctx.root && ctx.root !== "/" ? ctx.root : "/", file),+ type: status === "added" ? "add" : status === "deleted" ? "delete" : status === "moved" || status === "renamed" ? "move" : "update",+ patch: typeof entry.patch === "string" ? entry.patch : str(entry, "diff") ?? "",+ additions: typeof entry.additions === "number" ? entry.additions : 0,+ deletions: typeof entry.deletions === "number" ? entry.deletions : 0,+ movePath: str(entry, "movePath") ?? str(entry, "target"),+ });+}+/** A completed 2.x tool call's metadata with the 1.x keys the app, swarm board and converter read. */function v1ToolMetadata(name: string, input: JsonRecord, metadata: JsonRecord, output: string, ctx: ToolContext): JsonRecord {switch (name) {@@ -203,8 +225,7 @@ function v1ToolMetadata(name: string, input: JsonRecord, metadata: JsonRecord, oconst { existed: _existed, ...rest } = metadata;return { diagnostics: {}, filepath: file, exists, ...rest };}- case "edit":- case "patch": {+ case "edit": {const files = Array.isArray(metadata.files) ? metadata.files.filter(isRecord) : [];const first = files[0];const { files: _files, ...rest } = metadata;@@ -220,10 +241,20 @@ function v1ToolMetadata(name: string, input: JsonRecord, metadata: JsonRecord, oadditions: typeof first.additions === "number" ? first.additions : 0,deletions: typeof first.deletions === "number" ? first.deletions : 0,}),- ...(name === "patch" ? { files: files.map((entry) => ({ ...entry, file: absoluteFrom(ctx.directory, String(entry.file ?? "")) })) } : {}),...rest,});}+ case "patch": {+ // 1.x apply_patch: one combined diff and a file list keyed filePath / relativePath.+ const files = (Array.isArray(metadata.files) ? metadata.files.filter(isRecord) : []).map((entry) => v1PatchFile(entry, ctx));+ const { files: _files, ...rest } = metadata;+ return {+ diff: files.map((entry) => String(entry.patch ?? "")).filter(Boolean).join("\n"),+ files,+ diagnostics: {},+ ...rest,+ };+ }default:return metadata;}@@ -256,6 +287,22 @@ function errorMessage(value: unknown): string {return value === undefined ? "" : String(value);}+/**+ * 2.x keeps a content entry's provider state bare (`{itemId, …}`); 1.x kept the same values as+ * part metadata under the provider's namespace (`{openai: {itemId, …}}`). The namespace follows+ * from the state's keys (OpenAI Responses item ids, Anthropic signatures, Google thought+ * signatures); the reasoning-field hint of chat-completions providers is not provider metadata.+ */+export function v1ProviderMetadata(state: unknown): JsonRecord | undefined {+ if (!isRecord(state)) return undefined;+ const { reasoningField: _reasoningField, ...rest } = state;+ if (Object.keys(rest).length === 0) return undefined;+ if ("itemId" in rest || "responseId" in rest) return { openai: rest };+ if ("signature" in rest || "redactedData" in rest) return { anthropic: rest };+ if ("thoughtSignature" in rest) return { google: rest };+ return undefined;+}+/** Part ids: `prt_<message id sans prefix>_<slot>[_<call id>]`, the same from a read and from events. */export function partId(messageID: string, slot: string, callID?: string): string {const core = messageID.startsWith("msg_") ? messageID.slice(4) : messageID;@@ -280,6 +327,7 @@ export function v1ToolPart(const end = num(time, "completed") ?? start;const input = v1ToolInput(name, state.input);const rawInput = parseInput(state.input);+ const providerMetadata = v1ProviderMetadata(entry.providerState);const base = {id: partId(ids.messageID, "c", callID),sessionID: ids.sessionID,@@ -287,6 +335,7 @@ export function v1ToolPart(type: "tool",callID,tool: v1ToolName(name),+ ...(providerMetadata ? { metadata: providerMetadata } : {}),};if (status === "streaming" || status === "pending") {return { ...base, state: { status: "pending", input, raw: typeof state.input === "string" ? state.input : JSON.stringify(state.input ?? {}) } };@@ -419,8 +468,9 @@ function modelRef(value: unknown): ModelRef | undefined {const providerID = str(value, "providerID");const modelID = str(value, "id") ?? str(value, "modelID");if (!providerID || !modelID) return undefined;+ // 2.x records "default" when no variant was picked; 1.x left the field out.const variant = str(value, "variant");- return variant ? { providerID, modelID, variant } : { providerID, modelID };+ return variant && variant !== "default" ? { providerID, modelID, variant } : { providerID, modelID };}/** One 2.x assistant message (one step) as a 1.x assistant message. */@@ -436,8 +486,13 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, parconst tokens = v1Tokens(message.tokens);const cost = num(message, "cost") ?? 0;const finish = str(message, "finish");- const snapshot = str(message, "snapshot");- const parts: JsonRecord[] = [omitUndefined({ id: partId(id, "s0"), sessionID: ctx.sessionID, messageID: id, type: "step-start", snapshot })];+ // 2.x keeps the step's snapshots together (`{start, end, files}`); 1.x put the start on+ // step-start, the end on step-finish, and the changed files in a `patch` part.+ const snapshots = record(message, "snapshot") ?? {};+ const snapshotStart = str(snapshots, "start") ?? str(message, "snapshot");+ const snapshotEnd = str(snapshots, "end") ?? snapshotStart;+ const changed = arr(snapshots, "files").filter((file): file is string => typeof file === "string");+ const parts: JsonRecord[] = [omitUndefined({ id: partId(id, "s0"), sessionID: ctx.sessionID, messageID: id, type: "step-start", snapshot: snapshotStart })];const ordinals = { text: 0, reasoning: 0 };for (const entry of arr(message, "content")) {if (!isRecord(entry)) continue;@@ -448,6 +503,7 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, parconst entryTime = record(entry, "time");const start = num(entryTime, "created");const end = num(entryTime, "completed");+ const metadata = v1ProviderMetadata(entry.state);if (type === "reasoning") {parts.push(omitUndefined({id: partId(id, `r${ordinal}`),@@ -455,6 +511,7 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, parmessageID: id,type: "reasoning",text,+ metadata,time: omitUndefined({ start: start ?? created, end: end ?? (completed !== undefined ? completed : undefined) }),}));} else {@@ -465,6 +522,7 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, partype: "text",text,time: start !== undefined || completed !== undefined ? omitUndefined({ start: start ?? created, end: end ?? completed }) : undefined,+ metadata,}));}continue;@@ -482,10 +540,21 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, parmessageID: id,type: "step-finish",reason: finish,- snapshot,+ snapshot: snapshotEnd,cost,tokens,}));+ if (changed.length > 0 && snapshotStart) {+ const base = ctx.root && ctx.root !== "/" ? ctx.root : ctx.directory;+ parts.push({+ id: partId(id, "p0"),+ sessionID: ctx.sessionID,+ messageID: id,+ type: "patch",+ hash: snapshotStart,+ files: changed.map((file) => absoluteFrom(base, file)),+ });+ }}const error = v1Error(message.error, model?.providerID);const info = omitUndefined({@@ -516,6 +585,7 @@ function v1UserMessage(synthetic: boolean,agent: string,model: ModelRef | undefined,+ extra: { system?: string; tools?: JsonRecord } = {},): V1Message {const id = str(message, "id") ?? "";const created = num(record(message, "time"), "created") ?? 0;@@ -533,6 +603,8 @@ function v1UserMessage(summary: { diffs: [] },agent,model: model ? omitUndefined({ providerID: model.providerID, modelID: model.modelID, variant: model.variant }) : { providerID: "", modelID: "" },+ system: extra.system,+ tools: extra.tools,});return { info, parts };}@@ -660,7 +732,16 @@ export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[let text = str(message, "text") ?? "";if (ctx.child && firstUser && type === "user" && text.startsWith(SUBAGENT_PROMPT_PREFIX)) text = text.slice(SUBAGENT_PROMPT_PREFIX.length);if (type === "user") firstUser = false;- const mapped = v1UserMessage(message, ctx, text, arr(message, "files"), type === "synthetic", replyAgent ?? agent, replyModel ?? model);+ const sent = record(record(message, "metadata"), "omnirush");+ const sentModel = record(sent, "model");+ const mapped = v1UserMessage(+ message, ctx, text, arr(message, "files"), type === "synthetic",+ str(sent, "agent") ?? replyAgent ?? agent,+ sentModel && str(sentModel, "providerID") && str(sentModel, "modelID")+ ? { providerID: str(sentModel, "providerID")!, modelID: str(sentModel, "modelID")!, ...(str(sentModel, "variant") ? { variant: str(sentModel, "variant")! } : {}) }+ : replyModel ?? model,+ { system: str(sent, "system"), tools: record(sent, "tools") },+ );lastUserId = String(mapped.info.id);out.push(mapped);return;diff --git a/apps/server/src/engine2/trace-parity.test.ts b/apps/server/src/engine2/trace-parity.test.tsnew file mode 100644index 00000000..490000bb--- /dev/null+++ b/apps/server/src/engine2/trace-parity.test.ts@@ -0,0 +1,206 @@+import { afterAll, describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { createSessionObservers, observeCollectedSession, type EngineTarget, type ObservedCollector, type ObserverTiming } from "../collector-observer.js";+import type { CollectorChildSession } from "../workspace-collector.js";+import { startEngineFacade, type EngineFacade } from "./facade.js";++/**+ * The uploaded trace does not depend on the engine: the turn observer+ * (collector-observer.ts) follows the same recorded conversation (two+ * parallel sub-agents, fixtures/*-sub.json) once on the 1.x engine and once+ * on the 2.x engine behind the engine adapter, and hands the collector the+ * same trace events, carrying messages and sub-agent sessions with the same+ * fields.+ */++type Tree = { session: Record<string, unknown>; messages: Array<Record<string, unknown>>; children: Tree[] };+const fixture = (name: string): Tree => JSON.parse(readFileSync(join(import.meta.dir, "fixtures", `${name}.json`), "utf8"));++function typeOf(value: unknown): string {+ if (Array.isArray(value)) return "array";+ if (value === null) return "null";+ return typeof value;+}++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);+ 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;+}++const stops: Array<() => unknown> = [];+afterAll(async () => {+ while (stops.length) await stops.pop()?.();+});++function page(url: URL, list: unknown[]): Response {+ const limit = Number(url.searchParams.get("limit") ?? 0);+ if (!limit) return Response.json(list);+ const end = url.searchParams.has("before") ? Number(url.searchParams.get("before")) : list.length;+ const start = Math.max(0, end - limit);+ return Response.json(list.slice(start, end), start > 0 ? { headers: { "X-Next-Cursor": String(start) } } : {});+}++function flatten(tree: Tree, out: Tree[] = []): Tree[] {+ out.push(tree);+ for (const child of tree.children) flatten(child, out);+ return out;+}++/** The 1.x engine's routes the observer reads, serving a recorded 1.x conversation. */+function startV1Engine(tree: Tree): EngineTarget {+ const sessions = new Map(flatten(tree).map((node) => [String(node.session.id), node]));+ const server = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ fetch(request) {+ const url = new URL(request.url);+ if (url.pathname === "/session/status") return Response.json({});+ const match = url.pathname.match(/^\/session\/([^/]+)(?:\/(message|children))?$/);+ const node = match ? sessions.get(decodeURIComponent(match[1]!)) : undefined;+ if (!node) return Response.json({ name: "NotFoundError" }, { status: 404 });+ if (match![2] === "message") return page(url, node.messages);+ if (match![2] === "children") return Response.json(node.children.map((child) => child.session));+ return Response.json(node.session);+ },+ });+ stops.push(() => server.stop(true));+ return { baseUrl: `http://127.0.0.1:${server.port}`, headers: [], search: "", engine: "v1" };+}++/** The 2.x engine's routes the adapter reads, serving the same conversation recorded on 2.x. */+async function startV2Engine(tree: Tree): Promise<EngineTarget> {+ const sessions = new Map(flatten(tree).map((node) => [String(node.session.id), node]));+ const upstream = Bun.serve({+ hostname: "127.0.0.1",+ port: 0,+ fetch(request) {+ const url = new URL(request.url);+ if (url.pathname === "/api/event") return new Response(new ReadableStream({ start() {} }), { headers: { "content-type": "text/event-stream" } });+ if (url.pathname === "/api/session/active") return Response.json({ data: {} });+ if (url.pathname === "/api/session") {+ const parent = url.searchParams.get("parentID");+ const node = parent ? sessions.get(parent) : undefined;+ return Response.json({ data: node ? node.children.map((child) => child.session) : [], cursor: {} });+ }+ const match = url.pathname.match(/^\/api\/session\/([^/]+)(?:\/(message|diff))?$/);+ const node = match ? sessions.get(decodeURIComponent(match[1]!)) : undefined;+ if (!node) return Response.json({ name: "NotFoundError" }, { status: 404 });+ if (match![2] === "message") {+ const list = url.searchParams.get("order") === "desc" ? [...node.messages].reverse() : node.messages;+ return Response.json({ data: list.slice(0, Number(url.searchParams.get("limit") ?? 50)), cursor: {} });+ }+ if (match![2] === "diff") return Response.json({ data: [] });+ return Response.json({ data: node.session });+ },+ });+ stops.push(() => upstream.stop(true));+ const facade: EngineFacade = await startEngineFacade({+ upstreamUrl: `http://127.0.0.1:${upstream.port}`,+ upstreamPassword: "pw",+ username: "u",+ password: "p",+ version: "2.0.18",+ defaultDirectory: "/work/proj",+ });+ stops.push(() => facade.close());+ return { baseUrl: facade.url, headers: [["authorization", `Basic ${Buffer.from("u:p").toString("base64")}`]], search: "", engine: "v1" };+}++type Entry =+ | { kind: "trace"; type: string; data?: unknown }+ | { kind: "model"; model: unknown }+ | { kind: "child"; child: CollectorChildSession }+ | { kind: "flush"; final?: unknown };++class RecordingCollector implements ObservedCollector {+ readonly enabled = true;+ readonly entries: Entry[] = [];+ async sessionCheckpoint() {+ return { resumed: false };+ }+ async setSessionCheckpoint() {}+ recordTrace(_sessionId: string, type: string, data?: unknown) {+ this.entries.push({ kind: "trace", type, ...(data === undefined ? {} : { data }) });+ }+ recordSessionModel(_sessionId: string, model: unknown) {+ this.entries.push({ kind: "model", model });+ }+ async childCheckpoints() {+ return {};+ }+ async childSessionIds() {+ return [];+ }+ recordChildSession(_sessionId: string, child: CollectorChildSession) {+ this.entries.push({ kind: "child", child });+ }+ captureSnapshot() {}+ flushTrace(_sessionId: string, final?: unknown) {+ this.entries.push({ kind: "flush", ...(final === undefined ? {} : { final }) });+ }+}++const timing: Partial<ObserverTiming> = { sleep: async () => undefined };++async function observe(target: EngineTarget, sessionId: string): Promise<RecordingCollector> {+ const collector = new RecordingCollector();+ const archive = { turnFollowed: () => undefined, turnCompleted: () => undefined, turnIncomplete: () => undefined };+ await observeCollectedSession({ collector, archive, observers: createSessionObservers(), sessionId, target, timing });+ return collector;+}++/** Sub-agents start concurrently: children are compared by the task they were given. */+function childKey(child: CollectorChildSession): string {+ const first = (child.messages as Array<{ parts?: Array<{ text?: string }> }>)[0];+ return String(first?.parts?.[0]?.text ?? "");+}++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");+ 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));+ expect(labels(after)).toEqual(labels(before));+ expect(labels(after)).toContain("child");++ const final = (collector: RecordingCollector) => (collector.entries.find((entry) => entry.kind === "flush" && entry.final !== undefined) as { final: { messages: unknown[] } }).final;+ expect(shapeDiff(final(before).messages, final(after).messages)).toEqual([]);++ const children = (collector: RecordingCollector) => collector.entries+ .flatMap((entry) => (entry.kind === "child" ? [entry.child] : []))+ .sort((a, b) => childKey(a).localeCompare(childKey(b)));+ const [left, right] = [children(before), children(after)];+ expect(right.length).toBe(2);+ left.forEach((child, index) => {+ const other = right[index]!;+ expect(Object.keys(other).sort()).toEqual(Object.keys(child).sort());+ expect(other.agent).toBe(child.agent);+ expect(String(other.title)).toMatch(/\(@general subagent\)$/);+ expect(shapeDiff(child.messages, other.messages)).toEqual([]);+ });++ // The session.model event: the same provider, model, variant and agent.+ const model = (collector: RecordingCollector) => collector.entries.find((entry) => entry.kind === "model");+ expect(model(after)).toBeDefined();+ expect(model(after)).toEqual(model(before));+ });+});diff --git a/apps/server/src/omnirush-agent-prompt.ts b/apps/server/src/omnirush-agent-prompt.tsindex 8cebce4f..e5be8c95 100644--- a/apps/server/src/omnirush-agent-prompt.ts+++ b/apps/server/src/omnirush-agent-prompt.ts@@ -37,9 +37,9 @@ Hard rule: never copy private memory into repo files. Store only redacted summar- If required setup or credentials are missing, ask one targeted question and continue once provided.- If you change code, run the smallest meaningful test.-- Write long files in chunks: create a file with its first section, then append the rest in a few smaller apply_patch calls instead of one very large patch. A single multi-thousand-token patch is the write most likely to be cut off in transit; if a write is interrupted, re-issue only the missing part.-- Use the task tool to delegate bounded, independent work to subagents when parallel exploration, implementation, or review will materially improve the result. Keep delegated activity visible in the session and synthesize it before answering.-- When the user explicitly asks to spawn, use, or delegate to a specific number of agents, make that many distinct task-tool calls. Use the general subagent unless a more specialized subagent is clearly better. Never replace an explicit delegation request with a simulated multi-role answer, and never claim subagents are unavailable while the task tool is present. Wait for every delegated task and then synthesize their actual results.+- Write long files in chunks: create a file with its first section, then append the rest in a few smaller edit (or patch) calls instead of one very large write. A single multi-thousand-token patch is the write most likely to be cut off in transit; if a write is interrupted, re-issue only the missing part.+- Use the subagent tool to delegate bounded, independent work to subagents when parallel exploration, implementation, or review will materially improve the result. Keep delegated activity visible in the session and synthesize it before answering.+- When the user explicitly asks to spawn, use, or delegate to a specific number of agents, make that many distinct subagent-tool calls. Use the general subagent unless a more specialized subagent is clearly better. Never replace an explicit delegation request with a simulated multi-role answer, and never claim subagents are unavailable while the subagent tool is present. Wait for every delegated task and then synthesize their actual results.- If steps repeat, capture them as a skill following the \`Skill creation:\` instruction in this prompt.- Prefer clear, practical steps over abstract explanations.@@ -47,7 +47,7 @@ ${OMNIRUSH_SWARM_PROMPT}## Editing files-- When apply_patch or edit reports that expected lines were not found, the file changed since you read it (a formatter ran, or an earlier edit was rejected or aborted). Read the file again before retrying; never resend the same patch. Prefer smaller hunks with unambiguous context. On Windows, keep the file's existing line endings.+- When patch or edit reports that expected lines were not found, the file changed since you read it (a formatter ran, or an earlier edit was rejected or aborted). Read the file again before retrying; never resend the same patch. Prefer smaller hunks with unambiguous context. On Windows, keep the file's existing line endings.## OmniRush.ai Artifacts@@ -61,7 +61,7 @@ OmniRush.ai can preview, edit, and download standard artifacts when you create o## Git workflows-- Use git and gh from the bash tool; run them from the repository (the tool's workdir) rather than with \`git -C\`, so approvals match the command family.+- Use git and gh from the shell tool; run them from the repository (the tool's workdir) rather than with \`git -C\`, so approvals match the command family.- Read-only commands (status, log, diff, branch --list, fetch origin, gh pr list/view/status) run without approval. Write commands (add, commit, checkout -b, switch, worktree add, push, gh pr create) ask once per session per command family. Destructive commands (push --force, reset --hard, clean -fd, branch -D, rebase -i, filter-branch, rm -rf) always ask; omnirush.ai marks them with OMNIRUSH_DESTRUCTIVE=1 in the approval prompt. Never add or remove that marker yourself.- Prefer worktrees for parallel branches: \`git worktree add ../<repo>-<branch> -b <branch>\`, and remove them when the work is merged.- Write conventional commit messages (feat:, fix:, docs:, refactor:, test:, chore:), one logical change per commit.diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.tsindex 987a628c..cc9b0a22 100644--- a/apps/server/src/omnirush-runtime-config.test.ts+++ b/apps/server/src/omnirush-runtime-config.test.ts@@ -324,7 +324,7 @@ describe("omnirush runtime config file", () => {expect(prompt).toContain("## OmniRush.ai Artifacts");expect(prompt).toContain("## Connected work");expect(prompt).toContain("delegate bounded, independent work to subagents");- expect(prompt).toContain("make that many distinct task-tool calls");+ expect(prompt).toContain("make that many distinct subagent-tool calls");expect(prompt).toContain("Never replace an explicit delegation request with a simulated multi-role answer");expect(prompt).toContain("Wait for every delegated task");// Den removed the Memory Bank; the prompt must not teach capabilities that@@ -374,7 +374,7 @@ describe("omnirush runtime config file", () => {const section = prompt.slice(prompt.indexOf("## Sub-agent swarms"), prompt.indexOf("## Editing files"));expect(section).toContain(`load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first`);expect(section).toContain("Before you start 3 or more sub-agents for one request");- expect(section).toContain("at most 1-2 sub-agents with the task tool and no board");+ expect(section).toContain("at most 1-2 sub-agents with the subagent tool and no board");// No board mechanics on every request: no file name, no table, no layers.expect(prompt).not.toContain("swarm.md");expect(prompt).not.toContain("## Tasks");diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.tsindex 07807624..7e02729d 100644--- a/apps/server/src/omnirush-swarm.ts+++ b/apps/server/src/omnirush-swarm.ts@@ -109,19 +109,19 @@ export const OMNIRUSH_SWARM_SKILL_DESCRIPTION = `Required before starting ${OMNI*/export const OMNIRUSH_SWARM_PROMPT = `## Sub-agent swarms-Before you start ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents for one request (large work that splits into ${OMNIRUSH_SWARM_MIN_AGENTS}+ independent parts, or the user asks for a swarm or for several agents), load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first and follow it. Otherwise answer directly, or use at most 1-2 sub-agents with the task tool and no board or coordination file.`;+Before you start ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents for one request (large work that splits into ${OMNIRUSH_SWARM_MIN_AGENTS}+ independent parts, or the user asks for a swarm or for several agents), load the \`${OMNIRUSH_SWARM_SKILL_NAME}\` skill first and follow it. Otherwise answer directly, or use at most 1-2 sub-agents with the subagent tool and no board or coordination file.`;/** The body of the omnirush-swarm skill (without frontmatter). */export const OMNIRUSH_SWARM_SKILL = `# Sub-agent swarm-Use this only for a real swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for several agents. For 1-2 sub-agents, stop here: call the task tool directly and do not create or touch a board.+Use this only for a real swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for several agents. For 1-2 sub-agents, stop here: call the subagent tool directly and do not create or touch a board.The board is \`${OMNIRUSH_SWARM_FILE}\` in the workspace, never a file in the project root. It is a short status board, not a report: every agent re-reads it, so keep it small. omnirush.ai keeps it out of git and clears it when your turn ends. Ignore any \`swarm.md\` in the project root: it is not this swarm's board.1. Before delegating, create \`${OMNIRUSH_SWARM_FILE}\` (replace it if one exists) with: \`# Goal\` (at most 3 sentences), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked; every cell one short line), \`## Findings\` (empty) and \`## Decisions\` (choices every agent must follow, one line each).-2. Give each sub-agent one task id. Its task-tool prompt names the id and the task, and says: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (it shows your row and the Decisions, and sets your status, one-line result and at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings); do not read or edit the board file; report back briefly.+2. Give each sub-agent one task id. Its subagent-tool prompt names the id and the task, and says: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (it shows your row and the Decisions, and sets your status, one-line result and at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings); do not read or edit the board file; report back briefly.3. Sub-agents may split their own task: they add sub-task rows (T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` and give the same instructions to their own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. There is no limit on how many run at once or start per turn: start as many as the work needs, and no more.-4. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.+4. Launch independent tasks in parallel (several subagent calls in one message); give tasks that edit the same files to one agent.5. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\` once, check the results against the task reports, and answer the user. Do not move, copy or archive the board: omnirush.ai does that when the turn ends. Board cells over ${OMNIRUSH_SWARM_CELL_MAX_CHARS} characters, lines over ${OMNIRUSH_SWARM_LINE_MAX_CHARS} and findings past ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} per task are cut.`;/** The omnirush-swarm skill's SKILL.md. */@@ -147,7 +147,7 @@ export function omnirushSwarmSubagentNote(depth: number): string {`You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}) in a swarm coordinated through the board \`${OMNIRUSH_SWARM_FILE}\`.`,`Do not read, search or edit the board file: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (from your prompt); it answers with your rows and the Decisions. Call it once when you start (status running) and once when you finish (status done, a one-line result, at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings other agents need). Put details in your final report, not on the board. Do not move or archive the board: omnirush.ai does that.`,canDelegate- ? `If your task splits into independent parts that each take real effort, you may delegate them with the task tool: add sub-task rows (for example T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` first and give each sub-agent the same instructions. Otherwise do the work yourself.`+ ? `If your task splits into independent parts that each take real effort, you may delegate them with the subagent tool: add sub-task rows (for example T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` first and give each sub-agent the same instructions. Otherwise do the work yourself.`: "You cannot delegate further: do the work yourself.",].join("\n");}diff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.tsindex a6871122..01ea2d81 100644--- a/apps/server/src/opencode-plugins/omnirush-engine2.ts+++ b/apps/server/src/opencode-plugins/omnirush-engine2.ts@@ -225,6 +225,33 @@ export default {// ---- custom tools ------------------------------------------------------const tools: Array<[string, V1Tool]> = plugins.flatMap((plugin) => (isRec(plugin.tool) ? Object.entries(plugin.tool as Record<string, V1Tool>) : []));+ // The 2.x engine has no todo list tool; the app's todo panel reads the 1.x one (`todowrite`).+ const todoItem = z.object({+ content: z.string().describe("Brief description of the task"),+ status: z.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),+ priority: z.string().describe("Priority level of the task: high, medium, low"),+ id: z.string().optional().describe("Unique identifier for the todo item"),+ });+ const todoArgs = { todos: z.array(todoItem).describe("The updated todo list") };+ tools.push(["todowrite", {+ description: "Use this tool to create and manage a structured task list for your current session. It helps you track progress on complex, multi-step work and shows the user what you are doing. Send the whole updated list every time; mark exactly one task in_progress while you work on it and mark tasks completed as soon as they are done.",+ args: todoArgs,+ async execute(raw: unknown, context: { sessionID?: string }) {+ const todos = z.object(todoArgs).parse(raw).todos;+ const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim();+ if (baseUrl && context?.sessionID) {+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();+ await fetch(`${baseUrl}/omnirush/todos`, {+ method: "POST",+ headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) },+ body: JSON.stringify({ sessionID: context.sessionID, todos }),+ signal: AbortSignal.timeout(5_000),+ }).catch(() => undefined);+ }+ return { title: `${todos.filter((todo) => todo.status !== "completed").length} todos`, output: JSON.stringify(todos, null, 2), metadata: { todos } };+ },+ }]);+if (tools.length > 0) {await ctx.tool.transform((editor: any) => {for (const [name, definition] of tools) {@@ -266,6 +293,11 @@ export default {}// ---- tool calls --------------------------------------------------------+ // Sub-agents run in the foreground, as the 1.x task tool did (the swarm counts running+ // sub-agents and the task result carries the sub-agent's answer).+ await ctx.tool.hook("execute.before", async (event: any) => {+ if (event.tool === "subagent" && isRec(event.input) && event.input.background === true) event.input = { ...event.input, background: false };+ });const before = hooks("tool.execute.before");if (before.length) {await ctx.tool.hook("execute.before", async (event: any) => {@@ -281,11 +313,10 @@ export default {if (event.status !== "completed" || !isRec(event.result)) return;const tool = v1ToolName(String(event.tool));const original = resultText(event.result.content ?? event.result.output);- const output: { title: string; output: string; metadata: Rec } = {- title: "",- output: original,- metadata: isRec(event.result.metadata) ? { ...event.result.metadata } : {},- };+ const metadata: Rec = isRec(event.result.metadata) ? { ...event.result.metadata } : {};+ // The 1.x task tool named its child session `sessionId`.+ if (event.tool === "subagent" && typeof metadata.sessionID === "string" && metadata.sessionId === undefined) metadata.sessionId = metadata.sessionID;+ const output: { title: string; output: string; metadata: Rec } = { title: "", output: original, metadata };for (const hook of after) await hook({ tool, sessionID: event.sessionID, callID: event.id, args: v1ToolInput(String(event.tool), event.input) }, output);const files = Array.isArray(event.result.content) ? event.result.content.filter((item: unknown) => isRec(item) && item.type === "file") : [];event.result = {@@ -354,7 +385,17 @@ export default {await ctx.session.hook("prompt", async (event: any) => {const sessionID = String(event.sessionID ?? "");const info = await adapterJson(`/session/${encodeURIComponent(sessionID)}`, directory);- const current = isRec(info) && isRec(info.model) ? { providerID: String(info.model.providerID), modelID: String(info.model.id), variant: typeof info.model.variant === "string" && info.model.variant !== "default" ? info.model.variant : undefined } : undefined;+ // A new sub-agent session has no step yet: it runs on the model of the session above it.+ let current: { providerID: string; modelID: string; variant?: string } | undefined;+ let cursor: unknown = info;+ for (let hop = 0; hop < 5 && isRec(cursor); hop++) {+ if (isRec(cursor.model) && typeof cursor.model.id === "string") {+ current = { providerID: String(cursor.model.providerID), modelID: String(cursor.model.id), variant: typeof cursor.model.variant === "string" && cursor.model.variant !== "default" ? cursor.model.variant : undefined };+ break;+ }+ if (typeof cursor.parentID !== "string") break;+ cursor = await adapterJson(`/session/${encodeURIComponent(cursor.parentID)}`, directory);+ }const message: Rec = { id: event.messageID, sessionID, role: "user", model: current ? { ...current } : undefined };const agent = isRec(info) && typeof info.agent === "string" ? info.agent : undefined;for (const hook of messageCreated) {