workspace-server.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /** Isolated, deterministic standard-Hermes fixture. It exposes no plugin APIs. */
  2. import { createServer } from 'node:http'
  3. import { mkdtempSync, readFileSync, existsSync, writeFileSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join, resolve } from 'node:path'
  6. import { randomUUID, randomBytes, scryptSync } from 'node:crypto'
  7. import { WebSocketServer } from 'ws'
  8. import serve from 'koa-static'
  9. import { createApplication, createNodeServer } from '../../src/server/app.js'
  10. import { loadServerConfig } from '../../src/server/config.js'
  11. import { LocalAuthStore } from '../../src/server/localAuth.js'
  12. const home =
  13. process.env.WORKSPACE_FIXTURE_HOME || mkdtempSync(join(tmpdir(), 'yaoyao-workspace-browser-'))
  14. const port = Number(process.env.WORKSPACE_FIXTURE_PORT || 18800),
  15. upstreamPort = Number(process.env.WORKSPACE_FIXTURE_UPSTREAM_PORT || 19119)
  16. const sessions = new Map<
  17. string,
  18. {
  19. id: string
  20. profile: string
  21. source: string
  22. messages: Array<{ role: string; content: string; id: string; timestamp: number }>
  23. running: boolean
  24. }
  25. >()
  26. const calls: Array<{ method: string; params: Record<string, unknown> }> = []
  27. const heldReplies: Array<() => void> = []
  28. const profileState = new Map([
  29. ['default', { name: 'default', display_name: '通用助手', is_default: true, gateway_running: true, ui_meta: {} as Record<string, unknown>, ui_meta_revisions: {} as Record<string, number> }],
  30. ['server', { name: 'server', display_name: '开发助手', is_default: false, gateway_running: true, ui_meta: {} as Record<string, unknown>, ui_meta_revisions: {} as Record<string, number> }],
  31. ])
  32. const upstream = createServer((req, res) => {
  33. const url = new URL(req.url || '/', `http://127.0.0.1:${upstreamPort}`)
  34. res.setHeader('content-type', 'application/json')
  35. const send = (v: unknown) => res.end(JSON.stringify(v))
  36. if (url.pathname === '/__release' && req.method === 'POST') {
  37. const held = heldReplies.splice(0)
  38. for (const complete of held) complete()
  39. send({ released: held.length })
  40. return
  41. }
  42. if (url.pathname.includes('/plugins/')) {
  43. res.statusCode = 404
  44. send({ error: 'This fixture has no plugins' })
  45. return
  46. }
  47. if (url.pathname === '/__calls') {
  48. send({ calls })
  49. return
  50. }
  51. if (url.pathname === '/api/status') {
  52. send({ auth_required: true, overall: 'ready', gateway_running: true })
  53. return
  54. }
  55. if (url.pathname === '/api/auth/me') {
  56. send({ user_id: 'fixture', display_name: 'Fixture', provider: 'basic' })
  57. return
  58. }
  59. if (url.pathname === '/auth/password-login') {
  60. res.setHeader('set-cookie', 'hermes_session_at=fixture; Path=/; HttpOnly')
  61. send({ ok: true })
  62. return
  63. }
  64. if (url.pathname === '/api/auth/ws-ticket') {
  65. send({ ticket: 'fixture' })
  66. return
  67. }
  68. if (url.pathname === '/api/profiles') {
  69. send({ profiles: [...profileState.values()] })
  70. return
  71. }
  72. if (url.pathname === '/api/sessions') {
  73. const requestedSource = url.searchParams.get('source')
  74. const visible = [...sessions.values()].filter(session =>
  75. !requestedSource || session.source === requestedSource)
  76. send({
  77. sessions: visible.map((s) => ({
  78. id: s.id,
  79. title: 'Internal',
  80. source: s.source,
  81. profile: s.profile,
  82. })),
  83. total: visible.length,
  84. hasMore: false,
  85. offset: Number(url.searchParams.get('offset') ?? 0),
  86. limit: Number(url.searchParams.get('limit') ?? 100),
  87. })
  88. return
  89. }
  90. const detail = /^\/api\/sessions\/([^/]+)$/.exec(url.pathname)
  91. if (detail) {
  92. const session = sessions.get(detail[1]!)
  93. if (!session) {
  94. res.statusCode = 404
  95. send({ error: 'session not found' })
  96. return
  97. }
  98. send({
  99. id: session.id,
  100. profile: session.profile,
  101. source: session.source,
  102. title: 'Internal',
  103. message_count: session.messages.length,
  104. })
  105. return
  106. }
  107. const history = /^\/api\/sessions\/([^/]+)\/messages$/.exec(url.pathname)
  108. if (history) {
  109. send({ messages: sessions.get(history[1]!)?.messages || [] })
  110. return
  111. }
  112. if (url.pathname === '/api/files/download') {
  113. res.setHeader('content-type', 'text/plain')
  114. res.end('Fixture report\n')
  115. return
  116. }
  117. send({ ok: true })
  118. })
  119. const wss = new WebSocketServer({ server: upstream, path: '/api/ws' })
  120. wss.on('connection', (socket) => {
  121. const runtimes = new Map<string, string>()
  122. socket.send(
  123. JSON.stringify({
  124. method: 'event',
  125. params: { type: 'gateway.ready', payload: { capabilities: [] } },
  126. }),
  127. )
  128. socket.on('message', (raw) => {
  129. const f = JSON.parse(String(raw))
  130. calls.push({ method: f.method, params: f.params })
  131. const respond = (result: unknown) => socket.send(JSON.stringify({ id: f.id, result }))
  132. const event = (type: string, payload: unknown, sessionId: string) => {
  133. if (socket.readyState === 1)
  134. socket.send(
  135. JSON.stringify({
  136. method: 'event',
  137. params: { type, payload, session_id: sessionId, profile: 'default' },
  138. }),
  139. )
  140. }
  141. if (f.method === 'profiles.list') {
  142. respond({ profiles: [...profileState.values()] })
  143. return
  144. }
  145. if (f.method === 'profiles.configure') {
  146. const profile = profileState.get(String(f.params.name))
  147. if (!profile) { respond({ error: 'profile_not_found' }); return }
  148. for (const [namespace, value] of Object.entries(f.params.ui_meta ?? {})) {
  149. profile.ui_meta[namespace] = value
  150. profile.ui_meta_revisions[namespace] = (profile.ui_meta_revisions[namespace] ?? 0) + 1
  151. }
  152. respond({ profile })
  153. return
  154. }
  155. if (f.method === 'session.create' || f.method === 'session.resume') {
  156. let stored = f.method === 'session.resume' ? sessions.get(f.params.session_id) : undefined
  157. if (!stored) {
  158. stored = {
  159. id: randomUUID(),
  160. profile: f.params.profile,
  161. source: String(f.params.source ?? 'web'),
  162. messages: [],
  163. running: false,
  164. }
  165. sessions.set(stored.id, stored)
  166. }
  167. const runtimeId = randomUUID()
  168. runtimes.set(runtimeId, stored.id)
  169. respond({
  170. session_id: runtimeId,
  171. stored_session_id: stored.id,
  172. session_key: stored.id,
  173. running: stored.running,
  174. info: { profile_name: stored.profile },
  175. })
  176. return
  177. }
  178. const stored = sessions.get(runtimes.get(f.params.session_id) ?? '')
  179. if (f.method === 'prompt.submit' && stored) {
  180. stored.running = true
  181. stored.messages.push({
  182. id: randomUUID(),
  183. role: 'user',
  184. content: f.params.text,
  185. timestamp: Date.now() / 1000,
  186. })
  187. respond({ status: 'streaming' })
  188. const name = /你是 (.*?)。/.exec(f.params.text)?.[1] || '助手'
  189. const requested = /本轮用户指定成员:([^\n]*)/.exec(f.params.text)?.[1] ?? ''
  190. const delegates = f.params.text.includes('你是管理员。') && !f.params.text.includes('本批次执行结果:') && requested.startsWith('@')
  191. const text = `我是${name}。已按角色规则处理这条消息。\n\n- 会话独立保存\n- 可以继续交流\n\n[报告](/tmp/workspace-report.txt)${delegates ? `\n请${requested}处理任务。` : ''}`
  192. event('message.start', {}, f.params.session_id)
  193. setTimeout(() => event('message.delta', { text: text.slice(0, 12) }, f.params.session_id), 80)
  194. const complete = () => {
  195. stored!.running = false
  196. stored!.messages.push({
  197. id: randomUUID(),
  198. role: 'assistant',
  199. content: text,
  200. timestamp: Date.now() / 1000,
  201. })
  202. event('message.complete', { text, status: 'complete' }, f.params.session_id)
  203. }
  204. if (f.params.text.includes('[hold-workspace]')) heldReplies.push(complete)
  205. else setTimeout(complete, 250)
  206. return
  207. }
  208. if (f.method === 'session.interrupt' && stored) stored.running = false
  209. if (f.method === 'file.attach') {
  210. respond({ attached: true, ref_text: '@file:fixture-upload.txt' })
  211. return
  212. }
  213. respond({ ok: true, status: 'interrupted' })
  214. })
  215. })
  216. await new Promise<void>((resolve) => upstream.listen(upstreamPort, '127.0.0.1', resolve))
  217. const config = loadServerConfig({
  218. HERMES_YAOYAO_HOME: home,
  219. HERMES_YAOYAO_PORT: String(port),
  220. HERMES_YAOYAO_UPSTREAM: `http://127.0.0.1:${upstreamPort}`,
  221. HERMES_YAOYAO_UPSTREAM_USERNAME: 'fixture',
  222. HERMES_YAOYAO_UPSTREAM_PASSWORD: 'fixture',
  223. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  224. })
  225. // Synthetic credentials are seeded only into this disposable fixture directory.
  226. const usersPath = join(home, 'users.json')
  227. if (!existsSync(usersPath)) {
  228. const salt = randomBytes(16),
  229. now = Date.now()
  230. writeFileSync(
  231. usersPath,
  232. JSON.stringify({
  233. version: 1,
  234. users: [
  235. {
  236. id: randomUUID(),
  237. username: 'fixture',
  238. normalizedUsername: 'fixture',
  239. role: 'admin',
  240. enabled: true,
  241. mustChangePassword: false,
  242. salt: salt.toString('base64'),
  243. passwordHash: scryptSync('fixture-pass', salt, 32, {
  244. N: 2 ** 14,
  245. r: 8,
  246. p: 1,
  247. maxmem: 64 * 1024 * 1024,
  248. }).toString('base64'),
  249. authVersion: 1,
  250. createdAt: now,
  251. updatedAt: now,
  252. },
  253. ],
  254. }),
  255. { mode: 0o600 },
  256. )
  257. }
  258. const auth = new LocalAuthStore(home, false)
  259. const runtime = createApplication({ config, auth }),
  260. node = createNodeServer(runtime)
  261. runtime.app.use(serve(resolve('dist')))
  262. runtime.app.use((ctx) => {
  263. if (!ctx.path.startsWith('/api/')) {
  264. ctx.type = 'html'
  265. ctx.body = readFileSync(resolve('dist/index.html'))
  266. }
  267. })
  268. await new Promise<void>((resolve) => node.server.listen(port, '127.0.0.1', resolve))
  269. process.stdout.write(`Workspace fixture http://127.0.0.1:${port}; home=${home}\n`)
  270. for (const signal of ['SIGTERM', 'SIGINT'])
  271. process.once(signal, () => {
  272. void node.close().then(() => {
  273. for (const socket of wss.clients) socket.terminate()
  274. wss.close()
  275. upstream.close()
  276. })
  277. })