interception.spec.ts 34 KB

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