api-proxy-subagents.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import type { SessionId } from '@deepseek-ai/dsh-session'
  4. import { SubagentError } from '@deepseek-ai/dsh-subagent'
  5. import { RpcId } from '../src/api/rpc.ts'
  6. import type { RpcRequest } from '../src/api/rpc.ts'
  7. import { createApiProxy } from '../src/api-proxy.ts'
  8. const sid = (value: string): SessionId => value as SessionId
  9. const PARENT = sid('parent')
  10. const CHILD = sid('child')
  11. function request<P>(payload: P): RpcRequest<P> {
  12. return { rpcId: RpcId('subagent-rpc'), payload }
  13. }
  14. function bench(options: {
  15. parentLive?: boolean
  16. childStatus?: 'idle' | 'running'
  17. entries?: object[]
  18. followupError?: Error
  19. interruptError?: Error
  20. listError?: Error
  21. } = {}) {
  22. const parent = { id: PARENT }
  23. const child = options.childStatus === undefined
  24. ? undefined
  25. : { id: CHILD, status: options.childStatus }
  26. const getAgent = vi.fn((id: SessionId) => {
  27. if (options.parentLive !== false && id === PARENT) return parent
  28. if (id === CHILD) return child
  29. return undefined
  30. })
  31. const listChildren = vi.fn(() => options.listError === undefined
  32. ? Promise.resolve(options.entries ?? [
  33. {
  34. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  35. activity: 'inactive', hasChildren: false,
  36. },
  37. ])
  38. : Promise.reject(options.listError))
  39. const followup = vi.fn((
  40. _parent: unknown,
  41. _childId: SessionId,
  42. _content: unknown,
  43. _delivery: {
  44. source: { kind: string; rpcId: RpcId; clientTimeZone?: string }
  45. signal: AbortSignal
  46. },
  47. ) => options.followupError === undefined
  48. ? Promise.resolve('message-1')
  49. : Promise.reject(options.followupError))
  50. const interrupt = vi.fn((
  51. _targetSessionId: SessionId,
  52. _authority: { kind: 'user'; parentSessionId: SessionId },
  53. ) => {
  54. if (options.interruptError !== undefined) throw options.interruptError
  55. })
  56. const ctx = new Context()
  57. ctx.provide('agents', { get: getAgent })
  58. ctx.provide('subagents', { listChildren, followup, interrupt })
  59. const api = createApiProxy(ctx, {
  60. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  61. })
  62. return { api, getAgent, listChildren, followup, interrupt, parent }
  63. }
  64. describe('subagent gateway', () => {
  65. it('lists the complete catalog and reports exact live-parent availability', async () => {
  66. const { api, listChildren } = bench({ parentLive: false, entries: [
  67. {
  68. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  69. activity: 'inactive', hasChildren: true,
  70. },
  71. {
  72. kind: 'child', id: sid('one-shot'), mode: 'one-shot',
  73. activity: 'inactive', hasChildren: false,
  74. },
  75. { kind: 'diagnostic', id: sid('bad'), reason: 'corrupt' },
  76. ] })
  77. const response = await api.subagents.list(request({ parentSessionId: PARENT }))
  78. expect(response.rpcId).toBe('subagent-rpc')
  79. expect(response.result).toMatchObject({
  80. ok: true,
  81. value: {
  82. parentAvailable: false,
  83. entries: [
  84. { kind: 'child', mode: 'continuable' },
  85. { kind: 'child', mode: 'one-shot' },
  86. { kind: 'diagnostic' },
  87. ],
  88. },
  89. })
  90. expect(listChildren).toHaveBeenCalledWith(PARENT, undefined)
  91. })
  92. it('derives catalog activity from the live child Agent rather than Session residency', async () => {
  93. const residentIdle = bench({ childStatus: 'idle', entries: [{
  94. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  95. activity: 'running', hasChildren: false,
  96. }] })
  97. expect((await residentIdle.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  98. .toMatchObject({ ok: true, value: { entries: [{ activity: 'inactive' }] } })
  99. const running = bench({ childStatus: 'running' })
  100. expect((await running.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  101. .toMatchObject({ ok: true, value: { entries: [{ activity: 'running' }] } })
  102. })
  103. it('maps missing catalog projections on list without preflighting prompt delivery', async () => {
  104. const listError = () => new SubagentError(
  105. 'listing subagents requires the sessionProjections registry (load @deepseek-ai/dsh-session-projection)',
  106. 'SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE',
  107. )
  108. const expected = {
  109. code: 'internal',
  110. message: 'subagent catalog is unavailable: this deployment does not mount the sessionProjections registry (load @deepseek-ai/dsh-session-projection)',
  111. }
  112. const list = bench({ listError: listError() })
  113. expect((await list.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  114. .toMatchObject({ ok: false, error: expected })
  115. const prompt = bench({ listError: listError() })
  116. expect((await prompt.api.subagents.prompt(request({
  117. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  118. }), new AbortController().signal)).result).toMatchObject({ ok: true })
  119. expect(prompt.listChildren).not.toHaveBeenCalled()
  120. expect(prompt.followup).toHaveBeenCalledOnce()
  121. })
  122. it('routes human content through the exact live parent with rpc attribution', async () => {
  123. const { api, parent, followup } = bench()
  124. const content = [{ type: 'text' as const, text: '继续' }]
  125. const signal = new AbortController().signal
  126. const response = await api.subagents.prompt(request({
  127. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content,
  128. }), signal)
  129. expect(response.result).toMatchObject({
  130. ok: true, value: { messageId: 'message-1' },
  131. })
  132. expect(followup).toHaveBeenCalledWith(
  133. parent,
  134. CHILD,
  135. content,
  136. { source: { kind: 'user', rpcId: RpcId('subagent-rpc') }, signal },
  137. )
  138. })
  139. it('canonicalizes browser-zone provenance before delivering a child prompt', async () => {
  140. const { api, parent, followup } = bench()
  141. const alias = 'US/Pacific'
  142. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  143. .resolvedOptions().timeZone
  144. const content = [{ type: 'text' as const, text: 'continue locally' }]
  145. const signal = new AbortController().signal
  146. await expect(api.subagents.prompt(request({
  147. parentSessionId: PARENT,
  148. childSessionId: CHILD,
  149. mode: 'continuable',
  150. content,
  151. clientTimeZone: alias,
  152. }), signal)).resolves.toMatchObject({ result: { ok: true } })
  153. expect(followup).toHaveBeenCalledWith(parent, CHILD, content, {
  154. source: { kind: 'user', rpcId: RpcId('subagent-rpc'), clientTimeZone: canonical },
  155. signal,
  156. })
  157. const invalid = await api.subagents.prompt(request({
  158. parentSessionId: PARENT,
  159. childSessionId: CHILD,
  160. mode: 'continuable',
  161. content,
  162. clientTimeZone: 'Not/A_Real_Zone',
  163. }), signal)
  164. expect(invalid.result).toEqual({
  165. ok: false,
  166. error: {
  167. code: 'invalid-time-zone',
  168. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  169. details: { value: 'Not/A_Real_Zone' },
  170. },
  171. })
  172. expect(followup).toHaveBeenCalledOnce()
  173. })
  174. it('fails before delivery when the parent is absent and maps continuation failures', async () => {
  175. const absent = bench({ parentLive: false })
  176. expect((await absent.api.subagents.prompt(request({
  177. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  178. }), new AbortController().signal)).result).toMatchObject({
  179. ok: false, error: { code: 'subagent-parent-unavailable' },
  180. })
  181. expect(absent.listChildren).not.toHaveBeenCalled()
  182. const failed = bench({ followupError: new SubagentError('draining', 'DRAINING') })
  183. expect((await failed.api.subagents.prompt(request({
  184. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  185. }), new AbortController().signal)).result).toMatchObject({
  186. ok: false, error: { code: 'subagent-delivery-unavailable' },
  187. })
  188. })
  189. it('hides unexpected backend details', async () => {
  190. const catalog = bench({ listError: new Error('secret descriptor') })
  191. expect((await catalog.api.subagents.list(request({
  192. parentSessionId: PARENT,
  193. }))).result).toMatchObject({
  194. ok: false,
  195. error: { code: 'internal', message: 'subagent catalog read failed' },
  196. })
  197. const prompt = bench({ followupError: new Error('secret provider') })
  198. expect((await prompt.api.subagents.prompt(request({
  199. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  200. }), new AbortController().signal)).result).toMatchObject({
  201. ok: false,
  202. error: { code: 'internal', message: 'subagent prompt failed' },
  203. })
  204. })
  205. it('interrupts through the core primitive alone while the parent Agent is offline', async () => {
  206. const { api, interrupt, getAgent, listChildren } = bench({ parentLive: false })
  207. const response = await api.subagents.interrupt(request({
  208. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  209. }))
  210. expect(response.rpcId).toBe('subagent-rpc')
  211. expect(response.result).toEqual({ ok: true, value: { accepted: true } })
  212. expect(interrupt).toHaveBeenCalledExactlyOnceWith(CHILD, { kind: 'user', parentSessionId: PARENT })
  213. // No parent-registry or catalog dependency: this is what keeps a
  214. // live child interruptible after its parent Agent went offline.
  215. expect(getAgent).not.toHaveBeenCalled()
  216. expect(listChildren).not.toHaveBeenCalled()
  217. })
  218. it('maps interrupt authorization rejection without touching other services', async () => {
  219. const { api, listChildren } = bench({
  220. interruptError: new SubagentError('secret lineage', 'UNAUTHORIZED'),
  221. })
  222. const response = await api.subagents.interrupt(request({
  223. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  224. }))
  225. expect(response.result).toEqual({
  226. ok: false,
  227. error: {
  228. code: 'subagent-unauthorized',
  229. message: 'subagent does not belong to this parent',
  230. details: { childSessionId: CHILD },
  231. },
  232. })
  233. expect(listChildren).not.toHaveBeenCalled()
  234. })
  235. it('hides unexpected interrupt failures behind the internal code', async () => {
  236. const { api } = bench({ interruptError: new Error('secret activation state') })
  237. const response = await api.subagents.interrupt(request({
  238. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  239. }))
  240. expect(response.result).toEqual({
  241. ok: false,
  242. error: { code: 'internal', message: 'subagent interrupt failed', details: {} },
  243. })
  244. })
  245. })