interception.spec.ts 34 KB

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