interception.spec.ts 32 KB

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