api-proxy-commands.spec.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 } from 'vitest'
  12. import { Context } from 'cordis'
  13. import AgentRegistry, {} from '@deepseek-ai/dsh-agent'
  14. import type { Agent } 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. })
  93. describe('command.execute', () => {
  94. it('executes a known command against the addressed agent and detaches the result', async () => {
  95. const ctx = await harness()
  96. let received: string | undefined
  97. ctx.commands.register({
  98. name: 'goal',
  99. description: 'set goal',
  100. handler: (invocation) => {
  101. received = invocation.rawInput
  102. return { kind: 'success', text: `goal:${invocation.agent.id}` }
  103. },
  104. })
  105. const api = createApiProxy(ctx, DEFAULTS)
  106. const agent = stubAgent(ctx)
  107. const value = expectOk(await api.commands.execute(request({ sessionId: agent.id, line: '/goal ship it' }), new AbortController().signal))
  108. expect(value).toMatchObject({ matched: true })
  109. expect(value.commandId).toBeTruthy()
  110. expect(received).toBe(' ship it')
  111. // Pure admission on the wire: the outcome rides the durably logged
  112. // lifecycle pair instead of the response.
  113. const lifecycle = agent.session.events.filter(e => e.type === 'command/run' || e.type === 'command/done')
  114. expect(lifecycle).toMatchObject([
  115. { type: 'command/run', data: { commandId: value.commandId, name: 'goal', args: ' ship it' } },
  116. { type: 'command/done', data: { commandId: value.commandId, kind: 'success', text: `goal:${agent.id}` } },
  117. ])
  118. })
  119. it('returns matched:false when syntax or name does not resolve', async () => {
  120. const ctx = await harness()
  121. const api = createApiProxy(ctx, DEFAULTS)
  122. const agent = stubAgent(ctx)
  123. const signal = new AbortController().signal
  124. expect(expectOk(await api.commands.execute(request({ sessionId: agent.id, line: '/unknown' }), signal))).toEqual({ matched: false })
  125. expect(expectOk(await api.commands.execute(request({ sessionId: agent.id, line: 'not a command' }), signal))).toEqual({ matched: false })
  126. })
  127. it('maps a session miss to session-not-found and a registry gap to internal', async () => {
  128. const ctx = await harness()
  129. const api = createApiProxy(ctx, DEFAULTS)
  130. const missing = expectErr(await api.commands.execute(
  131. request({ sessionId: 'session-nope' as SessionId, line: '/x' }), new AbortController().signal))
  132. expect(missing.code).toBe('internal') // no persistence configured: resume fails loud past the gate
  133. const bare = await harness({ commands: false })
  134. const bareApi = createApiProxy(bare, DEFAULTS)
  135. expect(expectErr(await bareApi.commands.execute(
  136. request({ sessionId: 's' as SessionId, line: '/x' }), new AbortController().signal)).code).toBe('internal')
  137. })
  138. it('reports an aborted handler as cancelled and a throwing handler as internal', async () => {
  139. const ctx = await harness()
  140. ctx.commands.register({
  141. name: 'hang',
  142. description: 'never settles on its own',
  143. handler: () => new Promise(() => { /* settled only by abort */ }),
  144. })
  145. ctx.commands.register({
  146. name: 'boom',
  147. description: 'throws',
  148. handler: () => { throw new Error('kaboom') },
  149. })
  150. const api = createApiProxy(ctx, DEFAULTS)
  151. const agent = stubAgent(ctx)
  152. const controller = new AbortController()
  153. const pending = api.commands.execute(request({ sessionId: agent.id, line: '/hang' }), controller.signal)
  154. controller.abort()
  155. expect(expectErr(await pending).code).toBe('cancelled')
  156. const thrown = expectErr(await api.commands.execute(request({ sessionId: agent.id, line: '/boom' }), new AbortController().signal))
  157. expect(thrown.code).toBe('internal')
  158. expect(thrown.message).toContain('kaboom')
  159. })
  160. })
  161. describe('skill.list', () => {
  162. it('lists skills for the session cwd taken from the header', async () => {
  163. const ctx = await harness()
  164. const seenCwds: (string | undefined)[] = []
  165. ctx.skills.registerProvider({
  166. name: 'probe',
  167. list: (options) => {
  168. seenCwds.push(options.cwd)
  169. return Promise.resolve([{
  170. name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing',
  171. source: 'custom', provider: 'probe', rank: 0, locator: null,
  172. }])
  173. },
  174. get: () => Promise.resolve(undefined),
  175. })
  176. const api = createApiProxy(ctx, DEFAULTS)
  177. // No agent is registered for this session: header resolution must not
  178. // touch (or resume through) the Agent registry.
  179. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  180. const value = expectOk(await api.skills.list(request({ sessionId: session.id })))
  181. expect(value.skills).toEqual([{ name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing' }])
  182. expect(seenCwds).toEqual(['/proj'])
  183. expect(ctx.agents.get(session.id)).toBeUndefined()
  184. })
  185. it('fails loud on an unattached session id (business error, no resume attempt)', async () => {
  186. const ctx = await harness()
  187. const api = createApiProxy(ctx, DEFAULTS)
  188. const error = expectErr(await api.skills.list(request({ sessionId: 'session-cold' as SessionId })))
  189. expect(error.code).toBe('session-not-found')
  190. })
  191. it('fails loud with internal when the skill registry is not mounted', async () => {
  192. const ctx = await harness({ skills: false })
  193. const api = createApiProxy(ctx, DEFAULTS)
  194. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  195. const error = expectErr(await api.skills.list(request({ sessionId: session.id })))
  196. expect(error.code).toBe('internal')
  197. expect(error.message).toContain('skill registry is absent')
  198. })
  199. it('folds a provider failure into internal', async () => {
  200. const ctx = await harness()
  201. ctx.skills.registerProvider({
  202. name: 'broken',
  203. list: () => Promise.reject(new Error('directory exploded')),
  204. get: () => Promise.resolve(undefined),
  205. })
  206. const api = createApiProxy(ctx, DEFAULTS)
  207. const session = ctx.sessions.create(undefined, { meta: { cwd: '/proj' } })
  208. const response = await api.skills.list(request({ sessionId: session.id }))
  209. // dsh-skill contains one provider's failure (logs and serves the rest), so
  210. // this surfaces as an empty ok catalog rather than an error.
  211. const value = expectOk(response)
  212. expect(value.skills).toEqual([])
  213. })
  214. })
  215. describe('host/commands-changed frame', () => {
  216. it('broadcasts on registry change', async () => {
  217. const ctx = await harness()
  218. const api = createApiProxy(ctx, DEFAULTS)
  219. const abort = new AbortController()
  220. const stream = api.events.host({ rpcId: RpcId('t-host'), payload: {} }, abort.signal)
  221. const collected = collect<HostFrame>(stream, 1, abort)
  222. ctx.commands.register({ name: 'late', description: 'l', handler: () => ({ kind: 'success' }) })
  223. expect(await collected).toEqual([{ type: 'host/commands-changed' }])
  224. })
  225. })
  226. /** Build one frozen inbox message for the live `agent/inbox/*` events. */
  227. function inboxMessage(id: string, text: string, rpcId?: string): UserMessage {
  228. return freezeMessage({
  229. id: MessageId(id),
  230. role: 'user',
  231. content: [{ type: 'text' as const, text }],
  232. source: rpcId === undefined ? { kind: 'user' as const } : { kind: 'user' as const, rpcId: RpcId(rpcId) },
  233. })
  234. }
  235. describe('session/queued frames', () => {
  236. it('forwards live enqueue events and replays the snapshot on a later mux open', async () => {
  237. const ctx = await harness()
  238. const api = createApiProxy(ctx, DEFAULTS)
  239. const agent = stubAgent(ctx)
  240. const live = new AbortController()
  241. const liveStream = api.events.mux({ rpcId: RpcId('t-mux-live'), payload: {} }, live.signal)
  242. // subscribed baseline + 2 queued frames
  243. const liveCollected = collect<MuxFrame>(liveStream, 3, live)
  244. const queued = inboxMessage('m-1', 'queued prompt')
  245. const steering = inboxMessage('m-2', 'queued prompt')
  246. ctx.emit('agent/inbox/enqueue', agent, queued, 'queued')
  247. ctx.emit('agent/inbox/enqueue', agent, steering, 'steering')
  248. const liveFrames = (await liveCollected).filter(f => f.type === 'session/queued')
  249. expect(liveFrames).toEqual([
  250. { type: 'session/queued', sessionId: agent.id, message: queued, steering: false },
  251. { type: 'session/queued', sessionId: agent.id, message: steering, steering: true },
  252. ])
  253. // A fresh mux connection replays the still-pending entries as its baseline.
  254. const replay = new AbortController()
  255. const replayFrames = await collect<MuxFrame>(
  256. api.events.mux({ rpcId: RpcId('t-mux-replay'), payload: {} }, replay.signal), 3, replay)
  257. expect(replayFrames.filter(f => f.type === 'session/queued')).toEqual(liveFrames)
  258. })
  259. it('retires mirror entries on their terminal dequeue', async () => {
  260. const ctx = await harness()
  261. const api = createApiProxy(ctx, DEFAULTS)
  262. const agent = stubAgent(ctx)
  263. const queued = inboxMessage('m-3', 'x')
  264. const steering = inboxMessage('m-4', 'x', 'r-1')
  265. ctx.emit('agent/inbox/enqueue', agent, queued, 'queued')
  266. ctx.emit('agent/inbox/enqueue', agent, steering, 'steering')
  267. ctx.emit('agent/inbox/dequeue', agent, queued, 'queued')
  268. ctx.emit('agent/inbox/dequeue', agent, steering, 'steering')
  269. const abort = new AbortController()
  270. const frames = await collect<MuxFrame>(
  271. api.events.mux({ rpcId: RpcId('t-mux-after'), payload: {} }, abort.signal), 1, abort)
  272. expect(frames.filter(f => f.type === 'session/queued')).toHaveLength(0)
  273. })
  274. it('retires the matching placement when one message identity is queued and steering', async () => {
  275. const ctx = await harness()
  276. const api = createApiProxy(ctx, DEFAULTS)
  277. const agent = stubAgent(ctx)
  278. const repeated = inboxMessage('m-repeat', 'same prompt')
  279. ctx.emit('agent/inbox/enqueue', agent, repeated, 'queued')
  280. ctx.emit('agent/inbox/enqueue', agent, repeated, 'steering')
  281. ctx.emit('agent/inbox/dequeue', agent, inboxMessage('unknown', 'not queued'), 'queued')
  282. ctx.emit('agent/inbox/dequeue', agent, repeated, 'steering')
  283. const abort = new AbortController()
  284. const frames = await collect<MuxFrame>(
  285. api.events.mux({ rpcId: RpcId('t-mux-repeat'), payload: {} }, abort.signal), 2, abort)
  286. expect(frames.filter(f => f.type === 'session/queued')).toEqual([
  287. { type: 'session/queued', sessionId: agent.id, message: repeated, steering: false },
  288. ])
  289. })
  290. it('retires mirror entries on a batch discard (cancel path)', async () => {
  291. const ctx = await harness()
  292. const api = createApiProxy(ctx, DEFAULTS)
  293. const agent = stubAgent(ctx)
  294. const doomed = inboxMessage('m-5', 'doomed')
  295. const survivor = inboxMessage('m-6', 'survivor')
  296. ctx.emit('agent/inbox/enqueue', agent, doomed, 'queued')
  297. ctx.emit('agent/inbox/enqueue', agent, survivor, 'queued')
  298. ctx.emit('agent/inbox/discard', agent, [doomed])
  299. const abort = new AbortController()
  300. const frames = await collect<MuxFrame>(
  301. api.events.mux({ rpcId: RpcId('t-mux-swept'), payload: {} }, abort.signal), 2, abort)
  302. const remaining = frames.filter(f => f.type === 'session/queued')
  303. expect(remaining).toHaveLength(1)
  304. expect(remaining[0]).toMatchObject({ message: survivor })
  305. })
  306. })