workspace-server.ts 9.0 KB

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