dsh-sansheng-liubu/test/fake-ctx.js

107 lines
4.2 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.

// 测试用 fake 宿主:模拟 DSH 注入的公开服务,便于隔离验证,不接触真实 DSH。
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
export async function tempStateFile() {
const dir = await mkdtemp(join(tmpdir(), 'sansheng-test-'))
return join(dir, 'state.json')
}
export function createFakeHost(opts = {}) {
const sessions = new Map() // sessionId -> agent
const workspaces = new Map() // id -> { id, name, path }
const calls = { create: [], resolve: [], selectModel: 0, agentSelect: [], createAt: [] }
const control = {
failCreateOrder: null, // 第 N 次 create 抛错(1 起)
mismatchCreateOrder: null, // 第 N 次 create 返回另一个 ID
catalog: opts.catalog ?? {
providers: [{ provider: 'deepseek', models: ['deepseek-chat', 'deepseek-reasoner'] }],
default: { provider: 'deepseek', model: 'deepseek-chat' },
failures: [],
},
validRoutes: opts.validRoutes ?? new Set(['deepseek/deepseek-chat', 'deepseek/deepseek-reasoner']),
}
let createCount = 0
const workspaceRegistry = {
get(id) { return workspaces.get(id) },
list() { return [...workspaces.values()] },
async resolveByPath(p) { return [...workspaces.values()].find(w => w.path === p) },
async create(p, title) { const id = `ws-${workspaces.size + 1}`; const w = { id, name: title ?? id, path: p }; workspaces.set(id, w); return w },
}
function agentFor(sessionId) {
let agent = sessions.get(sessionId)
if (!agent) {
agent = {
id: sessionId,
_selection: null,
model: {
current() { return agent._selection },
select(selection) { agent._selection = selection; calls.agentSelect.push({ sessionId, selection }) },
},
}
sessions.set(sessionId, agent)
}
return agent
}
const sessionController = {
async resolveAgent(sessionId) {
calls.resolve.push(sessionId)
if (sessions.has(sessionId)) return { agent: sessions.get(sessionId) }
return { error: { code: 'session/not-found', message: 'session not found' } }
},
async create({ sessionId, workspaceId, cwd } = {}) {
createCount += 1
const order = createCount
calls.create.push({ sessionId, workspaceId, cwd, order })
if (control.failCreateOrder === order) {
const error = new Error('simulated create failure')
error.code = 'session/create-failed'
throw error
}
let actual = sessionId
if (control.mismatchCreateOrder === order) actual = `minted-${Math.random().toString(36).slice(2, 8)}`
agentFor(actual)
return { sessionId: actual }
},
async modelCatalog() { return control.catalog },
// 我们的代码绝不能调用它(会写 profile 全局默认);被调用即失败并计数。
async selectModel() { calls.selectModel += 1; throw new Error('sessionController.selectModel must not be called') },
}
const agents = { get(id) { return sessions.get(id) }, list() { return [...sessions.values()] } }
const llm = {
async resolveCallConfig(selection) {
const key = `${selection.provider}/${selection.model}`
if (control.validRoutes.size > 0 && !control.validRoutes.has(key)) {
const error = new Error(`unknown route ${key}`)
error.code = 'llm/unknown-model'
throw error
}
return { ...selection }
},
}
let promptSection = null
const systemPrompt = { section(def) { promptSection = def; return () => { promptSection = null } } }
let route = null
const connection = { fetch: { register(def) { route = def; return () => {} } } }
const host = { workspaceRegistry, sessionController, agents, llm, systemPrompt }
const ctx = {
workspaceRegistry, sessionController, agents, llm, systemPrompt, connection,
effect(fn) { const dispose = fn(); return dispose },
}
return {
host, ctx, calls, control, sessions, workspaces,
getPromptSection() { return promptSection },
getRoute() { return route },
addWorkspace(id, name, path) { workspaces.set(id, { id, name, path }) },
// 预置一个已存在的会话(用于“已存在不重建”测试)
addSession(sessionId) { return agentFor(sessionId) },
}
}