interception.spec.ts 31 KB

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