Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .github/qa/summarizer-chat/sidebar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions arena-backend/packages/arena-service/src/assignments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,13 +215,13 @@ export async function reserveRoutingAssignment(db: ArenaDb, userId: string, scop
return undefined
}

export async function hasActiveComparisonScope(db: ArenaDb, userId: string, scopeID: string) {
export async function hasComparisonScope(db: ArenaDb, userId: string, scopeID: string, includeResolved = false) {
const document = await collection(db).findOne({
_id: setID(userId, "battle", scopeID),
userId,
kind: "battle",
scopeID,
decision: { $exists: false },
...(includeResolved ? {} : { decision: { $exists: false } }),
})
return document !== null
}
Expand Down
62 changes: 62 additions & 0 deletions arena-backend/packages/arena-service/src/comparison.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,66 @@ describe("Arena comparison control plane", () => {
expect(response.status).toBe(400)
expect(contacted).toBe(false)
})
test("continues a summary with native tools and replayed tool results", async () => {
let upstreamBody: unknown
const messages = [
{ role: "system", content: "Explain Agent Duel" },
{ role: "user", content: "Summarize this battle" },
{ role: "assistant", content: "A changed the parser" },
{ role: "user", content: "Does B handle empty input?" },
{
role: "assistant",
content: null,
tool_calls: [
{ id: "call_1", type: "function", function: { name: "read", arguments: '{"path":"b/parser.ts"}' } },
],
},
{ role: "tool", tool_call_id: "call_1", content: "return input || []" },
]
const tools = [
{ type: "function", function: { name: "read", description: "Read a file", parameters: { type: "object" } } },
]
const response = await service({
fetch: async (_url, init) => {
upstreamBody = JSON.parse(String(init?.body))
return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })
},
}).comparison(request({ scopeID: "turn-1", conversation: true, messages, tools, stream: true, temperature: 0 }))
expect(response.status).toBe(200)
expect(upstreamBody).toMatchObject({
messages,
tools,
stream: true,
model: utilityModels[0].id,
reasoning: { effort: "high" },
})
expect(response.headers.get("x-arena-utility-model")).toBe(utilityModels[0].id)
expect(response.headers.get("x-arena-utility-reasoning-effort")).toBe("high")
})

test("keeps reasoning high when summarizer chat falls back to DeepSeek", async () => {
const upstream: Record<string, unknown>[] = []
const response = await service({
fetch: async (_url, init) => {
const body = JSON.parse(String(init?.body)) as Record<string, unknown>
upstream.push(body)
if (body.model === utilityModels[0].id) return Response.json({ error: "rate limited" }, { status: 429 })
return Response.json({ choices: [{ message: { content: "Inspected the saved evidence" } }] })
},
}).comparison(
request({
scopeID: "turn-1",
conversation: true,
messages: [{ role: "user", content: "Which result was tested?" }],
temperature: 0,
}),
)
expect(response.status).toBe(200)
expect(upstream.map((body) => ({ model: body.model, reasoning: body.reasoning }))).toEqual([
{ model: utilityModels[0].id, reasoning: { effort: "high" } },
{ model: utilityModels[1].id, reasoning: { effort: "high" } },
])
expect(response.headers.get("x-arena-utility-provider")).toBe("baseten")
expect(response.headers.get("x-arena-utility-reasoning-effort")).toBe("high")
})
})
68 changes: 63 additions & 5 deletions arena-backend/packages/arena-service/src/comparison.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,81 @@
import { hasActiveComparisonScope } from "./assignments"
import { z } from "zod"
import { hasComparisonScope } from "./assignments"
import { authorize, type ArenaContext } from "./context"
import { requestUtilityModel } from "./utility-model"

function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}

const conversationSchema = z
.object({
scopeID: z.string().trim().min(1),
conversation: z.literal(true),
messages: z
.array(
z
.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.union([z.string(), z.array(z.record(z.string(), z.unknown())), z.null()]).optional(),
tool_calls: z.array(z.record(z.string(), z.unknown())).optional(),
tool_call_id: z.string().optional(),
})
.passthrough(),
)
.min(1),
tools: z
.array(
z.object({
type: z.literal("function"),
function: z
.object({
name: z.string(),
description: z.string().optional(),
parameters: z.record(z.string(), z.unknown()),
})
.passthrough(),
}),
)
.optional(),
stream: z.boolean().optional(),
stream_options: z.object({ include_usage: z.boolean() }).optional(),
tool_choice: z.union([z.enum(["auto", "none", "required"]), z.record(z.string(), z.unknown())]).optional(),
parallel_tool_calls: z.boolean().optional(),
max_tokens: z.number().int().positive().max(32768).optional(),
temperature: z.literal(0),
})
.strict()

function validInput(value: unknown) {
if (record(value) && value.conversation === true) {
const parsed = conversationSchema.safeParse(value)
if (!parsed.success) return undefined
const { scopeID, conversation, ...body } = parsed.data
return { scopeID, conversation, body }
}
if (!record(value) || typeof value.scopeID !== "string" || !value.scopeID.trim()) return undefined
if (!Array.isArray(value.messages) || value.messages.length !== 1) return undefined
const message = value.messages[0]
if (!record(message) || message.role !== "user" || typeof message.content !== "string") return undefined
if (value.temperature !== 0) return undefined
if (Object.keys(value).some((key) => !["scopeID", "messages", "temperature"].includes(key))) return undefined
return { scopeID: value.scopeID.trim(), message: { role: "user", content: message.content } as const }
return {
scopeID: value.scopeID.trim(),
conversation: false,
body: { messages: [{ role: "user", content: message.content }], temperature: 0 },
}
}

function responseHeaders(source: Headers) {
const headers = new Headers()
for (const name of ["content-type", "cache-control", "retry-after"]) {
for (const name of [
"content-type",
"cache-control",
"retry-after",
"x-arena-utility-model",
"x-arena-utility-provider",
"x-arena-utility-reasoning-effort",
]) {
const value = source.get(name)
if (value) headers.set(name, value)
}
Expand All @@ -42,7 +99,7 @@ export async function handleComparisonRequest(request: Request, context: ArenaCo
if (!input) return Response.json({ error: "Arena comparison request is invalid" }, { status: 400 })
let active: boolean
try {
active = await hasActiveComparisonScope(await context.db(), caller.id, input.scopeID)
active = await hasComparisonScope(await context.db(), caller.id, input.scopeID, input.conversation)
} catch (error) {
console.error("[arena-service] Arena comparison scope could not be read", error)
return Response.json({ error: "Arena comparison is unavailable" }, { status: 503 })
Expand All @@ -59,8 +116,9 @@ export async function handleComparisonRequest(request: Request, context: ArenaCo
"Content-Type": "application/json",
"X-OpenRouter-Metadata": "enabled",
},
body: { messages: [input.message], temperature: 0 },
body: input.body,
signal: request.signal,
reasoning: input.conversation ? { effort: "high" } : undefined,
})
return new Response(response.body, { status: response.status, headers: responseHeaders(response.headers) })
} catch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ export const researchCollections = [
"events",
"sessionArchives",
"comparisons",
"summaryConversations",
"summaryMessages",
"summaryCalls",
"reviewEvents",
"battleMetrics",
"singleAgentRatings",
Expand Down
15 changes: 12 additions & 3 deletions arena-backend/packages/arena-service/src/utility-model.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ArenaContext } from "./context"

// The comparison and the metadata text run on a cheap, fast model, tried in this order. Each entry
// Comparison reports and metadata use these fast defaults. Interactive summarizer chat overrides
// them with high reasoning, including on fallback. Each entry
// pins one provider, because the reasoning setting is tuned per provider: Baseten ignores
// `effort: low` and reasons for thousands of tokens, so DeepSeek runs with reasoning off.
export const utilityModels = [
Expand Down Expand Up @@ -29,23 +30,31 @@ export async function requestUtilityModel(
readonly headers: Record<string, string>
readonly body: Record<string, unknown>
readonly signal: AbortSignal
readonly reasoning?: { readonly effort: "high" }
},
) {
for (const [index, model] of utilityModels.entries()) {
const last = index === utilityModels.length - 1
const reasoning = input.reasoning ?? model.reasoning
try {
const response = await context.fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: input.headers,
body: JSON.stringify({
model: model.id,
...input.body,
reasoning: model.reasoning,
reasoning,
provider: model.routing,
}),
signal: input.signal,
})
if (response.ok || last) return response
if (response.ok || last) {
const headers = new Headers(response.headers)
headers.set("x-arena-utility-model", model.id)
headers.set("x-arena-utility-provider", model.provider)
headers.set("x-arena-utility-reasoning-effort", "effort" in reasoning ? reasoning.effort : "none")
return new Response(response.body, { status: response.status, headers })
}
await response.body?.cancel().catch(() => undefined)
console.error(`[arena-service] Utility model ${model.id} failed with status ${response.status}`)
} catch (error) {
Expand Down
2 changes: 2 additions & 0 deletions arena-backend/packages/opencode/src/arena/http-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Image } from "@/image/image"
import { InstanceStore } from "@/project/instance-store"
import { Worktree } from "@/worktree"
import { ArenaService } from "./service"
import { createSummarizerPlugin } from "./summarizer/plugin"
import { createArenaEnginePlugin } from "./engine-runtime/plugin"
import { createArenaWebSearchPlugin } from "./websearch"
import { Service as V2EventsService, layer as v2EventsLayer } from "./v2-events"
Expand All @@ -22,6 +23,7 @@ export const enginePluginLayer = Layer.effectDiscard(
const plugins = yield* SdkPlugins.Service
yield* plugins.register(createArenaEnginePlugin())
yield* plugins.register(createArenaWebSearchPlugin())
yield* plugins.register(createSummarizerPlugin())
}),
)

Expand Down
11 changes: 11 additions & 0 deletions arena-backend/packages/opencode/src/arena/mongo.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ConversationDocument, MessageDocument, CallDocument } from "./summarizer/schema"
import { MongoClient, MongoServerError, type Db } from "mongodb"
import { inheritSingleAgentTurns, inheritTurns, MAX_FORK_DEPTH } from "./fork-lineage"
import {
Expand Down Expand Up @@ -213,6 +214,9 @@ export class Store {
readonly rawEvents: ArenaCollection<RawEventDocument>
readonly sessionArchives: ArenaCollection<SessionArchiveDocument>
readonly artifacts: ArenaCollection<ArtifactDocument>
readonly summaryConversations: ArenaCollection<ConversationDocument>
readonly summaryMessages: ArenaCollection<MessageDocument>
readonly summaryCalls: ArenaCollection<CallDocument>
readonly comparisons: ArenaCollection<ComparisonDocument>
readonly reviewEvents: ArenaCollection<ReviewEventDocument>
readonly battleMetrics: ArenaCollection<BattleMetricsDocument>
Expand All @@ -233,6 +237,9 @@ export class Store {
this.rawEvents = this.db.collection<RawEventDocument>("rawEvents")
this.sessionArchives = this.db.collection<SessionArchiveDocument>("sessionArchives")
this.artifacts = this.db.collection<ArtifactDocument>("artifacts")
this.summaryConversations = this.db.collection<ConversationDocument>("summaryConversations")
this.summaryMessages = this.db.collection<MessageDocument>("summaryMessages")
this.summaryCalls = this.db.collection("summaryCalls")
this.comparisons = this.db.collection<ComparisonDocument>("comparisons")
this.reviewEvents = this.db.collection<ReviewEventDocument>("reviewEvents")
this.battleMetrics = this.db.collection<BattleMetricsDocument>("battleMetrics")
Expand Down Expand Up @@ -309,6 +316,10 @@ export class Store {
),
this.sessionArchives.createIndex({ runID: 1 }, { unique: true }),
this.artifacts.createIndex({ runID: 1, createdAt: 1 }, { sparse: true }),
this.summaryConversations.createIndex({ turnID: 1, createdAt: -1 }),
this.summaryConversations.createIndex({ sessionID: 1 }, { unique: true }),
this.summaryMessages.createIndex({ conversationID: 1 }),
this.summaryCalls.createIndex({ conversationID: 1 }),
this.comparisons.createIndex({ turnID: 1 }, { unique: true }),
// The rollup reads one turn's review in the order the voter produced it.
this.reviewEvents.createIndex({ turnID: 1, offsetMs: 1 }),
Expand Down
31 changes: 31 additions & 0 deletions arena-backend/packages/opencode/src/arena/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import { ARENA_SENT_AT } from "./session-runtime/projection"
import { copyKeepingReferences } from "./compaction-reference"
import { KeyedMutex } from "@opencode/core/effect/keyed-mutex"
import { awaitedShells, closeShellTurn, openShellTurn, SERVER_CHECK_INTERVAL_MS } from "./engine-runtime/shell"
import { createSummarizer } from "./summarizer/service"
import { timeline as summaryTimeline } from "./summarizer/timeline"
import type { Conversation as SummaryConversation } from "./summarizer/schema"
import { ArenaActivity } from "./activity"
import { withChildWaitLimit } from "./child-wait"
import { createPromptDeclines } from "./prompt-declines"
Expand Down Expand Up @@ -1427,6 +1430,13 @@ export interface Interface {
partID: string,
location?: { readonly sessionID?: string; readonly messageID?: string },
) => Effect.Effect<{ readonly part: unknown }, Error>
readonly summaryConversation: (turnID: string) => Effect.Effect<SummaryConversation | null, Error>
readonly sendSummaryMessage: (
turnID: string,
prompt: string,
submissionID: string,
) => Effect.Effect<SummaryConversation, Error>
readonly stopSummaryConversation: (turnID: string) => Effect.Effect<SummaryConversation | null, Error>
readonly diff: (turnID: string) => Effect.Effect<ArenaSchema.ComparisonDiff, Error>
readonly fileDiff: (turnID: string, file: string) => Effect.Effect<ArenaSchema.ComparisonFileDiff, Error>
readonly inspect: (chatID: string, turnID: string, side: Side) => Effect.Effect<ArenaSchema.Snapshot, Error>
Expand Down Expand Up @@ -1887,6 +1897,24 @@ export const layer: Layer.Layer<
}
return yield* instances.provide({ directory }, effect)
})
const summarizer = createSummarizer({
store: available(),
sessions,
prompts,
scope,
inDirectory,
timeline: (store, run) =>
Effect.gen(function* () {
const raw = run.archiveComplete
? archivedMessages(yield* promise(() => archivedSessions(store, run)))
: (yield* Effect.forEach(
[run.rootSessionID, ...run.descendantSessionIDs],
(id) => sessions.messages({ sessionID: SessionID.make(id) }),
{ concurrency: 4 },
)).flat()
return summaryTimeline(ArenaTranscript.fromPromptMessages(raw, run.rootSessionID, promptBoundary(run)))
}),
})
/**
* What a contestant session may not change or reach outside its worktree: it reads the main
* checkout but does not write to it, and does not reach the checkout's `.agent-duel`, which holds
Expand Down Expand Up @@ -13220,6 +13248,9 @@ export const layer: Layer.Layer<
vote(turnID, selected, participantID, acceptFailed).pipe(Effect.mapError(error)),
recordReview,
retryResolution,
summaryConversation: summarizer.get,
sendSummaryMessage: summarizer.send,
stopSummaryConversation: summarizer.stop,
retryComparison,
stop: (turnID) => stop(turnID).pipe(Effect.mapError(error)),
resolveStop: (turnID, resolution, discardReason) =>
Expand Down
Loading
Loading