api-proxy-subagents.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 the missing projections capability to one wire face on list and prompt', 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: false, error: expected })
  119. expect(prompt.followup).not.toHaveBeenCalled()
  120. })
  121. it('routes human content through the exact live parent with rpc attribution', async () => {
  122. const { api, parent, followup } = bench()
  123. const content = [{ type: 'text' as const, text: '继续' }]
  124. const signal = new AbortController().signal
  125. const response = await api.subagents.prompt(request({
  126. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content,
  127. }), signal)
  128. expect(response.result).toMatchObject({
  129. ok: true, value: { messageId: 'message-1' },
  130. })
  131. expect(followup).toHaveBeenCalledWith(
  132. parent,
  133. CHILD,
  134. content,
  135. { source: { kind: 'user', rpcId: RpcId('subagent-rpc') }, signal },
  136. )
  137. })
  138. it('canonicalizes browser-zone provenance before delivering a child prompt', async () => {
  139. const { api, parent, followup } = bench()
  140. const alias = 'US/Pacific'
  141. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  142. .resolvedOptions().timeZone
  143. const content = [{ type: 'text' as const, text: 'continue locally' }]
  144. const signal = new AbortController().signal
  145. await expect(api.subagents.prompt(request({
  146. parentSessionId: PARENT,
  147. childSessionId: CHILD,
  148. mode: 'continuable',
  149. content,
  150. clientTimeZone: alias,
  151. }), signal)).resolves.toMatchObject({ result: { ok: true } })
  152. expect(followup).toHaveBeenCalledWith(parent, CHILD, content, {
  153. source: { kind: 'user', rpcId: RpcId('subagent-rpc'), clientTimeZone: canonical },
  154. signal,
  155. })
  156. const invalid = await api.subagents.prompt(request({
  157. parentSessionId: PARENT,
  158. childSessionId: CHILD,
  159. mode: 'continuable',
  160. content,
  161. clientTimeZone: 'Not/A_Real_Zone',
  162. }), signal)
  163. expect(invalid.result).toEqual({
  164. ok: false,
  165. error: {
  166. code: 'invalid-time-zone',
  167. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  168. details: { value: 'Not/A_Real_Zone' },
  169. },
  170. })
  171. expect(followup).toHaveBeenCalledOnce()
  172. })
  173. it('fails before delivery when the parent is absent and maps continuation failures', async () => {
  174. const absent = bench({ parentLive: false })
  175. expect((await absent.api.subagents.prompt(request({
  176. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  177. }), new AbortController().signal)).result).toMatchObject({
  178. ok: false, error: { code: 'subagent-parent-unavailable' },
  179. })
  180. expect(absent.listChildren).not.toHaveBeenCalled()
  181. const failed = bench({ followupError: new SubagentError('draining', 'DRAINING') })
  182. expect((await failed.api.subagents.prompt(request({
  183. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  184. }), new AbortController().signal)).result).toMatchObject({
  185. ok: false, error: { code: 'subagent-delivery-unavailable' },
  186. })
  187. })
  188. it('hides unexpected backend details', async () => {
  189. const catalog = bench({ listError: new Error('secret descriptor') })
  190. expect((await catalog.api.subagents.list(request({
  191. parentSessionId: PARENT,
  192. }))).result).toMatchObject({
  193. ok: false,
  194. error: { code: 'internal', message: 'subagent catalog read failed' },
  195. })
  196. const prompt = bench({ followupError: new Error('secret provider') })
  197. expect((await prompt.api.subagents.prompt(request({
  198. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  199. }), new AbortController().signal)).result).toMatchObject({
  200. ok: false,
  201. error: { code: 'internal', message: 'subagent prompt failed' },
  202. })
  203. })
  204. it('interrupts through the core primitive alone while the parent Agent is offline', async () => {
  205. const { api, interrupt, getAgent, listChildren } = bench({ parentLive: false })
  206. const response = await api.subagents.interrupt(request({
  207. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  208. }))
  209. expect(response.rpcId).toBe('subagent-rpc')
  210. expect(response.result).toEqual({ ok: true, value: { accepted: true } })
  211. expect(interrupt).toHaveBeenCalledExactlyOnceWith(CHILD, { kind: 'user', parentSessionId: PARENT })
  212. // No parent-registry or catalog dependency: this is what keeps a
  213. // live child interruptible after its parent Agent went offline.
  214. expect(getAgent).not.toHaveBeenCalled()
  215. expect(listChildren).not.toHaveBeenCalled()
  216. })
  217. it('maps interrupt authorization rejection without touching other services', async () => {
  218. const { api, listChildren } = bench({
  219. interruptError: new SubagentError('secret lineage', 'UNAUTHORIZED'),
  220. })
  221. const response = await api.subagents.interrupt(request({
  222. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  223. }))
  224. expect(response.result).toEqual({
  225. ok: false,
  226. error: {
  227. code: 'subagent-unauthorized',
  228. message: 'subagent does not belong to this parent',
  229. details: { childSessionId: CHILD },
  230. },
  231. })
  232. expect(listChildren).not.toHaveBeenCalled()
  233. })
  234. it('hides unexpected interrupt failures behind the internal code', async () => {
  235. const { api } = bench({ interruptError: new Error('secret activation state') })
  236. const response = await api.subagents.interrupt(request({
  237. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  238. }))
  239. expect(response.result).toEqual({
  240. ok: false,
  241. error: { code: 'internal', message: 'subagent interrupt failed', details: {} },
  242. })
  243. })
  244. })