interception.spec.ts 32 KB

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