mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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:
1 parent
90c6ccf236
commit
b36d412ca2
66 files changed
+6228
-468
No files matched your search
@@ -0,0 +1,45 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { ChangeWalkthroughSchema, type ChangeWalkthrough } from '@opencode-manager/shared/schemas'
|
||||
|
||||
interface ChangeWalkthroughRow {
|
||||
session_id: string
|
||||
diff_hash: string
|
||||
payload: string
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export function ensureChangeWalkthroughTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS change_walkthroughs (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
diff_hash TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
export function getChangeWalkthrough(db: Database, sessionId: string): ChangeWalkthrough | null {
|
||||
const row = db
|
||||
.prepare('SELECT session_id, diff_hash, payload, created_at FROM change_walkthroughs WHERE session_id = ?')
|
||||
.get(sessionId) as ChangeWalkthroughRow | undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return ChangeWalkthroughSchema.parse(JSON.parse(row.payload))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function saveChangeWalkthrough(db: Database, walkthrough: ChangeWalkthrough): void {
|
||||
db.prepare(`
|
||||
INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
diff_hash = excluded.diff_hash,
|
||||
payload = excluded.payload,
|
||||
created_at = excluded.created_at
|
||||
`).run(walkthrough.sessionId, walkthrough.diffHash, JSON.stringify(walkthrough), walkthrough.createdAt)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { ensureMultiRunFusionTable } from '../multi-runs'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610061700-multi-run-fusions',
|
||||
up(db) {
|
||||
ensureMultiRunFusionTable(db)
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS multi_run_fusions')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
import { ensureChangeWalkthroughTable } from '../change-walkthroughs'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610061701-change-walkthroughs',
|
||||
up(db) {
|
||||
ensureChangeWalkthroughTable(db)
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS change_walkthroughs')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -27,6 +27,8 @@ import migration025 from './025-session-permission-modes'
|
||||
import migration026 from './026-session-goals'
|
||||
import migration027 from './027-multi-runs'
|
||||
import migration202610061345 from './202610061345-schedule-workspace-mode'
|
||||
import migration202610061700 from './202610061700-multi-run-fusions'
|
||||
import migration202610061701 from './202610061701-change-walkthroughs'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -57,4 +59,6 @@ export const allMigrations: Migration[] = [
|
||||
migration026,
|
||||
migration027,
|
||||
migration202610061345,
|
||||
migration202610061700,
|
||||
migration202610061701,
|
||||
]
|
||||
+241
-17
@@ -1,5 +1,10 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { MultiRunEntryStatus } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
MultiRunFusionSourceSchema,
|
||||
type MultiRunEntryStatus,
|
||||
type MultiRunFusionSource,
|
||||
type MultiRunFusionStatus,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MultiRunEntryRecord {
|
||||
id: number
|
||||
@@ -13,6 +18,23 @@ export interface MultiRunEntryRecord {
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface MultiRunFusionRecord {
|
||||
id: number
|
||||
multiRunId: number
|
||||
requestId: string
|
||||
model: string
|
||||
instructions: string | null
|
||||
isolated: boolean
|
||||
baseRef: string | null
|
||||
sources: MultiRunFusionSource[]
|
||||
status: MultiRunFusionStatus
|
||||
sessionId: string | null
|
||||
directory: string | null
|
||||
error: string | null
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface MultiRunRecord {
|
||||
id: number
|
||||
repoId: number
|
||||
@@ -22,6 +44,7 @@ export interface MultiRunRecord {
|
||||
baseRef: string | null
|
||||
createdAt: number
|
||||
entries: MultiRunEntryRecord[]
|
||||
fusions: MultiRunFusionRecord[]
|
||||
}
|
||||
|
||||
export interface CreateMultiRunGroup {
|
||||
@@ -39,6 +62,23 @@ export interface MultiRunEntryPatch {
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
export interface CreateMultiRunFusionInput {
|
||||
multiRunId: number
|
||||
requestId: string
|
||||
model: string
|
||||
instructions: string | null
|
||||
isolated: boolean
|
||||
baseRef: string | null
|
||||
sources: MultiRunFusionSource[]
|
||||
}
|
||||
|
||||
export interface MultiRunFusionPatch {
|
||||
status?: MultiRunFusionStatus
|
||||
sessionId?: string | null
|
||||
directory?: string | null
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
interface MultiRunRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
@@ -61,10 +101,30 @@ interface MultiRunEntryRow {
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
interface MultiRunFusionRow {
|
||||
id: number
|
||||
multi_run_id: number
|
||||
request_id: string
|
||||
model: string
|
||||
instructions: string | null
|
||||
isolated: number
|
||||
base_ref: string | null
|
||||
sources: string
|
||||
status: MultiRunFusionStatus
|
||||
session_id: string | null
|
||||
directory: string | null
|
||||
error: string | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, name, prompt, isolated, base_ref, created_at'
|
||||
|
||||
const MULTI_RUN_ENTRY_COLUMNS = 'id, multi_run_id, model, status, session_id, directory, error, created_at, updated_at'
|
||||
|
||||
const MULTI_RUN_FUSION_COLUMNS =
|
||||
'id, multi_run_id, request_id, model, instructions, isolated, base_ref, sources, status, session_id, directory, error, created_at, updated_at'
|
||||
|
||||
export function ensureMultiRunTables(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS multi_runs (
|
||||
@@ -100,6 +160,32 @@ export function ensureMultiRunTables(db: Database): void {
|
||||
`)
|
||||
}
|
||||
|
||||
export function ensureMultiRunFusionTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS multi_run_fusions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
multi_run_id INTEGER NOT NULL,
|
||||
request_id TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
instructions TEXT,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
sources TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('starting','started','failed')),
|
||||
session_id TEXT,
|
||||
directory TEXT,
|
||||
error TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
UNIQUE(multi_run_id, request_id)
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_multi_run_fusions_group
|
||||
ON multi_run_fusions(multi_run_id)
|
||||
`)
|
||||
}
|
||||
|
||||
export function createMultiRunWithEntries(
|
||||
db: Database,
|
||||
group: CreateMultiRunGroup,
|
||||
@@ -137,7 +223,7 @@ export function getMultiRun(db: Database, id: number): MultiRunRecord | null {
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return toMultiRunRecord(row, loadEntries(db, row.id))
|
||||
return toMultiRunRecord(row, loadEntries(db, row.id), loadFusions(db, row.id))
|
||||
}
|
||||
|
||||
export function listMultiRuns(db: Database, repoId: number, limit: number): MultiRunRecord[] {
|
||||
@@ -170,7 +256,25 @@ export function listMultiRuns(db: Database, repoId: number, limit: number): Mult
|
||||
entriesByRun.get(entryRow.multi_run_id)?.push(entryRow)
|
||||
}
|
||||
|
||||
return rows.map((row) => toMultiRunRecord(row, entriesByRun.get(row.id) ?? []))
|
||||
const fusionRows = db
|
||||
.prepare(`
|
||||
SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions
|
||||
WHERE multi_run_id IN (${placeholders})
|
||||
ORDER BY multi_run_id ASC, id ASC
|
||||
`)
|
||||
.all(...rows.map((row) => row.id)) as MultiRunFusionRow[]
|
||||
|
||||
const fusionsByRun = new Map<number, MultiRunFusionRow[]>()
|
||||
for (const row of rows) {
|
||||
fusionsByRun.set(row.id, [])
|
||||
}
|
||||
for (const fusionRow of fusionRows) {
|
||||
fusionsByRun.get(fusionRow.multi_run_id)?.push(fusionRow)
|
||||
}
|
||||
|
||||
return rows.map((row) =>
|
||||
toMultiRunRecord(row, entriesByRun.get(row.id) ?? [], fusionsByRun.get(row.id) ?? []),
|
||||
)
|
||||
}
|
||||
|
||||
export function getMultiRunEntry(db: Database, multiRunId: number, entryId: number): MultiRunEntryRecord | null {
|
||||
@@ -193,6 +297,106 @@ export function updateMultiRunEntry(
|
||||
fromStatuses: MultiRunEntryStatus[],
|
||||
patch: MultiRunEntryPatch,
|
||||
): MultiRunEntryRecord | null {
|
||||
if (!runGuardedStatusUpdate(db, 'multi_run_entries', entryId, fromStatuses, patch)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const row = db.prepare('SELECT multi_run_id FROM multi_run_entries WHERE id = ?').get(entryId) as
|
||||
| { multi_run_id: number }
|
||||
| undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return getMultiRunEntry(db, row.multi_run_id, entryId)
|
||||
}
|
||||
|
||||
export function getMultiRunFusionByRequest(
|
||||
db: Database,
|
||||
multiRunId: number,
|
||||
requestId: string,
|
||||
): MultiRunFusionRecord | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? AND request_id = ?`)
|
||||
.get(multiRunId, requestId) as MultiRunFusionRow | undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return mapFusionRow(row)
|
||||
}
|
||||
|
||||
export function insertMultiRunFusion(
|
||||
db: Database,
|
||||
input: CreateMultiRunFusionInput,
|
||||
): { fusion: MultiRunFusionRecord; created: boolean } {
|
||||
const now = Date.now()
|
||||
return db.transaction(() => {
|
||||
const result = db
|
||||
.prepare(`
|
||||
INSERT INTO multi_run_fusions(
|
||||
multi_run_id, request_id, model, instructions, isolated, base_ref, sources,
|
||||
status, session_id, directory, error, created_at, updated_at
|
||||
)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
ON CONFLICT(multi_run_id, request_id) DO NOTHING
|
||||
`)
|
||||
.run(
|
||||
input.multiRunId,
|
||||
input.requestId,
|
||||
input.model,
|
||||
input.instructions,
|
||||
input.isolated ? 1 : 0,
|
||||
input.baseRef,
|
||||
JSON.stringify(input.sources),
|
||||
'starting',
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
now,
|
||||
now,
|
||||
)
|
||||
const fusion = getMultiRunFusionByRequest(db, input.multiRunId, input.requestId)
|
||||
if (!fusion) {
|
||||
throw new Error('Failed to create multi-run fusion')
|
||||
}
|
||||
return { fusion, created: result.changes > 0 }
|
||||
})()
|
||||
}
|
||||
|
||||
export function updateMultiRunFusion(
|
||||
db: Database,
|
||||
fusionId: number,
|
||||
fromStatuses: MultiRunFusionStatus[],
|
||||
patch: MultiRunFusionPatch,
|
||||
): MultiRunFusionRecord | null {
|
||||
if (!runGuardedStatusUpdate(db, 'multi_run_fusions', fusionId, fromStatuses, patch)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const row = db.prepare('SELECT multi_run_id, request_id FROM multi_run_fusions WHERE id = ?').get(fusionId) as
|
||||
| { multi_run_id: number; request_id: string }
|
||||
| undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return getMultiRunFusionByRequest(db, row.multi_run_id, row.request_id)
|
||||
}
|
||||
|
||||
type GuardedUpdateTable = 'multi_run_entries' | 'multi_run_fusions'
|
||||
|
||||
interface GuardedUpdatePatch {
|
||||
status?: string
|
||||
sessionId?: string | null
|
||||
directory?: string | null
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
function runGuardedStatusUpdate(
|
||||
db: Database,
|
||||
table: GuardedUpdateTable,
|
||||
id: number,
|
||||
fromStatuses: readonly string[],
|
||||
patch: GuardedUpdatePatch,
|
||||
): boolean {
|
||||
const assignments: string[] = ['updated_at = ?']
|
||||
const values: (string | number | null)[] = [Date.now()]
|
||||
|
||||
@@ -215,20 +419,10 @@ export function updateMultiRunEntry(
|
||||
|
||||
const placeholders = fromStatuses.map(() => '?').join(', ')
|
||||
const result = db
|
||||
.prepare(`UPDATE multi_run_entries SET ${assignments.join(', ')} WHERE id = ? AND status IN (${placeholders})`)
|
||||
.run(...values, entryId, ...fromStatuses)
|
||||
.prepare(`UPDATE ${table} SET ${assignments.join(', ')} WHERE id = ? AND status IN (${placeholders})`)
|
||||
.run(...values, id, ...fromStatuses)
|
||||
|
||||
if (result.changes === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const row = db.prepare('SELECT multi_run_id FROM multi_run_entries WHERE id = ?').get(entryId) as
|
||||
| { multi_run_id: number }
|
||||
| undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
return getMultiRunEntry(db, row.multi_run_id, entryId)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
function loadEntries(db: Database, multiRunId: number): MultiRunEntryRow[] {
|
||||
@@ -237,7 +431,17 @@ function loadEntries(db: Database, multiRunId: number): MultiRunEntryRow[] {
|
||||
.all(multiRunId) as MultiRunEntryRow[]
|
||||
}
|
||||
|
||||
function toMultiRunRecord(row: MultiRunRow, entries: MultiRunEntryRow[]): MultiRunRecord {
|
||||
function loadFusions(db: Database, multiRunId: number): MultiRunFusionRow[] {
|
||||
return db
|
||||
.prepare(`SELECT ${MULTI_RUN_FUSION_COLUMNS} FROM multi_run_fusions WHERE multi_run_id = ? ORDER BY id ASC`)
|
||||
.all(multiRunId) as MultiRunFusionRow[]
|
||||
}
|
||||
|
||||
function toMultiRunRecord(
|
||||
row: MultiRunRow,
|
||||
entries: MultiRunEntryRow[],
|
||||
fusions: MultiRunFusionRow[],
|
||||
): MultiRunRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
@@ -247,6 +451,26 @@ function toMultiRunRecord(row: MultiRunRow, entries: MultiRunEntryRow[]): MultiR
|
||||
baseRef: row.base_ref,
|
||||
createdAt: row.created_at,
|
||||
entries: entries.map((entry) => mapEntryRow(entry, row.isolated === 1)),
|
||||
fusions: fusions.map(mapFusionRow),
|
||||
}
|
||||
}
|
||||
|
||||
function mapFusionRow(row: MultiRunFusionRow): MultiRunFusionRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
multiRunId: row.multi_run_id,
|
||||
requestId: row.request_id,
|
||||
model: row.model,
|
||||
instructions: row.instructions,
|
||||
isolated: row.isolated === 1,
|
||||
baseRef: row.base_ref,
|
||||
sources: MultiRunFusionSourceSchema.array().parse(JSON.parse(row.sources)),
|
||||
status: row.status,
|
||||
sessionId: row.session_id,
|
||||
directory: row.directory,
|
||||
error: row.error,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -348,6 +348,7 @@ export function deleteRepo(db: Database, id: number): void {
|
||||
}
|
||||
|
||||
const remove = db.transaction(() => {
|
||||
db.prepare('DELETE FROM multi_run_fusions WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
|
||||
db.prepare('DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
|
||||
db.prepare('DELETE FROM multi_runs WHERE repo_id = ?').run(id)
|
||||
for (const table of TABLES_WITH_REPO_ID) {
|
||||
|
||||
@@ -41,6 +41,7 @@ import { createSessionPinRoutes } from './routes/session-pins'
|
||||
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
|
||||
import { createSessionGoalRoutes } from './routes/session-goals'
|
||||
import { createMultiRunRoutes } from './routes/multi-runs'
|
||||
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
|
||||
import { createLogRoutes } from './routes/logs'
|
||||
import { createPreviewRoutes, createPreviewAvailability } from './routes/preview'
|
||||
import { createPreviewGatewayApp, PreviewSessionStore } from './services/preview/gateway'
|
||||
@@ -54,6 +55,7 @@ import { SettingsService } from './services/settings'
|
||||
import { SessionPermissionModeService } from './services/session-permission-modes'
|
||||
import { SessionGoalService } from './services/session-goals'
|
||||
import { MultiRunService } from './services/multi-runs'
|
||||
import { ChangeWalkthroughService } from './services/change-walkthroughs'
|
||||
import { opencodeServerManager } from './services/opencode-single-server'
|
||||
import { createOpenCodeClient } from './services/opencode/client'
|
||||
import { getOpenCodeUpstreamBaseUrl } from './services/opencode/upstream'
|
||||
@@ -270,6 +272,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
|
||||
@@ -355,6 +358,7 @@ protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
|
||||
protectedApi.route('/session-goals', createSessionGoalRoutes(sessionGoalService))
|
||||
protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService))
|
||||
protectedApi.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
|
||||
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/logs', createLogRoutes())
|
||||
protectedApi.route('/preview', createPreviewRoutes({ store: previewSessionStore, isEnabled: previewAvailability.isEnabled }))
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Hono } from 'hono'
|
||||
import { GenerateChangeWalkthroughRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import type { ChangeWalkthroughService } from '../services/change-walkthroughs'
|
||||
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
|
||||
export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:sessionId', async (c) => {
|
||||
try {
|
||||
const state = await service.getState(c.req.param('sessionId'))
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read change walkthrough', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:sessionId', async (c) => {
|
||||
const parsed = await parseJsonBody(c, GenerateChangeWalkthroughRequestSchema, { allowEmpty: true })
|
||||
if (!parsed.ok) {
|
||||
return parsed.response
|
||||
}
|
||||
|
||||
try {
|
||||
const { walkthrough, created } = await service.generate(c.req.param('sessionId'), parsed.data)
|
||||
return c.json({ walkthrough }, created ? 201 : 200)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to generate change walkthrough', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Hono } from 'hono'
|
||||
import { LaunchMultiRunRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { FuseMultiRunRequestSchema, LaunchMultiRunRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { MultiRunError, type MultiRunService } from '../services/multi-runs'
|
||||
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
|
||||
export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const app = new Hono()
|
||||
@@ -11,7 +12,7 @@ export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const repoId = parseId(c.req.query('repoId'), 'repoId', MultiRunError)
|
||||
return c.json({ runs: service.list(repoId) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list multi-runs', MultiRunError)
|
||||
return handleServiceError(c, error, 'Failed to list multi-runs', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -25,7 +26,7 @@ export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const run = await service.launch(parsed.data)
|
||||
return c.json({ run }, 201)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to launch multi-run', MultiRunError)
|
||||
return handleServiceError(c, error, 'Failed to launch multi-run', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -36,7 +37,22 @@ export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const run = await service.discard(multiRunId, entryId)
|
||||
return c.json({ run })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to discard multi-run entry', MultiRunError)
|
||||
return handleServiceError(c, error, 'Failed to discard multi-run entry', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:id/fusions', async (c) => {
|
||||
try {
|
||||
const multiRunId = parseId(c.req.param('id'), 'multi-run id', MultiRunError)
|
||||
const parsed = await parseJsonBody(c, FuseMultiRunRequestSchema)
|
||||
if (!parsed.ok) {
|
||||
return parsed.response
|
||||
}
|
||||
|
||||
const { run, created } = await service.fuse(multiRunId, parsed.data)
|
||||
return c.json({ run }, created ? 201 : 200)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to fuse multi-run', ServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { CommitMessageContext } from '../services/git/commit-message-prompt
|
||||
import { RenameBranchRequestSchema, DeleteBranchRequestSchema, StashPushRequestSchema, StashApplyRequestSchema, StashDropRequestSchema, IntegrateBranchRequestSchema } from '@opencode-manager/shared'
|
||||
import type { GitService } from '../services/git/GitService'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import { GenerateTextTimeoutError, generateTextWithTimeout } from '../services/opencode/generate-text'
|
||||
import type { GitStatusResponse } from '../types/git'
|
||||
import type { Repo } from '../types/repo'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
@@ -19,13 +20,6 @@ export interface RepoGitRouteOptions {
|
||||
commitMessageTimeoutMs?: number
|
||||
}
|
||||
|
||||
class CommitMessageTimeoutError extends Error {
|
||||
constructor() {
|
||||
super('Commit message generation timed out')
|
||||
this.name = 'CommitMessageTimeoutError'
|
||||
}
|
||||
}
|
||||
|
||||
function parseStashIndex(raw: string | undefined): number | null {
|
||||
if (raw === undefined || !/^\d+$/.test(raw)) {
|
||||
return null
|
||||
@@ -174,25 +168,12 @@ export function createRepoGitRoutes(
|
||||
return c.json({ error: getErrorMessage(error) }, 400)
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
let timedOut = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
controller.abort()
|
||||
reject(new CommitMessageTimeoutError())
|
||||
}, commitMessageTimeoutMs)
|
||||
})
|
||||
|
||||
try {
|
||||
const { text } = await Promise.race([
|
||||
openCodeClient.api.generate.text(
|
||||
{ prompt: buildCommitMessagePrompt(context) },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
timeout,
|
||||
])
|
||||
const text = await generateTextWithTimeout(
|
||||
openCodeClient,
|
||||
{ prompt: buildCommitMessagePrompt(context) },
|
||||
commitMessageTimeoutMs,
|
||||
)
|
||||
const message = normalizeGeneratedCommitMessage(text)
|
||||
|
||||
if (!message) {
|
||||
@@ -201,13 +182,11 @@ export function createRepoGitRoutes(
|
||||
|
||||
return c.json({ message })
|
||||
} catch (error: unknown) {
|
||||
if (timedOut) {
|
||||
if (error instanceof GenerateTextTimeoutError) {
|
||||
return c.json({ error: 'Commit message generation timed out' }, 502)
|
||||
}
|
||||
logger.error('Failed to generate commit message:', error)
|
||||
return c.json({ error: getErrorMessage(error) }, 502)
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer)
|
||||
}
|
||||
}))
|
||||
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
|
||||
|
||||
@@ -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 } }
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,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
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
export 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
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export class ServiceError extends Error {
|
||||
status: number
|
||||
code?: string
|
||||
details?: unknown
|
||||
|
||||
constructor(message: string, status: number, options?: { code?: string; details?: unknown }) {
|
||||
super(message)
|
||||
this.name = 'ServiceError'
|
||||
this.status = status
|
||||
this.code = options?.code
|
||||
this.details = options?.details
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface TruncateTextResult {
|
||||
text: string
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export function truncateText(text: string, maxLength: number, marker: string): TruncateTextResult {
|
||||
if (text.length <= maxLength) {
|
||||
return { text, truncated: false }
|
||||
}
|
||||
return { text: `${text.slice(0, maxLength)}${marker}`, truncated: true }
|
||||
}
|
||||
Reference in new issue
Block a user