api-proxy-commands.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import { MessageId, freezeMessage } from '@deepseek-ai/dsh-llm'
  2. /**
  3. * Command/skill RPC handlers and the two new frames over createApiProxy:
  4. * command.list serves the addressed agent's effective catalog (missing
  5. * registry = loud internal error), command.execute dispatches through the
  6. * registry with the carrier signal, skill.list resolves cwd from the session
  7. * header (never via the Agent registry), the host stream broadcasts
  8. * commands-changed, and the mux stream carries live queued frames plus the
  9. * open-time queue snapshot.
  10. */
  11. import { describe, expect, it, vi } from 'vitest'
  12. import { Context } from 'cordis'
  13. import AgentRegistry, { InboxItemId } from '@deepseek-ai/dsh-agent'
  14. import type { Agent, InboxItem, InboxPlacement } from '@deepseek-ai/dsh-agent'
  15. import SessionStore from '@deepseek-ai/dsh-session'
  16. import type { SessionId, UserMessage } from '@deepseek-ai/dsh-session'
  17. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  18. import ToolRegistry from '@deepseek-ai/dsh-tools'
  19. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  20. import CommandService from '@deepseek-ai/dsh-commands'
  21. import SkillService from '@deepseek-ai/dsh-skill'
  22. import type { HostFrame, MuxFrame } from '../src/api/index.ts'
  23. import type { RpcRequest, RpcResponse } from '../src/api/rpc.ts'
  24. import { RpcId } from '../src/api/rpc.ts'
  25. import { createApiProxy } from '../src/api-proxy.ts'
  26. const DEFAULTS = { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }
  27. function request<P>(payload: P): RpcRequest<P> {
  28. return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload }
  29. }
  30. let nextRpc = 1
  31. function expectOk<T>(response: RpcResponse<T>): T {
  32. expect(response.result.ok).toBe(true)
  33. if (!response.result.ok) throw new Error('unreachable')
  34. return response.result.value
  35. }
  36. function expectErr<T>(response: RpcResponse<T>): { code: string; message: string } {
  37. expect(response.result.ok).toBe(false)
  38. if (response.result.ok) throw new Error('unreachable')
  39. return response.result.error
  40. }
  41. /** Composition floor for the command/skill paths (no LLM, no persistence). */
  42. async function harness(options: { commands?: boolean; skills?: boolean } = {}): Promise<Context> {
  43. const ctx = new Context()
  44. await ctx.plugin(SessionStore)
  45. await ctx.plugin(SystemPrompt, { persona: '' })
  46. await ctx.plugin(ToolRegistry)
  47. await ctx.plugin(UserInteractionService)
  48. await ctx.plugin(AgentRegistry)
  49. if (options.skills !== false) await ctx.plugin(SkillService, {})
  50. if (options.commands !== false) await ctx.plugin(CommandService)
  51. // Host-stream opener reads the committed-workspace baseline; the stub
  52. // suffices here — the real workspace composition is api-proxy-workspace.spec's.
  53. ctx.provide('workspace', { list: () => [] } as never)
  54. return ctx
  55. }
  56. /** Register a live structural agent stub (api-proxy-view precedent: only id/session/status/ctx are read). */
  57. function stubAgent(ctx: Context, sessionId?: SessionId): Agent {
  58. const session = ctx.sessions.create(sessionId)
  59. const agent = { id: session.id, session, status: 'idle', ctx } as Agent
  60. ctx.agents.register(agent)
  61. return agent
  62. }
  63. /** Drain `count` frames from a stream, then abort it. */
  64. async function collect<F>(iterable: AsyncIterable<RpcRequest<F>>, count: number, abort: AbortController): Promise<F[]> {
  65. const frames: F[] = []
  66. for await (const frame of iterable) {
  67. frames.push(frame.payload)
  68. if (frames.length >= count) abort.abort()
  69. }
  70. return frames
  71. }
  72. describe('command.list', () => {
  73. it('serves the addressed agent\'s name-sorted catalog', async () => {
  74. const ctx = await harness()
  75. ctx.commands.register({ name: 'zeta', description: 'z', handler: () => ({ kind: 'success' }) })
  76. ctx.commands.register({ name: 'alpha', description: 'a', input: { hint: '<x>' }, handler: () => ({ kind: 'success' }) })
  77. const api = createApiProxy(ctx, DEFAULTS)
  78. const agent = stubAgent(ctx)
  79. const value = expectOk(await api.commands.list(request({ sessionId: agent.id })))
  80. expect(value.commands).toEqual([
  81. { name: 'alpha', description: 'a', input: { hint: '<x>' } },
  82. { name: 'zeta', description: 'z' },
  83. ])
  84. })
  85. it('fails loud with internal when the command registry is not mounted', async () => {
  86. const ctx = await harness({ commands: false })
  87. const api = createApiProxy(ctx, DEFAULTS)
  88. const error = expectErr(await api.commands.list(request({ sessionId: 's' as SessionId })))
  89. expect(error.code).toBe('internal')
  90. expect(error.message).toContain('command registry')
  91. })
  92. it('does not route a live subagent through the generic command domain', async () => {
  93. const ctx = await harness()
  94. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj', origin: 'subagent' } })
  95. const agent = { id: session.id, session, status: 'idle', ctx } as Agent
  96. ctx.agents.register(agent)
  97. const api = createApiProxy(ctx, DEFAULTS)
  98. const error = expectErr(await api.commands.list(request({ sessionId: agent.id })))
  99. expect(error).toMatchObject({ code: 'agent-busy' })
  100. })
  101. })
  102. describe('command.execute', () => {
  103. it('executes a known command against the addressed agent and detaches the result', async () => {
  104. const ctx = await harness()
  105. let received: string | undefined
  106. ctx.commands.register({
  107. name: 'goal',
  108. description: 'set goal',
  109. handler: (invocation) => {
  110. received = invocation.rawInput
  111. return { kind: 'success', text: `goal:${invocation.agent.id}` }
  112. },
  113. })
  114. const api = createApiProxy(ctx, DEFAULTS)
  115. const agent = stubAgent(ctx)
  116. const value = expectOk(await api.commands.execute(request({ sessionId: agent.id, line: '/goal ship it' }), new AbortController().signal))
  117. expect(value).toMatchObject({ matched: true })
  118. expect(value.commandId).toBeTruthy()
  119. expect(received).toBe(' ship it')
  120. // Pure admission on the wire: the outcome rides the durably logged
  121. // lifecycle pair instead of the response.
  122. const lifecycle = agent.session.events.filter(e => e.type === 'command/run' || e.type === 'command/done')
  123. expect(lifecycle).toMatchObject([
  124. { type: 'command/run', data: { commandId: value.commandId, name: 'goal', args: ' ship it' } },
  125. { type: 'command/done', data: { commandId: value.commandId, kind: 'success', text: `goal:${agent.id}` } },
  126. ])
  127. })
  128. it('returns matched:false when syntax or name does not resolve', async () => {
  129. const ctx = await harness()
  130. const api = createApiProxy(ctx, DEFAULTS)
  131. const agent = stubAgent(ctx)
  132. const signal = new AbortController().signal
  133. expect(expectOk(await api.commands.execute(request({ sessionId: agent.id, line: '/unknown' }), signal))).toEqual({ matched: false })
  134. expect(expectOk(await api.commands.execute(request({ sessionId: agent.id, line: 'not a command' }), signal))).toEqual({ matched: false })
  135. })
  136. it('maps a session miss to session-not-found and a registry gap to internal', async () => {
  137. const ctx = await harness()
  138. const api = createApiProxy(ctx, DEFAULTS)
  139. const missing = expectErr(await api.commands.execute(
  140. request({ sessionId: 'session-nope' as SessionId, line: '/x' }), new AbortController().signal))
  141. expect(missing.code).toBe('internal') // Cold Agent-bound access fails loud when persistence is absent.
  142. const bare = await harness({ commands: false })
  143. const bareApi = createApiProxy(bare, DEFAULTS)
  144. expect(expectErr(await bareApi.commands.execute(
  145. request({ sessionId: 's' as SessionId, line: '/x' }), new AbortController().signal)).code).toBe('internal')
  146. })
  147. it('reports an aborted handler as cancelled and a throwing handler as internal', async () => {
  148. const ctx = await harness()
  149. ctx.commands.register({
  150. name: 'hang',
  151. description: 'never settles on its own',
  152. handler: () => new Promise(() => { /* settled only by abort */ }),
  153. })
  154. ctx.commands.register({
  155. name: 'boom',
  156. description: 'throws',
  157. handler: () => { throw new Error('kaboom') },
  158. })
  159. const api = createApiProxy(ctx, DEFAULTS)
  160. const agent = stubAgent(ctx)
  161. const controller = new AbortController()
  162. const pending = api.commands.execute(request({ sessionId: agent.id, line: '/hang' }), controller.signal)
  163. controller.abort()
  164. expect(expectErr(await pending).code).toBe('cancelled')
  165. const thrown = expectErr(await api.commands.execute(request({ sessionId: agent.id, line: '/boom' }), new AbortController().signal))
  166. expect(thrown.code).toBe('internal')
  167. expect(thrown.message).toContain('kaboom')
  168. })
  169. })
  170. describe('skill.list', () => {
  171. it('lists skills for the session cwd taken from the header', async () => {
  172. const ctx = await harness()
  173. const seenCwds: (string | undefined)[] = []
  174. ctx.skills.registerProvider(() => ({
  175. name: 'probe',
  176. list: (options) => {
  177. seenCwds.push(options.cwd)
  178. return Promise.resolve([
  179. {
  180. name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing',
  181. invocation: { modelInvocable: true, userInvocable: true },
  182. source: 'custom', provider: 'probe', rank: 0, locator: null,
  183. },
  184. {
  185. name: 'user-only', description: 'User-only',
  186. invocation: { modelInvocable: false, userInvocable: true },
  187. source: 'custom', provider: 'probe', rank: 0, locator: null,
  188. },
  189. {
  190. name: 'model-only', description: 'Model-only',
  191. invocation: { modelInvocable: true, userInvocable: false },
  192. source: 'custom', provider: 'probe', rank: 0, locator: null,
  193. },
  194. {
  195. name: 'trusted-only', description: 'Trusted-only',
  196. invocation: { modelInvocable: false, userInvocable: false },
  197. source: 'custom', provider: 'probe', rank: 0, locator: null,
  198. },
  199. ])
  200. },
  201. get: () => Promise.resolve(undefined),
  202. }))
  203. const api = createApiProxy(ctx, DEFAULTS)
  204. // No agent is registered for this session: header resolution must not
  205. // touch (or resume through) the Agent registry.
  206. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  207. const value = expectOk(await api.skills.list(request({ sessionId: session.id })))
  208. expect(value.skills).toEqual([{ name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing' }])
  209. expect(seenCwds).toEqual(['/proj'])
  210. expect(ctx.agents.get(session.id)).toBeUndefined()
  211. })
  212. it('fails loud on an unattached session id (business error, no resume attempt)', async () => {
  213. const ctx = await harness()
  214. const api = createApiProxy(ctx, DEFAULTS)
  215. const error = expectErr(await api.skills.list(request({ sessionId: 'session-cold' as SessionId })))
  216. expect(error.code).toBe('session-not-found')
  217. })
  218. it('fails loud with internal when the skill registry is not mounted', async () => {
  219. const ctx = await harness({ skills: false })
  220. const api = createApiProxy(ctx, DEFAULTS)
  221. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  222. const error = expectErr(await api.skills.list(request({ sessionId: session.id })))
  223. expect(error.code).toBe('internal')
  224. expect(error.message).toContain('skill registry is absent')
  225. })
  226. it('folds a provider failure into internal', async () => {
  227. const ctx = await harness()
  228. ctx.skills.registerProvider(() => ({
  229. name: 'broken',
  230. list: () => Promise.reject(new Error('directory exploded')),
  231. get: () => Promise.resolve(undefined),
  232. }))
  233. const api = createApiProxy(ctx, DEFAULTS)
  234. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  235. const response = await api.skills.list(request({ sessionId: session.id }))
  236. // dsh-skill contains one provider's failure (logs and serves the rest), so
  237. // this surfaces as an empty ok catalog rather than an error.
  238. const value = expectOk(response)
  239. expect(value.skills).toEqual([])
  240. })
  241. })
  242. describe('host/commands-changed frame', () => {
  243. it('broadcasts on registry change', async () => {
  244. const ctx = await harness()
  245. const api = createApiProxy(ctx, DEFAULTS)
  246. const abort = new AbortController()
  247. const stream = api.events.host({ rpcId: RpcId('t-host'), payload: {} }, abort.signal)
  248. const collected = collect<HostFrame>(stream, 1, abort)
  249. ctx.commands.register({ name: 'late', description: 'l', handler: () => ({ kind: 'success' }) })
  250. expect(await collected).toEqual([{ type: 'host/commands-changed' }])
  251. })
  252. })
  253. /** Build one frozen inbox message for the live `agent/inbox/*` events. */
  254. function inboxMessage(id: string, text: string, rpcId?: string): UserMessage {
  255. return freezeMessage({
  256. id: MessageId(id),
  257. role: 'user',
  258. content: [{ type: 'text' as const, text }],
  259. source: rpcId === undefined ? { kind: 'user' as const } : { kind: 'user' as const, rpcId: RpcId(rpcId) },
  260. })
  261. }
  262. /** Build one addressable inbox occurrence around a frozen message. */
  263. function inboxItem(id: string, message: UserMessage, placement: InboxPlacement): InboxItem {
  264. return { id: InboxItemId(id), message, placement }
  265. }
  266. describe('session.updateQueue', () => {
  267. it('routes an addressable action and reports a lost claim race', async () => {
  268. const ctx = await harness()
  269. const agent = stubAgent(ctx)
  270. const seen: unknown[] = []
  271. agent.updateInbox = (id, action) => {
  272. seen.push({ id, action })
  273. return id === InboxItemId('present') ? 'applied' : 'not-found'
  274. }
  275. const api = createApiProxy(ctx, DEFAULTS)
  276. const applied = await api.sessions.updateQueue({
  277. rpcId: RpcId('q-apply'),
  278. payload: {
  279. sessionId: agent.id,
  280. itemId: InboxItemId('present'),
  281. action: { kind: 'edit', content: [{ type: 'text', text: 'edited' }] },
  282. },
  283. })
  284. expect(expectOk(applied)).toEqual({ accepted: true })
  285. const missing = await api.sessions.updateQueue({
  286. rpcId: RpcId('q-missing'),
  287. payload: {
  288. sessionId: agent.id,
  289. itemId: InboxItemId('claimed'),
  290. action: { kind: 'remove' },
  291. },
  292. })
  293. expect(expectErr(missing)).toMatchObject({ code: 'queue-item-not-found' })
  294. expect(seen).toEqual([
  295. { id: 'present', action: { kind: 'edit', content: [{ type: 'text', text: 'edited' }] } },
  296. { id: 'claimed', action: { kind: 'remove' } },
  297. ])
  298. })
  299. it('rejects a stale occurrence without resuming a cold agent', async () => {
  300. const ctx = await harness()
  301. const resume = vi.spyOn(ctx.agents, 'resume')
  302. const api = createApiProxy(ctx, DEFAULTS)
  303. const response = await api.sessions.updateQueue({
  304. rpcId: RpcId('q-cold'),
  305. payload: {
  306. sessionId: 'cold-session' as SessionId,
  307. itemId: InboxItemId('stale-item'),
  308. action: { kind: 'remove' },
  309. },
  310. })
  311. expect(expectErr(response)).toMatchObject({ code: 'queue-item-not-found' })
  312. expect(resume).not.toHaveBeenCalled()
  313. })
  314. })
  315. describe('session/queue frames', () => {
  316. it('folds nested mutations observed before their outer enqueue', async () => {
  317. const ctx = await harness()
  318. const agent = stubAgent(ctx)
  319. const original = inboxItem('i-edit', inboxMessage('m-edit', 'before'), 'queued')
  320. const edited = inboxItem('i-edit', inboxMessage('m-edit', 'after'), 'queued')
  321. const removed = inboxItem('i-remove', inboxMessage('m-remove', 'remove me'), 'queued')
  322. ctx.on('agent/inbox/enqueue', (subject, item) => {
  323. if (subject !== agent) return
  324. if (item.id === original.id) ctx.emit('agent/inbox/update', agent, edited)
  325. if (item.id === removed.id) ctx.emit('agent/inbox/discard', agent, [removed])
  326. })
  327. const api = createApiProxy(ctx, DEFAULTS)
  328. const live = new AbortController()
  329. const collected = collect<MuxFrame>(
  330. api.events.mux({ rpcId: RpcId('t-mux-reentrant'), payload: {} }, live.signal), 2, live)
  331. ctx.emit('agent/inbox/enqueue', agent, original)
  332. ctx.emit('agent/inbox/enqueue', agent, removed)
  333. const liveFrames = (await collected).filter(frame => frame.type === 'session/queue')
  334. expect(liveFrames.map(frame => frame.items)).toEqual([
  335. [{ id: edited.id, message: edited.message }],
  336. ])
  337. const replay = new AbortController()
  338. const replayFrames = await collect<MuxFrame>(
  339. api.events.mux({ rpcId: RpcId('t-mux-reentrant-replay'), payload: {} }, replay.signal), 2, replay)
  340. expect(replayFrames.filter(frame => frame.type === 'session/queue')).toEqual(liveFrames)
  341. })
  342. it('publishes complete live snapshots and replays the latest snapshot on reconnect', async () => {
  343. const ctx = await harness()
  344. const api = createApiProxy(ctx, DEFAULTS)
  345. const agent = stubAgent(ctx)
  346. const live = new AbortController()
  347. const liveStream = api.events.mux({ rpcId: RpcId('t-mux-live'), payload: {} }, live.signal)
  348. // subscribed baseline + one queued snapshot; pending steering stays off this wire.
  349. const liveCollected = collect<MuxFrame>(liveStream, 2, live)
  350. const queued = inboxItem('i-1', inboxMessage('m-1', 'queued prompt'), 'queued')
  351. const steering = inboxItem('i-2', inboxMessage('m-2', 'steering prompt'), 'steering')
  352. ctx.emit('agent/inbox/enqueue', agent, queued)
  353. ctx.emit('agent/inbox/enqueue', agent, steering)
  354. const liveFrames = (await liveCollected).filter(f => f.type === 'session/queue')
  355. expect(liveFrames).toEqual([
  356. {
  357. type: 'session/queue',
  358. sessionId: agent.id,
  359. items: [{ id: queued.id, message: queued.message }],
  360. },
  361. ])
  362. // A fresh mux connection replays only the current authoritative snapshot.
  363. const replay = new AbortController()
  364. const replayFrames = await collect<MuxFrame>(
  365. api.events.mux({ rpcId: RpcId('t-mux-replay'), payload: {} }, replay.signal), 2, replay)
  366. expect(replayFrames.filter(f => f.type === 'session/queue')).toEqual([liveFrames[0]])
  367. })
  368. it('publishes edits in place in the authoritative order', async () => {
  369. const ctx = await harness()
  370. const api = createApiProxy(ctx, DEFAULTS)
  371. const agent = stubAgent(ctx)
  372. const abort = new AbortController()
  373. const collected = collect<MuxFrame>(
  374. api.events.mux({ rpcId: RpcId('t-mux-updates'), payload: {} }, abort.signal), 5, abort)
  375. const first = inboxItem('i-a', inboxMessage('m-a', 'a'), 'queued')
  376. const second = inboxItem('i-b', inboxMessage('m-b', 'b'), 'queued')
  377. const edited = inboxItem('i-b', inboxMessage('m-b', 'b edited'), 'queued')
  378. ctx.emit('agent/inbox/enqueue', agent, first)
  379. ctx.emit('agent/inbox/enqueue', agent, second)
  380. ctx.emit('agent/inbox/update', agent, edited)
  381. ctx.emit('agent/inbox/dequeue', agent, edited)
  382. const frames = (await collected).filter(frame => frame.type === 'session/queue')
  383. expect(frames.map(frame => frame.items)).toEqual([
  384. [{ id: first.id, message: first.message }],
  385. [{ id: first.id, message: first.message }, { id: second.id, message: second.message }],
  386. [{ id: first.id, message: first.message }, { id: edited.id, message: edited.message }],
  387. [{ id: first.id, message: first.message }],
  388. ])
  389. })
  390. it('publishes an empty snapshot after terminal discard', async () => {
  391. const ctx = await harness()
  392. const api = createApiProxy(ctx, DEFAULTS)
  393. const agent = stubAgent(ctx)
  394. const doomed = inboxItem('i-doomed', inboxMessage('m-5', 'doomed'), 'queued')
  395. ctx.emit('agent/inbox/enqueue', agent, doomed)
  396. ctx.emit('agent/inbox/discard', agent, [doomed])
  397. const abort = new AbortController()
  398. const frames = await collect<MuxFrame>(
  399. api.events.mux({ rpcId: RpcId('t-mux-swept'), payload: {} }, abort.signal), 1, abort)
  400. expect(frames.filter(frame => frame.type === 'session/queue')).toHaveLength(0)
  401. })
  402. })