interception.spec.ts 36 KB

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