Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: automatic compaction and steering on the new engine

ogsamrataad9706fc67f
diff --git a/apps/server/src/auto-compact-engine.ts b/apps/server/src/auto-compact-engine.ts
index 62efaee9..3b87fd02 100644
--- a/apps/server/src/auto-compact-engine.ts
+++ b/apps/server/src/auto-compact-engine.ts
@@ -7,6 +7,7 @@ import { buildOpencodeProxyUrl, projectArchiveEngineReads, type EngineTarget } f
import { loopbackFetch } from "./server-fetch.js";
import type { TraceCapabilities } from "./session-uploader.js";
import { assertEngineStartedWithinLock, assertProviderAllowed } from "./provider-lock.js";
+import { v1View } from "./engine-v2-view.js";
/** How long an answer of the server counts for an ordinary prompt; a due compaction asks again. */
export const POLICY_MAX_AGE_MS = 60_000;
@@ -14,8 +15,9 @@ const FRESH_WAIT_MS = 4_000;
type Fetch = (input: string, init: RequestInit) => Promise<Response>;
-/** The v1 engine `target` for `sessionId`. */
+/** The engine `target` for `sessionId` (a 2.x engine: opencodeV2AutoCompactEngine). */
export function desktopAutoCompactEngine(target: EngineTarget, sessionId: string, fetchImpl: Fetch = loopbackFetch): AutoCompactEngine {
+ if (target.engine === "v2") return opencodeV2AutoCompactEngine(target, sessionId, fetchImpl);
const reads = projectArchiveEngineReads(target, sessionId);
return {
messages: () => reads.messages(),
@@ -65,6 +67,63 @@ export function desktopAutoCompactEngine(target: EngineTarget, sessionId: string
};
}
+/**
+ * The same calls on the 2.x engine (the CLI's way): its running sessions,
+ * POST /api/session/:id/compact (the engine summarizes on the chat's own
+ * model; the call waits until the compaction message it created completed or
+ * failed), /interrupt. The chat's messages go to the shared module as their
+ * 1.x view (engine-v2-view.ts). No message delete: a compaction still queued
+ * is cancelled from the inbox; one already delivered is the engine's record and stays.
+ */
+function opencodeV2AutoCompactEngine(target: EngineTarget, sessionId: string, fetchImpl: Fetch): AutoCompactEngine {
+ const reads = projectArchiveEngineReads(target, sessionId);
+ const session = `/api/session/${encodeURIComponent(sessionId)}`;
+ const call = (path: string, init: RequestInit) => fetchImpl(buildOpencodeProxyUrl(target.baseUrl, path, target.search), { ...init, headers: new Headers(target.headers) });
+ return {
+ messages: async () => { const list = await reads.messages(); return Array.isArray(list) ? v1View(list, sessionId) : list; },
+ session: () => reads.session(),
+ async busy() {
+ const response = await call("/api/session/active", { signal: AbortSignal.timeout(5_000) });
+ if (!response.ok) { await response.body?.cancel().catch(() => undefined); return null; }
+ const payload = (await response.json()) as { data?: unknown };
+ const active = payload && typeof payload === "object" && "data" in payload ? payload.data : payload;
+ return Boolean(active && typeof active === "object" && Object.hasOwn(active, sessionId));
+ },
+ async summarize(model: ModelRef, signal: AbortSignal) {
+ assertProviderAllowed(model.providerID);
+ assertEngineStartedWithinLock(target.baseUrl, "POST", `${session}/compact`);
+ const response = await fetchImpl(buildOpencodeProxyUrl(target.baseUrl, `${session}/compact`, target.search), {
+ method: "POST", headers: (() => { const headers = new Headers(target.headers); headers.set("content-type", "application/json"); return headers; })(), body: "{}", signal,
+ });
+ const text = await response.text().catch(() => "");
+ if (!response.ok) throw new Error(`compact answered ${response.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
+ let id: string | null = null;
+ try { id = (JSON.parse(text) as { data?: { id?: string } }).data?.id ?? null; } catch { id = null; }
+ if (!id) return;
+ // The compaction message has the inbox item's id: done once it no longer runs.
+ while (!signal.aborted) {
+ const found = await call(`${session}/message?type=compaction&order=desc&limit=20`, { signal: AbortSignal.timeout(10_000) })
+ .then(async (answer) => (answer.ok ? ((await answer.json()) as { data?: unknown }).data : null)).catch(() => null);
+ const message = Array.isArray(found) ? (found as { id?: string; status?: string }[]).find((item) => item?.id === id) : undefined;
+ if (message && message.status !== "running") {
+ if (message.status !== "completed") throw new Error(`compaction ${message.status}`);
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ throw new Error("compaction stopped");
+ },
+ async removeMessage(messageID: string) {
+ const response = await call(`${session}/inbox/${encodeURIComponent(messageID.replace(/_summary$/, ""))}`, { method: "DELETE", signal: AbortSignal.timeout(10_000) });
+ await response.body?.cancel().catch(() => undefined);
+ },
+ async abort() {
+ const response = await call(`${session}/interrupt`, { method: "POST", signal: AbortSignal.timeout(10_000) });
+ await response.body?.cancel().catch(() => undefined);
+ },
+ };
+}
+
/**
* The server's policy through the broker's capabilities cache: at most
* POLICY_MAX_AGE_MS old for an ordinary prompt, asked again when `fresh`
diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.ts
index 4da618a1..e86ae537 100644
--- a/apps/server/src/engine-v2-next.test.ts
+++ b/apps/server/src/engine-v2-next.test.ts
@@ -117,3 +117,30 @@ test("MCP on the 2.x engine: the gate lists the server list's ids, entries stay
// Not on the gate: left out.
expect(await desiredV2Mcp(dir, root, engineEnv, [])).toEqual({});
}));
+
+test("steering and automatic compaction use the 2.x engine's routes", async () => {
+ const { createSteerTracker } = await import("./turn-steer.js");
+ const { desktopAutoCompactEngine } = await import("./auto-compact-engine.js");
+ const calls: string[] = [];
+ let last: unknown = { type: "assistant", id: "msg_a" };
+ const fetchImpl = async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input));
+ calls.push(`${init?.method ?? "GET"} ${url.pathname}`);
+ if (url.pathname === "/api/session/active") return Response.json({ data: { ses_busy: {} } });
+ if (url.pathname.endsWith("/message")) return Response.json({ data: [last] });
+ if (url.pathname.endsWith("/compact")) return Response.json({ data: { id: "cmp_1" } });
+ return new Response(null, { status: 204 });
+ };
+ const target = { baseUrl: "http://127.0.0.1:1", headers: [], search: "", engine: "v2" as const };
+ const tracker = createSteerTracker(target, { fetchImpl: fetchImpl as typeof fetch });
+ expect(await tracker.classify("ses_idle")).toMatchObject({ steer: false, reason: "idle" });
+ expect(await tracker.classify("ses_busy")).toMatchObject({ steer: true, reason: "working" });
+ last = { type: "compaction" };
+ expect(await tracker.classify("ses_busy")).toMatchObject({ steer: false, reason: "compacting" });
+ const engine = desktopAutoCompactEngine(target, "ses_busy", fetchImpl as never);
+ expect(await engine.busy()).toBe(true);
+ await engine.removeMessage("cmp_1_summary");
+ await engine.abort();
+ expect(calls).toContain("DELETE /api/session/ses_busy/inbox/cmp_1");
+ expect(calls).toContain("POST /api/session/ses_busy/interrupt");
+});
diff --git a/apps/server/src/engine-v2-view.ts b/apps/server/src/engine-v2-view.ts
new file mode 100644
index 00000000..26989b18
--- /dev/null
+++ b/apps/server/src/engine-v2-view.ts
@@ -0,0 +1,134 @@
+// The 2.x engine's stored messages as the 1.x `{info, parts}` shape, for the
+// capture's derived facts only (turn files, files used, turn writers, turn
+// outcome, the turn's model, settle checks). Uploads always carry the raw
+// 2.x messages; nothing here is ever sent.
+//
+// Tool names and input keys stay as the 2.x engine wrote them (`shell`,
+// `patch`, `read {path}`): the shared modules know both generations' names.
+// shortcut: a copy of the CLI's capture/engine-v2-view.ts; becomes the shared engine-v2-messages reader (PARITY) when WS2 lands it.
+
+type Rec = Record<string, unknown>;
+
+const isRecord = (value: unknown): value is Rec => typeof value === "object" && value !== null && !Array.isArray(value);
+
+/** Whether `messages` are 2.x stored messages (a top-level `type`, no `info`). */
+export function isV2Messages(messages: readonly unknown[]): boolean {
+ return messages.some((message) => isRecord(message) && typeof message.type === "string" && !isRecord(message.info));
+}
+
+function toolOutput(state: Rec): string {
+ const content = Array.isArray(state.content) ? state.content : [];
+ return content.filter((item) => isRecord(item) && item.type === "text").map((item) => String((item as Rec).text ?? "")).join("\n");
+}
+
+function toolPart(item: Rec, sessionID: string, messageID: string): Rec {
+ const state = isRecord(item.state) ? item.state : {};
+ const time = isRecord(item.time) ? item.time : {};
+ const status = state.status === "streaming" ? "pending" : state.status;
+ const files = (Array.isArray(state.content) ? state.content : []).filter((entry) => isRecord(entry) && entry.type === "file");
+ return {
+ type: "tool",
+ id: `${messageID}_${String(item.id)}`,
+ sessionID,
+ messageID,
+ tool: item.name,
+ callID: item.id,
+ state: {
+ status,
+ input: isRecord(state.input) ? state.input : {},
+ ...(status === "completed" || status === "error" ? { output: toolOutput(state) } : {}),
+ ...(isRecord(state.metadata) ? { metadata: state.metadata } : {}),
+ ...(isRecord(state.error) ? { error: String((state.error as Rec).message ?? "") } : {}),
+ ...(files.length ? { attachments: files.map((entry) => ({ type: "file", mime: (entry as Rec).mime, url: (entry as Rec).uri })) } : {}),
+ time: { start: time.ran ?? time.created, ...(time.completed !== undefined ? { end: time.completed } : {}) },
+ },
+ };
+}
+
+/** One 2.x message as `{info, parts}`; null for kinds with no 1.x counterpart (idle, agent/model switches). */
+export function v1ViewOf(message: unknown, sessionID = ""): Rec | null {
+ if (!isRecord(message) || typeof message.type !== "string") return isRecord(message) && isRecord(message.info) ? message : null;
+ const id = String(message.id ?? "");
+ const time = isRecord(message.time) ? message.time : {};
+ const base = { id, sessionID, time: { created: time.created, ...(time.completed !== undefined ? { completed: time.completed } : {}) } };
+ switch (message.type) {
+ case "user": {
+ const files = (Array.isArray(message.files) ? message.files : []).filter(isRecord).map((file) => ({ type: "file", url: file.uri, filename: file.name, mime: "" }));
+ return { info: { ...base, role: "user" }, parts: [{ type: "text", text: String(message.text ?? "") }, ...files] };
+ }
+ case "synthetic":
+ case "system":
+ case "skill":
+ return { info: { ...base, role: "user" }, parts: [{ type: "text", text: String(message.text ?? ""), synthetic: true }] };
+ case "compaction":
+ // One 2.x message is the 1.x request and its summary (auto-compact.ts reads both).
+ return { info: { ...base, role: "user" }, parts: [{ type: "compaction", auto: message.reason === "auto" }] };
+ case "assistant": {
+ const model = isRecord(message.model) ? message.model : {};
+ const parts = (Array.isArray(message.content) ? message.content : []).filter(isRecord).map((item) => {
+ if (item.type === "tool") return toolPart(item, sessionID, id);
+ return { type: item.type, text: String(item.text ?? "") };
+ });
+ if (message.finish !== undefined) parts.push({ type: "step-finish", reason: message.finish });
+ return {
+ info: {
+ ...base,
+ role: "assistant",
+ agent: message.agent,
+ modelID: model.id,
+ providerID: model.providerID,
+ ...(message.finish !== undefined ? { finish: message.finish } : {}),
+ ...(isRecord(message.error) ? { error: { name: String(message.error.type ?? "Error"), data: { message: message.error.message } } } : {}),
+ ...(isRecord(message.tokens) ? { tokens: message.tokens } : {}),
+ },
+ parts,
+ };
+ }
+ default:
+ return null;
+ }
+}
+
+/** A 2.x compaction's summary as the 1.x summary message (`summary: true`, agent compaction, its request as parent). */
+function compactionSummary(message: Rec, sessionID: string): Rec | null {
+ if (message.type !== "compaction" || message.status === "running") return null;
+ const time = isRecord(message.time) ? message.time : {};
+ const failed = message.status !== "completed";
+ return {
+ info: {
+ id: `${String(message.id)}_summary`,
+ sessionID,
+ role: "assistant",
+ summary: true,
+ agent: "compaction",
+ mode: "compaction",
+ parentID: String(message.id),
+ time: { created: time.created, ...(time.completed !== undefined ? { completed: time.completed } : failed ? {} : { completed: time.created }) },
+ ...(failed ? { error: { name: isRecord(message.error) ? String(message.error.type ?? "error") : "error" } } : {}),
+ ...(isRecord(message.tokens) ? { tokens: message.tokens } : {}),
+ },
+ parts: [{ type: "text", text: String(message.summary ?? "") }],
+ };
+}
+
+/** A message list for the shared modules: 1.x lists unchanged, 2.x lists as their 1.x view. */
+export function v1View(messages: readonly unknown[], sessionID = ""): unknown[] {
+ if (!isV2Messages(messages)) return [...messages];
+ return messages.flatMap((message) => [v1ViewOf(message, sessionID), isRecord(message) ? compactionSummary(message, sessionID) : null]).filter((message): message is Rec => message !== null);
+}
+
+/** The sub-agent sessions a 2.x turn started (its `subagent` calls' child sessions). */
+export function v2ChildSessions(messages: readonly unknown[]): string[] {
+ const ids: string[] = [];
+ for (const message of messages) {
+ if (!isRecord(message) || message.type !== "assistant" || !Array.isArray(message.content)) continue;
+ for (const item of message.content) {
+ if (!isRecord(item) || item.type !== "tool" || item.name !== "subagent" || !isRecord(item.state)) continue;
+ const metadata = isRecord(item.state.metadata) ? item.state.metadata : {};
+ const input = isRecord(item.state.input) ? item.state.input : {};
+ const id = [metadata.sessionID, metadata.sessionId, input.sessionID].find((value) => typeof value === "string" && value.startsWith("ses_"));
+ if (typeof id === "string" && !ids.includes(id)) ids.push(id);
+ }
+ }
+ return ids;
+}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 6bd9cc81..1b3c9458 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -2174,17 +2174,29 @@ export async function proxyOpencodeV2Request(input: {
? sessionId
: null;
const engine = capture && uploadedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;
+ // Automatic compaction (session-archive/auto-compact.ts), as on the 1.x engine (auto-compact-engine.ts: the 2.x calls).
+ const autoCompactor = engine && uploadedSessionId ? autoCompactorsByServer.get(input.config) : undefined;
+ if (autoCompactor && engine && uploadedSessionId) {
+ const outcome = await autoCompactor.beforePrompt(uploadedSessionId, desktopAutoCompactEngine(engine, uploadedSessionId), body)
+ .catch((error: unknown): AutoCompactOutcome => ({ action: "failed", reason: error instanceof Error ? error.message : String(error) }));
+ if (outcome.action !== "none") createServerLogger(input.config).log("info", "Automatic compaction.", { "auto_compact.action": outcome.action, "auto_compact.reason": outcome.reason ?? "", "auto_compact.turns": outcome.turns ?? -1 });
+ }
+ // Steering (turn-steer.ts): the 2.x engine delivers a prompt to a running chat into its turn; such a
+ // prompt opens no turn of its own (no start snapshot, no archive start) and is recorded as "turn.steer".
+ const steerSentAt = Date.now();
+ const turnKind = capture && uploadedSessionId && engine ? await createSteerTracker(engine).classify(uploadedSessionId) : null;
+ const steer = Boolean(turnKind?.steer && uploadedSessionId && capture?.hasSession(uploadedSessionId));
// A reopened chat's turns before this prompt: its turn numbers (uploads and box checkpoints) carry on from them.
- const turnsBefore = capture && uploadedSessionId && engine ? await turnsBeforeCapture(capture, uploadedSessionId, engine) : 0;
+ const turnsBefore = capture && uploadedSessionId && engine && !steer ? await turnsBeforeCapture(capture, uploadedSessionId, engine) : 0;
// 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.
// One pin per chat: a chat that runs in the box is not moved to this computer when its project's box is off.
const pinnedBoxWhy = promptDispatch && sessionId ? await boxServiceFor(input.config).pinnedBoxUnavailable(sessionId, input.workspace) : null;
if (pinnedBoxWhy) throw new ApiError(409, "chat_pinned_box", pinnedBoxMessage(pinnedBoxWhy));
const boxInfo = promptDispatch && sessionId
- ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine), turnsBefore, nativeModel: await promptsNativeOnlyModel(input.config, body), signal: input.request.signal })
+ ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine) && !steer, turnsBefore, nativeModel: await promptsNativeOnlyModel(input.config, body), signal: input.request.signal })
: null;
if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);
- if (capture && uploadedSessionId && engine) {
+ if (capture && uploadedSessionId && engine && !steer) {
// The turn before's background processes finish writing (at most 10 s after it ended), its project
// delta is taken (at most 5 s more, only when it ended a moment ago), then capture v2's session-start
// manifest is taken before the prompt reaches the engine (at most about 3 s).
@@ -2199,16 +2211,27 @@ export async function proxyOpencodeV2Request(input: {
capture.captureSnapshot(uploadedSessionId, "prompt");
capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);
}
- if (promptDispatch && sessionId) void pinChatCapturePolicy(input.config, capture, sessionId);
+ if (promptDispatch && sessionId && !steer) void pinChatCapturePolicy(input.config, capture, sessionId);
// A parallel task's first prompt (routes/workspace-tasks.ts): only task workspaces.
- if (input.workspace.task && promptDispatch && sessionId) {
+ if (input.workspace.task && promptDispatch && sessionId && !steer) {
await noteTaskPrompt(input.workspace, sessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));
}
if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);
const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });
// The engine has the prompt: its session status says busy from now on.
turnActivity?.promptDispatched();
- if (capture && uploadedSessionId && engine) {
+ if (capture && uploadedSessionId && engine && steer) {
+ if (response.ok) {
+ // The turn goes on (followed as before); the steer's record is found in the background.
+ capture.followSteer(uploadedSessionId, engine);
+ const reason = turnKind?.reason ?? "working";
+ const known = claimedSteerIds(uploadedSessionId);
+ void createSteerTracker(engine).describe(uploadedSessionId, steerSentAt, { known }).then((found) => {
+ if (found) claimSteerId(known, found.message_id);
+ capture.steerTurn(uploadedSessionId, steerRecord(found, steerSentAt, reason));
+ }).catch(() => capture.steerTurn(uploadedSessionId, steerRecord(null, steerSentAt, reason)));
+ }
+ } else if (capture && uploadedSessionId && engine) {
capture.recordTrace(uploadedSessionId, "engine.response", { method, path: routePath, status: response.status });
if (response.ok) capture.observeSession(uploadedSessionId, engine);
}
diff --git a/apps/server/src/session-upload-observer.ts b/apps/server/src/session-upload-observer.ts
index 2a74094f..88b97189 100644
--- a/apps/server/src/session-upload-observer.ts
+++ b/apps/server/src/session-upload-observer.ts
@@ -181,9 +181,12 @@ export function engineTarget(baseUrl: string, headers: Headers, search: string,
export function buildOpencodeProxyUrl(baseUrl: string, path: string, search: string) {
const target = new URL(baseUrl);
- const trimmedPath = path.replace(/^\/opencode/, "");
+ // A query in `path` (`/message?order=desc`) joins the target's own.
+ const [pathOnly = "", query] = path.split("?", 2);
+ const trimmedPath = pathOnly.replace(/^\/opencode/, "");
target.pathname = trimmedPath.startsWith("/") ? trimmedPath : `/${trimmedPath}`;
target.search = search;
+ if (query) for (const [key, value] of new URLSearchParams(query)) target.searchParams.set(key, value);
return target.toString();
}
diff --git a/apps/server/src/turn-steer.ts b/apps/server/src/turn-steer.ts
index fc88d872..2f3d1abf 100644
--- a/apps/server/src/turn-steer.ts
+++ b/apps/server/src/turn-steer.ts
@@ -122,6 +122,7 @@ export type SteerTrackerOptions = {
/** 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 = {}) {
+ if (target.engine === "v2") return createSteerTrackerV2(target, { timeoutMs, fetchImpl, delays });
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);
@@ -198,6 +199,70 @@ export function createSteerTracker(target: EngineTarget, { timeoutMs = 1_500, fe
};
}
+/**
+ * The same on the 2.x engine (the CLI's createSteerTrackerV2): it steers natively (a prompt to a
+ * running session is delivered into its turn), so a prompt to a session the engine lists as running
+ * steers once its turn answered anything. The record is the 2.x user message; tools are `content` items.
+ */
+function createSteerTrackerV2(target: EngineTarget, { timeoutMs, fetchImpl, delays }: Required<Pick<SteerTrackerOptions, "timeoutMs" | "fetchImpl" | "delays">>) {
+ const read = async (route: string, limit: number): Promise<unknown> => {
+ const response = await fetchImpl(buildOpencodeProxyUrl(target.baseUrl, route, target.search), { 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}`);
+ }
+ const body = await readBounded(response, limit);
+ return isRecord(body) ? body.data : null;
+ };
+ const newest = async (sessionId: string, count: number): Promise<Json[]> => {
+ const list = await read(`/api/session/${encodeURIComponent(sessionId)}/message?order=desc&limit=${count}`, MESSAGES_MAX_BYTES);
+ if (!Array.isArray(list)) throw new Error("unreadable message list");
+ return list.filter(isRecord).reverse();
+ };
+ const tools = (message: Json): Json[] => (Array.isArray(message.content) ? message.content.filter((item): item is Json => isRecord(item) && item.type === "tool") : []);
+ return {
+ async classify(sessionId: string): Promise<SteerVerdict> {
+ let active: unknown;
+ try { active = await read("/api/session/active", STATUS_MAX_BYTES); }
+ catch (error) { return { steer: false, busy: null, reason: "status_unreadable", error: errorText(error) }; }
+ if (!isRecord(active) || !(sessionId in active)) return { steer: false, busy: false, reason: "idle" };
+ try {
+ const [last] = (await newest(sessionId, 1)).slice(-1);
+ if (last?.type === "assistant") return { steer: true, busy: true, reason: "working" };
+ if (last?.type === "compaction") return { steer: false, busy: true, reason: "compacting" };
+ return { steer: false, busy: true, reason: last?.type === "user" ? "not_started" : "ending" };
+ } catch (error) {
+ return { steer: true, busy: true, reason: "busy_unread", error: errorText(error) };
+ }
+ },
+ 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: Json[];
+ try { list = await newest(sessionId, 6); } catch { continue; }
+ const createdOf = (message: Json) => toMs(isRecord(message.time) ? message.time.created : undefined);
+ const steer = list.find((message) => message.type === "user" && typeof message.id === "string" && !known.has(message.id) && (createdOf(message) ?? -Infinity) >= sentAt - 50);
+ if (!steer) continue;
+ const created = createdOf(steer) as number;
+ const running: SteerFound["running"] = [];
+ let last: SteerFound["after_call"] = null;
+ for (const item of list.flatMap(tools)) {
+ const time = isRecord(item.time) ? item.time : {};
+ const start = toMs(time.created);
+ if (start === null || start > created) continue;
+ const end = toMs(time.completed);
+ const call = { tool: typeof item.name === "string" ? item.name : null, call_id: typeof item.id === "string" ? item.id : null, started_at: new Date(start).toISOString(), ...(end !== null ? { ended_at: new Date(end).toISOString() } : {}) };
+ if (!last || start >= Date.parse(last.started_at)) last = call;
+ if (end === null || end > created) running.push(call);
+ }
+ return { message_id: steer.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);
}