interception.spec.ts 33 KB

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