interception.spec.ts 33 KB

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