feat: add multi-run fusion and session change walkthroughs

Fuse two to five completed multi-run entries into one synthesized session,
and explain a session's diff as ordered walkthrough stops cached by diff hash.

- Multi-run fusion service, persistence, routes and FuseRunDialog
- Change walkthrough service, persistence, routes and ChangesWalkthroughDialog
- Shared unified-diff parser plus bounded text generation, json-extract,
  text-truncate and service-error helpers
This commit is contained in:
Chris Scott committed 2026-10-06 15:27:14 -04:00
1 parent 90c6ccf236
commit b36d412ca2
66 files changed
+6228 -468

No files matched your search

+344
View File
@@ -0,0 +1,344 @@
import type { Database } from 'bun:sqlite'
import { createHash } from 'node:crypto'
import { z } from 'zod'
import {
isSessionNotFoundError,
type FileDiffInfo,
type SessionInfo,
} from '@opencode-manager/shared/opencode'
import {
WALKTHROUGH_DIFF_MAX_CHARS,
WALKTHROUGH_HUNK_MAX_CHARS,
WALKTHROUGH_MAX_STOPS,
WALKTHROUGH_TEXT_MAX_CHARS,
type ChangeWalkthrough,
type ChangeWalkthroughState,
type GenerateChangeWalkthroughRequest,
type WalkthroughHunk,
type WalkthroughOmittedFile,
type WalkthroughStop,
} from '@opencode-manager/shared/schemas'
import { splitDiffHunks } from '@opencode-manager/shared/utils'
import { getChangeWalkthrough, saveChangeWalkthrough } from '../db/change-walkthroughs'
import { getErrorMessage } from '../utils/error-utils'
import { ServiceError } from '../utils/service-error'
import { truncateText } from '../utils/text-truncate'
import { extractFirstJsonObject } from '../utils/json-extract'
import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text'
import type { OpenCodeClient } from './opencode/client'
import { readSessionChanges } from './session-changes'
const DEFAULT_TIMEOUT_MS = 120_000
const HUNK_TRUNCATION_MARKER = '\n[hunk truncated]'
const TEXT_TRUNCATION_MARKER = ''
const REMAINING_STOP_TITLE = 'Remaining changes'
const REMAINING_STOP_EXPLANATION = 'These changes were not covered by the generated walkthrough.'
const modelStopSchema = z.object({
title: z.string().catch(''),
explanation: z.string().catch(''),
hunkIds: z.array(z.string()).catch([]),
})
const modelResponseSchema = z.object({
summary: z.string().catch(''),
stops: z.array(modelStopSchema),
})
export interface WalkthroughInput {
hunks: WalkthroughHunk[]
omittedFiles: WalkthroughOmittedFile[]
}
export interface ParsedWalkthrough {
summary: string
stops: WalkthroughStop[]
}
export interface ChangeWalkthroughServiceOptions {
timeoutMs?: number
}
export class ChangeWalkthroughError extends ServiceError {
constructor(message: string, status: number, options?: { code?: string; details?: unknown }) {
super(message, status, options)
this.name = 'ChangeWalkthroughError'
}
}
export function computeChangesHash(changes: FileDiffInfo[]): string {
const hash = createHash('sha256')
for (const change of changes) {
hash.update(`${change.file}\0${change.status}\0${change.patch}\n`)
}
return hash.digest('hex')
}
export function buildWalkthroughInstructions(title: string): string {
return [
`You are writing a change walkthrough for a reviewer who reads it top to bottom to understand the change to "${title}".`,
'## How to write the walkthrough',
[
'- Order the stops by the reading order that best explains the change: contracts and data model first, then core logic, then callers and UI, then tests and config.',
'- Group related hunks, possibly across files.',
'- Reference only the hunk ids given below, each at most once.',
`- Use at most ${WALKTHROUGH_MAX_STOPS} stops.`,
'- Explain intent and impact rather than restating the code.',
'- Respond with only the JSON {"summary": string, "stops": [{"title": string, "explanation": string, "hunkIds": string[]}]}.',
].join('\n'),
'## Hunks',
].join('\n')
}
export function formatHunkBlock(hunk: WalkthroughHunk): string {
return `### ${hunk.id} ${hunk.file} (${hunk.status})\n\n\`\`\`diff\n${hunk.text}\n\`\`\``
}
export function buildWalkthroughInput(changes: FileDiffInfo[], title: string): WalkthroughInput {
const hunks: WalkthroughHunk[] = []
const omittedFiles: WalkthroughOmittedFile[] = []
let total = buildWalkthroughInstructions(title).length
let budgetExhausted = false
changes.forEach((change, fileIndex) => {
if (budgetExhausted) {
omittedFiles.push({ file: change.file, reason: 'budget' })
return
}
const fileHunks = splitDiffHunks(change.patch)
if (fileHunks.length === 0) {
omittedFiles.push({ file: change.file, reason: 'binary' })
return
}
const prepared = fileHunks.map((hunk, hunkIndex) => {
const truncated = truncateText(hunk.text, WALKTHROUGH_HUNK_MAX_CHARS, HUNK_TRUNCATION_MARKER)
return {
id: `f${fileIndex}h${hunkIndex}`,
file: change.file,
status: change.status,
header: hunk.header,
text: truncated.text,
truncated: truncated.truncated,
} satisfies WalkthroughHunk
})
const fileTotal = prepared.reduce((sum, hunk) => sum + formatHunkBlock(hunk).length + 2, 0)
if (total + fileTotal > WALKTHROUGH_DIFF_MAX_CHARS) {
budgetExhausted = true
omittedFiles.push({ file: change.file, reason: 'budget' })
return
}
total += fileTotal
hunks.push(...prepared)
})
return { hunks, omittedFiles }
}
export function buildWalkthroughPrompt({ title, hunks }: { title: string; hunks: WalkthroughHunk[] }): string {
const instructions = buildWalkthroughInstructions(title)
const blocks = hunks.map((hunk) => formatHunkBlock(hunk))
return [instructions, ...blocks].join('\n\n')
}
export function parseWalkthroughResponse(text: string, hunks: WalkthroughHunk[]): ParsedWalkthrough | null {
const extracted = extractFirstJsonObject(text)
if (!extracted) {
return null
}
let raw: unknown
try {
raw = JSON.parse(extracted)
} catch {
return null
}
const parsed = modelResponseSchema.safeParse(raw)
if (!parsed.success) {
return null
}
const validIds = new Set(hunks.map((hunk) => hunk.id))
const referenced = new Set<string>()
const stops: WalkthroughStop[] = []
for (const modelStop of parsed.data.stops) {
if (stops.length >= WALKTHROUGH_MAX_STOPS) {
break
}
const hunkIds: string[] = []
for (const id of modelStop.hunkIds) {
if (!validIds.has(id) || referenced.has(id)) {
continue
}
referenced.add(id)
hunkIds.push(id)
}
if (hunkIds.length === 0) {
continue
}
stops.push({
title: truncateText(modelStop.title, WALKTHROUGH_TEXT_MAX_CHARS, TEXT_TRUNCATION_MARKER).text,
explanation: truncateText(modelStop.explanation, WALKTHROUGH_TEXT_MAX_CHARS, TEXT_TRUNCATION_MARKER).text,
hunkIds,
})
}
if (stops.length === 0) {
return null
}
const unreferenced = hunks.filter((hunk) => !referenced.has(hunk.id)).map((hunk) => hunk.id)
if (unreferenced.length > 0) {
stops.push({
title: REMAINING_STOP_TITLE,
explanation: REMAINING_STOP_EXPLANATION,
hunkIds: unreferenced,
})
}
return {
summary: truncateText(parsed.data.summary, WALKTHROUGH_TEXT_MAX_CHARS, TEXT_TRUNCATION_MARKER).text,
stops,
}
}
export class ChangeWalkthroughService {
private readonly inFlight = new Map<string, Promise<{ walkthrough: ChangeWalkthrough; created: boolean }>>()
private readonly timeoutMs: number
constructor(
private readonly db: Database,
private readonly openCodeClient: OpenCodeClient,
options: ChangeWalkthroughServiceOptions = {},
) {
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
}
async getState(sessionId: string): Promise<ChangeWalkthroughState> {
await this.readSession(sessionId)
let currentDiffHash: string | null = null
try {
const changes = await readSessionChanges(this.openCodeClient, sessionId)
currentDiffHash = computeChangesHash(changes)
} catch {
currentDiffHash = null
}
const walkthrough = getChangeWalkthrough(this.db, sessionId)
return {
walkthrough,
currentDiffHash,
stale: walkthrough !== null && currentDiffHash !== null && walkthrough.diffHash !== currentDiffHash,
}
}
generate(sessionId: string, request: GenerateChangeWalkthroughRequest): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
const existing = this.inFlight.get(sessionId)
if (existing) {
return existing
}
const pending = this.runGenerate(sessionId, request).finally(() => {
this.inFlight.delete(sessionId)
})
this.inFlight.set(sessionId, pending)
return pending
}
private async runGenerate(
sessionId: string,
request: GenerateChangeWalkthroughRequest,
): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
const session = await this.readSession(sessionId)
let changes: FileDiffInfo[]
try {
changes = await readSessionChanges(this.openCodeClient, sessionId)
} catch (error) {
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to read session changes', 502, {
code: 'WALKTHROUGH_CHANGES_UNAVAILABLE',
})
}
if (changes.length === 0) {
throw new ChangeWalkthroughError('This session has no changes to walk through', 409, {
code: 'WALKTHROUGH_NO_CHANGES',
})
}
const diffHash = computeChangesHash(changes)
const stored = getChangeWalkthrough(this.db, sessionId)
if (stored && stored.diffHash === diffHash && !request.regenerate) {
return { walkthrough: stored, created: false }
}
const title = session.title ?? sessionId
const { hunks, omittedFiles } = buildWalkthroughInput(changes, title)
if (hunks.length === 0) {
if (omittedFiles.some((file) => file.reason === 'budget')) {
throw new ChangeWalkthroughError('These changes are too large to walk through', 413, {
code: 'WALKTHROUGH_CONTEXT_LIMIT',
details: { omittedFiles },
})
}
throw new ChangeWalkthroughError('This session has no text changes to walk through', 409, {
code: 'WALKTHROUGH_NO_TEXT_CHANGES',
})
}
const prompt = buildWalkthroughPrompt({ title, hunks })
let responseText: string
try {
responseText = await generateTextWithTimeout(this.openCodeClient, { prompt }, this.timeoutMs)
} catch (error) {
if (error instanceof GenerateTextTimeoutError) {
throw new ChangeWalkthroughError('Generating the change walkthrough timed out', 504, {
code: 'WALKTHROUGH_TIMEOUT',
})
}
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to generate the change walkthrough', 502)
}
const parsed = parseWalkthroughResponse(responseText, hunks)
if (!parsed) {
throw new ChangeWalkthroughError('The model did not return a usable change walkthrough', 502, {
code: 'WALKTHROUGH_UNPARSEABLE',
})
}
const walkthrough: ChangeWalkthrough = {
sessionId,
diffHash,
summary: parsed.summary,
stops: parsed.stops,
hunks,
omittedFiles,
createdAt: Date.now(),
}
saveChangeWalkthrough(this.db, walkthrough)
return { walkthrough, created: true }
}
private async readSession(sessionId: string): Promise<SessionInfo> {
try {
return await this.openCodeClient.api.session.get({ sessionID: sessionId })
} catch (error) {
if (isSessionNotFoundError(error)) {
throw new ChangeWalkthroughError('Session not found', 404)
}
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to read session', 502)
}
}
}
@@ -1,18 +1,15 @@
import { truncateText } from '../../utils/text-truncate'
export const MAX_COMMIT_PROMPT_DIFF_CHARS = 60_000
const COMMIT_PROMPT_DIFF_TRUNCATION_MARKER = '\n[diff truncated]'
export interface CommitMessageContext {
stagedStat: string
stagedDiff: string
recentSubjects: string[]
}
function truncateDiff(diff: string): string {
if (diff.length <= MAX_COMMIT_PROMPT_DIFF_CHARS) {
return diff
}
return `${diff.slice(0, MAX_COMMIT_PROMPT_DIFF_CHARS)}\n[diff truncated]`
}
export function buildCommitMessagePrompt({ stagedStat, stagedDiff, recentSubjects }: CommitMessageContext): string {
const subjects = recentSubjects.length > 0
? recentSubjects.map(subject => `- ${subject}`).join('\n')
@@ -31,7 +28,7 @@ export function buildCommitMessagePrompt({ stagedStat, stagedDiff, recentSubject
stagedStat.trim(),
'',
'Staged diff:',
truncateDiff(stagedDiff),
truncateText(stagedDiff, MAX_COMMIT_PROMPT_DIFF_CHARS, COMMIT_PROMPT_DIFF_TRUNCATION_MARKER).text,
].join('\n')
}
+267
View File
@@ -0,0 +1,267 @@
import {
isSessionNotFoundError,
type FileDiffInfo,
type SessionInfo,
} from '@opencode-manager/shared/opencode'
import {
FUSION_PROMPT_MAX_LENGTH,
type FusionUnavailableSource,
type MultiRunFusionSource,
} from '@opencode-manager/shared/schemas'
import type { MultiRunEntryRecord } from '../db/multi-runs'
import { getErrorMessage } from '../utils/error-utils'
import { ServiceError } from '../utils/service-error'
import { truncateText } from '../utils/text-truncate'
import type { OpenCodeClient } from './opencode/client'
import { readSessionChanges } from './session-changes'
import {
SESSION_REPLY_TRUNCATION_MARKER,
isSessionBusyIn,
readLatestAssistantReply,
type ActiveSessions,
} from './session-reply'
export interface CollectedFusionSource {
entryId: number
model: string
sessionId: string
directory: string | null
outcome: 'succeeded' | 'failed' | 'interrupted' | null
replyText: string
changes: FileDiffInfo[] | null
}
export interface FusionSourceCollection {
ready: CollectedFusionSource[]
unavailable: FusionUnavailableSource[]
}
export const FUSION_MIN_SOURCE_CONTEXT = 1500
const FUSION_REPLY_BUDGET_RATIO = 0.4
const FUSION_BLOCK_SEPARATOR = '\n\n'
export class FusionContextLimitError extends ServiceError {
constructor(requiredPerSource: number, availablePerSource: number) {
super(
'The selected results are too large to fuse. Select fewer sources or shorten the instructions.',
413,
{ code: 'FUSION_CONTEXT_LIMIT', details: { requiredPerSource, availablePerSource } },
)
this.name = 'FusionContextLimitError'
}
}
export interface FusionPromptInput {
runName: string
objective: string
instructions?: string
sources: CollectedFusionSource[]
}
export interface FusionPrompt {
prompt: string
sources: MultiRunFusionSource[]
}
export function buildFusionPrompt({ runName, objective, instructions, sources }: FusionPromptInput): FusionPrompt {
const preamble = buildFusionPreamble({ runName, objective, instructions })
if (sources.length === 0) {
return { prompt: preamble, sources: [] }
}
const scaffolds = sources.map((source, index) => buildFusionSourceBlock(source, index, '', source.changes === null ? null : ''))
const fixed = preamble.length
+ scaffolds.reduce((total, scaffold) => total + scaffold.length, 0)
+ FUSION_BLOCK_SEPARATOR.length * sources.length
const perSource = Math.floor((FUSION_PROMPT_MAX_LENGTH - fixed) / sources.length)
if (perSource < FUSION_MIN_SOURCE_CONTEXT) {
throw new FusionContextLimitError(FUSION_MIN_SOURCE_CONTEXT, perSource)
}
const markerLength = SESSION_REPLY_TRUNCATION_MARKER.length
const replySlot = Math.floor(perSource * FUSION_REPLY_BUDGET_RATIO)
const replyBudget = Math.max(replySlot - markerLength, 0)
const patchBudget = Math.max(perSource - replySlot - markerLength, 0)
const attributed: MultiRunFusionSource[] = []
const blocks = sources.map((source, index) => {
const reply = truncateText(source.replyText, replyBudget, SESSION_REPLY_TRUNCATION_MARKER)
const changes = source.changes === null
? null
: truncateText(renderFusionPatchText(source.changes), patchBudget, SESSION_REPLY_TRUNCATION_MARKER)
attributed.push({
entryId: source.entryId,
sessionId: source.sessionId,
model: source.model,
truncated: reply.truncated || Boolean(changes?.truncated),
})
return buildFusionSourceBlock(source, index, reply.text, changes ? changes.text : null)
})
return { prompt: [preamble, ...blocks].join(FUSION_BLOCK_SEPARATOR), sources: attributed }
}
function buildFusionPreamble({ runName, objective, instructions }: { runName: string; objective: string; instructions?: string }): string {
const trimmedInstructions = instructions?.trim()
return [
`You are synthesizing the results of the multi-run "${runName}" into a single implementation in the current workspace.`,
'## Original objective',
objective,
...(trimmedInstructions ? ['## Additional instructions', trimmedInstructions] : []),
'## Rules',
[
'- The source sessions and workspaces below are read-only references. Do not modify, merge or push them.',
'- Apply any adopted changes only in the current workspace.',
'- Attribute each adopted part of the synthesis to the source it came from.',
].join('\n'),
].join(FUSION_BLOCK_SEPARATOR)
}
function buildFusionSourceBlock(
source: CollectedFusionSource,
index: number,
replyBody: string,
patchBody: string | null,
): string {
return [
`## Source ${index + 1} — ${source.model}`,
'',
`- Session: ${source.sessionId}`,
`- Outcome: ${source.outcome ?? 'unknown'}`,
`- Workspace: ${source.directory ?? 'not recorded'}`,
'',
'Changed files:',
...renderFusionChangedFiles(source.changes),
'',
'### Final reply',
'',
replyBody,
'',
'### Changes',
'',
...(patchBody === null ? ['Changes could not be read.'] : ['```diff', patchBody, '```']),
].join('\n')
}
function renderFusionChangedFiles(changes: FileDiffInfo[] | null): string[] {
if (changes === null) {
return ['- (changes could not be read)']
}
if (changes.length === 0) {
return ['- (no files changed)']
}
return changes.map((change) => `- ${change.file} (${change.status}, +${change.additions}/-${change.deletions})`)
}
function renderFusionPatchText(changes: FileDiffInfo[]): string {
return changes.map((change) => change.patch).join('\n')
}
type FusionSourceResult =
| { kind: 'ready'; source: CollectedFusionSource }
| { kind: 'unavailable'; source: FusionUnavailableSource }
export async function collectFusionSources(
client: OpenCodeClient,
entries: MultiRunEntryRecord[],
): Promise<FusionSourceCollection> {
let activeSessions: Promise<ActiveSessions> | null = null
const getActiveSessions = (): Promise<ActiveSessions> => {
activeSessions ??= client.api.session.active()
return activeSessions
}
const results = await Promise.all(entries.map((entry) => collectFusionSource(client, entry, getActiveSessions)))
const ready: CollectedFusionSource[] = []
const unavailable: FusionUnavailableSource[] = []
for (const result of results) {
if (result.kind === 'ready') {
ready.push(result.source)
} else {
unavailable.push(result.source)
}
}
return { ready, unavailable }
}
async function collectFusionSource(
client: OpenCodeClient,
entry: MultiRunEntryRecord,
getActiveSessions: () => Promise<ActiveSessions>,
): Promise<FusionSourceResult> {
if (entry.status !== 'started' || !entry.sessionId) {
return unavailable(entry, 'not-started', 'The result has not started a session.')
}
const sessionId = entry.sessionId
let session: SessionInfo
try {
session = await client.api.session.get({ sessionID: sessionId })
} catch (error) {
if (isSessionNotFoundError(error)) {
return unavailable(entry, 'missing', 'The session no longer exists.')
}
return unavailable(entry, 'unavailable', getErrorMessage(error))
}
try {
if (isSessionBusyIn(await getActiveSessions(), sessionId)) {
return unavailable(entry, 'running', 'The session is still running.')
}
const reply = await readLatestAssistantReply(client, sessionId)
if (!reply || !reply.completed) {
return unavailable(entry, 'incomplete', 'The session has not produced a final reply.')
}
if (session.outcome === 'failed' || session.outcome === 'interrupted' || reply.errorText) {
return unavailable(entry, 'failed', failureMessage(session, reply.errorText))
}
const changes = await readSessionChanges(client, sessionId).catch(() => null)
return {
kind: 'ready',
source: {
entryId: entry.id,
model: entry.model,
sessionId,
directory: entry.directory,
outcome: session.outcome ?? null,
replyText: reply.responseText ?? '',
changes,
},
}
} catch (error) {
return unavailable(entry, 'unavailable', getErrorMessage(error))
}
}
function failureMessage(session: SessionInfo, errorText: string | null): string {
if (errorText) {
return `The session failed: ${errorText}`
}
return session.outcome === 'interrupted'
? 'The session was interrupted.'
: 'The session did not complete successfully.'
}
function unavailable(
entry: MultiRunEntryRecord,
reason: FusionUnavailableSource['reason'],
message: string,
): FusionSourceResult {
return { kind: 'unavailable', source: { entryId: entry.id, model: entry.model, reason, message } }
}
+183 -13
View File
@@ -1,18 +1,25 @@
import type { Database } from 'bun:sqlite'
import { existsSync } from 'node:fs'
import type { LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import { resolve } from 'node:path'
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import {
createMultiRunWithEntries,
getMultiRun,
getMultiRunEntry,
getMultiRunFusionByRequest,
insertMultiRunFusion,
listMultiRuns,
updateMultiRunEntry,
updateMultiRunFusion,
type MultiRunEntryRecord,
type MultiRunFusionRecord,
type MultiRunRecord,
} from '../db/multi-runs'
import { getRepoById } from '../db/queries'
import type { Repo } from '../types/repo'
import { getErrorMessage } from '../utils/error-utils'
import { ServiceError } from '../utils/service-error'
import { buildFusionPrompt, collectFusionSources } from './multi-run-fusion'
import type { OpenCodeClient } from './opencode/client'
import { RepoWorkspaceError } from './repo'
import type { RepoWorkspaceService } from './repo-workspace'
@@ -20,15 +27,7 @@ import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSes
const MULTI_RUN_LIST_LIMIT = 20
export class MultiRunError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.name = 'MultiRunError'
this.status = status
}
}
export class MultiRunError extends ServiceError {}
function toMultiRun(record: MultiRunRecord): MultiRun {
return {
@@ -50,6 +49,21 @@ function toMultiRun(record: MultiRunRecord): MultiRun {
createdAt: entry.createdAt,
updatedAt: entry.updatedAt,
})),
fusions: record.fusions.map((fusion) => ({
id: fusion.id,
requestId: fusion.requestId,
model: fusion.model,
instructions: fusion.instructions,
isolated: fusion.isolated,
baseRef: fusion.baseRef,
status: fusion.status,
sessionId: fusion.sessionId,
directory: fusion.directory,
error: fusion.error,
sources: fusion.sources,
createdAt: fusion.createdAt,
updatedAt: fusion.updatedAt,
})),
}
}
@@ -59,7 +73,7 @@ export class MultiRunService {
constructor(
private readonly db: Database,
openCodeClient: OpenCodeClient,
private readonly openCodeClient: OpenCodeClient,
private readonly repoWorkspaces: RepoWorkspaceService,
) {
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces)
@@ -128,18 +142,134 @@ export class MultiRunService {
return
}
const workspaceDirectory =
result.reason instanceof SessionLaunchError ? result.reason.workspaceDirectory : null
const launchError = result.reason instanceof SessionLaunchError ? result.reason : null
const workspaceDirectory = launchError?.workspaceDirectory ?? null
updateMultiRunEntry(this.db, launch.entry.id, ['starting'], {
status: 'failed',
error: getErrorMessage(result.reason) || 'Failed to launch session',
...(workspaceDirectory ? { directory: workspaceDirectory } : {}),
...(launchError?.sessionId ? { sessionId: launchError.sessionId } : {}),
})
})
return this.reload(record.id)
}
async fuse(multiRunId: number, request: FuseMultiRunRequest): Promise<{ run: MultiRun; created: boolean }> {
const record = getMultiRun(this.db, multiRunId)
if (!record) {
throw new MultiRunError('Multi-run not found', 404)
}
if (getMultiRunFusionByRequest(this.db, multiRunId, request.requestId)) {
return { run: this.reload(multiRunId), created: false }
}
let repo: Repo
try {
repo = requireReadyRepo(this.db, record.repoId)
} catch (error) {
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
}
const entriesById = new Map(record.entries.map((entry) => [entry.id, entry]))
const selectedEntries = request.entryIds.map((entryId) => {
const entry = entriesById.get(entryId)
if (!entry) {
throw new MultiRunError(`Unknown multi-run entry ${entryId}`, 400)
}
return entry
})
if (!request.isolate) {
const overlappingEntryIds = selectedEntries
.filter((entry) => entry.directory !== null && resolve(entry.directory) === resolve(repo.fullPath))
.map((entry) => entry.id)
if (overlappingEntryIds.length > 0) {
throw new MultiRunError(
'The synthesis cannot run in the repository checkout because a selected result ran there. Enable an isolated workspace.',
409,
{ code: 'FUSION_DESTINATION_OVERLAPS_SOURCE', details: { entryIds: overlappingEntryIds } },
)
}
}
try {
await this.sessionLauncher.resolveModel(repo, request.model)
} catch (error) {
if (error instanceof SessionLaunchError) {
throw new MultiRunError(error.message, error.status)
}
throw new MultiRunError(getErrorMessage(error) || 'Failed to resolve model', 502)
}
await this.reconcileUncertainFusions(record)
const collection = await collectFusionSources(this.openCodeClient, selectedEntries)
if (collection.unavailable.length > 0) {
throw new MultiRunError('Some selected results are not ready to fuse', 409, {
code: 'FUSION_SOURCES_UNAVAILABLE',
details: { unavailableSources: collection.unavailable },
})
}
const built = buildFusionPrompt({
runName: record.name,
objective: record.prompt,
instructions: request.instructions,
sources: collection.ready,
})
const { fusion, created } = insertMultiRunFusion(this.db, {
multiRunId,
requestId: request.requestId,
model: request.model,
instructions: request.instructions ?? null,
isolated: request.isolate,
baseRef: request.baseRef ?? null,
sources: built.sources,
})
if (!created) {
return { run: this.reload(multiRunId), created: false }
}
try {
const launched = await this.sessionLauncher.launch({
repoId: record.repoId,
prompt: built.prompt,
model: request.model,
title: `${record.name} · fusion`,
...(request.agent ? { agent: request.agent } : {}),
...(request.isolate
? {
workspace: {
name: `${record.name}-fusion-${fusion.id}`,
...(request.baseRef ? { ref: request.baseRef } : {}),
},
}
: {}),
})
updateMultiRunFusion(this.db, fusion.id, ['starting'], {
status: 'started',
sessionId: launched.sessionId,
directory: launched.directory,
})
} catch (error) {
const launchError = error instanceof SessionLaunchError ? error : null
const workspaceDirectory = launchError?.workspaceDirectory ?? null
updateMultiRunFusion(this.db, fusion.id, ['starting'], {
status: 'failed',
error: getErrorMessage(error) || 'Failed to launch session',
...(workspaceDirectory ? { directory: workspaceDirectory } : {}),
...(launchError?.sessionId ? { sessionId: launchError.sessionId } : {}),
})
}
return { run: this.reload(multiRunId), created: true }
}
list(repoId: number): MultiRun[] {
return listMultiRuns(this.db, repoId, MULTI_RUN_LIST_LIMIT).map(toMultiRun)
}
@@ -207,6 +337,46 @@ export class MultiRunService {
})
}
private async reconcileUncertainFusions(record: MultiRunRecord): Promise<void> {
const uncertain = record.fusions.filter(
(fusion): fusion is MultiRunFusionRecord & { sessionId: string } =>
fusion.status === 'failed' && fusion.sessionId !== null,
)
if (uncertain.length === 0) {
return
}
const recovered = (
await Promise.all(
uncertain.map(async (fusion) => {
try {
const response = await this.openCodeClient.api.message.list({
sessionID: fusion.sessionId,
type: 'user',
order: 'asc',
limit: 1,
})
if (response.data.length === 0) {
return null
}
} catch {
return null
}
updateMultiRunFusion(this.db, fusion.id, ['failed'], { status: 'started', error: null })
return { fusionId: fusion.id, sessionId: fusion.sessionId }
}),
)
).filter((entry): entry is { fusionId: number; sessionId: string } => entry !== null)
if (recovered.length > 0) {
throw new MultiRunError('An earlier fusion attempt is already running', 409, {
code: 'FUSION_ATTEMPT_RECOVERED',
details: { fusions: recovered },
})
}
}
private reload(multiRunId: number): MultiRun {
const record = getMultiRun(this.db, multiRunId)
if (!record) {
@@ -0,0 +1,34 @@
import type { ModelRef } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './client'
export class GenerateTextTimeoutError extends Error {
constructor() {
super('Text generation timed out')
this.name = 'GenerateTextTimeoutError'
}
}
export async function generateTextWithTimeout(
client: OpenCodeClient,
input: { prompt: string; model?: ModelRef },
timeoutMs: number,
): Promise<string> {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
const timeout = new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => {
controller.abort()
reject(new GenerateTextTimeoutError())
}, timeoutMs)
})
try {
const { text } = await Promise.race([
client.api.generate.text(input, { signal: controller.signal }),
timeout,
])
return text
} finally {
if (timer) clearTimeout(timer)
}
}
+24
View File
@@ -0,0 +1,24 @@
import type { FileDiffInfo } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from './opencode/client'
export const SESSION_CHANGES_CONTEXT_LINES = 3
export async function readSessionChanges(client: OpenCodeClient, sessionId: string): Promise<FileDiffInfo[]> {
const [first, last] = await Promise.all([
client.api.message.list({ sessionID: sessionId, type: 'user', order: 'asc', limit: 1 }),
client.api.message.list({ sessionID: sessionId, type: 'user', order: 'desc', limit: 1 }),
])
const from = first.data[0]
const to = last.data[0]
if (!from || !to) {
return []
}
return client.api.session.diff({
sessionID: sessionId,
from: from.id,
to: to.id,
context: SESSION_CHANGES_CONTEXT_LINES,
})
}
+1 -42
View File
@@ -1,4 +1,5 @@
import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas'
import { extractFirstJsonObject } from '../utils/json-extract'
import { truncateSessionReply } from './session-reply'
export const GOAL_AUDIT_REASON_MAX_CHARS = 500
@@ -91,45 +92,3 @@ function truncateReply(reply: string | null): string {
}
return truncateSessionReply(reply)
}
function extractFirstJsonObject(text: string): string | null {
const start = text.indexOf('{')
if (start === -1) {
return null
}
let depth = 0
let inString = false
let escaped = false
for (let index = start; index < text.length; index += 1) {
const char = text[index]
if (inString) {
if (escaped) {
escaped = false
} else if (char === '\\') {
escaped = true
} else if (char === '"') {
inString = false
}
continue
}
if (char === '"') {
inString = true
continue
}
if (char === '{') {
depth += 1
} else if (char === '}') {
depth -= 1
if (depth === 0) {
return text.slice(start, index + 1)
}
}
}
return null
}
+17 -1
View File
@@ -29,12 +29,19 @@ export interface LaunchedSession {
export class SessionLaunchError extends Error {
readonly status: 400 | 404 | 502
readonly workspaceDirectory: string | null
readonly sessionId: string | null
constructor(message: string, status: 400 | 404 | 502, workspaceDirectory: string | null = null) {
constructor(
message: string,
status: 400 | 404 | 502,
workspaceDirectory: string | null = null,
sessionId: string | null = null,
) {
super(message)
this.name = 'SessionLaunchError'
this.status = status
this.workspaceDirectory = workspaceDirectory
this.sessionId = sessionId
}
}
@@ -109,13 +116,22 @@ export class SessionLauncher {
},
...openCodeLocation(directory),
})
} catch (error) {
throw new SessionLaunchError(
withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory),
502,
workspaceDirectory,
)
}
try {
await this.openCodeClient.api.session.prompt({ sessionID: session.id, text: input.prompt })
} catch (error) {
throw new SessionLaunchError(
withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory),
502,
workspaceDirectory,
session.id,
)
}
+17 -8
View File
@@ -1,10 +1,17 @@
import { assistantText, sessionIDFromEvent, type SessionMessageAssistant, type SessionMessageInfo } from '@opencode-manager/shared/opencode'
import {
assistantText,
sessionIDFromEvent,
type OpenCodeApi,
type SessionMessageAssistant,
type SessionMessageInfo,
} from '@opencode-manager/shared/opencode'
import { truncateText } from '../utils/text-truncate'
import type { OpenCodeClient } from './opencode/client'
import { sseAggregator, type SSEEvent } from './sse-aggregator'
export const SESSION_REPLY_MAX_LENGTH = 20000
const SESSION_REPLY_TRUNCATION_MARKER = '\n\n[reply truncated]'
export const SESSION_REPLY_TRUNCATION_MARKER = '\n\n[reply truncated]'
export interface AssistantReplyState {
responseText: string | null
@@ -17,10 +24,7 @@ export interface SessionSettleSignal {
}
export function truncateSessionReply(text: string): string {
if (text.length <= SESSION_REPLY_MAX_LENGTH) {
return text
}
return `${text.slice(0, SESSION_REPLY_MAX_LENGTH)}${SESSION_REPLY_TRUNCATION_MARKER}`
return truncateText(text, SESSION_REPLY_MAX_LENGTH, SESSION_REPLY_TRUNCATION_MARKER).text
}
export function sessionSettleSignal(event: SSEEvent, sessionId: string): SessionSettleSignal | null {
@@ -110,7 +114,12 @@ export async function readLatestAssistantReply(client: OpenCodeClient, sessionId
return getLatestAssistantReplyState(response.data)
}
export async function isSessionBusy(client: OpenCodeClient, sessionId: string): Promise<boolean> {
const active = await client.api.session.active()
export type ActiveSessions = Awaited<ReturnType<OpenCodeApi['session']['active']>>
export function isSessionBusyIn(active: ActiveSessions, sessionId: string): boolean {
return sessionId in active
}
export async function isSessionBusy(client: OpenCodeClient, sessionId: string): Promise<boolean> {
return isSessionBusyIn(await client.api.session.active(), sessionId)
}