mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(servers): run Manager automation on linked servers
This commit is contained in:
1 parent
c591c15743
commit
a9bdb8358f
131 files changed
+6568
-949
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const SERVER_ID_COLUMN = 'server_id'
|
||||
|
||||
function tableExists(db: Database, table: string): boolean {
|
||||
return Boolean(
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table),
|
||||
)
|
||||
}
|
||||
|
||||
function hasColumn(db: Database, table: string, column: string): boolean {
|
||||
const columns = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
|
||||
return columns.some((entry) => entry.name === column)
|
||||
}
|
||||
|
||||
function addServerIdColumn(db: Database, table: string): void {
|
||||
if (!tableExists(db, table) || hasColumn(db, table, SERVER_ID_COLUMN)) {
|
||||
return
|
||||
}
|
||||
db.run(`ALTER TABLE ${table} ADD COLUMN server_id TEXT NOT NULL DEFAULT '${LOCAL_OPENCODE_SERVER_ID}'`)
|
||||
}
|
||||
|
||||
function dropServerIdColumn(db: Database, table: string): void {
|
||||
if (!tableExists(db, table) || !hasColumn(db, table, SERVER_ID_COLUMN)) {
|
||||
return
|
||||
}
|
||||
db.run(`ALTER TABLE ${table} DROP COLUMN ${SERVER_ID_COLUMN}`)
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181300-session-server-scope',
|
||||
|
||||
up(db) {
|
||||
addServerIdColumn(db, 'session_permission_modes')
|
||||
addServerIdColumn(db, 'session_goals')
|
||||
|
||||
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
|
||||
ON session_goals(server_id, session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
|
||||
if (tableExists(db, 'session_goals')) {
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
|
||||
ON session_goals(session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
}
|
||||
dropServerIdColumn(db, 'session_goals')
|
||||
dropServerIdColumn(db, 'session_permission_modes')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const REBUILT_COLUMNS = `
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
`
|
||||
|
||||
function needsRebuild(columns: ColumnInfo[]): boolean {
|
||||
if (columns.length === 0) return false
|
||||
|
||||
const byName = new Map(columns.map((column) => [column.name, column]))
|
||||
const repoId = byName.get('repo_id')
|
||||
if (!repoId || repoId.notnull === 1) return true
|
||||
return !byName.has('server_id') || !byName.has('directory')
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181310-multi-run-targets',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
if (!needsRebuild(columns)) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
const serverId = names.has('server_id') ? 'server_id' : "'local'"
|
||||
const directory = names.has('directory') ? 'directory' : 'NULL'
|
||||
|
||||
db.run('DROP TABLE IF EXISTS multi_runs_targets')
|
||||
db.run(`CREATE TABLE multi_runs_targets (${REBUILT_COLUMNS})`)
|
||||
db.run(`
|
||||
INSERT INTO multi_runs_targets (id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
SELECT id, repo_id, ${serverId}, ${directory}, name, prompt, isolated, base_ref, created_at
|
||||
FROM multi_runs
|
||||
`)
|
||||
db.run('DROP TABLE multi_runs')
|
||||
db.run('ALTER TABLE multi_runs_targets RENAME TO multi_runs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_repo ON multi_runs(repo_id, created_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_server ON multi_runs(server_id, directory, created_at DESC)')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
if (columns.length === 0) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
if (!names.has('server_id') && !names.has('directory')) return
|
||||
|
||||
db.run('DROP TABLE IF EXISTS multi_runs_repo_only')
|
||||
db.run(`
|
||||
CREATE TABLE multi_runs_repo_only (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
INSERT INTO multi_runs_repo_only (id, repo_id, name, prompt, isolated, base_ref, created_at)
|
||||
SELECT id, repo_id, name, prompt, isolated, base_ref, created_at
|
||||
FROM multi_runs
|
||||
WHERE repo_id IS NOT NULL
|
||||
`)
|
||||
db.run('DROP TABLE multi_runs')
|
||||
db.run('ALTER TABLE multi_runs_repo_only RENAME TO multi_runs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_repo ON multi_runs(repo_id, created_at DESC)')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,254 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const LEGACY_SUFFIX = '_legacy_202610181320'
|
||||
|
||||
function createJobsTable(db: { run: (sql: string) => void }, table: string): void {
|
||||
db.run(`
|
||||
CREATE TABLE ${table} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||
cron_expression TEXT,
|
||||
timezone TEXT,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
permission_config TEXT,
|
||||
mcp_servers TEXT,
|
||||
branch TEXT,
|
||||
workspace_mode TEXT NOT NULL DEFAULT 'worktree',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
function createRunsTable(db: { run: (sql: string) => void }, table: string): void {
|
||||
db.run(`
|
||||
CREATE TABLE ${table} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
trigger_source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER,
|
||||
viewed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
session_id TEXT,
|
||||
session_title TEXT,
|
||||
log_text TEXT,
|
||||
response_text TEXT,
|
||||
error_text TEXT,
|
||||
run_branch TEXT,
|
||||
commit_hash TEXT,
|
||||
worktree_path TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181320-remote-schedule-targets',
|
||||
|
||||
up(db) {
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
if (jobColumns.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const runColumns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const jobColumnNames = new Set(jobColumns.map((column) => column.name))
|
||||
const runColumnNames = new Set(runColumns.map((column) => column.name))
|
||||
const jobsNeedRebuild =
|
||||
!jobColumnNames.has('server_id') ||
|
||||
!jobColumnNames.has('directory') ||
|
||||
jobColumns.find((column) => column.name === 'repo_id')?.notnull !== 0
|
||||
const runsNeedRebuild =
|
||||
!runColumnNames.has('server_id') ||
|
||||
runColumns.find((column) => column.name === 'repo_id')?.notnull !== 0
|
||||
|
||||
if (!jobsNeedRebuild && !runsNeedRebuild) {
|
||||
return
|
||||
}
|
||||
|
||||
const jobsLegacy = `schedule_jobs${LEGACY_SUFFIX}`
|
||||
const runsLegacy = `schedule_runs${LEGACY_SUFFIX}`
|
||||
|
||||
db.run(`DROP TABLE IF EXISTS ${runsLegacy}`)
|
||||
db.run(`DROP TABLE IF EXISTS ${jobsLegacy}`)
|
||||
|
||||
db.run(`ALTER TABLE schedule_jobs RENAME TO ${jobsLegacy}`)
|
||||
db.run(`ALTER TABLE schedule_runs RENAME TO ${runsLegacy}`)
|
||||
|
||||
createJobsTable(db, 'schedule_jobs')
|
||||
createRunsTable(db, 'schedule_runs')
|
||||
|
||||
const jobServerColumn = jobColumnNames.has('server_id') ? 'server_id' : "'local'"
|
||||
const jobDirectoryColumn = jobColumnNames.has('directory') ? 'directory' : 'NULL'
|
||||
const jobOptionalColumns = ['permission_config', 'mcp_servers', 'branch', 'workspace_mode']
|
||||
.map((column) => (jobColumnNames.has(column) ? column : 'NULL'))
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs (
|
||||
id, repo_id, server_id, directory, name, description, enabled, interval_minutes, schedule_mode,
|
||||
cron_expression, timezone, agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers,
|
||||
branch, workspace_mode, created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id, repo_id, ${jobServerColumn}, ${jobDirectoryColumn}, name, description, enabled, interval_minutes,
|
||||
COALESCE(schedule_mode, 'interval'), cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
${jobOptionalColumns[0]}, ${jobOptionalColumns[1]}, ${jobOptionalColumns[2]},
|
||||
COALESCE(${jobOptionalColumns[3]}, 'worktree'), created_at, updated_at, last_run_at, next_run_at
|
||||
FROM ${jobsLegacy}
|
||||
`)
|
||||
|
||||
const runServerColumn = runColumnNames.has('server_id') ? 'server_id' : "'local'"
|
||||
const runOptionalColumns = ['viewed_at', 'run_branch', 'commit_hash', 'worktree_path']
|
||||
.map((column) => (runColumnNames.has(column) ? column : 'NULL'))
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_runs (
|
||||
id, job_id, repo_id, server_id, trigger_source, status, started_at, finished_at, viewed_at,
|
||||
created_at, session_id, session_title, log_text, response_text, error_text, run_branch,
|
||||
commit_hash, worktree_path
|
||||
)
|
||||
SELECT
|
||||
id, job_id, repo_id, ${runServerColumn}, trigger_source, status, started_at, finished_at,
|
||||
${runOptionalColumns[0]}, created_at, session_id, session_title, log_text, response_text, error_text,
|
||||
${runOptionalColumns[1]}, ${runOptionalColumns[2]}, ${runOptionalColumns[3]}
|
||||
FROM ${runsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`DROP TABLE ${runsLegacy}`)
|
||||
db.run(`DROP TABLE ${jobsLegacy}`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_server ON schedule_jobs(server_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_session ON schedule_runs(session_id, started_at DESC)')
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_schedule_runs_unread
|
||||
ON schedule_runs(finished_at DESC)
|
||||
WHERE viewed_at IS NULL
|
||||
`)
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DELETE FROM schedule_runs WHERE repo_id IS NULL')
|
||||
db.run('DELETE FROM schedule_jobs WHERE repo_id IS NULL')
|
||||
|
||||
const jobsLegacy = `schedule_jobs${LEGACY_SUFFIX}`
|
||||
const runsLegacy = `schedule_runs${LEGACY_SUFFIX}`
|
||||
|
||||
db.run(`DROP TABLE IF EXISTS ${runsLegacy}`)
|
||||
db.run(`DROP TABLE IF EXISTS ${jobsLegacy}`)
|
||||
|
||||
db.run(`ALTER TABLE schedule_jobs RENAME TO ${jobsLegacy}`)
|
||||
db.run(`ALTER TABLE schedule_runs RENAME TO ${runsLegacy}`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE schedule_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||
cron_expression TEXT,
|
||||
timezone TEXT,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
permission_config TEXT,
|
||||
mcp_servers TEXT,
|
||||
branch TEXT,
|
||||
workspace_mode TEXT NOT NULL DEFAULT 'worktree',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE schedule_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
trigger_source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER,
|
||||
viewed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
session_id TEXT,
|
||||
session_title TEXT,
|
||||
log_text TEXT,
|
||||
response_text TEXT,
|
||||
error_text TEXT,
|
||||
run_branch TEXT,
|
||||
commit_hash TEXT,
|
||||
worktree_path TEXT
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs (
|
||||
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||
agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers, branch, workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||
agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers, branch, workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
FROM ${jobsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_runs (
|
||||
id, job_id, repo_id, trigger_source, status, started_at, finished_at, viewed_at, created_at,
|
||||
session_id, session_title, log_text, response_text, error_text, run_branch, commit_hash, worktree_path
|
||||
)
|
||||
SELECT
|
||||
id, job_id, repo_id, trigger_source, status, started_at, finished_at, viewed_at, created_at,
|
||||
session_id, session_title, log_text, response_text, error_text, run_branch, commit_hash, worktree_path
|
||||
FROM ${runsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`DROP TABLE ${runsLegacy}`)
|
||||
db.run(`DROP TABLE ${jobsLegacy}`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_session ON schedule_runs(session_id, started_at DESC)')
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_schedule_runs_unread
|
||||
ON schedule_runs(finished_at DESC)
|
||||
WHERE viewed_at IS NULL
|
||||
`)
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -34,6 +34,9 @@ import migration202610141200 from './202610141200-session-sandbox-modes'
|
||||
import migration202610151200 from './202610151200-change-walkthrough-sessions'
|
||||
import migration202610161200 from './202610161200-change-walkthrough-execution'
|
||||
import migration202610181200 from './202610181200-opencode-servers'
|
||||
import migration202610181300 from './202610181300-session-server-scope'
|
||||
import migration202610181310 from './202610181310-multi-run-targets'
|
||||
import migration202610181320 from './202610181320-remote-schedule-targets'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -71,4 +74,7 @@ export const allMigrations: Migration[] = [
|
||||
migration202610151200,
|
||||
migration202610161200,
|
||||
migration202610181200,
|
||||
migration202610181300,
|
||||
migration202610181310,
|
||||
migration202610181320,
|
||||
]
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type MultiRunEntryStatus,
|
||||
type MultiRunFusionSource,
|
||||
type MultiRunFusionStatus,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MultiRunEntryRecord {
|
||||
@@ -37,7 +38,9 @@ export interface MultiRunFusionRecord {
|
||||
|
||||
export interface MultiRunRecord {
|
||||
id: number
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: boolean
|
||||
@@ -48,7 +51,9 @@ export interface MultiRunRecord {
|
||||
}
|
||||
|
||||
export interface CreateMultiRunGroup {
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: boolean
|
||||
@@ -81,7 +86,9 @@ export interface MultiRunFusionPatch {
|
||||
|
||||
interface MultiRunRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: number
|
||||
@@ -118,7 +125,7 @@ interface MultiRunFusionRow {
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, name, prompt, isolated, base_ref, created_at'
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, server_id, directory, 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'
|
||||
|
||||
@@ -129,7 +136,9 @@ export function ensureMultiRunTables(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS multi_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL,
|
||||
repo_id INTEGER,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
@@ -158,6 +167,10 @@ export function ensureMultiRunTables(db: Database): void {
|
||||
CREATE INDEX IF NOT EXISTS idx_multi_runs_repo
|
||||
ON multi_runs(repo_id, created_at DESC)
|
||||
`)
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_multi_runs_server
|
||||
ON multi_runs(server_id, directory, created_at DESC)
|
||||
`)
|
||||
}
|
||||
|
||||
export function ensureMultiRunFusionTable(db: Database): void {
|
||||
@@ -194,8 +207,20 @@ export function createMultiRunWithEntries(
|
||||
const now = Date.now()
|
||||
const create = db.transaction(() => {
|
||||
const result = db
|
||||
.prepare(`INSERT INTO multi_runs(repo_id, name, prompt, isolated, base_ref, created_at) VALUES(?,?,?,?,?,?)`)
|
||||
.run(group.repoId, group.name, group.prompt, group.isolated ? 1 : 0, group.baseRef, now)
|
||||
.prepare(
|
||||
`INSERT INTO multi_runs(repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)`,
|
||||
)
|
||||
.run(
|
||||
group.repoId,
|
||||
group.serverId,
|
||||
group.directory,
|
||||
group.name,
|
||||
group.prompt,
|
||||
group.isolated ? 1 : 0,
|
||||
group.baseRef,
|
||||
now,
|
||||
)
|
||||
const multiRunId = Number(result.lastInsertRowid)
|
||||
|
||||
const insertEntry = db.prepare(`
|
||||
@@ -226,15 +251,20 @@ export function getMultiRun(db: Database, id: number): MultiRunRecord | null {
|
||||
return toMultiRunRecord(row, loadEntries(db, row.id), loadFusions(db, row.id))
|
||||
}
|
||||
|
||||
export function listMultiRuns(db: Database, repoId: number, limit: number): MultiRunRecord[] {
|
||||
export function listMultiRuns(db: Database, target: MultiRunTarget, limit: number): MultiRunRecord[] {
|
||||
const [where, params] =
|
||||
target.kind === 'repo'
|
||||
? ['repo_id = ?', [target.repoId] as const]
|
||||
: ['server_id = ? AND directory = ?', [target.serverId, target.directory] as const]
|
||||
|
||||
const rows = db
|
||||
.prepare(`
|
||||
SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs
|
||||
WHERE repo_id = ?
|
||||
WHERE ${where}
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
.all(repoId, limit) as MultiRunRow[]
|
||||
.all(...params, limit) as MultiRunRow[]
|
||||
if (rows.length === 0) {
|
||||
return []
|
||||
}
|
||||
@@ -445,6 +475,8 @@ function toMultiRunRecord(
|
||||
return {
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id,
|
||||
directory: row.directory,
|
||||
name: row.name,
|
||||
prompt: row.prompt,
|
||||
isolated: row.isolated === 1,
|
||||
|
||||
+92
-52
@@ -1,5 +1,6 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
ScheduleJobSchema,
|
||||
ScheduleMcpServersSchema,
|
||||
SchedulePermissionConfigSchema,
|
||||
@@ -20,7 +21,9 @@ import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||
|
||||
interface ScheduleJobRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
description: string | null
|
||||
enabled: number
|
||||
@@ -45,7 +48,8 @@ interface ScheduleJobRow {
|
||||
interface ScheduleRunRow {
|
||||
id: number
|
||||
job_id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
trigger_source: string
|
||||
status: string
|
||||
started_at: number
|
||||
@@ -112,6 +116,8 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
return ScheduleJobSchema.parse({
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id ?? 'local',
|
||||
directory: row.directory ?? null,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
enabled: Boolean(row.enabled),
|
||||
@@ -139,6 +145,7 @@ function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
|
||||
id: row.id,
|
||||
jobId: row.job_id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id ?? 'local',
|
||||
triggerSource: row.trigger_source,
|
||||
status: row.status,
|
||||
startedAt: row.started_at,
|
||||
@@ -177,13 +184,19 @@ function serializeMcpServers(mcpServers: ScheduleJobPersistenceInput['mcpServers
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobsByServer(db: Database, serverId: string): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE server_id = ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(serverId) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobIdsByRepo(db: Database, repoId: number): number[] {
|
||||
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as Array<{ id: number }>
|
||||
return rows.map((row) => row.id)
|
||||
}
|
||||
@@ -194,28 +207,35 @@ export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function getScheduleJobById(db: Database, repoId: number, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
export function getScheduleJobById(db: Database, repoId: number | null, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
|
||||
return row ? rowToScheduleJob(row) : null
|
||||
}
|
||||
|
||||
export function createScheduleJob(db: Database, repoId: number, input: ScheduleJobPersistenceInput): ScheduleJob {
|
||||
export function createScheduleJob(
|
||||
db: Database,
|
||||
repoId: number | null,
|
||||
input: ScheduleJobPersistenceInput,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): ScheduleJob {
|
||||
const now = Date.now()
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_jobs (
|
||||
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
repo_id, server_id, directory, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
permission_config,
|
||||
mcp_servers,
|
||||
branch,
|
||||
workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
repoId,
|
||||
serverId,
|
||||
input.directory ?? null,
|
||||
input.name,
|
||||
input.description ?? null,
|
||||
input.enabled ? 1 : 0,
|
||||
@@ -244,7 +264,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
return job
|
||||
}
|
||||
|
||||
export function updateScheduleJob(db: Database, repoId: number, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||
export function updateScheduleJob(db: Database, repoId: number | null, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||
const existing = getScheduleJobById(db, repoId, jobId)
|
||||
if (!existing) {
|
||||
return null
|
||||
@@ -255,8 +275,8 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_jobs
|
||||
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?,
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id = ? AND id = ?
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, directory = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id IS ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -275,6 +295,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
input.directory ?? null,
|
||||
now,
|
||||
input.nextRunAt,
|
||||
repoId,
|
||||
@@ -284,9 +305,9 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
return getScheduleJobById(db, repoId, jobId)
|
||||
}
|
||||
|
||||
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?').run(repoId, jobId)
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
export function deleteScheduleJob(db: Database, repoId: number | null, jobId: number): boolean {
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ?').run(repoId, jobId)
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
const result = stmt.run(repoId, jobId)
|
||||
return result.changes > 0
|
||||
}
|
||||
@@ -298,9 +319,9 @@ export interface ScheduleRunArtifact {
|
||||
worktreePath: string | null
|
||||
}
|
||||
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobId: number): ScheduleRunArtifact[] {
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number | null, jobId: number): ScheduleRunArtifact[] {
|
||||
const rows = db
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id IS ? AND job_id = ? ORDER BY id DESC')
|
||||
.all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null }[]
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
@@ -317,28 +338,28 @@ export interface ScheduleJobWorktreeOwner {
|
||||
}
|
||||
|
||||
export function listScheduleJobWorktreeOwners(db: Database): ScheduleJobWorktreeOwner[] {
|
||||
const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs').all() as Array<{ id: number; repo_id: number; name: string }>
|
||||
const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs WHERE repo_id IS NOT NULL').all() as Array<{ id: number; repo_id: number; name: string }>
|
||||
return rows.map((row) => ({ id: row.id, repoId: row.repo_id, name: row.name }))
|
||||
}
|
||||
|
||||
export function clearScheduleRunWorktreePath(db: Database, repoId: number, jobId: number, worktreePath: string): number {
|
||||
export function clearScheduleRunWorktreePath(db: Database, repoId: number | null, jobId: number, worktreePath: string): number {
|
||||
return db
|
||||
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id = ? AND job_id = ? AND worktree_path = ?')
|
||||
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id IS ? AND job_id = ? AND worktree_path = ?')
|
||||
.run(repoId, jobId, worktreePath).changes
|
||||
}
|
||||
|
||||
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
|
||||
export function deleteScheduleRunById(db: Database, repoId: number | null, jobId: number, runId: number): boolean {
|
||||
const result = db
|
||||
.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
.prepare('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
.run(repoId, jobId, runId)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function deleteScheduleRunsByIds(db: Database, repoId: number, jobId: number, runIds: number[]): number {
|
||||
export function deleteScheduleRunsByIds(db: Database, repoId: number | null, jobId: number, runIds: number[]): number {
|
||||
if (runIds.length === 0) return 0
|
||||
const placeholders = runIds.map(() => '?').join(', ')
|
||||
const result = db
|
||||
.prepare(`DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id IN (${placeholders})`)
|
||||
.prepare(`DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id IN (${placeholders})`)
|
||||
.run(repoId, jobId, ...runIds)
|
||||
return result.changes
|
||||
}
|
||||
@@ -346,22 +367,22 @@ export function deleteScheduleRunsByIds(db: Database, repoId: number, jobId: num
|
||||
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
|
||||
const runStmt = db.prepare(`
|
||||
DELETE FROM schedule_runs
|
||||
WHERE (repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
|
||||
WHERE (repo_id IS NOT NULL AND repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
|
||||
OR job_id NOT IN (SELECT id FROM schedule_jobs)
|
||||
`)
|
||||
const orphanedRuns = runStmt.run(ASSISTANT_REPO_ID).changes
|
||||
|
||||
const jobStmt = db.prepare(`
|
||||
DELETE FROM schedule_jobs
|
||||
WHERE repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
|
||||
WHERE repo_id IS NOT NULL AND repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
|
||||
`)
|
||||
const orphanedJobs = jobStmt.run(ASSISTANT_REPO_ID).changes
|
||||
|
||||
return { orphanedJobs, orphanedRuns }
|
||||
}
|
||||
|
||||
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
export function updateScheduleJobRunState(db: Database, repoId: number | null, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id IS ? AND id = ?')
|
||||
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
|
||||
}
|
||||
|
||||
@@ -374,7 +395,8 @@ export function createScheduleRun(
|
||||
db: Database,
|
||||
input: {
|
||||
jobId: number
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId?: string
|
||||
triggerSource: ScheduleRunTriggerSource
|
||||
status: ScheduleRunStatus
|
||||
startedAt: number
|
||||
@@ -382,13 +404,14 @@ export function createScheduleRun(
|
||||
},
|
||||
): ScheduleRun {
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO schedule_runs (job_id, repo_id, server_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
input.jobId,
|
||||
input.repoId,
|
||||
input.serverId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
input.triggerSource,
|
||||
input.status,
|
||||
input.startedAt,
|
||||
@@ -404,7 +427,7 @@ export function createScheduleRun(
|
||||
|
||||
export function updateScheduleRun(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
@@ -420,7 +443,7 @@ export function updateScheduleRun(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET status = ?, finished_at = ?, session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -441,7 +464,7 @@ export function updateScheduleRun(
|
||||
|
||||
export function updateScheduleRunMetadata(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
@@ -460,7 +483,7 @@ export function updateScheduleRunMetadata(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -479,7 +502,7 @@ export function updateScheduleRunMetadata(
|
||||
|
||||
export function updateScheduleRunWorktree(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null },
|
||||
@@ -492,7 +515,7 @@ export function updateScheduleRunWorktree(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET worktree_path = ?, run_branch = ?, commit_hash = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -507,8 +530,8 @@ export function updateScheduleRunWorktree(
|
||||
return getScheduleRunById(db, repoId, jobId, runId)
|
||||
}
|
||||
|
||||
export function getScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
export function getScheduleRunById(db: Database, repoId: number | null, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
@@ -519,10 +542,10 @@ export function getScheduleRunBySessionId(db: Database, sessionId: string): Sche
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number | null, jobId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ? AND status = 'running'
|
||||
WHERE repo_id IS ? AND job_id = ? AND status = 'running'
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
@@ -541,12 +564,13 @@ export function listRunningScheduleRuns(db: Database, limit: number = 100): Sche
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number | null, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
id,
|
||||
job_id,
|
||||
repo_id,
|
||||
server_id,
|
||||
trigger_source,
|
||||
status,
|
||||
started_at,
|
||||
@@ -562,7 +586,7 @@ export function listScheduleRunsByJob(db: Database, repoId: number, jobId: numbe
|
||||
commit_hash,
|
||||
worktree_path
|
||||
FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ?
|
||||
WHERE repo_id IS ? AND job_id = ?
|
||||
ORDER BY started_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
@@ -583,6 +607,7 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
|
||||
repoName: string
|
||||
repoPath: string
|
||||
repoUrl: string
|
||||
serverName: string | null
|
||||
lastRun: ScheduleRunSummary | null
|
||||
}
|
||||
|
||||
@@ -591,6 +616,7 @@ interface ScheduleJobWithRepoRow extends ScheduleJobRow {
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_source_path: string | null
|
||||
server_name: string | null
|
||||
last_run_id: number | null
|
||||
last_run_status: string | null
|
||||
last_run_started_at: number | null
|
||||
@@ -601,14 +627,19 @@ interface ScheduleJobWithRepoRow extends ScheduleJobRow {
|
||||
}
|
||||
|
||||
interface RepoDisplayRow {
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_url?: string | null
|
||||
repo_source_path?: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
|
||||
function resolveRepoDisplay(row: RepoDisplayRow): { repoName: string; repoPath: string } {
|
||||
if (row.repo_id === null) {
|
||||
return { repoName: row.server_name ?? 'Linked server', repoPath: row.directory ?? '' }
|
||||
}
|
||||
if (row.repo_id === ASSISTANT_REPO_ID) {
|
||||
return { repoName: ASSISTANT_REPO_NAME, repoPath: ASSISTANT_REPO_PATH }
|
||||
}
|
||||
@@ -641,6 +672,7 @@ function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithR
|
||||
...rowToScheduleJob(row),
|
||||
...resolveRepoDisplay(row),
|
||||
repoUrl: row.repo_url ?? '',
|
||||
serverName: row.server_name ?? null,
|
||||
lastRun: buildLastRunSummary(row),
|
||||
}
|
||||
}
|
||||
@@ -649,6 +681,7 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sj.*, r.repo_url, r.local_path as repo_path, r.name as repo_name, r.source_path as repo_source_path,
|
||||
os.name AS server_name,
|
||||
sr.id AS last_run_id,
|
||||
sr.status AS last_run_status,
|
||||
sr.started_at AS last_run_started_at,
|
||||
@@ -658,10 +691,11 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
|
||||
substr(sr.response_text, 1, 600) AS last_run_response_head
|
||||
FROM schedule_jobs sj
|
||||
LEFT JOIN repos r ON sj.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
LEFT JOIN schedule_runs sr ON sr.id = (
|
||||
SELECT id FROM schedule_runs WHERE job_id = sj.id ORDER BY started_at DESC LIMIT 1
|
||||
)
|
||||
ORDER BY COALESCE(r.local_path, ''), sj.name
|
||||
ORDER BY COALESCE(r.local_path, sj.directory, ''), sj.name
|
||||
`)
|
||||
const rows = stmt.all() as ScheduleJobWithRepoRow[]
|
||||
return rows.map(rowToScheduleJobWithRepo)
|
||||
@@ -671,6 +705,7 @@ export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
jobName: string
|
||||
repoName: string
|
||||
repoPath: string
|
||||
serverName: string | null
|
||||
}
|
||||
|
||||
interface ScheduleRunWithContextRow extends ScheduleRunRow {
|
||||
@@ -679,12 +714,15 @@ interface ScheduleRunWithContextRow extends ScheduleRunRow {
|
||||
repo_name: string | null
|
||||
repo_url: string | null
|
||||
repo_source_path: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
|
||||
function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext {
|
||||
return {
|
||||
...rowToScheduleRun(row),
|
||||
jobName: row.job_name,
|
||||
serverName: row.server_name ?? null,
|
||||
...resolveRepoDisplay(row),
|
||||
}
|
||||
}
|
||||
@@ -732,7 +770,7 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
const searchTerm = search?.trim()
|
||||
if (searchTerm) {
|
||||
const pattern = `%${escapeLikePattern(searchTerm)}%`
|
||||
const searchColumns = ['sj.name', 'sr.session_title', 'sr.error_text', 'sr.run_branch', 'r.name', 'r.local_path']
|
||||
const searchColumns = ['sj.name', 'sr.session_title', 'sr.error_text', 'sr.run_branch', 'r.name', 'r.local_path', 'sj.directory', 'os.name']
|
||||
conditions.push(`(${searchColumns.map((column) => `${column} LIKE ? ESCAPE '\\'`).join(' OR ')})`)
|
||||
params.push(...searchColumns.map(() => pattern))
|
||||
}
|
||||
@@ -741,17 +779,18 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.trigger_source, sr.status,
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
sr.session_id, sr.session_title,
|
||||
NULL AS log_text, NULL AS response_text, sr.error_text,
|
||||
sr.viewed_at,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path,
|
||||
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path
|
||||
sj.name AS job_name, sj.directory AS directory, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path, os.name AS server_name
|
||||
FROM schedule_runs sr
|
||||
JOIN schedule_jobs sj ON sr.job_id = sj.id
|
||||
LEFT JOIN repos r ON sr.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
${whereClause}
|
||||
ORDER BY sr.started_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
@@ -810,17 +849,18 @@ interface UnreadScheduleRunRow extends ScheduleRunWithContextRow {
|
||||
export function listUnreadScheduleRuns(db: Database, limit: number = 20): ScheduleRunWithUnreadPreview[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.trigger_source, sr.status,
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
sr.session_id, sr.session_title, sr.viewed_at,
|
||||
NULL AS log_text, NULL AS response_text, sr.error_text,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path,
|
||||
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path,
|
||||
sj.name AS job_name, sj.directory AS directory, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path, os.name AS server_name,
|
||||
substr(sr.response_text, 1, 600) AS response_head
|
||||
FROM schedule_runs sr
|
||||
JOIN schedule_jobs sj ON sr.job_id = sj.id
|
||||
LEFT JOIN repos r ON sr.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
WHERE sr.status IN ('completed', 'failed') AND sr.viewed_at IS NULL
|
||||
ORDER BY (sr.status = 'failed') DESC, sr.finished_at DESC
|
||||
LIMIT ?
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type {
|
||||
SessionGoalStatus,
|
||||
SessionGoalStopReason,
|
||||
SessionGoalTurnState,
|
||||
SessionGoalVerdict,
|
||||
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
|
||||
@@ -29,6 +31,7 @@ export interface SessionGoalRecord {
|
||||
|
||||
export interface InsertSessionGoalInput {
|
||||
sessionId: string
|
||||
serverId?: string
|
||||
directory: string
|
||||
objective: string
|
||||
maxContinuations: number
|
||||
@@ -51,6 +54,7 @@ export interface SessionGoalPatch {
|
||||
interface SessionGoalRow {
|
||||
id: number
|
||||
session_id: string
|
||||
server_id: string
|
||||
directory: string
|
||||
objective: string
|
||||
status: SessionGoalStatus
|
||||
@@ -70,7 +74,7 @@ interface SessionGoalRow {
|
||||
}
|
||||
|
||||
const SESSION_GOAL_COLUMNS = `
|
||||
id, session_id, directory, objective, status, stop_reason, turn_state,
|
||||
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
|
||||
`
|
||||
@@ -80,6 +84,7 @@ export function ensureSessionGoalsTable(db: Database): void {
|
||||
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')),
|
||||
@@ -100,7 +105,7 @@ export function ensureSessionGoalsTable(db: Database): void {
|
||||
`)
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
|
||||
ON session_goals(session_id)
|
||||
ON session_goals(server_id, session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
db.run(`
|
||||
@@ -114,12 +119,13 @@ export function insertSessionGoal(db: Database, input: InsertSessionGoalInput):
|
||||
try {
|
||||
const result = db.prepare(`
|
||||
INSERT INTO session_goals(
|
||||
session_id, directory, objective, status, stop_reason, turn_state,
|
||||
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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
`).run(
|
||||
input.sessionId,
|
||||
input.serverId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
input.directory,
|
||||
input.objective,
|
||||
'active',
|
||||
@@ -153,10 +159,19 @@ export function getSessionGoalById(db: Database, id: number): SessionGoalRecord
|
||||
return row ? mapSessionGoalRow(row) : null
|
||||
}
|
||||
|
||||
export function getLatestSessionGoal(db: Database, sessionId: string): SessionGoalRecord | 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 session_id = ? ORDER BY created_at DESC, id DESC LIMIT 1`)
|
||||
.get(sessionId) as SessionGoalRow | undefined
|
||||
.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
|
||||
}
|
||||
|
||||
@@ -228,6 +243,7 @@ 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,
|
||||
|
||||
@@ -1,38 +1,60 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export function ensureSessionPermissionModesTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS session_permission_modes (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
export function getSessionPermissionMode(db: Database, sessionId: string): SessionPermissionMode | null {
|
||||
export function getSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): SessionPermissionMode | null {
|
||||
const row = db
|
||||
.prepare('SELECT mode FROM session_permission_modes WHERE session_id = ?')
|
||||
.get(sessionId) as { mode: SessionPermissionMode } | undefined
|
||||
.prepare('SELECT mode FROM session_permission_modes WHERE server_id = ? AND session_id = ?')
|
||||
.get(serverId, sessionId) as { mode: SessionPermissionMode } | undefined
|
||||
return row ? row.mode : null
|
||||
}
|
||||
|
||||
export function setSessionPermissionMode(db: Database, sessionId: string, mode: SessionPermissionMode): void {
|
||||
export function setSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare(`
|
||||
INSERT INTO session_permission_modes(session_id, mode, updated_at)
|
||||
VALUES(?,?,?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET mode=excluded.mode, updated_at=excluded.updated_at
|
||||
`).run(sessionId, mode, Date.now())
|
||||
INSERT INTO session_permission_modes(server_id, session_id, mode, updated_at)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
server_id=excluded.server_id,
|
||||
mode=excluded.mode,
|
||||
updated_at=excluded.updated_at
|
||||
`).run(serverId, sessionId, mode, Date.now())
|
||||
}
|
||||
|
||||
export function insertSessionPermissionModeIfAbsent(db: Database, sessionId: string, mode: SessionPermissionMode): void {
|
||||
export function insertSessionPermissionModeIfAbsent(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare(`
|
||||
INSERT OR IGNORE INTO session_permission_modes(session_id, mode, updated_at)
|
||||
VALUES(?,?,?)
|
||||
`).run(sessionId, mode, Date.now())
|
||||
INSERT OR IGNORE INTO session_permission_modes(server_id, session_id, mode, updated_at)
|
||||
VALUES(?,?,?,?)
|
||||
`).run(serverId, sessionId, mode, Date.now())
|
||||
}
|
||||
|
||||
export function deleteSessionPermissionMode(db: Database, sessionId: string): void {
|
||||
db.prepare('DELETE FROM session_permission_modes WHERE session_id = ?').run(sessionId)
|
||||
export function deleteSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare('DELETE FROM session_permission_modes WHERE server_id = ? AND session_id = ?').run(serverId, sessionId)
|
||||
}
|
||||
+48
-27
@@ -15,7 +15,7 @@ import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createFilesystemRoutes } from './routes/filesystem'
|
||||
import { createScheduleRoutes } from './routes/schedules'
|
||||
import { createScheduleRoutes, createServerScheduleRoutes } from './routes/schedules'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
@@ -53,6 +53,10 @@ import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { createOpenCodeServerProxyRoutes } from './routes/opencode-server-proxy'
|
||||
import { createOpenCodeServerRoutes } from './routes/opencode-servers'
|
||||
import {
|
||||
createOpenCodeServerTerminalRoutes,
|
||||
createOpenCodeServerTerminalSocketRoutes,
|
||||
} from './routes/opencode-server-terminals'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { RemoteServerEventHub } from './services/remote-server-events'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
|
||||
@@ -93,7 +97,7 @@ import {
|
||||
getTrustedOrigins,
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
|
||||
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
@@ -250,14 +254,25 @@ try {
|
||||
}
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
openCodeClient,
|
||||
{
|
||||
client: openCodeClient,
|
||||
baseUrl: () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
includeLocalCredentials: true,
|
||||
},
|
||||
new CredentialProvider(db),
|
||||
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
)
|
||||
const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
const connection = opencodeServerRegistry.getConnection(serverId)
|
||||
return terminalService.forTarget({
|
||||
client: opencodeServerRegistry.getClient(serverId),
|
||||
baseUrl: () => connection.baseUrl,
|
||||
includeLocalCredentials: false,
|
||||
})
|
||||
}
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry)
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
try {
|
||||
await terminalService.removeAll(directory)
|
||||
@@ -268,37 +283,31 @@ scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db)
|
||||
const notificationService = new NotificationService(db, opencodeServerRegistry)
|
||||
const sessionSettingsService = new SettingsService(db)
|
||||
const sessionAncestry = new SessionAncestry(openCodeClient)
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, sessionSettingsService, sessionAncestry)
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry)
|
||||
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => new SandboxRuntimeService(db).removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSettingsService, {
|
||||
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) =>
|
||||
(await sessionPermissionModeService.getEffectiveMode(sessionId)).lockedReason,
|
||||
resolveSessionLock: async (sessionId, serverId) =>
|
||||
(await sessionPermissionModeService.getEffectiveMode(sessionId, serverId)).lockedReason,
|
||||
})
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session permission mode event handling error:', err)
|
||||
})
|
||||
sessionSandboxService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session sandbox event handling error:', err)
|
||||
})
|
||||
sessionGoalService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session goal event handling error:', err)
|
||||
})
|
||||
try {
|
||||
changeWalkthroughService.handleEvent(event)
|
||||
} catch (err) {
|
||||
@@ -306,12 +315,21 @@ sseAggregator.onEvent((directory, event) => {
|
||||
}
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
if (event.type !== 'permission.asked' || !sessionId) return false
|
||||
return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto'
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
notificationService.addEventSuppressor((event, sessionId, serverId) =>
|
||||
sessionPermissionModeService.suppressesPermissionNotification(event, sessionId, serverId),
|
||||
)
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId, serverId) => {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return false
|
||||
if (!sessionId) return false
|
||||
if (event.type !== NotificationEventType.SESSION_IDLE && event.type !== NotificationEventType.SESSION_FAILED) return false
|
||||
return getChangeWalkthroughByWalkthroughSession(db, sessionId) !== null
|
||||
@@ -329,8 +347,8 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
privateKey: ENV.VAPID.PRIVATE_KEY,
|
||||
subject: ENV.VAPID.SUBJECT || 'mailto:push@localhost',
|
||||
})
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event).catch((err) => {
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Push notification dispatch error:', err)
|
||||
})
|
||||
})
|
||||
@@ -338,9 +356,9 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
|
||||
sseAggregator.setPendingActionsFetcher(openCodeClient)
|
||||
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
sseAggregator.onUpstreamConnected(() => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions().catch((err) => {
|
||||
logger.error('Failed to accept pending permission requests for active sessions:', err)
|
||||
sseAggregator.onServerConnected((serverId) => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
|
||||
})
|
||||
})
|
||||
sseAggregator.start()
|
||||
@@ -387,6 +405,9 @@ protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerRoutes(opencodeServerRegistry, () => remoteServerEvents.getStatuses()))
|
||||
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
|
||||
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
|
||||
|
||||
@@ -47,7 +47,7 @@ export function createInternalRoutes(
|
||||
const app = new Hono()
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
app.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
app.route('/session-goals', createSessionGoalRoutes(sessionGoals))
|
||||
app.route('/session-goals', createSessionGoalRoutes(sessionGoals, { serverScoped: false }))
|
||||
app.route('/multi-runs', createMultiRunRoutes(multiRuns))
|
||||
app.route('/notifications', createInternalNotificationRoutes(notificationService))
|
||||
app.route('/settings', createInternalSettingsRoutes(settingsService))
|
||||
|
||||
@@ -131,7 +131,7 @@ export function createInternalSessionRoutes(
|
||||
permissionModes.pinAsk(launched.sessionId)
|
||||
|
||||
const url = buildSessionPath(
|
||||
launched.repoId,
|
||||
input.repoId,
|
||||
launched.sessionId,
|
||||
launched.workspaceDirectory ? { repoTab: 'workspaces' } : undefined,
|
||||
)
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
import { Hono } from 'hono'
|
||||
import { FuseMultiRunRequestSchema, LaunchMultiRunRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
FuseMultiRunRequestSchema,
|
||||
LaunchMultiRunRequestSchema,
|
||||
type MultiRunTarget,
|
||||
} 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'
|
||||
|
||||
function listTarget(repoId: string | undefined, serverId: string | undefined, directory: string | undefined): MultiRunTarget {
|
||||
if (serverId) {
|
||||
if (!directory) {
|
||||
throw new MultiRunError('Missing directory', 400)
|
||||
}
|
||||
return { kind: 'server', serverId, directory }
|
||||
}
|
||||
|
||||
return { kind: 'repo', repoId: parseId(repoId, 'repoId', MultiRunError) }
|
||||
}
|
||||
|
||||
export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.query('repoId'), 'repoId', MultiRunError)
|
||||
return c.json({ runs: service.list(repoId) })
|
||||
const target = listTarget(c.req.query('repoId'), c.req.query('serverId'), c.req.query('directory'))
|
||||
return c.json({ runs: service.list(target) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list multi-runs', ServiceError)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import type { UpgradeWebSocket } from 'hono/ws'
|
||||
import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
CreateTerminalRequestSchema,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
ResizeTerminalRequestSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeServerError } from '../services/opencode-server-registry'
|
||||
import { TerminalNotFoundError, type TerminalService } from '../services/terminal'
|
||||
import { parseTerminalCursor } from '../utils/terminal-cursor'
|
||||
import { createBridgedSocketEvents, isAllowedUpgradeOrigin } from '../utils/websocket-bridge'
|
||||
import { handleOpenCodeError, handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
export type ServerTerminalServiceResolver = (serverId: string) => TerminalService
|
||||
|
||||
interface ServerTerminalSocketVariables {
|
||||
terminalService: TerminalService
|
||||
terminalDirectory: string
|
||||
terminalCursor: number | undefined
|
||||
}
|
||||
|
||||
function isAbsoluteDirectory(directory: string): boolean {
|
||||
return directory.startsWith('/') || /^[A-Za-z]:[\\/]/.test(directory)
|
||||
}
|
||||
|
||||
function readAbsoluteDirectory(raw: string | undefined): string | null {
|
||||
if (raw === undefined) return null
|
||||
const directory = raw.trim()
|
||||
return directory.length > 0 && isAbsoluteDirectory(directory) ? directory : null
|
||||
}
|
||||
|
||||
function rejectLocalServer(c: Context, serverId: string): Response | null {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return null
|
||||
return c.json({ error: 'Local terminals are served by the repo terminal routes' }, 400)
|
||||
}
|
||||
|
||||
function rejectDirectory(c: Context): Response {
|
||||
return c.json({ error: 'An absolute directory is required' }, 400)
|
||||
}
|
||||
|
||||
function handleTerminalError(c: Context, error: unknown) {
|
||||
if (error instanceof TerminalNotFoundError) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
if (error instanceof OpenCodeServerError) {
|
||||
return handleServiceError(c, error, 'Terminal request failed', OpenCodeServerError)
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Terminal request failed')
|
||||
}
|
||||
|
||||
export function createOpenCodeServerTerminalRoutes(resolveTerminalService: ServerTerminalServiceResolver) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:serverId/terminals', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
const terminals = await resolveTerminalService(serverId).list(directory)
|
||||
return c.json({ terminals })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:serverId/terminals', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const parsed = await parseJsonBody(c, CreateTerminalRequestSchema, { allowEmpty: true })
|
||||
if (!parsed.ok) return parsed.response
|
||||
|
||||
const directory = readAbsoluteDirectory(parsed.data.directory)
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
const terminal = await resolveTerminalService(serverId).create(directory, {
|
||||
kind: 'shell',
|
||||
name: parsed.data.title ?? 'Terminal',
|
||||
})
|
||||
return c.json(terminal)
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/:serverId/terminals/:ptyID', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const parsed = await parseJsonBody(c, ResizeTerminalRequestSchema)
|
||||
if (!parsed.ok) return parsed.response
|
||||
|
||||
const directory = readAbsoluteDirectory(parsed.data.directory)
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
try {
|
||||
const terminalService = resolveTerminalService(serverId)
|
||||
await terminalService.requireTerminal(directory, ptyID)
|
||||
await terminalService.resize(directory, ptyID, { cols: parsed.data.cols, rows: parsed.data.rows })
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:serverId/terminals/:ptyID', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
try {
|
||||
const terminalService = resolveTerminalService(serverId)
|
||||
await terminalService.requireTerminal(directory, ptyID)
|
||||
await terminalService.remove(directory, ptyID)
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
export function createOpenCodeServerTerminalSocketRoutes(
|
||||
resolveTerminalService: ServerTerminalServiceResolver,
|
||||
upgradeWebSocket: UpgradeWebSocket,
|
||||
trustedOrigins: readonly string[] = getTrustedOrigins(),
|
||||
) {
|
||||
const app = new Hono<{ Variables: ServerTerminalSocketVariables }>()
|
||||
|
||||
const validate: MiddlewareHandler<{ Variables: ServerTerminalSocketVariables }> = async (c, next) => {
|
||||
if (!isAllowedUpgradeOrigin(c.req.header('origin'), trustedOrigins)) {
|
||||
return c.json({ error: 'Origin not allowed' }, 403)
|
||||
}
|
||||
|
||||
const serverId = c.req.param('serverId') ?? ''
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const cursor = parseTerminalCursor(c.req.query('cursor'))
|
||||
if (cursor === null) {
|
||||
return c.json({ error: 'Invalid cursor' }, 400)
|
||||
}
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
c.set('terminalService', resolveTerminalService(serverId))
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
|
||||
c.set('terminalDirectory', directory)
|
||||
c.set('terminalCursor', cursor)
|
||||
await next()
|
||||
}
|
||||
|
||||
app.get(
|
||||
'/:serverId/terminals/:ptyID/connect',
|
||||
validate,
|
||||
upgradeWebSocket((c) => {
|
||||
const terminalService = c.get('terminalService')
|
||||
const directory = c.get('terminalDirectory')
|
||||
const cursor = c.get('terminalCursor')
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
return createBridgedSocketEvents((peer) => terminalService.connect(directory, ptyID, cursor, peer))
|
||||
}),
|
||||
)
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import { createBridgedSocketEvents, isAllowedUpgradeOrigin } from '../utils/websocket-bridge'
|
||||
import { parseTerminalCursor } from '../utils/terminal-cursor'
|
||||
import { resolveRepoRequestDirectory } from './repo-directory'
|
||||
|
||||
interface RepoTerminalSocketVariables {
|
||||
@@ -14,14 +15,6 @@ interface RepoTerminalSocketVariables {
|
||||
terminalCursor: number | undefined
|
||||
}
|
||||
|
||||
function parseCursor(raw: string | undefined): number | undefined | null {
|
||||
if (raw === undefined) return undefined
|
||||
if (!/^-?\d+$/.test(raw)) return null
|
||||
const parsed = Number(raw)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < -1) return null
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function createRepoTerminalSocketRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -38,7 +31,7 @@ export function createRepoTerminalSocketRoutes(
|
||||
return c.json({ error: 'Origin not allowed' }, 403)
|
||||
}
|
||||
|
||||
const cursor = parseCursor(c.req.query('cursor'))
|
||||
const cursor = parseTerminalCursor(c.req.query('cursor'))
|
||||
if (cursor === null) {
|
||||
return c.json({ error: 'Invalid cursor' }, 400)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,13 @@ import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types'
|
||||
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
import { parseId, handleServiceError } from '../utils/route-helpers'
|
||||
|
||||
function parseServerId(value: string | undefined): string {
|
||||
if (!value) {
|
||||
throw new ScheduleServiceError('OpenCode server id is required', 400)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function parseRunListLimit(value: string | undefined): number {
|
||||
if (value === undefined) {
|
||||
return 20
|
||||
@@ -270,4 +277,133 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
|
||||
return app
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule routes for a project directory on a linked OpenCode server. They mirror the
|
||||
* repo routes without worktree endpoints, because remote runs execute in place.
|
||||
*/
|
||||
export function createServerScheduleRoutes(scheduleService: ScheduleService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
return c.json({ jobs: scheduleService.listServerJobs(parseServerId(c.req.param('serverId'))) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list schedules', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const serverId = parseServerId(c.req.param('serverId'))
|
||||
const body = await c.req.json()
|
||||
const input = CreateScheduleJobRequestSchema.parse(body)
|
||||
if (!input.directory) {
|
||||
throw new ScheduleServiceError('A remote schedule requires an absolute target directory', 400)
|
||||
}
|
||||
const job = await scheduleService.createServerJob(serverId, input.directory, input)
|
||||
return c.json({ job }, 201)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to create schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const job = scheduleService.getServerJob(parseServerId(c.req.param('serverId')), jobId)
|
||||
if (!job) {
|
||||
return c.json({ error: 'Schedule not found' }, 404)
|
||||
}
|
||||
return c.json({ job })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to get schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/:jobId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const body = await c.req.json()
|
||||
const input = UpdateScheduleJobRequestSchema.parse(body)
|
||||
const job = await scheduleService.updateServerJob(parseServerId(c.req.param('serverId')), jobId, input)
|
||||
return c.json({ job })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to update schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
await scheduleService.deleteServerJob(parseServerId(c.req.param('serverId')), jobId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/run', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const run = await scheduleService.runServerJob(parseServerId(c.req.param('serverId')), jobId, 'manual')
|
||||
return c.json({ run })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to run schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/runs', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const limit = parseRunListLimit(c.req.query('limit'))
|
||||
return c.json({ runs: scheduleService.listServerRuns(parseServerId(c.req.param('serverId')), jobId, limit) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list schedule runs', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/runs/:runId', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
return c.json({ run: scheduleService.getServerRun(parseServerId(c.req.param('serverId')), jobId, runId) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to get schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/runs/:runId/cancel', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
const run = await scheduleService.cancelServerRun(parseServerId(c.req.param('serverId')), jobId, runId)
|
||||
return c.json({ run })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to cancel schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId/runs', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
return c.json(await scheduleService.clearServerRunHistory(parseServerId(c.req.param('serverId')), jobId))
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to clear schedule run history', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId/runs/:runId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
await scheduleService.deleteServerRun(parseServerId(c.req.param('serverId')), jobId, runId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,15 @@ import { StartSessionGoalRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { SessionGoalError, type SessionGoalService } from '../services/session-goals'
|
||||
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
export interface SessionGoalRouteOptions {
|
||||
serverScoped?: boolean
|
||||
}
|
||||
|
||||
export function createSessionGoalRoutes(
|
||||
service: SessionGoalService,
|
||||
options: SessionGoalRouteOptions = {},
|
||||
) {
|
||||
const serverScoped = options.serverScoped ?? true
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
@@ -12,7 +20,8 @@ export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
if (!sessionId) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
return c.json({ goal: service.getLatest(sessionId) })
|
||||
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)
|
||||
}
|
||||
@@ -25,7 +34,7 @@ export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
}
|
||||
|
||||
try {
|
||||
const goal = await service.start(parsed.data)
|
||||
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)
|
||||
|
||||
@@ -8,7 +8,10 @@ export function createSessionPermissionModeRoutes(service: SessionPermissionMode
|
||||
|
||||
app.get('/:sessionId', async (c) => {
|
||||
try {
|
||||
const state = await service.getEffectiveMode(c.req.param('sessionId'))
|
||||
const state = await service.getEffectiveMode(
|
||||
c.req.param('sessionId'),
|
||||
c.req.query('serverId') || undefined,
|
||||
)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read session permission mode', SessionPermissionModeError)
|
||||
@@ -22,7 +25,12 @@ export function createSessionPermissionModeRoutes(service: SessionPermissionMode
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await service.setMode(c.req.param('sessionId'), parsed.data.mode, parsed.data.directory)
|
||||
const state = await service.setMode(
|
||||
c.req.param('sessionId'),
|
||||
parsed.data.mode,
|
||||
parsed.data.directory,
|
||||
parsed.data.serverId,
|
||||
)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to set session permission mode', SessionPermissionModeError)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import { stream } from 'hono/streaming'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import { SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
|
||||
import { logger } from '../utils/logger'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import { createQueuedSSEWriter } from './sse-writer'
|
||||
@@ -92,7 +92,12 @@ export function createSSERoutes() {
|
||||
if (!result.success) {
|
||||
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
|
||||
}
|
||||
const success = sseAggregator.setClientVisibility(result.data.clientId, result.data.visible, result.data.activeSessionId ?? null)
|
||||
const success = sseAggregator.setClientVisibility(
|
||||
result.data.clientId,
|
||||
result.data.visible,
|
||||
result.data.activeSessionId ?? null,
|
||||
result.data.activeServerId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
)
|
||||
if (!success) {
|
||||
return c.json({ success: false, error: 'Client not found' }, 404)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'node:fs'
|
||||
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MultiRun,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
createMultiRunWithEntries,
|
||||
@@ -16,7 +22,6 @@ import {
|
||||
type MultiRunRecord,
|
||||
} from '../db/multi-runs'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { Repo } from '../types/repo'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
@@ -24,7 +29,15 @@ import { buildFusionPrompt, buildFusionSourcePermissionRuleset, collectFusionSou
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { RepoWorkspaceError } from './repo'
|
||||
import type { RepoWorkspaceService } from './repo-workspace'
|
||||
import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher'
|
||||
import {
|
||||
resolveSessionTarget,
|
||||
SessionLauncher,
|
||||
SessionLaunchError,
|
||||
sessionTargetInput,
|
||||
sessionTargetOfRun,
|
||||
type LaunchedSession,
|
||||
type ResolvedSessionTarget,
|
||||
} from './session-launcher'
|
||||
import type { SessionPermissionModeService } from './session-permission-modes'
|
||||
|
||||
const MULTI_RUN_LIST_LIMIT = 20
|
||||
@@ -35,6 +48,8 @@ function toMultiRun(record: MultiRunRecord): MultiRun {
|
||||
return {
|
||||
id: record.id,
|
||||
repoId: record.repoId,
|
||||
serverId: record.serverId,
|
||||
directory: record.directory,
|
||||
name: record.name,
|
||||
prompt: record.prompt,
|
||||
isolated: record.isolated,
|
||||
@@ -69,6 +84,22 @@ function toMultiRun(record: MultiRunRecord): MultiRun {
|
||||
}
|
||||
}
|
||||
|
||||
function multiRunTargetFromRequest(
|
||||
request: Pick<LaunchMultiRunRequest, 'repoId' | 'serverId' | 'directory'>,
|
||||
): MultiRunTarget {
|
||||
if (request.serverId !== undefined) {
|
||||
if (request.directory === undefined) {
|
||||
throw new MultiRunError('A server multi-run needs a directory', 400)
|
||||
}
|
||||
return { kind: 'server', serverId: request.serverId, directory: request.directory }
|
||||
}
|
||||
|
||||
if (request.repoId === undefined) {
|
||||
throw new MultiRunError('A multi-run needs a repository or server target', 400)
|
||||
}
|
||||
return { kind: 'repo', repoId: request.repoId }
|
||||
}
|
||||
|
||||
export class MultiRunService {
|
||||
private readonly sessionLauncher: SessionLauncher
|
||||
private readonly discardingEntries = new Set<number>()
|
||||
@@ -78,22 +109,21 @@ export class MultiRunService {
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly repoWorkspaces: RepoWorkspaceService,
|
||||
private readonly permissionModes: SessionPermissionModeService,
|
||||
private readonly getServerClient?: (serverId: string) => OpenCodeClient,
|
||||
) {
|
||||
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces)
|
||||
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces, getServerClient)
|
||||
}
|
||||
|
||||
async launch(request: LaunchMultiRunRequest): Promise<MultiRun> {
|
||||
let repo: Repo
|
||||
try {
|
||||
repo = requireReadyRepo(this.db, request.repoId)
|
||||
} catch (error) {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
|
||||
}
|
||||
const target = multiRunTargetFromRequest(request)
|
||||
const resolved = await this.resolveTarget(target)
|
||||
|
||||
const record = createMultiRunWithEntries(
|
||||
this.db,
|
||||
{
|
||||
repoId: request.repoId,
|
||||
repoId: target.kind === 'repo' ? target.repoId : null,
|
||||
serverId: target.kind === 'server' ? target.serverId : LOCAL_OPENCODE_SERVER_ID,
|
||||
directory: target.kind === 'server' ? target.directory : null,
|
||||
name: request.name,
|
||||
prompt: request.prompt,
|
||||
isolated: request.isolate,
|
||||
@@ -105,7 +135,7 @@ export class MultiRunService {
|
||||
const validations = await Promise.all(
|
||||
record.entries.map(async (entry) => {
|
||||
try {
|
||||
await this.sessionLauncher.resolveModel(repo, entry.model)
|
||||
await resolved.resolveModel(entry.model)
|
||||
return { entry, ok: true as const }
|
||||
} catch (error) {
|
||||
return { entry, ok: false as const, error }
|
||||
@@ -127,7 +157,7 @@ export class MultiRunService {
|
||||
})
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
launchable.map(({ entry, index }) => this.launchEntry(entry, index, request)),
|
||||
launchable.map(({ entry, index }) => this.launchEntry(entry, index, request, target)),
|
||||
)
|
||||
|
||||
results.forEach((result, resultIndex) => {
|
||||
@@ -174,12 +204,11 @@ export class MultiRunService {
|
||||
})
|
||||
}
|
||||
|
||||
let repo: Repo
|
||||
try {
|
||||
repo = requireReadyRepo(this.db, record.repoId)
|
||||
} catch (error) {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
|
||||
const target = sessionTargetOfRun(record)
|
||||
if (!target) {
|
||||
throw new MultiRunError('Multi-run target is no longer available', 409)
|
||||
}
|
||||
const resolved = await this.resolveTarget(target)
|
||||
|
||||
const entriesById = new Map(record.entries.map((entry) => [entry.id, entry]))
|
||||
const selectedEntries = request.entryIds.map((entryId) => {
|
||||
@@ -197,7 +226,7 @@ export class MultiRunService {
|
||||
)
|
||||
|
||||
try {
|
||||
await this.sessionLauncher.resolveModel(repo, request.model)
|
||||
await resolved.resolveModel(request.model)
|
||||
} catch (error) {
|
||||
if (error instanceof SessionLaunchError) {
|
||||
throw new MultiRunError(error.message, error.status)
|
||||
@@ -205,9 +234,9 @@ export class MultiRunService {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to resolve model', 502)
|
||||
}
|
||||
|
||||
await this.reconcileUncertainFusions(record)
|
||||
await this.reconcileUncertainFusions(record, resolved.client)
|
||||
|
||||
const collection = await collectFusionSources(this.openCodeClient, selectedEntries)
|
||||
const collection = await collectFusionSources(resolved.client, selectedEntries)
|
||||
if (collection.unavailable.length > 0) {
|
||||
throw new MultiRunError('Some selected results are not ready to fuse', 409, {
|
||||
code: 'FUSION_SOURCES_UNAVAILABLE',
|
||||
@@ -239,7 +268,7 @@ export class MultiRunService {
|
||||
let launched: LaunchedSession | null = null
|
||||
try {
|
||||
launched = await this.sessionLauncher.launch({
|
||||
repoId: record.repoId,
|
||||
...sessionTargetInput(target),
|
||||
prompt: built.prompt,
|
||||
model: request.model,
|
||||
title: `${record.name} · fusion`,
|
||||
@@ -269,7 +298,11 @@ export class MultiRunService {
|
||||
|
||||
if (launched) {
|
||||
try {
|
||||
await this.permissionModes.applyDefaultMode(launched.sessionId, launched.directory)
|
||||
await this.permissionModes.applyDefaultMode(
|
||||
launched.sessionId,
|
||||
launched.directory,
|
||||
target.kind === 'server' ? target.serverId : LOCAL_OPENCODE_SERVER_ID,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to apply the default permission mode to fusion session ${launched.sessionId}:`, error)
|
||||
}
|
||||
@@ -278,8 +311,8 @@ export class MultiRunService {
|
||||
return { run: this.reload(multiRunId), created: true }
|
||||
}
|
||||
|
||||
list(repoId: number): MultiRun[] {
|
||||
return listMultiRuns(this.db, repoId, MULTI_RUN_LIST_LIMIT).map(toMultiRun)
|
||||
list(target: MultiRunTarget): MultiRun[] {
|
||||
return listMultiRuns(this.db, target, MULTI_RUN_LIST_LIMIT).map(toMultiRun)
|
||||
}
|
||||
|
||||
async discard(multiRunId: number, entryId: number): Promise<MultiRun> {
|
||||
@@ -303,18 +336,8 @@ export class MultiRunService {
|
||||
this.discardingEntries.add(entryId)
|
||||
|
||||
try {
|
||||
if (entry.isolated && entry.directory && existsSync(entry.directory)) {
|
||||
const repo = getRepoById(this.db, record.repoId)
|
||||
if (!repo) {
|
||||
throw new MultiRunError('Repository not found', 404)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.repoWorkspaces.remove(repo, entry.directory)
|
||||
} catch (error) {
|
||||
const status = error instanceof RepoWorkspaceError ? error.status : 502
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status)
|
||||
}
|
||||
if (entry.isolated && entry.directory) {
|
||||
await this.removeEntryWorkspace(record, entry.directory)
|
||||
}
|
||||
|
||||
const updated = updateMultiRunEntry(this.db, entryId, ['started', 'failed'], { status: 'discarded' })
|
||||
@@ -328,13 +351,69 @@ export class MultiRunService {
|
||||
}
|
||||
}
|
||||
|
||||
private async removeEntryWorkspace(record: MultiRunRecord, directory: string): Promise<void> {
|
||||
const target = sessionTargetOfRun(record)
|
||||
if (!target) {
|
||||
throw new MultiRunError('Multi-run target is no longer available', 409)
|
||||
}
|
||||
|
||||
if (target.kind === 'repo') {
|
||||
if (!existsSync(directory)) {
|
||||
return
|
||||
}
|
||||
|
||||
const repo = getRepoById(this.db, target.repoId)
|
||||
if (!repo) {
|
||||
throw new MultiRunError('Repository not found', 404)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.repoWorkspaces.remove(repo, directory)
|
||||
} catch (error) {
|
||||
const status = error instanceof RepoWorkspaceError ? error.status : 502
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const resolved = await this.resolveTarget(target)
|
||||
await resolved.removeWorkspace(directory)
|
||||
} catch (error) {
|
||||
if (error instanceof MultiRunError) {
|
||||
throw error
|
||||
}
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', 502)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveTarget(target: MultiRunTarget): Promise<ResolvedSessionTarget> {
|
||||
try {
|
||||
return await resolveSessionTarget(
|
||||
{
|
||||
db: this.db,
|
||||
openCodeClient: this.openCodeClient,
|
||||
repoWorkspaces: this.repoWorkspaces,
|
||||
...(this.getServerClient ? { getServerClient: this.getServerClient } : {}),
|
||||
},
|
||||
target,
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof SessionLaunchError || error instanceof ServiceError) {
|
||||
throw new MultiRunError(error.message, error.status)
|
||||
}
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Multi-run target is unavailable', 502)
|
||||
}
|
||||
}
|
||||
|
||||
private async launchEntry(
|
||||
entry: MultiRunEntryRecord,
|
||||
index: number,
|
||||
request: LaunchMultiRunRequest,
|
||||
target: MultiRunTarget,
|
||||
): Promise<LaunchedSession> {
|
||||
return this.sessionLauncher.launch({
|
||||
repoId: request.repoId,
|
||||
...sessionTargetInput(target),
|
||||
prompt: request.prompt,
|
||||
model: entry.model,
|
||||
title: `${request.name} · ${entry.model}`,
|
||||
@@ -345,7 +424,7 @@ export class MultiRunService {
|
||||
})
|
||||
}
|
||||
|
||||
private async reconcileUncertainFusions(record: MultiRunRecord): Promise<void> {
|
||||
private async reconcileUncertainFusions(record: MultiRunRecord, client: OpenCodeClient): Promise<void> {
|
||||
const uncertain = record.fusions.filter(
|
||||
(fusion): fusion is MultiRunFusionRecord & { sessionId: string } =>
|
||||
fusion.status === 'failed' && fusion.sessionId !== null,
|
||||
@@ -358,7 +437,7 @@ export class MultiRunService {
|
||||
await Promise.all(
|
||||
uncertain.map(async (fusion) => {
|
||||
try {
|
||||
const response = await this.openCodeClient.api.message.list({
|
||||
const response = await client.api.message.list({
|
||||
sessionID: fusion.sessionId,
|
||||
type: 'user',
|
||||
order: 'asc',
|
||||
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
import {
|
||||
NotificationEventType,
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type OpenCodeServer,
|
||||
type SessionGoal,
|
||||
} from "@opencode-manager/shared/schemas";
|
||||
import {
|
||||
@@ -23,10 +25,14 @@ import { sseAggregator, type SSEEvent } from "./sse-aggregator";
|
||||
import { getRepoName } from "../db/queries";
|
||||
import { getScheduleRunBySessionId } from "../db/schedules";
|
||||
import type { Repo } from "../types/repo";
|
||||
import { buildSessionPath } from "@opencode-manager/shared/utils";
|
||||
import { buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils";
|
||||
import { sessionIDFromEvent } from "@opencode-manager/shared/opencode";
|
||||
import { resolveRepoForDirectory } from "./repo";
|
||||
|
||||
export interface NotificationServerRegistry {
|
||||
get(serverId: string): Pick<OpenCodeServer, "name" | "enabled"> | null;
|
||||
}
|
||||
|
||||
interface VapidConfig {
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
@@ -123,6 +129,8 @@ export function buildEventNotificationPayload(
|
||||
context: {
|
||||
repoName?: string;
|
||||
repoId?: number;
|
||||
serverId?: string;
|
||||
serverName?: string;
|
||||
sessionId?: string;
|
||||
directory?: string;
|
||||
url: string;
|
||||
@@ -134,8 +142,9 @@ export function buildEventNotificationPayload(
|
||||
const title = config.titleFn(event.data);
|
||||
|
||||
const detail = config.bodyFn(event.data);
|
||||
const rawBody = context.repoName
|
||||
? `${context.repoName} · ${detail}`
|
||||
const displayName = context.repoName ?? context.serverName;
|
||||
const rawBody = displayName
|
||||
? `${displayName} · ${detail}`
|
||||
: detail;
|
||||
const body = truncateWithEllipsis(rawBody, MAX_BODY_LENGTH);
|
||||
|
||||
@@ -151,19 +160,28 @@ export function buildEventNotificationPayload(
|
||||
directory: context.directory,
|
||||
repoId: context.repoId,
|
||||
repoName: context.repoName,
|
||||
serverId: context.serverId,
|
||||
serverName: context.serverName,
|
||||
url: context.url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type EventSuppressor = (event: SSEEvent, sessionId: string | undefined) => Promise<boolean>;
|
||||
type EventSuppressor = (
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
serverId: string
|
||||
) => Promise<boolean>;
|
||||
|
||||
export class NotificationService {
|
||||
private vapidConfig: VapidConfig | null = null;
|
||||
private settingsService: SettingsService;
|
||||
private eventSuppressors: EventSuppressor[] = [];
|
||||
|
||||
constructor(private db: Database) {
|
||||
constructor(
|
||||
private db: Database,
|
||||
private serverRegistry: NotificationServerRegistry | null = null
|
||||
) {
|
||||
this.settingsService = new SettingsService(db);
|
||||
this.initializePushSubscriptionsTable();
|
||||
}
|
||||
@@ -335,17 +353,29 @@ export class NotificationService {
|
||||
|
||||
async handleSSEEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID
|
||||
): Promise<void> {
|
||||
const config = EVENT_CONFIG[event.type];
|
||||
if (!config) return;
|
||||
|
||||
const sessionId = resolveEventSessionId(event);
|
||||
if (sessionId && sseAggregator.isSessionBeingViewed(sessionId)) return;
|
||||
if (sessionId && sseAggregator.isSubagentSession(sessionId)) return;
|
||||
if (sessionId && sseAggregator.isSessionBeingViewed(sessionId, serverId)) return;
|
||||
if (sessionId && sseAggregator.isSubagentSession(sessionId, serverId)) return;
|
||||
|
||||
for (const suppressor of this.eventSuppressors) {
|
||||
if (await suppressor(event, sessionId)) return;
|
||||
if (await suppressor(event, sessionId, serverId)) return;
|
||||
}
|
||||
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) {
|
||||
await this.deliverRemoteEvent(
|
||||
serverId,
|
||||
directory,
|
||||
event,
|
||||
sessionId,
|
||||
config.preferencesKey
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = directory ? await resolveRepoForDirectory(this.db, directory) : null;
|
||||
@@ -371,19 +401,53 @@ export class NotificationService {
|
||||
);
|
||||
}
|
||||
|
||||
private async deliverRemoteEvent(
|
||||
serverId: string,
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events
|
||||
): Promise<void> {
|
||||
const server = this.serverRegistry?.get(serverId) ?? null;
|
||||
if (!server || !server.enabled) return;
|
||||
|
||||
const url = sessionId
|
||||
? buildServerSessionPath(serverId, sessionId)
|
||||
: `/servers/${encodeURIComponent(serverId)}`;
|
||||
|
||||
const payload = buildEventNotificationPayload(event, {
|
||||
serverId,
|
||||
serverName: server.name,
|
||||
sessionId,
|
||||
directory: directory ?? undefined,
|
||||
url,
|
||||
});
|
||||
if (!payload) return;
|
||||
|
||||
await this.deliverToSubscribers(
|
||||
payload,
|
||||
(preferences) =>
|
||||
preferences.enabled &&
|
||||
preferences.events[preferencesKey] === true
|
||||
);
|
||||
}
|
||||
|
||||
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)) return;
|
||||
if (sseAggregator.isSessionBeingViewed(goal.sessionId, goal.serverId)) return;
|
||||
|
||||
const repo = goal.directory
|
||||
const isRemote = goal.serverId !== LOCAL_OPENCODE_SERVER_ID;
|
||||
const repo = !isRemote && goal.directory
|
||||
? await resolveRepoForDirectory(this.db, goal.directory)
|
||||
: null;
|
||||
const server = isRemote ? this.serverRegistry?.get(goal.serverId) ?? null : null;
|
||||
const repoName = repo ? getRepoName(repo) : undefined;
|
||||
const displayName = repoName ?? server?.name;
|
||||
|
||||
const payload: PushNotificationPayload = {
|
||||
title: getGoalOutcomeTitle(goal.status),
|
||||
body: buildGoalOutcomeBody(goal, repoName),
|
||||
body: buildGoalOutcomeBody(goal, displayName),
|
||||
tag: `session-goal-${goal.id}`,
|
||||
timestamp: Date.now(),
|
||||
renotify: true,
|
||||
@@ -393,7 +457,11 @@ export class NotificationService {
|
||||
directory: goal.directory,
|
||||
repoId: repo?.id,
|
||||
repoName,
|
||||
url: buildNotificationUrl(repo, goal.sessionId),
|
||||
serverId: goal.serverId,
|
||||
serverName: server?.name,
|
||||
url: isRemote
|
||||
? buildServerSessionPath(goal.serverId, goal.sessionId)
|
||||
: buildNotificationUrl(repo, goal.sessionId),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ export interface RemoteEventAggregator {
|
||||
sendRemoteResync(serverId: string, data: string): void
|
||||
hasClientDirectory(clientId: string, key: string): boolean
|
||||
setRemoteReplayHandler(handler: RemoteReplayHandler | null): void
|
||||
notifyServerEvent(serverId: string, directory: string | null, event: V2Event): void
|
||||
notifyServerConnected(serverId: string): void
|
||||
setRemoteSubagentResolver(resolver: ((serverId: string, sessionId: string) => boolean) | null): void
|
||||
}
|
||||
|
||||
export interface RemoteEventSource {
|
||||
@@ -51,6 +54,7 @@ interface RemoteServerStream {
|
||||
version: string | null
|
||||
versionRequested: boolean
|
||||
sessionDirectories: Map<string, string>
|
||||
subagentSessions: Set<string>
|
||||
}
|
||||
|
||||
type RemoteReplayEventType = 'permission.asked' | 'form.created'
|
||||
@@ -94,6 +98,7 @@ export class RemoteServerEventHub {
|
||||
this.started = true
|
||||
this.aggregator.setRemoteReplayHandler((clientId, serverId, directory) =>
|
||||
this.replayPendingActions(clientId, serverId, directory))
|
||||
this.aggregator.setRemoteSubagentResolver((serverId, sessionId) => this.isSubagentSession(serverId, sessionId))
|
||||
this.unsubscribeRegistry = this.registry.onChange(change => this.handleRegistryChange(change))
|
||||
this.connectAll()
|
||||
}
|
||||
@@ -108,6 +113,11 @@ export class RemoteServerEventHub {
|
||||
this.forgetStream(serverId)
|
||||
}
|
||||
this.aggregator.setRemoteReplayHandler(null)
|
||||
this.aggregator.setRemoteSubagentResolver(null)
|
||||
}
|
||||
|
||||
isSubagentSession(serverId: string, sessionId: string): boolean {
|
||||
return this.streams.get(serverId)?.subagentSessions.has(sessionId) ?? false
|
||||
}
|
||||
|
||||
getStatuses(): OpenCodeServerStatus[] {
|
||||
@@ -254,6 +264,7 @@ export class RemoteServerEventHub {
|
||||
stream.error = null
|
||||
stream.reconnectDelay = this.reconnectDelayMs
|
||||
logger.info(`Remote event stream connected: ${serverId}`)
|
||||
this.aggregator.notifyServerConnected(serverId)
|
||||
this.aggregator.sendRemoteResync(serverId, JSON.stringify({ timestamp: Date.now() }))
|
||||
void this.refreshVersion(serverId)
|
||||
}
|
||||
@@ -308,10 +319,16 @@ export class RemoteServerEventHub {
|
||||
|
||||
if (sessionID && event.type === 'session.deleted') {
|
||||
stream.sessionDirectories.delete(sessionID)
|
||||
stream.subagentSessions.delete(sessionID)
|
||||
} else if (sessionID && rememberedDirectory) {
|
||||
stream.sessionDirectories.set(sessionID, rememberedDirectory)
|
||||
}
|
||||
|
||||
if (event.type === 'session.created' && event.data.parentID) {
|
||||
stream.subagentSessions.add(event.data.sessionID)
|
||||
}
|
||||
|
||||
this.aggregator.notifyServerEvent(serverId, resolvedDirectory ?? null, event)
|
||||
this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, payloadJson)
|
||||
} catch (error) {
|
||||
logger.error(`Remote event stream failed to handle ${event.type} for ${serverId}:`, error)
|
||||
@@ -374,6 +391,7 @@ export class RemoteServerEventHub {
|
||||
version: null,
|
||||
versionRequested: false,
|
||||
sessionDirectories: new Map(),
|
||||
subagentSessions: new Set(),
|
||||
}
|
||||
this.streams.set(serverId, stream)
|
||||
return stream
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface ScheduleJobPersistenceInput {
|
||||
mcpServers: ScheduleMcpServer[]
|
||||
branch: string | null
|
||||
workspaceMode: ScheduleWorkspaceMode
|
||||
directory?: string | null
|
||||
nextRunAt: number | null
|
||||
}
|
||||
|
||||
@@ -104,6 +105,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
|
||||
skillMetadata: input.skillMetadata,
|
||||
branch: input.branch?.trim() || null,
|
||||
workspaceMode: input.workspaceMode ?? 'worktree',
|
||||
...(input.directory !== undefined ? { directory: input.directory?.trim() || null } : {}),
|
||||
}
|
||||
|
||||
const scheduleConfig = input.scheduleMode === 'cron'
|
||||
@@ -166,6 +168,9 @@ export function buildUpdatedSchedulePersistenceInput(
|
||||
mcpServers: input.mcpServers ?? existing.mcpServers,
|
||||
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
|
||||
workspaceMode: input.workspaceMode ?? existing.workspaceMode,
|
||||
...(input.directory !== undefined || existing.directory !== undefined
|
||||
? { directory: input.directory === undefined ? (existing.directory ?? null) : (input.directory?.trim() || null) }
|
||||
: {}),
|
||||
nextRunAt,
|
||||
}
|
||||
}
|
||||
+400
-119
File diff suppressed because it is too large.
Load diff
@@ -1,25 +1,42 @@
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
const MAX_PARENT_HOPS = 10
|
||||
|
||||
export type SessionClientResolver = (serverId: string) => OpenCodeClient
|
||||
|
||||
function sessionKey(serverId: string, sessionId: string): string {
|
||||
return `${serverId}:${sessionId}`
|
||||
}
|
||||
|
||||
export class SessionAncestry {
|
||||
private readonly parentBySession = new Map<string, string | null>()
|
||||
private readonly resolveClient: SessionClientResolver
|
||||
|
||||
constructor(private readonly openCodeClient: OpenCodeClient) {}
|
||||
|
||||
rememberParent(sessionId: string, parentId: string | null | undefined): void {
|
||||
this.parentBySession.set(sessionId, parentId ?? null)
|
||||
constructor(clientOrResolver: OpenCodeClient | SessionClientResolver) {
|
||||
this.resolveClient = typeof clientOrResolver === 'function' ? clientOrResolver : () => clientOrResolver
|
||||
}
|
||||
|
||||
forget(sessionId: string): void {
|
||||
this.parentBySession.delete(sessionId)
|
||||
rememberParent(
|
||||
sessionId: string,
|
||||
parentId: string | null | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
this.parentBySession.set(sessionKey(serverId, sessionId), parentId ?? null)
|
||||
}
|
||||
|
||||
async resolveRootSessionId(sessionId: string): Promise<string> {
|
||||
forget(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): void {
|
||||
this.parentBySession.delete(sessionKey(serverId, sessionId))
|
||||
}
|
||||
|
||||
async resolveRootSessionId(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<string> {
|
||||
let current = sessionId
|
||||
|
||||
for (let hops = 0; hops < MAX_PARENT_HOPS; hops += 1) {
|
||||
const parentId = await this.getParentId(current)
|
||||
const parentId = await this.getParentId(current, serverId)
|
||||
if (!parentId) {
|
||||
return current
|
||||
}
|
||||
@@ -29,14 +46,15 @@ export class SessionAncestry {
|
||||
return current
|
||||
}
|
||||
|
||||
private async getParentId(sessionId: string): Promise<string | null> {
|
||||
if (this.parentBySession.has(sessionId)) {
|
||||
return this.parentBySession.get(sessionId) ?? null
|
||||
private async getParentId(sessionId: string, serverId: string): Promise<string | null> {
|
||||
const key = sessionKey(serverId, sessionId)
|
||||
if (this.parentBySession.has(key)) {
|
||||
return this.parentBySession.get(key) ?? null
|
||||
}
|
||||
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
const session = await this.resolveClient(serverId).api.session.get({ sessionID: sessionId })
|
||||
const parentId = session.parentID ?? null
|
||||
this.parentBySession.set(sessionId, parentId)
|
||||
this.parentBySession.set(key, parentId)
|
||||
return parentId
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
DEFAULT_SESSION_DEFAULTS,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type SessionGoal,
|
||||
type SessionGoalStatus,
|
||||
type SessionGoalStopReason,
|
||||
@@ -43,10 +44,17 @@ 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) => Promise<SessionLockReason | null>
|
||||
resolveSessionLock?: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
|
||||
}
|
||||
|
||||
export class SessionGoalError extends Error {
|
||||
@@ -62,10 +70,29 @@ export function sessionTokenTotal(tokens: { input: number; output: number; reaso
|
||||
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,
|
||||
@@ -91,16 +118,18 @@ export class SessionGoalService {
|
||||
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) => Promise<SessionLockReason | null>
|
||||
private readonly resolveSessionLock: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
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)
|
||||
@@ -109,7 +138,7 @@ export class SessionGoalService {
|
||||
loadOpenGoals(): void {
|
||||
this.goalBySession.clear()
|
||||
for (const record of listOpenSessionGoals(this.db)) {
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +147,9 @@ export class SessionGoalService {
|
||||
if (record.status !== 'active' || record.turnState !== 'running') {
|
||||
continue
|
||||
}
|
||||
if (!this.isServerAvailable(record.serverId)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await this.recoverRunningGoal(record)
|
||||
} catch (error) {
|
||||
@@ -127,73 +159,93 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
private async recoverRunningGoal(record: SessionGoalRecord): Promise<void> {
|
||||
const generation = this.currentAuditGeneration(record.sessionId)
|
||||
const key = goalKey(record.serverId, record.sessionId)
|
||||
const generation = this.currentAuditGeneration(key)
|
||||
const client = this.servers.getClient(record.serverId)
|
||||
try {
|
||||
await this.openCodeClient.api.session.get({ sessionID: record.sessionId })
|
||||
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(record.sessionId, record.id, generation)
|
||||
this.scheduleRecoveryRetry(key, record.id, generation)
|
||||
return
|
||||
}
|
||||
|
||||
const busy = await this.readPrerequisite(record.id, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, record.sessionId),
|
||||
isSessionBusy(client, record.sessionId),
|
||||
)
|
||||
if (!busy.ok) {
|
||||
this.scheduleRecoveryRetry(record.sessionId, record.id, generation)
|
||||
this.scheduleRecoveryRetry(key, record.id, generation)
|
||||
return
|
||||
}
|
||||
if (busy.value) {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(record.sessionId, record.id, 0)
|
||||
this.scheduleAudit(key, record.id, 0)
|
||||
}
|
||||
|
||||
private scheduleRecoveryRetry(sessionId: string, goalId: number, generation: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
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(sessionId)
|
||||
void this.retryRecovery(sessionId, goalId, generation).catch((error) => {
|
||||
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(sessionId, timer)
|
||||
this.recoveryTimers.set(key, timer)
|
||||
}
|
||||
|
||||
private async retryRecovery(sessionId: string, goalId: number, generation: number): Promise<void> {
|
||||
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.currentAuditGeneration(sessionId) !== generation) {
|
||||
if (!this.isServerAvailable(record.serverId)) {
|
||||
return
|
||||
}
|
||||
if (this.currentAuditGeneration(key) !== generation) {
|
||||
return
|
||||
}
|
||||
await this.recoverRunningGoal(record)
|
||||
}
|
||||
|
||||
private clearRecoveryTimer(sessionId: string): void {
|
||||
const timer = this.recoveryTimers.get(sessionId)
|
||||
private clearRecoveryTimer(key: string): void {
|
||||
const timer = this.recoveryTimers.get(key)
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
this.recoveryTimers.delete(sessionId)
|
||||
this.recoveryTimers.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
async start(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
await this.assertSessionCanStartGoal(input.sessionId)
|
||||
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)
|
||||
const tokensAtStart = await this.readSessionTokenTotalOrDefault(input.sessionId, serverId)
|
||||
|
||||
const record = insertSessionGoal(this.db, {
|
||||
sessionId: input.sessionId,
|
||||
serverId,
|
||||
directory: input.directory,
|
||||
objective: input.objective,
|
||||
maxContinuations,
|
||||
@@ -205,19 +257,19 @@ export class SessionGoalService {
|
||||
throw new SessionGoalError('This session already has an open goal', 409)
|
||||
}
|
||||
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
|
||||
return toSessionGoal(record)
|
||||
}
|
||||
|
||||
getLatest(sessionId: string): SessionGoal | null {
|
||||
const record = getLatestSessionGoal(this.db, sessionId)
|
||||
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): Promise<void> {
|
||||
private async assertSessionCanStartGoal(sessionId: string, serverId: string): Promise<void> {
|
||||
let lock: SessionLockReason | null
|
||||
try {
|
||||
lock = await this.resolveSessionLock(sessionId)
|
||||
lock = await this.resolveSessionLock(sessionId, serverId)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to resolve session lock for ${sessionId}:`, error)
|
||||
return
|
||||
@@ -256,41 +308,46 @@ export class SessionGoalService {
|
||||
})
|
||||
}
|
||||
|
||||
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
|
||||
async handleEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
const sessionId = sessionIDFromEvent(event)
|
||||
if (!sessionId) {
|
||||
return
|
||||
}
|
||||
|
||||
const goalId = this.goalBySession.get(sessionId)
|
||||
const key = goalKey(serverId, sessionId)
|
||||
const goalId = this.goalBySession.get(key)
|
||||
if (goalId === undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'session.execution.started':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.applyTransition(goalId, ['active'], { turnState: 'running' })
|
||||
return
|
||||
case 'session.idle':
|
||||
case 'session.execution.succeeded':
|
||||
this.scheduleAuditFromEvent(sessionId, goalId)
|
||||
this.scheduleAuditFromEvent(key, goalId)
|
||||
return
|
||||
case 'session.status':
|
||||
if (event.data.status.type === 'idle') {
|
||||
this.scheduleAuditFromEvent(sessionId, goalId)
|
||||
this.scheduleAuditFromEvent(key, goalId)
|
||||
}
|
||||
return
|
||||
case 'session.execution.failed':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'stopped', 'turn_error')
|
||||
return
|
||||
case 'session.execution.interrupted':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'paused', 'interrupted')
|
||||
return
|
||||
case 'session.deleted':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'stopped', 'session_deleted', ['active', 'paused'])
|
||||
return
|
||||
default:
|
||||
@@ -298,50 +355,51 @@ export class SessionGoalService {
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleAuditFromEvent(sessionId: string, goalId: number): void {
|
||||
private scheduleAuditFromEvent(key: string, goalId: number): void {
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
if (!record || record.status !== 'active' || record.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(sessionId, goalId, this.quietMs)
|
||||
this.scheduleAudit(key, goalId, this.quietMs)
|
||||
}
|
||||
|
||||
private async scheduleAuditWhenIdle(goal: SessionGoal): Promise<void> {
|
||||
const generation = this.currentAuditGeneration(goal.sessionId)
|
||||
const key = goalKey(goal.serverId, goal.sessionId)
|
||||
const generation = this.currentAuditGeneration(key)
|
||||
const busy = await this.readPrerequisite(goal.id, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, goal.sessionId),
|
||||
isSessionBusy(this.servers.getClient(goal.serverId), goal.sessionId),
|
||||
)
|
||||
|
||||
if (!busy.ok) {
|
||||
this.failAudit(goal.id, goal.sessionId, generation)
|
||||
this.failAudit(goal.id, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goal.id, goal.sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goal.id, key, generation)) {
|
||||
return
|
||||
}
|
||||
if (busy.value) {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(goal.sessionId, goal.id, 0)
|
||||
this.scheduleAudit(key, goal.id, 0)
|
||||
}
|
||||
|
||||
private scheduleAudit(sessionId: string, goalId: number, delay: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
this.clearAuditTimer(sessionId)
|
||||
private scheduleAudit(key: string, goalId: number, delay: number): void {
|
||||
this.clearRecoveryTimer(key)
|
||||
this.clearAuditTimer(key)
|
||||
const timer = setTimeout(() => {
|
||||
this.auditTimers.delete(sessionId)
|
||||
this.auditTimers.delete(key)
|
||||
void this.runAudit(goalId).catch((error) => {
|
||||
logger.error(`Session goal audit failed for goal ${goalId}:`, error)
|
||||
})
|
||||
}, delay)
|
||||
this.auditTimers.set(sessionId, timer)
|
||||
this.auditTimers.set(key, timer)
|
||||
}
|
||||
|
||||
private clearAuditTimer(sessionId: string): void {
|
||||
const timer = this.auditTimers.get(sessionId)
|
||||
private clearAuditTimer(key: string): void {
|
||||
const timer = this.auditTimers.get(key)
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
this.auditTimers.delete(sessionId)
|
||||
this.auditTimers.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,27 +429,29 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const sessionId = goal.sessionId
|
||||
const generation = this.currentAuditGeneration(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(this.openCodeClient, sessionId),
|
||||
isSessionBusy(client, sessionId),
|
||||
)
|
||||
if (!busy.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation) || busy.value) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation) || busy.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const total = await this.readPrerequisite(goalId, 'token read', () =>
|
||||
this.readSessionTokenTotal(sessionId),
|
||||
this.readSessionTokenTotal(sessionId, goal.serverId),
|
||||
)
|
||||
if (!total.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -407,13 +467,13 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const reply = await this.readPrerequisite(goalId, 'reply read', () =>
|
||||
readLatestAssistantReply(this.openCodeClient, sessionId),
|
||||
readLatestAssistantReply(client, sessionId),
|
||||
)
|
||||
if (!reply.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -423,7 +483,7 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const verdict = await this.evaluateAudit(updated, reply.value)
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
if (!verdict) {
|
||||
@@ -431,16 +491,17 @@ export class SessionGoalService {
|
||||
return
|
||||
}
|
||||
|
||||
await this.applyVerdict(goalId, sessionId, generation, updated, verdict)
|
||||
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 this.openCodeClient.api.generate.text(model ? { prompt, model } : { prompt })
|
||||
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)
|
||||
@@ -457,12 +518,12 @@ export class SessionGoalService {
|
||||
|
||||
private async applyVerdict(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
goal: SessionGoalRecord,
|
||||
verdict: GoalVerdict,
|
||||
): Promise<void> {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -487,11 +548,11 @@ export class SessionGoalService {
|
||||
return
|
||||
}
|
||||
|
||||
await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, patch)
|
||||
await this.continueGoal(goalId, key, generation, goal, verdict.reason, patch)
|
||||
return
|
||||
}
|
||||
|
||||
await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, {
|
||||
await this.continueGoal(goalId, key, generation, goal, verdict.reason, {
|
||||
consecutiveBlocked: 0,
|
||||
lastVerdict: 'continue',
|
||||
lastReason: verdict.reason,
|
||||
@@ -500,13 +561,13 @@ export class SessionGoalService {
|
||||
|
||||
private async continueGoal(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
goal: SessionGoalRecord,
|
||||
reason: string,
|
||||
patch: SessionGoalPatch,
|
||||
): Promise<void> {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -525,13 +586,13 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.openCodeClient.api.session.prompt({
|
||||
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, sessionId, generation, 'waiting')) {
|
||||
if (this.isAuditCurrent(goalId, key, generation, 'waiting')) {
|
||||
this.finishGoal(goalId, 'stopped', 'turn_error')
|
||||
}
|
||||
}
|
||||
@@ -555,8 +616,8 @@ export class SessionGoalService {
|
||||
}
|
||||
}
|
||||
|
||||
private failAudit(goalId: number, sessionId: string, generation: number): void {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
private failAudit(goalId: number, key: string, generation: number): void {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
this.finishGoal(goalId, 'paused', 'audit_failed')
|
||||
@@ -579,19 +640,19 @@ export class SessionGoalService {
|
||||
|
||||
private isAuditCurrent(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
turnState: SessionGoalTurnState = 'running',
|
||||
): boolean {
|
||||
if (this.currentAuditGeneration(sessionId) !== generation) {
|
||||
if (this.currentAuditGeneration(key) !== generation) {
|
||||
return false
|
||||
}
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
return Boolean(record && record.status === 'active' && record.turnState === turnState)
|
||||
}
|
||||
|
||||
private currentAuditGeneration(sessionId: string): number {
|
||||
return this.auditGeneration.get(sessionId) ?? 0
|
||||
private currentAuditGeneration(key: string): number {
|
||||
return this.auditGeneration.get(key) ?? 0
|
||||
}
|
||||
|
||||
private applyTransition(
|
||||
@@ -632,14 +693,15 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
private syncGoalIndex(record: SessionGoalRecord): void {
|
||||
const key = goalKey(record.serverId, record.sessionId)
|
||||
if (record.status === 'active' || record.status === 'paused') {
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(key, record.id)
|
||||
} else {
|
||||
this.goalBySession.delete(record.sessionId)
|
||||
this.clearAuditTimer(record.sessionId)
|
||||
this.goalBySession.delete(key)
|
||||
this.clearAuditTimer(key)
|
||||
}
|
||||
if (record.status !== 'active') {
|
||||
this.clearRecoveryTimer(record.sessionId)
|
||||
this.clearRecoveryTimer(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -647,18 +709,19 @@ export class SessionGoalService {
|
||||
if (patch.status === undefined && patch.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
this.auditGeneration.set(record.sessionId, this.currentAuditGeneration(record.sessionId) + 1)
|
||||
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): Promise<number> {
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
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): Promise<number> {
|
||||
private async readSessionTokenTotalOrDefault(sessionId: string, serverId: string): Promise<number> {
|
||||
try {
|
||||
return await this.readSessionTokenTotal(sessionId)
|
||||
return await this.readSessionTokenTotal(sessionId, serverId)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to read token usage for session ${sessionId}:`, error)
|
||||
return 0
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type MultiRunTarget } from '@opencode-manager/shared/schemas'
|
||||
import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { Repo } from '../types/repo'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { resolveOpenCodeModel, type ResolvedOpenCodeModel } from './opencode-models'
|
||||
import { resolveRepoProjectId } from './repo'
|
||||
import type { RepoWorkspaceService } from './repo-workspace'
|
||||
|
||||
type SessionCreateInput = NonNullable<Parameters<OpenCodeClient['api']['session']['create']>[0]>
|
||||
|
||||
interface LaunchSessionInput {
|
||||
repoId: number
|
||||
interface LaunchSessionCommon {
|
||||
prompt: string
|
||||
title?: string
|
||||
model?: string
|
||||
@@ -20,9 +21,12 @@ interface LaunchSessionInput {
|
||||
permissions?: SessionCreateInput['permissions']
|
||||
}
|
||||
|
||||
export type LaunchSessionInput = LaunchSessionCommon &
|
||||
({ repoId: number } | { serverId: string; directory: string })
|
||||
|
||||
export interface LaunchedSession {
|
||||
sessionId: string
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
directory: string
|
||||
workspaceDirectory: string | null
|
||||
model: string
|
||||
@@ -48,11 +52,31 @@ export class SessionLaunchError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SessionTargetDeps {
|
||||
db: Database
|
||||
openCodeClient: OpenCodeClient
|
||||
repoWorkspaces: RepoWorkspaceService
|
||||
getServerClient?: (serverId: string) => OpenCodeClient
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved place to run sessions: the local repository checkout or a directory on a linked
|
||||
* OpenCode server. Workspaces and models are resolved through the same client the sessions run on.
|
||||
*/
|
||||
export interface ResolvedSessionTarget {
|
||||
client: OpenCodeClient
|
||||
directory: string
|
||||
repo: Repo | null
|
||||
resolveModel(requestedModel?: string): Promise<ResolvedOpenCodeModel>
|
||||
createWorkspace(options?: { name?: string; ref?: string }): Promise<string>
|
||||
removeWorkspace(directory: string): Promise<void>
|
||||
}
|
||||
|
||||
function withWorkspace(message: string, workspaceDirectory: string | null): string {
|
||||
return workspaceDirectory ? `${message} (workspace: ${workspaceDirectory})` : message
|
||||
}
|
||||
|
||||
export function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
throw new SessionLaunchError('Repository not found or not ready', 404)
|
||||
@@ -60,48 +84,137 @@ export function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
return repo
|
||||
}
|
||||
|
||||
export function sessionTargetInput(
|
||||
target: MultiRunTarget,
|
||||
): { repoId: number } | { serverId: string; directory: string } {
|
||||
return target.kind === 'repo'
|
||||
? { repoId: target.repoId }
|
||||
: { serverId: target.serverId, directory: target.directory }
|
||||
}
|
||||
|
||||
export function sessionTargetOfRun(run: {
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
}): MultiRunTarget | null {
|
||||
if (run.repoId !== null) {
|
||||
return { kind: 'repo', repoId: run.repoId }
|
||||
}
|
||||
if (run.serverId === LOCAL_OPENCODE_SERVER_ID || run.directory === null) {
|
||||
return null
|
||||
}
|
||||
return { kind: 'server', serverId: run.serverId, directory: run.directory }
|
||||
}
|
||||
|
||||
async function resolveModelIn(
|
||||
client: OpenCodeClient,
|
||||
directory: string,
|
||||
requestedModel?: string,
|
||||
): Promise<ResolvedOpenCodeModel> {
|
||||
let resolved: ResolvedOpenCodeModel
|
||||
try {
|
||||
resolved = await resolveOpenCodeModel(client, directory, { preferredModel: requestedModel })
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to resolve OpenCode model', 502)
|
||||
}
|
||||
|
||||
if (requestedModel) {
|
||||
const requestedRef = parseOpenCodeModelRef(requestedModel)
|
||||
if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) {
|
||||
throw new SessionLaunchError(`Model ${requestedModel} is not available`, 400)
|
||||
}
|
||||
}
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
function repoSessionTarget(deps: SessionTargetDeps, repoId: number): ResolvedSessionTarget {
|
||||
const repo = requireReadyRepo(deps.db, repoId)
|
||||
const client = deps.openCodeClient
|
||||
|
||||
return {
|
||||
client,
|
||||
directory: repo.fullPath,
|
||||
repo,
|
||||
resolveModel: (requestedModel) => resolveModelIn(client, repo.fullPath, requestedModel),
|
||||
createWorkspace: async (options) => (await deps.repoWorkspaces.create(repo, options)).directory,
|
||||
removeWorkspace: (directory) => deps.repoWorkspaces.remove(repo, directory),
|
||||
}
|
||||
}
|
||||
|
||||
function serverSessionTarget(
|
||||
deps: SessionTargetDeps,
|
||||
serverId: string,
|
||||
directory: string,
|
||||
): ResolvedSessionTarget {
|
||||
if (!deps.getServerClient) {
|
||||
throw new SessionLaunchError('Remote OpenCode servers are not available', 400)
|
||||
}
|
||||
|
||||
const client = deps.getServerClient(serverId)
|
||||
|
||||
return {
|
||||
client,
|
||||
directory,
|
||||
repo: null,
|
||||
resolveModel: (requestedModel) => resolveModelIn(client, directory, requestedModel),
|
||||
createWorkspace: async (options) => {
|
||||
const projectID = await resolveRepoProjectId(client, directory)
|
||||
const worktree = await client.api.worktree.create({
|
||||
projectID,
|
||||
...(options?.name ? { name: options.name } : {}),
|
||||
...(options?.ref ? { branch: options.ref } : {}),
|
||||
})
|
||||
return worktree.directory
|
||||
},
|
||||
removeWorkspace: async (workspaceDirectory) => {
|
||||
const projectID = await resolveRepoProjectId(client, directory)
|
||||
await client.api.worktree.remove({ projectID, directory: workspaceDirectory, force: true })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSessionTarget(
|
||||
deps: SessionTargetDeps,
|
||||
target: MultiRunTarget,
|
||||
): Promise<ResolvedSessionTarget> {
|
||||
return target.kind === 'repo'
|
||||
? repoSessionTarget(deps, target.repoId)
|
||||
: serverSessionTarget(deps, target.serverId, target.directory)
|
||||
}
|
||||
|
||||
export class SessionLauncher {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly repoWorkspaces: RepoWorkspaceService,
|
||||
private readonly getServerClient?: (serverId: string) => OpenCodeClient,
|
||||
) {}
|
||||
|
||||
async resolveModel(repo: Repo, requestedModel?: string): Promise<ResolvedOpenCodeModel> {
|
||||
let resolved: ResolvedOpenCodeModel
|
||||
try {
|
||||
resolved = await resolveOpenCodeModel(this.openCodeClient, repo.fullPath, {
|
||||
preferredModel: requestedModel,
|
||||
})
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to resolve OpenCode model', 502)
|
||||
}
|
||||
|
||||
if (requestedModel) {
|
||||
const requestedRef = parseOpenCodeModelRef(requestedModel)
|
||||
if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) {
|
||||
throw new SessionLaunchError(`Model ${requestedModel} is not available`, 400)
|
||||
}
|
||||
}
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
async launch(input: LaunchSessionInput): Promise<LaunchedSession> {
|
||||
const repo = requireReadyRepo(this.db, input.repoId)
|
||||
const model = await this.resolveModel(repo, input.model)
|
||||
const target = await resolveSessionTarget(
|
||||
{
|
||||
db: this.db,
|
||||
openCodeClient: this.openCodeClient,
|
||||
repoWorkspaces: this.repoWorkspaces,
|
||||
...(this.getServerClient ? { getServerClient: this.getServerClient } : {}),
|
||||
},
|
||||
'repoId' in input
|
||||
? { kind: 'repo', repoId: input.repoId }
|
||||
: { kind: 'server', serverId: input.serverId, directory: input.directory },
|
||||
)
|
||||
const model = await target.resolveModel(input.model)
|
||||
|
||||
let directory = repo.fullPath
|
||||
let directory = target.directory
|
||||
let workspaceDirectory: string | null = null
|
||||
|
||||
if (input.workspace) {
|
||||
try {
|
||||
const workspace = await this.repoWorkspaces.create(repo, {
|
||||
directory = await target.createWorkspace({
|
||||
name: sanitizeRepoDirectoryName(input.workspace.name ?? '', 'session'),
|
||||
...(input.workspace.ref ? { ref: input.workspace.ref } : {}),
|
||||
})
|
||||
directory = workspace.directory
|
||||
workspaceDirectory = workspace.directory
|
||||
workspaceDirectory = directory
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to create workspace', 502)
|
||||
}
|
||||
@@ -109,7 +222,7 @@ export class SessionLauncher {
|
||||
|
||||
let session: { id: string; title?: string | null }
|
||||
try {
|
||||
session = await this.openCodeClient.api.session.create({
|
||||
session = await target.client.api.session.create({
|
||||
...(input.title ? { title: input.title } : {}),
|
||||
...(input.agent ? { agent: input.agent } : {}),
|
||||
...(input.permissions ? { permissions: input.permissions } : {}),
|
||||
@@ -129,7 +242,7 @@ export class SessionLauncher {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.openCodeClient.api.session.prompt({ sessionID: session.id, text: input.prompt })
|
||||
await target.client.api.session.prompt({ sessionID: session.id, text: input.prompt })
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(
|
||||
withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory),
|
||||
@@ -141,7 +254,7 @@ export class SessionLauncher {
|
||||
|
||||
return {
|
||||
sessionId: session.id,
|
||||
repoId: repo.id,
|
||||
repoId: target.repo?.id ?? null,
|
||||
directory,
|
||||
workspaceDirectory,
|
||||
model: model.model,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type {
|
||||
SessionLockReason,
|
||||
SessionPermissionMode,
|
||||
SessionPermissionModeState,
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type SessionLockReason,
|
||||
type SessionPermissionMode,
|
||||
type SessionPermissionModeState,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { openCodeLocation, type PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { getScheduleRunBySessionId } from '../db/schedules'
|
||||
@@ -18,6 +19,16 @@ import type { SessionAncestry } from './session-ancestry'
|
||||
import type { SSEEvent } from './sse-aggregator'
|
||||
import type { SettingsService } from './settings'
|
||||
|
||||
export interface SessionClientProvider {
|
||||
getClient(serverId: string): OpenCodeClient
|
||||
}
|
||||
|
||||
export type SessionClientSource = OpenCodeClient | SessionClientProvider
|
||||
|
||||
function isClientProvider(source: SessionClientSource): source is SessionClientProvider {
|
||||
return typeof (source as SessionClientProvider).getClient === 'function'
|
||||
}
|
||||
|
||||
export class SessionPermissionModeError extends Error {
|
||||
status: number
|
||||
|
||||
@@ -28,55 +39,71 @@ export class SessionPermissionModeError extends Error {
|
||||
}
|
||||
|
||||
export class SessionPermissionModeService {
|
||||
private readonly clients: SessionClientProvider
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
clients: SessionClientSource,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly ancestry: SessionAncestry,
|
||||
) {}
|
||||
) {
|
||||
this.clients = isClientProvider(clients) ? clients : { getClient: () => clients }
|
||||
}
|
||||
|
||||
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
|
||||
async handleEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
switch (event.type) {
|
||||
case 'session.created': {
|
||||
const { sessionID, parentID, permissions } = event.data
|
||||
this.ancestry.rememberParent(sessionID, parentID)
|
||||
this.ancestry.rememberParent(sessionID, parentID, serverId)
|
||||
const hasExplicitPermissions = Array.isArray(permissions) && permissions.length > 0
|
||||
if (!parentID && !hasExplicitPermissions && this.defaultMode() === 'auto') {
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto', serverId)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'session.forked': {
|
||||
const { sessionID, parentID } = event.data
|
||||
this.ancestry.rememberParent(sessionID, null)
|
||||
const sourceMode = await this.getEffectiveMode(parentID)
|
||||
this.ancestry.rememberParent(sessionID, null, serverId)
|
||||
const sourceMode = await this.getEffectiveMode(parentID, serverId)
|
||||
if (sourceMode.mode === 'auto') {
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto', serverId)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'permission.asked': {
|
||||
const { sessionID, id } = event.data
|
||||
await this.autoAcceptRequest(sessionID, id)
|
||||
await this.autoAcceptRequest(sessionID, id, serverId)
|
||||
return
|
||||
}
|
||||
case 'session.deleted': {
|
||||
const { sessionID } = event.data
|
||||
this.ancestry.forget(sessionID)
|
||||
deleteSessionPermissionMode(this.db, sessionID)
|
||||
this.ancestry.forget(sessionID, serverId)
|
||||
deleteSessionPermissionMode(this.db, sessionID, serverId)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getEffectiveMode(sessionId: string): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId)
|
||||
return this.effectiveModeForRoot(sessionId, rootSessionId)
|
||||
async getEffectiveMode(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId, serverId)
|
||||
return this.effectiveModeForRoot(sessionId, rootSessionId, serverId)
|
||||
}
|
||||
|
||||
async setMode(sessionId: string, mode: SessionPermissionMode, directory: string): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
|
||||
async setMode(
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
directory: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId, serverId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId, serverId)
|
||||
if (lockedReason === 'schedule') {
|
||||
throw new SessionPermissionModeError(
|
||||
'Scheduled runs use their own permission configuration',
|
||||
@@ -91,15 +118,15 @@ export class SessionPermissionModeService {
|
||||
)
|
||||
}
|
||||
|
||||
setSessionPermissionMode(this.db, sessionId, mode)
|
||||
setSessionPermissionMode(this.db, sessionId, mode, serverId)
|
||||
if (mode === 'auto') {
|
||||
await this.acceptPendingRequestsInDirectory(directory, sessionId)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId, sessionId)
|
||||
}
|
||||
return { sessionId, rootSessionId, mode, lockedReason: null }
|
||||
}
|
||||
|
||||
pinAsk(sessionId: string): void {
|
||||
setSessionPermissionMode(this.db, sessionId, 'ask')
|
||||
pinAsk(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): void {
|
||||
setSessionPermissionMode(this.db, sessionId, 'ask', serverId)
|
||||
}
|
||||
|
||||
defaultMode(): SessionPermissionMode {
|
||||
@@ -112,66 +139,93 @@ export class SessionPermissionModeService {
|
||||
*
|
||||
* Does nothing when the default mode is `ask`, since that needs no stored row.
|
||||
*/
|
||||
async applyDefaultMode(sessionId: string, directory: string): Promise<void> {
|
||||
async applyDefaultMode(
|
||||
sessionId: string,
|
||||
directory: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
if (this.defaultMode() !== 'auto') {
|
||||
return
|
||||
}
|
||||
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionId, 'auto')
|
||||
await this.acceptPendingRequestsInDirectory(directory, sessionId)
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionId, 'auto', serverId)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId, sessionId)
|
||||
}
|
||||
|
||||
async acceptPendingRequestsForActiveSessions(): Promise<void> {
|
||||
async acceptPendingRequestsForActiveSessions(serverId: string = LOCAL_OPENCODE_SERVER_ID): Promise<void> {
|
||||
try {
|
||||
const active = await this.openCodeClient.api.session.active()
|
||||
const client = this.clients.getClient(serverId)
|
||||
const active = await client.api.session.active()
|
||||
const directories = new Set<string>()
|
||||
|
||||
for (const sessionId of Object.keys(active ?? {})) {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId)
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId, serverId)
|
||||
if (!rootSessionId) continue
|
||||
if (this.effectiveModeForRoot(sessionId, rootSessionId).mode !== 'auto') continue
|
||||
const directory = await this.resolveSessionDirectory(sessionId)
|
||||
if (this.effectiveModeForRoot(sessionId, rootSessionId, serverId).mode !== 'auto') continue
|
||||
const directory = await this.resolveSessionDirectory(sessionId, serverId)
|
||||
if (directory) directories.add(directory)
|
||||
}
|
||||
|
||||
for (const directory of directories) {
|
||||
await this.acceptPendingRequestsInDirectory(directory)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to accept pending permission requests for active sessions:', error)
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
async suppressesPermissionNotification(
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<boolean> {
|
||||
if (event.type !== 'permission.asked' || !sessionId) {
|
||||
return false
|
||||
}
|
||||
return (await this.getEffectiveMode(sessionId, serverId)).mode === 'auto'
|
||||
}
|
||||
|
||||
private effectiveModeForRoot(
|
||||
sessionId: string,
|
||||
rootSessionId: string | null,
|
||||
serverId: string,
|
||||
): SessionPermissionModeState {
|
||||
if (!rootSessionId) {
|
||||
return { sessionId, rootSessionId: sessionId, mode: 'ask', lockedReason: null }
|
||||
}
|
||||
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId, serverId)
|
||||
|
||||
if (lockedReason === 'schedule') {
|
||||
return { sessionId, rootSessionId, mode: 'ask', lockedReason }
|
||||
}
|
||||
|
||||
const stored = getSessionPermissionMode(this.db, rootSessionId)
|
||||
const stored = getSessionPermissionMode(this.db, rootSessionId, serverId)
|
||||
return { sessionId, rootSessionId, mode: stored ?? 'ask', lockedReason }
|
||||
}
|
||||
|
||||
private lockReasonForRoot(sessionId: string, rootSessionId: string): SessionLockReason | null {
|
||||
if (getScheduleRunBySessionId(this.db, rootSessionId)) {
|
||||
private lockReasonForRoot(
|
||||
sessionId: string,
|
||||
rootSessionId: string,
|
||||
serverId: string,
|
||||
): SessionLockReason | null {
|
||||
if (serverId === LOCAL_OPENCODE_SERVER_ID && getScheduleRunBySessionId(this.db, rootSessionId)) {
|
||||
return 'schedule'
|
||||
}
|
||||
|
||||
return rootSessionId !== sessionId ? 'child' : null
|
||||
}
|
||||
|
||||
private async acceptPendingRequestsInDirectory(directory: string, expectedRootSessionId?: string): Promise<void> {
|
||||
private async acceptPendingRequestsInDirectory(
|
||||
directory: string,
|
||||
serverId: string,
|
||||
expectedRootSessionId?: string,
|
||||
): Promise<void> {
|
||||
let requests: PermissionRequest[]
|
||||
try {
|
||||
const result = await this.openCodeClient.api.permission.request.list(openCodeLocation(directory))
|
||||
const result = await this.clients
|
||||
.getClient(serverId)
|
||||
.api.permission.request.list(openCodeLocation(directory))
|
||||
requests = result.data
|
||||
} catch (error) {
|
||||
logger.error(`Failed to list pending permission requests for directory ${directory}:`, error)
|
||||
@@ -179,13 +233,13 @@ export class SessionPermissionModeService {
|
||||
}
|
||||
|
||||
for (const request of requests) {
|
||||
await this.autoAcceptRequest(request.sessionID, request.id, expectedRootSessionId)
|
||||
await this.autoAcceptRequest(request.sessionID, request.id, serverId, expectedRootSessionId)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveSessionDirectory(sessionId: string): Promise<string | null> {
|
||||
private async resolveSessionDirectory(sessionId: string, serverId: string): Promise<string | null> {
|
||||
try {
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
const session = await this.clients.getClient(serverId).api.session.get({ sessionID: sessionId })
|
||||
return session.location.directory
|
||||
} catch (error) {
|
||||
logger.error(`Failed to resolve directory for session ${sessionId}:`, error)
|
||||
@@ -196,9 +250,10 @@ export class SessionPermissionModeService {
|
||||
private async autoAcceptRequest(
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
serverId: string,
|
||||
expectedRootSessionId?: string,
|
||||
): Promise<void> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionID)
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionID, serverId)
|
||||
if (!rootSessionId) {
|
||||
return
|
||||
}
|
||||
@@ -207,25 +262,27 @@ export class SessionPermissionModeService {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.effectiveModeForRoot(sessionID, rootSessionId).mode !== 'auto') {
|
||||
if (this.effectiveModeForRoot(sessionID, rootSessionId, serverId).mode !== 'auto') {
|
||||
return
|
||||
}
|
||||
|
||||
await this.replyOnce(sessionID, requestID)
|
||||
await this.replyOnce(sessionID, requestID, serverId)
|
||||
}
|
||||
|
||||
private async replyOnce(sessionID: string, requestID: string): Promise<void> {
|
||||
private async replyOnce(sessionID: string, requestID: string, serverId: string): Promise<void> {
|
||||
try {
|
||||
await this.openCodeClient.api.permission.reply({ sessionID, requestID, decision: 'once' })
|
||||
await this.clients
|
||||
.getClient(serverId)
|
||||
.api.permission.reply({ sessionID, requestID, decision: 'once' })
|
||||
logger.info(`Auto-accepted permission request ${requestID} for session ${sessionID}`)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to auto-accept permission request ${requestID} for session ${sessionID}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveRootSessionIdOrNull(sessionId: string): Promise<string | null> {
|
||||
private async resolveRootSessionIdOrNull(sessionId: string, serverId: string): Promise<string | null> {
|
||||
try {
|
||||
return await this.ancestry.resolveRootSessionId(sessionId)
|
||||
return await this.ancestry.resolveRootSessionId(sessionId, serverId)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type SessionMessageAssistant,
|
||||
type SessionMessageInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { truncateText } from '../utils/text-truncate'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { sseAggregator, type SSEEvent } from './sse-aggregator'
|
||||
@@ -47,7 +48,12 @@ export function sessionSettleSignal(event: SSEEvent, sessionId: string): Session
|
||||
}
|
||||
}
|
||||
|
||||
export function waitForSessionSettled(client: OpenCodeClient, sessionId: string, timeoutMs: number): Promise<void> {
|
||||
export function waitForSessionSettled(
|
||||
client: OpenCodeClient,
|
||||
sessionId: string,
|
||||
timeoutMs: number,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
if (timeoutMs <= 0) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
@@ -69,7 +75,10 @@ export function waitForSessionSettled(client: OpenCodeClient, sessionId: string,
|
||||
resolve()
|
||||
}
|
||||
|
||||
unsubscribe = sseAggregator.onEvent((_directory, event) => {
|
||||
unsubscribe = sseAggregator.onServerEvent((eventServerId, _directory, event) => {
|
||||
if (eventServerId !== serverId) {
|
||||
return
|
||||
}
|
||||
if (sessionSettleSignal(event, sessionId)) {
|
||||
finish()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ import { encodeSSEFrame } from '../utils/sse-frame'
|
||||
type SSEClientCallback = (event: string, data: string) => void
|
||||
type SSEClientFrameWriter = (frame: Uint8Array) => void
|
||||
type SSEEventListener = (directory: string | null, event: SSEEvent) => void
|
||||
type ServerEventListener = (serverId: string, directory: string | null, event: SSEEvent) => void
|
||||
type ServerConnectedListener = (serverId: string) => void
|
||||
type RemoteSubagentResolver = (serverId: string, sessionId: string) => boolean
|
||||
|
||||
export type RemoteReplayHandler = (clientId: string, serverId: string, directory: string) => void | Promise<void>
|
||||
|
||||
@@ -20,6 +23,7 @@ interface SSEClient {
|
||||
directories: Set<string>
|
||||
visible: boolean
|
||||
activeSessionId: string | null
|
||||
activeServerId: string | null
|
||||
}
|
||||
|
||||
export type SSEEvent = V2Event
|
||||
@@ -54,7 +58,10 @@ class SSEAggregator {
|
||||
private activeSessions: Map<string, Set<string>> = new Map()
|
||||
private sessionDirectories: Map<string, string> = new Map()
|
||||
private eventListeners: Set<SSEEventListener> = new Set()
|
||||
private serverEventListeners: Set<ServerEventListener> = new Set()
|
||||
private upstreamConnectedListeners: Set<() => void> = new Set()
|
||||
private serverConnectedListeners: Set<ServerConnectedListener> = new Set()
|
||||
private remoteSubagentResolver: RemoteSubagentResolver | null = null
|
||||
private subagentSessions: Map<string, Set<string>> = new Map()
|
||||
private upstream: EventSource | null = null
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
@@ -122,7 +129,8 @@ class SSEAggregator {
|
||||
writeFrame,
|
||||
directories: new Set(directories),
|
||||
visible: false,
|
||||
activeSessionId: null
|
||||
activeSessionId: null,
|
||||
activeServerId: null
|
||||
}
|
||||
this.clients.set(id, client)
|
||||
directories.forEach(dir => this.indexClientDirectory(id, dir))
|
||||
@@ -436,6 +444,7 @@ class SSEAggregator {
|
||||
this.upstreamConnectedListeners.forEach(listener => {
|
||||
try { listener() } catch { /* ignore listener errors */ }
|
||||
})
|
||||
this.notifyServerConnected(LOCAL_OPENCODE_SERVER_ID)
|
||||
}
|
||||
|
||||
private broadcastResync(): void {
|
||||
@@ -456,11 +465,37 @@ class SSEAggregator {
|
||||
return () => { this.eventListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onServerEvent(listener: ServerEventListener): () => void {
|
||||
this.serverEventListeners.add(listener)
|
||||
return () => { this.serverEventListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onUpstreamConnected(listener: () => void): () => void {
|
||||
this.upstreamConnectedListeners.add(listener)
|
||||
return () => { this.upstreamConnectedListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onServerConnected(listener: ServerConnectedListener): () => void {
|
||||
this.serverConnectedListeners.add(listener)
|
||||
return () => { this.serverConnectedListeners.delete(listener) }
|
||||
}
|
||||
|
||||
notifyServerEvent(serverId: string, directory: string | null, event: SSEEvent): void {
|
||||
this.serverEventListeners.forEach(listener => {
|
||||
try { listener(serverId, directory, event) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
}
|
||||
|
||||
notifyServerConnected(serverId: string): void {
|
||||
this.serverConnectedListeners.forEach(listener => {
|
||||
try { listener(serverId) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
}
|
||||
|
||||
setRemoteSubagentResolver(resolver: RemoteSubagentResolver | null): void {
|
||||
this.remoteSubagentResolver = resolver
|
||||
}
|
||||
|
||||
private handleUpstreamMessage(data: string): void {
|
||||
let event: V2Event
|
||||
try {
|
||||
@@ -531,6 +566,7 @@ class SSEAggregator {
|
||||
this.eventListeners.forEach(listener => {
|
||||
try { listener(directory, event) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
this.notifyServerEvent(LOCAL_OPENCODE_SERVER_ID, directory, event)
|
||||
}
|
||||
|
||||
private writeEnvelopeToClients(clientIds: Iterable<string>, directory: string | null, payloadJson: string): void {
|
||||
@@ -692,7 +728,12 @@ class SSEAggregator {
|
||||
return this.clients.size
|
||||
}
|
||||
|
||||
setClientVisibility(id: string, visible: boolean, activeSessionId: string | null = null): boolean {
|
||||
setClientVisibility(
|
||||
id: string,
|
||||
visible: boolean,
|
||||
activeSessionId: string | null = null,
|
||||
activeServerId: string | null = null
|
||||
): boolean {
|
||||
const client = this.clients.get(id)
|
||||
if (!client) {
|
||||
logger.warn(`setClientVisibility: client ${id} not found`)
|
||||
@@ -700,19 +741,23 @@ class SSEAggregator {
|
||||
}
|
||||
client.visible = visible
|
||||
client.activeSessionId = visible ? activeSessionId : null
|
||||
client.activeServerId = visible ? (activeServerId ?? LOCAL_OPENCODE_SERVER_ID) : null
|
||||
return true
|
||||
}
|
||||
|
||||
isSessionBeingViewed(sessionId: string): boolean {
|
||||
isSessionBeingViewed(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): boolean {
|
||||
for (const client of this.clients.values()) {
|
||||
if (client.visible && client.activeSessionId === sessionId) {
|
||||
if (client.visible && client.activeSessionId === sessionId && client.activeServerId === serverId) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
isSubagentSession(sessionId: string): boolean {
|
||||
isSubagentSession(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): boolean {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) {
|
||||
return this.remoteSubagentResolver?.(serverId, sessionId) ?? false
|
||||
}
|
||||
for (const sessions of this.subagentSessions.values()) {
|
||||
if (sessions.has(sessionId)) {
|
||||
return true
|
||||
@@ -760,7 +805,10 @@ class SSEAggregator {
|
||||
this.directoryClients.clear()
|
||||
this.clients.clear()
|
||||
this.eventListeners.clear()
|
||||
this.serverEventListeners.clear()
|
||||
this.upstreamConnectedListeners.clear()
|
||||
this.serverConnectedListeners.clear()
|
||||
this.remoteSubagentResolver = null
|
||||
this.remoteReplayHandler = null
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,12 @@ export interface TerminalSize {
|
||||
rows: number
|
||||
}
|
||||
|
||||
export interface TerminalTarget {
|
||||
client: OpenCodeClient
|
||||
baseUrl: () => string
|
||||
includeLocalCredentials: boolean
|
||||
}
|
||||
|
||||
export class TerminalNotFoundError extends Error {
|
||||
constructor(ptyID: string) {
|
||||
super(`Terminal not found: ${ptyID}`)
|
||||
@@ -32,24 +38,30 @@ export class TerminalNotFoundError extends Error {
|
||||
|
||||
export class TerminalService {
|
||||
constructor(
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly target: TerminalTarget,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly upstreamBaseUrl: () => string,
|
||||
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
|
||||
) {}
|
||||
|
||||
forTarget(target: TerminalTarget): TerminalService {
|
||||
return new TerminalService(target, this.credentialProvider, this.openSocket)
|
||||
}
|
||||
|
||||
async list(directory: string): Promise<TerminalInfo[]> {
|
||||
const result = await this.openCodeClient.api.pty.list({ location: { directory } })
|
||||
const result = await this.target.client.api.pty.list({ location: { directory } })
|
||||
return result.data.map((pty) => this.toTerminalInfo(pty))
|
||||
}
|
||||
|
||||
async create(directory: string, input: CreateTerminalInput): Promise<TerminalInfo> {
|
||||
const result = await this.openCodeClient.api.pty.create({
|
||||
const result = await this.target.client.api.pty.create({
|
||||
location: { directory },
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
|
||||
...(input.command !== undefined ? { command: input.command } : {}),
|
||||
...(input.args !== undefined ? { args: input.args } : {}),
|
||||
env: { ...this.credentialProvider.getGhCliEnv({ cwd: directory }), ...input.env },
|
||||
env: {
|
||||
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
|
||||
...input.env,
|
||||
},
|
||||
})
|
||||
return this.toTerminalInfo(result.data)
|
||||
}
|
||||
@@ -64,11 +76,11 @@ export class TerminalService {
|
||||
}
|
||||
|
||||
async resize(directory: string, ptyID: string, size: TerminalSize): Promise<void> {
|
||||
await this.openCodeClient.api.pty.update({ ptyID, location: { directory }, size })
|
||||
await this.target.client.api.pty.update({ ptyID, location: { directory }, size })
|
||||
}
|
||||
|
||||
async remove(directory: string, ptyID: string): Promise<void> {
|
||||
await this.openCodeClient.api.pty.remove({ ptyID, location: { directory } })
|
||||
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
|
||||
}
|
||||
|
||||
async removeAll(directory: string): Promise<void> {
|
||||
@@ -92,13 +104,13 @@ export class TerminalService {
|
||||
): Promise<WebSocketBridge> {
|
||||
await this.requireTerminal(directory, ptyID)
|
||||
|
||||
const result = await this.openCodeClient.api.pty.connect.token({
|
||||
const result = await this.target.client.api.pty.connect.token({
|
||||
ptyID,
|
||||
location: { directory },
|
||||
'x-opencode-ticket': '1',
|
||||
})
|
||||
|
||||
const base = new URL(this.upstreamBaseUrl())
|
||||
const base = new URL(this.target.baseUrl())
|
||||
if (!base.pathname.endsWith('/')) base.pathname += '/'
|
||||
const socketUrl = new URL(`api/pty/${encodeURIComponent(ptyID)}/connect`, base)
|
||||
socketUrl.searchParams.set('ticket', result.data.ticket)
|
||||
@@ -111,7 +123,7 @@ export class TerminalService {
|
||||
private async removePersistentTerminals(directory: string): Promise<void> {
|
||||
let cursor: string | undefined
|
||||
do {
|
||||
const page = await this.openCodeClient.api.session.list({ directory, cursor })
|
||||
const page = await this.target.client.api.session.list({ directory, cursor })
|
||||
for (const session of page.data) {
|
||||
await this.removeSessionPersistentTerminals(session.id)
|
||||
}
|
||||
@@ -122,7 +134,7 @@ export class TerminalService {
|
||||
private async removeSessionPersistentTerminals(sessionID: string): Promise<void> {
|
||||
let terminals: OpenCodePersistentPty[]
|
||||
try {
|
||||
terminals = await this.openCodeClient.api.experimental.persistentPty.list({ sessionID })
|
||||
terminals = await this.target.client.api.experimental.persistentPty.list({ sessionID })
|
||||
} catch (error: unknown) {
|
||||
if (openCodeErrorStatus(error) === 404) return
|
||||
throw error
|
||||
@@ -130,7 +142,7 @@ export class TerminalService {
|
||||
|
||||
for (const terminal of terminals) {
|
||||
try {
|
||||
await this.openCodeClient.api.experimental.persistentPty.remove({ ptyID: terminal.id })
|
||||
await this.target.client.api.experimental.persistentPty.remove({ ptyID: terminal.id })
|
||||
} catch (error: unknown) {
|
||||
if (openCodeErrorStatus(error) === 404) continue
|
||||
throw error
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export function parseTerminalCursor(raw: string | undefined): number | undefined | null {
|
||||
if (raw === undefined) return undefined
|
||||
if (!/^-?\d+$/.test(raw)) return null
|
||||
const parsed = Number(raw)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < -1) return null
|
||||
return parsed
|
||||
}
|
||||
Reference in new issue
Block a user