built-lib.e2e.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import { execFile } from 'node:child_process'
  2. import { existsSync } from 'node:fs'
  3. import { join, resolve } from 'node:path'
  4. import { fileURLToPath, pathToFileURL } from 'node:url'
  5. import { describe, expect, it } from 'vitest'
  6. /**
  7. * Built-artifact smoke for the first generated Remote: plain Node boots the
  8. * Host and Browser bundle handoffs, then crosses the shared `/api` HTTP route.
  9. */
  10. const packageDir = fileURLToPath(new URL('..', import.meta.url))
  11. const root = resolve(packageDir, '../../..')
  12. const artifact = (path: string): string => join(root, path)
  13. const artifactUrl = (path: string): string => pathToFileURL(artifact(path)).href
  14. const requiredArtifacts = [
  15. 'packages/client/connection/lib/client.js',
  16. 'packages/client/connection/lib/index.js',
  17. 'packages/api/remotes/lib/client.js',
  18. 'packages/core/agent/lib/index.js',
  19. 'packages/core/session/lib/index.js',
  20. 'packages/goal/goal/lib/index.js',
  21. 'packages/goal/goal/lib/typert.host.js',
  22. 'packages/api/gateway/lib/client.js',
  23. 'packages/api/gateway/lib/index.js',
  24. 'packages/typert/registry/lib/client.js',
  25. 'packages/typert/registry/lib/index.js',
  26. ].every(path => existsSync(artifact(path)))
  27. describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => {
  28. it('runs root and Agent-scoped calls through generated bundles and real HTTP', async () => {
  29. const urls = Object.fromEntries(Object.entries({
  30. agent: 'packages/core/agent/lib/index.js',
  31. apiGatewayClient: 'packages/api/gateway/lib/client.js',
  32. apiGatewayHost: 'packages/api/gateway/lib/index.js',
  33. connectionClient: 'packages/client/connection/lib/client.js',
  34. connectionHost: 'packages/client/connection/lib/index.js',
  35. goal: 'packages/goal/goal/lib/index.js',
  36. goalTypert: 'packages/goal/goal/lib/typert.host.js',
  37. registryClient: 'packages/typert/registry/lib/client.js',
  38. registryHost: 'packages/typert/registry/lib/index.js',
  39. remotesClient: 'packages/api/remotes/lib/client.js',
  40. session: 'packages/core/session/lib/index.js',
  41. }).map(([key, path]) => [key, artifactUrl(path)]))
  42. const script = `
  43. import { createServer } from 'node:http'
  44. import * as cordis from '@deepseek-ai/cordis'
  45. const urls = ${JSON.stringify(urls)}
  46. const { Context } = cordis
  47. const { default: AgentRegistry } = await import(urls.agent)
  48. const connectionHost = await import(urls.connectionHost)
  49. const { default: TypertGatewayService } = await import(urls.apiGatewayHost)
  50. const { default: GoalService } = await import(urls.goal)
  51. const { TYPERT } = await import(urls.goalTypert)
  52. const { default: TypertRegistry } = await import(urls.registryHost)
  53. const { Session, SessionId } = await import(urls.session)
  54. const routes = []
  55. const host = new Context()
  56. host.provide('httpServer', {
  57. register(route) {
  58. routes.push(route)
  59. return () => { routes.splice(routes.indexOf(route), 1) }
  60. },
  61. tapIndex() { return () => {} },
  62. port: 0,
  63. })
  64. await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply })
  65. await host.plugin(TypertRegistry)
  66. await host.plugin(AgentRegistry)
  67. await host.plugin(TypertGatewayService)
  68. await host.plugin(GoalService)
  69. host.typert.register(TYPERT)
  70. const makeAgent = rawId => {
  71. const session = new Session(SessionId(rawId))
  72. return {
  73. id: session.id,
  74. options: {},
  75. session,
  76. ctx: host.extend(),
  77. status: 'idle',
  78. acceptsNextStep: false,
  79. send() {},
  80. updateInbox() { return 'not-found' },
  81. followup() {},
  82. steer() { return { outcome: Promise.resolve({ status: 'rejected' }) } },
  83. inject(input) { session.append('user/message', input, { surfaceOp: 'append' }) },
  84. reserveTurnAdmission() {},
  85. cancel() {},
  86. whenIdle() { return Promise.resolve() },
  87. }
  88. }
  89. const rootAgent = makeAgent('built-root-agent')
  90. const scopedAgent = makeAgent('built-scoped-agent')
  91. host.agents.register(rootAgent)
  92. host.agents.register(scopedAgent)
  93. if (routes.length !== 1 || routes[0].path !== '/api') {
  94. throw new Error('Connection did not register exactly one /api route')
  95. }
  96. const server = createServer((request, response) => { void routes[0].handler(request, response) })
  97. await new Promise(resolveListen => server.listen(0, '127.0.0.1', resolveListen))
  98. const address = server.address()
  99. if (address === null || typeof address === 'string') throw new Error('HTTP server has no TCP address')
  100. const origin = 'http://127.0.0.1:' + String(address.port)
  101. const handoffs = new Map()
  102. globalThis.window = {
  103. __ModuleLoader__: {
  104. load(handoff) { handoffs.set(handoff.id, handoff) },
  105. },
  106. }
  107. globalThis.location = { hostname: '127.0.0.1', origin, search: '' }
  108. await import(urls.registryClient)
  109. await import(urls.connectionClient)
  110. await import(urls.apiGatewayClient)
  111. await import(urls.remotesClient)
  112. const instantiate = id => {
  113. const handoff = handoffs.get(id)
  114. if (handoff === undefined) throw new Error('missing Client bundle handoff ' + id)
  115. return handoff.factory(specifier => {
  116. if (specifier === '@deepseek-ai/cordis') return cordis
  117. throw new Error('unexpected Client external ' + specifier)
  118. })
  119. }
  120. const client = new Context()
  121. for (const id of [
  122. '@deepseek-ai/dsh-typert-registry',
  123. '@deepseek-ai/dsh-client-connection',
  124. '@deepseek-ai/dsh-api-gateway',
  125. '@deepseek-ai/dsh-api-remotes',
  126. ]) {
  127. const plugin = instantiate(id)
  128. await client.plugin({ inject: plugin.inject, apply: plugin.apply })
  129. }
  130. client.typert.contexts.registerClient('agent', {
  131. identity: candidate => candidate.builtAgentId,
  132. })
  133. let invalidRejected = false
  134. try {
  135. await client.remote.goals.create(rootAgent.id, { objective: 1 })
  136. } catch {
  137. invalidRejected = true
  138. }
  139. const rootResult = await client.remote.goals.create(rootAgent.id, { objective: 'root goal' })
  140. const rootEdit = await client.remote.goals.edit(
  141. rootAgent.id,
  142. rootResult.ref,
  143. { objective: 'edited root goal' },
  144. )
  145. const agentContext = client.extend({ builtAgentId: scopedAgent.id })
  146. const scopedResult = await agentContext.remote.goals.create({ objective: 'scoped goal', maxGoalRounds: 3 })
  147. const result = {
  148. invalidRejected,
  149. rootResult,
  150. rootEdit,
  151. scopedResult,
  152. rootGoal: host.goals.get(rootAgent)?.objective,
  153. scopedGoal: host.goals.get(scopedAgent)?.objective,
  154. rootEvents: rootAgent.session.events.length,
  155. scopedEvents: scopedAgent.session.events.length,
  156. }
  157. await client.fiber.dispose()
  158. await new Promise((resolveClose, rejectClose) => server.close(error => {
  159. if (error === undefined) resolveClose()
  160. else rejectClose(error)
  161. }))
  162. await host.fiber.dispose()
  163. console.log(JSON.stringify(result))
  164. `
  165. const result = await runPlainNode(script)
  166. expect(result.exitCode, `stderr:\n${result.stderr}`).toBe(0)
  167. const output = JSON.parse(result.stdout.trim().split('\n').at(-1) ?? '{}') as {
  168. invalidRejected: boolean
  169. rootResult: { ref: { id: string; revision: number } }
  170. rootEdit: { objective: string; revision: number }
  171. scopedResult: { ref: { id: string; revision: number } }
  172. rootGoal: string
  173. scopedGoal: string
  174. rootEvents: number
  175. scopedEvents: number
  176. }
  177. expect(output).toMatchObject({
  178. invalidRejected: true,
  179. rootResult: { ref: { revision: 1 } },
  180. rootEdit: { objective: 'edited root goal', revision: 2 },
  181. scopedResult: { ref: { revision: 1 } },
  182. rootGoal: 'edited root goal',
  183. scopedGoal: 'scoped goal',
  184. rootEvents: 2,
  185. scopedEvents: 1,
  186. })
  187. expect(output.rootResult.ref.id).toMatch(/^goal-/)
  188. expect(output.scopedResult.ref.id).toMatch(/^goal-/)
  189. }, 60_000)
  190. })
  191. /** Execute one ESM script without tsx or a TypeScript loader. */
  192. function runPlainNode(script: string): Promise<{
  193. readonly exitCode: number | null
  194. readonly stdout: string
  195. readonly stderr: string
  196. }> {
  197. return new Promise((resolveRun) => {
  198. execFile(process.execPath, ['--input-type=module', '-e', script], {
  199. cwd: packageDir,
  200. encoding: 'utf8',
  201. timeout: 55_000,
  202. }, (error, stdout, stderr) => {
  203. resolveRun({
  204. exitCode: error === null ? 0 : typeof error.code === 'number' ? error.code : null,
  205. stdout,
  206. stderr,
  207. })
  208. })
  209. })
  210. }