built-lib.e2e.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. 'packages/session/session-projection/lib/index.js',
  27. ].every(path => existsSync(artifact(path)))
  28. describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => {
  29. it('runs root and Agent-scoped calls through generated bundles and real HTTP', async () => {
  30. const urls = Object.fromEntries(Object.entries({
  31. agent: 'packages/core/agent/lib/index.js',
  32. apiGatewayClient: 'packages/api/gateway/lib/client.js',
  33. apiGatewayHost: 'packages/api/gateway/lib/index.js',
  34. connectionClient: 'packages/client/connection/lib/client.js',
  35. connectionHost: 'packages/client/connection/lib/index.js',
  36. goal: 'packages/goal/goal/lib/index.js',
  37. goalTypert: 'packages/goal/goal/lib/typert.host.js',
  38. registryClient: 'packages/typert/registry/lib/client.js',
  39. registryHost: 'packages/typert/registry/lib/index.js',
  40. remotesClient: 'packages/api/remotes/lib/client.js',
  41. session: 'packages/core/session/lib/index.js',
  42. sessionProjections: 'packages/session/session-projection/lib/index.js',
  43. }).map(([key, path]) => [key, artifactUrl(path)]))
  44. const script = `
  45. import { createServer } from 'node:http'
  46. import * as cordis from '@deepseek-ai/cordis'
  47. const urls = ${JSON.stringify(urls)}
  48. const { Context } = cordis
  49. const { default: AgentRegistry } = await import(urls.agent)
  50. const connectionHost = await import(urls.connectionHost)
  51. const { default: TypertRemoteService } = await import(urls.apiGatewayHost)
  52. const { default: GoalService } = await import(urls.goal)
  53. const { default: SessionProjectionRegistry } = await import(urls.sessionProjections)
  54. const { TYPERT } = await import(urls.goalTypert)
  55. const { default: TypertRegistry } = await import(urls.registryHost)
  56. const { Session, SessionId } = await import(urls.session)
  57. const routes = []
  58. const credentialRecords = new Map()
  59. const host = new Context()
  60. host.provide('webServer', {
  61. register(route) {
  62. routes.push(route)
  63. return () => { routes.splice(routes.indexOf(route), 1) }
  64. },
  65. tapIndex() { return () => {} },
  66. port: 0,
  67. })
  68. host.provide('credentials', {
  69. readRecord(key) { return Promise.resolve(credentialRecords.get(key)) },
  70. async modifyRecord(key, mutate) {
  71. const current = credentialRecords.get(key)
  72. const next = await mutate(current)
  73. if (next !== undefined) credentialRecords.set(key, next)
  74. return next ?? current
  75. },
  76. })
  77. await host.plugin({ inject: connectionHost.inject, apply: connectionHost.apply })
  78. await host.plugin(TypertRegistry)
  79. await host.plugin(AgentRegistry)
  80. await host.plugin(TypertRemoteService)
  81. await host.plugin(SessionProjectionRegistry)
  82. await host.plugin(GoalService)
  83. host.typert.register(TYPERT)
  84. const makeAgent = rawId => {
  85. const session = new Session(SessionId(rawId))
  86. return {
  87. id: session.id,
  88. options: {},
  89. session,
  90. ctx: host.extend(),
  91. status: 'idle',
  92. acceptsNextStep: false,
  93. send() {},
  94. updateInbox() { return 'not-found' },
  95. followup() {},
  96. steer() { return { outcome: Promise.resolve({ status: 'rejected' }) } },
  97. inject(input) { session.append('user/message', input, { surfaceOp: 'append' }) },
  98. reserveTurnAdmission() {},
  99. cancel() {},
  100. whenIdle() { return Promise.resolve() },
  101. }
  102. }
  103. const rootAgent = makeAgent('built-root-agent')
  104. const scopedAgent = makeAgent('built-scoped-agent')
  105. host.agents.register(rootAgent)
  106. host.agents.register(scopedAgent)
  107. if (routes.length !== 1 || routes[0].path !== '/api') {
  108. throw new Error('Connection did not register exactly one /api route')
  109. }
  110. const server = createServer((request, response) => {
  111. if ((request.url ?? '/').startsWith('/?')) {
  112. if (host.connection.authorizeIndex(request, response)) {
  113. response.writeHead(200, { 'content-type': 'text/html' })
  114. response.end('<body>shell</body>')
  115. }
  116. return
  117. }
  118. void routes[0].handler(request, response)
  119. })
  120. await new Promise(resolveListen => server.listen(0, '127.0.0.1', resolveListen))
  121. const address = server.address()
  122. if (address === null || typeof address === 'string') throw new Error('HTTP server has no TCP address')
  123. const origin = 'http://127.0.0.1:' + String(address.port)
  124. const login = await fetch(host.connection.authenticatedUrl(origin), { redirect: 'manual' })
  125. const setCookie = login.headers.get('set-cookie')
  126. if (login.status !== 303 || setCookie === null) throw new Error('browser token exchange failed')
  127. const cookie = setCookie.split(';', 1)[0]
  128. const hostFetch = globalThis.fetch
  129. globalThis.fetch = (input, init = {}) => {
  130. const headers = new Headers(init.headers)
  131. headers.set('cookie', cookie)
  132. return hostFetch(input, { ...init, headers })
  133. }
  134. const handoffs = new Map()
  135. globalThis.window = {
  136. __ModuleLoader__: {
  137. load(handoff) { handoffs.set(handoff.id, handoff) },
  138. },
  139. }
  140. globalThis.location = { hostname: '127.0.0.1', origin, search: '' }
  141. await import(urls.registryClient)
  142. await import(urls.connectionClient)
  143. await import(urls.apiGatewayClient)
  144. await import(urls.remotesClient)
  145. const instantiate = id => {
  146. const handoff = handoffs.get(id)
  147. if (handoff === undefined) throw new Error('missing Client bundle handoff ' + id)
  148. return handoff.factory(specifier => {
  149. if (specifier === '@deepseek-ai/cordis') return cordis
  150. throw new Error('unexpected Client external ' + specifier)
  151. })
  152. }
  153. const client = new Context()
  154. for (const id of [
  155. '@deepseek-ai/dsh-typert-registry',
  156. '@deepseek-ai/dsh-client-connection',
  157. '@deepseek-ai/dsh-api-gateway',
  158. '@deepseek-ai/dsh-api-remotes',
  159. ]) {
  160. const plugin = instantiate(id)
  161. await client.plugin({ inject: plugin.inject, apply: plugin.apply })
  162. }
  163. client.typert.contexts.registerClient('agent', {
  164. identity: candidate => candidate.builtAgentId,
  165. })
  166. let invalidRejected = false
  167. try {
  168. await client.remote.goals.create(rootAgent.id, { objective: 1 })
  169. } catch {
  170. invalidRejected = true
  171. }
  172. // Every generated method resolves to the RemoteResult envelope; the
  173. // business values below are what the assertions pin.
  174. const rootResult = await client.remote.goals.create(rootAgent.id, { objective: 'root goal' })
  175. const rootEdit = await client.remote.goals.edit(
  176. rootAgent.id,
  177. rootResult.value.ref,
  178. { objective: 'edited root goal' },
  179. )
  180. const agentContext = client.extend({ builtAgentId: scopedAgent.id })
  181. const scopedResult = await agentContext.remote.goals.create({ objective: 'scoped goal', maxGoalRounds: 3 })
  182. const result = {
  183. invalidRejected,
  184. rootResult: rootResult.value,
  185. rootEdit: rootEdit.value,
  186. scopedResult: scopedResult.value,
  187. rootGoal: host.goals.get(rootAgent)?.objective,
  188. scopedGoal: host.goals.get(scopedAgent)?.objective,
  189. rootEvents: rootAgent.session.events.length,
  190. scopedEvents: scopedAgent.session.events.length,
  191. }
  192. await client.fiber.dispose()
  193. await new Promise((resolveClose, rejectClose) => server.close(error => {
  194. if (error === undefined) resolveClose()
  195. else rejectClose(error)
  196. }))
  197. await host.fiber.dispose()
  198. console.log(JSON.stringify(result))
  199. `
  200. const result = await runPlainNode(script)
  201. expect(result.exitCode, `stderr:\n${result.stderr}`).toBe(0)
  202. const output = JSON.parse(result.stdout.trim().split('\n').at(-1) ?? '{}') as {
  203. invalidRejected: boolean
  204. rootResult: { ref: { id: string; revision: number } }
  205. rootEdit: { objective: string; revision: number }
  206. scopedResult: { ref: { id: string; revision: number } }
  207. rootGoal: string
  208. scopedGoal: string
  209. rootEvents: number
  210. scopedEvents: number
  211. }
  212. expect(output).toMatchObject({
  213. invalidRejected: true,
  214. rootResult: { ref: { revision: 1 } },
  215. rootEdit: { objective: 'edited root goal', revision: 2 },
  216. scopedResult: { ref: { revision: 1 } },
  217. rootGoal: 'edited root goal',
  218. scopedGoal: 'scoped goal',
  219. rootEvents: 2,
  220. scopedEvents: 1,
  221. })
  222. expect(output.rootResult.ref.id).toMatch(/^goal-/)
  223. expect(output.scopedResult.ref.id).toMatch(/^goal-/)
  224. }, 60_000)
  225. })
  226. /** Execute one ESM script without tsx or a TypeScript loader. */
  227. function runPlainNode(script: string): Promise<{
  228. readonly exitCode: number | null
  229. readonly stdout: string
  230. readonly stderr: string
  231. }> {
  232. return new Promise((resolveRun) => {
  233. execFile(process.execPath, ['--input-type=module', '-e', script], {
  234. cwd: packageDir,
  235. encoding: 'utf8',
  236. timeout: 55_000,
  237. }, (error, stdout, stderr) => {
  238. resolveRun({
  239. exitCode: error === null ? 0 : typeof error.code === 'number' ? error.code : null,
  240. stdout,
  241. stderr,
  242. })
  243. })
  244. })
  245. }