Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: automations run on the new engine

ogsamrata6eabc7bb3f5
diff --git a/apps/server/src/headless-threads.e2e.test.ts b/apps/server/src/headless-threads.e2e.test.ts
index 045fd5c0..3e961bdb 100644
--- a/apps/server/src/headless-threads.e2e.test.ts
+++ b/apps/server/src/headless-threads.e2e.test.ts
@@ -1,282 +1,87 @@
-import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
+import { afterAll, beforeAll, expect, test } from "bun:test";
+import { existsSync } from "node:fs";
import { mkdtemp, mkdir, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import { createHeadlessThreadClient } from "@omnirush/headless-threads";
-import { startServer } from "./server.js";
-import type { ServerConfig } from "./types.js";
-
-import { afterAll as afterAllUnlocked, beforeAll as beforeAllUnlocked } from "bun:test";
-import { applyProviderLockAnswer, resetProviderLock } from "./provider-lock.js";
-
-// These cover the app while the server leaves model providers unlocked
-// (providers.locked false); provider-lock.test.ts covers the lock.
-beforeAllUnlocked(() => { applyProviderLockAnswer({ providers: { locked: false } }); });
-afterAllUnlocked(() => resetProviderLock());
-
-// These tests dispatch prompts through a local workspace without an omnirush.ai
-// account. The server's sign-in gate refuses that unless both development
-// flags are set; the gate itself is covered by session-uploader.server.e2e.test.ts.
-const uploadGateEnv = { OMNIRUSH_DEV_MODE: process.env.OMNIRUSH_DEV_MODE, OMNIRUSH_SESSION_UPLOAD_OPTIONAL: process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL };
-beforeAll(() => {
- process.env.OMNIRUSH_DEV_MODE = "1";
- process.env.OMNIRUSH_SESSION_UPLOAD_OPTIONAL = "1";
-});
-afterAll(() => {
- for (const [name, value] of Object.entries(uploadGateEnv)) {
- if (value === undefined) delete process.env[name];
- else process.env[name] = value;
- }
-});
-
-
-type Served = {
- port: number;
- stop: (closeActiveConnections?: boolean) => void | Promise<void>;
-};
-
-const SESSION_ID = "ses_headless";
-const FIRST_ANSWER = "The refund window closed after 30 days.";
-const SECOND_ANSWER = "Without a receipt, use the order lookup.";
-
-const stops: Array<() => void | Promise<void>> = [];
-const roots: string[] = [];
-
-afterEach(async () => {
- while (stops.length) await stops.pop()?.();
- while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
-});
-
-function message(id: string, role: string, text: string) {
- return {
- info: { id, sessionID: SESSION_ID, role, time: { created: 100 } },
- parts: [{ id: `prt_${id}`, messageID: id, sessionID: SESSION_ID, type: "text", text }],
- };
-}
-
-const USER_1 = message("msg_1", "user", "A customer wants a refund after 40 days.");
-const ASSISTANT_1 = message("msg_2", "assistant", FIRST_ANSWER);
-const USER_2 = message("msg_3", "user", "They also lost the receipt.");
-const ASSISTANT_2 = message("msg_4", "assistant", SECOND_ANSWER);
-
-/**
- * What the engine looks like at each step of two turns. Beat 0 and beat 3 are
- * the moments that matter: the thread has accepted a prompt but has not
- * started, so it reads idle with no new reply. A client that settles there
- * reports a turn finished before it began.
- */
-const BEATS = [
- { busy: false, messages: [USER_1] },
- { busy: true, messages: [USER_1] },
- { busy: false, messages: [USER_1, ASSISTANT_1] },
- { busy: false, messages: [USER_1, ASSISTANT_1, USER_2] },
- { busy: true, messages: [USER_1, ASSISTANT_1, USER_2] },
- { busy: false, messages: [USER_1, ASSISTANT_1, USER_2, ASSISTANT_2] },
-];
-
-async function createWorkspaceRoot() {
- const root = await mkdtemp(join(tmpdir(), "omnirush-headless-threads-"));
- await mkdir(join(root, ".opencode"), { recursive: true });
- roots.push(root);
- return root;
-}
-
-/**
- * A managed-OpenCode stand-in. It only moves to the next beat when `advance()`
- * is called, which the test wires to the client's sleep — so the whole journey
- * is deterministic and needs no wall-clock waiting.
- */
-function startMockOpencode() {
- const prompts: Array<Record<string, unknown>> = [];
- let aborted = 0;
- let beat = 0;
-
- const server = Bun.serve({
- hostname: "127.0.0.1",
+import { createManagedOpencodeV2Server, type ManagedOpencodeV2Server } from "./managed-opencode-v2.js";
+
+// The headless client (automations) against the real bundled 2.x engine, through a stand-in for the
+// server's `/workspace/:id/opencode2` mount (the mount itself: opencode-proxy and session-uploader tests).
+const triple = process.arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu";
+const engineBin = process.env.OMNIRUSH_OPENCODE2_BIN?.trim()
+ || join(resolve(import.meta.dir, "../../.."), `apps/desktop/resources/sidecars/opencode2-${triple}`);
+const realEngine = process.platform === "linux" && existsSync(engineBin) ? test : test.skip;
+
+let root = "";
+let engine: ManagedOpencodeV2Server | undefined;
+let model: ReturnType<typeof Bun.serve> | undefined;
+let mount: ReturnType<typeof Bun.serve> | undefined;
+
+beforeAll(async () => {
+ if (!existsSync(engineBin) || process.platform !== "linux") return;
+ root = await mkdtemp(join(tmpdir(), "headless-v2-"));
+ await mkdir(join(root, "project"), { recursive: true });
+ // A model that answers every request with "ok" (chat completions, streamed).
+ model = Bun.serve({
port: 0,
- async fetch(request) {
- const url = new URL(request.url);
- const current = BEATS[Math.min(beat, BEATS.length - 1)];
- const session = {
- id: SESSION_ID,
- title: "Refund policy",
- slug: "refund-policy",
- directory: request.headers.get("x-opencode-directory"),
- time: { created: 100, updated: 100 },
- };
-
- if (url.pathname === "/session" && request.method === "POST") return Response.json(session);
- if (url.pathname === "/session" && request.method === "GET") return Response.json([session]);
- if (url.pathname === `/session/${SESSION_ID}`) return Response.json(session);
- if (url.pathname === `/session/${SESSION_ID}/message`) return Response.json(current.messages);
- if (url.pathname === `/session/${SESSION_ID}/todo`) return Response.json([]);
- if (url.pathname === "/session/status") {
- return Response.json(current.busy ? { [SESSION_ID]: { type: "busy" } } : {});
- }
- if (url.pathname === `/session/${SESSION_ID}/prompt_async` && request.method === "POST") {
- prompts.push(await request.json());
- return new Response(null, { status: 204 });
- }
- if (url.pathname === `/session/${SESSION_ID}/abort` && request.method === "POST") {
- aborted += 1;
- return Response.json(true);
- }
- return Response.json({ code: "not_found", message: `Not found: ${request.method} ${url.pathname}` }, { status: 404 });
- },
- }) as Served;
- stops.push(() => server.stop(true));
-
- return {
- server,
- prompts,
- advance: () => {
- beat += 1;
+ hostname: "127.0.0.1",
+ fetch: () => {
+ const chunk = (delta: unknown, finish: string | null) => `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", choices: [{ index: 0, delta, finish_reason: finish }], ...(finish ? { usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } } : {}) })}\n\n`;
+ return new Response(`${chunk({ role: "assistant", content: "ok" }, null)}${chunk({}, "stop")}data: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } });
},
- abortCount: () => aborted,
- };
-}
-
-async function startOmniRushServer(input: { workspaceRoot: string; opencodeBaseUrl: string }) {
- const config: ServerConfig = {
- host: "127.0.0.1",
- port: 0,
- token: "owt_test_token",
- hostToken: "owt_host_token",
- approval: { mode: "auto", timeoutMs: 1000 },
- corsOrigins: ["*"],
- workspaces: [
- {
- id: "ws_1",
- name: "Workspace",
- path: input.workspaceRoot,
- preset: "starter",
- workspaceType: "local",
- baseUrl: input.opencodeBaseUrl,
- },
- ],
- authorizedRoots: [input.workspaceRoot],
- readOnly: false,
- startedAt: Date.now(),
- tokenSource: "cli",
- hostTokenSource: "cli",
- logFormat: "pretty",
- logRequests: false,
- };
- const server = await startServer(config) as Served;
- stops.push(() => server.stop(true));
- return { server, token: config.token };
-}
-
-test("drives two headless turns on a native OmniRush.ai thread", async () => {
- const workspaceRoot = await createWorkspaceRoot();
- const engine = startMockOpencode();
- const omnirush = await startOmniRushServer({
- workspaceRoot,
- opencodeBaseUrl: `http://127.0.0.1:${engine.server.port}`,
});
-
- let clock = 0;
- const threads = createHeadlessThreadClient({
- baseUrl: `http://127.0.0.1:${omnirush.server.port}`,
- workspaceId: "ws_1",
- token: omnirush.token,
- defaultModel: { providerId: "anthropic", modelId: "claude-sonnet-5" },
- now: () => clock,
- // Each poll gap moves the engine exactly one beat, so the journey below is
- // reproducible and never waits on real time.
- sleep: async (ms) => {
- clock += ms;
- engine.advance();
+ engine = await createManagedOpencodeV2Server({ bin: engineBin, rootDir: join(root, "engine"), bootTimeoutMs: 90_000, env: { HOME: join(root, "home") } });
+ await engine.setProviders([{ id: "omnirush", name: "OmniRush", baseUrl: `http://127.0.0.1:${model.port}/v1`, package: "@opencode-ai/ai/providers/openai-compatible", apiKey: "x", models: [{ id: "test-model", name: "test-model", config: { tool_call: true } }] }]);
+ for (let i = 0; i < 120 && !JSON.stringify((await engine.fetchJson("/api/model", { directory: join(root, "project") })).json).includes("test-model"); i += 1) await Bun.sleep(250);
+ const active = engine;
+ mount = Bun.serve({
+ port: 0,
+ hostname: "127.0.0.1",
+ fetch: async (request) => {
+ const url = new URL(request.url);
+ const target = new URL(active.url);
+ target.pathname = url.pathname.replace(/^\/workspace\/ws_1\/opencode2/, "");
+ target.search = url.search;
+ target.searchParams.set("location[directory]", join(root, "project"));
+ const body = request.method === "GET" ? undefined : await request.text();
+ const forwarded = url.pathname.endsWith("/api/session") && request.method === "POST"
+ ? JSON.stringify({ ...JSON.parse(body || "{}"), location: { directory: join(root, "project") } })
+ : body;
+ const answer = await fetch(target, { method: request.method, headers: { authorization: `Basic ${Buffer.from(`opencode:${active.password}`).toString("base64")}`, "content-type": "application/json" }, body: forwarded });
+ return new Response(await answer.arrayBuffer(), { status: answer.status, headers: { "content-type": answer.headers.get("content-type") ?? "application/json" } });
},
});
+}, 120_000);
- const thread = await threads.createThread({
- title: "Refund policy",
- prompt: "A customer wants a refund after 40 days.",
- });
-
- expect(thread.id).toBe(SESSION_ID);
- expect(thread.started).toBe(true);
- expect(thread.directory).toBe(workspaceRoot);
- expect(engine.prompts).toHaveLength(1);
- expect(engine.prompts[0]).toEqual({
- parts: [{ type: "text", text: "A customer wants a refund after 40 days." }],
- model: { providerID: "anthropic", modelID: "claude-sonnet-5" },
- });
-
- const firstWait = await threads.waitForThread(thread.id, { timeoutMs: 60_000, pollIntervalMs: 10 });
-
- expect(firstWait.outcome).toBe("settled");
- expect(firstWait.observedRunning).toBe(true);
- // Beat 0 was idle with no reply yet: settling there would have been wrong.
- expect(firstWait.polls).toBe(3);
-
- const firstTranscript = await threads.exportTranscript(thread.id);
- expect(firstTranscript.finalAssistantText).toBe(FIRST_ANSWER);
- expect(firstTranscript.messages.map((entry) => entry.role)).toEqual(["user", "assistant"]);
-
- const followUp = await threads.sendTurn(thread.id, { prompt: "They also lost the receipt." });
-
- expect(followUp.messageCountBefore).toBe(2);
- expect(engine.prompts).toHaveLength(2);
- expect(engine.prompts[1]).toEqual({
- parts: [{ type: "text", text: "They also lost the receipt." }],
- model: { providerID: "anthropic", modelID: "claude-sonnet-5" },
- });
-
- const secondWait = await threads.waitForThread(thread.id, {
- timeoutMs: 60_000,
- pollIntervalMs: 10,
- since: followUp,
- });
-
- expect(secondWait.outcome).toBe("settled");
- expect(secondWait.observedRunning).toBe(true);
- // The first answer was already in the thread; only the new one settles it.
- expect(secondWait.polls).toBe(4);
-
- const transcript = await threads.exportTranscript(thread.id);
- expect(transcript.finalAssistantText).toBe(SECOND_ANSWER);
- expect(transcript.messages.map((entry) => entry.text)).toEqual([
- "A customer wants a refund after 40 days.",
- FIRST_ANSWER,
- "They also lost the receipt.",
- SECOND_ANSWER,
- ]);
-
- await expect(threads.abortThread(thread.id)).resolves.toEqual({ threadId: thread.id, accepted: true });
- expect(engine.abortCount()).toBe(1);
+afterAll(async () => {
+ await mount?.stop(true);
+ await engine?.close();
+ await model?.stop(true);
+ if (root) await rm(root, { recursive: true, force: true });
});
-test("leaves the thread readable through the session surface the app uses", async () => {
- const workspaceRoot = await createWorkspaceRoot();
- const engine = startMockOpencode();
- const omnirush = await startOmniRushServer({
- workspaceRoot,
- opencodeBaseUrl: `http://127.0.0.1:${engine.server.port}`,
- });
- const base = `http://127.0.0.1:${omnirush.server.port}`;
-
- const thread = await createHeadlessThreadClient({
- baseUrl: base,
+realEngine("drives two headless turns on a native 2.x thread", async () => {
+ const client = createHeadlessThreadClient({
+ baseUrl: `http://127.0.0.1:${mount!.port}`,
workspaceId: "ws_1",
- token: omnirush.token,
- }).createThread({ title: "Refund policy" });
-
- // The app lists and opens sessions through the native workspace mount. A headless thread
- // is an ordinary session, so it has to be visible here with the same id.
- const listed = await fetch(`${base}/workspace/ws_1/opencode/session`, {
- headers: { Authorization: `Bearer ${omnirush.token}` },
- });
- expect(listed.status).toBe(200);
- const listedBody = await listed.json();
- expect(listedBody.map((item: { id: string }) => item.id)).toContain(thread.id);
-
- const opened = await fetch(`${base}/workspace/ws_1/opencode/session/${thread.id}`, {
- headers: { Authorization: `Bearer ${omnirush.token}` },
+ token: "owt_test",
+ defaultModel: { providerId: "omnirush", modelId: "test-model" },
});
- expect(opened.status).toBe(200);
- await expect(opened.json()).resolves.toMatchObject({ id: thread.id, title: "Refund policy" });
-});
+ const thread = await client.createThread({ title: "Headless", prompt: "Say ok." });
+ expect(thread.started).toBe(true);
+ const first = await client.waitForThread(thread.id, { timeoutMs: 60_000, since: { messageCountBefore: 0, messageId: null } });
+ expect(first.outcome).toBe("settled");
+
+ const accepted = await client.sendTurn(thread.id, { prompt: "Again.", messageId: "msg_headless_2" });
+ const second = await client.waitForThread(thread.id, { timeoutMs: 60_000, since: accepted });
+ expect(second.outcome).toBe("settled");
+ // Sending the same message id again is not a second turn.
+ expect((await client.sendTurn(thread.id, { prompt: "Again.", messageId: "msg_headless_2" })).alreadyPresent).toBe(true);
+
+ const transcript = await client.exportTranscript(thread.id);
+ expect(JSON.stringify(transcript)).toContain("ok");
+ expect((await client.abortThread(thread.id)).threadId).toBe(thread.id);
+}, 180_000);
diff --git a/packages/headless-threads/package.json b/packages/headless-threads/package.json
index c6dcb63b..a871498c 100644
--- a/packages/headless-threads/package.json
+++ b/packages/headless-threads/package.json
@@ -22,7 +22,6 @@
"test": "bun test src"
},
"dependencies": {
- "@opencode-ai/sdk": "^1.18.15",
"zod": "^4.3.6"
},
"devDependencies": {
diff --git a/packages/headless-threads/src/client.test.ts b/packages/headless-threads/src/client.test.ts
index 7e5c247b..b56265c2 100644
--- a/packages/headless-threads/src/client.test.ts
+++ b/packages/headless-threads/src/client.test.ts
@@ -61,6 +61,23 @@ function createOmniRushDouble(input?: { beats?: Beat[]; messages?: MessageWire[]
const session = { id: SESSION_ID, title: "Refund policy", directory: "/workspace", time: { created: 1 } };
+ // The 2.x engine's shapes (wire.ts reads them back): newest first, `data`-wrapped.
+ const v2Message = (message: MessageWire) => {
+ const parts = message.parts as Array<{ type?: string; text?: string; tool?: string; callID?: string; state?: unknown }>;
+ if (message.info.role === "user") {
+ return { id: message.info.id, type: "user", time: message.info.time, text: parts.filter((part) => part.type === "text").map((part) => part.text ?? "").join("") };
+ }
+ return {
+ id: message.info.id, type: "assistant", time: message.info.time,
+ ...(message.info.error !== undefined ? { error: message.info.error } : {}),
+ ...(message.info.tokens !== undefined ? { tokens: message.info.tokens } : {}),
+ ...(message.info.cost !== undefined ? { cost: message.info.cost } : {}),
+ content: parts.map((part) => part.type === "tool" ? { type: "tool", id: part.callID, name: part.tool, state: part.state ?? {} } : { type: part.type, text: part.text }),
+ };
+ };
+ const v2Session = { id: SESSION_ID, title: session.title, location: { directory: session.directory }, time: session.time };
+ const root = "/workspace/ws_1/opencode2/api/session";
+
const fetchImpl: HeadlessFetch = async (url, init) => {
const parsed = new URL(url);
const method = init?.method ?? "GET";
@@ -74,29 +91,26 @@ function createOmniRushDouble(input?: { beats?: Beat[]; messages?: MessageWire[]
signal: init?.signal,
});
- if (method === "POST" && parsed.pathname === "/workspace/ws_1/opencode/session") {
- return Response.json(session);
+ if (method === "POST" && parsed.pathname === root) {
+ return Response.json({ data: v2Session });
}
- if (method === "GET" && parsed.pathname === `/workspace/ws_1/opencode/session/${SESSION_ID}`) {
+ if (method === "GET" && parsed.pathname === `${root}/${SESSION_ID}`) {
activeBeat = beats[Math.min(beatIndex, beats.length - 1)];
beatIndex += 1;
- return Response.json(session);
- }
- if (method === "GET" && parsed.pathname === `/workspace/ws_1/opencode/session/${SESSION_ID}/message`) {
- return Response.json(activeBeat?.messages ?? messages);
+ return Response.json({ data: v2Session });
}
- if (method === "GET" && parsed.pathname === `/workspace/ws_1/opencode/session/${SESSION_ID}/todo`) {
- return Response.json([]);
+ if (method === "GET" && parsed.pathname === `${root}/${SESSION_ID}/message`) {
+ return Response.json({ data: (activeBeat?.messages ?? messages).map(v2Message).reverse(), cursor: {} });
}
- if (method === "GET" && parsed.pathname === "/workspace/ws_1/opencode/session/status") {
+ if (method === "GET" && parsed.pathname === `${root}/active`) {
const status = activeBeat?.status;
- return Response.json(status === undefined || status.type === "idle" ? {} : { [SESSION_ID]: status });
+ return Response.json({ data: status === undefined || status.type === "idle" ? {} : { [SESSION_ID]: { type: "running" } } });
}
- if (method === "POST" && parsed.pathname === `/workspace/ws_1/opencode/session/${SESSION_ID}/prompt_async`) {
- return new Response(null, { status: 204 });
+ if (method === "POST" && (parsed.pathname === `${root}/${SESSION_ID}/prompt` || parsed.pathname === `${root}/${SESSION_ID}/model`)) {
+ return Response.json({ data: {} });
}
- if (method === "POST" && parsed.pathname === `/workspace/ws_1/opencode/session/${SESSION_ID}/abort`) {
- return Response.json(input?.abortResult ?? true);
+ if (method === "POST" && parsed.pathname === `${root}/${SESSION_ID}/interrupt`) {
+ return Response.json({ data: { interrupted: input?.abortResult ?? true } });
}
return Response.json({ code: "not_found", message: "Not found" }, { status: 404 });
};
@@ -137,15 +151,12 @@ describe("createThread", () => {
});
expect(double.requests.map(({ method, path }) => ({ method, path }))).toEqual([
- { method: "POST", path: "/workspace/ws_1/opencode/session" },
- { method: "POST", path: "/workspace/ws_1/opencode/session/ses_1/prompt_async" },
+ { method: "POST", path: "/workspace/ws_1/opencode2/api/session" },
+ { method: "POST", path: "/workspace/ws_1/opencode2/api/session/ses_1/prompt" },
]);
- expect(double.requests[0]?.body).toEqual({ title: "Refund policy" });
- expect(double.requests[1]?.body).toEqual({
- parts: [{ type: "text", text: "A customer wants a refund after 40 days." }],
- model: { providerID: "anthropic", modelID: "claude-sonnet-5" },
- variant: "thinking",
- });
+ // The 2.x engine takes the model with the new session, the prompt as text.
+ expect(double.requests[0]?.body).toEqual({ title: "Refund policy", model: { id: "claude-sonnet-5", providerID: "anthropic", variant: "thinking" } });
+ expect(double.requests[1]?.body).toEqual({ text: "A customer wants a refund after 40 days." });
expect(thread).toEqual({
id: SESSION_ID,
workspaceId: "ws_1",
@@ -167,7 +178,7 @@ describe("createThread", () => {
await client.createThread({ title: "Refund policy" });
- expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode/session");
+ expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode2/api/session");
});
test("authenticates server-to-server Cloud requests with both worker tokens", async () => {
@@ -220,7 +231,7 @@ describe("createThread", () => {
await client.createThread({ title: " Refund policy ", prompt: " Review it " });
expect(double.requests[0]?.body).toEqual({ title: "Refund policy" });
- expect(double.requests[1]?.body).toEqual({ parts: [{ type: "text", text: "Review it" }] });
+ expect(double.requests[1]?.body).toEqual({ text: "Review it" });
await expect(client.createThread({ title: " " })).rejects.toMatchObject({
code: "invalid_payload",
@@ -257,13 +268,12 @@ describe("sendTurn", () => {
alreadyPresent: false,
});
expect(double.requests.map((request) => request.path)).toEqual([
- "/workspace/ws_1/opencode/session/ses_1/message",
- "/workspace/ws_1/opencode/session/ses_1/prompt_async",
+ "/workspace/ws_1/opencode2/api/session/ses_1/message?limit=200&order=desc",
+ "/workspace/ws_1/opencode2/api/session/ses_1/model",
+ "/workspace/ws_1/opencode2/api/session/ses_1/prompt",
]);
- expect(double.requests[1]?.body).toEqual({
- parts: [{ type: "text", text: "They also lost the receipt." }],
- model: { providerID: "anthropic", modelID: "claude-sonnet-5" },
- });
+ expect(double.requests[1]?.body).toEqual({ model: { id: "claude-sonnet-5", providerID: "anthropic" } });
+ expect(double.requests[2]?.body).toEqual({ text: "They also lost the receipt." });
});
test("falls back to the client's default model", async () => {
@@ -278,10 +288,8 @@ describe("sendTurn", () => {
await client.sendTurn(SESSION_ID, { prompt: "hello" });
- expect(double.requests[1]?.body).toEqual({
- parts: [{ type: "text", text: "hello" }],
- model: { providerID: "openai", modelID: "gpt-5" },
- });
+ expect(double.requests[1]?.body).toEqual({ model: { id: "gpt-5", providerID: "openai" } });
+ expect(double.requests[2]?.body).toEqual({ text: "hello" });
});
test("uses a stable message id and does not submit it twice", async () => {
@@ -295,7 +303,7 @@ describe("sendTurn", () => {
expect(acceptance.alreadyPresent).toBe(true);
expect(acceptance.messageId).toBe("msg_run_1");
expect(double.requests).toHaveLength(1);
- expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode/session/ses_1/message");
+ expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode2/api/session/ses_1/message?limit=200&order=desc");
});
test("passes a new stable message id to OpenCode", async () => {
@@ -303,10 +311,7 @@ describe("sendTurn", () => {
await createClient(double).sendTurn(SESSION_ID, { prompt: "Run it.", messageId: "msg_run_2" });
- expect(double.requests[1]?.body).toEqual({
- parts: [{ type: "text", text: "Run it." }],
- messageID: "msg_run_2",
- });
+ expect(double.requests[1]?.body).toEqual({ text: "Run it.", id: "msg_run_2" });
});
test("URL-encodes workspace and session IDs on native proxy calls", async () => {
@@ -327,14 +332,14 @@ describe("sendTurn", () => {
await client.sendTurn("ses /?", { prompt: "hello" });
expect(paths).toEqual([
- "/workspace/ws%20%2F%3F/opencode/session/ses%20%2F%3F/message",
- "/workspace/ws%20%2F%3F/opencode/session/ses%20%2F%3F/prompt_async",
+ "/workspace/ws%20%2F%3F/opencode2/api/session/ses%20%2F%3F/message",
+ "/workspace/ws%20%2F%3F/opencode2/api/session/ses%20%2F%3F/prompt",
]);
});
});
describe("getThreadSnapshot", () => {
- test("reads session, messages, todos, and status in parallel", async () => {
+ test("reads session, messages and status in parallel (the 2.x engine has no todos)", async () => {
const requests: string[] = [];
let markStarted: () => void = () => {};
let releaseRequests: () => void = () => {};
@@ -347,29 +352,27 @@ describe("getThreadSnapshot", () => {
const fetchImpl: HeadlessFetch = async (url) => {
const path = new URL(url).pathname;
requests.push(path);
- if (requests.length === 4) markStarted();
+ if (requests.length === 3) markStarted();
await released;
- if (path.endsWith("/message")) return Response.json([]);
- if (path.endsWith("/todo")) return Response.json([{ content: "Check", status: "pending", priority: "high" }]);
- if (path.endsWith("/status")) return Response.json({ [SESSION_ID]: { type: "busy" } });
- return Response.json({ id: SESSION_ID, title: "Refund policy", directory: "/workspace", time: { created: 1 } });
+ if (path.endsWith("/message")) return Response.json({ data: [] });
+ if (path.endsWith("/active")) return Response.json({ data: { [SESSION_ID]: {} } });
+ return Response.json({ data: { id: SESSION_ID, title: "Refund policy", location: { directory: "/workspace" }, time: { created: 1 } } });
};
const client = createHeadlessThreadClient({ baseUrl: BASE_URL, workspaceId: "ws_1", token: "owt_test", fetch: fetchImpl });
const pending = client.getThreadSnapshot(SESSION_ID);
await allStarted;
expect(requests).toEqual([
- "/workspace/ws_1/opencode/session/ses_1",
- "/workspace/ws_1/opencode/session/ses_1/message",
- "/workspace/ws_1/opencode/session/ses_1/todo",
- "/workspace/ws_1/opencode/session/status",
+ "/workspace/ws_1/opencode2/api/session/ses_1",
+ "/workspace/ws_1/opencode2/api/session/ses_1/message",
+ "/workspace/ws_1/opencode2/api/session/active",
]);
releaseRequests();
await expect(pending).resolves.toMatchObject({
threadId: SESSION_ID,
status: { type: "busy" },
- todos: [{ content: "Check", status: "pending", priority: "high" }],
+ todos: [],
});
});
@@ -491,7 +494,7 @@ describe("waitForThread", () => {
expect(result.polls).toBe(1);
expect(double.snapshotReads()).toBe(2);
// Cancelling a wait must never cancel the engine turn on the caller's behalf.
- expect(double.requests.some((request) => request.path.endsWith("/abort"))).toBe(false);
+ expect(double.requests.some((request) => request.path.endsWith("/interrupt"))).toBe(false);
});
test("matches the assistant response to the stable user message", async () => {
@@ -499,7 +502,9 @@ describe("waitForThread", () => {
beats: [{
status: { type: "idle" },
messages: [
+ reply("msg_old", "user", "before"),
reply("msg_old_answer", "assistant", "old", "msg_old"),
+ reply("msg_run_1", "user", "run"),
reply("msg_new_answer", "assistant", "new", "msg_run_1"),
],
}],
@@ -516,7 +521,7 @@ describe("waitForThread", () => {
test("reports a terminal assistant error", async () => {
const failed = reply("msg_failed", "assistant", undefined, "msg_run_1");
failed.info.error = { name: "ProviderAuthError", data: { message: "Reconnect the provider." } };
- const double = createOmniRushDouble({ beats: [{ status: { type: "idle" }, messages: [failed] }] });
+ const double = createOmniRushDouble({ beats: [{ status: { type: "idle" }, messages: [reply("msg_run_1", "user", "run"), failed] }] });
const result = await createClient(double).waitForThread(SESSION_ID, {
timeoutMs: 1_000,
@@ -540,7 +545,7 @@ describe("failures", () => {
expect(error.code).toBe("not_found");
expect(error.status).toBe(404);
expect(error.method).toBe("GET");
- expect(error.path).toBe("/workspace/ws_1/opencode/session/ses_missing");
+ expect(error.path).toBe("/workspace/ws_1/opencode2/api/session/ses_missing");
expect(error.message).toBe("Not found");
expect(error.body).toEqual({ code: "not_found", message: "Not found" });
});
@@ -579,7 +584,7 @@ describe("failures", () => {
if (!(error instanceof HeadlessThreadError)) throw new Error("expected a HeadlessThreadError");
expect(error.code).toBe("request_failed");
expect(error.method).toBe("GET");
- expect(error.path).toBe("/workspace/ws_1/opencode/session/ses_1");
+ expect(error.path).toBe("/workspace/ws_1/opencode2/api/session/ses_1");
expect(error.status).toBeNull();
});
@@ -627,7 +632,7 @@ describe("failures", () => {
try {
await client.createThread({ title: "No timeout" });
expect(requested).toEqual([]);
- expect(double.requests[0]?.signal?.aborted).toBe(false);
+ expect(double.requests[0]?.signal?.aborted ?? false).toBe(false);
} finally {
Object.defineProperty(AbortSignal, "timeout", timeoutDescriptor);
}
@@ -715,7 +720,7 @@ describe("abortThread", () => {
threadId: SESSION_ID,
accepted: false,
});
- expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode/session/ses_1/abort");
+ expect(double.requests[0]?.path).toBe("/workspace/ws_1/opencode2/api/session/ses_1/interrupt");
});
test("waits until the aborted thread is observably idle", async () => {
diff --git a/packages/headless-threads/src/client.ts b/packages/headless-threads/src/client.ts
index 7553627f..17449598 100644
--- a/packages/headless-threads/src/client.ts
+++ b/packages/headless-threads/src/client.ts
@@ -1,13 +1,15 @@
/**
* A function-driven client for native OmniRush.ai threads.
*
- * Every call uses the OpenCode SDK through OmniRush.ai's workspace-scoped mount:
+ * Every call goes to the 2.x engine's API through OmniRush.ai's workspace-scoped mount:
*
- * - `POST /workspace/:id/opencode/session` creates a thread
- * - native session reads provide messages, todos, and status
- * - native prompt and abort calls control a turn
+ * - `POST /workspace/:id/opencode2/api/session` creates a thread
+ * - native session reads provide messages and status (the 2.x engine has no todos)
+ * - native prompt and interrupt calls control a turn
+ *
+ * The engine's 2.x messages are read in the wire shape below (`{info, parts}`, wire.ts); tool names
+ * stay the engine's own.
*/
-import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
import { z } from "zod";
import { HeadlessThreadError } from "./errors.js";
@@ -25,14 +27,13 @@ import type {
HeadlessThreadWaitResult,
HeadlessTurnAcceptance,
} from "./types.js";
+import { nextCursorOf, v2MessagesToWire, v2SessionToWire } from "./v2.js";
import {
abortResultSchema,
isRunning,
sessionSchema,
threadMessagesSchema,
threadSnapshotSchema,
- threadStatusesSchema,
- threadTodosSchema,
toSnapshot,
toThread,
} from "./wire.js";
@@ -44,6 +45,11 @@ const errorBodySchema = z
.object({ code: z.string().optional(), message: z.string().optional() })
.passthrough();
+function settled<T>(result: PromiseSettledResult<T>): T {
+ if (result.status === "rejected") throw result.reason;
+ return result.value;
+}
+
function defaultSleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -67,7 +73,7 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const workspacePath = `/workspace/${encodeURIComponent(workspaceId)}`;
- const opencodePath = `${workspacePath}/opencode`;
+ const opencodePath = `${workspacePath}/opencode2/api`;
function invalidCreatePayload(message: string): never {
const path = `${opencodePath}/session`;
@@ -106,37 +112,40 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
return signals.length === 0 ? undefined : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
}
- const sdkFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
- const request = input instanceof Request ? input : new Request(input, init);
- const headers: Record<string, string> = {};
- request.headers.forEach((value, key) => {
- headers[key] = value;
- });
- const body = request.method === "GET" || request.method === "HEAD" ? undefined : await request.text();
- return fetchImpl(request.url, {
- method: request.method,
- headers,
- ...(body === "" ? {} : { body }),
- redirect: "error",
- signal: request.signal,
- });
- };
- const opencode = createOpencodeClient({
- baseUrl: `${baseUrl}${opencodePath}`,
- headers: {
- Authorization: `Bearer ${options.token}`,
- ...(options.hostToken === undefined ? {} : { "X-OmniRush-Host-Token": options.hostToken }),
- },
- redirect: "error",
- fetch: Object.assign(sdkFetch, { preconnect: () => {} }),
- });
-
type SdkResult<T> = {
data?: T;
error?: unknown;
response?: Response;
+ /** The whole answer (its `cursor` too). */
+ payload?: unknown;
};
+ /** One call to the engine's API (`data` unwrapped), as the SDK reported it. */
+ async function call(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<SdkResult<unknown>> {
+ let response: Response;
+ try {
+ response = await fetchImpl(`${baseUrl}${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${options.token}`,
+ ...(options.hostToken === undefined ? {} : { "X-OmniRush-Host-Token": options.hostToken }),
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ redirect: "error",
+ signal: requestSignal(signal),
+ });
+ } catch (error) {
+ return { error: { message: error instanceof Error ? error.message : String(error) } };
+ }
+ const text = await response.text();
+ let payload: unknown = undefined;
+ try { payload = text ? JSON.parse(text) : undefined; } catch { payload = text; }
+ if (!response.ok) return { error: payload ?? {}, response };
+ const data = payload !== null && typeof payload === "object" && "data" in payload ? (payload as { data: unknown }).data : payload;
+ return { data, response, payload };
+ }
+
function sdkSuccess<T>(result: SdkResult<T>, method: string, path: string): T | undefined {
if (result.error === undefined) return result.data;
const detail = errorBodySchema.safeParse(result.error);
@@ -167,37 +176,45 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
});
}
- async function readMessages(threadId: string, signal?: AbortSignal) {
+ /** The thread's messages, oldest first, in the wire shape (every page; `limit`: the newest that many). */
+ async function readMessages(threadId: string, signal?: AbortSignal, limit?: number) {
const path = `${opencodePath}/session/${encodeURIComponent(threadId)}/message`;
- return sdkJson(
- threadMessagesSchema,
- await opencode.session.messages({ sessionID: threadId }, { signal: requestSignal(signal) }),
- "GET",
- path,
- );
+ const out: unknown[] = [];
+ let cursor: string | undefined;
+ for (let page = 0; page < 200; page += 1) {
+ const query = new URLSearchParams({ limit: "200", ...(cursor ? { cursor } : { order: "desc" }) });
+ const result = await call("GET", `${path}?${query}`, undefined, signal);
+ const data = sdkSuccess(result, "GET", path);
+ const items = Array.isArray(data) ? data : [];
+ out.push(...items);
+ cursor = nextCursorOf(result.payload);
+ if (!cursor || items.length === 0 || (limit !== undefined && out.length >= limit)) break;
+ }
+ const wire = v2MessagesToWire(out.reverse());
+ return sdkJson(threadMessagesSchema, { data: limit === undefined ? wire : wire.slice(-limit) }, "GET", path);
}
async function getThreadSnapshot(threadId: string, input?: { signal?: AbortSignal; limit?: number }): Promise<HeadlessThreadSnapshot> {
- const encodedThreadId = encodeURIComponent(threadId);
- const sessionPath = `${opencodePath}/session/${encodedThreadId}`;
- const messagesPath = `${sessionPath}/message`;
- const todosPath = `${sessionPath}/todo`;
- const statusPath = `${opencodePath}/session/status`;
- const [sessionResult, messagesResult, todosResult, statusResult] = await Promise.all([
- opencode.session.get({ sessionID: threadId }, { signal: requestSignal(input?.signal) }),
- opencode.session.messages({ sessionID: threadId, limit: input?.limit }, { signal: requestSignal(input?.signal) }),
- opencode.session.todo({ sessionID: threadId }, { signal: requestSignal(input?.signal) }),
- opencode.session.status(undefined, { signal: requestSignal(input?.signal) }),
+ const sessionPath = `${opencodePath}/session/${encodeURIComponent(threadId)}`;
+ const statusPath = `${opencodePath}/session/active`;
+ const [sessionRead, messagesRead, statusRead] = await Promise.allSettled([
+ call("GET", sessionPath, undefined, input?.signal),
+ readMessages(threadId, input?.signal, input?.limit),
+ call("GET", statusPath, undefined, input?.signal),
]);
- const session = sdkJson(sessionSchema, sessionResult, "GET", sessionPath);
- const messages = sdkJson(threadMessagesSchema, messagesResult, "GET", messagesPath);
- const todos = sdkJson(threadTodosSchema, todosResult, "GET", todosPath);
- const statuses = sdkJson(threadStatusesSchema, statusResult, "GET", statusPath);
+ // The session's own failure is reported first (it says the most: a missing thread).
+ const sessionResult = settled(sessionRead);
+ if (sessionResult.error !== undefined) sdkSuccess(sessionResult, "GET", sessionPath);
+ const messages = settled(messagesRead);
+ const statusResult = settled(statusRead);
+ const session = sdkJson(sessionSchema, { ...sessionResult, data: v2SessionToWire(sessionResult.data) }, "GET", sessionPath);
+ const active = sdkSuccess(statusResult, "GET", statusPath);
+ const running = active !== null && typeof active === "object" && Object.hasOwn(active, threadId);
return toSnapshot(threadSnapshotSchema.parse({
session,
messages,
- todos,
- status: statuses[threadId] ?? { type: "idle" },
+ todos: [],
+ status: running ? { type: "busy" } : { type: "idle" },
}));
}
@@ -205,21 +222,14 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
const model = input.model ?? options.defaultModel;
const createPath = `${opencodePath}/session`;
const prompt = initialPrompt(input.prompt);
- const session = sdkJson(
- sessionSchema,
- await opencode.session.create({ title: createTitle(input.title) }, { signal: requestSignal(input.signal) }),
- "POST",
- createPath,
- );
+ const created = await call("POST", createPath, {
+ title: createTitle(input.title),
+ ...(model === undefined ? {} : { model: { id: model.modelId, providerID: model.providerId, ...(model.variant === undefined ? {} : { variant: model.variant }) } }),
+ }, input.signal);
+ const session = sdkJson(sessionSchema, { ...created, data: v2SessionToWire(created.data) }, "POST", createPath);
if (prompt !== undefined) {
- const promptPath = `${opencodePath}/session/${encodeURIComponent(session.id)}/prompt_async`;
- const result = await opencode.session.promptAsync({
- sessionID: session.id,
- parts: [{ type: "text", text: prompt }],
- ...(model === undefined ? {} : { model: { providerID: model.providerId, modelID: model.modelId } }),
- ...(model?.variant === undefined ? {} : { variant: model.variant }),
- }, { signal: requestSignal(input.signal) });
- sdkSuccess(result, "POST", promptPath);
+ const promptPath = `${opencodePath}/session/${encodeURIComponent(session.id)}/prompt`;
+ sdkSuccess(await call("POST", promptPath, { text: prompt }, input.signal), "POST", promptPath);
}
return toThread(session, workspaceId, prompt !== undefined);
}
@@ -231,15 +241,12 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
if (input.messageId && messages.some((message) => message.info.id === input.messageId && message.info.role === "user")) {
return { threadId, acceptedAt: now(), messageCountBefore, messageId: input.messageId, alreadyPresent: true };
}
- const path = `${opencodePath}/session/${encodeURIComponent(threadId)}/prompt_async`;
- const result = await opencode.session.promptAsync({
- sessionID: threadId,
- parts: [{ type: "text", text: input.prompt }],
- ...(input.messageId === undefined ? {} : { messageID: input.messageId }),
- ...(model === undefined ? {} : { model: { providerID: model.providerId, modelID: model.modelId } }),
- ...(model?.variant === undefined ? {} : { variant: model.variant }),
- }, { signal: requestSignal(input.signal) });
- sdkSuccess(result, "POST", path);
+ const session = `${opencodePath}/session/${encodeURIComponent(threadId)}`;
+ if (model !== undefined) {
+ sdkSuccess(await call("POST", `${session}/model`, { model: { id: model.modelId, providerID: model.providerId, ...(model.variant === undefined ? {} : { variant: model.variant }) } }, input.signal), "POST", `${session}/model`);
+ }
+ const path = `${session}/prompt`;
+ sdkSuccess(await call("POST", path, { text: input.prompt, ...(input.messageId === undefined ? {} : { id: input.messageId }) }, input.signal), "POST", path);
return { threadId, acceptedAt: now(), messageCountBefore, messageId: input.messageId ?? null, alreadyPresent: false };
}
@@ -311,13 +318,11 @@ export function createHeadlessThreadClient(options: HeadlessThreadClientOptions)
}
async function abortThread(threadId: string, input?: { signal?: AbortSignal }): Promise<HeadlessAbortResult> {
- const path = `${opencodePath}/session/${encodeURIComponent(threadId)}/abort`;
- const accepted = sdkJson(
- abortResultSchema,
- await opencode.session.abort({ sessionID: threadId }, { signal: requestSignal(input?.signal) }),
- "POST",
- path,
- );
+ const path = `${opencodePath}/session/${encodeURIComponent(threadId)}/interrupt`;
+ const result = await call("POST", path, {}, input?.signal);
+ const data = sdkSuccess(result, "POST", path);
+ const interrupted = data !== null && typeof data === "object" && "interrupted" in data ? (data as { interrupted: unknown }).interrupted : data;
+ const accepted = sdkJson(abortResultSchema, { data: interrupted }, "POST", path);
return { threadId, accepted };
}
diff --git a/packages/headless-threads/src/v2.ts b/packages/headless-threads/src/v2.ts
new file mode 100644
index 00000000..742a0e55
--- /dev/null
+++ b/packages/headless-threads/src/v2.ts
@@ -0,0 +1,61 @@
+/**
+ * The 2.x engine's session and messages in the wire shape (wire.ts). Display data for a headless
+ * caller only: tool names and inputs stay the engine's own, nothing is renamed.
+ */
+type Rec = Record<string, unknown>;
+const isRecord = (value: unknown): value is Rec => typeof value === "object" && value !== null && !Array.isArray(value);
+
+/** `cursor.next` of a paged 2.x answer, if any. */
+export function nextCursorOf(payload: unknown): string | undefined {
+ const cursor = isRecord(payload) && isRecord(payload.cursor) ? payload.cursor.next : undefined;
+ return typeof cursor === "string" && cursor ? cursor : undefined;
+}
+
+/** A 2.x session (`location.directory`) as the wire session (`directory`). */
+export function v2SessionToWire(value: unknown): unknown {
+ if (!isRecord(value)) return value;
+ const location = isRecord(value.location) ? value.location : {};
+ return { ...value, directory: typeof location.directory === "string" ? location.directory : null };
+}
+
+function part(id: string, item: Rec): Rec | null {
+ if (item.type === "text" || item.type === "reasoning") return { id, type: item.type, text: typeof item.text === "string" ? item.text : "" };
+ if (item.type === "tool") {
+ const state = isRecord(item.state) ? item.state : {};
+ return { id, type: "tool", tool: item.name, callID: item.id, state: { status: state.status } };
+ }
+ return null;
+}
+
+/** 2.x messages (oldest first) as `{info, parts}`; turn markers and switches are left out. */
+export function v2MessagesToWire(messages: readonly unknown[]): Rec[] {
+ const out: Rec[] = [];
+ // A 2.x answer names no prompt: it answers the user message before it (wire `parentID`).
+ let lastUser: string | undefined;
+ for (const message of messages) {
+ if (!isRecord(message) || typeof message.id !== "string") continue;
+ const time = isRecord(message.time) ? { created: message.time.created } : undefined;
+ if (message.type === "user" || message.type === "synthetic") {
+ const text = typeof message.text === "string" ? message.text : "";
+ if (message.type === "user") lastUser = message.id;
+ out.push({ info: { id: message.id, role: "user", ...(time ? { time } : {}) }, parts: [{ id: `${message.id}_text`, type: "text", text, ...(message.type === "synthetic" ? { synthetic: true } : {}) }] });
+ continue;
+ }
+ if (message.type !== "assistant") continue;
+ const content = Array.isArray(message.content) ? message.content : [];
+ const parts = content.flatMap((item, index) => {
+ const mapped = isRecord(item) ? part(`${message.id}_${index}`, item) : null;
+ return mapped ? [mapped] : [];
+ });
+ out.push({
+ info: {
+ id: message.id, role: "assistant", ...(time ? { time } : {}), ...(lastUser ? { parentID: lastUser } : {}),
+ ...(message.error !== undefined ? { error: message.error } : {}),
+ ...(typeof message.cost === "number" ? { cost: message.cost } : {}),
+ ...(isRecord(message.tokens) ? { tokens: message.tokens } : {}),
+ },
+ parts,
+ });
+ }
+ return out;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dda728ae..d68dba00 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1353,9 +1353,6 @@ importers:
packages/headless-threads:
dependencies:
- '@opencode-ai/sdk':
- specifier: ^1.18.15
- version: 1.18.18
zod:
specifier: ^4.3.6
version: 4.3.6