- {data.title} · {data.role} · {dateFormatter.format(new Date(data.createdAt))} + {data.title} · {messageAuthorLabel(data.role, data.speaker)} ·{" "} + {dateFormatter.format(new Date(data.createdAt))} {data.archived ? " · archived" : ""}
diff --git a/evals/README.md b/evals/README.md index 7dd4ed22cf249..226e0c5a41af8 100644 --- a/evals/README.md +++ b/evals/README.md @@ -10,7 +10,7 @@ Write or run an eval when a change affects what a model sees or does: agent inst | [group-conversation](group-conversation/) | Whether peers engage, preserve attribution, use PASS and handles, edit with the real side chat digest, and continue through delegation. Compares parallel and serial reactions. | | [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | | [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [conversation-summaries](conversation-summaries/) | Whether a roll-up of four conversation summaries keeps reversals, attribution and open items within its budget. | +| [conversation-summaries](conversation-summaries/) | Whether summaries credit a peer's proposal to the peer, and a roll-up keeps reversals, attribution and open items within its budget. | | [model-evaluations](model-evaluations/) | Whether blind judges use outcome evidence, respect task scope, ignore injected scoring instructions, and abstain when evidence is missing. | | [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | | [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | diff --git a/evals/conversation-summaries/README.md b/evals/conversation-summaries/README.md index fad5d3a893340..881401363d2f8 100644 --- a/evals/conversation-summaries/README.md +++ b/evals/conversation-summaries/README.md @@ -1,21 +1,33 @@ # Conversation summaries -Checks the roll-up prompt: four adjacent conversation summaries condensed into one, as the summary pass does for long threads. Each sample calls the server's real summary generator through the local Codex login, with the prompt from this checkout. +Checks how background text generation reads a conversation, using the prompts from this checkout. A leaf summary covers one exchange, including a reply from another model in the thread. A roll-up condenses four adjacent summaries, as the summary pass does for long threads. + +The production summarizer is an OpenCode model. A `gpt-*` model calls the server's real Codex generator through the local Codex login. A `morph-*` model calls Morph's free API directly, using the production prompt builders and reply decoder. The key comes from `MORPH_API_KEY`, or else from the `morph` provider in `~/.config/opencode/opencode.json`. ```sh cd evals -pnpm conversation-summaries --model gpt-6-luna --out runs/summaries-before -pnpm conversation-summaries --model gpt-6-luna --out runs/summaries-after --baseline runs/summaries-before/results.json +pnpm conversation-summaries --model morph-kimik31 --arm main --samples 8 --out runs/peer-main +pnpm conversation-summaries --model morph-kimik31 --arm full --samples 8 --out runs/peer-full --baseline runs/peer-main/results.json ``` +`--arm` sets how a peer reply reaches the model, so the arms compare from one checkout: + +- `main` sends it as a nameless assistant message, as `main` does. Its leaf case fails by construction, because the name the grader wants is not in the input. +- `peer-as-user` renders it as a historical user message with the speaker in its header, as handoff history renders a peer. +- `full` is this checkout, where it carries the peer's name. It is the default. + +Cases: + - `condensed-four-sources-retain-reversal-and-unverified-claim` passes when the roll-up keeps the later Postgres decision instead of the reversed Redis one, keeps the agent's test claim attributed and unverified, keeps the open rollback script, cites only the given summaries, and fits in 1,200 characters. - `condensed-four-ordinary-sources` is the control: an ordinary docs task that must keep its open item and fit the same budget. -- `--case` limits the run, `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. +- `leaf-peer-proposal-is-not-a-user-decision` passes when the summary names Astra as the one who proposed Postgres, and credits that proposal to neither the user nor the agent. +- `leaf-ordinary-exchange-has-no-peer` is the leaf control: an ordinary docs task with no peer. +- `--case ` limits the run, and `--samples ` sets samples per case (default 3). A case fails when half or more of its samples fail. Read the statements in `results.json` as well as the automated result. ## Add a case -Add an entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. `run.test.ts` tests the grader. +Add a condensed entry to `cases.ts` with an `id`, a `kind`, a `source`, the four child `summaries`, and the regex checks. A leaf entry has `messages` instead of `summaries`. `run.test.ts` tests the grader. ## Cost -Each sample is one paid call through the local subscription; the full suite is six. The CLI does not report per-call cost here. +A `morph-*` sample is free but rate limited to about 24,000 uncached input tokens a minute; the runner waits out `Retry-After`. A `gpt-*` sample is one call on the local subscription. The CLI does not report per-call cost. diff --git a/evals/conversation-summaries/cases.ts b/evals/conversation-summaries/cases.ts index 08742d1a02dc6..886bacc738b71 100644 --- a/evals/conversation-summaries/cases.ts +++ b/evals/conversation-summaries/cases.ts @@ -1,3 +1,94 @@ +/** One finalized exchange, as a leaf summary pass sends it. A peer carries the seat that spoke. */ +export type LeafMessage = + | { readonly role: "user" | "assistant"; readonly text: string } + | { + readonly role: "peer"; + readonly text: string; + readonly speaker: { readonly label: string; readonly model: string }; + }; + +export interface LeafCase { + readonly id: string; + readonly kind: "bad" | "control"; + readonly source: string; + readonly messages: ReadonlyArray ; + /** Each regex must match some statement. */ + readonly mustMention: ReadonlyArray ; + /** A statement matching `when` must also match `require`. */ + readonly attributed: ReadonlyArray<{ readonly when: string; readonly require: string }>; + /** No statement may match these. */ + readonly mustNot: ReadonlyArray ; +} + +/** Words that keep a choice open or point away from Postgres before it is named. */ +const open = String.raw`(?:not|never|against|between|whether|if|or|wait|waiting|before|keep|keeping|rather than|instead of)`; +/** `target` within the clause, with no `open` word before it. */ +const toward = (target: string) => String.raw`(?:(?!\b${open}\b)[^.;]){0,60}\b${target}\b`; + +/** + * Statements that hand the peer's Postgres proposal to the user or to the thread's agent, whom the + * summarizer sees as `assistant`. Regexes, so they miss paraphrase; read the statements too. + */ +const misattributed = [ + String.raw`\buser asked to (?:drop Redis|use Postgres|keep Redis)`, + String.raw`\buser\s+(?:(?:is|has|had|then|also|later|finally|ultimately|eventually|now)\s+)*(?:decided|chose|chosen|picked|selected|opted|wants|wanted|going with|went with|goes with|settled on|agreed|accepted|approved|adopted|endorsed|signed off)\b${toward("(?:Postgres|Astra|proposal|suggestion)")}`, + String.raw`\buser's (?:decision|choice|pick|preference)\b${toward("Postgres")}`, + String.raw`\b(?:per|according to) the user\b${toward("Postgres")}`, + String.raw`\bPostgres\b[^.;]{0,60}(?:\b(?:per|according to|as (?:decided|requested|chosen|approved) by)\s+the user\b|\bat the user's (?:request|direction)\b)`, + String.raw`\b(?:agent|assistant)\s+(?:(?:also|first|then|initially|had|has)\s+)*(?:propos(?:ed|es)|suggest(?:ed|s)|recommend(?:ed|s)|push(?:ed|es) for|answered|said|replied|argued|wants|wanted)\b${toward("Postgres")}`, + String.raw`\b(?:agent|assistant)'s (?:proposal|suggestion|recommendation)\b${toward("Postgres")}`, +]; + +/** The leaf exchange: the user asks, Astra proposes, the agent disagrees. */ +const peerProposal: ReadonlyArray = [ + { role: "user", text: "Where should sessions live? I have not decided." }, + { + role: "peer", + speaker: { label: "Astra", model: "gpt-6-astra" }, + text: "Drop Redis and use Postgres for sessions.", + }, + { + role: "assistant", + text: "I disagree. Keep Redis for sessions. The choice is still open.", + }, +]; + +const peerProposalSource = + 'Group threads (ScriptedAlchemy/t3code#131): a seat model\'s published reply reached the summarizer as a plain assistant message with no name, and production summaries said "The assistant answered" for words the peer spoke.'; + +export const leafCases: ReadonlyArray = [ + { + id: "leaf-peer-proposal-is-not-a-user-decision", + kind: "bad", + source: peerProposalSource, + messages: peerProposal, + mustMention: ["Astra", "Postgres"], + attributed: [ + { + // A verb, not "the proposal", so a statement that credits no one stays open. + when: `(?:propos|suggest|recommend)(?:ed|es|s)\\b${toward("Postgres")}|Postgres\\b[^.]{0,80}\\b(?:propos|suggest|recommend)ed\\b`, + require: "Astra", + }, + ], + mustNot: misattributed, + }, + { + id: "leaf-ordinary-exchange-has-no-peer", + kind: "control", + source: "Control for peer attribution: an ordinary user and agent exchange with no peer.", + messages: [ + { role: "user", text: "Add a README section on configuring the proxy." }, + { + role: "assistant", + text: "I added the README section with an example config. The link checker has not run yet.", + }, + ], + mustMention: ["README", "link checker|links"], + attributed: [], + mustNot: ["Astra"], + }, +]; + /** A roll-up input: four adjacent child summaries, oldest first, as the summary pass sends them. */ export interface CondensedCase { readonly id: string; diff --git a/evals/conversation-summaries/grade.ts b/evals/conversation-summaries/grade.ts index 506611fcb42f4..2fa438d578a9f 100644 --- a/evals/conversation-summaries/grade.ts +++ b/evals/conversation-summaries/grade.ts @@ -1,29 +1,60 @@ -import type { CondensedCase } from "./cases.ts"; +import type { CondensedCase, LeafCase } from "./cases.ts"; const MAX_CHARS = 1_200; -/** Every way a roll-up reply breaks the case's rules; empty when it passes. */ -export function gradeCondensed( - fixture: CondensedCase, - statements: ReadonlyArray<{ readonly text: string; readonly citations: ReadonlyArray }>, +type Statement = { readonly text: string; readonly citations: ReadonlyArray }; +type Rules = Pick ; + +function gradeStatements( + refs: ReadonlySet , + statements: ReadonlyArray , + rules: Rules, + maxChars: number | undefined, ): ReadonlyArray { - const refs = new Set(fixture.summaries.map((_, index) => `M${index + 1}`)); const texts = statements.map((statement) => statement.text); const failures: Array = []; if (statements.length === 0) failures.push("no statements"); for (const statement of statements) if (!statement.citations.some((ref) => refs.has(ref.trim()))) failures.push(`cites no given source: ${statement.text}`); - const chars = texts.reduce((sum, text) => sum + text.trim().length, 0); - if (chars > MAX_CHARS) failures.push(`${chars} characters, over ${MAX_CHARS}`); - for (const pattern of fixture.mustMention) + if (maxChars !== undefined) { + const chars = texts.reduce((sum, text) => sum + text.trim().length, 0); + if (chars > maxChars) failures.push(`${chars} characters, over ${maxChars}`); + } + for (const pattern of rules.mustMention) if (!texts.some((text) => new RegExp(pattern).test(text))) failures.push(`missing ${pattern}`); - for (const rule of fixture.attributed) + for (const rule of rules.attributed) for (const text of texts) if (new RegExp(rule.when).test(text) && !new RegExp(rule.require, "i").test(text)) failures.push(`${rule.when} without ${rule.require}: ${text}`); - for (const pattern of fixture.mustNot) + for (const pattern of rules.mustNot) for (const text of texts) if (new RegExp(pattern, "i").test(text)) failures.push(`${pattern}: ${text}`); return failures; } + +/** Every way a roll-up reply breaks the case's rules; empty when it passes. */ +export function gradeCondensed( + fixture: CondensedCase, + statements: ReadonlyArray , +): ReadonlyArray { + return gradeStatements( + new Set(fixture.summaries.map((_, index) => `M${index + 1}`)), + statements, + fixture, + MAX_CHARS, + ); +} + +/** Every way a leaf reply breaks the case's rules; empty when it passes. */ +export function gradeLeaf( + fixture: LeafCase, + statements: ReadonlyArray , +): ReadonlyArray { + return gradeStatements( + new Set(fixture.messages.map((_, index) => `M${index + 1}`)), + statements, + fixture, + undefined, + ); +} diff --git a/evals/conversation-summaries/morph.test.ts b/evals/conversation-summaries/morph.test.ts new file mode 100644 index 0000000000000..676844882820d --- /dev/null +++ b/evals/conversation-summaries/morph.test.ts @@ -0,0 +1,49 @@ +import { expect, it } from "@effect/vitest"; +import { ProviderInstanceId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; +import { vi } from "vite-plus/test"; + +import { morphRunner } from "./morph.ts"; + +it.effect("times out when Morph response headers arrive but the body stalls", () => + Effect.gen(function* () { + vi.stubEnv("MORPH_API_KEY", "eval-test-key"); + const reading = Promise.withResolvers (); + const body = Promise.withResolvers (); + const response = new Response(null, { status: 200 }); + using _body = vi.spyOn(response, "arrayBuffer").mockImplementation(() => { + reading.resolve(); + return body.promise; + }); + using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(response); + const completed = new TextEncoder().encode( + JSON.stringify({ + output: [{ type: "message", content: [{ text: '{"statements":[]}' }] }], + }), + ).buffer; + try { + const result = yield* morphRunner()({ + operation: "generateConversationSummary", + cwd: "/project", + modelSelection: { instanceId: ProviderInstanceId.make("morph"), model: "morph-test" }, + prompt: "Summarize the conversation.", + outputSchema: Schema.Struct({ statements: Schema.Array(Schema.Unknown) }), + }).pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => reading.promise); + yield* TestClock.adjust("121 seconds"); + body.resolve(completed); + const exit = yield* Fiber.join(result); + expect(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit).toMatchObject({ + _tag: "TimeoutError", + }); + } finally { + body.resolve(completed); + vi.unstubAllEnvs(); + } + }), +); diff --git a/evals/conversation-summaries/morph.ts b/evals/conversation-summaries/morph.ts new file mode 100644 index 0000000000000..335b09b8c9dcd --- /dev/null +++ b/evals/conversation-summaries/morph.ts @@ -0,0 +1,59 @@ +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; + +import { morphConfig } from "../shared/proxy.ts"; + +const decodeMorphReply = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array( + Schema.Struct({ + type: Schema.String, + content: Schema.optional( + Schema.Array(Schema.Struct({ text: Schema.optional(Schema.String) })), + ), + }), + ), + }), + ), +); + +const MORPH_ATTEMPTS = 8; + +/** Morph's free Responses API, given the production prompt as OpenCode sends it: text only. */ +export const morphRunner = (): TextGenerationOperations.Runner => { + const endpoint = morphConfig(); + return (request) => + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + const post = HttpClientRequest.post(`${endpoint.url}/responses`).pipe( + HttpClientRequest.setHeaders(endpoint.headers), + HttpClientRequest.bodyJson({ + model: request.modelSelection.model, + input: [{ role: "user", content: [{ type: "input_text", text: request.prompt }] }], + store: false, + max_output_tokens: 8_000, + }), + Effect.flatMap(client.execute), + ); + let response = yield* post; + // Morph limits input tokens per minute and says when to come back. + for (let attempt = 1; response.status === 429 || response.status >= 500; attempt++) { + if (attempt >= MORPH_ATTEMPTS) break; + const retryAfter = Number(response.headers["retry-after"]); + yield* Effect.sleep(`${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`); + response = yield* post; + } + // The body is omitted so a credential echoed in an error never reaches the log. + if (response.status !== 200) return yield* Effect.die(`Morph HTTP ${response.status}`); + const reply = yield* decodeMorphReply(yield* response.text); + const text = reply.output + .filter((item) => item.type === "message") + .flatMap((item) => item.content ?? []) + .map((part) => part.text ?? "") + .join(""); + return yield* TextGenerationOperations.decodeJsonReply(request, "Morph", text); + }).pipe(Effect.timeout("120 seconds"), Effect.orDie, Effect.provide(FetchHttpClient.layer)); +}; diff --git a/evals/conversation-summaries/run.test.ts b/evals/conversation-summaries/run.test.ts index dc6f4a2f0c073..42f5de22734a5 100644 --- a/evals/conversation-summaries/run.test.ts +++ b/evals/conversation-summaries/run.test.ts @@ -1,8 +1,15 @@ import { expect, it } from "vite-plus/test"; -import { condensedCases } from "./cases.ts"; -import { gradeCondensed } from "./grade.ts"; +import { condensedCases, leafCases } from "./cases.ts"; +import { gradeCondensed, gradeLeaf } from "./grade.ts"; const [reversal, control] = condensedCases; +const [peerLeaf, ordinaryLeaf] = leafCases; +/** The full leaf grade of one statement beside a sibling that credits Astra, which passes alone. */ +const gradeBesideAstra = (text: string) => + gradeLeaf(peerLeaf!, [ + { text: "Astra proposed Postgres for sessions.", citations: ["M2"] }, + { text, citations: ["M2"] }, + ]); it("passes a roll-up that keeps the reversal, the attribution and the open item", () => { expect( @@ -40,6 +47,79 @@ it("fails a roll-up that drops the reversal, verifies a claim, or overruns its b ); }); +it("passes a leaf that names the peer and leaves the choice open", () => { + expect( + gradeLeaf(peerLeaf!, [ + { + text: "Astra proposed dropping Redis and using Postgres for sessions.", + citations: ["M2"], + }, + { + text: "The agent disagreed and wants to keep Redis. The user has not decided.", + citations: ["M1", "M3"], + }, + ]), + ).toEqual([]); +}); + +it.each([ + "Astra proposed dropping Redis and using Postgres for sessions.", + "The user has not decided.", + "The user has not chosen between Redis and Postgres; the agent prefers Redis.", + "The user has yet to decide between Redis and Postgres.", + "The user hasn't decided whether to use Postgres.", + "The user is still deciding between Redis and Postgres.", + "The user never agreed to Postgres.", + "The agent rejected the proposal to use Postgres.", + "The user decided to wait before choosing Postgres or Redis.", + "The agent suggested keeping Redis rather than Postgres.", +])("leaves an open choice open: %s", (text) => { + expect(gradeBesideAstra(text)).toEqual([]); +}); + +it.each([ + "The user decided to use Postgres for sessions.", + "Astra proposed Postgres and the user agreed to use Postgres.", + "The user chose Postgres for sessions, following Astra.", + "The user accepted Astra's proposal, so sessions move to Postgres.", + "The user went with Postgres.", + "The user approved Postgres.", + "Sessions will move to Postgres, per the user.", + "The agent proposed moving sessions to Postgres; Astra wants to keep Redis.", + "The user is going with Postgres.", + "The user wants Postgres.", + "The user's choice: Postgres for sessions.", + "Per the user, sessions move to Postgres.", + "The user later agreed and sessions moved to Postgres.", + "The assistant answered that sessions should move to Postgres.", + "The assistant recommended Postgres for sessions.", +])("fails a statement that hands the proposal to the user or the agent: %s", (text) => { + expect(gradeBesideAstra(text)).not.toEqual([]); +}); + +it("does not treat an open Postgres choice as the peer's proposal", () => { + expect( + gradeLeaf(peerLeaf!, [ + { + text: "The user has not chosen between Redis and Postgres; the agent prefers Redis.", + citations: ["M1", "M3"], + }, + ]), + ).toEqual(["missing Astra"]); +}); + +it("passes an ordinary leaf with no peer", () => { + expect( + gradeLeaf(ordinaryLeaf!, [ + { + text: "The user asked for a README section on the proxy, and the agent added it.", + citations: ["M1", "M2"], + }, + { text: "The link checker has not run yet.", citations: ["M2"] }, + ]), + ).toEqual([]); +}); + it("passes an ordinary roll-up in the control case", () => { expect( gradeCondensed(control!, [ diff --git a/evals/conversation-summaries/run.ts b/evals/conversation-summaries/run.ts index a6a0cbb3f7202..ef8d8679f7baa 100644 --- a/evals/conversation-summaries/run.ts +++ b/evals/conversation-summaries/run.ts @@ -1,7 +1,9 @@ #!/usr/bin/env node import * as NodeUtil from "node:util"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; +import { CodexSettings, ProviderInstanceId, RunId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -9,8 +11,16 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; import * as ServerConfig from "../../apps/server/src/config.ts"; -import { condensedCases } from "./cases.ts"; -import { gradeCondensed } from "./grade.ts"; +import { condensedCases, leafCases, type LeafMessage } from "./cases.ts"; +import { gradeCondensed, gradeLeaf } from "./grade.ts"; +import { morphRunner } from "./morph.ts"; + +/** + * How a peer reply reaches the model. `main` sends it as a nameless assistant message, as main + * does. `peer-as-user` renders it as a historical user message with the speaker in its header, as + * handoff history does. `full` is this checkout. + */ +const arms = ["main", "peer-as-user", "full"] as const; const { values } = NodeUtil.parseArgs({ options: { @@ -19,18 +29,24 @@ const { values } = NodeUtil.parseArgs({ baseline: { type: "string" }, case: { type: "string" }, samples: { type: "string", default: "3" }, + arm: { type: "string", default: "full" }, }, }); if (!values.model || !values.out) throw new Error("Use --model --out ."); const model = values.model; const outputDirectory = values.out; const samples = Number(values.samples); -const selected = condensedCases.filter( - (fixture) => values.case === undefined || values.case.split(",").includes(fixture.id), -); -if (selected.length === 0) +const arm = arms.find((candidate) => candidate === values.arm); +if (arm === undefined) throw new Error(`Unknown --arm ${values.arm}. Use ${arms.join(", ")}.`); +const morph = model.startsWith("morph-"); +const selectedIds = values.case?.split(","); +const selected = (fixtures: ReadonlyArray ) => + fixtures.filter((fixture) => selectedIds === undefined || selectedIds.includes(fixture.id)); +const selectedCondensed = selected(condensedCases); +const selectedLeaf = selected(leafCases); +if (selectedCondensed.length + selectedLeaf.length === 0) throw new Error( - `Unknown --case ${values.case}. Available cases: ${condensedCases.map((fixture) => fixture.id).join(", ")}`, + `Unknown --case ${values.case}. Available cases: ${[...condensedCases, ...leafCases].map((fixture) => fixture.id).join(", ")}`, ); const Results = Schema.Array( Schema.Struct({ @@ -46,6 +62,28 @@ const Results = Schema.Array( const decodeSettings = Schema.decodeUnknownSync(CodexSettings); const decodeResults = Schema.decodeEffect(Schema.fromJsonString(Results)); const encodeResults = Schema.encodeEffect(Schema.fromJsonString(Results)); +const asArm = (message: LeafMessage, index: number) => { + const ref = `M${index + 1}`; + if (message.role !== "peer" || arm === "full") return { ref, ...message }; + if (arm === "main") return { ref, role: "assistant" as const, text: message.text }; + const [, rendered] = historyResponseItems( + [ + { + role: "user", + text: message.text, + speaker: message.speaker, + threadId: ThreadId.make("thread"), + runId: RunId.make("run"), + itemId: TurnItemId.make(`item-${ref}`), + providerThreadId: null, + status: "completed", + kind: "peer_reply", + }, + ], + "", + ); + return { ref, role: "user" as const, text: rendered!.content[0]!.text }; +}; await Effect.runPromise( Effect.gen(function* () { @@ -55,27 +93,44 @@ await Effect.runPromise( ? yield* fs.readFileString(values.baseline).pipe(Effect.tap(decodeResults)) : undefined; const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-summary-eval-" }); - const generation = yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); + const generation = morph + ? TextGenerationOperations.fromRunner("Morph", morphRunner()) + : yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); + const modelSelection = { + instanceId: ProviderInstanceId.make(morph ? "morph" : "codex"), + model, + }; const results: Array<(typeof Results.Type)[number]> = []; - for (const fixture of selected) { + const record = ( + id: string, + sample: number, + statements: (typeof Results.Type)[number]["statements"], + failures: ReadonlyArray , + ) => { + results.push({ id, sample, statements, failures, passed: failures.length === 0 }); + }; + for (const fixture of selectedCondensed) { for (let sample = 0; sample < samples; sample++) { const { statements } = yield* generation.generateConversationSummary({ cwd, - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model }, + modelSelection, messages: fixture.summaries.map((text, index) => ({ ref: `M${index + 1}`, - role: "summary", + role: "summary" as const, text, })), }); - const failures = gradeCondensed(fixture, statements); - results.push({ - id: fixture.id, - sample, - statements, - failures, - passed: failures.length === 0, + record(fixture.id, sample, statements, gradeCondensed(fixture, statements)); + } + } + for (const fixture of selectedLeaf) { + for (let sample = 0; sample < samples; sample++) { + const { statements } = yield* generation.generateConversationSummary({ + cwd, + modelSelection, + messages: fixture.messages.map(asArm), }); + record(fixture.id, sample, statements, gradeLeaf(fixture, statements)); } } yield* fs.makeDirectory(outputDirectory, { recursive: true }); @@ -85,12 +140,12 @@ await Effect.runPromise( ); if (baseline !== undefined) yield* fs.writeFileString(path.join(outputDirectory, "baseline.json"), baseline); - for (const fixture of selected) { + for (const fixture of [...selectedCondensed, ...selectedLeaf]) { const rows = results.filter((row) => row.id === fixture.id); const passed = rows.filter((row) => row.passed).length; // A case fails when half or more of its samples fail. yield* Effect.log( - `${fixture.id} (${fixture.kind}): ${passed}/${rows.length} samples passed, ${passed * 2 > rows.length ? "PASS" : "FAIL"}`, + `${arm} ${fixture.id} (${fixture.kind}): ${passed}/${rows.length} samples passed, ${passed * 2 > rows.length ? "PASS" : "FAIL"}`, ); } yield* Effect.log(`Results in ${outputDirectory}`); diff --git a/evals/shared/proxy.ts b/evals/shared/proxy.ts index ede72be8fdab2..fb4f123a2ad4e 100644 --- a/evals/shared/proxy.ts +++ b/evals/shared/proxy.ts @@ -31,3 +31,33 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h})) ), ), ); + +/** + * Morph's free OpenAI-compatible API, for evals that should not spend on paid models. The key is + * `MORPH_API_KEY`, else the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`). + */ +export const morphConfig = () => + decodeProxyConfig( + JSON.parse( + NodeChildProcess.execFileSync( + "python3", + [ + "-c", + ` +import json, os, pathlib +key = os.environ.get('MORPH_API_KEY') +url = os.environ.get('MORPH_BASE_URL', 'https://api.morphllm.com/v1') +if not key: + home = pathlib.Path(os.environ.get('XDG_CONFIG_HOME') or pathlib.Path.home() / '.config') + # OpenCode writes literal control characters inside strings, which strict parsing rejects. + settings = json.loads((home / 'opencode' / 'opencode.json').read_text(), strict=False)['providers']['morph']['settings'] + key, url = settings.get('apiKey'), settings.get('baseURL', url) +if not key: + raise SystemExit('no morph key') +print(json.dumps({'url': url.rstrip('/'), 'headers': {'Authorization': 'Bearer ' + key}})) +`, + ], + { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, + ), + ), + ); diff --git a/packages/client-runtime/src/conversationSummaries/index.ts b/packages/client-runtime/src/conversationSummaries/index.ts index 75599b3ef7587..430ed8c2a8488 100644 --- a/packages/client-runtime/src/conversationSummaries/index.ts +++ b/packages/client-runtime/src/conversationSummaries/index.ts @@ -49,6 +49,17 @@ export interface ConversationSummarySourceCursor { readonly textOffset: number; } +/** Who wrote a message: the user, the thread's agent, or the peer seat that spoke it. */ +export function messageAuthorLabel( + role: "user" | "assistant", + speaker?: { readonly label: string; readonly model: string }, +): string { + if (role === "user") return "User"; + if (speaker === undefined) return "Assistant"; + // A seat without a label is named by its model. + return speaker.label === speaker.model ? speaker.label : `${speaker.label} (${speaker.model})`; +} + /** Who a source came from; a child summary is named by its id so it can be opened. */ export function conversationSummarySourceLabel( ref: ConversationSummarySourceRef, @@ -57,9 +68,8 @@ export function conversationSummarySourceLabel( if (result.state !== "available") return "Unavailable"; switch (result.role) { case "user": - return "User"; case "assistant": - return "Assistant"; + return messageAuthorLabel(result.role, result.speaker); case "tool": return "Tool"; case "summary": diff --git a/packages/contracts/src/conversationSummaries.ts b/packages/contracts/src/conversationSummaries.ts index 3fd05d6c43490..7ac71dcc93d1f 100644 --- a/packages/contracts/src/conversationSummaries.ts +++ b/packages/contracts/src/conversationSummaries.ts @@ -6,6 +6,7 @@ import { ProjectId, RunId, ThreadId, + TrimmedNonEmptyString, TurnItemId, } from "./baseSchemas.ts"; import { ModelSelection } from "./modelSelection.ts"; @@ -84,6 +85,10 @@ export const ConversationSummarySourceResult = Schema.Union([ title: Schema.String, /** "summary" when the source is a child summary; its text is that summary's statements. */ role: Schema.Literals(["user", "assistant", "tool", "summary"]), + /** Set when an assistant message was spoken by another model in the thread. */ + speaker: Schema.optionalKey( + Schema.Struct({ label: TrimmedNonEmptyString, model: TrimmedNonEmptyString }), + ), createdAt: IsoDateTime, archived: Schema.Boolean, /** Offset and total length within this source's recorded range. */ diff --git a/packages/contracts/src/projectKnowledge.ts b/packages/contracts/src/projectKnowledge.ts index 80c4ea03dd1b4..325f4e2b356e3 100644 --- a/packages/contracts/src/projectKnowledge.ts +++ b/packages/contracts/src/projectKnowledge.ts @@ -328,6 +328,10 @@ const ProjectKnowledgeSourceSchema = Schema.Union([ text: Schema.String, title: Schema.String, role: Schema.Literals(["user", "assistant"]), + /** Set when an assistant message was spoken by another model in the thread. */ + speaker: Schema.optionalKey( + Schema.Struct({ label: TrimmedNonEmptyString, model: TrimmedNonEmptyString }), + ), createdAt: IsoDateTime, archived: Schema.Boolean, }), diff --git a/packages/provider-core/src/server/textGeneration.ts b/packages/provider-core/src/server/textGeneration.ts index 57f97ca637550..e542477fd7bc1 100644 --- a/packages/provider-core/src/server/textGeneration.ts +++ b/packages/provider-core/src/server/textGeneration.ts @@ -12,7 +12,11 @@ import type { import type * as Effect from "effect/Effect"; import type { TextGenerationPolicy } from "./textGenerationPolicy.ts"; -import type { ThreadTitleForkSource } from "./textGenerationPrompts.ts"; +import type { + ConversationSummaryPromptMessage, + KnowledgeCandidatesPromptMessage, + ThreadTitleForkSource, +} from "./textGenerationPrompts.ts"; export interface CommitMessageGenerationInput { cwd: string; @@ -111,14 +115,7 @@ export interface KnowledgeCandidatesGenerationInput { cwd: string; runOutcome: "completed" | "failed" | "interrupted"; /** Finalized new evidence from one thread family, oldest first; `ref` is what citations name. */ - messages: ReadonlyArray<{ - readonly ref: string; - readonly threadId?: string; - readonly runId?: string; - readonly runOutcome?: "completed" | "failed" | "interrupted"; - readonly role: "user" | "assistant"; - readonly text: string; - }>; + messages: ReadonlyArray ; modelSelection: ModelSelection; } @@ -137,12 +134,7 @@ export interface ConversationSummaryGenerationInput { * Consecutive finalized source ranges, or consecutive summaries for a roll-up, oldest first; * `ref` is what citations name. */ - messages: ReadonlyArray<{ - readonly ref: string; - readonly role: "user" | "assistant" | "tool" | "summary"; - readonly text: string; - readonly range?: { readonly start: number; readonly end: number; readonly total: number }; - }>; + messages: ReadonlyArray ; modelSelection: ModelSelection; } diff --git a/packages/provider-core/src/server/textGenerationPrompts.ts b/packages/provider-core/src/server/textGenerationPrompts.ts index 421a76838a860..fea15f7858dff 100644 --- a/packages/provider-core/src/server/textGenerationPrompts.ts +++ b/packages/provider-core/src/server/textGenerationPrompts.ts @@ -504,16 +504,29 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { return { prompt, outputSchema }; } +type PeerSpeaker = { readonly label: string; readonly model: string }; + +/** A seat without a label is named by its model; say it once. */ +const peerDetails = (speaker: PeerSpeaker, extra?: string) => + [ + ...(speaker.label === speaker.model ? [] : [speaker.model]), + ...(extra === undefined ? [] : [extra]), + ].join(", "); + +export type KnowledgeCandidatesPromptMessage = { + readonly ref: string; + readonly threadId?: string; + readonly runId?: string; + readonly runOutcome?: "completed" | "failed" | "interrupted"; + readonly text: string; +} & ( + | { readonly role: "user" | "assistant" } + | { readonly role: "peer"; readonly speaker: PeerSpeaker } +); + export interface KnowledgeCandidatesPromptInput { runOutcome: "completed" | "failed" | "interrupted"; - messages: ReadonlyArray<{ - readonly ref: string; - readonly threadId?: string; - readonly runId?: string; - readonly runOutcome?: "completed" | "failed" | "interrupted"; - readonly role: "user" | "assistant"; - readonly text: string; - }>; + messages: ReadonlyArray ; } export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptInput) { @@ -545,10 +558,15 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI ]), "", "Messages:", - ...input.messages.map( - (message) => - `[${message.ref}] ${message.role}${message.runId === undefined ? "" : ` (${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome})`}:\n${message.text}\n`, - ), + ...input.messages.map((message) => { + const run = + message.runId === undefined + ? undefined + : `${threads.get(message.threadId ?? "") ?? "T?"}/${runs.get(message.runId)}, ${message.runOutcome ?? input.runOutcome}`; + const role = message.role === "peer" ? `peer ${message.speaker.label}` : message.role; + const details = message.role === "peer" ? peerDetails(message.speaker, run) : run; + return `[${message.ref}] ${role}${details ? ` (${details})` : ""}:\n${message.text}\n`; + }), ].join("\n"); const outputSchema = Schema.Struct({ candidates: Schema.Array( @@ -566,13 +584,17 @@ export function buildKnowledgeCandidatesPrompt(input: KnowledgeCandidatesPromptI /** The rolled-up statements must fit beside the verbatim tail of a small handoff. */ const CONDENSED_SUMMARY_MAX_CHARS = 1_200; +export type ConversationSummaryPromptMessage = { + readonly ref: string; + readonly text: string; + readonly range?: { readonly start: number; readonly end: number; readonly total: number }; +} & ( + | { readonly role: "user" | "assistant" | "tool" | "summary" } + | { readonly role: "peer"; readonly speaker: PeerSpeaker } +); + export interface ConversationSummaryPromptInput { - messages: ReadonlyArray<{ - readonly ref: string; - readonly role: "user" | "assistant" | "tool" | "summary"; - readonly text: string; - readonly range?: { readonly start: number; readonly end: number; readonly total: number }; - }>; + messages: ReadonlyArray ; } export function buildConversationSummaryPrompt(input: ConversationSummaryPromptInput) { @@ -595,10 +617,18 @@ export function buildConversationSummaryPrompt(input: ConversationSummaryPromptI : []), "", "Sources:", - ...input.messages.map( - (message) => - `[${message.ref}] ${message.role}${message.range === undefined ? "" : ` (UTF-16 range ${message.range.start}–${message.range.end} of ${message.range.total})`}:\n${message.text}\n`, - ), + ...input.messages.map((message) => { + const details = message.role === "peer" ? peerDetails(message.speaker) : ""; + const role = + message.role === "peer" + ? `peer ${message.speaker.label}${details ? ` (${details})` : ""}` + : message.role; + const range = + message.range === undefined + ? "" + : ` (UTF-16 range ${message.range.start}–${message.range.end} of ${message.range.total})`; + return `[${message.ref}] ${role}${range}:\n${message.text}\n`; + }), ].join("\n"); const outputSchema = Schema.Struct({ statements: Schema.Array(