interception.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { createUserMessage, CallId } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, {
  5. SessionId,
  6. type SessionEvent,
  7. type TurnEndReason,
  8. type UserMessage,
  9. } from '@deepseek-ai/dsh-session'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRegistry, { defineContentToolFixture, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools'
  12. import AgentRegistry, {
  13. type Agent,
  14. type PromptDecision,
  15. type SessionStartSource,
  16. } from '@deepseek-ai/dsh-agent'
  17. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  18. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  19. /**
  20. * The interception seams introduced by the hooks taxonomy: `agent/prompt-submit`,
  21. * `agent/session-start`, `agent/turn-stopping`, and the
  22. * `tools/pre-execute` / `tools/post-execute`
  23. * split with `additionalContexts` buffering. These verify the canonical event
  24. * surface a hook bridge (or a native plugin) programs against, WITHOUT any
  25. * external protocol — a native plugin uses the typed decisions directly.
  26. */
  27. async function harness(adapter: MockAdapter) {
  28. const ctx = new Context()
  29. await ctx.plugin(LlmService)
  30. await ctx.plugin(SessionStore)
  31. await ctx.plugin(SystemPrompt)
  32. await ctx.plugin(ToolRegistry)
  33. await ctx.plugin(AgentRegistry)
  34. await ctx.plugin(AgentLoop, { agents: [] })
  35. ctx.llm.registerAdapter(['mock'], adapter)
  36. return ctx
  37. }
  38. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  39. return new Promise((resolve) => {
  40. const dispose = ctx.on('agent/status', (subject, status) => {
  41. if (subject === agent && status === 'idle') {
  42. dispose()
  43. resolve()
  44. }
  45. })
  46. })
  47. }
  48. function send(agent: Agent, text: string) {
  49. agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  50. }
  51. function events(agent: Agent): SessionEvent[] {
  52. return [...agent.session.events]
  53. }
  54. describe('agent/prompt-submit', () => {
  55. it('allow (default via next) records the user/message unchanged', async () => {
  56. const adapter = new MockAdapter([textResponse('ok')])
  57. const ctx = await harness(adapter)
  58. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  59. const seen: string[] = []
  60. ctx.on('agent/prompt-submit', async (_agent, messages, _signal, next) => {
  61. seen.push(messages[0]!.content.map(b => (b.type === 'text' ? b.text : '')).join(''))
  62. return next()
  63. })
  64. send(agent, 'hello')
  65. await waitForIdle(ctx, agent)
  66. expect(seen).toEqual(['hello'])
  67. const userMsg = events(agent).find(e => e.type === 'user/message')
  68. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'hello' }])
  69. })
  70. it('publishes frozen input without replacing its identity', async () => {
  71. const adapter = new MockAdapter([textResponse('ok')])
  72. const ctx = await harness(adapter)
  73. const agent = ctx.agentLoop.create(SessionId('owned-input'), { provider: 'mock', model: 'mock' })
  74. const entered = Promise.withResolvers<undefined>()
  75. const decision = Promise.withResolvers<PromptDecision>()
  76. const observed: UserMessage[] = []
  77. ctx.on('agent/prompt-submit', async (subject, messages) => {
  78. if (subject !== agent) return { kind: 'allow', messages }
  79. const message = messages[0]!
  80. expect(Object.isFrozen(message)).toBe(true)
  81. expect(Object.isFrozen(message.content)).toBe(true)
  82. expect(Object.isFrozen(message.content[0])).toBe(true)
  83. expect(Object.isFrozen(message.source)).toBe(true)
  84. expect(() => {
  85. const block = message.content[0]
  86. if (block?.type === 'text') block.text = 'listener mutation'
  87. }).toThrow()
  88. observed.push(message)
  89. entered.resolve(undefined)
  90. return decision.promise
  91. })
  92. const input: UserMessage = createUserMessage({
  93. content: [{ type: 'text', text: 'accepted text' }],
  94. source: { kind: 'plugin', plugin: 'accepted source' },
  95. })
  96. const idle = waitForIdle(ctx, agent)
  97. agent.followup(input)
  98. await entered.promise
  99. const block = input.content[0]
  100. expect(() => {
  101. if (block?.type === 'text') block.text = 'caller mutation'
  102. }).toThrow(TypeError)
  103. expect(() => {
  104. if (input.source.kind === 'plugin') input.source.plugin = 'caller mutation'
  105. }).toThrow(TypeError)
  106. decision.resolve({ kind: 'allow', messages: [input] })
  107. await idle
  108. expect(observed).toHaveLength(1)
  109. expect(observed[0]).not.toBe(input)
  110. expect(observed[0]).toMatchObject({
  111. content: [{ type: 'text', text: 'accepted text' }],
  112. source: { kind: 'plugin', plugin: 'accepted source' },
  113. })
  114. const userMsg = events(agent).find(event => event.type === 'user/message')
  115. expect(userMsg?.type === 'user/message' && userMsg.data).toEqual(input)
  116. })
  117. it('allow with content REWRITES the prompt before it is recorded', async () => {
  118. const adapter = new MockAdapter([textResponse('ok')])
  119. const ctx = await harness(adapter)
  120. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  121. ctx.on('agent/prompt-submit', async (_agent, messages): Promise<PromptDecision> =>
  122. ({
  123. kind: 'allow',
  124. messages: [{ ...messages[0]!, content: [{ type: 'text', text: 'REWRITTEN' }] }],
  125. }))
  126. send(agent, 'original')
  127. await waitForIdle(ctx, agent)
  128. const userMsg = events(agent).find(e => e.type === 'user/message')
  129. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'REWRITTEN' }])
  130. // the rewritten prompt is what reached the model
  131. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('REWRITTEN')
  132. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('original')
  133. })
  134. it('allow with additionalContexts injects separate injected-context user messages into the turn', async () => {
  135. const adapter = new MockAdapter([textResponse('ok')])
  136. const ctx = await harness(adapter)
  137. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  138. ctx.on('agent/prompt-submit', async (_agent, messages): Promise<PromptDecision> =>
  139. ({
  140. kind: 'allow',
  141. messages: [...messages, createUserMessage({
  142. content: [{ type: 'text', text: '<system-reminder>extra ctx</system-reminder>' }],
  143. source: { kind: 'plugin', plugin: 'test' },
  144. })],
  145. }))
  146. send(agent, 'go')
  147. await waitForIdle(ctx, agent)
  148. const log = events(agent)
  149. const userMsg = log.find(e => e.type === 'user/message' && e.data.source.kind === 'user')
  150. const ctxMsg = log.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  151. expect(userMsg).toBeDefined()
  152. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.content).toEqual([{ type: 'text', text: '<system-reminder>extra ctx</system-reminder>' }])
  153. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  154. const sent = JSON.stringify(adapter.requests[0]!.messages)
  155. expect(sent).toContain('extra ctx')
  156. })
  157. it('runs pre-step after prompt rewrites and injected context become durable', async () => {
  158. const adapter = new MockAdapter([textResponse('ok')])
  159. const ctx = await harness(adapter)
  160. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  161. ctx.on('agent/prompt-submit', async (_agent, messages): Promise<PromptDecision> =>
  162. ({
  163. kind: 'allow',
  164. messages: [{
  165. ...messages[0]!,
  166. content: [{ type: 'text', text: 'REWRITTEN prompt' }],
  167. }, createUserMessage({
  168. content: [{ type: 'text', text: 'injected ctx' }], source: { kind: 'plugin', plugin: 'test' },
  169. })],
  170. }))
  171. let preStepDerived: string | undefined
  172. ctx.on('agent/step', (subject, _turn, step) => {
  173. if (subject === agent && step === 1) preStepDerived = JSON.stringify(subject.session.deriveMessages())
  174. })
  175. send(agent, 'ORIGINAL prompt')
  176. await waitForIdle(ctx, agent)
  177. expect(preStepDerived).toBeDefined()
  178. expect(preStepDerived).toContain('REWRITTEN prompt')
  179. expect(preStepDerived).toContain('injected ctx')
  180. expect(preStepDerived).not.toContain('ORIGINAL prompt')
  181. })
  182. it('block drops the claimed prompt before any turn or model call', async () => {
  183. const adapter = new MockAdapter([textResponse('should not run')])
  184. const ctx = await harness(adapter)
  185. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  186. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  187. ({ kind: 'block', reason: 'blocked by policy' }))
  188. const reasons: TurnEndReason[] = []
  189. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  190. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'do something' }], source: { kind: 'user' } }))
  191. await agent.whenIdle()
  192. // the model was never called
  193. expect(adapter.requests).toHaveLength(0)
  194. const log = events(agent)
  195. expect(log.some(e => e.type === 'turn/start')).toBe(false)
  196. expect(log.some(e => e.type === 'turn/end')).toBe(false)
  197. expect(log.some(e => e.type === 'user/message')).toBe(false)
  198. expect(log.some(e => e.type === 'step/start')).toBe(false)
  199. expect(reasons).toEqual([])
  200. })
  201. it('stages inject and steer during admission for the admitted turn', async () => {
  202. const adapter = new MockAdapter([textResponse('ok')])
  203. const ctx = await harness(adapter)
  204. const agent = ctx.agentLoop.create(SessionId('admission-outbox'), { provider: 'mock', model: 'mock' })
  205. const entered = Promise.withResolvers<undefined>()
  206. const decision = Promise.withResolvers<PromptDecision>()
  207. let claimed: UserMessage[] = []
  208. let firstAdmission = true
  209. ctx.on('agent/prompt-submit', async (_agent, messages) => {
  210. if (!firstAdmission) return { kind: 'allow', messages }
  211. firstAdmission = false
  212. claimed = messages
  213. entered.resolve(undefined)
  214. return decision.promise
  215. })
  216. const idle = waitForIdle(ctx, agent)
  217. send(agent, 'admitted prompt')
  218. await entered.promise
  219. expect(agent.status).toBe('running')
  220. expect(events(agent).some(event => event.type === 'turn/start')).toBe(false)
  221. agent.inject(createUserMessage({
  222. content: [{ type: 'text', text: 'attached context' }],
  223. source: { kind: 'plugin', plugin: 'test' },
  224. }))
  225. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'admission steering' }], source: { kind: 'user' } }))
  226. expect(events(agent).some(event => event.type === 'user/message')).toBe(false)
  227. expect(agent.inbox.nextStep.map(message => message.content[0]))
  228. .toEqual([
  229. { type: 'text', text: 'attached context' },
  230. { type: 'text', text: 'admission steering' },
  231. ])
  232. decision.resolve({ kind: 'allow', messages: claimed })
  233. await idle
  234. expect(agent.inbox.hasPending).toBe(false)
  235. const staged = events(agent).filter(event =>
  236. event.type === 'turn/start' || event.type === 'user/message' || event.type === 'steering/message')
  237. expect(staged.map(event => event.type)).toEqual([
  238. 'turn/start',
  239. 'user/message',
  240. 'user/message',
  241. 'user/message',
  242. ])
  243. expect(staged[1]?.type === 'user/message' && staged[1].data.content)
  244. .toEqual([{ type: 'text', text: 'admitted prompt' }])
  245. expect(staged[2]?.type === 'user/message' && staged[2].data.content)
  246. .toEqual([{ type: 'text', text: 'attached context' }])
  247. expect(staged[3]?.type === 'user/message' && staged[3].data.content)
  248. .toEqual([{ type: 'text', text: 'admission steering' }])
  249. const firstRequest = JSON.stringify(adapter.requests[0]?.messages)
  250. expect(firstRequest).toContain('admitted prompt')
  251. expect(firstRequest).not.toContain('attached context')
  252. expect(firstRequest).not.toContain('admission steering')
  253. const nextRequest = JSON.stringify(adapter.requests[1]?.messages)
  254. expect(nextRequest).toContain('attached context')
  255. expect(nextRequest).toContain('admission steering')
  256. })
  257. it('cancels admission-time input when admission is blocked', async () => {
  258. const adapter = new MockAdapter([textResponse('retried')])
  259. const ctx = await harness(adapter)
  260. const agent = ctx.agentLoop.create(SessionId('blocked-admission-outbox'), { provider: 'mock', model: 'mock' })
  261. const entered = Promise.withResolvers<undefined>()
  262. const decision = Promise.withResolvers<PromptDecision>()
  263. const disposeBlock = ctx.on('agent/prompt-submit', async () => {
  264. entered.resolve(undefined)
  265. return decision.promise
  266. })
  267. const blockedIdle = waitForIdle(ctx, agent)
  268. send(agent, 'blocked prompt')
  269. await entered.promise
  270. agent.inject(createUserMessage({
  271. content: [{ type: 'text', text: 'staged context' }],
  272. source: { kind: 'plugin', plugin: 'test' },
  273. }))
  274. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'staged steering' }], source: { kind: 'user' } }))
  275. decision.resolve({ kind: 'block', reason: 'policy' })
  276. await blockedIdle
  277. expect(agent.inbox.nextStep).toHaveLength(0)
  278. expect(events(agent).some(event => event.type === 'turn/start')).toBe(false)
  279. expect(adapter.requests).toEqual([])
  280. disposeBlock()
  281. send(agent, 'resume')
  282. await waitForIdle(ctx, agent)
  283. const staged = events(agent).filter(event =>
  284. event.type === 'user/message' || event.type === 'steering/message')
  285. expect(staged.map(event => event.type)).toEqual(['user/message'])
  286. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('blocked prompt')
  287. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('staged context')
  288. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('staged steering')
  289. })
  290. it('cancels later queued work when an admission is blocked', async () => {
  291. const adapter = new MockAdapter([textResponse('continued')])
  292. const ctx = await harness(adapter)
  293. const agent = ctx.agentLoop.create(SessionId('rejected-admission-order'), {
  294. provider: 'mock',
  295. model: 'mock',
  296. })
  297. ctx.on('agent/prompt-submit', async (_agent, messages, _signal, next) => {
  298. const decision = await next()
  299. return messages.some(message =>
  300. message.content.some(block => block.type === 'text' && block.text === 'blocked prompt'))
  301. ? { kind: 'block', reason: 'policy' }
  302. : decision
  303. })
  304. ctx.on('agent/prompt-submit', async (subject, messages, _signal, next) => {
  305. if (messages.some(message =>
  306. message.content.some(block => block.type === 'text' && block.text === 'blocked prompt'))) {
  307. subject.inject(createUserMessage({
  308. content: [{ type: 'text', text: 'earlier state change' }],
  309. source: { kind: 'plugin', plugin: 'test' },
  310. }))
  311. subject.steer(createUserMessage({
  312. content: [{ type: 'text', text: 'earlier steering' }],
  313. source: { kind: 'user' },
  314. }))
  315. }
  316. return next()
  317. })
  318. const idle = waitForIdle(ctx, agent)
  319. send(agent, 'blocked prompt')
  320. send(agent, 'later prompt')
  321. await idle
  322. expect(events(agent).some(event => event.type === 'turn/start')).toBe(false)
  323. expect(agent.inbox.hasPending).toBe(false)
  324. expect(adapter.requests).toEqual([])
  325. })
  326. it('cancels context-only injection when admission closes without a turn', async () => {
  327. const adapter = new MockAdapter([])
  328. const ctx = await harness(adapter)
  329. const agent = ctx.agentLoop.create(SessionId('blocked-admission-context'), { provider: 'mock', model: 'mock' })
  330. const entered = Promise.withResolvers<undefined>()
  331. const decision = Promise.withResolvers<PromptDecision>()
  332. ctx.on('agent/prompt-submit', async () => {
  333. entered.resolve(undefined)
  334. return decision.promise
  335. })
  336. const idle = waitForIdle(ctx, agent)
  337. send(agent, 'blocked prompt')
  338. await entered.promise
  339. agent.inject(createUserMessage({
  340. content: [{ type: 'text', text: 'independent context' }],
  341. source: { kind: 'plugin', plugin: 'test' },
  342. }))
  343. decision.resolve({ kind: 'block', reason: 'policy' })
  344. await idle
  345. const log = events(agent)
  346. expect(log.some(event => event.type === 'user/message')).toBe(false)
  347. expect(agent.inbox.hasPending).toBe(false)
  348. expect(adapter.requests).toEqual([])
  349. })
  350. it('leaves inbox state unchanged when its durable append fails', async () => {
  351. const adapter = new MockAdapter([])
  352. const ctx = await harness(adapter)
  353. const agent = ctx.agentLoop.create(SessionId('blocked-admission-append-failure'), {
  354. provider: 'mock',
  355. model: 'mock',
  356. })
  357. vi.spyOn(agent.session, 'append').mockImplementationOnce(() => {
  358. throw new Error('append unavailable')
  359. })
  360. expect(() => {
  361. send(agent, 'blocked prompt')
  362. }).toThrow('append unavailable')
  363. expect(events(agent)).toEqual([])
  364. expect(agent.inbox.hasPending).toBe(false)
  365. expect(agent.status).toBe('idle')
  366. })
  367. it('a blocked prompt cancels adjacent queued prompts', async () => {
  368. const adapter = new MockAdapter([textResponse('ran once')])
  369. const ctx = await harness(adapter)
  370. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  371. ctx.on('agent/prompt-submit', async (_agent, messages, _signal, next): Promise<PromptDecision> => {
  372. const text = messages.flatMap(message => message.content)
  373. .map(b => (b.type === 'text' ? b.text : '')).join('')
  374. return text === 'secret' ? { kind: 'block', reason: 'policy: no secrets' } : next()
  375. })
  376. const reasons: TurnEndReason[] = []
  377. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  378. send(agent, 'secret')
  379. send(agent, 'safe')
  380. await waitForIdle(ctx, agent)
  381. const log = events(agent)
  382. expect(log.filter(e => e.type === 'user/message')).toHaveLength(0)
  383. expect(adapter.requests).toHaveLength(0)
  384. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(0)
  385. expect(reasons).toEqual([])
  386. })
  387. it('a throwing prompt-submit listener reports the driver error and retains adjacent work', async () => {
  388. const adapter = new MockAdapter([textResponse('after')])
  389. const ctx = await harness(adapter)
  390. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  391. let threw = false
  392. ctx.on('agent/prompt-submit', async (_agent, messages) => {
  393. if (!threw) { threw = true; throw new Error('prompt hook broke') }
  394. return { kind: 'allow' as const, messages }
  395. })
  396. const errors: Error[] = []
  397. const reasons: TurnEndReason[] = []
  398. const statuses: string[] = []
  399. ctx.on('agent/error', (_a, _t, _s, error) => {
  400. if (error instanceof Error) errors.push(error)
  401. })
  402. ctx.on('agent/status', (subject, status) => { if (subject === agent) statuses.push(status) })
  403. ctx.on('session/event', (session, event) => {
  404. if (session === agent.session && event.type === 'turn/end') reasons.push(event.data.reason)
  405. })
  406. const idle = waitForIdle(ctx, agent)
  407. send(agent, 'first')
  408. send(agent, 'second')
  409. await idle
  410. expect(errors).toEqual([expect.objectContaining({ message: 'prompt hook broke' })])
  411. const log = events(agent)
  412. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(0)
  413. expect(log.filter(e => e.type === 'turn/end')).toHaveLength(0)
  414. expect(reasons).toEqual([])
  415. expect(statuses).toEqual(['running', 'idle'])
  416. expect(adapter.requests).toHaveLength(0)
  417. expect(agent.inbox.nextTurn).toHaveLength(2)
  418. })
  419. })
  420. describe('agent/session-start', () => {
  421. it('fires once with source "startup" for a fresh create, before the first turn', async () => {
  422. const adapter = new MockAdapter([textResponse('ok')])
  423. const ctx = await harness(adapter)
  424. const sources: SessionStartSource[] = []
  425. ctx.on('agent/session-start', (_agent, source) => void sources.push(source))
  426. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  427. // fires synchronously at create, before any turn
  428. expect(sources).toEqual(['startup'])
  429. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  430. send(agent, 'go')
  431. await waitForIdle(ctx, agent)
  432. // still only one session-start
  433. expect(sources).toEqual(['startup'])
  434. })
  435. it('a session-start listener can inject context the first request sees', async () => {
  436. const adapter = new MockAdapter([textResponse('ok')])
  437. const ctx = await harness(adapter)
  438. ctx.on('agent/session-start', (agent) => {
  439. agent.inject(createUserMessage({ content: [{ type: 'text', text: 'session preamble' }], source: { kind: 'plugin', plugin: 'test' } }))
  440. })
  441. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  442. send(agent, 'go')
  443. await waitForIdle(ctx, agent)
  444. // the injected context reached the model on the first (only) request
  445. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  446. // and is recorded with the plugin source, never mislabeled as a user prompt
  447. const ctxMsg = events(agent).find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  448. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  449. })
  450. it('a throwing session-start listener does not abort agent construction', async () => {
  451. const adapter = new MockAdapter([textResponse('ok')])
  452. const ctx = await harness(adapter)
  453. ctx.on('agent/session-start', () => { throw new Error('session-start hook broke') })
  454. // create must not throw — the listener error is contained/logged
  455. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  456. expect(agent.id).toBe(SessionId('a1'))
  457. // and the agent still runs
  458. send(agent, 'go')
  459. await waitForIdle(ctx, agent)
  460. expect(adapter.requests).toHaveLength(1)
  461. })
  462. })
  463. describe('tool additionalContexts buffering across a step', () => {
  464. it('appends each call\'s contexts only AFTER all tool/results, preserving adjacency', async () => {
  465. // One assistant step with TWO tool calls; the second model response stops.
  466. const twoCalls = [
  467. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  468. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  469. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  470. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  471. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  472. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  473. ]
  474. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  475. const ctx = await harness(adapter)
  476. ctx.tools.register(defineContentToolFixture({
  477. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  478. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  479. }))
  480. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  481. // Each call attaches one context naming itself.
  482. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  483. ({
  484. kind: 'accept',
  485. additionalContexts: [createUserMessage({
  486. content: [{ type: 'text', text: `ctx-${exec.callId}` }],
  487. source: { kind: 'plugin', plugin: 'p' },
  488. })],
  489. }))
  490. send(agent, 'go')
  491. await waitForIdle(ctx, agent)
  492. // Event order in the log: both tool/results, THEN both injected contexts —
  493. // never interleaved (which would break tool-call/result adjacency).
  494. const injected = events(agent).filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  495. const seqs = events(agent)
  496. const firstResult = seqs.findIndex(e => e.type === 'tool/result')
  497. const lastResult = seqs.map(e => e.type).lastIndexOf('tool/result')
  498. const firstCtx = seqs.findIndex(e => e === injected[0])
  499. expect(firstResult).toBeGreaterThanOrEqual(0)
  500. expect(lastResult).toBeGreaterThan(firstResult) // two results
  501. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  502. // both contexts present
  503. const ctxTexts = injected
  504. .flatMap(e => (e.type === 'user/message' ? e.data.content : []))
  505. .map(b => (b.type === 'text' ? b.text : ''))
  506. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  507. })
  508. it('appends multiple contexts deferred by one composite tool after its outer result', async () => {
  509. const adapter = new MockAdapter([toolCallResponse('c1', 'composite', {}), textResponse('done')])
  510. const ctx = await harness(adapter)
  511. ctx.tools.register(defineContentToolFixture({
  512. name: 'composite', description: 'composite', parameters: {},
  513. async execute(_args, exec) {
  514. exec.deferContext(createUserMessage({
  515. content: [{ type: 'text', text: 'nested-a' }], source: { kind: 'plugin', plugin: 'a' },
  516. }))
  517. exec.deferContext(createUserMessage({
  518. content: [{ type: 'text', text: 'nested-b' }], source: { kind: 'plugin', plugin: 'b' },
  519. }))
  520. return [{ type: 'text', text: 'outer result' }]
  521. },
  522. }))
  523. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  524. send(agent, 'go')
  525. await waitForIdle(ctx, agent)
  526. const log = events(agent)
  527. const resultIndex = log.findIndex(event => event.type === 'tool/result')
  528. const contextEvents = log.filter(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  529. expect(resultIndex).toBeGreaterThanOrEqual(0)
  530. expect(log.findIndex(event => event === contextEvents[0])).toBeGreaterThan(resultIndex)
  531. expect(contextEvents.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  532. { kind: 'plugin', plugin: 'a' },
  533. { kind: 'plugin', plugin: 'b' },
  534. ])
  535. })
  536. })
  537. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  538. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  539. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  540. const ctx = await harness(adapter)
  541. let ran = false
  542. ctx.tools.register(defineContentToolFixture({
  543. name: 'danger', description: 'danger', parameters: {},
  544. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  545. }))
  546. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  547. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  548. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  549. return next()
  550. })
  551. send(agent, 'go')
  552. await waitForIdle(ctx, agent)
  553. expect(ran).toBe(false)
  554. const result = events(agent).find(e => e.type === 'tool/result')
  555. expect(result?.type === 'tool/result' && result.data.message.content[0].isError).toBe(true)
  556. expect(result?.type === 'tool/result'
  557. && result.data.message.content[0].content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  558. })
  559. })
  560. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  561. // The whole point of the interception taxonomy: a "native hook" needs no dsh-hook-protocol,
  562. // no external command, no hook/* log — it is an ordinary cordis plugin subscribing to the
  563. // canonical events and returning typed decisions.
  564. const NativeGuard = {
  565. name: 'native-guard',
  566. apply(ctx: Context) {
  567. // 1. SessionStart: seed a standing instruction.
  568. ctx.on('agent/session-start', (agent, source) => {
  569. agent.inject(createUserMessage({ content: [{ type: 'text', text: `policy active (started: ${source})` }], source: { kind: 'plugin', plugin: 'native-guard' } }))
  570. })
  571. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  572. ctx.on('agent/prompt-submit', async (_agent, messages, _signal, next): Promise<PromptDecision> => {
  573. const text = messages.flatMap(message => message.content)
  574. .map(b => (b.type === 'text' ? b.text : '')).join('')
  575. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  576. return next()
  577. })
  578. // 3. PreToolUse: deny a dangerous tool by name.
  579. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  580. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  581. return next()
  582. })
  583. // 4. PostToolUse: attach context after a tool runs.
  584. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  585. const decision = await next()
  586. if (decision.kind === 'accept') {
  587. return { kind: 'accept', additionalContexts: [createUserMessage({
  588. content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' },
  589. })] }
  590. }
  591. return decision
  592. })
  593. },
  594. }
  595. it('all four seams fire for a real allowed turn with a tool call', async () => {
  596. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  597. const ctx = await harness(adapter)
  598. await ctx.plugin(NativeGuard)
  599. ctx.tools.register(defineContentToolFixture({
  600. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  601. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  602. }))
  603. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  604. send(agent, 'please echo hi')
  605. await waitForIdle(ctx, agent)
  606. const log = events(agent)
  607. // session-start preamble injected
  608. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin'
  609. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  610. // prompt allowed → user-sourced user/message recorded
  611. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'user')).toBe(true)
  612. // tool ran (echo allowed) and post-execute attached "audited" context
  613. expect(log.some(e => e.type === 'tool/result' && !e.data.message.content[0].isError)).toBe(true)
  614. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin'
  615. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  616. // NO hook/* events — a native plugin needs none
  617. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  618. })
  619. it('the same plugin blocks a destructive prompt before a turn or model call', async () => {
  620. const adapter = new MockAdapter([textResponse('should not run')])
  621. const ctx = await harness(adapter)
  622. await ctx.plugin(NativeGuard)
  623. const agent = ctx.agentLoop.create(SessionId('a2'), { provider: 'mock', model: 'mock' })
  624. const reasons: TurnEndReason[] = []
  625. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  626. send(agent, 'run rm -rf /')
  627. await agent.whenIdle()
  628. expect(adapter.requests).toHaveLength(0)
  629. expect(reasons).toEqual([])
  630. })
  631. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  632. const adapter = new MockAdapter([textResponse('ok')])
  633. const ctx = await harness(adapter)
  634. const fiber = await ctx.plugin(NativeGuard)
  635. await fiber.dispose()
  636. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  637. const agent = ctx.agentLoop.create(SessionId('a3'), { provider: 'mock', model: 'mock' })
  638. send(agent, 'run rm -rf /')
  639. await waitForIdle(ctx, agent)
  640. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  641. expect(adapter.requests).toHaveLength(1)
  642. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  643. })
  644. })