interception.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, type Message } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, {
  8. AgentId,
  9. type ContinuationDecision,
  10. type PromptDecision,
  11. type SessionStartSource,
  12. } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  14. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  15. /**
  16. * The interception seams introduced by the hooks taxonomy: `agent/prompt-submit`,
  17. * `agent/session-start`, the reshaped `agent/turn-continuation`
  18. * ({@link ContinuationDecision}), and the `tools/pre-execute` / `tools/post-execute`
  19. * split with `additionalContexts` buffering. These verify the canonical event
  20. * surface a hook bridge (or a native plugin) programs against, WITHOUT any
  21. * external protocol — a native plugin uses the typed decisions directly.
  22. */
  23. async function harness(adapter: MockAdapter) {
  24. const ctx = new Context()
  25. await ctx.plugin(LlmService)
  26. await ctx.plugin(SessionStore)
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRegistry)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(AgentLoop, { agents: [] })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  35. return new Promise((resolve) => {
  36. const dispose = ctx.on('agent/status', (subject, status) => {
  37. if (subject === agent && status === 'idle') {
  38. dispose()
  39. resolve()
  40. }
  41. })
  42. })
  43. }
  44. function send(agent: ReactLoopAgent, text: string) {
  45. agent.send([{ type: 'text', text }])
  46. }
  47. function events(agent: ReactLoopAgent): SessionEvent[] {
  48. return [...agent.session.events]
  49. }
  50. describe('agent/prompt-submit', () => {
  51. it('allow (default via next) records the user/message unchanged', async () => {
  52. const adapter = new MockAdapter([textResponse('ok')])
  53. const ctx = await harness(adapter)
  54. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  55. const seen: string[] = []
  56. ctx.on('agent/prompt-submit', async (_agent, content, _source, next) => {
  57. seen.push(content.map(b => (b.type === 'text' ? b.text : '')).join(''))
  58. return next()
  59. })
  60. send(agent, 'hello')
  61. await waitForIdle(ctx, agent)
  62. expect(seen).toEqual(['hello'])
  63. const userMsg = events(agent).find(e => e.type === 'user/message')
  64. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'hello' }])
  65. })
  66. it('allow with content REWRITES the prompt before it is recorded', async () => {
  67. const adapter = new MockAdapter([textResponse('ok')])
  68. const ctx = await harness(adapter)
  69. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  70. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  71. ({ kind: 'allow', content: [{ type: 'text', text: 'REWRITTEN' }] }))
  72. send(agent, 'original')
  73. await waitForIdle(ctx, agent)
  74. const userMsg = events(agent).find(e => e.type === 'user/message')
  75. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'REWRITTEN' }])
  76. // the rewritten prompt is what reached the model
  77. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('REWRITTEN')
  78. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('original')
  79. })
  80. it('allow with additionalContexts injects separate context/message events into the turn', async () => {
  81. const adapter = new MockAdapter([textResponse('ok')])
  82. const ctx = await harness(adapter)
  83. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  84. const meta = { kind: 'prompt-context', version: 1 }
  85. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  86. ({
  87. kind: 'allow',
  88. additionalContexts: [{
  89. content: [{ type: 'text', text: '<system-reminder>extra ctx</system-reminder>' }],
  90. source: { kind: 'plugin', plugin: 'test' },
  91. envelope: 'raw',
  92. meta,
  93. }],
  94. }))
  95. send(agent, 'go')
  96. await waitForIdle(ctx, agent)
  97. const log = events(agent)
  98. const userMsg = log.find(e => e.type === 'user/message')
  99. const ctxMsg = log.find(e => e.type === 'context/message')
  100. expect(userMsg).toBeDefined()
  101. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.content).toEqual([{ type: 'text', text: '<system-reminder>extra ctx</system-reminder>' }])
  102. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  103. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.envelope).toBe('raw')
  104. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.meta).toEqual(meta)
  105. // both the prompt and the injected context reach the model
  106. const sent = JSON.stringify(adapter.requests[0]!.messages)
  107. expect(sent).toContain('extra ctx')
  108. })
  109. it('a prompt-submit rewrite + additionalContexts is VISIBLE to the agent/pre-step seam (merged ordering)', async () => {
  110. // Prompt rewrites and injected context land before `agent/pre-step`, so a
  111. // compaction listener measures the current surface before the single derive.
  112. const adapter = new MockAdapter([textResponse('ok')])
  113. const ctx = await harness(adapter)
  114. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  115. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  116. ({
  117. kind: 'allow',
  118. content: [{ type: 'text', text: 'REWRITTEN prompt' }],
  119. additionalContexts: [{ content: [{ type: 'text', text: 'injected ctx' }], source: { kind: 'plugin', plugin: 'test' } }],
  120. }))
  121. // The pre-step seam (where compaction lives) derives the surface it would act
  122. // on. Capture what it sees on the first step.
  123. let preStepDerived: string | undefined
  124. ctx.on('agent/pre-step', (subject, _turn, step) => {
  125. if (subject === agent && step === 1) preStepDerived = JSON.stringify(subject.session.deriveMessages())
  126. })
  127. send(agent, 'ORIGINAL prompt')
  128. await waitForIdle(ctx, agent)
  129. // The pre-step seam ran and saw BOTH the rewrite (not the original) and the
  130. // injected context — i.e. the prompt-submit effects landed before it.
  131. expect(preStepDerived).toBeDefined()
  132. expect(preStepDerived).toContain('REWRITTEN prompt')
  133. expect(preStepDerived).toContain('injected ctx')
  134. expect(preStepDerived).not.toContain('ORIGINAL prompt')
  135. })
  136. it('block drops the (only) prompt → zero-step turn ends rejected, model never called', async () => {
  137. const adapter = new MockAdapter([textResponse('should not run')])
  138. const ctx = await harness(adapter)
  139. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  140. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  141. ({ kind: 'block', reason: 'blocked by policy' }))
  142. const reasons: TurnEndReason[] = []
  143. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  144. send(agent, 'do something')
  145. await waitForIdle(ctx, agent)
  146. // the model was never called
  147. expect(adapter.requests).toHaveLength(0)
  148. // the turn opened and closed balanced, with no user/message and no step
  149. const log = events(agent)
  150. expect(log.some(e => e.type === 'turn/start')).toBe(true)
  151. expect(log.some(e => e.type === 'turn/end')).toBe(true)
  152. expect(log.some(e => e.type === 'user/message')).toBe(false)
  153. expect(log.some(e => e.type === 'step/start')).toBe(false)
  154. // the veto is recorded durably as a prompt/blocked in the open turn
  155. const blocked = log.find(e => e.type === 'prompt/blocked')
  156. expect(blocked?.type === 'prompt/blocked' && blocked.data).toMatchObject({
  157. content: [{ type: 'text', text: 'do something' }],
  158. reason: 'blocked by policy',
  159. })
  160. // ended rejected with the block reason
  161. expect(reasons).toEqual([{ kind: 'rejected', reason: 'blocked by policy' }])
  162. const turnEnd = log.findLast(e => e.type === 'turn/end')
  163. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'rejected', reason: 'blocked by policy' })
  164. })
  165. it('a mixed batch records a prompt/blocked for the vetoed prompt while the allowed one runs', async () => {
  166. // Blocking one prompt in a mixed batch must persist its reason even though
  167. // the allowed prompt keeps the turn from ending rejected.
  168. const adapter = new MockAdapter([textResponse('ran once')])
  169. const ctx = await harness(adapter)
  170. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  171. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  172. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  173. return text === 'secret' ? { kind: 'block', reason: 'policy: no secrets' } : next()
  174. })
  175. const reasons: TurnEndReason[] = []
  176. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  177. // both sends land before the loop drains → one batched turn
  178. send(agent, 'secret')
  179. send(agent, 'safe')
  180. await waitForIdle(ctx, agent)
  181. const log = events(agent)
  182. // the allowed prompt became a user/message and drove exactly one model call
  183. const userMsgs = log.filter(e => e.type === 'user/message')
  184. expect(userMsgs).toHaveLength(1)
  185. expect(userMsgs[0]?.type === 'user/message' && userMsgs[0].data.content).toEqual([{ type: 'text', text: 'safe' }])
  186. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  187. // the blocked prompt is durably recorded, with its content + reason
  188. const blocked = log.filter(e => e.type === 'prompt/blocked')
  189. expect(blocked).toHaveLength(1)
  190. expect(blocked[0]?.type === 'prompt/blocked' && blocked[0].data).toMatchObject({
  191. content: [{ type: 'text', text: 'secret' }],
  192. reason: 'policy: no secrets',
  193. })
  194. // the turn did NOT reject — a sibling was allowed — so the boundary reason
  195. // alone would not have preserved the block
  196. expect(reasons.some(r => r.kind === 'rejected')).toBe(false)
  197. })
  198. it('a throwing prompt-submit listener ends the turn balanced (error), loop survives', async () => {
  199. const adapter = new MockAdapter([textResponse('after')])
  200. const ctx = await harness(adapter)
  201. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  202. let threw = false
  203. ctx.on('agent/prompt-submit', async () => {
  204. if (!threw) { threw = true; throw new Error('prompt hook broke') }
  205. return { kind: 'allow' as const }
  206. })
  207. const errors: Error[] = []
  208. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  209. send(agent, 'first')
  210. await waitForIdle(ctx, agent)
  211. expect(errors.map(e => e.message)).toEqual(['prompt hook broke'])
  212. // turn balanced
  213. const log = events(agent)
  214. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  215. expect(log.filter(e => e.type === 'turn/end')).toHaveLength(1)
  216. // loop survives: a second prompt runs normally
  217. send(agent, 'second')
  218. await waitForIdle(ctx, agent)
  219. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  220. })
  221. })
  222. describe('agent/session-start', () => {
  223. it('fires once with source "startup" for a fresh create, before the first turn', async () => {
  224. const adapter = new MockAdapter([textResponse('ok')])
  225. const ctx = await harness(adapter)
  226. const sources: SessionStartSource[] = []
  227. ctx.on('agent/session-start', (_agent, source) => void sources.push(source))
  228. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  229. // fires synchronously at create, before any turn
  230. expect(sources).toEqual(['startup'])
  231. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  232. send(agent, 'go')
  233. await waitForIdle(ctx, agent)
  234. // still only one session-start
  235. expect(sources).toEqual(['startup'])
  236. })
  237. it('a session-start listener can inject context the first request sees', async () => {
  238. const adapter = new MockAdapter([textResponse('ok')])
  239. const ctx = await harness(adapter)
  240. ctx.on('agent/session-start', (agent) => {
  241. agent.inject([{ type: 'text', text: 'session preamble' }], { source: { kind: 'plugin', plugin: 'test' } })
  242. })
  243. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  244. send(agent, 'go')
  245. await waitForIdle(ctx, agent)
  246. // the injected context reached the model on the first (only) request
  247. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  248. // and is recorded with the plugin source, never mislabeled as a user prompt
  249. const ctxMsg = events(agent).find(e => e.type === 'context/message')
  250. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  251. })
  252. it('a throwing session-start listener does not abort agent construction', async () => {
  253. const adapter = new MockAdapter([textResponse('ok')])
  254. const ctx = await harness(adapter)
  255. ctx.on('agent/session-start', () => { throw new Error('session-start hook broke') })
  256. // create must not throw — the listener error is contained/logged
  257. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  258. expect(agent.id).toBe(AgentId('a1'))
  259. // and the agent still runs
  260. send(agent, 'go')
  261. await waitForIdle(ctx, agent)
  262. expect(adapter.requests).toHaveLength(1)
  263. })
  264. })
  265. describe('agent/session-prefix', () => {
  266. it('dispatches to global and matching agent-scope listeners only', async () => {
  267. const adapter = new MockAdapter([textResponse('a done'), textResponse('b done')])
  268. const ctx = await harness(adapter)
  269. const agentA = ctx.agentLoop.create(AgentId('prefix-a'), { provider: 'mock', model: 'mock' })
  270. const agentB = ctx.agentLoop.create(AgentId('prefix-b'), { provider: 'mock', model: 'mock' })
  271. const seen: string[] = []
  272. ctx.on('agent/session-prefix', async (agent, _prefix, _signal, next) => {
  273. seen.push(`global:${agent.id}`)
  274. return next()
  275. })
  276. agentA.ctx.on('agent/session-prefix', async (agent, _prefix, _signal, next) => {
  277. seen.push(`a:${agent.id}`)
  278. return next()
  279. })
  280. agentB.ctx.on('agent/session-prefix', async (agent, _prefix, _signal, next) => {
  281. seen.push(`b:${agent.id}`)
  282. return next()
  283. })
  284. send(agentA, 'run a')
  285. await waitForIdle(ctx, agentA)
  286. send(agentB, 'run b')
  287. await waitForIdle(ctx, agentB)
  288. expect(seen).toEqual([
  289. 'global:prefix-a', 'a:prefix-a',
  290. 'global:prefix-b', 'b:prefix-b',
  291. ])
  292. })
  293. it('composes once per loop instance and fronts every request; the header records it; history stays untouched', async () => {
  294. const adapter = new MockAdapter([
  295. toolCallResponse('c1', 'echo', { text: 'ping' }),
  296. textResponse('done'),
  297. textResponse('again'),
  298. ])
  299. const ctx = await harness(adapter)
  300. ctx.tools.register(defineTool({
  301. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  302. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  303. }))
  304. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  305. const reminder: Message = { role: 'user', content: [{ type: 'text', text: '<system-reminder>catalog</system-reminder>' }] }
  306. let composed = 0
  307. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  308. composed += 1
  309. return [...await next(), reminder]
  310. })
  311. send(agent, 'go')
  312. await waitForIdle(ctx, agent)
  313. send(agent, 'next turn')
  314. await waitForIdle(ctx, agent)
  315. // Three requests (two turns), ONE composition: the frozen product is
  316. // reused verbatim, so the prefix cannot drift mid-session.
  317. expect(adapter.requests).toHaveLength(3)
  318. expect(composed).toBe(1)
  319. for (const request of adapter.requests) {
  320. expect(request.messages[0]).toEqual(reminder)
  321. }
  322. // The anchoring snapshot is the prefix's durable record — and the ONLY
  323. // header event: reuse means no changed snapshot ever.
  324. const headerEvents = events(agent).filter(e => e.type === 'request/header')
  325. expect(headerEvents).toHaveLength(1)
  326. expect(headerEvents[0]?.type === 'request/header' && headerEvents[0].data.header.messagePrefix).toEqual([reminder])
  327. // Never session history: the derivation starts at the real user prompt.
  328. expect(agent.session.deriveMessages()[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'go' }] })
  329. })
  330. it('composes before the first pre-step and hands the prefix to the seam (pressure gates see the real value)', async () => {
  331. const adapter = new MockAdapter([textResponse('ok')])
  332. const ctx = await harness(adapter)
  333. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  334. const reminder: Message = { role: 'user', content: [{ type: 'text', text: 'opener' }] }
  335. const order: string[] = []
  336. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  337. order.push('compose')
  338. return [reminder, ...await next()]
  339. })
  340. const seen: (readonly Message[])[] = []
  341. ctx.on('agent/pre-step', (_agent, _turn, _step, _system, sessionPrefix) => {
  342. order.push('pre-step')
  343. seen.push(sessionPrefix)
  344. })
  345. send(agent, 'hi')
  346. await waitForIdle(ctx, agent)
  347. // Composition precedes the pre-step seam, and the seam receives THIS
  348. // instance's composed prefix — a token-pressure gate (compaction) counts
  349. // what the request will actually carry, never a stale logged prefix.
  350. expect(order).toEqual(['compose', 'pre-step'])
  351. expect(seen[0]).toEqual([reminder])
  352. })
  353. it('the canonical prepend pattern composes contributions in registration order', async () => {
  354. const adapter = new MockAdapter([textResponse('ok')])
  355. const ctx = await harness(adapter)
  356. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  357. // Both listeners use the canonical `[mine, ...await next()]` prepend: the
  358. // waterfall unwinds innermost-first (the second listener's array is built
  359. // first), so prepending puts the FIRST-registered contribution first.
  360. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  361. return [{ role: 'user', content: [{ type: 'text', text: 'first' }] }, ...await next()]
  362. })
  363. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  364. return [{ role: 'user', content: [{ type: 'text', text: 'second' }] }, ...await next()]
  365. })
  366. send(agent, 'hi')
  367. await waitForIdle(ctx, agent)
  368. const texts = adapter.requests[0]!.messages.map(m => m.content[0]?.type === 'text' ? m.content[0].text : '')
  369. expect(texts).toEqual(['first', 'second', 'hi'])
  370. })
  371. it('with no contributions the header omits messagePrefix and the request is the bare derivation', async () => {
  372. const adapter = new MockAdapter([textResponse('ok')])
  373. const ctx = await harness(adapter)
  374. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  375. // A listener that delegates without contributing — the canonical no-op.
  376. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => next())
  377. send(agent, 'hi')
  378. await waitForIdle(ctx, agent)
  379. const headerEvent = events(agent).find(e => e.type === 'request/header')
  380. expect(headerEvent?.type === 'request/header' && 'messagePrefix' in headerEvent.data.header).toBe(false)
  381. expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }])
  382. })
  383. it('the frozen seed rejects in-place mutation — a contribution is a returned extension', async () => {
  384. const adapter = new MockAdapter([textResponse('ok')])
  385. const ctx = await harness(adapter)
  386. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  387. let mutationError: unknown
  388. ctx.on('agent/session-prefix', async (_agent, prefix, _signal, next): Promise<Message[]> => {
  389. try {
  390. prefix.push({ role: 'user', content: [{ type: 'text', text: 'smuggled' }] })
  391. } catch (error: unknown) {
  392. mutationError = error
  393. }
  394. return next()
  395. })
  396. send(agent, 'hi')
  397. await waitForIdle(ctx, agent)
  398. expect(mutationError).toBeInstanceOf(TypeError)
  399. expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }])
  400. })
  401. it('mutating a listener-held reference after composition cannot alter later requests (the cache is a frozen clone)', async () => {
  402. const adapter = new MockAdapter([
  403. toolCallResponse('c1', 'echo', { text: 'ping' }),
  404. textResponse('done'),
  405. ])
  406. const ctx = await harness(adapter)
  407. ctx.tools.register(defineTool({
  408. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  409. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  410. }))
  411. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  412. const held: Message = { role: 'user', content: [{ type: 'text', text: 'v1' }] }
  413. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => [...await next(), held])
  414. send(agent, 'go')
  415. await waitForIdle(ctx, agent)
  416. // The listener mutates the object it contributed AFTER composition; the
  417. // cached prefix is a deep-frozen clone, so step 2's request is unchanged.
  418. held.content = [{ type: 'text', text: 'v2' }]
  419. expect(adapter.requests[1]!.messages[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'v1' }] })
  420. expect(events(agent).filter(e => e.type === 'request/header')).toHaveLength(1)
  421. })
  422. })
  423. describe('agent/turn-continuation (ContinuationDecision)', () => {
  424. it('a continue decision with a reason records next-step steering in the same turn', async () => {
  425. const adapter = new MockAdapter([textResponse('step 1 no tools'), textResponse('step 2')])
  426. const ctx = await harness(adapter)
  427. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  428. let forced = false
  429. ctx.on('agent/turn-continuation', async (_agent, _turn, _default, next): Promise<ContinuationDecision> => {
  430. if (!forced) {
  431. forced = true
  432. return { action: 'continue', reason: { content: [{ type: 'text', text: 'keep going on the goal' }], source: { kind: 'plugin', plugin: 'goal' } } }
  433. }
  434. return next()
  435. })
  436. send(agent, 'go')
  437. await waitForIdle(ctx, agent)
  438. const log = events(agent)
  439. // The continuation stays in the turn, is logged with provenance before step 2,
  440. // and reaches that step's request.
  441. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  442. expect(log.filter(e => e.type === 'step/start')).toHaveLength(2)
  443. const steering = log.find(e => e.type === 'steering/message')
  444. expect(steering?.type === 'steering/message' && steering.data.content).toEqual([{ type: 'text', text: 'keep going on the goal' }])
  445. expect(steering?.type === 'steering/message' && steering.data.source).toEqual({ kind: 'plugin', plugin: 'goal' })
  446. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going on the goal')
  447. })
  448. it('a stop decision ends the turn even when the step had tool calls', async () => {
  449. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' })])
  450. const ctx = await harness(adapter)
  451. ctx.tools.register(defineTool({
  452. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  453. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  454. }))
  455. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  456. ctx.on('agent/turn-continuation', async (): Promise<ContinuationDecision> => ({ action: 'stop' }))
  457. send(agent, 'go')
  458. await waitForIdle(ctx, agent)
  459. // default would have continued (had tool calls), but the stop decision wins
  460. expect(adapter.requests).toHaveLength(1)
  461. expect(events(agent).some(e => e.type === 'tool/result')).toBe(true)
  462. })
  463. })
  464. describe('tool additionalContexts buffering across a step', () => {
  465. it('appends each call\'s contexts only AFTER all tool/results, preserving adjacency', async () => {
  466. // One assistant step with TWO tool calls; the second model response stops.
  467. const twoCalls = [
  468. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  469. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  470. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  471. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  472. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  473. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  474. ]
  475. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  476. const ctx = await harness(adapter)
  477. ctx.tools.register(defineTool({
  478. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  479. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  480. }))
  481. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  482. // Each call attaches one context naming itself.
  483. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  484. ({
  485. kind: 'accept',
  486. additionalContexts: [{
  487. content: [{ type: 'text', text: `ctx-${exec.callId}` }],
  488. source: { kind: 'plugin', plugin: 'p' },
  489. envelope: 'raw',
  490. meta: { callId: exec.callId },
  491. }],
  492. }))
  493. send(agent, 'go')
  494. await waitForIdle(ctx, agent)
  495. // Event order in the log: both tool/results, THEN both context/messages —
  496. // never interleaved (which would break tool-call/result adjacency).
  497. const types = events(agent).map(e => e.type)
  498. const firstResult = types.indexOf('tool/result')
  499. const lastResult = types.lastIndexOf('tool/result')
  500. const firstCtx = types.indexOf('context/message')
  501. expect(firstResult).toBeGreaterThanOrEqual(0)
  502. expect(lastResult).toBeGreaterThan(firstResult) // two results
  503. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  504. // both contexts present
  505. const ctxTexts = events(agent)
  506. .filter(e => e.type === 'context/message')
  507. .flatMap(e => (e.type === 'context/message' ? e.data.content : []))
  508. .map(b => (b.type === 'text' ? b.text : ''))
  509. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  510. const contextEvents = events(agent).filter(e => e.type === 'context/message')
  511. expect(contextEvents.map(e => e.type === 'context/message' && e.data.envelope)).toEqual(['raw', 'raw'])
  512. expect(contextEvents.map(e => e.type === 'context/message' && e.data.meta)).toEqual([{ callId: 'c1' }, { callId: 'c2' }])
  513. })
  514. it('appends multiple contexts deferred by one composite tool after its outer result', async () => {
  515. const adapter = new MockAdapter([toolCallResponse('c1', 'composite', {}), textResponse('done')])
  516. const ctx = await harness(adapter)
  517. ctx.tools.register(defineTool({
  518. name: 'composite', description: 'composite', parameters: {},
  519. async execute(_args, exec) {
  520. exec.deferContext({ content: [{ type: 'text', text: 'nested-a' }], source: { kind: 'plugin', plugin: 'a' }, meta: { order: 1 } })
  521. exec.deferContext({ content: [{ type: 'text', text: 'nested-b' }], source: { kind: 'plugin', plugin: 'b' }, envelope: 'raw', meta: { order: 2 } })
  522. return [{ type: 'text', text: 'outer result' }]
  523. },
  524. }))
  525. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  526. send(agent, 'go')
  527. await waitForIdle(ctx, agent)
  528. const log = events(agent)
  529. const resultIndex = log.findIndex(event => event.type === 'tool/result')
  530. const contextEvents = log.filter(event => event.type === 'context/message')
  531. expect(resultIndex).toBeGreaterThanOrEqual(0)
  532. expect(log.findIndex(event => event === contextEvents[0])).toBeGreaterThan(resultIndex)
  533. expect(contextEvents.map(event => event.type === 'context/message' && event.data.source)).toEqual([
  534. { kind: 'plugin', plugin: 'a' },
  535. { kind: 'plugin', plugin: 'b' },
  536. ])
  537. expect(contextEvents.map(event => event.type === 'context/message' && event.data.meta)).toEqual([{ order: 1 }, { order: 2 }])
  538. })
  539. })
  540. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  541. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  542. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  543. const ctx = await harness(adapter)
  544. let ran = false
  545. ctx.tools.register(defineTool({
  546. name: 'danger', description: 'danger', parameters: {},
  547. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  548. }))
  549. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  550. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  551. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  552. return next()
  553. })
  554. send(agent, 'go')
  555. await waitForIdle(ctx, agent)
  556. expect(ran).toBe(false)
  557. const result = events(agent).find(e => e.type === 'tool/result')
  558. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  559. expect(result?.type === 'tool/result'
  560. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  561. })
  562. })
  563. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  564. // The whole point of the interception taxonomy: a "native hook" needs no dsh-hook-protocol,
  565. // no external command, no hook/* log — it is an ordinary cordis plugin subscribing to the
  566. // canonical events and returning typed decisions.
  567. const NativeGuard = {
  568. name: 'native-guard',
  569. apply(ctx: Context) {
  570. // 1. SessionStart: seed a standing instruction.
  571. ctx.on('agent/session-start', (agent, source) => {
  572. agent.inject(
  573. [{ type: 'text', text: `policy active (started: ${source})` }],
  574. { source: { kind: 'plugin', plugin: 'native-guard' } },
  575. )
  576. })
  577. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  578. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  579. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  580. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  581. return next()
  582. })
  583. // 3. PreToolUse: deny a dangerous tool by name.
  584. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  585. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  586. return next()
  587. })
  588. // 4. PostToolUse: attach context after a tool runs.
  589. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  590. const decision = await next()
  591. if (decision.kind === 'accept') {
  592. return { kind: 'accept', additionalContexts: [{ content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' } }] }
  593. }
  594. return decision
  595. })
  596. },
  597. }
  598. it('all four seams fire for a real allowed turn with a tool call', async () => {
  599. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  600. const ctx = await harness(adapter)
  601. await ctx.plugin(NativeGuard)
  602. ctx.tools.register(defineTool({
  603. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  604. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  605. }))
  606. const agent = ctx.agentLoop.create(AgentId('a1'), { provider: 'mock', model: 'mock' })
  607. send(agent, 'please echo hi')
  608. await waitForIdle(ctx, agent)
  609. const log = events(agent)
  610. // session-start preamble injected
  611. expect(log.some(e => e.type === 'context/message'
  612. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  613. // prompt allowed → user/message recorded
  614. expect(log.some(e => e.type === 'user/message')).toBe(true)
  615. // tool ran (echo allowed) and post-execute attached "audited" context
  616. expect(log.some(e => e.type === 'tool/result' && !e.data.isError)).toBe(true)
  617. expect(log.some(e => e.type === 'context/message'
  618. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  619. // NO hook/* events — a native plugin needs none
  620. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  621. })
  622. it('the same plugin blocks a destructive prompt → rejected turn, model never called', async () => {
  623. const adapter = new MockAdapter([textResponse('should not run')])
  624. const ctx = await harness(adapter)
  625. await ctx.plugin(NativeGuard)
  626. const agent = ctx.agentLoop.create(AgentId('a2'), { provider: 'mock', model: 'mock' })
  627. const reasons: TurnEndReason[] = []
  628. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  629. send(agent, 'run rm -rf /')
  630. await waitForIdle(ctx, agent)
  631. expect(adapter.requests).toHaveLength(0)
  632. expect(reasons).toEqual([{ kind: 'rejected', reason: 'destructive prompt blocked' }])
  633. })
  634. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  635. const adapter = new MockAdapter([textResponse('ok')])
  636. const ctx = await harness(adapter)
  637. const fiber = await ctx.plugin(NativeGuard)
  638. await fiber.dispose()
  639. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  640. const agent = ctx.agentLoop.create(AgentId('a3'), { provider: 'mock', model: 'mock' })
  641. send(agent, 'run rm -rf /')
  642. await waitForIdle(ctx, agent)
  643. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  644. expect(adapter.requests).toHaveLength(1)
  645. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  646. })
  647. })