interception.spec.ts 30 KB

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