An open-source, faster Devin alternative
TypeScript
Fix web Codex sessions using the Claude runner (#1086)
opencomputer-app[bot]40bd39dc4cd5
diff --git a/services/managed-agents/src/computer/api-model-route.ts b/services/managed-agents/src/computer/api-model-route.tsnew file mode 100644index 00000000..01b10c3c--- /dev/null+++ b/services/managed-agents/src/computer/api-model-route.ts@@ -0,0 +1,57 @@+// Session API writes resolve the owner's model seat before a runner starts,+// just as Slack deliveries do. The model frame precedes the API frame so the+// host never falls back to the organization's Claude route for a Codex model.++import { harnessOnProfile } from "./harnesses.js";+import type { ModelAccess } from "./model-access.js";+import { webOwner } from "./model-access.js";+import type { CalvinApiError, CalvinGatewayToHost, CalvinSessionSpec, ModelProfile } from "./protocol.js";+import { workOsUserOf } from "./session-ids.js";++export type RoutedApiSession = { session: CalvinSessionSpec; error?: CalvinApiError };++/** The subscription identity shared by a dashboard member and their Slack login. */+export function apiSubscriptionOwner(access: ModelAccess, member: string | undefined): string | undefined {+ const user = member && workOsUserOf(member);+ return user ? access.agents.view(user).linkedSlackUser?.id ?? webOwner(user) : undefined;+}++export async function routeApiSession(+ deps: {+ access: ModelAccess;+ profiles: () => ModelProfile[] | undefined;+ send: (frame: CalvinGatewayToHost) => boolean;+ },+ session: CalvinSessionSpec,+ member?: string,+): Promise<RoutedApiSession> {+ const ownerOf = (id: string | undefined) => apiSubscriptionOwner(deps.access, id);+ const owner = session.owner.slackUserId || ownerOf(session.owner.userId);+ let wanted = deps.access.models.harness(session.key);+ if (session.kind === "api") {+ if (session.model?.startsWith("gpt-")) wanted = "codex";+ else if (session.model?.startsWith("claude-")) wanted = "claude";+ }+ // A non-WorkOS API identity has no personal subscription to resolve.+ if (!owner) return wanted === "codex"+ ? { session, error: { code: "model_unavailable", status: 403, message: "This model requires a linked Codex connection." } }+ : { session };+ deps.access.models.setHarness(session.key, wanted);+ const poster = !member || member === session.owner.userId ? owner : ownerOf(member) ?? webOwner(member);+ const { route } = await deps.access.models.forDelivery({ key: session.key, ownerId: owner }, poster);+ if (route.mode === "refuse") return { session, error: { code: "model_unavailable", status: 403, message: route.reason } };+ const harness = route.mode === "subscription"+ ? route.provider === "chatgpt" ? "codex" : "claude"+ : route.mode === "profile" ? harnessOnProfile(deps.profiles(), route.profile, wanted) : "claude";+ if (wanted === "codex" && harness !== "codex") {+ return { session, error: { code: "model_unavailable", status: 403, message: "This model requires an available Codex connection. Connect ChatGPT or select a Claude model." } };+ }+ // The public build has no subscription router. Its managed credentials are+ // already in welcome; no per-session override is needed for that route.+ if (route.mode === "managed") return { session: { ...session, harness } };+ if (!deps.send({ t: "model", sessionKey: session.key, model: route })) {+ return { session, error: { code: "computer_unavailable", status: 503, message: "The computer disconnected. Retry the request.", retryable: true } };+ }+ deps.access.models.noteSent(session.key, route);+ return { session: { ...session, harness } };+}diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 64f0957a..0f82c336 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -100,6 +100,7 @@ import { hostToken } from "./host-token.js";import { failureNotice } from "./failure.js";import { type AdoptedComputer, ComputerLifecycle, type ComputerState, type LifecycleReply } from "./lifecycle.js";import { MANAGED_MODEL_PROVIDER, type ModelCredentials, managedModelRoute, modelCredentials, requestManagedModelKey } from "./model-key.js";+import { apiSubscriptionOwner, routeApiSession } from "./api-model-route.js";import { mintOpenComputerKey } from "./opencomputer-key.js";import { type AutomationRepositoryEnv, automationRepositoryCredential } from "../edge/automation-repository.js";import { daysUnpaid, idleParkMs, parkingDecision, unpaidStage, unpaidWarning, unpaidWarningGiven } from "./parking.js";@@ -577,7 +578,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {send: (frame) => this.send(frame),schedule: (purpose) => this.purposeScheduler(purpose),liveSessions: () => this.liveSessions(),- session: (key) => this.runnerSession(key),+ session: (key) => this.modelSession(key),// A token connected on the dashboard (`web:<id>`, work 081) has nobody in Slack to tell.directMessage: (userId, text) => (userId.startsWith(WEB_OWNER_PREFIX) ? Promise.resolve(false) : this.directMessage(userId, text)),threadUrl: (channelId, threadTs) => slackThreadUrl(this.setting("slackTeamId") ?? "", channelId, threadTs) ?? undefined,@@ -664,6 +665,7 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {host: () => this.apiHost(),enabled: () => this.apiEnabled(),send: (frame) => this.send(frame),+ routeSession: (session, member) => routeApiSession({ access: this.access, profiles: () => this.liveHost()?.profiles, send: (frame) => this.send(frame) }, session, member),closeHost: (code, reason) => this.socket()?.close(code, reason),wake: () => this.wakeForApi(),computerStatus: () => this.apiComputerStatus(),@@ -3504,9 +3506,22 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {/** Sessions running now, with their conversations and last activity (pushes go to these). */private liveSessions(): ModelSession[] {- return [...this.ctx.storage.sql.exec<{ key: string; ownerId: string | null; channelId: string; threadTs: string; status: string; activeAt: number }>(- "SELECT runner_key AS key, owner_id AS ownerId, channel_id AS channelId, thread_ts AS threadTs, status, updated_at AS activeAt FROM sessions WHERE status IN ('starting', 'idle', 'busy')",- )].flatMap((row) => (row.ownerId ? [{ key: row.key, ownerId: row.ownerId, channelId: row.channelId, threadTs: row.threadTs, status: row.status, activeAt: row.activeAt }] : []));+ return [...this.ctx.storage.sql.exec<{ key: string; status: string; activeAt: number }>(+ "SELECT runner_key AS key, COALESCE(api_status, status) AS status, updated_at AS activeAt FROM sessions WHERE COALESCE(api_status, status) IN ('starting', 'idle', 'busy', 'running', 'waiting')",+ )].flatMap((row) => {+ const session = this.modelSession(row.key);+ const status = row.status === "running" ? "busy" : row.status === "waiting" ? "idle" : row.status;+ return session ? [{ ...session, status, activeAt: row.activeAt }] : [];+ });+ }++ /** Subscription refreshes, disconnects and host reconnects include API sessions too. */+ private modelSession(key: string): ModelSession | undefined {+ const slack = this.runnerSession(key);+ if (slack) return slack;+ const row = this.api.row(key);+ const ownerId = row?.ownerUserId ? apiSubscriptionOwner(this.access, row.ownerUserId) : undefined;+ return row && ownerId ? { key: row.key, ownerId, channelId: row.channelId, threadTs: row.threadTs } : undefined;}/** Slack says a person left, was deactivated or became a guest (work 077): their Claude subscription goes. */diff --git a/services/managed-agents/src/computer/sessions-api.ts b/services/managed-agents/src/computer/sessions-api.tsindex 711737b9..411f21bc 100644--- a/services/managed-agents/src/computer/sessions-api.ts+++ b/services/managed-agents/src/computer/sessions-api.ts@@ -16,6 +16,7 @@// title/mode/model stay the Slack path's, and only a v4 host sees any of it.import type { ApiTelemetry } from "./telemetry/api.js";+import type { RoutedApiSession } from "./api-model-route.js";import type { AssertedApiKey } from "../edge/auth.js";import type { ApiScope, Ask, LogSummary, Origin, Person, Session, SessionStatus } from "./api-types.js";import { DEFAULT_MODE, MODELS, capabilities, checkSettings } from "./capabilities.js";@@ -209,6 +210,8 @@ export interface SessionsApiDeps {/** The rollout gate (api-gate.ts): false, and every operation but `me` answers 409 feature_unavailable. */enabled: () => boolean;send: (frame: CalvinGatewayToHost) => boolean;+ /** Resolves the owner's subscription and runner before starting or delivering a turn. */+ routeSession?: (session: CalvinSessionSpec, member?: string) => Promise<RoutedApiSession>;closeHost: (code: number, reason: string) => void;/** Starts or wakes the computer (no Slack notice). */wake: () => Promise<void>;@@ -532,7 +535,8 @@ export class ComputerSessionsApi {({ turn, delivery, seq } = result);duplicate = repeat && result.duplicate === true;} else if (!repeat) {- this.startSession(row);+ const outcome = await this.startSession(row);+ if (outcome.error) return hostError(outcome.error);} else {duplicate = true;}@@ -544,14 +548,16 @@ export class ComputerSessionsApi {private async wake(sessionId: string): Promise<void> {await this.epochSends.get(sessionId);const row = this.row(sessionId);- if (row) this.startSession(row);+ if (row) await this.startSession(row);}/** A session with no first message: the host claims a spare and forks for it (answered by `started`). */- private startSession(row: ApiRow): void {+ private async startSession(row: ApiRow): Promise<HostOutcome> {const id = crypto.randomUUID();- const sent = this.deps.send({ t: "start", id, session: this.spec(row), epoch: row.logEpoch, lastSeq: row.lastSeq });- if (!sent) return;+ const routed = await this.deps.routeSession?.(this.spec(row), row.ownerUserId ?? undefined);+ if (routed?.error) return { error: routed.error };+ const sent = this.deps.send({ t: "start", id, session: routed?.session ?? this.spec(row), epoch: row.logEpoch, lastSeq: row.lastSeq });+ if (!sent) return { error: hostLost() };// Nobody waits for it; a refusal is logged (the session stays `starting` until a send).this.pending.set(id, {resolve: (outcome) => {@@ -559,6 +565,7 @@ export class ComputerSessionsApi {},timer: setTimeout(() => this.settle(id, {}), HOST_CALL_TIMEOUT_MS),});+ return {};}private async get(caller: ApiCaller, sessionId: string, minSeq?: number): Promise<ApiReply> {@@ -906,6 +913,16 @@ export class ComputerSessionsApi {}const wait = this.answerWait(frame.sessionId, moving !== undefined);if (note) note.wait = wait;+ if (frame.session && ADMITTED.has(frame.method) && this.deps.routeSession) {+ const routed = await this.deps.routeSession(frame.session, frame.member).catch(() => ({ session: frame.session!, error: hostLost() }));+ if (routed.error) {+ const outcome = { error: routed.error };+ if (key && this.keyed.get(key)?.id === frame.id) this.keyed.delete(key);+ resolve(outcome);+ return outcome;+ }+ frame = { ...frame, session: routed.session };+ }const sent = this.deps.send(frame);if (note) note.sentAt = performance.now();if (!sent) {diff --git a/services/managed-agents/test/computer-model-access-do.test.ts b/services/managed-agents/test/computer-model-access-do.test.tsindex 96325e49..5e15285d 100644--- a/services/managed-agents/test/computer-model-access-do.test.ts+++ b/services/managed-agents/test/computer-model-access-do.test.ts@@ -62,6 +62,24 @@ const job = (team: string, messageTs: string, text: string) => ({receivedAt: Date.now(),});const deliveries = (stub: Stub) => inside(stub, (instance) => instance.deliveries as string[]);++it("tracks web sessions on the linked subscription for refreshes and reconnects", async () => {+ const stub = computers().getByName("org_web_subscription_tracking");+ const tracked = await inside(stub, (instance, state) => {+ const member = "usr_01jabcdefghjkmnpqrstvwxyz0";+ const key = "cs_0000000000000001";+ instance.access.agents.view = () => ({ linkedSlackUser: { id: "ULINKED" } });+ state.storage.sql.exec(+ `INSERT INTO sessions (runner_key, team_id, channel_id, thread_ts, title, created_at, updated_at,+ session_id, origin_type, owner_user_id, api_status)+ VALUES (?, '', '', '', 'Web session', 1, 2, ?, 'dashboard', ?, 'running')`,+ key, key, member,+ );+ return { session: instance.modelSession(key), live: instance.liveSessions() };+ });+ expect(tracked.session).toMatchObject({ key: "cs_0000000000000001", ownerId: "ULINKED" });+ expect(tracked.live).toEqual([{ ...tracked.session, status: "busy", activeAt: 2 }]);+});// By channel, never by clearing the fake: other files' tests read its calls at the same time.const claudeAnswers = async () => (await slackCalls()).filter((c) => c.method === "chat.postEphemeral" && c.body.channel === "CSEAMPUB" && typeof c.body.text === "string" && c.body.text.includes("!claude"));diff --git a/services/managed-agents/test/computer-sessions-api.test.ts b/services/managed-agents/test/computer-sessions-api.test.tsindex 7c7e83c5..d67121a2 100644--- a/services/managed-agents/test/computer-sessions-api.test.ts+++ b/services/managed-agents/test/computer-sessions-api.test.ts@@ -21,6 +21,9 @@ import {import { ApiTelemetry } from "../src/computer/telemetry/api.js";import { createTelemetry } from "../src/computer/telemetry/emitter.js";import type { RequestIdentity } from "../src/edge/auth.js";+import { routeApiSession } from "../src/computer/api-model-route.js";+import { noModelAccess, type ResolvedRoute } from "../src/computer/model-access.js";+import type { SessionsApiDeps } from "../src/computer/sessions-api.js";import { sqlStorage } from "./fixtures/computer-sql.js";/**@@ -135,7 +138,7 @@ const event = (seq: number, sessionId = SID): ApiEvent => ({data: {},});-function fixture(options: { protocol?: number | null; enabled?: boolean; status?: "ready" | "asleep" | "not_set_up"; admitted?: boolean | "throws"; ticketKey?: boolean; telemetry?: ApiTelemetry } = {}) {+function fixture(options: { protocol?: number | null; enabled?: boolean; status?: "ready" | "asleep" | "not_set_up"; admitted?: boolean | "throws"; ticketKey?: boolean; telemetry?: ApiTelemetry; routeSession?: SessionsApiDeps["routeSession"] } = {}) {const sql = sqlStorage();sql.exec(`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);@@ -172,6 +175,7 @@ function fixture(options: { protocol?: number | null; enabled?: boolean; status?organizationId: () => ORG,host: () => (state.protocol === null ? undefined : { protocol: state.protocol }),enabled: () => options.enabled ?? true,+ routeSession: options.routeSession,send: (frame) => {if (state.protocol === null) return false;sent.push(frame);@@ -237,6 +241,98 @@ async function created(f: ReturnType<typeof fixture>, id = SID, member = OWNER)return reply;}+describe("API model routing", () => {+ function routed() {+ const access = noModelAccess();+ const view = access.agents.view("");+ access.agents.view = vi.fn(() => ({ ...view, linkedSlackUser: { id: "U1", name: "Owner", teamName: "Team" } }));+ access.models.setHarness = vi.fn();+ access.models.noteSent = vi.fn();+ access.models.forDelivery = vi.fn(async () => ({+ route: { mode: "profile" as const, profile: "chatgpt", vars: {}, key: "seat" }, reason: "subscription" as const,+ }));+ const f = fixture({+ routeSession: (session, member) => routeApiSession({+ access,+ profiles: () => [{ name: "chatgpt", vars: [], harness: { codex: {} } }],+ send: (frame) => { f.sent.push(frame); return true; },+ }, session, member),+ });+ return { ...f, access };+ }++ it("starts the web session on the linked Slack Codex seat before launching its runner", async () => {+ const f = routed();+ const reply = await f.api.handle(caller(), { op: "create", body: { id: SID, model: "gpt-6.2-sol" } });+ expect(reply.status).toBe(201);+ expect(f.access.models.setHarness).toHaveBeenCalledWith(SID, "codex");+ expect(f.access.models.forDelivery).toHaveBeenCalledWith({ key: SID, ownerId: "U1" }, "U1");+ expect(f.frames("start")[0]?.session).toMatchObject({ model: "gpt-6.2-sol", harness: "codex" });+ expect(f.sent.findIndex((frame) => frame.t === "model")).toBeLessThan(f.sent.findIndex((frame) => frame.t === "start"));+ });++ it("routes the first input and re-resolves the connection before later inputs", async () => {+ const f = routed();+ f.answers.set("turns.send", () => ({ result: { turn: {}, delivery: {}, seq: 1 } }));+ const reply = await f.api.handle(caller(), { op: "create", body: { id: SID, model: "gpt-6.2-sol", input: "hi codo" } });+ expect(reply.status).toBe(201);+ expect(f.frames("api")[0]?.session?.harness).toBe("codex");+ expect(f.sent.findIndex((frame) => frame.t === "model")).toBeLessThan(f.sent.findIndex((frame) => frame.t === "api"));+ await f.api.handle(caller(), { op: "call", sessionId: SID, method: "turns.send", params: { input: "again" } });+ expect(f.access.models.forDelivery).toHaveBeenCalledTimes(2);+ expect(f.frames("api")[1]?.session?.harness).toBe("codex");+ });++ it("returns a subscription refusal without delivering an input to Claude", async () => {+ const f = routed();+ f.access.models.forDelivery = vi.fn(async (): Promise<ResolvedRoute> => ({ route: { mode: "refuse", reason: "Connect ChatGPT first." }, reason: "no_subscription" }));+ const reply = await f.api.handle(caller(), { op: "create", body: { id: SID, model: "gpt-6.2-sol", input: "hi" } });+ expect(reply.status).toBe(403);+ expect(reply.error?.message).toBe("Connect ChatGPT first.");+ expect(f.frames("api")).toHaveLength(0);+ expect(f.frames("start")).toHaveLength(0);+ });++ it("does not send a GPT model through a managed Claude fallback", async () => {+ const f = routed();+ f.access.models.forDelivery = vi.fn(async (): Promise<ResolvedRoute> => ({ route: { mode: "managed" }, reason: "limited" }));+ const reply = await f.api.handle(caller(), { op: "create", body: { id: SID, model: "gpt-6.2-sol" } });+ expect(reply.status).toBe(403);+ expect(f.frames("start")).toHaveLength(0);+ });++ it("keeps another driver's identity when resolving the owner's seat", async () => {+ const f = routed();+ const view = f.access.agents.view("");+ f.access.agents.view = vi.fn((user) => ({ ...view, linkedSlackUser: { id: user === caller().userId ? "U1" : "U2", name: "Person", teamName: "Team" } }));+ await f.api.handle(caller(), { op: "create", body: { id: SID, model: "gpt-6.2-sol" } });+ f.answers.set("turns.send", () => ({ result: { turn: {}, delivery: {}, seq: 1 } }));+ await f.api.handle(caller(MO), { op: "call", sessionId: SID, method: "turns.send", params: { input: "hello" } });+ expect(f.access.models.forDelivery).toHaveBeenLastCalledWith({ key: SID, ownerId: "U1" }, "U2");+ });++ it("keeps managed Claude sessions working without a subscription", async () => {+ const f = routed();+ f.access.models.forDelivery = vi.fn(async (): Promise<ResolvedRoute> => ({ route: { mode: "managed" }, reason: "no_subscription" }));+ const reply = await f.api.handle(caller(), { op: "create", body: { id: SID, model: "claude-opus-5-5" } });+ expect(reply.status).toBe(201);+ expect(f.frames("start")[0]?.session.harness).toBe("claude");+ expect(f.frames("model")).toHaveLength(0);+ });++ it("preserves a Slack thread's explicit harness when it is driven through the API", async () => {+ const f = routed();+ await created(f);+ const session = f.frames("start")[0]!.session;+ f.access.models.harness = () => "codex";+ const result = await routeApiSession({ access: f.access, profiles: () => [{ name: "chatgpt", vars: [], harness: { codex: {} } }], send: () => true }, {+ ...session, kind: "thread", owner: { ...session.owner, slackUserId: "U1" }, model: "claude-opus-5-5",+ }, OWNER);+ expect(result.session.harness).toBe("codex");+ expect(f.access.models.setHarness).toHaveBeenLastCalledWith(SID, "codex");+ });+});+describe("journal: single writer, no gaps, no duplicates", () => {it("stores, mirrors and acks a batch; fences an older epoch", async () => {const f = fixture();