From 82156f18c4025278bdebd850731f1c2a67b7bf7a Mon Sep 17 00:00:00 2001 From: Yash Date: Mon, 14 Sep 2026 20:22:08 +0000 Subject: [PATCH] feat(harness): expose revision-bound Assistant transport --- packages/harness/src/server/opencode.test.ts | 205 +++++++++++++++++++ packages/harness/src/server/opencode.ts | 124 ++++++++--- 2 files changed, 305 insertions(+), 24 deletions(-) diff --git a/packages/harness/src/server/opencode.test.ts b/packages/harness/src/server/opencode.test.ts index 26620b3dc..2ee0b6f24 100644 --- a/packages/harness/src/server/opencode.test.ts +++ b/packages/harness/src/server/opencode.test.ts @@ -16,6 +16,9 @@ import { } from "../core/studio-assistant-context.js"; import { openCodeTransportFailure } from "../shared/opencode-errors.js"; import { scopedOpenCodeEvent } from "./opencode-events.js"; +import { AssistantLifecycleCoordinator } from "../core/assistant-lifecycle.js"; +import { AssistantSessionStore } from "../core/assistant-session-store.js"; +import { OpenCodeAssociations } from "../core/opencode-association.js"; let root: string; let origin: string; @@ -119,6 +122,11 @@ beforeEach(async () => { id: `msg_admitted_${requests.filter((request) => request.path.endsWith("/prompt_async")).length}`, role: "user", time: {}, + system: ( + requests + .filter((request) => request.path.endsWith("/prompt_async")) + .at(-1)?.body as { system?: string } | undefined + )?.system, }, parts: [], }, @@ -732,3 +740,200 @@ it("binds an authorized association even when its browser disconnects during att expect(hosted.signal.aborted).toBe(false); expect(close).not.toHaveBeenCalled(); }); + +function installLifecycle( + context: Parameters[2] = resolveContext, +) { + const host = { + ensure, + observe, + current: (id: string) => { + const current = hosts.get(id); + return current?.isCurrent() ? current : null; + }, + assertCurrent: async (hosted: HostedOpenCode) => { + if (!enabled || !hosted.isCurrent()) + throw new OpenCodeAccessError("unavailable"); + }, + retireExact: async (hosted: HostedOpenCode) => { + aborts.get(hosted.harnessSessionId)?.abort(); + }, + retireWithResult: async (id: string) => { + aborts.get(id)?.abort(); + return { state: "confirmed" as const }; + }, + beginShutdown: () => { + for (const abort of aborts.values()) abort.abort(); + }, + }; + const associations = new OpenCodeAssociations(); + const lifecycle = new AssistantLifecycleCoordinator({ + host, + associations, + store: new AssistantSessionStore(root), + }); + router = createOpenCodeRouter( + host, + "boot-token", + context, + associations, + undefined, + lifecycle, + ); + return lifecycle; +} +const leaseHeaders = (lease: string) => ({ + "X-Harness-Token": "boot-token", + "Content-Type": "application/json", + "X-Assistant-Lease": lease, +}); +async function attachLease(expectedRevision = 0) { + const response = await request("studio-a/attach", { + method: "POST", + body: JSON.stringify({ expectedRevision }), + }); + expect(response.status).toBe(200); + return response.json() as Promise<{ + conversationId: string; + lease: string; + lifecycle: { revision: number; execution: string }; + }>; +} + +it("requires a revision for attach and an exact lease for every subsequent native request", async () => { + installLifecycle(); + const descriptor = await request("studio-a/lifecycle"); + expect(await descriptor.json()).toMatchObject({ + revision: 0, + lifecycle: "open", + execution: "paused", + }); + expect(ensure).not.toHaveBeenCalled(); + expect((await request("studio-a/session/status")).status).toBe(409); + expect(ensure).not.toHaveBeenCalled(); + expect( + (await request("studio-a/attach", { method: "POST", body: "{}" })).status, + ).toBe(400); + const attached = await attachLease(); + expect(attached.lifecycle).toMatchObject({ + revision: 1, + execution: "paused", + }); + const count = requests.length; + const wrong = await request( + `studio-a/session/${attached.conversationId}/message`, + { headers: leaseHeaders("wrong") }, + ); + expect(wrong.status).toBe(409); + expect(requests).toHaveLength(count); + expect( + ( + await request(`studio-a/session/${attached.conversationId}/message`, { + headers: leaseHeaders(attached.lease), + }) + ).status, + ).toBe(200); + expect(ensure).toHaveBeenCalledOnce(); + const other = await request("studio-b/session/status", { + headers: leaseHeaders(attached.lease), + }); + expect(other.status).toBe(409); +}); + +it("rejects paused recovery before native reads and enables only explicit prepared Send", async () => { + const lifecycle = installLifecycle(); + const attached = await attachLease(); + const count = requests.length; + const paused = await request( + `studio-a/session/${attached.conversationId}/final-response`, + { + method: "POST", + headers: leaseHeaders(attached.lease), + body: JSON.stringify({ messageId: "msg_empty" }), + }, + ); + expect(paused.status).toBe(409); + expect(await paused.json()).toMatchObject({ + error: { code: "execution_paused" }, + }); + expect(requests).toHaveLength(count); + const sent = await request( + `studio-a/session/${attached.conversationId}/prompt_async`, + { + method: "POST", + headers: leaseHeaders(attached.lease), + body: JSON.stringify({ + parts: [{ type: "text", text: "Explicit new work" }], + }), + }, + ); + expect(sent.status).toBe(204); + expect(sent.headers.get("X-Assistant-Execution")).toBe("enabled"); + expect((await lifecycle.describe("studio-a")).execution).toBe("enabled"); + const active = await attachLease(2); + expect(active.lease).toBe(attached.lease); + expect(active.lifecycle.execution).toBe("enabled"); + const ending = lifecycle.beginEnd("studio-a"); + await ending.persistence; + await ending.native; + await lifecycle.finishEnd(ending.fence); + const endedCount = requests.length; + expect( + ( + await request(`studio-a/session/${attached.conversationId}/message`, { + headers: leaseHeaders(attached.lease), + }) + ).status, + ).toBe(409); + expect(requests).toHaveLength(endedCount); + expect( + ( + await request("studio-a/attach", { + method: "POST", + body: JSON.stringify({ expectedRevision: 4 }), + }) + ).status, + ).toBe(409); + expect(ensure).toHaveBeenCalledOnce(); +}); + +it("composes the accepted-context owner's interface inside the same leased dispatch", async () => { + const accepted = { acceptanceId: "fixture" }; + const context = { + accept: vi.fn().mockResolvedValue(accepted), + compose: vi.fn().mockResolvedValue({ system: "exact accepted system" }), + recover: vi.fn(), + }; + installLifecycle(context); + const attached = await attachLease(); + const response = await request( + `studio-a/session/${attached.conversationId}/prompt_async`, + { + method: "POST", + headers: leaseHeaders(attached.lease), + body: JSON.stringify({ + selectedAgentPath: null, + parts: [{ type: "text", text: "Prepare accepted work" }], + }), + }, + ); + expect(response.status).toBe(204); + expect(context.accept).toHaveBeenCalledExactlyOnceWith( + hosts.get("studio-a"), + attached.conversationId, + null, + expect.any(AbortSignal), + ); + expect(context.compose).toHaveBeenCalledWith( + hosts.get("studio-a"), + attached.conversationId, + accepted, + { attemptToken: expect.any(String) }, + expect.any(AbortSignal), + ); + expect(resolveContext).not.toHaveBeenCalled(); + expect(context.recover).not.toHaveBeenCalled(); + expect( + requests.filter(({ path }) => path.endsWith("/prompt_async")), + ).toHaveLength(1); +}); diff --git a/packages/harness/src/server/opencode.ts b/packages/harness/src/server/opencode.ts index 49c62cd81..120dfc604 100644 --- a/packages/harness/src/server/opencode.ts +++ b/packages/harness/src/server/opencode.ts @@ -1,4 +1,5 @@ import express, { type Request, type Response, type Router } from "express"; +import { randomUUID } from "node:crypto"; import { OpenCodeAssociations, isConversationId, @@ -18,15 +19,33 @@ import { composeAssistantPrompt, type ResolveAssistantContext, } from "../core/studio-assistant-context.js"; +import type { AssistantContextDelivery } from "../core/studio-assistant-delivery.js"; +import type { AssistantLifecycleCoordinator } from "../core/assistant-lifecycle.js"; export function createOpenCodeRouter( - host: Pick, + host: Pick & + Partial>, bootToken: string, - resolveContext: ResolveAssistantContext, + context: ResolveAssistantContext | AssistantContextDelivery, associations = new OpenCodeAssociations(), - finalResponse = new OpenCodeFinalResponse(), + finalResponse?: OpenCodeFinalResponse, + lifecycle?: Pick< + AssistantLifecycleCoordinator, + "describe" | "attach" | "use" | "enable" | "assertRuntime" + >, ): Router { const router = express.Router(); + const dispatch = + finalResponse ?? + new OpenCodeFinalResponse({ + assertCurrent: async (hosted) => { + await lifecycle?.assertRuntime(hosted, true); + await host.assertCurrent?.(hosted); + }, + ...(typeof context === "function" + ? {} + : { recoverPrompt: context.recover }), + }); router.use( createBootTokenMiddleware(bootToken), express.json({ limit: "1mb" }), @@ -42,6 +61,7 @@ export function createOpenCodeRouter( const path = req.params[0] ?? ""; const id = req.params.harnessSessionId!; const read = req.method === "GET"; + const descriptor = read && path === "lifecycle" && !!lifecycle; const conversation = /^session\/(ses_[A-Za-z0-9_-]+)(\/message|\/prompt_async|\/final-response)?$/.exec( path, @@ -58,6 +78,7 @@ export function createOpenCodeRouter( const recover = req.method === "POST" && conversation?.[2] === "/final-response"; const allowed = + descriptor || attach || prompt || recover || @@ -79,6 +100,11 @@ export function createOpenCodeRouter( !/^[A-Za-z0-9_-]{1,128}$/.test(id) || !queryAllowed || (conversation && !isConversationId(conversation[1])) || + (attach && + lifecycle && + (Object.keys(req.body ?? {}).length !== 1 || + !Number.isSafeInteger(req.body?.expectedRevision) || + req.body.expectedRevision < 0)) || (recover && (Object.keys(req.body ?? {}).length !== 1 || !/^msg_[A-Za-z0-9_-]{1,128}$/.test(req.body?.messageId ?? ""))) @@ -97,8 +123,21 @@ export function createOpenCodeRouter( res.once("close", cancel); res.setHeader("Cache-Control", "no-store"); try { - const hosted = await host.ensure(id); - const nativeId = await associations.ensure(hosted); + if (descriptor) { + res.json(await lifecycle!.describe(id)); + return; + } + if (attach && lifecycle) { + const attached = await lifecycle.attach(id, req.body.expectedRevision); + if (!res.destroyed) res.json(attached); + return; + } + const bound = lifecycle + ? await lifecycle.use(id, req.header("X-Assistant-Lease"), recover) + : null; + const hosted = bound?.hosted ?? (await host.ensure(id)); + const nativeId = + bound?.conversationId ?? (await associations.ensure(hosted)); if (conversation && conversation[1] !== nativeId) { res.status(403).json({ error: "Conversation does not belong to this Studio session", @@ -117,11 +156,11 @@ export function createOpenCodeRouter( return; } if (recover) { - await finalResponse.recover(hosted, nativeId, req.body.messageId); + await dispatch.recover(hosted, nativeId, req.body.messageId); if (!res.destroyed) res.status(204).end(); return; } - if (prompt && finalResponse.isRunning(hosted)) { + if (prompt && dispatch.isRunning(hosted)) { res .status(409) .json({ error: "Assistant is finishing the previous response" }); @@ -138,20 +177,48 @@ export function createOpenCodeRouter( signal: AbortSignal.any([signal, AbortSignal.timeout(30000)]), }; const upstream = prompt - ? await finalResponse.send(hosted, nativeId, async () => ({ - ...init, - body: JSON.stringify({ - parts: req.body.parts, - model: hosted.model, - ...composeAssistantPrompt( - await resolveContext( - hosted, - req.body.selectedAgentPath, - init.signal, - ), - ), - }), - })) + ? await dispatch.send( + hosted, + nativeId, + async (admissionSignal) => { + const prompt = + typeof context === "function" + ? composeAssistantPrompt( + await context( + hosted, + req.body.selectedAgentPath, + admissionSignal, + ), + ) + : await context.compose( + hosted, + nativeId, + await context.accept( + hosted, + nativeId, + req.body.selectedAgentPath, + admissionSignal, + ), + { attemptToken: randomUUID() }, + admissionSignal, + ); + admissionSignal.throwIfAborted(); + await lifecycle?.enable(hosted); + const request = { + ...init, + signal: admissionSignal, + body: JSON.stringify({ + parts: req.body.parts, + model: hosted.model, + ...prompt, + }), + }; + return typeof context === "function" + ? request + : { init: request, expectedSystem: prompt.system }; + }, + signal, + ) : await hosted.server.fetch(`/${nativePath}`, init); if (!upstream.ok) { await upstream.body?.cancel(); @@ -166,6 +233,8 @@ export function createOpenCodeRouter( return; } if (upstream.status === 204) { + if (prompt && lifecycle) + res.setHeader("X-Assistant-Execution", "enabled"); res.status(204).end(); return; } @@ -204,9 +273,16 @@ function sendFailure(res: Response, failure: OpenCodeTransportFailure): void { ? 401 : failure.code === "access_denied" || failure.code === "access_expired" ? 403 - : failure.code === "native_history_missing" - ? 410 - : 503; + : [ + "lifecycle_changed", + "session_ended", + "execution_paused", + "cleanup_unconfirmed", + ].includes(failure.code) + ? 409 + : failure.code === "native_history_missing" + ? 410 + : 503; res.status(status).json({ error: failure }); }