interception.spec.ts 32 KB

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