Merge branch 'main' into Fix-0-Providers

This commit is contained in:
Wesley Tanner authored and GitHub committed 2026-10-30 06:40:37 -05:00
commit cb7d073af0
84 files changed
+2120 -6323

No files matched your search

+32 -2
View File
@@ -1,11 +1,41 @@
import type { Migration } from '../migration-runner'
import { ensureSessionGoalsTable } from '../session-goals'
const migration: Migration = {
id: '026-session-goals',
legacy: { version: 26, name: 'session-goals' },
up(db) {
ensureSessionGoalsTable(db)
db.run(`
CREATE TABLE IF NOT EXISTS session_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT 'local',
directory TEXT NOT NULL,
objective TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('active','paused','completed','blocked','stopped')),
stop_reason TEXT,
turn_state TEXT NOT NULL DEFAULT 'waiting',
continuation_count INTEGER NOT NULL DEFAULT 0,
max_continuations INTEGER NOT NULL,
token_budget INTEGER,
tokens_at_start INTEGER NOT NULL DEFAULT 0,
tokens_used INTEGER NOT NULL DEFAULT 0,
consecutive_blocked INTEGER NOT NULL DEFAULT 0,
last_verdict TEXT,
last_reason TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
finished_at INTEGER
)
`)
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
db.run(`
CREATE INDEX IF NOT EXISTS idx_session_goals_session
ON session_goals(session_id, created_at DESC)
`)
},
down(db) {
db.run('DROP TABLE IF EXISTS session_goals')
@@ -0,0 +1,53 @@
import type { Database } from 'bun:sqlite'
import type { Migration } from '../migration-runner'
function createSessionGoalsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT 'local',
directory TEXT NOT NULL,
objective TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('active','paused','completed','blocked','stopped')),
stop_reason TEXT,
turn_state TEXT NOT NULL DEFAULT 'waiting',
continuation_count INTEGER NOT NULL DEFAULT 0,
max_continuations INTEGER NOT NULL,
token_budget INTEGER,
tokens_at_start INTEGER NOT NULL DEFAULT 0,
tokens_used INTEGER NOT NULL DEFAULT 0,
consecutive_blocked INTEGER NOT NULL DEFAULT 0,
last_verdict TEXT,
last_reason TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
finished_at INTEGER
)
`)
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
db.run(`
CREATE INDEX IF NOT EXISTS idx_session_goals_session
ON session_goals(session_id, created_at DESC)
`)
}
const migration: Migration = {
id: '202610291200-drop-session-goals',
up(db) {
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
db.run('DROP INDEX IF EXISTS idx_session_goals_session')
db.run('DROP TABLE IF EXISTS session_goals')
},
down(db) {
createSessionGoalsTable(db)
},
}
export default migration
+2
View File
@@ -42,6 +42,7 @@ import { secretsGlobalScopeIndexMigration } from './202610181410-secrets-global-
import migration202610221800 from './202610221800-session-device-name'
import migration202610231200 from './202610231200-push-subscription-session-id'
import migration202610251900 from './202610251900-schedule-sandbox-config'
import migration202610291200 from './202610291200-drop-session-goals'
export const allMigrations: Migration[] = [
migration001,
@@ -87,4 +88,5 @@ export const allMigrations: Migration[] = [
migration202610221800,
migration202610231200,
migration202610251900,
migration202610291200,
]
-268
View File
@@ -1,268 +0,0 @@
import type { Database } from 'bun:sqlite'
import {
LOCAL_OPENCODE_SERVER_ID,
type SessionGoalStatus,
type SessionGoalStopReason,
type SessionGoalTurnState,
type SessionGoalVerdict,
} from '@opencode-manager/shared/schemas'
export interface SessionGoalRecord {
id: number
sessionId: string
serverId: string
directory: string
objective: string
status: SessionGoalStatus
stopReason: SessionGoalStopReason | null
turnState: SessionGoalTurnState
continuationCount: number
maxContinuations: number
tokenBudget: number | null
tokensAtStart: number
tokensUsed: number
consecutiveBlocked: number
lastVerdict: SessionGoalVerdict | null
lastReason: string | null
createdAt: number
updatedAt: number
finishedAt: number | null
}
export interface InsertSessionGoalInput {
sessionId: string
serverId?: string
directory: string
objective: string
maxContinuations: number
tokenBudget: number | null
tokensAtStart: number
}
export interface SessionGoalPatch {
status?: SessionGoalStatus
stopReason?: SessionGoalStopReason | null
turnState?: SessionGoalTurnState
continuationCount?: number
tokensUsed?: number
consecutiveBlocked?: number
lastVerdict?: SessionGoalVerdict | null
lastReason?: string | null
finishedAt?: number | null
}
interface SessionGoalRow {
id: number
session_id: string
server_id: string
directory: string
objective: string
status: SessionGoalStatus
stop_reason: SessionGoalStopReason | null
turn_state: SessionGoalTurnState
continuation_count: number
max_continuations: number
token_budget: number | null
tokens_at_start: number
tokens_used: number
consecutive_blocked: number
last_verdict: SessionGoalVerdict | null
last_reason: string | null
created_at: number
updated_at: number
finished_at: number | null
}
const SESSION_GOAL_COLUMNS = `
id, session_id, server_id, directory, objective, status, stop_reason, turn_state,
continuation_count, max_continuations, token_budget, tokens_at_start, tokens_used,
consecutive_blocked, last_verdict, last_reason, created_at, updated_at, finished_at
`
export function ensureSessionGoalsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT 'local',
directory TEXT NOT NULL,
objective TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('active','paused','completed','blocked','stopped')),
stop_reason TEXT,
turn_state TEXT NOT NULL DEFAULT 'waiting',
continuation_count INTEGER NOT NULL DEFAULT 0,
max_continuations INTEGER NOT NULL,
token_budget INTEGER,
tokens_at_start INTEGER NOT NULL DEFAULT 0,
tokens_used INTEGER NOT NULL DEFAULT 0,
consecutive_blocked INTEGER NOT NULL DEFAULT 0,
last_verdict TEXT,
last_reason TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
finished_at INTEGER
)
`)
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
db.run(`
CREATE INDEX IF NOT EXISTS idx_session_goals_session
ON session_goals(session_id, created_at DESC)
`)
}
export function insertSessionGoal(db: Database, input: InsertSessionGoalInput): SessionGoalRecord | null {
const now = Date.now()
try {
const result = db.prepare(`
INSERT INTO session_goals(
session_id, server_id, directory, objective, status, stop_reason, turn_state,
continuation_count, max_continuations, token_budget, tokens_at_start, tokens_used,
consecutive_blocked, last_verdict, last_reason, created_at, updated_at, finished_at
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
`).run(
input.sessionId,
input.serverId ?? LOCAL_OPENCODE_SERVER_ID,
input.directory,
input.objective,
'active',
null,
'waiting',
0,
input.maxContinuations,
input.tokenBudget,
input.tokensAtStart,
0,
0,
null,
null,
now,
now,
null,
)
return getSessionGoalById(db, Number(result.lastInsertRowid))
} catch (error) {
if (isUniqueConstraintError(error)) {
return null
}
throw error
}
}
export function getSessionGoalById(db: Database, id: number): SessionGoalRecord | null {
const row = db
.prepare(`SELECT ${SESSION_GOAL_COLUMNS} FROM session_goals WHERE id = ?`)
.get(id) as SessionGoalRow | undefined
return row ? mapSessionGoalRow(row) : null
}
export function getLatestSessionGoal(
db: Database,
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): SessionGoalRecord | null {
const row = db
.prepare(`
SELECT ${SESSION_GOAL_COLUMNS} FROM session_goals
WHERE server_id = ? AND session_id = ?
ORDER BY created_at DESC, id DESC
LIMIT 1
`)
.get(serverId, sessionId) as SessionGoalRow | undefined
return row ? mapSessionGoalRow(row) : null
}
export function listOpenSessionGoals(db: Database): SessionGoalRecord[] {
const rows = db
.prepare(`SELECT ${SESSION_GOAL_COLUMNS} FROM session_goals WHERE status IN ('active','paused') ORDER BY created_at ASC`)
.all() as SessionGoalRow[]
return rows.map(mapSessionGoalRow)
}
export function transitionSessionGoal(
db: Database,
id: number,
fromStatuses: SessionGoalStatus[],
patch: SessionGoalPatch,
): SessionGoalRecord | null {
const assignments: string[] = ['updated_at = ?']
const values: (string | number | null)[] = [Date.now()]
if (patch.status !== undefined) {
assignments.push('status = ?')
values.push(patch.status)
}
if (patch.stopReason !== undefined) {
assignments.push('stop_reason = ?')
values.push(patch.stopReason)
}
if (patch.turnState !== undefined) {
assignments.push('turn_state = ?')
values.push(patch.turnState)
}
if (patch.continuationCount !== undefined) {
assignments.push('continuation_count = ?')
values.push(patch.continuationCount)
}
if (patch.tokensUsed !== undefined) {
assignments.push('tokens_used = ?')
values.push(patch.tokensUsed)
}
if (patch.consecutiveBlocked !== undefined) {
assignments.push('consecutive_blocked = ?')
values.push(patch.consecutiveBlocked)
}
if (patch.lastVerdict !== undefined) {
assignments.push('last_verdict = ?')
values.push(patch.lastVerdict)
}
if (patch.lastReason !== undefined) {
assignments.push('last_reason = ?')
values.push(patch.lastReason)
}
if (patch.finishedAt !== undefined) {
assignments.push('finished_at = ?')
values.push(patch.finishedAt)
}
const placeholders = fromStatuses.map(() => '?').join(', ')
const result = db
.prepare(`UPDATE session_goals SET ${assignments.join(', ')} WHERE id = ? AND status IN (${placeholders})`)
.run(...values, id, ...fromStatuses)
if (result.changes === 0) {
return null
}
return getSessionGoalById(db, id)
}
function mapSessionGoalRow(row: SessionGoalRow): SessionGoalRecord {
return {
id: row.id,
sessionId: row.session_id,
serverId: row.server_id,
directory: row.directory,
objective: row.objective,
status: row.status,
stopReason: row.stop_reason,
turnState: row.turn_state,
continuationCount: row.continuation_count,
maxContinuations: row.max_continuations,
tokenBudget: row.token_budget,
tokensAtStart: row.tokens_at_start,
tokensUsed: row.tokens_used,
consecutiveBlocked: row.consecutive_blocked,
lastVerdict: row.last_verdict,
lastReason: row.last_reason,
createdAt: row.created_at,
updatedAt: row.updated_at,
finishedAt: row.finished_at,
}
}
function isUniqueConstraintError(error: unknown): boolean {
return error instanceof Error && /UNIQUE constraint failed/i.test(error.message)
}
+9 -21
View File
@@ -41,7 +41,6 @@ import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createSessionPinRoutes } from './routes/session-pins'
import { createSessionPermissionModeRoutes } from './routes/session-permission-modes'
import { createSessionSandboxRoutes } from './routes/session-sandbox'
import { createSessionGoalRoutes } from './routes/session-goals'
import { createMultiRunRoutes } from './routes/multi-runs'
import { createChangeWalkthroughRoutes } from './routes/change-walkthroughs'
import { getChangeWalkthroughByWalkthroughSession } from './db/change-walkthroughs'
@@ -67,7 +66,7 @@ import { RemoteAccessHeadersService } from './services/remote-access-headers'
import { SessionPermissionModeService } from './services/session-permission-modes'
import { SessionSandboxService } from './services/session-sandbox'
import { SessionAncestry } from './services/session-ancestry'
import { SessionGoalService } from './services/session-goals'
import { GoalOutcomeTracker } from './services/goal-outcomes'
import { MultiRunService } from './services/multi-runs'
import { ChangeWalkthroughService } from './services/change-walkthroughs'
import { opencodeServerManager } from './services/opencode-single-server'
@@ -302,16 +301,7 @@ const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
const notificationService = new NotificationService(db, opencodeServerRegistry)
const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry)
const sessionGoalService = new SessionGoalService(db, opencodeServerRegistry, sessionSettingsService, {
onOutcome: (goal) => {
void notificationService.notifyGoalOutcome(goal).catch((error) => {
logger.error('Goal outcome notification error:', error)
})
},
resolveSessionLock: async (sessionId, serverId) =>
(await sessionPermissionModeService.getEffectiveMode(sessionId, serverId)).lockedReason,
})
sessionGoalService.loadOpenGoals()
const goalOutcomes = new GoalOutcomeTracker()
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
@@ -331,9 +321,12 @@ sseAggregator.onServerEvent((serverId, directory, event) => {
sessionPermissionModeService.handleEvent(directory, event, serverId).catch((err) => {
logger.error('Session permission mode event handling error:', err)
})
sessionGoalService.handleEvent(directory, event, serverId).catch((err) => {
logger.error('Session goal event handling error:', err)
})
const outcome = goalOutcomes.observe(serverId, directory, event)
if (outcome) {
void notificationService.notifyGoalOutcome(outcome).catch((error) => {
logger.error('Goal outcome notification error:', error)
})
}
})
notificationService.addEventSuppressor((event, sessionId, serverId) =>
@@ -378,10 +371,6 @@ sseAggregator.start()
const remoteServerEvents = new RemoteServerEventHub(opencodeServerRegistry, sseAggregator)
remoteServerEvents.start()
void sessionGoalService.recoverOpenGoals().catch((error) => {
logger.error('Session goal recovery error:', error)
})
sseAggregator.setScheduledSessionsResolver(
() => scheduleService.getActiveRunSessions(),
)
@@ -397,7 +386,7 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth))
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, multiRunService, changeWalkthroughService, sessionSandboxService, repoEnvService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
const protectedApi = new Hono()
@@ -431,7 +420,6 @@ protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resol
protectedApi.route('/opencode-servers', createOpenCodeServerRoutes(opencodeServerRegistry, () => remoteServerEvents.getStatuses()))
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
protectedApi.route('/session-goals', createSessionGoalRoutes(sessionGoalService))
protectedApi.route('/multi-runs', createMultiRunRoutes(multiRunService))
protectedApi.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
-4
View File
@@ -19,7 +19,6 @@ import { createInternalShellEnvRoutes } from './shell-env'
import { createInternalGitCredentialsRoutes } from './git-credentials'
import { createInternalSandboxRoutes } from './sandbox'
import { createInternalSessionArtifactRoutes } from './session-artifacts'
import { createSessionGoalRoutes } from '../session-goals'
import { createMultiRunRoutes } from '../multi-runs'
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
import { createInternalWalkthroughSessionRoutes } from './walkthrough-sessions'
@@ -27,7 +26,6 @@ import type { SessionPermissionModeService } from '../../services/session-permis
import type { SessionSandboxService } from '../../services/session-sandbox'
import type { RepoWorkspaceService } from '../../services/repo-workspace'
import type { GitAuthService } from '../../services/git-auth'
import type { SessionGoalService } from '../../services/session-goals'
import type { MultiRunService } from '../../services/multi-runs'
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
import type { RepoEnvService } from '../../services/repo-env'
@@ -41,7 +39,6 @@ export function createInternalRoutes(
permissionModes: SessionPermissionModeService,
repoWorkspaces: RepoWorkspaceService,
gitAuthService: GitAuthService,
sessionGoals: SessionGoalService,
multiRuns: MultiRunService,
changeWalkthroughService: ChangeWalkthroughService,
sessionSandbox: SessionSandboxService,
@@ -50,7 +47,6 @@ export function createInternalRoutes(
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
app.route('/schedules', createScheduleRoutes(scheduleService))
app.route('/session-goals', createSessionGoalRoutes(sessionGoals, { serverScoped: false }))
app.route('/multi-runs', createMultiRunRoutes(multiRuns))
app.route('/notifications', createInternalNotificationRoutes(notificationService))
app.route('/settings', createInternalSettingsRoutes(settingsService))
-72
View File
@@ -1,72 +0,0 @@
import { Hono } from 'hono'
import { StartSessionGoalRequestSchema } from '@opencode-manager/shared/schemas'
import { SessionGoalError, type SessionGoalService } from '../services/session-goals'
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
export interface SessionGoalRouteOptions {
serverScoped?: boolean
}
export function createSessionGoalRoutes(
service: SessionGoalService,
options: SessionGoalRouteOptions = {},
) {
const serverScoped = options.serverScoped ?? true
const app = new Hono()
app.get('/', (c) => {
try {
const sessionId = c.req.query('sessionId')
if (!sessionId) {
return c.json({ error: 'Invalid request' }, 400)
}
const serverId = serverScoped ? c.req.query('serverId') : undefined
return c.json({ goal: serverId ? service.getLatest(sessionId, serverId) : service.getLatest(sessionId) })
} catch (error) {
return handleServiceError(c, error, 'Failed to read session goal', SessionGoalError)
}
})
app.post('/', async (c) => {
const parsed = await parseJsonBody(c, StartSessionGoalRequestSchema)
if (!parsed.ok) {
return parsed.response
}
try {
const goal = await service.start(serverScoped ? parsed.data : { ...parsed.data, serverId: undefined })
return c.json({ goal }, 201)
} catch (error) {
return handleServiceError(c, error, 'Failed to start session goal', SessionGoalError)
}
})
app.post('/:id/pause', (c) => {
try {
const goal = service.pause(parseId(c.req.param('id'), 'goal id', SessionGoalError))
return c.json({ goal })
} catch (error) {
return handleServiceError(c, error, 'Failed to pause session goal', SessionGoalError)
}
})
app.post('/:id/resume', (c) => {
try {
const goal = service.resume(parseId(c.req.param('id'), 'goal id', SessionGoalError))
return c.json({ goal })
} catch (error) {
return handleServiceError(c, error, 'Failed to resume session goal', SessionGoalError)
}
})
app.post('/:id/cancel', (c) => {
try {
const goal = service.cancel(parseId(c.req.param('id'), 'goal id', SessionGoalError))
return c.json({ goal })
} catch (error) {
return handleServiceError(c, error, 'Failed to cancel session goal', SessionGoalError)
}
})
return app
}
+76
View File
@@ -0,0 +1,76 @@
import {
goalChangeFromEvent,
isGoalOutcome,
sessionIDFromEvent,
type GoalState,
type GoalStatus,
} from '@opencode-manager/shared/opencode'
import type { SSEEvent } from './sse-aggregator'
/**
* A goal outcome observed for a session, ready to be turned into a notification.
*
* `directory` is the working directory to attribute the outcome to, preferring the
* observer's directory over the event location.
*/
export interface SessionGoalOutcome {
serverId: string
sessionId: string
directory: string | null
goal: GoalState
}
/**
* Tracks the last goal state seen per session so each goal outcome is reported once.
*
* State is in-memory only and keyed by server and session separated by a NUL
* character, which cannot appear in either id. Nothing is persisted or written to
* the database, so a fresh tracker reports the first outcome it sees.
*/
export class GoalOutcomeTracker {
private readonly observed = new Map<string, { id: string; status: GoalStatus }>()
/**
* Records a goal change and returns the outcome it produces, if any.
*
* Returns an outcome only when the goal reached a terminal state and that exact
* goal id and status were not already seen for the session. A deleted session, a
* cleared goal, or a missing goal reports no outcome and forgets the stored state.
*/
observe(serverId: string, directory: string | null, event: SSEEvent): SessionGoalOutcome | null {
if (event.type === 'session.deleted') {
const sessionId = sessionIDFromEvent(event)
if (sessionId) {
this.observed.delete(this.key(serverId, sessionId))
}
return null
}
const change = goalChangeFromEvent(event)
if (!change) return null
const key = this.key(serverId, change.sessionID)
if (change.goal === null) {
this.observed.delete(key)
return null
}
const goal = change.goal
const previous = this.observed.get(key)
this.observed.set(key, { id: goal.id, status: goal.status })
if (!isGoalOutcome(goal)) return null
if (previous?.id === goal.id && previous.status === goal.status) return null
return {
serverId,
sessionId: change.sessionID,
directory: directory ?? event.location?.directory ?? null,
goal,
}
}
private key(serverId: string, sessionID: string): string {
return `${serverId}\u0000${sessionID}`
}
}
+25 -23
View File
@@ -11,14 +11,12 @@ import {
DEFAULT_NOTIFICATION_PREFERENCES,
LOCAL_OPENCODE_SERVER_ID,
type OpenCodeServer,
type SessionGoal,
} from "@opencode-manager/shared/schemas";
import {
getPermissionLabel,
getPermissionDetail,
getFormText,
getGoalOutcomeTitle,
getGoalOutcomeReason,
getGoalStatusTitle,
} from "@opencode-manager/shared/notifications";
import { SettingsService } from "./settings";
import { sseAggregator, type SSEEvent } from "./sse-aggregator";
@@ -30,6 +28,7 @@ import type { Repo } from "../types/repo";
import { buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils";
import { sessionIDFromEvent } from "@opencode-manager/shared/opencode";
import { resolveRepoForDirectory } from "./repo";
import type { SessionGoalOutcome } from "./goal-outcomes";
export interface NotificationServerRegistry {
get(serverId: string): Pick<OpenCodeServer, "name" | "enabled"> | null;
@@ -91,19 +90,23 @@ function truncateWithEllipsis(text: string, maxLength: number): string {
return `${text.slice(0, maxLength - 1)}…`;
}
function buildGoalOutcomeBody(goal: SessionGoal, repoName: string | undefined): string {
const reason = getGoalOutcomeReason(goal)?.trim() || undefined;
function buildGoalOutcomeBody(
objective: string,
reason: string | undefined,
repoName: string | undefined
): string {
const trimmedReason = reason?.trim() || undefined;
const prefix = repoName ? `${repoName} · ` : "";
const separator = " — ";
const reasonBudget = Math.max(0, MAX_BODY_LENGTH - prefix.length - separator.length);
const boundedReason = reason ? truncateWithEllipsis(reason, reasonBudget) : "";
const boundedReason = trimmedReason ? truncateWithEllipsis(trimmedReason, reasonBudget) : "";
const suffix = boundedReason ? `${separator}${boundedReason}` : "";
const objectiveBudget = Math.max(0, MAX_BODY_LENGTH - prefix.length - suffix.length);
const objective = truncateWithEllipsis(goal.objective, objectiveBudget);
const boundedObjective = truncateWithEllipsis(objective, objectiveBudget);
return truncateWithEllipsis(`${prefix}${objective}${suffix}`, MAX_BODY_LENGTH);
return truncateWithEllipsis(`${prefix}${boundedObjective}${suffix}`, MAX_BODY_LENGTH);
}
function resolveEventSessionId(event: SSEEvent): string | undefined {
@@ -435,36 +438,35 @@ export class NotificationService {
);
}
async notifyGoalOutcome(goal: SessionGoal): Promise<void> {
if (goal.stopReason === "turn_error") return;
if (goal.stopReason === "cancelled" || goal.stopReason === "user_paused") return;
if (sseAggregator.isSessionBeingViewed(goal.sessionId, goal.serverId)) return;
async notifyGoalOutcome(outcome: SessionGoalOutcome): Promise<void> {
if (sseAggregator.isSessionBeingViewed(outcome.sessionId, outcome.serverId)) return;
const isRemote = goal.serverId !== LOCAL_OPENCODE_SERVER_ID;
const repo = !isRemote && goal.directory
? await resolveRepoForDirectory(this.db, goal.directory)
const { goal } = outcome;
const isRemote = outcome.serverId !== LOCAL_OPENCODE_SERVER_ID;
const repo = !isRemote && outcome.directory
? await resolveRepoForDirectory(this.db, outcome.directory)
: null;
const server = isRemote ? this.serverRegistry?.get(goal.serverId) ?? null : null;
const server = isRemote ? this.serverRegistry?.get(outcome.serverId) ?? null : null;
const repoName = repo ? getRepoName(repo) : undefined;
const displayName = repoName ?? server?.name;
const payload: PushNotificationPayload = {
title: getGoalOutcomeTitle(goal.status),
body: buildGoalOutcomeBody(goal, displayName),
title: getGoalStatusTitle(goal.status),
body: buildGoalOutcomeBody(goal.objective, goal.reason, displayName),
tag: `session-goal-${goal.id}`,
timestamp: Date.now(),
renotify: true,
data: {
eventType: "session.goal.outcome",
sessionId: goal.sessionId,
directory: goal.directory,
sessionId: outcome.sessionId,
directory: outcome.directory ?? undefined,
repoId: repo?.id,
repoName,
serverId: goal.serverId,
serverId: outcome.serverId,
serverName: server?.name,
url: isRemote
? buildServerSessionPath(goal.serverId, goal.sessionId)
: buildNotificationUrl(repo, goal.sessionId),
? buildServerSessionPath(outcome.serverId, outcome.sessionId)
: buildNotificationUrl(repo, outcome.sessionId),
},
};
@@ -449,7 +449,7 @@ describe('OpenCodeServerRegistry', () => {
describe('test', () => {
it('reports a supported version', async () => {
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.1.2' }))
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.2.1' }))
const result = await registry.test({
baseUrl: 'https://studio.example.com/',
@@ -457,7 +457,7 @@ describe('OpenCodeServerRegistry', () => {
password: 'super-secret',
})
expect(result).toEqual({ ok: true, version: '2.1.2', versionSupported: true, error: null })
expect(result).toEqual({ ok: true, version: '2.2.1', versionSupported: true, error: null })
expect(fetchFn.mock.calls[0]?.[0]).toBe('https://studio.example.com/api/info')
const headers = new Headers(fetchFn.mock.calls[0]?.[1]?.headers)
expect(headers.get('authorization')).toBe(`Basic ${btoa('alice:super-secret')}`)
@@ -478,7 +478,7 @@ describe('OpenCodeServerRegistry', () => {
username: 'alice',
password: 'super-secret',
})
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.1.2' }))
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.2.1' }))
const result = await registry.test({ serverId: server.id })
@@ -493,7 +493,7 @@ describe('OpenCodeServerRegistry', () => {
baseUrl: 'https://studio.example.com',
password: 'super-secret',
})
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.1.2' }))
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.2.1' }))
const result = await registry.test({
baseUrl: 'https://studio.example.com/opencode',
@@ -513,7 +513,7 @@ describe('OpenCodeServerRegistry', () => {
baseUrl: 'https://studio.example.com',
password: 'super-secret',
})
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.1.2' }))
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.2.1' }))
const result = await registry.test({
baseUrl: 'https://relocated.example.com',
@@ -533,7 +533,7 @@ describe('OpenCodeServerRegistry', () => {
baseUrl: 'https://studio.example.com',
password: 'super-secret',
})
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.1.2' }))
fetchFn.mockResolvedValueOnce(jsonResponse({ version: '2.2.1' }))
await registry.test({
baseUrl: 'https://studio.example.com',
@@ -1,79 +0,0 @@
import { z } from 'zod'
import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas'
import { parseFirstJsonObject } from '../utils/json-extract'
import { truncateSessionReply } from './session-reply'
export const GOAL_AUDIT_REASON_MAX_CHARS = 500
export const GOAL_AUDIT_UNPARSED_REASON = 'Auditor response was not understood'
export interface GoalAuditPromptInput {
objective: string
reply: string | null
}
export interface GoalContinuationPromptInput {
objective: string
reason: string
}
export interface GoalVerdict {
verdict: SessionGoalVerdict
reason: string
}
export function buildGoalAuditPrompt({ objective, reply }: GoalAuditPromptInput): string {
return [
'You audit whether an autonomous coding goal has been achieved.',
'You can only see the goal objective and the agent\'s latest reply. You cannot run tools or read files.',
'',
'Goal objective:',
objective,
'',
'Agent\'s latest reply:',
truncateReply(reply),
'',
'Decide the goal state:',
'- "done": the objective is verifiably achieved based on the reply.',
'- "blocked": the agent needs a user decision or access it cannot obtain.',
'- "continue": anything else, including when the reply is not enough to confirm completion.',
'',
'Respond with only this JSON and nothing else:',
'{"verdict":"continue"|"done"|"blocked","reason":"<one sentence>"}',
].join('\n')
}
export function buildGoalContinuationPrompt({ objective, reason }: GoalContinuationPromptInput): string {
return [
`Continue working toward this goal: ${objective}`,
'',
`Progress check: ${reason}`,
'',
'Keep working until the goal is achieved. If you need a user decision or access you cannot obtain, stop and state exactly what you need.',
].join('\n')
}
const goalVerdictSchema = z.object({
verdict: SessionGoalVerdictSchema,
reason: z.string(),
})
export function parseGoalVerdict(text: string): GoalVerdict | null {
const parsed = parseFirstJsonObject(text, goalVerdictSchema)
if (!parsed) {
return null
}
const reason = parsed.reason.trim()
if (!reason) {
return null
}
return { verdict: parsed.verdict, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) }
}
function truncateReply(reply: string | null): string {
if (!reply) {
return '(no reply yet)'
}
return truncateSessionReply(reply)
}
-730
View File
@@ -1,730 +0,0 @@
import type { Database } from 'bun:sqlite'
import {
DEFAULT_SESSION_DEFAULTS,
LOCAL_OPENCODE_SERVER_ID,
type SessionGoal,
type SessionGoalStatus,
type SessionGoalStopReason,
type SessionGoalTurnState,
type SessionLockReason,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
import {
isSessionNotFoundError,
parseOpenCodeModelRef,
sessionIDFromEvent,
type ModelRef,
} from '@opencode-manager/shared/opencode'
import {
getLatestSessionGoal,
getSessionGoalById,
insertSessionGoal,
listOpenSessionGoals,
transitionSessionGoal,
type SessionGoalPatch,
type SessionGoalRecord,
} from '../db/session-goals'
import { logger } from '../utils/logger'
import {
buildGoalAuditPrompt,
buildGoalContinuationPrompt,
GOAL_AUDIT_UNPARSED_REASON,
parseGoalVerdict,
type GoalVerdict,
} from './session-goal-audit'
import { isSessionBusy, readLatestAssistantReply, type AssistantReplyState } from './session-reply'
import type { OpenCodeClient } from './opencode/client'
import type { SettingsService } from './settings'
import type { SSEEvent } from './sse-aggregator'
const DEFAULT_QUIET_MS = 3000
const BLOCKED_LIMIT = 3
const AUDITOR_ATTEMPTS = 2
const RECOVERY_RETRY_MS = 5000
type PrerequisiteResult<T> = { ok: true; value: T } | { ok: false }
export interface SessionServerRegistry {
getClient(serverId: string): OpenCodeClient
get(serverId: string): { enabled: boolean } | null
}
export type SessionServerSource = OpenCodeClient | SessionServerRegistry
export interface SessionGoalServiceOptions {
quietMs?: number
onOutcome?: (goal: SessionGoal) => void
resolveSessionLock?: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
}
export class SessionGoalError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
}
}
export function sessionTokenTotal(tokens: { input: number; output: number; reasoning: number }): number {
return tokens.input + tokens.output + tokens.reasoning
}
function goalKey(serverId: string, sessionId: string): string {
return `${serverId}:${sessionId}`
}
function isServerRegistry(source: SessionServerSource): source is SessionServerRegistry {
return typeof (source as SessionServerRegistry).getClient === 'function'
}
function toServerRegistry(source: SessionServerSource): SessionServerRegistry {
if (isServerRegistry(source)) {
return source
}
return {
getClient: () => source,
get: (serverId) => (serverId === LOCAL_OPENCODE_SERVER_ID ? { enabled: true } : null),
}
}
function toSessionGoal(record: SessionGoalRecord): SessionGoal {
return {
id: record.id,
sessionId: record.sessionId,
serverId: record.serverId,
directory: record.directory,
objective: record.objective,
status: record.status,
stopReason: record.stopReason,
turnState: record.turnState,
continuationCount: record.continuationCount,
maxContinuations: record.maxContinuations,
tokenBudget: record.tokenBudget,
tokensUsed: record.tokensUsed,
consecutiveBlocked: record.consecutiveBlocked,
lastVerdict: record.lastVerdict,
lastReason: record.lastReason,
createdAt: record.createdAt,
updatedAt: record.updatedAt,
finishedAt: record.finishedAt,
}
}
export class SessionGoalService {
private readonly goalBySession = new Map<string, number>()
private readonly auditTimers = new Map<string, ReturnType<typeof setTimeout>>()
private readonly recoveryTimers = new Map<string, ReturnType<typeof setTimeout>>()
private readonly auditing = new Set<number>()
private readonly auditRequested = new Set<number>()
private readonly auditGeneration = new Map<string, number>()
private readonly servers: SessionServerRegistry
private readonly quietMs: number
private readonly onOutcome: (goal: SessionGoal) => void
private readonly resolveSessionLock: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
constructor(
private readonly db: Database,
servers: SessionServerSource,
private readonly settingsService: SettingsService,
options: SessionGoalServiceOptions = {},
) {
this.servers = toServerRegistry(servers)
this.quietMs = options.quietMs ?? DEFAULT_QUIET_MS
this.onOutcome = options.onOutcome ?? (() => {})
this.resolveSessionLock = options.resolveSessionLock ?? (async () => null)
}
loadOpenGoals(): void {
this.goalBySession.clear()
for (const record of listOpenSessionGoals(this.db)) {
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
}
}
async recoverOpenGoals(): Promise<void> {
for (const record of listOpenSessionGoals(this.db)) {
if (record.status !== 'active' || record.turnState !== 'running') {
continue
}
if (!this.isServerAvailable(record.serverId)) {
continue
}
try {
await this.recoverRunningGoal(record)
} catch (error) {
logger.error(`Session goal recovery failed for goal ${record.id}:`, error)
}
}
}
private async recoverRunningGoal(record: SessionGoalRecord): Promise<void> {
const key = goalKey(record.serverId, record.sessionId)
const generation = this.currentAuditGeneration(key)
const client = this.servers.getClient(record.serverId)
try {
await client.api.session.get({ sessionID: record.sessionId })
} catch (error) {
if (isSessionNotFoundError(error)) {
this.finishGoal(record.id, 'stopped', 'session_deleted')
return
}
logger.error(`Session goal recovery could not read session ${record.sessionId}:`, error)
this.scheduleRecoveryRetry(key, record.id, generation)
return
}
const busy = await this.readPrerequisite(record.id, 'busy check', () =>
isSessionBusy(client, record.sessionId),
)
if (!busy.ok) {
this.scheduleRecoveryRetry(key, record.id, generation)
return
}
if (busy.value) {
return
}
this.scheduleAudit(key, record.id, 0)
}
private isServerAvailable(serverId: string): boolean {
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
return true
}
try {
const server = this.servers.get(serverId)
return Boolean(server?.enabled)
} catch (error) {
logger.error(`Failed to resolve OpenCode server ${serverId}:`, error)
return false
}
}
private scheduleRecoveryRetry(key: string, goalId: number, generation: number): void {
this.clearRecoveryTimer(key)
const timer = setTimeout(() => {
this.recoveryTimers.delete(key)
void this.retryRecovery(key, goalId, generation).catch((error) => {
logger.error(`Session goal recovery retry failed for goal ${goalId}:`, error)
})
}, RECOVERY_RETRY_MS)
this.recoveryTimers.set(key, timer)
}
private async retryRecovery(key: string, goalId: number, generation: number): Promise<void> {
const record = getSessionGoalById(this.db, goalId)
if (!record || record.status !== 'active' || record.turnState !== 'running') {
return
}
if (!this.isServerAvailable(record.serverId)) {
return
}
if (this.currentAuditGeneration(key) !== generation) {
return
}
await this.recoverRunningGoal(record)
}
private clearRecoveryTimer(key: string): void {
const timer = this.recoveryTimers.get(key)
if (timer !== undefined) {
clearTimeout(timer)
this.recoveryTimers.delete(key)
}
}
async start(input: StartSessionGoalRequest): Promise<SessionGoal> {
const serverId = input.serverId ?? LOCAL_OPENCODE_SERVER_ID
await this.assertSessionCanStartGoal(input.sessionId, serverId)
const defaults = this.settingsService.getSettings().preferences.sessionDefaults
const maxContinuations =
input.maxContinuations ?? defaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations
const tokenBudget = input.tokenBudget ?? defaults?.goalTokenBudget ?? null
const tokensAtStart = await this.readSessionTokenTotalOrDefault(input.sessionId, serverId)
const record = insertSessionGoal(this.db, {
sessionId: input.sessionId,
serverId,
directory: input.directory,
objective: input.objective,
maxContinuations,
tokenBudget,
tokensAtStart,
})
if (!record) {
throw new SessionGoalError('This session already has an open goal', 409)
}
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
return toSessionGoal(record)
}
getLatest(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): SessionGoal | null {
const record = getLatestSessionGoal(this.db, sessionId, serverId)
return record ? toSessionGoal(record) : null
}
private async assertSessionCanStartGoal(sessionId: string, serverId: string): Promise<void> {
let lock: SessionLockReason | null
try {
lock = await this.resolveSessionLock(sessionId, serverId)
} catch (error) {
logger.error(`Failed to resolve session lock for ${sessionId}:`, error)
return
}
if (lock === 'schedule') {
throw new SessionGoalError('Scheduled runs cannot run goals', 409)
}
if (lock === 'child') {
throw new SessionGoalError('Goals can only be started on top-level sessions', 400)
}
}
pause(id: number): SessionGoal {
return this.transitionWithOutcome(id, ['active'], { status: 'paused', stopReason: 'user_paused' })
}
resume(id: number): SessionGoal {
const record = this.transition(id, ['paused'], {
status: 'active',
stopReason: null,
turnState: 'running',
finishedAt: null,
})
const goal = toSessionGoal(record)
void this.scheduleAuditWhenIdle(goal)
return goal
}
cancel(id: number): SessionGoal {
return this.transitionWithOutcome(id, ['active', 'paused'], {
status: 'stopped',
stopReason: 'cancelled',
finishedAt: Date.now(),
})
}
async handleEvent(
directory: string | null,
event: SSEEvent,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): Promise<void> {
const sessionId = sessionIDFromEvent(event)
if (!sessionId) {
return
}
const key = goalKey(serverId, sessionId)
const goalId = this.goalBySession.get(key)
if (goalId === undefined) {
return
}
switch (event.type) {
case 'session.execution.started':
this.clearAuditTimer(key)
this.applyTransition(goalId, ['active'], { turnState: 'running' })
return
case 'session.idle':
case 'session.execution.succeeded':
this.scheduleAuditFromEvent(key, goalId)
return
case 'session.status':
if (event.data.status.type === 'idle') {
this.scheduleAuditFromEvent(key, goalId)
}
return
case 'session.execution.failed':
this.clearAuditTimer(key)
this.finishGoal(goalId, 'stopped', 'turn_error')
return
case 'session.execution.interrupted':
this.clearAuditTimer(key)
this.finishGoal(goalId, 'paused', 'interrupted')
return
case 'session.deleted':
this.clearAuditTimer(key)
this.finishGoal(goalId, 'stopped', 'session_deleted', ['active', 'paused'])
return
default:
return
}
}
private scheduleAuditFromEvent(key: string, goalId: number): void {
const record = getSessionGoalById(this.db, goalId)
if (!record || record.status !== 'active' || record.turnState !== 'running') {
return
}
this.scheduleAudit(key, goalId, this.quietMs)
}
private async scheduleAuditWhenIdle(goal: SessionGoal): Promise<void> {
const key = goalKey(goal.serverId, goal.sessionId)
const generation = this.currentAuditGeneration(key)
const busy = await this.readPrerequisite(goal.id, 'busy check', () =>
isSessionBusy(this.servers.getClient(goal.serverId), goal.sessionId),
)
if (!busy.ok) {
this.failAudit(goal.id, key, generation)
return
}
if (!this.isAuditCurrent(goal.id, key, generation)) {
return
}
if (busy.value) {
return
}
this.scheduleAudit(key, goal.id, 0)
}
private scheduleAudit(key: string, goalId: number, delay: number): void {
this.clearRecoveryTimer(key)
this.clearAuditTimer(key)
const timer = setTimeout(() => {
this.auditTimers.delete(key)
void this.runAudit(goalId).catch((error) => {
logger.error(`Session goal audit failed for goal ${goalId}:`, error)
})
}, delay)
this.auditTimers.set(key, timer)
}
private clearAuditTimer(key: string): void {
const timer = this.auditTimers.get(key)
if (timer !== undefined) {
clearTimeout(timer)
this.auditTimers.delete(key)
}
}
private async runAudit(goalId: number): Promise<void> {
if (this.auditing.has(goalId)) {
this.auditRequested.add(goalId)
return
}
this.auditing.add(goalId)
try {
let pending = true
while (pending) {
this.auditRequested.delete(goalId)
await this.performAudit(goalId)
pending = this.auditRequested.has(goalId)
}
} finally {
this.auditing.delete(goalId)
}
}
private async performAudit(goalId: number): Promise<void> {
const goal = getSessionGoalById(this.db, goalId)
if (!goal || goal.status !== 'active' || goal.turnState !== 'running') {
return
}
const sessionId = goal.sessionId
const key = goalKey(goal.serverId, sessionId)
const generation = this.currentAuditGeneration(key)
const client = this.servers.getClient(goal.serverId)
const busy = await this.readPrerequisite(goalId, 'busy check', () =>
isSessionBusy(client, sessionId),
)
if (!busy.ok) {
this.failAudit(goalId, key, generation)
return
}
if (!this.isAuditCurrent(goalId, key, generation) || busy.value) {
return
}
const total = await this.readPrerequisite(goalId, 'token read', () =>
this.readSessionTokenTotal(sessionId, goal.serverId),
)
if (!total.ok) {
this.failAudit(goalId, key, generation)
return
}
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
const tokensUsed = Math.max(0, total.value - goal.tokensAtStart)
const updated = this.applyTransition(goalId, ['active'], { tokensUsed })
if (!updated) {
return
}
if (updated.tokenBudget !== null && tokensUsed >= updated.tokenBudget) {
this.finishGoal(goalId, 'stopped', 'token_budget')
return
}
const reply = await this.readPrerequisite(goalId, 'reply read', () =>
readLatestAssistantReply(client, sessionId),
)
if (!reply.ok) {
this.failAudit(goalId, key, generation)
return
}
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
if (reply.value?.errorText) {
this.finishGoal(goalId, 'stopped', 'turn_error')
return
}
const verdict = await this.evaluateAudit(updated, reply.value)
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
if (!verdict) {
this.finishGoal(goalId, 'paused', 'audit_failed')
return
}
await this.applyVerdict(goalId, key, generation, updated, verdict)
}
private async evaluateAudit(goal: SessionGoalRecord, reply: AssistantReplyState | null): Promise<GoalVerdict | null> {
const prompt = buildGoalAuditPrompt({ objective: goal.objective, reply: reply?.responseText ?? null })
const model = this.resolveAuditorModel()
const localClient = this.servers.getClient(LOCAL_OPENCODE_SERVER_ID)
for (let attempt = 0; attempt < AUDITOR_ATTEMPTS; attempt += 1) {
try {
const result = await localClient.api.generate.text(model ? { prompt, model } : { prompt })
return parseGoalVerdict(result.text) ?? { verdict: 'continue', reason: GOAL_AUDIT_UNPARSED_REASON }
} catch (error) {
logger.error(`Goal auditor call failed for goal ${goal.id} (attempt ${attempt + 1}):`, error)
}
}
return null
}
private resolveAuditorModel(): ModelRef | undefined {
const configured = this.settingsService.getSettings().preferences.sessionDefaults?.goalAuditorModel
return configured ? parseOpenCodeModelRef(configured) : undefined
}
private async applyVerdict(
goalId: number,
key: string,
generation: number,
goal: SessionGoalRecord,
verdict: GoalVerdict,
): Promise<void> {
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
if (verdict.verdict === 'done') {
this.finishGoal(goalId, 'completed', null, ['active'], {
lastVerdict: 'done',
lastReason: verdict.reason,
})
return
}
if (verdict.verdict === 'blocked') {
const consecutiveBlocked = goal.consecutiveBlocked + 1
const patch: SessionGoalPatch = {
consecutiveBlocked,
lastVerdict: 'blocked',
lastReason: verdict.reason,
}
if (consecutiveBlocked >= BLOCKED_LIMIT) {
this.finishGoal(goalId, 'blocked', null, ['active'], patch)
return
}
await this.continueGoal(goalId, key, generation, goal, verdict.reason, patch)
return
}
await this.continueGoal(goalId, key, generation, goal, verdict.reason, {
consecutiveBlocked: 0,
lastVerdict: 'continue',
lastReason: verdict.reason,
})
}
private async continueGoal(
goalId: number,
key: string,
generation: number,
goal: SessionGoalRecord,
reason: string,
patch: SessionGoalPatch,
): Promise<void> {
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
if (goal.continuationCount >= goal.maxContinuations) {
this.finishGoal(goalId, 'stopped', 'continuation_limit', ['active'], patch)
return
}
const record = this.applyTransition(goalId, ['active'], {
...patch,
continuationCount: goal.continuationCount + 1,
turnState: 'waiting',
})
if (!record) {
return
}
try {
await this.servers.getClient(record.serverId).api.session.prompt({
sessionID: record.sessionId,
text: buildGoalContinuationPrompt({ objective: record.objective, reason }),
})
} catch (error) {
logger.error(`Failed to send continuation for goal ${goalId}:`, error)
if (this.isAuditCurrent(goalId, key, generation, 'waiting')) {
this.finishGoal(goalId, 'stopped', 'turn_error')
}
}
}
private finishGoal(
goalId: number,
status: SessionGoalStatus,
stopReason: SessionGoalStopReason | null,
fromStatuses: SessionGoalStatus[] = ['active'],
patch: SessionGoalPatch = {},
): void {
const record = this.applyTransition(goalId, fromStatuses, {
...patch,
status,
stopReason,
finishedAt: status === 'paused' ? null : Date.now(),
})
if (record) {
this.onOutcome(toSessionGoal(record))
}
}
private failAudit(goalId: number, key: string, generation: number): void {
if (!this.isAuditCurrent(goalId, key, generation)) {
return
}
this.finishGoal(goalId, 'paused', 'audit_failed')
}
private async readPrerequisite<T>(
goalId: number,
label: string,
read: () => Promise<T>,
): Promise<PrerequisiteResult<T>> {
for (let attempt = 0; attempt < AUDITOR_ATTEMPTS; attempt += 1) {
try {
return { ok: true, value: await read() }
} catch (error) {
logger.error(`Session goal ${goalId} ${label} failed (attempt ${attempt + 1}):`, error)
}
}
return { ok: false }
}
private isAuditCurrent(
goalId: number,
key: string,
generation: number,
turnState: SessionGoalTurnState = 'running',
): boolean {
if (this.currentAuditGeneration(key) !== generation) {
return false
}
const record = getSessionGoalById(this.db, goalId)
return Boolean(record && record.status === 'active' && record.turnState === turnState)
}
private currentAuditGeneration(key: string): number {
return this.auditGeneration.get(key) ?? 0
}
private applyTransition(
goalId: number,
fromStatuses: SessionGoalStatus[],
patch: SessionGoalPatch,
): SessionGoalRecord | null {
const record = transitionSessionGoal(this.db, goalId, fromStatuses, patch)
if (!record) {
return null
}
this.syncGoalIndex(record)
this.maybeInvalidateAudits(record, patch)
return record
}
private transitionWithOutcome(
id: number,
fromStatuses: SessionGoalStatus[],
patch: SessionGoalPatch,
): SessionGoal {
const goal = toSessionGoal(this.transition(id, fromStatuses, patch))
this.onOutcome(goal)
return goal
}
private transition(id: number, fromStatuses: SessionGoalStatus[], patch: SessionGoalPatch): SessionGoalRecord {
const record = this.applyTransition(id, fromStatuses, patch)
if (!record) {
if (!getSessionGoalById(this.db, id)) {
throw new SessionGoalError('Session goal not found', 404)
}
throw new SessionGoalError('Session goal cannot transition from its current state', 409)
}
return record
}
private syncGoalIndex(record: SessionGoalRecord): void {
const key = goalKey(record.serverId, record.sessionId)
if (record.status === 'active' || record.status === 'paused') {
this.goalBySession.set(key, record.id)
} else {
this.goalBySession.delete(key)
this.clearAuditTimer(key)
}
if (record.status !== 'active') {
this.clearRecoveryTimer(key)
}
}
private maybeInvalidateAudits(record: SessionGoalRecord, patch: SessionGoalPatch): void {
if (patch.status === undefined && patch.turnState !== 'running') {
return
}
const key = goalKey(record.serverId, record.sessionId)
this.auditGeneration.set(key, this.currentAuditGeneration(key) + 1)
this.auditRequested.delete(record.id)
}
private async readSessionTokenTotal(sessionId: string, serverId: string): Promise<number> {
const session = await this.servers.getClient(serverId).api.session.get({ sessionID: sessionId })
return sessionTokenTotal(session.tokens)
}
private async readSessionTokenTotalOrDefault(sessionId: string, serverId: string): Promise<number> {
try {
return await this.readSessionTokenTotal(sessionId, serverId)
} catch (error) {
logger.error(`Failed to read token usage for session ${sessionId}:`, error)
return 0
}
}
}
-64
View File
@@ -1,64 +0,0 @@
import type { ZodType } from 'zod'
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
}
export function parseFirstJsonObject<T>(text: string, schema: ZodType<T>): T | null {
const extracted = extractFirstJsonObject(text)
if (!extracted) {
return null
}
let raw: unknown
try {
raw = JSON.parse(extracted)
} catch {
return null
}
const parsed = schema.safeParse(raw)
if (!parsed.success) {
return null
}
return parsed.data
}