Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: steer a running turn

ogsamrat172f04183666
diff --git a/apps/app/src/app/lib/good-session-integrity.ts b/apps/app/src/app/lib/good-session-integrity.ts
index 7f0c50ce..1ffc2072 100644
--- a/apps/app/src/app/lib/good-session-integrity.ts
+++ b/apps/app/src/app/lib/good-session-integrity.ts
@@ -39,7 +39,7 @@ function reasonCopy(code: string | undefined, messages: Readonly<Record<string,
}
/**
- * The line for one chat: "Good session ★" (true), "Checking session…"
+ * The line for one chat: "Good session ★" (true), "Checking session quality…"
* (pending, unknown, 404, 429, offline) or "Not a good session: <main
* reason>. <one fix>" with the rewards guide (false). The main reason is the
* first of `good_session_reasons`, else the first of `reasons`.
diff --git a/apps/app/src/react-app/domains/quality/good-session.tsx b/apps/app/src/react-app/domains/quality/good-session.tsx
index 59500c38..37337dec 100644
--- a/apps/app/src/react-app/domains/quality/good-session.tsx
+++ b/apps/app/src/react-app/domains/quality/good-session.tsx
@@ -251,7 +251,7 @@ function useGoodSession(
return read.sessionId === sessionId ? read.result : null;
}
-/** "Good session ★", "Checking session…" (muted) or why not, with the rewards guide. */
+/** "Good session ★", "Checking session quality…" (muted) or why not, with the rewards guide. */
export function GoodSessionLine({ result }: { result: OmniRushGoodSession | null }) {
const copy = goodSessionCopy(result);
return (
diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
index cb5616ce..6dcf5c3f 100644
--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx
+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx
@@ -2251,6 +2251,9 @@ export function SessionSurface(props: SessionSurfaceProps) {
// Immediate sends and queued sends share the same slot across all panes.
dispatchQueuedDrain(props.sessionId, { type: "user_retry" });
if (!claimQueuedSend(props.sessionId, nextDraft.messageId, true)) return;
+ // A steer joins the run the engine reports busy: that run's end is this
+ // send's end too, so a draft queued behind it goes out once it is idle.
+ if (liveStatus.type !== "idle") dispatchQueuedDrain(props.sessionId, { type: "busy_observed" });
const sentAttachments = sourceAttachments;
const composerCheckpoint = useComposerStateStore.getState().sessions[props.sessionId];
const savedComposer = sourceComposer ?? composerCheckpoint;
@@ -2340,7 +2343,7 @@ export function SessionSurface(props: SessionSurfaceProps) {
} finally {
setAttachmentsUploading(false);
}
- }, [attachments, baseRenderedMessages, buildDraft, clearComposer, draft, persistedDraftKey, props.onDraftChange, props.sessionId, sendDraft, sessionOwner]);
+ }, [attachments, baseRenderedMessages, buildDraft, clearComposer, draft, liveStatus.type, persistedDraftKey, props.onDraftChange, props.sessionId, sendDraft, sessionOwner]);
// One-step run from the empty-state hero: the route keeps the continuation
// in this session's composer and marks the submitted snapshot for auto-send.
diff --git a/apps/app/tests/composer-focus-continuity.test.tsx b/apps/app/tests/composer-focus-continuity.test.tsx
index f7b68bc2..613d042f 100644
--- a/apps/app/tests/composer-focus-continuity.test.tsx
+++ b/apps/app/tests/composer-focus-continuity.test.tsx
@@ -356,7 +356,7 @@ test("composer focus and optimistic sends preserve drafts through snapshots and
await waitFor(() => container.textContent?.split("Uncertain send").length === 3, "the unrelated same-text turn beside the pending bubble");
expect(Object.values(useComposerStateStore.getState().pendingMessages).flat()).toHaveLength(1);
const checkAcceptance = () => {
- const button = [...container.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent === "Check acceptance");
+ const button = [...container.querySelectorAll<HTMLButtonElement>("button")].find((item) => item.textContent === "Check message");
if (!button) throw new Error("Expected the read-only acceptance check");
button.click();
};
diff --git a/apps/app/tests/composer-queue-steer.test.tsx b/apps/app/tests/composer-queue-steer.test.tsx
new file mode 100644
index 00000000..bb883763
--- /dev/null
+++ b/apps/app/tests/composer-queue-steer.test.tsx
@@ -0,0 +1,258 @@
+/** @jsxImportSource react */
+import { expect, mock, test } from "bun:test";
+import { GlobalRegistrator } from "@happy-dom/global-registrator";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { createRequire } from "node:module";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import type { SessionStatus } from "@opencode-ai/sdk/v2/client";
+
+import type { OmniRushSessionSnapshot } from "../src/app/lib/omnirush-server";
+import type { ComposerDraft } from "../src/app/types";
+import type { CloudMcpSubmissionResult } from "../src/react-app/domains/connections/cloud-mcp-submit-readiness";
+
+const workspaceId = "workspace-queue-steer";
+const sessionId = "session-queue-steer";
+
+function createSnapshot(status: SessionStatus, updated: number): OmniRushSessionSnapshot {
+ return {
+ session: {
+ id: sessionId,
+ slug: sessionId,
+ projectID: "project-queue-steer",
+ directory: "/tmp/project-queue-steer",
+ title: "Queue and steer",
+ version: "1",
+ time: { created: 1, updated },
+ },
+ messages: [{
+ info: {
+ id: "existing-user-message", sessionID: sessionId, role: "user", time: { created: 1 },
+ agent: "build", model: { providerID: "test", modelID: "test-model" },
+ },
+ parts: [{ id: "existing-user-part", sessionID: sessionId, messageID: "existing-user-message", type: "text", text: "Keep this session mounted." }],
+ }],
+ todos: [],
+ status,
+ };
+}
+
+async function waitFor(predicate: () => boolean, label: string) {
+ const deadline = Date.now() + 2_000;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await act(async () => {
+ await new Promise<void>((resolve) => setTimeout(resolve, 10));
+ });
+ }
+ throw new Error(`Timed out waiting for ${label}`);
+}
+
+// While the agent works, Enter keeps the message in the app's own queue (sent
+// as a new turn once the agent is idle) and Cmd/Ctrl+Enter sends it at once:
+// the engine takes it into the running turn (steering). Nothing waits for a Stop.
+test("while busy, Enter queues locally and Cmd/Ctrl+Enter steers; the queued message sends once idle", async () => {
+ const require = createRequire(import.meta.url);
+ // Bun's isolated test loader cycles Lexical's ESM entries; use their real CJS entries before the app imports the editor.
+ for (const moduleId of [
+ "lexical",
+ "@lexical/react/LexicalComposer.js",
+ "@lexical/react/LexicalPlainTextPlugin.js",
+ "@lexical/react/LexicalContentEditable.js",
+ "@lexical/react/LexicalErrorBoundary.js",
+ "@lexical/react/LexicalOnChangePlugin.js",
+ "@lexical/react/LexicalHistoryPlugin.js",
+ "@lexical/react/LexicalComposerContext.js",
+ ]) {
+ const moduleExports = require(moduleId);
+ mock.module(moduleId, () => moduleExports);
+ }
+ const [
+ { createOmniRushServerClient },
+ { IDLE_CLOUD_MCP_SUBMISSION_GATE_STATE },
+ { useComposerStateStore },
+ { getReactQueryClient },
+ { LocalProvider },
+ { ShellConfigProvider },
+ ] = await Promise.all([
+ import("../src/app/lib/omnirush-server"),
+ import("../src/react-app/domains/connections/cloud-mcp-submit-readiness"),
+ import("../src/react-app/domains/session/surface/composer-state-store"),
+ import("../src/react-app/infra/query-client"),
+ import("../src/react-app/kernel/local-provider"),
+ import("../src/react-app/shell/shell-config"),
+ ]);
+ const registeredDom = typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined";
+ if (registeredDom) GlobalRegistrator.register({ url: "http://localhost/" });
+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
+ configurable: true,
+ value: true,
+ });
+ document.open();
+ document.write("<!doctype html><html><body></body></html>");
+ document.close();
+ Object.defineProperty(document, "compatMode", { configurable: true, value: "CSS1Compat" });
+ let acceptedMessageId: string | null = null;
+ const acceptanceRequests: Request[] = [];
+ const fetchStub = async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ if (new URL(request.url).pathname.includes(`/session/${sessionId}/message/`)) {
+ acceptanceRequests.push(request);
+ return acceptedMessageId
+ ? Response.json({ info: { id: acceptedMessageId, sessionID: sessionId, role: "user" }, parts: [] })
+ : new Response(null, { status: 404 });
+ }
+ return Response.json({});
+ };
+ Object.defineProperty(globalThis, "fetch", { configurable: true, value: fetchStub });
+ Object.defineProperty(window, "fetch", { configurable: true, value: fetchStub });
+ window.localStorage.setItem("omnirush.shell-config", JSON.stringify({ starterCards: false }));
+ let fetchedSnapshot = createSnapshot({ type: "busy" }, 1);
+ mock.module("@/components/model-select", () => ({ ModelSelect: () => null }));
+ mock.module("@/react-app/domains/session/surface/composer/workspace-run-mode-menu", () => ({ WorkspaceRunModeMenu: () => null }));
+ mock.module("@/react-app/domains/session/surface/composer/full-permissions-toggle", () => ({ FullPermissionsToggle: () => null }));
+ mock.module("@/react-app/domains/session/surface/composer/subagent-model-menu", () => ({ SubagentModelMenu: () => null }));
+ mock.module("@/app/lib/opencode-session-native", () => ({
+ composeNativeSessionSnapshot: async () => fetchedSnapshot,
+ isMissingSessionError: () => false,
+ }));
+ const { SessionSurface } = await import("../src/react-app/domains/session/surface/session-surface");
+ const { snapshotKey, statusKey, transcriptKey } = await import("../src/react-app/domains/session/sync/session-sync");
+ const { resetQueuedDrainForTests } = await import("../src/react-app/domains/session/surface/queued-drain-machine");
+ const queryClient = getReactQueryClient();
+ queryClient.clear();
+ queryClient.setQueryData(snapshotKey(workspaceId, sessionId), createSnapshot({ type: "busy" }, 1));
+ queryClient.setQueryData(transcriptKey(workspaceId, sessionId), [{
+ id: "existing-user-message",
+ role: "user",
+ parts: [{ type: "text", text: "Keep this session mounted." }],
+ }]);
+ const client = createOmniRushServerClient({ baseUrl: "http://127.0.0.1:1", token: "test-token" });
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ const sentDrafts: ComposerDraft[] = [];
+
+ try {
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <LocalProvider>
+ <ShellConfigProvider>
+ <SessionSurface
+ client={client}
+ workspaceId={workspaceId}
+ workspaceRoot="/tmp/project-queue-steer"
+ sessionId={sessionId}
+ draftScope="local"
+ isControlTarget={false}
+ opencodeBaseUrl="http://127.0.0.1:1/opencode"
+ omnirushToken="test-token"
+ developerMode
+ modelLabel="Test model"
+ onModelClick={() => {}}
+ modelPickerOpen={false}
+ selectedModel={{ providerID: "test", modelID: "test-model" }}
+ onModelPickerOpenChange={() => {}}
+ onModelChange={() => {}}
+ onSendDraft={async (value) => {
+ sentDrafts.push(value);
+ return { outcome: "accepted" };
+ }}
+ cloudMcpSubmissionState={IDLE_CLOUD_MCP_SUBMISSION_GATE_STATE}
+ onOpenConnect={() => {}}
+ onDraftChange={() => {}}
+ attachmentsEnabled={false}
+ attachmentsDisabledReason="Not needed in this test"
+ modelVariantLabel="Default"
+ modelVariant={null}
+ onModelVariantChange={() => {}}
+ agentLabel="OmniRush.ai"
+ selectedAgent={null}
+ listAgents={async () => []}
+ onSelectAgent={() => {}}
+ listCommands={async () => []}
+ recentFiles={[]}
+ searchFiles={async () => []}
+ isRemoteWorkspace
+ isSandboxWorkspace={false}
+ providerConnectedCount={1}
+ />
+ </ShellConfigProvider>
+ </LocalProvider>
+ </QueryClientProvider>,
+ );
+ });
+ await waitFor(
+ () => container.querySelector('[contenteditable="true"][data-lexical-editor="true"]') !== null,
+ "the Lexical editor",
+ );
+ const editor = container.querySelector<HTMLElement>('[contenteditable="true"][data-lexical-editor="true"]');
+ if (!editor) throw new Error("Expected the Lexical editor");
+ editor.focus();
+ expect(document.activeElement).toBe(editor);
+
+ const typeDraft = async (text: string) => {
+ await act(async () => useComposerStateStore.getState().setDraft(sessionId, text));
+ await waitFor(() => editor.textContent === text, `the draft "${text}" to reach Lexical`);
+ };
+ // Enter as Lexical sees it: with the caret at the end of the draft (happy-dom sets no selection on focus).
+ const lexical = require("lexical") as typeof import("lexical");
+ const lexicalEditor = (editor as HTMLElement & { __lexicalEditor?: import("lexical").LexicalEditor }).__lexicalEditor;
+ if (!lexicalEditor) throw new Error("Expected the Lexical editor instance");
+ const press = async (init: KeyboardEventInit) => {
+ await act(async () => {
+ lexicalEditor.update(() => {
+ lexical.$getRoot().selectEnd();
+ lexicalEditor.dispatchCommand(lexical.KEY_ENTER_COMMAND, new KeyboardEvent("keydown", { key: "Enter", bubbles: true, ...init }));
+ }, { discrete: true });
+ });
+ };
+
+ // Busy: Enter queues the draft locally; nothing reaches the engine.
+ await typeDraft("Queue this for later");
+ await press({});
+ expect(sentDrafts).toHaveLength(0);
+ expect(useComposerStateStore.getState().queuedDrafts[sessionId]?.map((item) => item.draft.text)).toEqual(["Queue this for later"]);
+ await waitFor(() => editor.textContent === "", "the composer to clear after queueing");
+ expect(container.textContent).not.toContain("Stop the current turn before sending another message.");
+
+ // Busy: Ctrl+Enter (and Cmd+Enter) steers: the draft is sent now, into the running turn.
+ await typeDraft("Use port 8080 instead");
+ await press({ ctrlKey: true });
+ await waitFor(() => sentDrafts.length === 1, "the steer to be sent while busy");
+ expect(sentDrafts[0]?.text).toBe("Use port 8080 instead");
+ await typeDraft("And skip the docs");
+ await press({ metaKey: true });
+ await waitFor(() => sentDrafts.length === 2, "the second steer to be sent while busy");
+ expect(sentDrafts[1]?.text).toBe("And skip the docs");
+ // The queued draft still waits for the agent to finish.
+ expect(useComposerStateStore.getState().queuedDrafts[sessionId]).toHaveLength(1);
+
+ // The engine took both steers into the running turn: the transcript shows them.
+ await act(async () => queryClient.setQueryData(transcriptKey(workspaceId, sessionId), [
+ { id: "existing-user-message", role: "user", parts: [{ type: "text", text: "Keep this session mounted." }] },
+ ...sentDrafts.map((sent) => ({ id: sent.messageId, role: "user", parts: [{ type: "text", text: sent.text }] })),
+ ]));
+
+ // Idle: the queued draft goes out as a normal new turn.
+ await act(async () => {
+ fetchedSnapshot = createSnapshot({ type: "idle" }, 2);
+ queryClient.setQueryData(snapshotKey(workspaceId, sessionId), createSnapshot({ type: "idle" }, 2));
+ // The session-status stream's observed level.
+ queryClient.setQueryData(statusKey(workspaceId, sessionId), { type: "idle" });
+ });
+ await waitFor(() => sentDrafts.length === 3, "the queued draft to be sent once idle");
+ expect(sentDrafts[2]?.text).toBe("Queue this for later");
+ await waitFor(() => (useComposerStateStore.getState().queuedDrafts[sessionId] ?? []).length === 0, "the queue to drain");
+ expect(acceptedMessageId).toBeNull();
+ } finally {
+ await act(async () => root.unmount());
+ resetQueuedDrainForTests();
+ useComposerStateStore.setState({ sessions: {}, queuedDrafts: {}, history: {}, pendingMessages: {}, failedDrafts: {} });
+ queryClient.clear();
+ container.remove();
+ mock.restore();
+ if (registeredDom) await GlobalRegistrator.unregister();
+ }
+});
diff --git a/apps/app/tests/good-session-integrity.test.tsx b/apps/app/tests/good-session-integrity.test.tsx
index 85fd2d43..a858ffda 100644
--- a/apps/app/tests/good-session-integrity.test.tsx
+++ b/apps/app/tests/good-session-integrity.test.tsx
@@ -25,9 +25,9 @@ describe("goodSessionCopy", () => {
expect(goodSessionCopy(result({ good_session: true, integrity: "ok" }))).toEqual({ state: "good", text: "Good session ★" });
});
- test("pending, unknown, 404, 429 and offline read Checking session…", () => {
+ test("pending, unknown, 404, 429 and offline read Checking session quality…", () => {
for (const value of [result({ good_session: "pending", reasons: ["archive_uploading"] }), null, undefined]) {
- expect(goodSessionCopy(value)).toEqual({ state: "pending", text: "Checking session…" });
+ expect(goodSessionCopy(value)).toEqual({ state: "pending", text: "Checking session quality…" });
}
});
@@ -76,7 +76,7 @@ describe("goodSessionCopy", () => {
test("the line renders each state", () => {
expect(renderToStaticMarkup(<GoodSessionLine result={result({ good_session: true })} />)).toContain("Good session ★");
const pending = renderToStaticMarkup(<GoodSessionLine result={null} />);
- expect(pending).toContain("Checking session…");
+ expect(pending).toContain("Checking session quality…");
expect(pending).toContain("text-muted-foreground");
expect(pending).not.toContain("<svg");
const bad = renderToStaticMarkup(<GoodSessionLine result={result({ good_session: false, good_session_reasons: ["no_trace"] })} />);
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 65861aee..e3bddfb3 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -89,6 +89,10 @@ export type CaptureService = {
/** The "engine.request" event of a captured request (its body parsed off the main thread), plus a prompt's attachments. */
recordPrompt(sessionId: string, prompt: Omit<PromptRecord, "body"> & { body: ArrayBuffer | undefined }): void;
captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"): void;
+ /** A prompt steered the running turn: its "turn.steer" event (turn-steer.ts steerRecord). */
+ steerTurn(sessionId: string, steer: Record<string, unknown>): void;
+ /** The engine took a steer: its turn is followed (if no observer follows it already). */
+ followSteer(sessionId: string, target: EngineTarget): void;
/** Whether the visit is recorded (a tracked session and an uploadable URL). */
recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean;
archiveSessionStarted(sessionId: string, root: string, target: EngineTarget): void;
@@ -224,6 +228,17 @@ class CaptureClient implements CaptureService {
this.send({ kind: "call", id: null, method: "captureSnapshot", args: outcome ? [sessionId, trigger, outcome] : [sessionId, trigger] });
}
+ steerTurn(sessionId: string, steer: Record<string, unknown>): void {
+ this.send({ kind: "call", id: null, method: "steerTurn", args: [sessionId, steer] });
+ }
+
+ followSteer(sessionId: string, target: EngineTarget): void {
+ this.observedTargets.delete(sessionId);
+ this.observedTargets.set(sessionId, target);
+ if (this.observedTargets.size > MAX_OBSERVED_TARGETS) this.observedTargets.delete(this.observedTargets.keys().next().value as string);
+ this.send({ kind: "call", id: null, method: "followSteer", args: [sessionId, target] });
+ }
+
recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
if (this.local) return this.local.recordWebVisit(sessionId, visit);
if (!this.hasSession(sessionId) || typeof visit.url !== "string" || !isUploadableWebUrl(visit.url)) return false;
diff --git a/apps/server/src/capture-context.test.ts b/apps/server/src/capture-context.test.ts
index 2c21a18e..2e2b25ca 100644
--- a/apps/server/src/capture-context.test.ts
+++ b/apps/server/src/capture-context.test.ts
@@ -712,12 +712,12 @@ test("CLI/desktop parity: the context modules match PARITY.sha256 (the same list
for (const name of files) assert.equal(createHash("sha256").update(fs.readFileSync(path.join(contextDir, name))).digest("hex"), listed.get(name), `${name} changed: port it to the CLI and update PARITY.sha256 in both`);
});
-test("CLI/desktop parity: the shared session-archive modules match their PARITY.sha256 (late writes, tool start, turn writers)", async () => {
+test("CLI/desktop parity: the shared session-archive modules match their PARITY.sha256 (late writes, tool start, turn writers, turn prompts)", async () => {
const { createHash } = await import("node:crypto");
const dir = path.join(import.meta.dir, "session-archive");
const lines = fs.readFileSync(path.join(dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));
const listed = new Map(lines.map((line) => { const [hash, name] = line.split(/\s+/); return [name, hash]; }));
- assert.deepEqual([...listed.keys()].sort(), ["late-writes.ts", "tool-start.ts", "turn-writers.ts"]);
+ assert.deepEqual([...listed.keys()].sort(), ["late-writes.ts", "tool-start.ts", "turn-prompts.ts", "turn-writers.ts"]);
for (const [name, hash] of listed) assert.equal(createHash("sha256").update(fs.readFileSync(path.join(dir, name))).digest("hex"), hash, `${name} changed: port it to the CLI and update PARITY.sha256 in both`);
});
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 840dcc6b..186ca796 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -69,6 +69,8 @@ export type PromptRecord = {
* engine saw it): a turn of the session still being followed ends here.
*/
dispatchedAt?: number;
+ /** A prompt that started a turn while the engine was not plainly idle: why (turn-steer.ts), on its "engine.request" event. */
+ turnStart?: string;
};
export type CaptureHostOptions = {
@@ -276,6 +278,7 @@ export class CaptureHost {
method: prompt.method,
path: prompt.path,
body: prompt.engine === "v2" ? v2PromptBodyForTrace(payload) : promptBodyForTrace(payload),
+ ...(prompt.turnStart ? { turn_start: prompt.turnStart } : {}),
});
if (!prompt.attachments) return;
void readPromptAttachments(payload, prompt.root).then((attachments) => {
@@ -287,6 +290,22 @@ export class CaptureHost {
this.sessionUploader.captureSnapshot(sessionId, trigger, outcome);
}
+ /** A prompt steered the running turn (turn-steer.ts): its "turn.steer" event. */
+ steerTurn(sessionId: string, steer: Record<string, unknown>): void {
+ this.sessionUploader.steerTurn(sessionId, steer);
+ }
+
+ /**
+ * The engine took a steer: the running turn goes on, followed by its
+ * observer. A turn no observer follows (its observation ended) is followed
+ * from here; a followed one is left as it is, so the steer never counts as
+ * a request of its own (a turn after this one).
+ */
+ followSteer(sessionId: string, target: EngineTarget): void {
+ if (this.observers.sessions.has(sessionId)) return;
+ this.observeSession(sessionId, target);
+ }
+
recordWebVisit(sessionId: string, visit: UploadWebVisit): boolean {
return this.sessionUploader.recordWebVisit(sessionId, visit);
}
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 51e17d96..13c80d5e 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -24,6 +24,8 @@ export type CaptureCalls = {
finishSession: [sessionId: string, finalTrace?: unknown];
recordPrompt: [sessionId: string, prompt: PromptRecord];
captureSnapshot: [sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"];
+ steerTurn: [sessionId: string, steer: Record<string, unknown>];
+ followSteer: [sessionId: string, target: EngineTarget];
recordWebVisit: [sessionId: string, visit: UploadWebVisit];
archiveSessionStarted: [sessionId: string, root: string, target: EngineTarget];
archiveStartGate: [sessionId: string, root: string, lateWrites?: LateWritesGate | null];
@@ -177,6 +179,10 @@ export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {
return host.recordPrompt(...call.args);
case "captureSnapshot":
return host.captureSnapshot(...call.args);
+ case "steerTurn":
+ return host.steerTurn(...call.args);
+ case "followSteer":
+ return host.followSteer(...call.args);
case "recordWebVisit":
return host.recordWebVisit(...call.args);
case "archiveSessionStarted":
diff --git a/apps/server/src/opencode-proxy.e2e.test.ts b/apps/server/src/opencode-proxy.e2e.test.ts
index 5ddd5461..c7962c9a 100644
--- a/apps/server/src/opencode-proxy.e2e.test.ts
+++ b/apps/server/src/opencode-proxy.e2e.test.ts
@@ -611,7 +611,7 @@ describe("workspace OpenCode proxy", () => {
expect(response.status).toBe(400);
await expect(response.json()).resolves.toMatchObject({
code: "opencode_unconfigured",
- message: "OpenCode base URL is missing for this workspace",
+ message: "OmniRush base URL is missing for this workspace",
});
});
});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 3ae6592d..3adc7091 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -202,6 +202,7 @@ import { sessionUploaderEnabled } from "./session-uploader.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
import type { LateWritesGate } from "./capture-host.js";
import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
+import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord } from "./turn-steer.js";
import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
import { awaitOmniRushModelCatalogSettled, startOmniRushModelCatalogSync } from "./omnirush-model-catalog-sync.js";
import { OmniRushVoiceService, voiceProjectContext } from "./omnirush-voice.js";
@@ -2178,11 +2179,23 @@ export async function proxyOpencodeRequest(input: {
// and end snapshot behind.
const captured = Boolean(capture?.uploadEnabled && uploadedSessionId && workspace && workspace.workspaceType !== "remote"
&& (capture.hasSession(uploadedSessionId) || await engineHasSession(baseUrl, auth, directory, uploadedSessionId)));
+ // Steering (turn-steer.ts): a prompt sent while the agent works goes into
+ // the running turn, which the engine hands to the model at the agent's next
+ // step. Classified before anything is taken for it, with two small reads at
+ // most; it goes through at once and opens no turn: no late-writes settle, no
+ // box checkpoint, no start snapshot, no context turn, no archive start, and
+ // the running turn is not cut. The turn records it as "turn.steer".
+ const steerSentAt = Date.now();
+ const turnKind = capture && captured && uploadedSessionId && workspace && isUploadPromptDispatch(method, proxyPath)
+ ? await createSteerTracker(engineTarget(baseUrl, headers, search)).classify(uploadedSessionId)
+ : null;
+ const steer = Boolean(turnKind?.steer && uploadedSessionId && capture?.hasSession(uploadedSessionId));
+ if (steer) createServerLogger(input.config).log("info", "Prompt steers the running turn.", { "turn.steer.reason": turnKind?.reason ?? "" });
// The Linux sandbox (box/): a prompt of a workspace whose box is on starts the box, and takes the turn's checkpoint when it is captured.
const boxInfo = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)
- ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured })
+ ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured && !steer })
: null;
- if (capture && captured && uploadedSessionId && workspace) {
+ if (capture && captured && uploadedSessionId && workspace && !steer) {
const promptDispatch = isUploadPromptDispatch(method, proxyPath);
// The turn before's background processes finish writing (at most 10 s after it ended), then
// capture v2's session-start manifest is taken before the prompt reaches the engine (at most about 3 s).
@@ -2198,12 +2211,24 @@ export async function proxyOpencodeRequest(input: {
attachments: promptDispatch,
// Taken before the engine sees the prompt: the session's previous turn ends here.
...(promptDispatch ? { dispatchedAt: Date.now() } : {}),
+ // A turn started while the engine was not plainly idle says why.
+ ...(turnKind && turnKind.reason !== "idle" ? { turnStart: turnKind.reason } : {}),
});
if (promptDispatch) {
capture.captureSnapshot(uploadedSessionId, "prompt");
capture.archiveSessionStarted(uploadedSessionId, workspace.path, engineTarget(baseUrl, headers, search));
}
}
+ // The engine took a steer: its turn goes on (followed as before), and the steer's record is found in the background.
+ const steered = (service: CaptureService, sessionId: string, target: EngineTarget) => {
+ service.followSteer(sessionId, target);
+ const reason = turnKind?.reason ?? "working";
+ const known = claimedSteerIds(sessionId);
+ void createSteerTracker(target).describe(sessionId, steerSentAt, { known }).then((found) => {
+ if (found) claimSteerId(known, found.message_id);
+ service.steerTurn(sessionId, steerRecord(found, steerSentAt, reason));
+ }).catch(() => service.steerTurn(sessionId, steerRecord(null, steerSentAt, reason)));
+ };
if (pool && method === "GET" && isEngineEventPath(proxyPath)) {
// An open engine event stream means this workspace is visible somewhere in
// the UI; hold its instance so the idle reaper leaves it alone until the
@@ -2283,7 +2308,9 @@ export async function proxyOpencodeRequest(input: {
body,
}).finally(() => release?.()).then((response) => {
enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);
- if (capture?.uploadEnabled && uploadedSessionId) {
+ if (capture?.uploadEnabled && uploadedSessionId && steer) {
+ if (response.ok) steered(capture, uploadedSessionId, engineTarget(baseUrl, headers, search));
+ } else if (capture?.uploadEnabled && uploadedSessionId) {
capture.recordTrace(uploadedSessionId, "engine.response", {
method,
path: normalizeOpencodeProxyPath(proxyPath),
@@ -2367,7 +2394,9 @@ export async function proxyOpencodeRequest(input: {
const forwardAndUpload = async () => {
const response = await forward();
- if (capture?.uploadEnabled && uploadedSessionId) {
+ if (capture?.uploadEnabled && uploadedSessionId && steer) {
+ if (workspace && response.ok) steered(capture, uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));
+ } else if (capture?.uploadEnabled && uploadedSessionId) {
capture.recordTrace(uploadedSessionId, "engine.response", {
method,
path: normalizeOpencodeProxyPath(proxyPath),
diff --git a/apps/server/src/session-archive/PARITY.sha256 b/apps/server/src/session-archive/PARITY.sha256
index 52e1ea4f..6f719713 100644
--- a/apps/server/src/session-archive/PARITY.sha256
+++ b/apps/server/src/session-archive/PARITY.sha256
@@ -3,3 +3,4 @@
8fd84683b5542236f0c88750e3d9bd756e15a304d263141b57998b17c4a1ab9c late-writes.ts
4d9a13a5df136cd6e13d0aeb67983249ca4a6913b66c5a8f768daa63da511dda tool-start.ts
1906cab8c93370abd1d024d3552fe919a0006af9ebef084ada7b64c290d1bc95 turn-writers.ts
+402d175a7cffb8fdac490a97430b7590d72f4dde637e134e0a8de7c88ba06687 turn-prompts.ts
diff --git a/apps/server/src/session-archive/lifecycle.ts b/apps/server/src/session-archive/lifecycle.ts
index f89b8972..b7d890cd 100644
--- a/apps/server/src/session-archive/lifecycle.ts
+++ b/apps/server/src/session-archive/lifecycle.ts
@@ -15,6 +15,7 @@ import { realpath } from "node:fs/promises";
import { attachmentsFromMessages } from "./attachments.js";
import type { StartCapture } from "./capture-v2.js";
+import { completedTurnCount, promptTurnAt } from "./turn-prompts.js";
import type { CaptureResult, DrainResult, FilesUsedStatus, FinalReason, SessionArchiver } from "./index.js";
import type { UsedToolCall } from "./files-used.js";
@@ -96,82 +97,7 @@ export function isFinishedAssistantMessage(message: Record<string, unknown>): bo
return parts.some((part) => isRecord(part) && ["step-finish", "finish", "error"].includes(String(part.type)));
}
-/**
- * A user message that is a prompt someone sent: not a compaction's request
- * (a "compaction" part, or the 2.x adapter's compaction agent) and not
- * synthetic text alone (a user-run shell command's notice, an activated
- * skill, a background job's report, the engine's own continue nudge). A
- * message without parts (an outline from before parts were kept) is one.
- */
-export function isPromptMessage(message: Record<string, unknown>): boolean {
- const info = messageInfo(message);
- if ((info.role ?? info.type) !== "user") return false;
- if (info.agent === "compaction") return false;
- const parts = (Array.isArray(message.parts) ? message.parts : []).filter(isRecord);
- if (parts.some((part) => part.type === "compaction")) return false;
- const content = parts.filter((part) => part.type === "text" || part.type === "file" || part.type === "agent" || part.type === "subtask");
- return !(content.length > 0 && content.every((part) => part.type === "text" && part.synthetic === true));
-}
-
-/**
- * Completed turns in an engine message list: the prompts that ended,
- * answered by an assistant message that ended (several assistant steps of
- * one turn count once) or followed by the next prompt (stopped before any
- * answer). A compaction's request and summary, and synthetic notices with
- * the replies they woke, are no turn: the count is the number of prompts the
- * session finished, as the trace's prompt milestones number them. Each
- * completed turn adds one, so the number strictly increases from one turn to
- * the next and survives app restarts. Null when the list could not be read.
- */
-export function completedTurnCount(messages: unknown): number | null {
- if (!Array.isArray(messages)) return null;
- let turns = 0;
- let awaitingReply = false;
- for (const message of messages) {
- if (!isRecord(message)) continue;
- const info = messageInfo(message);
- const role = info.role ?? info.type;
- if (isPromptMessage(message)) {
- // The prompt before ended without an answer (stopped right away): it was a turn too.
- if (awaitingReply) turns += 1;
- awaitingReply = true;
- } else if (role === "assistant" && awaitingReply && isFinishedAssistantMessage(message)) {
- turns += 1;
- awaitingReply = false;
- }
- }
- return turns;
-}
-
-function createdAtMs(message: Record<string, unknown>): number | null {
- const info = messageInfo(message);
- const time = isRecord(info.time) ? info.time.created : info.createdAt ?? info.created_at;
- if (typeof time === "number" && Number.isFinite(time)) return time;
- if (typeof time === "string") {
- const parsed = Date.parse(time);
- return Number.isFinite(parsed) ? parsed : null;
- }
- return null;
-}
-
-/**
- * The turn a tool call that started at `at` belongs to: the number of prompts
- * sent up to then (the first prompt is turn 1), counting a prompt without a
- * creation time as sent. A prompt sent before the previous turn settled (a
- * quick follow-up, or one typed into a running turn) is its own turn, as the
- * converter numbers them. Null when the list could not be read or holds no
- * prompt.
- */
-export function promptTurnAt(messages: unknown, at: number): number | null {
- if (!Array.isArray(messages)) return null;
- let turns = 0;
- for (const message of messages) {
- if (!isRecord(message) || !isPromptMessage(message)) continue;
- const created = createdAtMs(message);
- if (created === null || created <= at) turns += 1;
- }
- return turns > 0 ? turns : null;
-}
+export { completedTurnCount, isPromptMessage, promptTurnAt, steerPrompts } from "./turn-prompts.js";
/** The parent of a session record: a string for a child (sub-agent) session, null for a root one, undefined when unreadable. */
function parentSessionId(session: unknown): string | null | undefined {
diff --git a/apps/server/src/session-archive/turn-prompts.ts b/apps/server/src/session-archive/turn-prompts.ts
new file mode 100644
index 00000000..67e3247e
--- /dev/null
+++ b/apps/server/src/session-archive/turn-prompts.ts
@@ -0,0 +1,172 @@
+/**
+ * Which user messages of an engine session open a turn. The same file ships
+ * in omnirush-cli and omnirush-gui (PARITY.sha256): every turn number the
+ * clients write (archive states, context turns, a resumed session's count)
+ * comes from here, so both number turns the same way.
+ *
+ * A turn is a prompt someone sent and everything the agent did for it. Two
+ * kinds of user message do not open one:
+ *
+ * - the engine's own: a compaction's request, synthetic text alone (a
+ * user-run shell command's notice, an activated skill, a background job's
+ * report, the continue nudge);
+ * - a steer: a prompt sent while the agent was still working on the turn
+ * before. The engine delivers it at the agent's next step, inside the
+ * running turn, so the turn keeps the workspace its first prompt found and
+ * the steer is recorded in it (the client's `turn.steer` event).
+ *
+ * A prompt is a steer when an assistant message created before it ended
+ * after it was sent (the agent was mid-step: thinking, a tool, a sub-agent),
+ * or when the step before it asked for more steps (tool calls) and ended at
+ * most STEER_GAP_MS before it, without an error (between two steps). An
+ * assistant message that never ended (a crashed run) proves nothing.
+ */
+export const STEER_GAP_MS = 2_000;
+
+type MessageRecord = Record<string, unknown>;
+
+function isRecord(value: unknown): value is MessageRecord {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function infoOf(message: MessageRecord): MessageRecord {
+ return isRecord(message.info) ? message.info : message;
+}
+
+function timeMs(value: unknown): number | null {
+ if (typeof value === "number" && Number.isFinite(value)) return value;
+ if (typeof value === "string") {
+ const parsed = Date.parse(value);
+ return Number.isFinite(parsed) ? parsed : null;
+ }
+ return null;
+}
+
+function createdMs(message: MessageRecord): number | null {
+ const info = infoOf(message);
+ return timeMs(isRecord(info.time) ? info.time.created : info.createdAt ?? info.created_at);
+}
+
+function completedMs(message: MessageRecord): number | null {
+ const info = infoOf(message);
+ return timeMs(isRecord(info.time) ? info.time.completed : info.completedAt ?? info.completed_at);
+}
+
+function roleOf(message: MessageRecord): unknown {
+ const info = infoOf(message);
+ return info.role ?? info.type;
+}
+
+/**
+ * A user message that is a prompt someone sent: not a compaction's request
+ * (a "compaction" part, or the 2.x adapter's compaction agent) and not
+ * synthetic text alone. A message without parts (an outline from before
+ * parts were kept) is one.
+ */
+export function isPromptMessage(message: MessageRecord): boolean {
+ const info = infoOf(message);
+ if ((info.role ?? info.type) !== "user") return false;
+ if (info.agent === "compaction") return false;
+ const parts = (Array.isArray(message.parts) ? message.parts : Array.isArray(info.content) ? info.content : []).filter(isRecord);
+ if (parts.some((part) => part.type === "compaction")) return false;
+ const content = parts.filter((part) => part.type === "text" || part.type === "file" || part.type === "agent" || part.type === "subtask");
+ return !(content.length > 0 && content.every((part) => part.type === "text" && part.synthetic === true));
+}
+
+/**
+ * The ids (or, for a message without an id, the positions) of the prompts in
+ * `messages` that steered a running turn. `messages`: one session's
+ * messages in the engine's order.
+ */
+export function steerPrompts(messages: readonly unknown[]): Set<string | number> {
+ const steers = new Set<string | number>();
+ let opened = false;
+ // The latest end of an assistant message so far, and the step that ended last.
+ let busyUntil = -Infinity;
+ let lastStep: { completed: number | null; continues: boolean } | null = null;
+ messages.forEach((message, index) => {
+ if (!isRecord(message)) return;
+ const role = roleOf(message);
+ if (role === "assistant") {
+ const info = infoOf(message);
+ const completed = completedMs(message);
+ if (completed !== null) busyUntil = Math.max(busyUntil, completed);
+ lastStep = { completed, continues: info.error == null && (info.finish === "tool-calls" || info.finish === "unknown") };
+ return;
+ }
+ if (!isPromptMessage(message)) return;
+ const sent = createdMs(message);
+ const step = lastStep as { completed: number | null; continues: boolean } | null;
+ const steer = opened && sent !== null && (
+ busyUntil > sent ||
+ (step !== null && step.continues && step.completed !== null && sent - step.completed <= STEER_GAP_MS)
+ );
+ if (steer) {
+ const id = infoOf(message).id;
+ steers.add(typeof id === "string" ? id : index);
+ }
+ opened = true;
+ });
+ return steers;
+}
+
+/** Whether the message at `index` of `messages` opens a turn (a prompt, not a steer). */
+function opensTurn(message: MessageRecord, index: number, steers: Set<string | number>): boolean {
+ if (!isPromptMessage(message)) return false;
+ const id = infoOf(message).id;
+ return !steers.has(typeof id === "string" ? id : index);
+}
+
+/**
+ * Completed turns in an engine message list: the turns that ended, answered
+ * by an assistant message that ended (several assistant steps of one turn,
+ * and the steps after its steers, count once) or followed by the next prompt
+ * (stopped before any answer). Each completed turn adds one, so the number
+ * strictly increases from one turn to the next and survives app restarts.
+ * Null when the list could not be read.
+ */
+export function completedTurnCount(messages: unknown): number | null {
+ if (!Array.isArray(messages)) return null;
+ const steers = steerPrompts(messages);
+ let turns = 0;
+ let awaitingReply = false;
+ messages.forEach((message, index) => {
+ if (!isRecord(message)) return;
+ if (opensTurn(message, index, steers)) {
+ // The prompt before ended without an answer (stopped right away): it was a turn too.
+ if (awaitingReply) turns += 1;
+ awaitingReply = true;
+ } else if (roleOf(message) === "assistant" && awaitingReply && isEnded(message)) {
+ turns += 1;
+ awaitingReply = false;
+ }
+ });
+ return turns;
+}
+
+function isEnded(message: MessageRecord): boolean {
+ const info = infoOf(message);
+ if (completedMs(message) !== null) return true;
+ if (typeof info.finish === "string" || info.error != null) return true;
+ const parts = Array.isArray(message.parts) ? message.parts : Array.isArray(info.content) ? info.content : [];
+ return parts.some((part) => isRecord(part) && ["step-finish", "finish", "error"].includes(String(part.type)));
+}
+
+/**
+ * The turn a tool call that started at `at` belongs to: the number of turns
+ * opened up to then (the first prompt is turn 1), counting a prompt without
+ * a creation time as sent. A steer is no turn of its own: its tool calls
+ * belong to the turn it steered. Null when the list could not be read or
+ * holds no prompt.
+ */
+export function promptTurnAt(messages: unknown, at: number): number | null {
+ if (!Array.isArray(messages)) return null;
+ const steers = steerPrompts(messages);
+ let turns = 0;
+ messages.forEach((message, index) => {
+ if (!isRecord(message) || !opensTurn(message, index, steers)) return;
+ const created = createdMs(message);
+ if (created === null || created <= at) turns += 1;
+ });
+ return turns > 0 ? turns : null;
+}
diff --git a/apps/server/src/session-upload-observer-big-turn.test.ts b/apps/server/src/session-upload-observer-big-turn.test.ts
index 72c60bf6..b69fa9e4 100644
--- a/apps/server/src/session-upload-observer-big-turn.test.ts
+++ b/apps/server/src/session-upload-observer-big-turn.test.ts
@@ -20,7 +20,7 @@ function bigPrompt(id: string, text: string, files: Array<{ file: string; bytes:
id,
sessionID: "ses_big",
role: "user",
- time: { created: 1 },
+ time: { created: 4 },
summary: { diffs: files.map(({ file, bytes }) => ({ file, before: "", after: blob(bytes, file), additions: 1, deletions: 0, status: "added" })) },
},
parts: [{ type: "text", text }],
diff --git a/apps/server/src/session-upload-observer.test.ts b/apps/server/src/session-upload-observer.test.ts
index 24543999..a715978e 100644
--- a/apps/server/src/session-upload-observer.test.ts
+++ b/apps/server/src/session-upload-observer.test.ts
@@ -670,8 +670,10 @@ describe("session upload observer across engine rollovers and queued prompts", (
});
describe("session upload observer with the project archive", () => {
- const user = (id: string) => message(`msg_user_${id}`, "user");
- const answer = (id: string) => message(`msg_assistant_${id}`, "assistant");
+ // Turn n's prompt is sent after turn n-1's answer completed (an earlier one would steer that turn).
+ const timed = (entry: EngineMessage, time: Record<string, number>): EngineMessage => ({ ...entry, info: { ...entry.info, time } });
+ const user = (id: string) => timed(message(`msg_user_${id}`, "user"), { created: Number(id) * 10 });
+ const answer = (id: string) => timed(message(`msg_assistant_${id}`, "assistant"), { created: Number(id) * 10 + 1, completed: Number(id) * 10 + 2 });
test("a turn that runs past the old one-hour cap and then settles gets its delta, and the idle final archive once the session stays quiet", async () => {
const clock = fakeClock();
diff --git a/apps/server/src/session-uploader.server.e2e.test.ts b/apps/server/src/session-uploader.server.e2e.test.ts
index 55475f1d..701e074d 100644
--- a/apps/server/src/session-uploader.server.e2e.test.ts
+++ b/apps/server/src/session-uploader.server.e2e.test.ts
@@ -112,7 +112,7 @@ function messagePage(url: URL, list: EngineMessage[]): Response {
* the synchronous prompt route on the "ses_workflow" session it creates. The
* root session can start with an earlier `history`.
*/
-function startMockEngine(input: { provider: string; model: string; history?: EngineMessage[] }) {
+function startMockEngine(input: { provider: string; model: string; history?: EngineMessage[]; steerable?: boolean }) {
let turn = 0;
let busy = false;
let workflowBusy = false;
@@ -184,6 +184,28 @@ function startMockEngine(input: { provider: string; model: string; history?: Eng
if (pathname === "/session/ses_workflow/abort" && request.method === "POST") return Response.json(true);
if (pathname === "/session/ses_root/prompt_async" && request.method === "POST") {
prompts.push(await request.json().catch(() => null));
+ if (input.steerable) {
+ // Real clock times: a prompt into a busy session joins the running step,
+ // whose assistant message stays open (no completion) until the session goes idle.
+ if (busy) {
+ const steer = message("ses_root", `user_steer_${turn}_${root.length}`, "user", "steer");
+ steer.info = { ...steer.info, time: { created: Date.now() } };
+ root.push(steer);
+ return new Response(null, { status: 204 });
+ }
+ turn += 1;
+ busy = true;
+ const user = message("ses_root", `user_${turn}`, "user", `prompt ${turn}`);
+ user.info = { ...user.info, time: { created: Date.now() } };
+ const answer = message("ses_root", `assistant_${turn}`, "assistant", `answer ${turn}`);
+ answer.info = { ...answer.info, time: { created: Date.now() + 1 } };
+ root.push(user, answer);
+ setTimeout(() => {
+ answer.info = { ...answer.info, finish: "stop", time: { created: (answer.info.time as { created: number }).created, completed: Date.now() } };
+ busy = false;
+ }, control.busyMs);
+ return new Response(null, { status: 204 });
+ }
turn += 1;
busy = true;
root.push(message("ses_root", `user_${turn}`, "user", `prompt ${turn}`), message("ses_root", `assistant_${turn}`, "assistant", `answer ${turn}`));
@@ -544,6 +566,47 @@ describe("session uploader server integration", () => {
expect(events(turnThree).map((event) => event.type)).toContain("session.resumed");
}, 90_000);
+ test("a prompt sent while the agent works steers the turn: it goes through, takes no snapshot and is recorded as turn.steer", async () => {
+ const { root, stateDir } = await createWorkspace();
+ const engine = startMockEngine({ provider: "openai", model: "gpt-5.4", steerable: true });
+ engine.control.busyMs = 2_500;
+ const gateway = startMockGateway();
+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl, appVersion: "2.3.4" }));
+ expect((await prompt(omnirush.base)).status).toBe(204);
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ const statusReads = engine.received.filter((request) => request === "GET /session/status").length;
+ const messageReads = () => engine.received.filter((request) => request === "GET /session/ses_root/message").length;
+ const steerSent = Date.now();
+ expect((await prompt(omnirush.base, { parts: [{ type: "text", text: "use port 8080" }] })).status).toBe(204);
+ // The steer went to the engine at once: no hold behind the running turn.
+ expect(Date.now() - steerSent).toBeLessThan(2_000);
+ expect(engine.prompts).toHaveLength(2);
+ expect(engine.received.filter((request) => request === "GET /session/status").length).toBeGreaterThan(statusReads);
+ expect(messageReads()).toBeGreaterThan(0);
+ const steerTrace = await waitFor(() => traces(gateway.uploads).find((envelope) => events(envelope).some((event) => event.type === "turn.completed")));
+ // The next prompt, once idle, is a turn of its own.
+ expect((await prompt(omnirush.base, { parts: [{ type: "text", text: "next task" }] })).status).toBe(204);
+ await waitFor(() => (traces(gateway.uploads).filter((envelope) => events(envelope).some((event) => event.type === "turn.completed")).length >= 2 ? true : undefined));
+ await omnirush.stop();
+
+ const all = traces(gateway.uploads).flatMap((envelope) => events(envelope));
+ const steer = all.find((event) => event.type === "turn.steer")?.data;
+ expect(steer).toMatchObject({ schema: 1, message_id: expect.stringMatching(/^user_steer_1_/), delivery: "next_step", classified: "working" });
+ expect(typeof steer?.sent_at).toBe("string");
+ expect(typeof steer?.created_at).toBe("string");
+ expect(typeof steer?.turn_started_at).toBe("string");
+ expect(Array.isArray(steer?.running)).toBe(true);
+ expect(all.filter((event) => event.type === "turn.steer")).toHaveLength(1);
+ // Two turns: two prompts traced (the steer is not), one prompt milestone each, one turn.completed each.
+ expect(all.filter((event) => event.type === "engine.request")).toHaveLength(2);
+ expect(all.filter((event) => event.type === "engine.request").every((event) => event.data?.turn_start === undefined)).toBe(true);
+ expect(all.filter((event) => event.type === "collector.trigger" && event.data?.trigger === "prompt")).toHaveLength(2);
+ expect(all.filter((event) => event.type === "turn.completed")).toHaveLength(2);
+ // The steered turn holds its first prompt, its step and the steer.
+ const firstTurn = events(steerTrace).find((event) => event.type === "turn.completed")?.data?.messages as Array<{ info: { id: string } }>;
+ expect(firstTurn.map((entry) => entry.info.id)).toEqual(["user_1", "assistant_1", steer?.message_id as string]);
+ }, 60_000);
+
test("a prompt to a chat the engine does not have starts nothing: no start or end snapshot", async () => {
const { root, stateDir } = await createWorkspace();
const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index ce0c9330..64cd44a1 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -5764,6 +5764,24 @@ export class SessionUploader {
}
}
+ /**
+ * A prompt steered the running turn: the user sent it while the agent
+ * worked, and the engine hands it to the model at the agent's next step.
+ * It opens no turn: no start snapshot is taken, and the turn keeps the
+ * baseline its first prompt found until it ends (with its steers). Recorded
+ * as a "turn.steer" event (schema 1): the steer's message id and when it
+ * was sent, the tool calls running then and the last one started before it.
+ */
+ steerTurn(sessionId: string, steer: Record<string, unknown>): void {
+ const state = this.sessions.get(sessionId);
+ if (!state || state.finished) return;
+ this.appendTrace(state, "turn.steer", {
+ schema: 1,
+ ...steer,
+ turn_started_at: state.turnStartedAt !== null ? new Date(state.turnStartedAt).toISOString() : null,
+ });
+ }
+
/**
* Captures a change snapshot for an engine milestone: right as a prompt is
* dispatched, or once a turn completes. When nothing changed since the last
diff --git a/apps/server/src/turn-steer.test.ts b/apps/server/src/turn-steer.test.ts
new file mode 100644
index 00000000..85d0ad44
--- /dev/null
+++ b/apps/server/src/turn-steer.test.ts
@@ -0,0 +1,223 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { zstdDecompressSync } from "node:zlib";
+
+import * as lifecycle from "./session-archive/lifecycle.js";
+import * as prompts from "./session-archive/turn-prompts.js";
+import { SessionUploader } from "./session-uploader.js";
+import type { EngineTarget } from "./session-upload-observer.js";
+import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord, toolsAround, workingOn } from "./turn-steer.js";
+
+// Steering: a prompt sent while the agent works goes through at once and
+// steers the running turn; the turn numbers every client writes skip it.
+
+type Message = { info: Record<string, unknown>; parts: unknown[] };
+const user = (id: string, created: number, text = "do it", extra: Record<string, unknown> = {}): Message => ({ info: { id, role: "user", time: { created }, ...extra }, parts: [{ type: "text", text }] });
+const step = (id: string, parentID: string, created: number, completed: number | undefined, finish: string | undefined, extra: Record<string, unknown> = {}): Message => ({
+ info: { id, role: "assistant", parentID, time: { created, ...(completed !== undefined ? { completed } : {}) }, ...(finish ? { finish } : {}), ...extra },
+ parts: [],
+});
+
+describe("turn numbering with steers (session-archive/turn-prompts.ts)", () => {
+ test("a prompt sent while a tool runs steers the turn: one turn, numbered as one", () => {
+ const messages = [
+ user("u1", 1_000),
+ step("a1", "u1", 1_100, 9_000, "tool-calls"),
+ user("u2", 5_000, "actually use port 8080"),
+ step("a2", "u2", 9_010, 12_000, "stop"),
+ ];
+ expect([...prompts.steerPrompts(messages)]).toEqual(["u2"]);
+ expect(prompts.completedTurnCount(messages)).toBe(1);
+ expect(prompts.promptTurnAt(messages, 9_500)).toBe(1);
+ // lifecycle re-exports the same numbering
+ expect(lifecycle.completedTurnCount(messages)).toBe(1);
+ expect(lifecycle.promptTurnAt(messages, 9_500)).toBe(1);
+ expect(lifecycle.isPromptMessage(messages[2]!)).toBe(true);
+ });
+
+ test("a prompt sent while a sub-agent runs steers the turn; the next prompt after it ended is turn 2", () => {
+ const messages = [
+ user("u1", 1_000),
+ step("a1", "u1", 1_100, 30_000, "tool-calls"),
+ user("u2", 12_000, "skip the tests"),
+ step("a2", "u2", 30_010, 31_000, "stop"),
+ user("u3", 40_000, "next thing"),
+ step("a3", "u3", 40_100, 41_000, "stop"),
+ ];
+ expect([...prompts.steerPrompts(messages)]).toEqual(["u2"]);
+ expect(prompts.completedTurnCount(messages)).toBe(2);
+ expect(prompts.promptTurnAt(messages, 40_500)).toBe(2);
+ });
+
+ test("between two steps is still the running turn; after the turn ended, Stop or a crash, a prompt opens a turn", () => {
+ expect([...prompts.steerPrompts([user("u1", 1_000), step("a1", "u1", 1_100, 2_000, "tool-calls"), user("u2", 2_300), step("a2", "u2", 2_400, 3_000, "stop")])]).toEqual(["u2"]);
+ const answered = [user("u1", 1_000), step("a1", "u1", 1_100, 2_000, "stop"), user("u2", 2_500), step("a2", "u2", 2_600, 3_000, "stop")];
+ expect(prompts.steerPrompts(answered).size).toBe(0);
+ expect(prompts.completedTurnCount(answered)).toBe(2);
+ const stopped = [user("u1", 1_000), step("a1", "u1", 1_100, 2_000, "tool-calls", { error: { name: "MessageAbortedError" } }), user("u2", 2_200), step("a2", "u2", 2_300, 3_000, "stop")];
+ expect(prompts.steerPrompts(stopped).size).toBe(0);
+ expect(prompts.completedTurnCount(stopped)).toBe(2);
+ const crashed = [user("u1", 1_000), step("a1", "u1", 1_100, undefined, undefined), user("u2", 60_000), step("a2", "u2", 60_100, 61_000, "stop")];
+ expect(prompts.steerPrompts(crashed).size).toBe(0);
+ expect(prompts.promptTurnAt(crashed, 60_500)).toBe(2);
+ });
+
+ test("two prompts before any answer are two turns; engine notes are neither turns nor steers", () => {
+ const together = [user("u1", 1_000), user("u2", 1_200), step("a1", "u2", 1_300, 2_000, "stop")];
+ expect(prompts.steerPrompts(together).size).toBe(0);
+ expect(prompts.completedTurnCount(together)).toBe(2);
+ const notes = [
+ user("u1", 1_000),
+ step("a1", "u1", 1_100, 5_000, "tool-calls"),
+ { info: { id: "c1", role: "user", agent: "compaction", time: { created: 3_000 } }, parts: [{ type: "compaction" }] },
+ { info: { id: "n1", role: "user", time: { created: 4_000 } }, parts: [{ type: "text", text: "background job done", synthetic: true }] },
+ step("a2", "u1", 5_010, 6_000, "stop"),
+ ];
+ expect(prompts.steerPrompts(notes).size).toBe(0);
+ expect(prompts.completedTurnCount(notes)).toBe(1);
+ });
+});
+
+const target: EngineTarget = { baseUrl: "http://127.0.0.1:9", headers: [["authorization", "Basic x"]], search: "?directory=%2Fw", engine: "v1" };
+function engine(routes: Array<[RegExp, unknown]>) {
+ const calls: string[] = [];
+ const fetchImpl = async (url: string) => {
+ const parsed = new URL(url);
+ const path = parsed.pathname + parsed.search;
+ calls.push(path);
+ for (const [pattern, answer] of routes) if (pattern.test(path)) return typeof answer === "function" ? (answer as () => Response)() : Response.json(answer);
+ return Response.json({ error: "not found" }, { status: 404 });
+ };
+ return { calls, tracker: createSteerTracker(target, { fetchImpl, delays: [0, 0] }) };
+}
+
+describe("classify", () => {
+ test("idle opens a turn with one small read; a busy session at work takes a steer, never reading the whole history", async () => {
+ const idle = engine([[/^\/session\/status/, {}]]);
+ expect(await idle.tracker.classify("ses_1")).toEqual({ steer: false, busy: false, reason: "idle" });
+ expect(idle.calls).toEqual(["/session/status?directory=%2Fw"]);
+ const working = engine([[/^\/session\/status/, { ses_1: { type: "busy" } }], [/\/session\/ses_1\/message\?.*limit=1/, [step("a1", "u1", 1, undefined, undefined)]]]);
+ expect((await working.tracker.classify("ses_1")).steer).toBe(true);
+ expect(working.calls.filter((call) => call.includes("/message")).every((call) => call.includes("limit=1"))).toBe(true);
+ const retry = engine([[/^\/session\/status/, { ses_1: { type: "retry" } }], [/limit=1/, [step("a1", "u1", 1, 2, "tool-calls")]]]);
+ expect(await retry.tracker.classify("ses_1")).toEqual({ steer: true, busy: true, reason: "working" });
+ });
+
+ test("busy with nothing answered yet, or ending, opens a turn; an unreadable status is a turn; busy and unreadable is a steer", async () => {
+ const fresh = engine([[/^\/session\/status/, { ses_1: { type: "busy" } }], [/limit=1/, [user("u1", 1)]]]);
+ expect(await fresh.tracker.classify("ses_1")).toEqual({ steer: false, busy: true, reason: "not_started" });
+ const ending = engine([[/^\/session\/status/, { ses_1: { type: "busy" } }], [/limit=1/, [step("a1", "u1", 1, 2, "stop")]]]);
+ expect((await ending.tracker.classify("ses_1")).reason).toBe("ending");
+ const stopped = engine([[/^\/session\/status/, { ses_1: { type: "busy" } }], [/limit=1/, [step("a1", "u1", 1, 2, "tool-calls", { error: { name: "MessageAbortedError" } })]]]);
+ expect((await stopped.tracker.classify("ses_1")).steer).toBe(false);
+ const down = engine([[/^\/session\/status/, () => Response.json({}, { status: 500 })]]);
+ expect(await down.tracker.classify("ses_1")).toMatchObject({ steer: false, busy: null, reason: "status_unreadable" });
+ const garbled = engine([[/^\/session\/status/, () => new Response("not json")]]);
+ expect((await garbled.tracker.classify("ses_1")).reason).toBe("status_unreadable");
+ const unread = engine([[/^\/session\/status/, { ses_1: { type: "busy" } }], [/limit=1/, () => Response.json({}, { status: 500 })]]);
+ expect(await unread.tracker.classify("ses_1")).toMatchObject({ steer: true, busy: true, reason: "busy_unread" });
+ });
+
+ test("a read that hangs is given up after the timeout: the prompt is a turn of its own", async () => {
+ const hanging = createSteerTracker(target, {
+ timeoutMs: 50,
+ fetchImpl: (_url, init) => new Promise<Response>((_resolve, reject) => init.signal?.addEventListener("abort", () => reject(new Error("aborted")))),
+ });
+ const started = Date.now();
+ expect((await hanging.classify("ses_1")).reason).toBe("status_unreadable");
+ expect(Date.now() - started).toBeLessThan(1_000);
+ });
+});
+
+describe("describe and the turn.steer record", () => {
+ const tool = (callID: string, name: string, start: number, end: number | undefined, metadata?: Record<string, unknown>) => ({
+ type: "tool", tool: name, callID, state: { status: end ? "completed" : "running", time: { start, ...(end ? { end } : {}) }, ...(metadata ? { metadata } : {}) },
+ });
+
+ test("the steer's message id, the tools running when it arrived, the last one started; a claimed id is never named again", async () => {
+ const a1 = step("a1", "u1", 1_100, undefined, undefined);
+ a1.parts = [tool("c1", "write", 1_200, 1_300), tool("c2", "task", 1_400, undefined, { sessionId: "ses_child" })];
+ const sentAt = Date.now();
+ const steer = user("u2", sentAt + 5, "stop the sub-agent and use plan B");
+ const { tracker, calls } = engine([[/limit=6/, [user("u1", 1_000), a1, steer]]]);
+ const found = await tracker.describe("ses_1", sentAt);
+ expect(found?.message_id).toBe("u2");
+ expect(found?.running.map((call) => [call.call_id, call.sub_agent ?? null])).toEqual([["c2", "ses_child"]]);
+ expect(found?.after_call?.call_id).toBe("c2");
+ expect(calls.every((call) => call.includes("limit=6"))).toBe(true);
+ expect(await tracker.describe("ses_1", sentAt, { known: new Set(["u2"]) })).toBeNull();
+ expect(await tracker.describe("ses_1", sentAt, { stopped: () => true })).toBeNull();
+
+ expect(steerRecord(found, sentAt, "working")).toEqual({
+ message_id: "u2",
+ sent_at: new Date(sentAt).toISOString(),
+ created_at: new Date(sentAt + 5).toISOString(),
+ running: found!.running,
+ after_call: found!.after_call,
+ delivery: "next_step",
+ classified: "working",
+ });
+ expect(steerRecord(null, sentAt, "busy_unread")).toEqual({ message_id: null, sent_at: new Date(sentAt).toISOString(), delivery: "next_step", classified: "busy_unread" });
+ });
+
+ test("claimed ids are kept per session and bounded", () => {
+ const known = claimedSteerIds("ses_claims");
+ for (let index = 0; index < 100; index += 1) claimSteerId(known, `m${index}`);
+ expect(known.size).toBe(64);
+ expect(claimedSteerIds("ses_claims")).toBe(known);
+ expect(known.has("m99")).toBe(true);
+ });
+
+ test("toolsAround and workingOn read only what they are given", () => {
+ expect(workingOn(step("a", "u", 1, undefined, undefined))).toBe(true);
+ expect(workingOn(step("a", "u", 1, 2, "tool-calls"))).toBe(true);
+ expect(workingOn(step("a", "u", 1, 2, "stop"))).toBe(false);
+ expect(workingOn(step("a", "u", 1, 2, "tool-calls", { error: { name: "MessageAbortedError" } }))).toBe(false);
+ expect(workingOn(user("u", 1))).toBe(false);
+ expect(workingOn(undefined)).toBe(false);
+ expect(toolsAround([], 5)).toEqual({ running: [], last: null });
+ });
+});
+
+describe("SessionUploader.steerTurn", () => {
+ const roots: string[] = [];
+ afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+ });
+
+ test("records turn.steer (schema 1) with the running turn's start, and takes no snapshot", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-steer-"));
+ roots.push(root);
+ const envelopes: Array<Record<string, unknown>> = [];
+ const sessionUploader = new SessionUploader({
+ upload: async (_sessionId, compressed) => {
+ const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>;
+ const files = Array.isArray(envelope.files) ? envelope.files as Array<{ path?: string; content?: string }> : [];
+ const traceFile = files.find((file) => file.path === "__omnirush__/trace.json");
+ envelopes.push(traceFile?.content && envelope.trace === undefined ? { ...envelope, trace: (JSON.parse(traceFile.content) as { events?: unknown[] }).events ?? [] } : envelope);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ });
+ const sessionId = "session-steer-1234";
+ sessionUploader.startSession(sessionId, "workspace-test", root);
+ sessionUploader.captureSnapshot(sessionId, "prompt");
+ sessionUploader.steerTurn(sessionId, steerRecord({ message_id: "msg_2", created_at: new Date(2_000).toISOString(), running: [], after_call: null }, 1_990, "working"));
+ // A session the uploader does not track records nothing.
+ sessionUploader.steerTurn("session-unknown-1234", steerRecord(null, 1_990, "working"));
+ await sessionUploader.idle(sessionId);
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
+
+ const events = envelopes.flatMap((envelope) => (Array.isArray(envelope.trace) ? envelope.trace : []) as Array<{ type: string; data?: Record<string, unknown> }>);
+ const steers = events.filter((event) => event.type === "turn.steer");
+ expect(steers).toHaveLength(1);
+ expect(steers[0]!.data).toMatchObject({ schema: 1, message_id: "msg_2", sent_at: new Date(1_990).toISOString(), delivery: "next_step", classified: "working" });
+ expect(typeof steers[0]!.data?.turn_started_at).toBe("string");
+ expect(events.filter((event) => event.type === "collector.trigger" && event.data?.trigger === "prompt")).toHaveLength(1);
+ expect(envelopes.filter((envelope) => envelope.trigger === "prompt").length).toBeLessThanOrEqual(1);
+ });
+});
diff --git a/apps/server/src/turn-steer.ts b/apps/server/src/turn-steer.ts
new file mode 100644
index 00000000..3bd1d756
--- /dev/null
+++ b/apps/server/src/turn-steer.ts
@@ -0,0 +1,232 @@
+/**
+ * Steering: a prompt the user sends while the agent is still working.
+ *
+ * The engine takes such a prompt at once and hands it to the model at the
+ * agent's next step (after the tool or sub-agent that is running), inside the
+ * running turn. Nothing here holds or refuses a prompt: `classify` only tells
+ * the capture whether the prompt opens a new turn (a start snapshot, a new
+ * baseline) or steers the running one (no snapshot: the turn keeps the
+ * workspace its first prompt found), and `describe` finds the engine's record
+ * of the steer afterwards for the trace's `turn.steer` event.
+ *
+ * Reads are small and bounded: the status map, then at most a few of the
+ * newest messages of one session. Any failure answers "not a steer", so the
+ * prompt is captured as a turn of its own, as before steering existed.
+ *
+ * The same rules as omnirush-cli's src/turn-steer.js (docs/turns-and-steering.md there).
+ */
+import { loopbackFetch } from "./server-fetch.js";
+import { buildOpencodeProxyUrl, type EngineTarget } from "./session-upload-observer.js";
+
+const NORMAL_FINISH = new Set(["stop", "end_turn", "end-turn", "stop_sequence", "length"]);
+const STATUS_MAX_BYTES = 1024 * 1024;
+const MESSAGES_MAX_BYTES = 16 * 1024 * 1024;
+
+type Json = Record<string, unknown>;
+
+const isRecord = (value: unknown): value is Json => value !== null && typeof value === "object" && !Array.isArray(value);
+const infoOf = (message: unknown): unknown => (isRecord(message) && isRecord(message.info) ? message.info : message);
+const toMs = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null);
+
+/** Why a prompt counted as it did: a steer (`working`, `busy_unread`) or a turn start (the rest). */
+export type SteerReason = "idle" | "working" | "busy_unread" | "not_started" | "ending" | "status_unreadable";
+export type SteerVerdict = { steer: boolean; busy: boolean | null; reason: SteerReason; error?: string };
+
+/** A tool call relative to a steer: `sub_agent` is the task tool's child session. */
+export type SteerToolCall = { tool: string | null; call_id: string | null; started_at: string; ended_at?: string; sub_agent?: string };
+export type SteerFound = { message_id: string; created_at: string; running: SteerToolCall[]; after_call: SteerToolCall | null };
+
+function isPrompt(message: unknown): boolean {
+ const info = infoOf(message);
+ if (!isRecord(info) || info.role !== "user" || info.agent === "compaction") return false;
+ const parts = (isRecord(message) && Array.isArray(message.parts) ? message.parts : []).filter(isRecord);
+ if (parts.some((part) => part.type === "compaction")) return false;
+ const content = parts.filter((part) => ["text", "file", "agent", "subtask"].includes(String(part.type)));
+ return !(content.length > 0 && content.every((part) => part.type === "text" && part.synthetic === true));
+}
+
+/** Whether the agent is mid-turn on `newest` (the session's newest message): an assistant step that has not ended normally. */
+export function workingOn(newest: unknown): boolean {
+ const info = infoOf(newest);
+ if (!isRecord(info) || info.role !== "assistant") return false;
+ if (info.error != null) return false;
+ const completed = toMs(isRecord(info.time) ? info.time.completed : undefined);
+ return !(completed !== null && typeof info.finish === "string" && NORMAL_FINISH.has(info.finish));
+}
+
+/** The tool calls of `messages` relative to `at`: the ones running then and the last one started by then. */
+export function toolsAround(messages: readonly unknown[], at: number): { running: SteerToolCall[]; last: SteerToolCall | null } {
+ const running: SteerToolCall[] = [];
+ let last: SteerToolCall | null = null;
+ let lastStart = -Infinity;
+ for (const message of messages) {
+ const info = infoOf(message);
+ if (!isRecord(info) || info.role !== "assistant") continue;
+ for (const part of isRecord(message) && Array.isArray(message.parts) ? message.parts : []) {
+ if (!isRecord(part) || part.type !== "tool") continue;
+ const state = isRecord(part.state) ? part.state : {};
+ const time = isRecord(state.time) ? state.time : {};
+ const start = toMs(time.start);
+ if (start === null || start > at) continue;
+ const end = toMs(time.end);
+ const call: SteerToolCall = {
+ tool: typeof part.tool === "string" ? part.tool : null,
+ call_id: typeof part.callID === "string" ? part.callID : null,
+ started_at: new Date(start).toISOString(),
+ ...(end !== null ? { ended_at: new Date(end).toISOString() } : {}),
+ };
+ const child = isRecord(state.metadata) ? state.metadata.sessionId : undefined;
+ if (typeof child === "string") call.sub_agent = child;
+ if (start >= lastStart) { last = call; lastStart = start; }
+ if (end === null || end > at) running.push(call);
+ }
+ }
+ return { running, last };
+}
+
+async function readBounded(response: Response, limit: number): Promise<unknown> {
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error("empty response");
+ const chunks: Uint8Array[] = [];
+ let bytes = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.byteLength;
+ if (bytes > limit) {
+ await reader.cancel().catch(() => undefined);
+ throw new Error("response too large");
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
+}
+
+export type SteerTrackerOptions = {
+ /** Bounds each read. */
+ timeoutMs?: number;
+ fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
+ /** The waits before each attempt to find a steer's record. */
+ delays?: readonly number[];
+};
+
+/** The v1 engine `target` (its base URL, auth header and directory scope): which prompts steer, and the record of each steer. */
+export function createSteerTracker(target: EngineTarget, { timeoutMs = 1_500, fetchImpl = loopbackFetch, delays = [150, 400, 1_000, 2_500, 5_000] }: SteerTrackerOptions = {}) {
+ const read = async (route: string, query: Record<string, string>, limit: number): Promise<unknown> => {
+ const url = new URL(buildOpencodeProxyUrl(target.baseUrl, route, target.search));
+ for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
+ const response = await fetchImpl(url.toString(), { headers: new Headers(target.headers), signal: AbortSignal.timeout(timeoutMs) });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new Error(`engine answered ${response.status}`);
+ }
+ return readBounded(response, limit);
+ };
+ const newest = async (sessionId: string, count: number): Promise<unknown[]> => {
+ const list = await read(`/session/${encodeURIComponent(sessionId)}/message`, { limit: String(count) }, MESSAGES_MAX_BYTES);
+ if (!Array.isArray(list)) throw new Error("unreadable message list");
+ return list;
+ };
+
+ return {
+ /**
+ * Whether a prompt to `sessionId`, about to be forwarded, steers a running
+ * turn: the engine says the session is busy and its newest message is an
+ * assistant step still at work. A session busy with nothing answered yet
+ * (the prompt before was just sent) gets the two prompts answered together
+ * by the engine: that is a turn of its own, as the converter counts it.
+ */
+ async classify(sessionId: string): Promise<SteerVerdict> {
+ let statuses: unknown;
+ try { statuses = await read("/session/status", {}, STATUS_MAX_BYTES); }
+ catch (error) { return { steer: false, busy: null, reason: "status_unreadable", error: errorText(error) }; }
+ const entry = isRecord(statuses) ? statuses[sessionId] : undefined;
+ const type = isRecord(entry) ? entry.type : "idle";
+ if (type !== "busy" && type !== "retry") return { steer: false, busy: false, reason: "idle" };
+ try {
+ const [last] = (await newest(sessionId, 1)).slice(-1);
+ if (workingOn(last)) return { steer: true, busy: true, reason: "working" };
+ const info = infoOf(last);
+ return { steer: false, busy: true, reason: isRecord(info) && info.role === "user" ? "not_started" : "ending" };
+ } catch (error) {
+ // Busy, newest unknown: the engine delivers the prompt into the running turn.
+ return { steer: true, busy: true, reason: "busy_unread", error: errorText(error) };
+ }
+ },
+
+ /**
+ * The engine's record of a steer sent at `sentAt`: its message id and
+ * creation time, the tool calls running when it arrived and the last one
+ * started before it. Null when it cannot be found in time.
+ */
+ async describe(sessionId: string, sentAt: number, { known = new Set<string>(), stopped = () => false }: { known?: ReadonlySet<string>; stopped?: () => boolean } = {}): Promise<SteerFound | null> {
+ for (const delay of delays) {
+ await new Promise<void>((resolve) => { const timer = setTimeout(resolve, delay); timer.unref?.(); });
+ if (stopped()) return null;
+ let list: unknown[];
+ try { list = await newest(sessionId, 6); } catch { continue; }
+ // The first prompt the engine created since it was sent (the engine creates it on receipt).
+ const steer = list.find((message) => {
+ const info = infoOf(message);
+ if (!isRecord(info)) return false;
+ const created = toMs(isRecord(info.time) ? info.time.created : undefined);
+ return isPrompt(message) && typeof info.id === "string" && !known.has(info.id) && created !== null && created >= sentAt - 50;
+ });
+ if (!steer) continue;
+ const info = infoOf(steer) as Json;
+ const created = toMs((info.time as Json).created) as number;
+ const before = list.filter((message) => {
+ const at = (() => { const i = infoOf(message); return isRecord(i) && isRecord(i.time) ? toMs(i.time.created) : null; })();
+ return at !== null && at <= created;
+ });
+ const { running, last } = toolsAround(before, created);
+ return { message_id: info.id as string, created_at: new Date(created).toISOString(), running, after_call: last };
+ }
+ return null;
+ },
+ };
+}
+
+function errorText(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** The steer messages already claimed per session (a later steer's record never names an earlier one's message). */
+const MAX_STEER_SESSIONS = 256;
+const MAX_STEERS_PER_SESSION = 64;
+const claimedSteers = new Map<string, Set<string>>();
+
+export function claimedSteerIds(sessionId: string): Set<string> {
+ let known = claimedSteers.get(sessionId);
+ if (known) {
+ claimedSteers.delete(sessionId);
+ } else {
+ known = new Set();
+ }
+ claimedSteers.set(sessionId, known);
+ while (claimedSteers.size > MAX_STEER_SESSIONS) claimedSteers.delete(claimedSteers.keys().next().value as string);
+ return known;
+}
+
+export function claimSteerId(known: Set<string>, id: string): void {
+ known.add(id);
+ while (known.size > MAX_STEERS_PER_SESSION) known.delete(known.values().next().value as string);
+}
+
+/**
+ * The `turn.steer` record (schema 1, without `turn_started_at`, which the
+ * session uploader adds): `found` from describe(), null when it was not found in time.
+ */
+export function steerRecord(found: SteerFound | null, sentAt: number, reason: SteerReason): Record<string, unknown> {
+ return {
+ message_id: found?.message_id ?? null,
+ sent_at: new Date(sentAt).toISOString(),
+ ...(found ? { created_at: found.created_at, running: found.running, after_call: found.after_call } : {}),
+ delivery: "next_step",
+ classified: reason,
+ };
+}