interception.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId, type Message } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, {
  8. AgentId,
  9. type ContinuationDecision,
  10. type PromptDecision,
  11. type SessionStartSource,
  12. } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  14. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  15. /**
  16. * The interception seams introduced by the hooks taxonomy: `agent/prompt-submit`,
  17. * `agent/session-start`, the reshaped `agent/turn-continuation`
  18. * ({@link ContinuationDecision}), and the `tools/pre-execute` / `tools/post-execute`
  19. * split with `additionalContext` buffering. These verify the canonical event
  20. * surface a hook bridge (or a native plugin) programs against, WITHOUT any
  21. * external protocol — a native plugin uses the typed decisions directly.
  22. */
  23. async function harness(adapter: MockAdapter) {
  24. const ctx = new Context()
  25. await ctx.plugin(LlmService)
  26. await ctx.plugin(SessionStore)
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRegistry)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(AgentLoop, { agents: [] })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  35. return new Promise((resolve) => {
  36. const dispose = ctx.on('agent/status', (subject, status) => {
  37. if (subject === agent && status === 'idle') {
  38. dispose()
  39. resolve()
  40. }
  41. })
  42. })
  43. }
  44. function send(agent: ReactLoopAgent, text: string) {
  45. agent.send([{ type: 'text', text }])
  46. }
  47. function events(agent: ReactLoopAgent): SessionEvent[] {
  48. return [...agent.session.events]
  49. }
  50. describe('agent/prompt-submit', () => {
  51. it('allow (default via next) records the user/message unchanged', async () => {
  52. const adapter = new MockAdapter([textResponse('ok')])
  53. const ctx = await harness(adapter)
  54. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  55. const seen: string[] = []
  56. ctx.on('agent/prompt-submit', async (_agent, content, _source, next) => {
  57. seen.push(content.map(b => (b.type === 'text' ? b.text : '')).join(''))
  58. return next()
  59. })
  60. send(agent, 'hello')
  61. await waitForIdle(ctx, agent)
  62. expect(seen).toEqual(['hello'])
  63. const userMsg = events(agent).find(e => e.type === 'user/message')
  64. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'hello' }])
  65. })
  66. it('allow with content REWRITES the prompt before it is recorded', async () => {
  67. const adapter = new MockAdapter([textResponse('ok')])
  68. const ctx = await harness(adapter)
  69. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  70. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  71. ({ kind: 'allow', content: [{ type: 'text', text: 'REWRITTEN' }] }))
  72. send(agent, 'original')
  73. await waitForIdle(ctx, agent)
  74. const userMsg = events(agent).find(e => e.type === 'user/message')
  75. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'REWRITTEN' }])
  76. // the rewritten prompt is what reached the model
  77. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('REWRITTEN')
  78. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('original')
  79. })
  80. it('allow with additionalContext injects a separate context/message into the turn', async () => {
  81. const adapter = new MockAdapter([textResponse('ok')])
  82. const ctx = await harness(adapter)
  83. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  84. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  85. ({
  86. kind: 'allow',
  87. additionalContext: { content: [{ type: 'text', text: 'extra ctx' }], source: { kind: 'plugin', plugin: 'test' } },
  88. }))
  89. send(agent, 'go')
  90. await waitForIdle(ctx, agent)
  91. const log = events(agent)
  92. const userMsg = log.find(e => e.type === 'user/message')
  93. const ctxMsg = log.find(e => e.type === 'context/message')
  94. expect(userMsg).toBeDefined()
  95. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.content).toEqual([{ type: 'text', text: 'extra ctx' }])
  96. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  97. // both the prompt and the injected context reach the model
  98. const sent = JSON.stringify(adapter.requests[0]!.messages)
  99. expect(sent).toContain('extra ctx')
  100. })
  101. it('a prompt-submit rewrite + additionalContext is VISIBLE to the agent/pre-step seam (merged ordering)', async () => {
  102. // The merge of the interception seams with master's compaction seam pins one ordering:
  103. // `agent/prompt-submit` runs (rewriting the prompt and injecting context) before the step
  104. // loop, and `agent/pre-step` fires inside the step before the single deriveMessages().
  105. const adapter = new MockAdapter([textResponse('ok')])
  106. const ctx = await harness(adapter)
  107. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  108. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  109. ({
  110. kind: 'allow',
  111. content: [{ type: 'text', text: 'REWRITTEN prompt' }],
  112. additionalContext: { content: [{ type: 'text', text: 'injected ctx' }], source: { kind: 'plugin', plugin: 'test' } },
  113. }))
  114. // The pre-step seam (where compaction lives) derives the surface it would act
  115. // on. Capture what it sees on the first step.
  116. let preStepDerived: string | undefined
  117. ctx.on('agent/pre-step', (subject, _turn, step) => {
  118. if (subject === agent && step === 1) preStepDerived = JSON.stringify(subject.session.deriveMessages())
  119. })
  120. send(agent, 'ORIGINAL prompt')
  121. await waitForIdle(ctx, agent)
  122. // The pre-step seam ran and saw BOTH the rewrite (not the original) and the
  123. // injected context — i.e. the prompt-submit effects landed before it.
  124. expect(preStepDerived).toBeDefined()
  125. expect(preStepDerived).toContain('REWRITTEN prompt')
  126. expect(preStepDerived).toContain('injected ctx')
  127. expect(preStepDerived).not.toContain('ORIGINAL prompt')
  128. })
  129. it('block drops the (only) prompt → zero-step turn ends rejected, model never called', async () => {
  130. const adapter = new MockAdapter([textResponse('should not run')])
  131. const ctx = await harness(adapter)
  132. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  133. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  134. ({ kind: 'block', reason: 'blocked by policy' }))
  135. const reasons: TurnEndReason[] = []
  136. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  137. send(agent, 'do something')
  138. await waitForIdle(ctx, agent)
  139. // the model was never called
  140. expect(adapter.requests).toHaveLength(0)
  141. // the turn opened and closed balanced, with no user/message and no step
  142. const log = events(agent)
  143. expect(log.some(e => e.type === 'turn/start')).toBe(true)
  144. expect(log.some(e => e.type === 'turn/end')).toBe(true)
  145. expect(log.some(e => e.type === 'user/message')).toBe(false)
  146. expect(log.some(e => e.type === 'step/start')).toBe(false)
  147. // the veto is recorded durably as a prompt/blocked in the open turn
  148. const blocked = log.find(e => e.type === 'prompt/blocked')
  149. expect(blocked?.type === 'prompt/blocked' && blocked.data).toMatchObject({
  150. content: [{ type: 'text', text: 'do something' }],
  151. reason: 'blocked by policy',
  152. })
  153. // ended rejected with the block reason
  154. expect(reasons).toEqual([{ kind: 'rejected', reason: 'blocked by policy' }])
  155. const turnEnd = log.findLast(e => e.type === 'turn/end')
  156. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'rejected', reason: 'blocked by policy' })
  157. })
  158. it('a mixed batch records a prompt/blocked for the vetoed prompt while the allowed one runs', async () => {
  159. // Two prompts queued into one turn: block "secret", allow "safe".
  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. // same turn, two steps
  432. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  433. expect(log.filter(e => e.type === 'step/start')).toHaveLength(2)
  434. // the reason was recorded as steering BEFORE step 2, with its plugin source
  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. // and reached the next request
  439. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going on the goal')
  440. })
  441. it('a stop decision ends the turn even when the step had tool calls', async () => {
  442. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' })])
  443. const ctx = await harness(adapter)
  444. ctx.tools.register(defineTool({
  445. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  446. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  447. }))
  448. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  449. ctx.on('agent/turn-continuation', async (): Promise<ContinuationDecision> => ({ action: 'stop' }))
  450. send(agent, 'go')
  451. await waitForIdle(ctx, agent)
  452. // default would have continued (had tool calls), but the stop decision wins
  453. expect(adapter.requests).toHaveLength(1)
  454. expect(events(agent).some(e => e.type === 'tool/result')).toBe(true)
  455. })
  456. })
  457. describe('tools/post-execute additionalContext buffering across a multi-call step', () => {
  458. it('appends each call\'s additionalContext only AFTER all tool/results, preserving adjacency', async () => {
  459. // One assistant step with TWO tool calls; the second model response stops.
  460. const twoCalls = [
  461. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  462. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  463. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  464. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  465. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  466. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  467. ]
  468. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  469. const ctx = await harness(adapter)
  470. ctx.tools.register(defineTool({
  471. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  472. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  473. }))
  474. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  475. // Each call attaches additionalContext naming itself.
  476. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  477. ({ kind: 'accept', additionalContext: { content: [{ type: 'text', text: `ctx-${exec.callId}` }], source: { kind: 'plugin', plugin: 'p' } } }))
  478. send(agent, 'go')
  479. await waitForIdle(ctx, agent)
  480. // Event order in the log: both tool/results, THEN both context/messages —
  481. // never interleaved (which would break tool-call/result adjacency).
  482. const types = events(agent).map(e => e.type)
  483. const firstResult = types.indexOf('tool/result')
  484. const lastResult = types.lastIndexOf('tool/result')
  485. const firstCtx = types.indexOf('context/message')
  486. expect(firstResult).toBeGreaterThanOrEqual(0)
  487. expect(lastResult).toBeGreaterThan(firstResult) // two results
  488. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  489. // both contexts present
  490. const ctxTexts = events(agent)
  491. .filter(e => e.type === 'context/message')
  492. .flatMap(e => (e.type === 'context/message' ? e.data.content : []))
  493. .map(b => (b.type === 'text' ? b.text : ''))
  494. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  495. })
  496. })
  497. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  498. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  499. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  500. const ctx = await harness(adapter)
  501. let ran = false
  502. ctx.tools.register(defineTool({
  503. name: 'danger', description: 'danger', parameters: {},
  504. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  505. }))
  506. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  507. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  508. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  509. return next()
  510. })
  511. send(agent, 'go')
  512. await waitForIdle(ctx, agent)
  513. expect(ran).toBe(false)
  514. const result = events(agent).find(e => e.type === 'tool/result')
  515. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  516. expect(result?.type === 'tool/result'
  517. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  518. })
  519. })
  520. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  521. // The whole point of the interception taxonomy: a "native hook" needs no dsh-hook-protocol,
  522. // no external command, no hook/* log — it is an ordinary cordis plugin subscribing to the
  523. // canonical events and returning typed decisions.
  524. const NativeGuard = {
  525. name: 'native-guard',
  526. apply(ctx: Context) {
  527. // 1. SessionStart: seed a standing instruction.
  528. ctx.on('agent/session-start', (agent, source) => {
  529. agent.inject(
  530. [{ type: 'text', text: `policy active (started: ${source})` }],
  531. { source: { kind: 'plugin', plugin: 'native-guard' } },
  532. )
  533. })
  534. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  535. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  536. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  537. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  538. return next()
  539. })
  540. // 3. PreToolUse: deny a dangerous tool by name.
  541. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  542. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  543. return next()
  544. })
  545. // 4. PostToolUse: attach context after a tool runs.
  546. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  547. const decision = await next()
  548. if (decision.kind === 'accept') {
  549. return { kind: 'accept', additionalContext: { content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' } } }
  550. }
  551. return decision
  552. })
  553. },
  554. }
  555. it('all four seams fire for a real allowed turn with a tool call', async () => {
  556. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  557. const ctx = await harness(adapter)
  558. await ctx.plugin(NativeGuard)
  559. ctx.tools.register(defineTool({
  560. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  561. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  562. }))
  563. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  564. send(agent, 'please echo hi')
  565. await waitForIdle(ctx, agent)
  566. const log = events(agent)
  567. // session-start preamble injected
  568. expect(log.some(e => e.type === 'context/message'
  569. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  570. // prompt allowed → user/message recorded
  571. expect(log.some(e => e.type === 'user/message')).toBe(true)
  572. // tool ran (echo allowed) and post-execute attached "audited" context
  573. expect(log.some(e => e.type === 'tool/result' && !e.data.isError)).toBe(true)
  574. expect(log.some(e => e.type === 'context/message'
  575. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  576. // NO hook/* events — a native plugin needs none
  577. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  578. })
  579. it('the same plugin blocks a destructive prompt → rejected turn, model never called', async () => {
  580. const adapter = new MockAdapter([textResponse('should not run')])
  581. const ctx = await harness(adapter)
  582. await ctx.plugin(NativeGuard)
  583. const agent = ctx.agentLoop.create(AgentId('a2'), { model: 'mock' })
  584. const reasons: TurnEndReason[] = []
  585. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  586. send(agent, 'run rm -rf /')
  587. await waitForIdle(ctx, agent)
  588. expect(adapter.requests).toHaveLength(0)
  589. expect(reasons).toEqual([{ kind: 'rejected', reason: 'destructive prompt blocked' }])
  590. })
  591. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  592. const adapter = new MockAdapter([textResponse('ok')])
  593. const ctx = await harness(adapter)
  594. const fiber = await ctx.plugin(NativeGuard)
  595. await fiber.dispose()
  596. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  597. const agent = ctx.agentLoop.create(AgentId('a3'), { model: 'mock' })
  598. send(agent, 'run rm -rf /')
  599. await waitForIdle(ctx, agent)
  600. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  601. expect(adapter.requests).toHaveLength(1)
  602. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  603. })
  604. })