built-lib.e2e.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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: TypertRemoteService } = 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('webServer', {
  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(TypertRemoteService)
  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. // Every generated method resolves to the RemoteResult envelope; the
  140. // business values below are what the assertions pin.
  141. const rootResult = await client.remote.goals.create(rootAgent.id, { objective: 'root goal' })
  142. const rootEdit = await client.remote.goals.edit(
  143. rootAgent.id,
  144. rootResult.value.ref,
  145. { objective: 'edited root goal' },
  146. )
  147. const agentContext = client.extend({ builtAgentId: scopedAgent.id })
  148. const scopedResult = await agentContext.remote.goals.create({ objective: 'scoped goal', maxGoalRounds: 3 })
  149. const result = {
  150. invalidRejected,
  151. rootResult: rootResult.value,
  152. rootEdit: rootEdit.value,
  153. scopedResult: scopedResult.value,
  154. rootGoal: host.goals.get(rootAgent)?.objective,
  155. scopedGoal: host.goals.get(scopedAgent)?.objective,
  156. rootEvents: rootAgent.session.events.length,
  157. scopedEvents: scopedAgent.session.events.length,
  158. }
  159. await client.fiber.dispose()
  160. await new Promise((resolveClose, rejectClose) => server.close(error => {
  161. if (error === undefined) resolveClose()
  162. else rejectClose(error)
  163. }))
  164. await host.fiber.dispose()
  165. console.log(JSON.stringify(result))
  166. `
  167. const result = await runPlainNode(script)
  168. expect(result.exitCode, `stderr:\n${result.stderr}`).toBe(0)
  169. const output = JSON.parse(result.stdout.trim().split('\n').at(-1) ?? '{}') as {
  170. invalidRejected: boolean
  171. rootResult: { ref: { id: string; revision: number } }
  172. rootEdit: { objective: string; revision: number }
  173. scopedResult: { ref: { id: string; revision: number } }
  174. rootGoal: string
  175. scopedGoal: string
  176. rootEvents: number
  177. scopedEvents: number
  178. }
  179. expect(output).toMatchObject({
  180. invalidRejected: true,
  181. rootResult: { ref: { revision: 1 } },
  182. rootEdit: { objective: 'edited root goal', revision: 2 },
  183. scopedResult: { ref: { revision: 1 } },
  184. rootGoal: 'edited root goal',
  185. scopedGoal: 'scoped goal',
  186. rootEvents: 2,
  187. scopedEvents: 1,
  188. })
  189. expect(output.rootResult.ref.id).toMatch(/^goal-/)
  190. expect(output.scopedResult.ref.id).toMatch(/^goal-/)
  191. }, 60_000)
  192. })
  193. /** Execute one ESM script without tsx or a TypeScript loader. */
  194. function runPlainNode(script: string): Promise<{
  195. readonly exitCode: number | null
  196. readonly stdout: string
  197. readonly stderr: string
  198. }> {
  199. return new Promise((resolveRun) => {
  200. execFile(process.execPath, ['--input-type=module', '-e', script], {
  201. cwd: packageDir,
  202. encoding: 'utf8',
  203. timeout: 55_000,
  204. }, (error, stdout, stderr) => {
  205. resolveRun({
  206. exitCode: error === null ? 0 : typeof error.code === 'number' ? error.code : null,
  207. stdout,
  208. stderr,
  209. })
  210. })
  211. })
  212. }