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