workspace-server.ts 8.5 KB

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