interception.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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('composes once per loop instance and fronts every request; the header records it; history stays untouched', async () => {
  274. const adapter = new MockAdapter([
  275. toolCallResponse('c1', 'echo', { text: 'ping' }),
  276. textResponse('done'),
  277. textResponse('again'),
  278. ])
  279. const ctx = await harness(adapter)
  280. ctx.tools.register(defineTool({
  281. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  282. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  283. }))
  284. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  285. const reminder: Message = { role: 'user', content: [{ type: 'text', text: '<system-reminder>catalog</system-reminder>' }] }
  286. let composed = 0
  287. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  288. composed += 1
  289. return [...await next(), reminder]
  290. })
  291. send(agent, 'go')
  292. await waitForIdle(ctx, agent)
  293. send(agent, 'next turn')
  294. await waitForIdle(ctx, agent)
  295. // Three requests (two turns), ONE composition: the frozen product is
  296. // reused verbatim, so the prefix cannot drift mid-session.
  297. expect(adapter.requests).toHaveLength(3)
  298. expect(composed).toBe(1)
  299. for (const request of adapter.requests) {
  300. expect(request.messages[0]).toEqual(reminder)
  301. }
  302. // The anchoring snapshot is the prefix's durable record — and the ONLY
  303. // header event: reuse means no request/header-delta ever.
  304. const headerEvents = events(agent).filter(e => e.type === 'request/header' || e.type === 'request/header-delta')
  305. expect(headerEvents).toHaveLength(1)
  306. expect(headerEvents[0]?.type === 'request/header' && headerEvents[0].data.header.messagePrefix).toEqual([reminder])
  307. // Never session history: the derivation starts at the real user prompt.
  308. expect(agent.session.deriveMessages()[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'go' }] })
  309. })
  310. it('composes before the first pre-step and hands the prefix to the seam (pressure gates see the real value)', async () => {
  311. const adapter = new MockAdapter([textResponse('ok')])
  312. const ctx = await harness(adapter)
  313. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  314. const reminder: Message = { role: 'user', content: [{ type: 'text', text: 'opener' }] }
  315. const order: string[] = []
  316. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  317. order.push('compose')
  318. return [reminder, ...await next()]
  319. })
  320. const seen: (readonly Message[])[] = []
  321. ctx.on('agent/pre-step', (_agent, _turn, _step, _system, sessionPrefix) => {
  322. order.push('pre-step')
  323. seen.push(sessionPrefix)
  324. })
  325. send(agent, 'hi')
  326. await waitForIdle(ctx, agent)
  327. // Composition precedes the pre-step seam, and the seam receives THIS
  328. // instance's composed prefix — a token-pressure gate (compaction) counts
  329. // what the request will actually carry, never a stale logged prefix.
  330. expect(order).toEqual(['compose', 'pre-step'])
  331. expect(seen[0]).toEqual([reminder])
  332. })
  333. it('the canonical prepend pattern composes contributions in registration order', async () => {
  334. const adapter = new MockAdapter([textResponse('ok')])
  335. const ctx = await harness(adapter)
  336. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  337. // Both listeners use the canonical `[mine, ...await next()]` prepend: the
  338. // waterfall unwinds innermost-first (the second listener's array is built
  339. // first), so prepending puts the FIRST-registered contribution first.
  340. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  341. return [{ role: 'user', content: [{ type: 'text', text: 'first' }] }, ...await next()]
  342. })
  343. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  344. return [{ role: 'user', content: [{ type: 'text', text: 'second' }] }, ...await next()]
  345. })
  346. send(agent, 'hi')
  347. await waitForIdle(ctx, agent)
  348. const texts = adapter.requests[0]!.messages.map(m => m.content[0]?.type === 'text' ? m.content[0].text : '')
  349. expect(texts).toEqual(['first', 'second', 'hi'])
  350. })
  351. it('with no contributions the header omits messagePrefix and the request is the bare derivation', async () => {
  352. const adapter = new MockAdapter([textResponse('ok')])
  353. const ctx = await harness(adapter)
  354. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  355. // A listener that delegates without contributing — the canonical no-op.
  356. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => next())
  357. send(agent, 'hi')
  358. await waitForIdle(ctx, agent)
  359. const headerEvent = events(agent).find(e => e.type === 'request/header')
  360. expect(headerEvent?.type === 'request/header' && 'messagePrefix' in headerEvent.data.header).toBe(false)
  361. expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }])
  362. })
  363. it('the frozen seed rejects in-place mutation — a contribution is a returned extension', 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. let mutationError: unknown
  368. ctx.on('agent/session-prefix', async (_agent, prefix, _signal, next): Promise<Message[]> => {
  369. try {
  370. prefix.push({ role: 'user', content: [{ type: 'text', text: 'smuggled' }] })
  371. } catch (error: unknown) {
  372. mutationError = error
  373. }
  374. return next()
  375. })
  376. send(agent, 'hi')
  377. await waitForIdle(ctx, agent)
  378. expect(mutationError).toBeInstanceOf(TypeError)
  379. expect(adapter.requests[0]!.messages).toEqual([{ role: 'user', content: [{ type: 'text', text: 'hi' }] }])
  380. })
  381. it('mutating a listener-held reference after composition cannot alter later requests (the cache is a frozen clone)', async () => {
  382. const adapter = new MockAdapter([
  383. toolCallResponse('c1', 'echo', { text: 'ping' }),
  384. textResponse('done'),
  385. ])
  386. const ctx = await harness(adapter)
  387. ctx.tools.register(defineTool({
  388. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  389. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  390. }))
  391. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  392. const held: Message = { role: 'user', content: [{ type: 'text', text: 'v1' }] }
  393. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => [...await next(), held])
  394. send(agent, 'go')
  395. await waitForIdle(ctx, agent)
  396. // The listener mutates the object it contributed AFTER composition; the
  397. // cached prefix is a deep-frozen clone, so step 2's request is unchanged.
  398. held.content = [{ type: 'text', text: 'v2' }]
  399. expect(adapter.requests[1]!.messages[0]).toEqual({ role: 'user', content: [{ type: 'text', text: 'v1' }] })
  400. expect(events(agent).filter(e => e.type === 'request/header-delta')).toHaveLength(0)
  401. })
  402. })
  403. describe('agent/turn-continuation (ContinuationDecision)', () => {
  404. it('a continue decision with a reason records next-step steering in the same turn', async () => {
  405. const adapter = new MockAdapter([textResponse('step 1 no tools'), textResponse('step 2')])
  406. const ctx = await harness(adapter)
  407. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  408. let forced = false
  409. ctx.on('agent/turn-continuation', async (_agent, _turn, _default, next): Promise<ContinuationDecision> => {
  410. if (!forced) {
  411. forced = true
  412. return { action: 'continue', reason: { content: [{ type: 'text', text: 'keep going on the goal' }], source: { kind: 'plugin', plugin: 'goal' } } }
  413. }
  414. return next()
  415. })
  416. send(agent, 'go')
  417. await waitForIdle(ctx, agent)
  418. const log = events(agent)
  419. // same turn, two steps
  420. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  421. expect(log.filter(e => e.type === 'step/start')).toHaveLength(2)
  422. // the reason was recorded as steering BEFORE step 2, with its plugin source
  423. const steering = log.find(e => e.type === 'steering/message')
  424. expect(steering?.type === 'steering/message' && steering.data.content).toEqual([{ type: 'text', text: 'keep going on the goal' }])
  425. expect(steering?.type === 'steering/message' && steering.data.source).toEqual({ kind: 'plugin', plugin: 'goal' })
  426. // and reached the next request
  427. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going on the goal')
  428. })
  429. it('a stop decision ends the turn even when the step had tool calls', async () => {
  430. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' })])
  431. const ctx = await harness(adapter)
  432. ctx.tools.register(defineTool({
  433. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  434. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  435. }))
  436. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  437. ctx.on('agent/turn-continuation', async (): Promise<ContinuationDecision> => ({ action: 'stop' }))
  438. send(agent, 'go')
  439. await waitForIdle(ctx, agent)
  440. // default would have continued (had tool calls), but the stop decision wins
  441. expect(adapter.requests).toHaveLength(1)
  442. expect(events(agent).some(e => e.type === 'tool/result')).toBe(true)
  443. })
  444. })
  445. describe('tools/post-execute additionalContext buffering across a multi-call step', () => {
  446. it('appends each call\'s additionalContext only AFTER all tool/results, preserving adjacency', async () => {
  447. // One assistant step with TWO tool calls; the second model response stops.
  448. const twoCalls = [
  449. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  450. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  451. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  452. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  453. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  454. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  455. ]
  456. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  457. const ctx = await harness(adapter)
  458. ctx.tools.register(defineTool({
  459. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  460. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  461. }))
  462. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  463. // Each call attaches additionalContext naming itself.
  464. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  465. ({
  466. kind: 'accept',
  467. additionalContext: {
  468. content: [{ type: 'text', text: `ctx-${exec.callId}` }],
  469. source: { kind: 'plugin', plugin: 'p' },
  470. envelope: 'raw',
  471. meta: { callId: exec.callId },
  472. },
  473. }))
  474. send(agent, 'go')
  475. await waitForIdle(ctx, agent)
  476. // Event order in the log: both tool/results, THEN both context/messages —
  477. // never interleaved (which would break tool-call/result adjacency).
  478. const types = events(agent).map(e => e.type)
  479. const firstResult = types.indexOf('tool/result')
  480. const lastResult = types.lastIndexOf('tool/result')
  481. const firstCtx = types.indexOf('context/message')
  482. expect(firstResult).toBeGreaterThanOrEqual(0)
  483. expect(lastResult).toBeGreaterThan(firstResult) // two results
  484. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  485. // both contexts present
  486. const ctxTexts = events(agent)
  487. .filter(e => e.type === 'context/message')
  488. .flatMap(e => (e.type === 'context/message' ? e.data.content : []))
  489. .map(b => (b.type === 'text' ? b.text : ''))
  490. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  491. const contextEvents = events(agent).filter(e => e.type === 'context/message')
  492. expect(contextEvents.map(e => e.type === 'context/message' && e.data.envelope)).toEqual(['raw', 'raw'])
  493. expect(contextEvents.map(e => e.type === 'context/message' && e.data.meta)).toEqual([{ callId: 'c1' }, { callId: 'c2' }])
  494. })
  495. })
  496. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  497. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  498. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  499. const ctx = await harness(adapter)
  500. let ran = false
  501. ctx.tools.register(defineTool({
  502. name: 'danger', description: 'danger', parameters: {},
  503. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  504. }))
  505. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  506. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  507. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  508. return next()
  509. })
  510. send(agent, 'go')
  511. await waitForIdle(ctx, agent)
  512. expect(ran).toBe(false)
  513. const result = events(agent).find(e => e.type === 'tool/result')
  514. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  515. expect(result?.type === 'tool/result'
  516. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  517. })
  518. })
  519. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  520. // The whole point of the interception taxonomy: a "native hook" needs no
  521. // dsh-hook-protocol, no external command, no hook/* log — it is an ordinary
  522. // cordis plugin subscribing to the canonical events and returning typed
  523. // decisions. This proves all four seams compose end-to-end through the REAL
  524. // loop, with NO hook/* SessionEvents involved (those belong to the bridge lib).
  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, 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. })