interception.spec.ts 34 KB

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