built-lib.e2e.ts 10 KB

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