gateway.host.spec.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. import { createServer } from 'node:http'
  2. import type { AddressInfo } from 'node:net'
  3. import { describe, expect, it } from 'vitest'
  4. import { Context, Service, symbols } from '@deepseek-ai/cordis'
  5. import { z } from 'zod'
  6. import { apply as applyConnection, inject as connectionInject } from '@deepseek-ai/dsh-client-connection'
  7. import type { HostConnectionHandle } from '@deepseek-ai/dsh-client-connection'
  8. import type { WebServer, WebRoute } from '@deepseek-ai/dsh-host-webserver'
  9. import {
  10. bindTypertRemote,
  11. Remote,
  12. RemoteError,
  13. RemoteScope,
  14. type InvocationDescriptor,
  15. type TypertContext,
  16. type TypertLookup,
  17. type TypertLookupProvider,
  18. } from '@deepseek-ai/dsh-typert-protocol'
  19. import TypertRegistry, { type TypertContribution } from '@deepseek-ai/dsh-typert-registry'
  20. import TypertGatewayService, { TypertGatewayError } from '@deepseek-ai/dsh-api-gateway'
  21. import { provideBrowserCredentials } from './browser-credentials.ts'
  22. interface FixtureAgent {
  23. readonly id: string
  24. }
  25. interface MarkedContext extends Context {
  26. readonly fixtureScope?: string
  27. }
  28. declare module '@deepseek-ai/dsh-typert-protocol' {
  29. interface TypertLookupMap {
  30. gatewayFixture: TypertLookup<FixtureAgent, string>
  31. gatewayFixtureAlias: TypertLookup<FixtureAgent, string>
  32. }
  33. interface TypertContextMap {
  34. gatewayFixture: TypertContext<string>
  35. }
  36. interface RemoteErrorDetailsMap {
  37. 'session/agent-busy': { readonly reason: string }
  38. }
  39. }
  40. const emptyModel: TypertContribution['model'] = {
  41. services: [],
  42. events: [],
  43. objects: [],
  44. }
  45. class GoalService extends Service {
  46. readonly typertRemote = bindTypertRemote(this, 'goals')
  47. readonly calls: string[] = []
  48. lastSignal: AbortSignal | undefined
  49. nextResult: unknown = undefined
  50. businessError: Error | undefined
  51. constructor(ctx: Context) {
  52. super(ctx, 'goals')
  53. }
  54. @Remote
  55. create(agent: FixtureAgent, request: { readonly title: string }, signal: AbortSignal): unknown {
  56. this.calls.push('create')
  57. this.lastSignal = signal
  58. return {
  59. agentId: agent.id,
  60. title: request.title,
  61. scope: (this.ctx as MarkedContext).fixtureScope ?? 'root',
  62. }
  63. }
  64. @RemoteScope('gatewayFixture')
  65. rename(request: { readonly title: string }): unknown {
  66. this.calls.push('rename')
  67. return { title: request.title, scope: (this.ctx as MarkedContext).fixtureScope ?? 'root' }
  68. }
  69. @Remote
  70. passthrough(value: unknown): unknown {
  71. this.calls.push('passthrough')
  72. return this.nextResult === undefined ? value : this.nextResult
  73. }
  74. @Remote
  75. maybe(value: string | null | undefined): string | null | undefined {
  76. this.calls.push('maybe')
  77. return value
  78. }
  79. @Remote
  80. fail(request: unknown): never {
  81. void request
  82. this.calls.push('fail')
  83. throw this.businessError ?? new Error('fixture business failure')
  84. }
  85. strictOnly(request: { readonly title: string }): unknown {
  86. this.calls.push('strictOnly')
  87. return this.nextResult === undefined ? request : this.nextResult
  88. }
  89. }
  90. type FakeRpcResult =
  91. | { readonly ok: true; readonly value: unknown }
  92. | { readonly ok: false; readonly error: { readonly code: string; readonly message: string; readonly details: object } }
  93. type FakeRpcHandler = (endpoint: string, payload: unknown, signal: AbortSignal) => Promise<FakeRpcResult>
  94. class FakeConnectionService extends Service {
  95. channel: string | undefined
  96. matches: ((endpoint: string) => boolean) | undefined
  97. handler: FakeRpcHandler | undefined
  98. constructor(ctx: Context) {
  99. super(ctx, 'connection')
  100. }
  101. get rpc() {
  102. const owner = this.ctx
  103. return {
  104. intercept: (
  105. channel: string,
  106. matches: (endpoint: string) => boolean,
  107. handler: FakeRpcHandler,
  108. ) =>
  109. owner.effect(() => {
  110. this.channel = channel
  111. this.matches = matches
  112. this.handler = handler
  113. return () => {
  114. this.channel = undefined
  115. this.matches = undefined
  116. this.handler = undefined
  117. }
  118. }),
  119. }
  120. }
  121. requestRejection(): undefined {
  122. return undefined
  123. }
  124. }
  125. function fakeHttpServer(routes: WebRoute[]): Pick<WebServer, 'register' | 'tapIndex' | 'port'> {
  126. return {
  127. register(route) {
  128. if (routes.some(candidate => candidate.kind === route.kind && candidate.path === route.path)) {
  129. throw new Error(`duplicate route ${route.path}`)
  130. }
  131. routes.push(route)
  132. return () => { routes.splice(routes.indexOf(route), 1) }
  133. },
  134. tapIndex: () => () => {},
  135. port: 0,
  136. }
  137. }
  138. async function serveRoute(route: WebRoute): Promise<{ readonly origin: string; close(): Promise<void> }> {
  139. const server = createServer((request, response) => {
  140. void route.handler(request, response)
  141. })
  142. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  143. const address = server.address() as AddressInfo
  144. return {
  145. origin: `http://127.0.0.1:${String(address.port)}`,
  146. close: () => new Promise<void>((resolve, reject) => {
  147. server.close((error) => {
  148. if (error === undefined || error === null) resolve()
  149. else reject(error)
  150. })
  151. }),
  152. }
  153. }
  154. /** Exchange a Connection launch token without mounting the frontend fallback. */
  155. function browserCookie(connection: HostConnectionHandle, origin: string): string {
  156. const target = new URL(connection.authenticatedUrl(origin))
  157. let setCookie: string | undefined
  158. connection.authorizeIndex({
  159. method: 'GET',
  160. url: `${target.pathname}${target.search}`,
  161. headers: { host: target.host },
  162. }, {
  163. writeHead(_status, headers) { setCookie = headers?.['set-cookie'] },
  164. end() {},
  165. })
  166. if (setCookie === undefined) throw new Error('gateway fixture did not receive an authentication cookie')
  167. return setCookie.split(';', 1)[0]!
  168. }
  169. class FirstSharedService extends Service {
  170. readonly typertRemote = bindTypertRemote(this, 'firstShared', { namespace: 'shared' })
  171. constructor(ctx: Context) {
  172. super(ctx, 'firstShared')
  173. }
  174. @Remote
  175. run(value: string): string {
  176. return value
  177. }
  178. }
  179. class SecondSharedService extends Service {
  180. readonly typertRemote = bindTypertRemote(this, 'secondShared', { namespace: 'shared' })
  181. constructor(ctx: Context) {
  182. super(ctx, 'secondShared')
  183. }
  184. @Remote
  185. run(value: string): string {
  186. return value
  187. }
  188. }
  189. class DefaultParameterService extends Service {
  190. readonly typertRemote = bindTypertRemote(this, 'defaultParameter', { namespace: 'invalid-default' })
  191. constructor(ctx: Context) {
  192. super(ctx, 'defaultParameter')
  193. }
  194. @Remote
  195. run(value = 'fallback'): string {
  196. return value
  197. }
  198. }
  199. class DestructuredParameterService extends Service {
  200. readonly typertRemote = bindTypertRemote(this, 'destructuredParameter', { namespace: 'invalid-destructure' })
  201. constructor(ctx: Context) {
  202. super(ctx, 'destructuredParameter')
  203. }
  204. @Remote
  205. run({ value }: { readonly value: string }): string {
  206. return value
  207. }
  208. }
  209. class RestParameterService extends Service {
  210. readonly typertRemote = bindTypertRemote(this, 'restParameter', { namespace: 'invalid-rest' })
  211. constructor(ctx: Context) {
  212. super(ctx, 'restParameter')
  213. }
  214. @Remote
  215. run(...values: readonly unknown[]): string {
  216. return values.map(String).join(',')
  217. }
  218. }
  219. class NonFinalSignalService extends Service {
  220. readonly typertRemote = bindTypertRemote(this, 'nonFinalSignal', { namespace: 'invalid-signal' })
  221. constructor(ctx: Context) {
  222. super(ctx, 'nonFinalSignal')
  223. }
  224. @Remote
  225. run(signal: AbortSignal, value: string): string {
  226. return signal.aborted ? '' : value
  227. }
  228. }
  229. class WrongBindingService extends Service {
  230. readonly typertRemote = bindTypertRemote(this, 'notWrongBinding', { namespace: 'wrong-binding' })
  231. constructor(ctx: Context) {
  232. super(ctx, 'wrongBinding')
  233. }
  234. @Remote
  235. run(value: string): string {
  236. return value
  237. }
  238. }
  239. class ExportedMethodService extends Service {
  240. readonly typertRemote = bindTypertRemote(this, 'exportedMethod', { namespace: 'exported' })
  241. constructor(ctx: Context) {
  242. super(ctx, 'exportedMethod')
  243. }
  244. @Remote('execute')
  245. run(value: string): string {
  246. return value
  247. }
  248. }
  249. class EmptyMethodService extends Service {
  250. readonly typertRemote = bindTypertRemote(this, 'emptyMethod', { namespace: 'empty' })
  251. constructor(ctx: Context) {
  252. super(ctx, 'emptyMethod')
  253. }
  254. @Remote
  255. ping(): string {
  256. return 'pong'
  257. }
  258. }
  259. class CollidingWireService extends Service {
  260. readonly typertRemote = bindTypertRemote(this, 'collidingWire', { namespace: 'colliding-wire' })
  261. constructor(ctx: Context) {
  262. super(ctx, 'collidingWire')
  263. }
  264. @Remote
  265. run(agent: FixtureAgent, agentId: string): string {
  266. return `${agent.id}:${agentId}`
  267. }
  268. }
  269. class ContextWireService extends Service {
  270. readonly typertRemote = bindTypertRemote(this, 'contextWire', { namespace: 'context-wire' })
  271. constructor(ctx: Context) {
  272. super(ctx, 'contextWire')
  273. }
  274. @RemoteScope('gatewayFixture')
  275. run(agentId: string): string {
  276. return agentId
  277. }
  278. }
  279. class NoBindingService extends Service {
  280. constructor(ctx: Context) {
  281. super(ctx, 'noBinding')
  282. }
  283. run(value: string): string {
  284. return value
  285. }
  286. }
  287. class ObservedClaimService extends Service {
  288. private readonly binding = bindTypertRemote(this, 'observedClaim', { namespace: 'observed-claim' })
  289. bindingReads = 0
  290. constructor(ctx: Context) {
  291. super(ctx, 'observedClaim')
  292. }
  293. get typertRemote() {
  294. this.bindingReads += 1
  295. return this.binding
  296. }
  297. @Remote
  298. run(value: string): string {
  299. return value
  300. }
  301. }
  302. class MissingMethodService extends Service {
  303. readonly typertRemote = bindTypertRemote(this, 'missingMethod', { namespace: 'missing-method' })
  304. constructor(ctx: Context) {
  305. super(ctx, 'missingMethod')
  306. }
  307. @Remote
  308. run(value: string): string {
  309. return value
  310. }
  311. }
  312. class InheritedMethodBase extends Service {
  313. readonly typertRemote = bindTypertRemote(this, 'inheritedMethod', { namespace: 'inherited' })
  314. constructor(ctx: Context) {
  315. super(ctx, 'inheritedMethod')
  316. }
  317. @Remote
  318. run(value: string): string {
  319. return value
  320. }
  321. }
  322. class InheritedMethodService extends InheritedMethodBase {}
  323. describe('TypertGatewayService', () => {
  324. it('invokes a strict direct method with schema decoding and a live lookup', async () => {
  325. const { ctx, service } = await setup()
  326. const agent = { id: 'agent-1' }
  327. registerAgentLookup(ctx, agent)
  328. registerStrict(ctx, [createDescriptor()])
  329. const caller = ctx.extend({ fixtureScope: 'direct-caller' })
  330. const abort = new AbortController()
  331. await expect(caller.typertGateway.invoke({
  332. namespace: 'goals',
  333. method: 'create',
  334. args: { agentId: 'agent-1', request: { title: ' ship ' } },
  335. signal: abort.signal,
  336. })).resolves.toEqual({ agentId: 'agent-1', title: 'ship', scope: 'direct-caller' })
  337. expect(service.calls).toEqual(['create'])
  338. expect(service.lastSignal).toBe(abort.signal)
  339. await expect(caller.typertGateway.invoke({
  340. namespace: 'goals',
  341. method: 'create',
  342. args: { agentId: 'agent-1', request: { title: 'again' } },
  343. })).resolves.toEqual({ agentId: 'agent-1', title: 'again', scope: 'direct-caller' })
  344. expect(service.lastSignal).toBeInstanceOf(AbortSignal)
  345. expect(service.lastSignal?.aborted).toBe(false)
  346. })
  347. it('resolves strict Remote Scope identity without adding a business argument', async () => {
  348. const { ctx, service } = await setup()
  349. const scoped = ctx.extend({ fixtureScope: 'agent-scope' })
  350. ctx.typert.contexts.registerHost('gatewayFixture', contextProvider(scoped))
  351. registerStrict(ctx, [renameDescriptor()])
  352. await expect(ctx.typertGateway.invoke({
  353. namespace: 'goals',
  354. method: 'rename',
  355. args: { agentId: 'agent-1', request: { title: 'land' } },
  356. })).resolves.toEqual({ title: 'land', scope: 'agent-scope' })
  357. expect(service.calls).toEqual(['rename'])
  358. })
  359. it('derives SRC direct lookup and JSON parameters from marker and parameter names', async () => {
  360. const { ctx, service } = await setup()
  361. const agent = { id: 'agent-1' }
  362. registerAgentLookup(ctx, agent)
  363. const caller = ctx.extend({ fixtureScope: 'direct-src' })
  364. const abort = new AbortController()
  365. await expect(caller.typertGateway.invoke({
  366. namespace: 'goals',
  367. method: 'create',
  368. args: { agentId: 'agent-1', request: { title: 'ship' } },
  369. signal: abort.signal,
  370. })).resolves.toEqual({ agentId: 'agent-1', title: 'ship', scope: 'direct-src' })
  371. expect(service.lastSignal).toBe(abort.signal)
  372. })
  373. it('does not downgrade an observed SRC lookup after its provider unloads', async () => {
  374. const { ctx, service } = await setup()
  375. const dispose = registerAgentLookup(ctx, { id: 'agent-1' })
  376. await dispose()
  377. await expectCode(ctx.typertGateway.invoke({
  378. namespace: 'goals',
  379. method: 'create',
  380. args: { agentId: 'agent-1', request: { title: 'ship' } },
  381. }), 'gateway/lookup-unavailable')
  382. expect(service.calls).toEqual([])
  383. })
  384. it('derives SRC Remote Scope identity and preserves the scoped Proxy receiver', async () => {
  385. const { ctx } = await setup()
  386. const scoped = ctx.extend({ fixtureScope: 'agent-src' })
  387. ctx.typert.contexts.registerHost('gatewayFixture', contextProvider(scoped))
  388. await expect(ctx.typertGateway.invoke({
  389. namespace: 'goals',
  390. method: 'rename',
  391. args: { agentId: 'agent-1', request: { title: 'land' } },
  392. })).resolves.toEqual({ title: 'land', scope: 'agent-src' })
  393. })
  394. it('derives exported, empty, inherited, and distinct-namespace SRC methods', async () => {
  395. const ctx = await setupGateway()
  396. await ctx.plugin(ExportedMethodService)
  397. await ctx.plugin(EmptyMethodService)
  398. await ctx.plugin(InheritedMethodService)
  399. await expect(ctx.typertGateway.invoke({
  400. namespace: 'exported', method: 'execute', args: { value: 'ship' },
  401. })).resolves.toBe('ship')
  402. await expect(ctx.typertGateway.invoke({
  403. namespace: 'empty', method: 'ping', args: {},
  404. })).resolves.toBe('pong')
  405. await expect(ctx.typertGateway.invoke({
  406. namespace: 'inherited', method: 'run', args: { value: 'land' },
  407. })).resolves.toBe('land')
  408. await expectCode(ctx.typertGateway.invoke({
  409. namespace: 'other', method: 'absent', args: {},
  410. }), 'gateway/invocation-unavailable')
  411. })
  412. it('rejects SRC wire collisions and unavailable Context providers', async () => {
  413. const colliding = await setupGateway()
  414. await colliding.plugin(CollidingWireService)
  415. registerAgentLookup(colliding, { id: 'agent-1' })
  416. await expectCode(colliding.typertGateway.invoke({
  417. namespace: 'colliding-wire',
  418. method: 'run',
  419. args: { agentId: 'agent-1' },
  420. }), 'gateway/signature-invalid')
  421. const missing = await setup()
  422. await expectCode(missing.ctx.typertGateway.invoke({
  423. namespace: 'goals',
  424. method: 'rename',
  425. args: { agentId: 'agent-1', request: { title: 'land' } },
  426. }), 'gateway/context-unavailable')
  427. const contextCollision = await setupGateway()
  428. await contextCollision.plugin(ContextWireService)
  429. contextCollision.typert.contexts.registerHost('gatewayFixture', contextProvider(contextCollision.extend()))
  430. await expectCode(contextCollision.typertGateway.invoke({
  431. namespace: 'context-wire',
  432. method: 'run',
  433. args: { agentId: 'agent-1' },
  434. }), 'gateway/signature-invalid')
  435. })
  436. it('re-reads Service and providers on every strict invocation', async () => {
  437. const { ctx, serviceFiber } = await setup()
  438. const agent = { id: 'agent-1' }
  439. const disposeLookup = registerAgentLookup(ctx, agent)
  440. registerStrict(ctx, [createDescriptor()])
  441. await disposeLookup()
  442. await expectCode(ctx.typertGateway.invoke({
  443. namespace: 'goals',
  444. method: 'create',
  445. args: { agentId: 'agent-1', request: { title: 'ship' } },
  446. }), 'gateway/lookup-unavailable')
  447. registerAgentLookup(ctx, agent)
  448. await serviceFiber.dispose()
  449. await expectCode(ctx.typertGateway.invoke({
  450. namespace: 'goals',
  451. method: 'create',
  452. args: { agentId: 'agent-1', request: { title: 'ship' } },
  453. }), 'gateway/service-unavailable')
  454. })
  455. it('re-reads and contains Context providers', async () => {
  456. const { ctx } = await setup()
  457. const scoped = ctx.extend()
  458. const dispose = ctx.typert.contexts.registerHost('gatewayFixture', contextProvider(scoped))
  459. registerStrict(ctx, [renameDescriptor()])
  460. await dispose()
  461. await expectCode(ctx.typertGateway.invoke({
  462. namespace: 'goals',
  463. method: 'rename',
  464. args: { agentId: 'agent-1', request: { title: 'land' } },
  465. }), 'gateway/context-unavailable')
  466. ctx.typert.contexts.registerHost('gatewayFixture', {
  467. ...contextProvider(scoped),
  468. resolve: () => { throw new Error('provider failed') },
  469. })
  470. const error = await expectCode(ctx.typertGateway.invoke({
  471. namespace: 'goals',
  472. method: 'rename',
  473. args: { agentId: 'agent-1', request: { title: 'land' } },
  474. }), 'gateway/context-failed')
  475. expect(error.cause).toEqual(new Error('provider failed'))
  476. })
  477. it('preserves a Host Context policy rejection for the active RPC adapter', async () => {
  478. const { ctx } = await setup()
  479. const rejection = new RemoteError('session/agent-busy', 'owned', { reason: 'subagent' })
  480. ctx.typert.contexts.registerHost('gatewayFixture', {
  481. ...contextProvider(ctx.extend()),
  482. resolve: async () => { throw rejection },
  483. })
  484. registerStrict(ctx, [renameDescriptor()])
  485. await expect(ctx.typertGateway.invoke({
  486. namespace: 'goals',
  487. method: 'rename',
  488. args: { agentId: 'agent-1', request: { title: 'land' } },
  489. })).rejects.toBe(rejection)
  490. })
  491. it('reports Context provider metadata mismatch and unresolved identities', async () => {
  492. const { ctx } = await setup()
  493. registerStrict(ctx, [renameDescriptor()])
  494. const scoped = ctx.extend()
  495. const mismatch = ctx.typert.contexts.registerHost('gatewayFixture', {
  496. ...contextProvider(scoped),
  497. wire: 'differentAgentId',
  498. })
  499. await expectCode(ctx.typertGateway.invoke({
  500. namespace: 'goals',
  501. method: 'rename',
  502. args: { agentId: 'agent-1', request: { title: 'land' } },
  503. }), 'gateway/provider-mismatch')
  504. await mismatch()
  505. ctx.typert.contexts.registerHost('gatewayFixture', {
  506. ...contextProvider(scoped),
  507. resolve: () => undefined,
  508. })
  509. await expectCode(ctx.typertGateway.invoke({
  510. namespace: 'goals',
  511. method: 'rename',
  512. args: { agentId: 'agent-1', request: { title: 'land' } },
  513. }), 'gateway/context-not-found')
  514. })
  515. it('contains lookup provider failures and missing identities', async () => {
  516. const { ctx } = await setup()
  517. registerStrict(ctx, [createDescriptor()])
  518. const throwing = ctx.typert.lookups.register('gatewayFixture', {
  519. ...agentLookup({ id: 'agent-1' }),
  520. resolve: async () => { throw new Error('lookup failed') },
  521. })
  522. const failure = await expectCode(ctx.typertGateway.invoke({
  523. namespace: 'goals',
  524. method: 'create',
  525. args: { agentId: 'agent-1', request: { title: 'ship' } },
  526. }), 'gateway/lookup-failed')
  527. expect(failure.cause).toEqual(new Error('lookup failed'))
  528. await throwing()
  529. const missing = ctx.typert.lookups.register('gatewayFixture', {
  530. ...agentLookup({ id: 'agent-1' }),
  531. resolve: () => Promise.resolve(undefined),
  532. })
  533. await expectCode(ctx.typertGateway.invoke({
  534. namespace: 'goals',
  535. method: 'create',
  536. args: { agentId: 'agent-1', request: { title: 'ship' } },
  537. }), 'gateway/lookup-not-found')
  538. await missing()
  539. ctx.typert.lookups.register('gatewayFixture', {
  540. ...agentLookup({ id: 'agent-1' }),
  541. resolve: async id => ({ id }),
  542. })
  543. await expect(ctx.typertGateway.invoke({
  544. namespace: 'goals',
  545. method: 'create',
  546. args: { agentId: 'agent-1', request: { title: 'ship' } },
  547. })).resolves.toMatchObject({ agentId: 'agent-1', title: 'ship' })
  548. })
  549. it('never downgrades an observed strict endpoint after definition disposal', async () => {
  550. const { ctx } = await setup()
  551. const dispose = registerStrict(ctx, [passthroughDescriptor()])
  552. await dispose()
  553. await expectCode(ctx.typertGateway.invoke({
  554. namespace: 'goals',
  555. method: 'passthrough',
  556. args: { value: 'would pass through SRC' },
  557. }), 'gateway/definition-unavailable')
  558. })
  559. it('seeds the no-downgrade guard from definitions present before Gateway startup', async () => {
  560. const ctx = new Context()
  561. await ctx.plugin(TypertRegistry)
  562. const dispose = registerStrict(ctx, [passthroughDescriptor()])
  563. await ctx.plugin(TypertGatewayService)
  564. await ctx.plugin(GoalService)
  565. await dispose()
  566. await expectCode(ctx.typertGateway.invoke({
  567. namespace: 'goals',
  568. method: 'passthrough',
  569. args: { value: 'would pass through SRC' },
  570. }), 'gateway/definition-unavailable')
  571. })
  572. it('retains the no-downgrade guard across Gateway Service reloads', async () => {
  573. const ctx = new Context()
  574. await ctx.plugin(TypertRegistry)
  575. const gatewayFiber = ctx.plugin(TypertGatewayService)
  576. await gatewayFiber
  577. await ctx.plugin(GoalService)
  578. const dispose = registerStrict(ctx, [passthroughDescriptor()])
  579. await dispose()
  580. await gatewayFiber.dispose()
  581. await ctx.plugin(TypertGatewayService)
  582. await expectCode(ctx.typertGateway.invoke({
  583. namespace: 'goals',
  584. method: 'passthrough',
  585. args: { value: 'would pass through SRC' },
  586. }), 'gateway/definition-unavailable')
  587. })
  588. it('rejects ambiguous SRC endpoints independently of reflection order', async () => {
  589. const ctx = await setupGateway()
  590. await ctx.plugin(FirstSharedService)
  591. await ctx.plugin(SecondSharedService)
  592. const error = await expectCode(ctx.typertGateway.invoke({
  593. namespace: 'shared',
  594. method: 'run',
  595. args: { value: 'ship' },
  596. }), 'gateway/ambiguous-endpoint')
  597. expect(error.message).toContain('firstShared, secondShared')
  598. })
  599. it('rejects SRC signatures that cannot map one wire field to each position', async () => {
  600. const cases = [
  601. { plugin: DefaultParameterService, namespace: 'invalid-default', args: { value: 'x' } },
  602. { plugin: DestructuredParameterService, namespace: 'invalid-destructure', args: { value: { value: 'x' } } },
  603. { plugin: RestParameterService, namespace: 'invalid-rest', args: { values: ['x'] } },
  604. { plugin: NonFinalSignalService, namespace: 'invalid-signal', args: { value: 'x' } },
  605. ] as const
  606. for (const testCase of cases) {
  607. const ctx = await setupGateway()
  608. await ctx.plugin(testCase.plugin)
  609. await expectCode(ctx.typertGateway.invoke({
  610. namespace: testCase.namespace,
  611. method: 'run',
  612. args: testCase.args,
  613. }), 'gateway/signature-invalid')
  614. }
  615. })
  616. it('rejects a SRC parameter matching more than one lookup provider', async () => {
  617. const { ctx } = await setup()
  618. const provider = agentLookup({ id: 'agent-1' })
  619. ctx.typert.lookups.register('gatewayFixture', provider)
  620. ctx.typert.lookups.register('gatewayFixtureAlias', provider)
  621. await expectCode(ctx.typertGateway.invoke({
  622. namespace: 'goals',
  623. method: 'create',
  624. args: { agentId: 'agent-1', request: { title: 'ship' } },
  625. }), 'gateway/signature-invalid')
  626. })
  627. it('requires exact wire fields before invoking business code', async () => {
  628. const { ctx, service } = await setup()
  629. registerAgentLookup(ctx, { id: 'agent-1' })
  630. await expectCode(ctx.typertGateway.invoke({
  631. namespace: 'goals',
  632. method: 'create',
  633. args: { request: { title: 'ship' } },
  634. }), 'gateway/arguments-invalid')
  635. await expectCode(ctx.typertGateway.invoke({
  636. namespace: 'goals',
  637. method: 'create',
  638. args: { agentId: 'agent-1', request: { title: 'ship' }, optional: true },
  639. }), 'gateway/arguments-invalid')
  640. await expectCode(ctx.typertGateway.invoke({
  641. namespace: 'goals',
  642. method: 'create',
  643. args: [] as unknown as Record<string, unknown>,
  644. }), 'gateway/arguments-invalid')
  645. expect(service.calls).toEqual([])
  646. })
  647. it('validates strict input without decoding the business result', async () => {
  648. const { ctx, service } = await setup()
  649. registerStrict(ctx, [strictOnlyDescriptor()])
  650. await expectCode(ctx.typertGateway.invoke({
  651. namespace: 'goals',
  652. method: 'strictOnly',
  653. args: { request: { title: 1 } },
  654. }), 'gateway/input-invalid')
  655. service.nextResult = { title: 1 }
  656. await expect(ctx.typertGateway.invoke({
  657. namespace: 'goals',
  658. method: 'strictOnly',
  659. args: { request: { title: 'ship' } },
  660. })).resolves.toEqual({ title: 1 })
  661. })
  662. it('does not inspect non-JSON business results', async () => {
  663. const { ctx, service } = await setup()
  664. registerStrict(ctx, [strictOnlyDescriptor()])
  665. service.nextResult = 1n
  666. await expect(ctx.typertGateway.invoke({
  667. namespace: 'goals',
  668. method: 'strictOnly',
  669. args: { request: { title: 'ship' } },
  670. })).resolves.toBe(1n)
  671. })
  672. it.each([
  673. undefined,
  674. Number.NaN,
  675. Number.POSITIVE_INFINITY,
  676. 1n,
  677. Symbol('value'),
  678. () => 'value',
  679. new Date(0),
  680. new Map(),
  681. [, 'sparse'],
  682. ])('rejects non-JSON SRC input %#', async (value) => {
  683. const { ctx } = await setup()
  684. await expectCode(ctx.typertGateway.invoke({
  685. namespace: 'goals',
  686. method: 'passthrough',
  687. args: { value },
  688. }), 'gateway/input-invalid')
  689. })
  690. it('admits an omitted SRC field and hands the Host method undefined', async () => {
  691. const { ctx, service } = await setup()
  692. // A weak descriptor reads parameter names from the JavaScript signature and
  693. // cannot see which are optional, so an absent field is admitted; the case
  694. // above keeps an explicitly undefined field rejected.
  695. await expect(ctx.typertGateway.invoke({
  696. namespace: 'goals',
  697. method: 'passthrough',
  698. args: {},
  699. })).resolves.toBeUndefined()
  700. expect(service.calls).toContain('passthrough')
  701. })
  702. it('rejects cyclic SRC input without inspecting SRC results', async () => {
  703. const { ctx, service } = await setup()
  704. const cyclic: { self?: unknown } = {}
  705. cyclic.self = cyclic
  706. await expectCode(ctx.typertGateway.invoke({
  707. namespace: 'goals',
  708. method: 'passthrough',
  709. args: { value: cyclic },
  710. }), 'gateway/input-invalid')
  711. const result = new Date(0)
  712. service.nextResult = result
  713. await expect(ctx.typertGateway.invoke({
  714. namespace: 'goals',
  715. method: 'passthrough',
  716. args: { value: null },
  717. })).resolves.toBe(result)
  718. })
  719. it('accepts dense JSON and rejects decorated arrays and object properties', async () => {
  720. const { ctx } = await setup()
  721. await expect(ctx.typertGateway.invoke({
  722. namespace: 'goals',
  723. method: 'passthrough',
  724. args: { value: [1, { nested: true }] },
  725. })).resolves.toEqual([1, { nested: true }])
  726. const sparseWithExtra = Array(1) as unknown[] & { extra?: boolean }
  727. sparseWithExtra.extra = true
  728. const symbolArray = [1]
  729. Object.defineProperty(symbolArray, Symbol('extra'), { value: true })
  730. const symbolObject = { value: true }
  731. Object.defineProperty(symbolObject, Symbol('extra'), { value: true })
  732. const hidden = {}
  733. Object.defineProperty(hidden, 'value', { value: true, enumerable: false })
  734. const accessor = {}
  735. Object.defineProperty(accessor, 'value', { get: () => true, enumerable: true })
  736. for (const value of [sparseWithExtra, symbolArray, symbolObject, hidden, accessor]) {
  737. await expectCode(ctx.typertGateway.invoke({
  738. namespace: 'goals', method: 'passthrough', args: { value },
  739. }), 'gateway/input-invalid')
  740. }
  741. })
  742. it('validates strict provider identity against generated wire metadata', async () => {
  743. const { ctx } = await setup()
  744. ctx.typert.lookups.register('gatewayFixture', {
  745. ...agentLookup({ id: 'agent-1' }),
  746. wire: 'differentAgentId',
  747. })
  748. registerStrict(ctx, [createDescriptor()])
  749. await expectCode(ctx.typertGateway.invoke({
  750. namespace: 'goals',
  751. method: 'create',
  752. args: { agentId: 'agent-1', request: { title: 'ship' } },
  753. }), 'gateway/provider-mismatch')
  754. })
  755. it('validates binding identity and active method availability', async () => {
  756. const ctx = await setupGateway()
  757. await ctx.plugin(WrongBindingService)
  758. await expectCode(ctx.typertGateway.invoke({
  759. namespace: 'wrong-binding',
  760. method: 'run',
  761. args: { value: 'ship' },
  762. }), 'gateway/binding-invalid')
  763. await ctx.plugin(GoalService)
  764. registerStrict(ctx, [{ ...passthroughDescriptor(), method: 'missing' }])
  765. await expectCode(ctx.typertGateway.invoke({
  766. namespace: 'goals',
  767. method: 'missing',
  768. args: { value: 'ship' },
  769. }), 'gateway/method-unavailable')
  770. })
  771. it('requires a visible binding and supports explicitly provided plain Services', async () => {
  772. const ctx = await setupGateway()
  773. await ctx.plugin(NoBindingService)
  774. registerStrict(ctx, [{
  775. ...passthroughDescriptor(),
  776. id: '@fixture/gateway#no-binding/run',
  777. service: 'noBinding',
  778. namespace: 'no-binding',
  779. method: 'run',
  780. }])
  781. await expectCode(ctx.typertGateway.invoke({
  782. namespace: 'no-binding', method: 'run', args: { value: 'ship' },
  783. }), 'gateway/binding-invalid')
  784. const plain: {
  785. typertRemote?: ReturnType<typeof bindTypertRemote>
  786. run(value: string): string
  787. } = { run: value => value }
  788. plain.typertRemote = bindTypertRemote(plain, 'plainRemote', { namespace: 'plain' })
  789. ctx.provide('plainRemote', plain)
  790. ctx.typert.register({
  791. package: '@fixture/plain',
  792. face: 'host',
  793. schemas: [],
  794. model: emptyModel,
  795. invocations: [{
  796. ...passthroughDescriptor(),
  797. id: '@fixture/plain#plain/run',
  798. service: 'plainRemote',
  799. namespace: 'plain',
  800. method: 'run',
  801. }],
  802. })
  803. await expect(ctx.typertGateway.invoke({
  804. namespace: 'plain', method: 'run', args: { value: 'land' },
  805. })).resolves.toBe('land')
  806. })
  807. it('reports a SRC marker whose prototype implementation disappeared', async () => {
  808. const ctx = await setupGateway()
  809. await ctx.plugin(MissingMethodService)
  810. const descriptor = Object.getOwnPropertyDescriptor(MissingMethodService.prototype, 'run')!
  811. Object.defineProperty(MissingMethodService.prototype, 'run', {
  812. configurable: true,
  813. value: 42,
  814. })
  815. try {
  816. await expectCode(ctx.typertGateway.invoke({
  817. namespace: 'missing-method', method: 'run', args: { value: 'ship' },
  818. }), 'gateway/method-unavailable')
  819. } finally {
  820. Object.defineProperty(MissingMethodService.prototype, 'run', descriptor)
  821. }
  822. })
  823. it('preserves business exception identity after invocation begins', async () => {
  824. const { ctx, service } = await setup()
  825. const failure = new Error('business identity')
  826. service.businessError = failure
  827. await expect(ctx.typertGateway.invoke({
  828. namespace: 'goals',
  829. method: 'fail',
  830. args: { request: { reason: 'fixture' } },
  831. })).rejects.toBe(failure)
  832. })
  833. it('reports an absent endpoint without retaining receiver state', async () => {
  834. const { ctx } = await setup()
  835. await expectCode(ctx.typertGateway.invoke({
  836. namespace: 'goals',
  837. method: 'absent',
  838. args: {},
  839. }), 'gateway/invocation-unavailable')
  840. })
  841. it('mounts a shared /api interceptor through an optional Connection and returns existing RPC results', async () => {
  842. const ctx = new Context().extend({ fixtureScope: 'rpc-caller' })
  843. await ctx.plugin(TypertRegistry)
  844. await ctx.plugin(FakeConnectionService)
  845. const gatewayFiber = ctx.plugin(TypertGatewayService)
  846. await gatewayFiber
  847. await ctx.plugin(GoalService)
  848. const connection = rawConnection(ctx)
  849. expect(connection).toMatchObject({ channel: '/api' })
  850. registerAgentLookup(ctx, { id: 'agent-1' })
  851. registerStrict(ctx, [createDescriptor(), maybeDescriptor()])
  852. expect(connection.matches?.('goals/create')).toBe(true)
  853. expect(connection.matches?.('goals/passthrough')).toBe(true)
  854. expect(connection.matches?.('goals')).toBe(false)
  855. expect(connection.matches?.('goals/missing')).toBe(false)
  856. expect(connection.matches?.('legacy/list')).toBe(false)
  857. const abort = new AbortController()
  858. const signal = abort.signal
  859. const handler = connection.handler
  860. if (handler === undefined) throw new Error('fixture Connection did not retain the /api interceptor')
  861. await expect(handler('goals/create', {
  862. args: { agentId: 'agent-1', request: { title: 'ship' } },
  863. }, signal)).resolves.toEqual({
  864. ok: true,
  865. value: { agentId: 'agent-1', title: 'ship', scope: 'rpc-caller' },
  866. })
  867. const service = rawGoalService(ctx)
  868. expect(service.lastSignal).toBe(signal)
  869. abort.abort(new Error('client disconnected'))
  870. expect(service.lastSignal?.aborted).toBe(true)
  871. const invalid = await handler('goals/create', { invalid: true }, signal)
  872. expect(invalid).toMatchObject({
  873. ok: false,
  874. error: { code: 'gateway/internal' },
  875. })
  876. if (invalid.ok) throw new Error('invalid Remote payload unexpectedly succeeded')
  877. expect(invalid.error.message).toMatch(/exactly one plain-object args field/)
  878. await expect(handler('goals/maybe', { args: {} }, signal)).resolves.toEqual({
  879. ok: true,
  880. value: undefined,
  881. })
  882. await expect(handler('goals/maybe', { args: { value: null } }, signal)).resolves.toEqual({
  883. ok: true,
  884. value: null,
  885. })
  886. for (const endpoint of ['goals', '/create', 'goals/', 'goals/create/extra']) {
  887. const result = await handler(endpoint, { args: {} }, signal)
  888. expect(result).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
  889. if (result.ok) throw new Error('invalid Remote endpoint unexpectedly succeeded')
  890. expect(result.error.message).toContain('invalid Remote endpoint')
  891. }
  892. for (const payload of [null, [], { args: {}, extra: true }, { only: true }, { args: null }, { args: [] }]) {
  893. const result = await handler('goals/create', payload, signal)
  894. expect(result).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
  895. if (result.ok) throw new Error('invalid Remote payload unexpectedly succeeded')
  896. expect(result.error.message).toContain('plain-object args field')
  897. }
  898. service.businessError = 'non-error failure' as unknown as Error
  899. await expect(handler(
  900. 'goals/fail',
  901. { args: { request: null } },
  902. new AbortController().signal,
  903. )).resolves.toEqual({
  904. ok: false,
  905. error: { code: 'gateway/internal', message: 'non-error failure', details: {} },
  906. })
  907. // A business rejection observed while the carrier signal is already aborted
  908. // is the caller's cancellation, not an internal gateway fault.
  909. const cancelledCall = new AbortController()
  910. cancelledCall.abort(new Error('client disconnected'))
  911. service.businessError = new Error('fixture business failure')
  912. await expect(handler(
  913. 'goals/fail',
  914. { args: { request: null } },
  915. cancelledCall.signal,
  916. )).resolves.toEqual({
  917. ok: false,
  918. error: {
  919. code: 'gateway/cancelled',
  920. message: 'Remote invocation "goals/fail" was aborted',
  921. details: {},
  922. },
  923. })
  924. await gatewayFiber.dispose()
  925. expect(connection.handler).toBeUndefined()
  926. })
  927. it('claims and validates in-process Remote event results for the active Client generation', async () => {
  928. const ctx = new Context()
  929. await ctx.plugin(TypertRegistry)
  930. await ctx.plugin(FakeConnectionService)
  931. await ctx.plugin(TypertGatewayService)
  932. const connection = rawConnection(ctx)
  933. const handler = connection.handler
  934. if (handler === undefined) throw new Error('fixture Connection did not retain the /api interceptor')
  935. expect(connection.matches?.('$events/result')).toBe(true)
  936. const result = {
  937. args: { clientId: 'missing-client', eventId: 'missing', outcome: { kind: 'next' } },
  938. }
  939. const inactive = await handler('$events/result', result, new AbortController().signal)
  940. expect(inactive).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
  941. if (inactive.ok) throw new Error('inactive Remote event result unexpectedly succeeded')
  942. expect(inactive.error.message).toContain('identifies no active event stream')
  943. const unregister = ctx.typertGateway.registerRemoteEvents(signal => (async function* () {
  944. await new Promise<void>((resolve) => {
  945. if (signal.aborted) resolve()
  946. else signal.addEventListener('abort', () => { resolve() }, { once: true })
  947. })
  948. })(), { home: '/home/fixture' })
  949. const carrier = new AbortController()
  950. const events = rawGatewayEventHarness(ctx).openRemoteEvents({ args: {} }, carrier.signal)
  951. const opening = await events.next()
  952. expect(opening).toMatchObject({
  953. done: false,
  954. value: { type: 'ready', host: { home: '/home/fixture' } },
  955. })
  956. if (opening.done) throw new Error('Remote event stream ended before ready')
  957. const clientId: unknown = Reflect.get(opening.value as object, 'clientId')
  958. if (typeof clientId !== 'string') throw new Error('Remote event stream omitted its Client id')
  959. for (const payload of [null, [], {}, { other: {} }]) {
  960. const invalid = await handler('$events/result', payload, carrier.signal)
  961. expect(invalid).toMatchObject({ ok: false, error: { code: 'gateway/internal' } })
  962. if (invalid.ok) throw new Error('invalid Remote event result payload unexpectedly succeeded')
  963. expect(invalid.error.message).toContain('requires exactly one plain-object args field')
  964. }
  965. await expect(handler('$events/result', {
  966. args: { clientId, eventId: 'missing', outcome: { kind: 'next' } },
  967. }, carrier.signal)).resolves.toEqual({
  968. ok: true,
  969. value: undefined,
  970. })
  971. await events.return(undefined)
  972. await unregister()
  973. await ctx.fiber.dispose()
  974. })
  975. it('preserves a lookup policy rejection through the Connection RPC result', async () => {
  976. const ctx = new Context()
  977. await ctx.plugin(TypertRegistry)
  978. await ctx.plugin(FakeConnectionService)
  979. await ctx.plugin(TypertGatewayService)
  980. await ctx.plugin(GoalService)
  981. registerStrict(ctx, [createDescriptor()])
  982. const failure = {
  983. code: 'session/agent-busy',
  984. message: 'session is owned by subagent routing',
  985. details: { reason: 'use subagent delivery for this child session' },
  986. }
  987. ctx.typert.lookups.register('gatewayFixture', {
  988. ...agentLookup({ id: 'agent-1' }),
  989. resolve: () => { throw new RemoteError('session/agent-busy', failure.message, failure.details) },
  990. })
  991. const handler = rawConnection(ctx).handler
  992. if (handler === undefined) throw new Error('fixture Connection did not retain the /api interceptor')
  993. await expect(handler('goals/create', {
  994. args: { agentId: 'agent-1', request: { title: 'ship' } },
  995. }, new AbortController().signal)).resolves.toEqual({ ok: false, error: failure })
  996. })
  997. it('caches SRC ownership until the Cordis Service set changes', async () => {
  998. const ctx = new Context()
  999. await ctx.plugin(TypertRegistry)
  1000. await ctx.plugin(FakeConnectionService)
  1001. await ctx.plugin(TypertGatewayService)
  1002. const observedFiber = ctx.plugin(ObservedClaimService)
  1003. await observedFiber
  1004. const connection = rawConnection(ctx)
  1005. const observed = ctx.get('observedClaim') as unknown as ObservedClaimService & {
  1006. [symbols.original]?: ObservedClaimService
  1007. }
  1008. const service = observed[symbols.original] ?? observed
  1009. expect(connection.matches?.('legacy/list')).toBe(false)
  1010. expect(connection.matches?.('legacy/list')).toBe(false)
  1011. expect(service.bindingReads).toBe(1)
  1012. expect(connection.matches?.('observed-claim/run')).toBe(true)
  1013. expect(connection.matches?.('observed-claim/run')).toBe(true)
  1014. expect(service.bindingReads).toBe(1)
  1015. const unrelatedFiber = ctx.plugin(NoBindingService)
  1016. await unrelatedFiber
  1017. expect(connection.matches?.('legacy/list')).toBe(false)
  1018. expect(service.bindingReads).toBe(2)
  1019. await observedFiber.dispose()
  1020. expect(connection.matches?.('observed-claim/run')).toBe(false)
  1021. await unrelatedFiber.dispose()
  1022. })
  1023. it('dispatches claimed invocations through /api and leaves unclaimed endpoints to its fallback', async () => {
  1024. const ctx = new Context().extend({ fixtureScope: 'http-caller' })
  1025. const routes: WebRoute[] = []
  1026. provideBrowserCredentials(ctx)
  1027. ctx.provide('webServer', fakeHttpServer(routes) as WebServer)
  1028. const connectionFiber = ctx.plugin({ inject: [...connectionInject], apply: applyConnection })
  1029. await connectionFiber
  1030. await ctx.plugin(TypertRegistry)
  1031. const gatewayFiber = ctx.plugin(TypertGatewayService)
  1032. await gatewayFiber
  1033. const goalFiber = ctx.plugin(GoalService)
  1034. await goalFiber
  1035. const removeLookup = registerAgentLookup(ctx, { id: 'agent-1' })
  1036. const removeStrict = registerStrict(ctx, [createDescriptor()])
  1037. let strictActive = true
  1038. expect(routes).toHaveLength(1)
  1039. const server = await serveRoute(routes[0]!)
  1040. const cookie = browserCookie(ctx.connection, server.origin)
  1041. try {
  1042. const response = await fetch(`${server.origin}/api/goals/create`, {
  1043. method: 'POST',
  1044. headers: { 'content-type': 'application/json', cookie },
  1045. body: JSON.stringify({
  1046. type: 'client-request',
  1047. rpcId: 'rpc-http',
  1048. method: 'goals/create',
  1049. payload: { args: { agentId: 'agent-1', request: { title: ' ship ' } } },
  1050. }),
  1051. })
  1052. expect(response.status).toBe(200)
  1053. await expect(response.json()).resolves.toEqual({
  1054. type: 'server-response',
  1055. rpcId: 'rpc-http',
  1056. result: {
  1057. ok: true,
  1058. value: { agentId: 'agent-1', title: 'ship', scope: 'http-caller' },
  1059. },
  1060. })
  1061. const invalid = await fetch(`${server.origin}/api/goals/create`, {
  1062. method: 'POST',
  1063. headers: { 'content-type': 'application/json', cookie },
  1064. body: JSON.stringify({
  1065. type: 'client-request',
  1066. rpcId: 'rpc-invalid',
  1067. method: 'goals/create',
  1068. payload: { invalid: true },
  1069. }),
  1070. })
  1071. expect(invalid.status).toBe(200)
  1072. const invalidBody = await invalid.json() as unknown
  1073. expect(invalidBody).toMatchObject({
  1074. type: 'server-response',
  1075. rpcId: 'rpc-invalid',
  1076. result: {
  1077. ok: false,
  1078. error: { code: 'gateway/internal' },
  1079. },
  1080. })
  1081. expect(JSON.stringify(invalidBody)).toContain('plain-object args field')
  1082. await removeStrict()
  1083. strictActive = false
  1084. const withdrawn = await fetch(`${server.origin}/api/goals/create`, {
  1085. method: 'POST',
  1086. headers: { 'content-type': 'application/json', cookie },
  1087. body: JSON.stringify({
  1088. type: 'client-request',
  1089. rpcId: 'rpc-withdrawn',
  1090. method: 'goals/create',
  1091. payload: { args: { agentId: 'agent-1', request: { title: 'ship' } } },
  1092. }),
  1093. })
  1094. expect(withdrawn.status).toBe(200)
  1095. const withdrawnBody = await withdrawn.json() as unknown
  1096. expect(withdrawnBody).toMatchObject({
  1097. type: 'server-response',
  1098. rpcId: 'rpc-withdrawn',
  1099. result: {
  1100. ok: false,
  1101. error: { code: 'gateway/definition-unavailable' },
  1102. },
  1103. })
  1104. expect(JSON.stringify(withdrawnBody)).toContain('strict definition was withdrawn')
  1105. const unclaimed = await fetch(`${server.origin}/api/legacy/list`, {
  1106. method: 'POST',
  1107. headers: { cookie },
  1108. })
  1109. expect(unclaimed.status).toBe(404)
  1110. } finally {
  1111. await server.close()
  1112. if (strictActive) await removeStrict()
  1113. await removeLookup()
  1114. await goalFiber.dispose()
  1115. await gatewayFiber.dispose()
  1116. await connectionFiber.dispose()
  1117. }
  1118. expect(routes).toHaveLength(0)
  1119. })
  1120. })
  1121. async function setup(): Promise<{
  1122. readonly ctx: Context
  1123. readonly service: GoalService
  1124. readonly serviceFiber: ReturnType<Context['plugin']>
  1125. }> {
  1126. const ctx = await setupGateway()
  1127. const serviceFiber = ctx.plugin(GoalService)
  1128. await serviceFiber
  1129. return { ctx, service: rawGoalService(ctx), serviceFiber }
  1130. }
  1131. async function setupGateway(): Promise<Context> {
  1132. const ctx = new Context()
  1133. await ctx.plugin(TypertRegistry)
  1134. await ctx.plugin(TypertGatewayService)
  1135. return ctx
  1136. }
  1137. function rawGoalService(ctx: Context): GoalService {
  1138. const receiver = ctx.get('goals') as unknown as GoalService & { [symbols.original]?: GoalService }
  1139. return receiver[symbols.original] ?? receiver
  1140. }
  1141. function rawConnection(ctx: Context): FakeConnectionService {
  1142. const receiver = ctx.get('connection') as unknown as FakeConnectionService & {
  1143. [symbols.original]?: FakeConnectionService
  1144. }
  1145. return receiver[symbols.original] ?? receiver
  1146. }
  1147. interface GatewayEventHarness {
  1148. openRemoteEvents(payload: unknown, signal: AbortSignal): AsyncGenerator
  1149. }
  1150. function rawGatewayEventHarness(ctx: Context): GatewayEventHarness {
  1151. const receiver = ctx.get('typertGateway') as unknown as GatewayEventHarness & {
  1152. [symbols.original]?: GatewayEventHarness
  1153. }
  1154. return receiver[symbols.original] ?? receiver
  1155. }
  1156. function registerStrict(ctx: Context, descriptors: readonly InvocationDescriptor[]): () => Promise<void> {
  1157. return ctx.typert.register({
  1158. package: '@fixture/gateway',
  1159. face: 'host',
  1160. schemas: [],
  1161. model: emptyModel,
  1162. invocations: descriptors,
  1163. })
  1164. }
  1165. function registerAgentLookup(ctx: Context, agent: FixtureAgent): () => Promise<void> {
  1166. return ctx.typert.lookups.register('gatewayFixture', agentLookup(agent))
  1167. }
  1168. function agentLookup(agent: FixtureAgent): TypertLookupProvider<FixtureAgent, string> {
  1169. return {
  1170. parameter: 'agent',
  1171. wire: 'agentId',
  1172. hostTypeSymbol: '@fixture/domain#Agent',
  1173. wireTypeSymbol: '@fixture/domain#AgentId',
  1174. resolve: id => id === agent.id ? agent : undefined,
  1175. }
  1176. }
  1177. function contextProvider(context: Context) {
  1178. return {
  1179. wire: 'agentId',
  1180. wireTypeSymbol: '@fixture/domain#AgentId',
  1181. resolve: (id: string) => id === 'agent-1' ? context : undefined,
  1182. }
  1183. }
  1184. function strictCodec(typeSymbol: string, schema: z.ZodType): InvocationDescriptor['result'] {
  1185. return { mode: 'strict', typeSymbol, schema }
  1186. }
  1187. function createDescriptor(): InvocationDescriptor {
  1188. return {
  1189. id: '@fixture/gateway#goals/create',
  1190. service: 'goals',
  1191. namespace: 'goals',
  1192. method: 'create',
  1193. invocation: { kind: 'direct' },
  1194. parameters: [
  1195. {
  1196. name: 'agent',
  1197. wire: 'agentId',
  1198. source: 'lookup',
  1199. lookup: 'gatewayFixture',
  1200. codec: strictCodec('@fixture/domain#AgentId', z.string()),
  1201. },
  1202. {
  1203. name: 'request',
  1204. wire: 'request',
  1205. source: 'json',
  1206. codec: strictCodec('@fixture/gateway#CreateRequest', z.object({
  1207. title: z.string().transform(value => value.trim()),
  1208. })),
  1209. },
  1210. ],
  1211. cancellation: { parameter: 'signal' },
  1212. result: strictCodec('@fixture/gateway#CreateResult', z.object({
  1213. agentId: z.string(),
  1214. title: z.string(),
  1215. scope: z.string(),
  1216. })),
  1217. }
  1218. }
  1219. function renameDescriptor(): InvocationDescriptor {
  1220. return {
  1221. id: '@fixture/gateway#goals/rename',
  1222. service: 'goals',
  1223. namespace: 'goals',
  1224. method: 'rename',
  1225. invocation: {
  1226. kind: 'context',
  1227. context: 'gatewayFixture',
  1228. wire: 'agentId',
  1229. codec: strictCodec('@fixture/domain#AgentId', z.string()),
  1230. },
  1231. parameters: [{
  1232. name: 'request',
  1233. wire: 'request',
  1234. source: 'json',
  1235. codec: strictCodec('@fixture/gateway#RenameRequest', z.object({ title: z.string() })),
  1236. }],
  1237. result: strictCodec('@fixture/gateway#RenameResult', z.object({
  1238. title: z.string(),
  1239. scope: z.string(),
  1240. })),
  1241. }
  1242. }
  1243. function passthroughDescriptor(): InvocationDescriptor {
  1244. return {
  1245. id: '@fixture/gateway#goals/passthrough',
  1246. service: 'goals',
  1247. namespace: 'goals',
  1248. method: 'passthrough',
  1249. invocation: { kind: 'direct' },
  1250. parameters: [{
  1251. name: 'value',
  1252. wire: 'value',
  1253. source: 'json',
  1254. codec: { mode: 'src-json' },
  1255. }],
  1256. result: { mode: 'src-json' },
  1257. }
  1258. }
  1259. function strictOnlyDescriptor(): InvocationDescriptor {
  1260. const value = strictCodec('@fixture/gateway#StrictValue', z.object({ title: z.string() }))
  1261. return {
  1262. id: '@fixture/gateway#goals/strictOnly',
  1263. service: 'goals',
  1264. namespace: 'goals',
  1265. method: 'strictOnly',
  1266. invocation: { kind: 'direct' },
  1267. parameters: [{ name: 'request', wire: 'request', source: 'json', codec: value }],
  1268. result: value,
  1269. }
  1270. }
  1271. function maybeDescriptor(): InvocationDescriptor {
  1272. const value = strictCodec(
  1273. '@fixture/gateway#MaybeValue',
  1274. z.union([z.string(), z.null(), z.undefined()]),
  1275. )
  1276. return {
  1277. id: '@fixture/gateway#goals/maybe',
  1278. service: 'goals',
  1279. namespace: 'goals',
  1280. method: 'maybe',
  1281. invocation: { kind: 'direct' },
  1282. parameters: [{
  1283. name: 'value',
  1284. wire: 'value',
  1285. source: 'json',
  1286. acceptsUndefined: true,
  1287. codec: value,
  1288. }],
  1289. result: value,
  1290. }
  1291. }
  1292. async function expectCode(
  1293. promise: Promise<unknown>,
  1294. code: TypertGatewayError['code'],
  1295. ): Promise<TypertGatewayError> {
  1296. try {
  1297. await promise
  1298. } catch (error) {
  1299. expect(error).toBeInstanceOf(TypertGatewayError)
  1300. expect(error).toMatchObject({ code })
  1301. return error as TypertGatewayError
  1302. }
  1303. throw new Error(`expected TypertGatewayError ${code}`)
  1304. }