interception.spec.ts 35 KB

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