api-proxy-subagents.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import type { SessionEvent, SessionHeader, 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. /** Persistence forgets the child entirely (the vanished-mid-read race). */
  22. storedChild?: false
  23. /** Attach the child to the live session store instead of persistence only. */
  24. liveChild?: true
  25. /** Every registered projection unit throws on this child's payloads. */
  26. projectionsThrow?: true
  27. historyParent?: SessionId
  28. } = {}) {
  29. const parent = { id: PARENT }
  30. const child = options.childStatus === undefined
  31. ? undefined
  32. : { id: CHILD, status: options.childStatus }
  33. const getAgent = vi.fn((id: SessionId) => {
  34. if (options.parentLive !== false && id === PARENT) return parent
  35. if (id === CHILD) return child
  36. return undefined
  37. })
  38. const listChildren = vi.fn(() => options.listError === undefined
  39. ? Promise.resolve(options.entries ?? [
  40. {
  41. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  42. activity: 'inactive', hasChildren: false,
  43. },
  44. ])
  45. : Promise.reject(options.listError))
  46. const followup = vi.fn((
  47. _parent: unknown,
  48. _childId: SessionId,
  49. _content: unknown,
  50. _delivery: {
  51. source: { kind: string; rpcId: RpcId; clientTimeZone?: string }
  52. signal: AbortSignal
  53. },
  54. ) => options.followupError === undefined
  55. ? Promise.resolve('message-1')
  56. : Promise.reject(options.followupError))
  57. const interrupt = vi.fn((
  58. _targetSessionId: SessionId,
  59. _authority: { kind: 'user'; parentSessionId: SessionId },
  60. ) => {
  61. if (options.interruptError !== undefined) throw options.interruptError
  62. })
  63. const childHeader = {
  64. version: 0, id: CHILD, createdAt: 1, cwd: '/proj', parentSession: options.historyParent ?? PARENT,
  65. } satisfies SessionHeader
  66. const childEvents = [
  67. { type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } } },
  68. ] as unknown as SessionEvent[]
  69. const inspect = vi.fn(() => Promise.resolve({ meta: childHeader, events: childEvents }))
  70. const liveBlock = { values: {}, asOfSeq: 3 }
  71. const coldBlock = { values: {}, asOfSeq: 0 }
  72. const snapshot = vi.fn(() => {
  73. if (options.projectionsThrow === true) throw new Error('hostile unit')
  74. return liveBlock
  75. })
  76. const restore = vi.fn(() => {
  77. if (options.projectionsThrow === true) throw new Error('hostile unit')
  78. return { snapshot: coldBlock }
  79. })
  80. const ctx = new Context()
  81. ctx.provide('agents', { get: getAgent })
  82. ctx.provide('subagents', { listChildren, followup, interrupt })
  83. ctx.provide('sessions', {
  84. get: (id: SessionId) => options.liveChild === true && id === CHILD
  85. ? { id: CHILD, header: childHeader, events: childEvents }
  86. : undefined,
  87. })
  88. ctx.provide('sessionPersistence', {
  89. list: () => Promise.resolve(options.storedChild === false ? [] : [childHeader]),
  90. inspect,
  91. locate: () => undefined,
  92. })
  93. // The gateway's own projection push feed subscribes at construction; the
  94. // no-op disposer keeps that feed quiet while these tests pin history reads.
  95. ctx.provide('sessionProjections', { snapshot, restore, onChanged: () => () => {} })
  96. ctx.provide('userInteraction', { registerProvider: () => () => {} })
  97. const api = createApiProxy(ctx, {
  98. defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp',
  99. })
  100. return { api, getAgent, listChildren, inspect, snapshot, restore, followup, interrupt, parent }
  101. }
  102. describe('subagent gateway', () => {
  103. it('lists the complete catalog and reports exact live-parent availability', async () => {
  104. const { api, listChildren } = bench({ parentLive: false, entries: [
  105. {
  106. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  107. activity: 'inactive', hasChildren: true,
  108. },
  109. {
  110. kind: 'child', id: sid('one-shot'), mode: 'one-shot',
  111. activity: 'inactive', hasChildren: false,
  112. },
  113. { kind: 'diagnostic', id: sid('bad'), reason: 'corrupt' },
  114. ] })
  115. const response = await api.subagents.list(request({ parentSessionId: PARENT }))
  116. expect(response.rpcId).toBe('subagent-rpc')
  117. expect(response.result).toMatchObject({
  118. ok: true,
  119. value: {
  120. parentAvailable: false,
  121. entries: [
  122. { kind: 'child', mode: 'continuable' },
  123. { kind: 'child', mode: 'one-shot' },
  124. { kind: 'diagnostic' },
  125. ],
  126. },
  127. })
  128. expect(listChildren).toHaveBeenCalledWith(PARENT, undefined)
  129. })
  130. it('derives catalog activity from the live child Agent rather than Session residency', async () => {
  131. const residentIdle = bench({ childStatus: 'idle', entries: [{
  132. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  133. activity: 'running', hasChildren: false,
  134. }] })
  135. expect((await residentIdle.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  136. .toMatchObject({ ok: true, value: { entries: [{ activity: 'inactive' }] } })
  137. const running = bench({ childStatus: 'running' })
  138. expect((await running.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  139. .toMatchObject({ ok: true, value: { entries: [{ activity: 'running' }] } })
  140. })
  141. it('reads a healthy direct child without looking up or activating any Agent', async () => {
  142. const { api, getAgent, inspect, restore } = bench()
  143. const response = await api.subagents.history(request({
  144. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', maxMessages: 10,
  145. }))
  146. expect(response.result).toMatchObject({
  147. ok: true,
  148. value: { hasMore: false, events: [{ event: { type: 'user/message', seq: 0 } }] },
  149. })
  150. expect(inspect).toHaveBeenCalledWith(CHILD)
  151. expect(restore).toHaveBeenCalledTimes(1)
  152. expect(getAgent).not.toHaveBeenCalled()
  153. })
  154. it('serves a live child from the in-memory snapshot and the watermark projections', async () => {
  155. const { api, inspect, snapshot, restore } = bench({ liveChild: true })
  156. const response = await api.subagents.history(request({
  157. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  158. }))
  159. expect(response.result).toMatchObject({
  160. ok: true,
  161. value: { hasMore: false, projections: { asOfSeq: 3 } },
  162. })
  163. expect(snapshot).toHaveBeenCalledTimes(1)
  164. expect(restore).not.toHaveBeenCalled()
  165. expect(inspect).not.toHaveBeenCalled()
  166. })
  167. it('serves the page without projections when a hostile unit breaks the fold', async () => {
  168. const cold = bench({ projectionsThrow: true })
  169. const coldResponse = await cold.api.subagents.history(request({
  170. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  171. }))
  172. expect(coldResponse.result).toMatchObject({
  173. ok: true,
  174. value: { hasMore: false, events: [{ event: { type: 'user/message', seq: 0 } }] },
  175. })
  176. if (coldResponse.result.ok) expect('projections' in coldResponse.result.value).toBe(false)
  177. const live = bench({ projectionsThrow: true, liveChild: true })
  178. const liveResponse = await live.api.subagents.history(request({
  179. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  180. }))
  181. expect(liveResponse.result).toMatchObject({
  182. ok: true,
  183. value: { hasMore: false, events: [{ event: { type: 'user/message', seq: 0 } }] },
  184. })
  185. if (liveResponse.result.ok) expect('projections' in liveResponse.result.value).toBe(false)
  186. expect(live.snapshot).toHaveBeenCalledTimes(1)
  187. })
  188. it('reads one-shot history and rejects an address with the wrong mode', async () => {
  189. const oneShot = {
  190. kind: 'child', id: CHILD, mode: 'one-shot', label: 'batch',
  191. activity: 'inactive', hasChildren: false,
  192. }
  193. const { api, inspect } = bench({ entries: [oneShot] })
  194. expect((await api.subagents.history(request({
  195. parentSessionId: PARENT, childSessionId: CHILD, mode: 'one-shot',
  196. }))).result).toMatchObject({ ok: true })
  197. expect((await api.subagents.history(request({
  198. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  199. }))).result).toMatchObject({ ok: false, error: { code: 'subagent-not-found' } })
  200. expect(inspect).toHaveBeenCalledTimes(1)
  201. })
  202. it('rejects a diagnostic address before reading history', async () => {
  203. const { api, inspect } = bench({ entries: [
  204. { kind: 'diagnostic', id: CHILD, reason: 'unsupported' },
  205. ] })
  206. const response = await api.subagents.history(request({
  207. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  208. }))
  209. expect(response.result).toMatchObject({
  210. ok: false,
  211. error: {
  212. code: 'subagent-catalog-diagnostic',
  213. details: { parentSessionId: PARENT, childSessionId: CHILD, reason: 'unsupported' },
  214. },
  215. })
  216. expect(inspect).not.toHaveBeenCalled()
  217. })
  218. it('maps the missing projections capability to one wire face on list, history, and prompt', async () => {
  219. const listError = () => new SubagentError(
  220. 'listing subagents requires the sessionProjections registry (load @deepseek-ai/dsh-session-projection)',
  221. 'SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE',
  222. )
  223. const expected = {
  224. code: 'internal',
  225. message: 'subagent catalog is unavailable: this deployment does not mount the sessionProjections registry (load @deepseek-ai/dsh-session-projection)',
  226. }
  227. const list = bench({ listError: listError() })
  228. expect((await list.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  229. .toMatchObject({ ok: false, error: expected })
  230. const history = bench({ listError: listError() })
  231. expect((await history.api.subagents.history(request({
  232. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  233. }))).result).toMatchObject({ ok: false, error: expected })
  234. expect(history.inspect).not.toHaveBeenCalled()
  235. const prompt = bench({ listError: listError() })
  236. expect((await prompt.api.subagents.prompt(request({
  237. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  238. }), new AbortController().signal)).result).toMatchObject({ ok: false, error: expected })
  239. expect(prompt.followup).not.toHaveBeenCalled()
  240. })
  241. it('routes human content through the exact live parent with rpc attribution', async () => {
  242. const { api, parent, followup } = bench()
  243. const content = [{ type: 'text' as const, text: '继续' }]
  244. const signal = new AbortController().signal
  245. const response = await api.subagents.prompt(request({
  246. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content,
  247. }), signal)
  248. expect(response.result).toMatchObject({
  249. ok: true, value: { messageId: 'message-1' },
  250. })
  251. expect(followup).toHaveBeenCalledWith(
  252. parent,
  253. CHILD,
  254. content,
  255. { source: { kind: 'user', rpcId: RpcId('subagent-rpc') }, signal },
  256. )
  257. })
  258. it('canonicalizes browser-zone provenance before delivering a child prompt', async () => {
  259. const { api, parent, followup } = bench()
  260. const alias = 'US/Pacific'
  261. const canonical = new Intl.DateTimeFormat('en-US', { timeZone: alias })
  262. .resolvedOptions().timeZone
  263. const content = [{ type: 'text' as const, text: 'continue locally' }]
  264. const signal = new AbortController().signal
  265. await expect(api.subagents.prompt(request({
  266. parentSessionId: PARENT,
  267. childSessionId: CHILD,
  268. mode: 'continuable',
  269. content,
  270. clientTimeZone: alias,
  271. }), signal)).resolves.toMatchObject({ result: { ok: true } })
  272. expect(followup).toHaveBeenCalledWith(parent, CHILD, content, {
  273. source: { kind: 'user', rpcId: RpcId('subagent-rpc'), clientTimeZone: canonical },
  274. signal,
  275. })
  276. const invalid = await api.subagents.prompt(request({
  277. parentSessionId: PARENT,
  278. childSessionId: CHILD,
  279. mode: 'continuable',
  280. content,
  281. clientTimeZone: 'Not/A_Real_Zone',
  282. }), signal)
  283. expect(invalid.result).toEqual({
  284. ok: false,
  285. error: {
  286. code: 'invalid-time-zone',
  287. message: 'clientTimeZone must be UTC or a valid IANA Area/Location name',
  288. details: { value: 'Not/A_Real_Zone' },
  289. },
  290. })
  291. expect(followup).toHaveBeenCalledOnce()
  292. })
  293. it('fails before delivery when the parent is absent and maps continuation failures', async () => {
  294. const absent = bench({ parentLive: false })
  295. expect((await absent.api.subagents.prompt(request({
  296. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  297. }), new AbortController().signal)).result).toMatchObject({
  298. ok: false, error: { code: 'subagent-parent-unavailable' },
  299. })
  300. expect(absent.listChildren).not.toHaveBeenCalled()
  301. const failed = bench({ followupError: new SubagentError('draining', 'DRAINING') })
  302. expect((await failed.api.subagents.prompt(request({
  303. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  304. }), new AbortController().signal)).result).toMatchObject({
  305. ok: false, error: { code: 'subagent-delivery-unavailable' },
  306. })
  307. })
  308. it('maps history disappearance and hides unexpected backend details', async () => {
  309. const disappeared = bench({ storedChild: false })
  310. expect((await disappeared.api.subagents.history(request({
  311. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  312. }))).result).toMatchObject({
  313. ok: false,
  314. error: {
  315. code: 'subagent-not-found',
  316. message: 'subagent disappeared during history read',
  317. details: { parentSessionId: PARENT, childSessionId: CHILD },
  318. },
  319. })
  320. const catalog = bench({ listError: new Error('secret descriptor') })
  321. expect((await catalog.api.subagents.list(request({
  322. parentSessionId: PARENT,
  323. }))).result).toMatchObject({
  324. ok: false,
  325. error: { code: 'internal', message: 'subagent catalog read failed' },
  326. })
  327. const prompt = bench({ followupError: new Error('secret provider') })
  328. expect((await prompt.api.subagents.prompt(request({
  329. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  330. }), new AbortController().signal)).result).toMatchObject({
  331. ok: false,
  332. error: { code: 'internal', message: 'subagent prompt failed' },
  333. })
  334. })
  335. it('interrupts through the core primitive alone while the parent Agent is offline', async () => {
  336. const { api, interrupt, getAgent, listChildren, inspect } = bench({ parentLive: false })
  337. const response = await api.subagents.interrupt(request({
  338. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  339. }))
  340. expect(response.rpcId).toBe('subagent-rpc')
  341. expect(response.result).toEqual({ ok: true, value: { accepted: true } })
  342. expect(interrupt).toHaveBeenCalledExactlyOnceWith(CHILD, { kind: 'user', parentSessionId: PARENT })
  343. // No parent-registry, catalog, or history dependency: this is what keeps a
  344. // live child interruptible after its parent Agent went offline.
  345. expect(getAgent).not.toHaveBeenCalled()
  346. expect(listChildren).not.toHaveBeenCalled()
  347. expect(inspect).not.toHaveBeenCalled()
  348. })
  349. it('maps interrupt authorization rejection without touching other services', async () => {
  350. const { api, listChildren } = bench({
  351. interruptError: new SubagentError('secret lineage', 'UNAUTHORIZED'),
  352. })
  353. const response = await api.subagents.interrupt(request({
  354. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  355. }))
  356. expect(response.result).toEqual({
  357. ok: false,
  358. error: {
  359. code: 'subagent-unauthorized',
  360. message: 'subagent does not belong to this parent',
  361. details: { childSessionId: CHILD },
  362. },
  363. })
  364. expect(listChildren).not.toHaveBeenCalled()
  365. })
  366. it('hides unexpected interrupt failures behind the internal code', async () => {
  367. const { api } = bench({ interruptError: new Error('secret activation state') })
  368. const response = await api.subagents.interrupt(request({
  369. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' as const,
  370. }))
  371. expect(response.result).toEqual({
  372. ok: false,
  373. error: { code: 'internal', message: 'subagent interrupt failed', details: {} },
  374. })
  375. })
  376. })