workspace-server.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. title: string
  23. messages: Array<{ role: string; content: string; id: string; timestamp: number }>
  24. running: boolean
  25. cwd?: string
  26. }
  27. >()
  28. const latestRuntimeBySession = new Map<string, string>()
  29. const calls: Array<{ method: string; params: Record<string, unknown> }> = []
  30. const heldReplies: Array<() => void> = []
  31. const profileState = new Map([
  32. ['default', { name: 'default', display_name: '通用助手', is_default: true, gateway_running: true, ui_meta: {} as Record<string, unknown>, ui_meta_revisions: {} as Record<string, number> }],
  33. ['server', { name: 'server', display_name: '开发助手', is_default: false, gateway_running: true, ui_meta: {} as Record<string, unknown>, ui_meta_revisions: {} as Record<string, number> }],
  34. ])
  35. function broadcastUpstreamEvent(
  36. type: string,
  37. payload: Record<string, unknown>,
  38. sessionId?: string,
  39. profile = 'default',
  40. ) {
  41. const frame = JSON.stringify({
  42. method: 'event',
  43. params: {
  44. type,
  45. payload,
  46. ...(sessionId ? { session_id: sessionId, profile } : {}),
  47. },
  48. })
  49. for (const socket of wss.clients) {
  50. if (socket.readyState === 1) socket.send(frame)
  51. }
  52. }
  53. const upstream = createServer((req, res) => {
  54. const url = new URL(req.url || '/', `http://127.0.0.1:${upstreamPort}`)
  55. res.setHeader('content-type', 'application/json')
  56. const send = (v: unknown) => res.end(JSON.stringify(v))
  57. if (url.pathname === '/api/config') {
  58. send({ terminal: { cwd: `/tmp/hermes-fixture/${url.searchParams.get('profile') || 'default'}` } })
  59. return
  60. }
  61. if (url.pathname === '/__release' && req.method === 'POST') {
  62. const held = heldReplies.splice(0)
  63. for (const complete of held) complete()
  64. send({ released: held.length })
  65. return
  66. }
  67. if (url.pathname.includes('/plugins/')) {
  68. res.statusCode = 404
  69. send({ error: 'This fixture has no plugins' })
  70. return
  71. }
  72. if (url.pathname === '/__calls') {
  73. send({ calls })
  74. return
  75. }
  76. if (url.pathname === '/__test/sessions/title' && req.method === 'POST') {
  77. const id = url.searchParams.get('id')?.trim() || ''
  78. const title = url.searchParams.get('title')?.trim() || ''
  79. const session = sessions.get(id)
  80. const runtimeId = latestRuntimeBySession.get(id)
  81. if (!session || !runtimeId || !title) {
  82. res.statusCode = 409
  83. send({ error: 'session route is not active' })
  84. return
  85. }
  86. session.title = title
  87. broadcastUpstreamEvent(
  88. 'session.title',
  89. { session_id: id, title },
  90. runtimeId,
  91. session.profile,
  92. )
  93. send({ id, title })
  94. return
  95. }
  96. if (url.pathname === '/api/status') {
  97. send({ auth_required: true, overall: 'ready', gateway_running: true })
  98. return
  99. }
  100. if (url.pathname === '/api/auth/me') {
  101. send({ user_id: 'fixture', display_name: 'Fixture', provider: 'basic' })
  102. return
  103. }
  104. if (url.pathname === '/auth/password-login') {
  105. res.setHeader('set-cookie', 'hermes_session_at=fixture; Path=/; HttpOnly')
  106. send({ ok: true })
  107. return
  108. }
  109. if (url.pathname === '/api/auth/ws-ticket') {
  110. send({ ticket: 'fixture' })
  111. return
  112. }
  113. if (url.pathname === '/api/profiles') {
  114. send({ profiles: [...profileState.values()] })
  115. return
  116. }
  117. if (url.pathname === '/api/sessions') {
  118. const requestedSource = url.searchParams.get('source')
  119. const visible = [...sessions.values()].filter(session =>
  120. !requestedSource || session.source === requestedSource)
  121. send({
  122. sessions: visible.map((s) => ({
  123. id: s.id,
  124. title: s.title,
  125. source: s.source,
  126. profile: s.profile,
  127. })),
  128. total: visible.length,
  129. hasMore: false,
  130. offset: Number(url.searchParams.get('offset') ?? 0),
  131. limit: Number(url.searchParams.get('limit') ?? 100),
  132. })
  133. return
  134. }
  135. const detail = /^\/api\/sessions\/([^/]+)$/.exec(url.pathname)
  136. if (detail) {
  137. const session = sessions.get(detail[1]!)
  138. if (!session) {
  139. res.statusCode = 404
  140. send({ error: 'session not found' })
  141. return
  142. }
  143. send({
  144. id: session.id,
  145. profile: session.profile,
  146. source: session.source,
  147. title: session.title,
  148. message_count: session.messages.length,
  149. })
  150. return
  151. }
  152. const history = /^\/api\/sessions\/([^/]+)\/messages$/.exec(url.pathname)
  153. if (history) {
  154. const messages = sessions.get(history[1]!)?.messages || []
  155. send({ session_id: history[1], messages,
  156. pagination: {offset: 0, limit: 100, returned: messages.length, total: messages.length, has_more: false} })
  157. return
  158. }
  159. if (url.pathname === '/api/files/download') {
  160. res.setHeader('content-type', 'text/plain')
  161. res.end('Fixture report\n')
  162. return
  163. }
  164. send({ ok: true })
  165. })
  166. const wss = new WebSocketServer({ server: upstream, path: '/api/ws' })
  167. wss.on('connection', (socket) => {
  168. const runtimes = new Map<string, string>()
  169. socket.send(
  170. JSON.stringify({
  171. method: 'event',
  172. params: { type: 'gateway.ready', payload: { capabilities: [] } },
  173. }),
  174. )
  175. socket.on('message', (raw) => {
  176. const f = JSON.parse(String(raw))
  177. calls.push({ method: f.method, params: f.params })
  178. const respond = (result: unknown) => socket.send(JSON.stringify({ id: f.id, result }))
  179. const event = (type: string, payload: unknown, sessionId: string) => {
  180. if (socket.readyState === 1)
  181. socket.send(
  182. JSON.stringify({
  183. method: 'event',
  184. params: { type, payload, session_id: sessionId, profile: 'default' },
  185. }),
  186. )
  187. }
  188. if (f.method === 'profiles.list') {
  189. respond({ profiles: [...profileState.values()] })
  190. return
  191. }
  192. if (f.method === 'profiles.configure') {
  193. const profile = profileState.get(String(f.params.name))
  194. if (!profile) { respond({ error: 'profile_not_found' }); return }
  195. for (const [namespace, value] of Object.entries(f.params.ui_meta ?? {})) {
  196. profile.ui_meta[namespace] = value
  197. profile.ui_meta_revisions[namespace] = (profile.ui_meta_revisions[namespace] ?? 0) + 1
  198. }
  199. respond({ profile })
  200. return
  201. }
  202. if (f.method === 'session.create' || f.method === 'session.resume') {
  203. let stored = f.method === 'session.resume' ? sessions.get(f.params.session_id) : undefined
  204. if (!stored) {
  205. stored = {
  206. id: randomUUID(),
  207. profile: f.params.profile,
  208. source: String(f.params.source ?? 'web'),
  209. title: String(f.params.title ?? '新对话'),
  210. messages: [],
  211. running: false,
  212. }
  213. sessions.set(stored.id, stored)
  214. }
  215. // A live Hermes resume joins the same runtime, including other viewers.
  216. const runtimeId = latestRuntimeBySession.get(stored.id) ?? randomUUID()
  217. runtimes.set(runtimeId, stored.id)
  218. latestRuntimeBySession.set(stored.id, runtimeId)
  219. respond({
  220. session_id: runtimeId,
  221. stored_session_id: stored.id,
  222. session_key: stored.id,
  223. running: stored.running,
  224. info: { profile_name: stored.profile, cwd: stored.cwd },
  225. })
  226. return
  227. }
  228. const stored = sessions.get(runtimes.get(f.params.session_id) ?? '')
  229. if (f.method === 'session.cwd.set' && stored) {
  230. stored.cwd = String(f.params.cwd)
  231. respond({ cwd: stored.cwd })
  232. return
  233. }
  234. if (f.method === 'prompt.submit' && stored) {
  235. stored.running = true
  236. const requestedTitle = /^\[cross-client-title:([^\]\r\n]+)\]/
  237. .exec(String(f.params.text))?.[1]?.trim()
  238. if (requestedTitle) {
  239. stored.title = requestedTitle
  240. setTimeout(() => broadcastUpstreamEvent('sessions.changed', {}), 0)
  241. }
  242. stored.messages.push({
  243. id: randomUUID(),
  244. role: 'user',
  245. content: f.params.text,
  246. timestamp: Date.now() / 1000,
  247. })
  248. respond({ status: 'streaming' })
  249. const name = /你是 (.*?)。/.exec(f.params.text)?.[1] || '助手'
  250. const requested = /本轮用户指定成员:([^\n]*)/.exec(f.params.text)?.[1] ?? ''
  251. const delegates = f.params.text.includes('你是管理员。') && !f.params.text.includes('本批次执行结果:') && requested.startsWith('@')
  252. const markdownStream = String(f.params.text).includes('[streaming-markdown]')
  253. const crossClientRun = String(f.params.text).includes('[cross-client-live]')
  254. const markdownPrefix = '# 流式标题\n\n**即时格式化**\n\n- 第一项\n- 第二项\n\n```ts\nconst answer = 42' + (String(f.params.text).includes('[long]') ? `\n\x60\x60\x60\n\n${'这是持续生成的长回复段落。\n\n'.repeat(80)}流式末尾标记\n\n\x60\x60\x60ts\nconst tail = 1` : '')
  255. const markdownFinal = `${markdownPrefix}\n\x60\x60\x60\n\n| 名称 | 数量 |\n| --- | --- |\n| 项目 | 2 |\n\n最终完整标记`
  256. const text = markdownStream ? markdownFinal : `我是${name}。已按角色规则处理这条消息。\n\n- 会话独立保存\n- 可以继续交流\n\n[报告](/tmp/workspace-report.txt)${delegates ? `\n请${requested}处理任务。` : ''}`
  257. event('message.start', {}, f.params.session_id)
  258. if (crossClientRun) event('tool.start', { tool_id: 'cross-client-tool', name: 'read_file' }, f.params.session_id)
  259. else setTimeout(() => event('message.delta', { text: markdownStream ? markdownPrefix : text.slice(0, 12) }, f.params.session_id), 80)
  260. const complete = () => {
  261. if (crossClientRun) event('tool.complete', { tool_id: 'cross-client-tool', name: 'read_file', result: 'ok' }, f.params.session_id)
  262. stored!.running = false
  263. stored!.messages.push({
  264. id: randomUUID(),
  265. role: 'assistant',
  266. content: text,
  267. timestamp: Date.now() / 1000,
  268. })
  269. event('message.complete', { text, status: 'complete' }, f.params.session_id)
  270. }
  271. if (crossClientRun || markdownStream || f.params.text.includes('[hold-workspace]')) heldReplies.push(complete)
  272. else setTimeout(complete, 250)
  273. return
  274. }
  275. if (f.method === 'session.interrupt' && stored) stored.running = false
  276. if (f.method === 'file.attach') {
  277. respond({ attached: true, ref_text: '@file:fixture-upload.txt' })
  278. return
  279. }
  280. respond({ ok: true, status: 'interrupted' })
  281. })
  282. })
  283. await new Promise<void>((resolve) => upstream.listen(upstreamPort, '127.0.0.1', resolve))
  284. const config = loadServerConfig({
  285. HERMES_YAOYAO_HOME: home,
  286. HERMES_YAOYAO_PORT: String(port),
  287. HERMES_YAOYAO_UPSTREAM: `http://127.0.0.1:${upstreamPort}`,
  288. HERMES_YAOYAO_UPSTREAM_USERNAME: 'fixture',
  289. HERMES_YAOYAO_UPSTREAM_PASSWORD: 'fixture',
  290. HERMES_YAOYAO_ALLOWED_HOSTS: '127.0.0.1,localhost',
  291. })
  292. // Synthetic credentials are seeded only into this disposable fixture directory.
  293. const usersPath = join(home, 'users.json')
  294. if (!existsSync(usersPath)) {
  295. const salt = randomBytes(16),
  296. now = Date.now()
  297. writeFileSync(
  298. usersPath,
  299. JSON.stringify({
  300. version: 1,
  301. users: [
  302. {
  303. id: randomUUID(),
  304. username: 'fixture',
  305. normalizedUsername: 'fixture',
  306. role: 'admin',
  307. enabled: true,
  308. mustChangePassword: false,
  309. salt: salt.toString('base64'),
  310. passwordHash: scryptSync('fixture-pass', salt, 32, {
  311. N: 2 ** 14,
  312. r: 8,
  313. p: 1,
  314. maxmem: 64 * 1024 * 1024,
  315. }).toString('base64'),
  316. authVersion: 1,
  317. createdAt: now,
  318. updatedAt: now,
  319. },
  320. ],
  321. }),
  322. { mode: 0o600 },
  323. )
  324. }
  325. const auth = new LocalAuthStore(home, false)
  326. const runtime = createApplication({ config, auth }),
  327. node = createNodeServer(runtime)
  328. runtime.app.use(serve(resolve('dist')))
  329. runtime.app.use((ctx) => {
  330. if (!ctx.path.startsWith('/api/')) {
  331. ctx.type = 'html'
  332. ctx.body = readFileSync(resolve('dist/index.html'))
  333. }
  334. })
  335. await new Promise<void>((resolve) => node.server.listen(port, '127.0.0.1', resolve))
  336. process.stdout.write(`Workspace fixture http://127.0.0.1:${port}; home=${home}\n`)
  337. for (const signal of ['SIGTERM', 'SIGINT'])
  338. process.once(signal, () => {
  339. void node.close().then(() => {
  340. for (const socket of wss.clients) socket.terminate()
  341. wss.close()
  342. upstream.close()
  343. })
  344. })