interception.spec.ts 33 KB

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