dsh-sansheng-liubu/sansheng/src/host/model-sync.js

201 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// R-001:十席模型解析与跨会话同步。
// 顺序:项目覆盖(seat.model)→ 全局默认(setting.json)→ 部署默认(仅会话级回退)→ none。
// 每个 projectId:seatId 一个串行队列;generation 递增,旧结果不得写入状态。
import { SEAT_IDS } from '../shared/roles.js'
import { applyModel, ModelError } from './model.js'
export class ModelSyncError extends Error {
constructor(code, message) {
super(message)
this.name = 'ModelSyncError'
this.code = code
}
}
function cleanText(value) { return typeof value === 'string' ? value.trim() : '' }
function copy(value) { try { return structuredClone(value) } catch { return JSON.parse(JSON.stringify(value)) } }
function sameModel(a, b) {
if (!a && !b) return true
if (!a || !b) return false
return a.provider === b.provider && a.model === b.model && (a.reasoningEffort ?? undefined) === (b.reasoningEffort ?? undefined)
}
function modelKey(model) {
if (!model) return ''
return model.provider + '::' + model.model + '::' + (model.reasoningEffort ?? '')
}
function fingerprintOf(project, globalRevision) {
const parts = [String(globalRevision ?? 0)]
for (const seatId of SEAT_IDS) {
const seat = project?.seats?.[seatId]
parts.push(seatId + ':' + (seat?.sessionId ?? '') + ':' + modelKey(seat?.model))
}
return parts.join('|')
}
export function createModelSync({ store, globalStore, host, normalizeCatalog, now = () => Date.now() } = {}) {
if (!store || !globalStore || !host) throw new ModelSyncError('sansheng/model-sync-deps', 'createModelSync 需要 store/globalStore/host')
const clock = typeof now === 'function' ? now : () => Number(now)
const statuses = new Map()
const queues = new Map()
const generations = new Map()
const fingerprints = new Map()
const keyOf = (projectId, seatId) => projectId + ':' + seatId
async function ensureLoaded() {
if (typeof store.ensureLoaded === 'function') await store.ensureLoaded()
if (typeof globalStore.ensureLoaded === 'function') await globalStore.ensureLoaded()
}
function setStatus(projectId, seatId, patch) {
const key = keyOf(projectId, seatId)
const previous = statuses.get(key) ?? {}
// agentRef 是活 Agent,不能深拷贝;状态对外只通过 publicStatus 去掉它。
const next = { ...previous, ...patch, updatedAt: clock() }
statuses.set(key, next)
return publicStatus(next)
}
function publicStatus(record) {
if (!record) return null
const { agentRef, ...rest } = record
return copy(rest)
}
function statusOf(projectId) {
const out = {}
for (const seatId of SEAT_IDS) {
const record = statuses.get(keyOf(projectId, seatId))
if (!record) { out[seatId] = null; continue }
let view = publicStatus(record)
view.sessionModel = view.currentModel ?? null
view.configuredModel = view.targetModel ?? null
view.modelSource = view.targetSource ?? 'none'
view.modelSyncStatus = view.status
if (record.status === 'synced') {
const seat = store.get(projectId)?.seats?.[seatId]
const live = seat?.sessionId ? host.agents?.get?.(seat.sessionId) : null
if (!seat || seat.sessionId !== record.sessionId || live !== record.agentRef) view = { ...view, status: 'stale' }
}
out[seatId] = view
}
return out
}
async function resolveDesired(projectId, seatId) {
const project = store.get(projectId)
const seat = project?.seats?.[seatId]
if (!seat) throw new ModelSyncError('sansheng/not-found', '项目 ' + projectId + ' 的席 ' + seatId + ' 不存在')
if (seat.model) return { model: copy(seat.model), source: 'project' }
await globalStore.ensureLoaded()
const globalModel = globalStore.getSeat(seatId)
if (globalModel) return { model: copy(globalModel), source: 'global' }
let catalog = null
try { catalog = typeof normalizeCatalog === 'function' ? normalizeCatalog(await host.sessionController.modelCatalog()) : null } catch { catalog = null }
const def = catalog?.default
if (def && cleanText(def.provider) && cleanText(def.model)) {
try {
await host.llm.resolveCallConfig({ provider: def.provider, model: def.model })
return { model: { provider: def.provider, model: def.model }, source: 'deployment' }
} catch (error) {
return { model: null, source: 'none', error: '部署默认不可用:' + (error?.message ?? error) }
}
}
return { model: null, source: 'none' }
}
async function perform(projectId, seatId, reason) {
const key = keyOf(projectId, seatId)
const generation = (generations.get(key) ?? 0) + 1
generations.set(key, generation)
const isCurrent = () => generations.get(key) === generation
const startProject = store.get(projectId)
const startSeat = startProject?.seats?.[seatId]
if (!startProject || !startSeat) return setStatus(projectId, seatId, { status: 'failed', error: '项目或席位不存在' })
if (startSeat.status !== 'bound' || !startSeat.sessionId) {
return setStatus(projectId, seatId, { status: 'unbound', sessionId: null, agentId: null, agentRef: null, targetModel: null, targetSource: 'none', currentModel: null, error: '席位尚未绑定会话' })
}
const expectedSessionId = startSeat.sessionId
const expectedProjectRevision = startProject.revision ?? 0
const expectedGlobalRevision = globalStore.revision
const expectedSeatModel = copy(startSeat.model)
setStatus(projectId, seatId, { status: 'pending', sessionId: expectedSessionId, agentId: null, agentRef: null, targetModel: null, targetSource: 'none', currentModel: null, error: null, reason: reason ?? 'manual' })
let lastError = null
let lastDesired = null
for (let attempt = 0; attempt < 3; attempt += 1) {
if (!isCurrent()) return { status: 'stale' }
let resolved
try { resolved = await host.sessionController.resolveAgent(expectedSessionId) } catch (error) { lastError = error; break }
if (!resolved || ('error' in resolved && resolved.error)) { lastError = resolved?.error ?? new Error('resolveAgent 返回空'); break }
const agent = resolved.agent
if (!agent) { lastError = new Error('resolveAgent 未返回 agent'); break }
if (host.agents.get(expectedSessionId) !== agent) { lastError = new ModelSyncError('sansheng/conflict', '同步期间 Agent 已变化'); continue }
let desired
try { desired = await resolveDesired(projectId, seatId) } catch (error) { lastError = error; break }
lastDesired = desired
if (!desired.model) {
return setStatus(projectId, seatId, { status: desired.error ? 'failed' : 'unresolved', sessionId: expectedSessionId, agentId: agent.id ?? null, agentRef: agent, targetModel: null, targetSource: 'none', currentModel: agent.model?.current?.() ?? null, error: desired.error ?? null })
}
try { await host.llm.resolveCallConfig(desired.model) } catch (error) {
lastError = error
if (desired.source !== 'deployment') {
return setStatus(projectId, seatId, { status: 'failed', sessionId: expectedSessionId, agentId: agent.id ?? null, agentRef: agent, targetModel: copy(desired.model), targetSource: desired.source, currentModel: agent.model?.current?.() ?? null, error: error?.message ?? String(error) })
}
return setStatus(projectId, seatId, { status: 'unresolved', sessionId: expectedSessionId, agentId: agent.id ?? null, agentRef: agent, targetModel: null, targetSource: 'none', currentModel: agent.model?.current?.() ?? null, error: '部署默认不可用:' + (error?.message ?? error) })
}
const projectNow = store.get(projectId)
const seatNow = projectNow?.seats?.[seatId]
if (!isCurrent()) return { status: 'stale' }
if (!projectNow || !seatNow || seatNow.sessionId !== expectedSessionId || (projectNow.revision ?? 0) !== expectedProjectRevision || globalStore.revision !== expectedGlobalRevision || !sameModel(seatNow.model, expectedSeatModel) || host.agents.get(expectedSessionId) !== agent) continue
try {
const current = await applyModel(host, expectedSessionId, desired.model)
if (!isCurrent()) return { status: 'stale' }
const afterProject = store.get(projectId)
const afterSeat = afterProject?.seats?.[seatId]
if (!afterProject || !afterSeat || afterSeat.sessionId !== expectedSessionId || (afterProject.revision ?? 0) !== expectedProjectRevision || globalStore.revision !== expectedGlobalRevision || !sameModel(afterSeat.model, expectedSeatModel) || host.agents.get(expectedSessionId) !== agent) continue
if (!sameModel(current, desired.model)) { lastError = new ModelError('sansheng/model-not-applied', '模型回读与目标不一致'); break }
return setStatus(projectId, seatId, { status: 'synced', sessionId: expectedSessionId, agentId: agent.id ?? null, agentRef: agent, targetModel: copy(desired.model), targetSource: desired.source, currentModel: copy(current), error: null })
} catch (error) { lastError = error; break }
}
const liveAgent = host.agents.get(expectedSessionId) ?? null
return setStatus(projectId, seatId, { status: 'failed', sessionId: expectedSessionId, agentId: liveAgent?.id ?? null, agentRef: liveAgent, targetModel: copy(lastDesired?.model ?? null), targetSource: lastDesired?.source ?? 'none', currentModel: liveAgent?.model?.current?.() ?? null, error: lastError?.message ?? String(lastError ?? '同步失败') })
}
function enqueue(projectId, seatId, reason) {
const key = keyOf(projectId, seatId)
const prev = queues.get(key) ?? Promise.resolve()
const run = prev.then(() => perform(projectId, seatId, reason), () => perform(projectId, seatId, reason))
const guarded = run.finally(() => { if (queues.get(key) === guarded) queues.delete(key) })
queues.set(key, guarded)
return guarded
}
async function syncSeat(projectId, seatId, reason = 'manual') {
await ensureLoaded()
if (!SEAT_IDS.includes(seatId)) throw new ModelSyncError('sansheng/invalid', '未知席 ' + seatId)
return enqueue(projectId, seatId, reason)
}
async function syncProject(projectId) {
await ensureLoaded()
const project = store.get(projectId)
if (!project) throw new ModelSyncError('sansheng/not-found', '项目 ' + projectId + ' 不存在')
const fp = fingerprintOf(project, globalStore.revision)
const cached = fingerprints.get(projectId)
if (cached && cached.fingerprint === fp) {
const all = SEAT_IDS.every(seatId => (statuses.get(keyOf(projectId, seatId))?.status ?? '') === 'synced')
if (all) return statusOf(projectId)
}
for (const seatId of SEAT_IDS) {
const seat = project.seats?.[seatId]
if (!seat || seat.status !== 'bound' || !seat.sessionId) {
setStatus(projectId, seatId, { status: 'unbound', sessionId: null, targetSource: 'none', error: '席位尚未绑定会话' })
continue
}
await enqueue(projectId, seatId, 'project')
}
fingerprints.set(projectId, { fingerprint: fp, at: clock() })
return statusOf(projectId)
}
async function syncAll() {
await ensureLoaded()
const all = {}
for (const project of store.list()) {
try { all[project.id] = await syncProject(project.id) } catch (error) { all[project.id] = { error: error?.message ?? String(error) } }
}
return all
}
async function retrySeat(projectId, seatId) { return syncSeat(projectId, seatId, 'retry') }
return { syncSeat, syncProject, syncAll, statusOf, retrySeat, resolveDesired }
}