interception.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. const disposeBlock = 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. disposeBlock()
  271. send(agent, 'resume')
  272. await waitForIdle(ctx, agent)
  273. const staged = events(agent).filter(event =>
  274. event.type === 'user/message' || event.type === 'steering/message')
  275. expect(staged.map(event => event.type)).toEqual([
  276. 'user/message',
  277. 'steering/message',
  278. 'user/message',
  279. ])
  280. expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('blocked prompt')
  281. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('staged context')
  282. expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('staged steering')
  283. })
  284. it('orders rejected-admission outbox input before a later admitted prompt', async () => {
  285. const adapter = new MockAdapter([textResponse('continued')])
  286. const ctx = await harness(adapter)
  287. const agent = ctx.agentLoop.create(SessionId('rejected-admission-order'), {
  288. provider: 'mock',
  289. model: 'mock',
  290. })
  291. ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next) => {
  292. const decision = await next()
  293. return content.some(block => block.type === 'text' && block.text === 'blocked prompt')
  294. ? { kind: 'block', reason: 'policy' }
  295. : decision
  296. })
  297. ctx.on('agent/prompt-submit', async (subject, content, _source, _signal, next) => {
  298. if (content.some(block => block.type === 'text' && block.text === 'blocked prompt')) {
  299. subject.inject({
  300. content: [{ type: 'text', text: 'earlier state change' }],
  301. source: { kind: 'plugin', plugin: 'test' },
  302. })
  303. subject.steer({
  304. content: [{ type: 'text', text: 'earlier steering' }],
  305. source: { kind: 'user' },
  306. })
  307. }
  308. return next()
  309. })
  310. const idle = waitForIdle(ctx, agent)
  311. send(agent, 'blocked prompt')
  312. send(agent, 'later prompt')
  313. await idle
  314. const staged = events(agent).filter(event =>
  315. event.type === 'turn/start' || event.type === 'user/message' || event.type === 'steering/message')
  316. expect(staged.map(event => event.type)).toEqual([
  317. 'turn/start',
  318. 'user/message',
  319. 'steering/message',
  320. 'user/message',
  321. ])
  322. expect(staged[1]?.type === 'user/message' && staged[1].data.content)
  323. .toEqual([{ type: 'text', text: 'earlier state change' }])
  324. expect(staged[2]?.type === 'steering/message' && staged[2].data.content)
  325. .toEqual([{ type: 'text', text: 'earlier steering' }])
  326. expect(staged[3]?.type === 'user/message' && staged[3].data.content)
  327. .toEqual([{ type: 'text', text: 'later prompt' }])
  328. })
  329. it('commits context-only injection when admission closes without a turn', async () => {
  330. const adapter = new MockAdapter([])
  331. const ctx = await harness(adapter)
  332. const agent = ctx.agentLoop.create(SessionId('blocked-admission-context'), { provider: 'mock', model: 'mock' })
  333. const entered = Promise.withResolvers<undefined>()
  334. const decision = Promise.withResolvers<PromptDecision>()
  335. ctx.on('agent/prompt-submit', async () => {
  336. entered.resolve(undefined)
  337. return decision.promise
  338. })
  339. const idle = waitForIdle(ctx, agent)
  340. send(agent, 'blocked prompt')
  341. await entered.promise
  342. agent.inject({
  343. content: [{ type: 'text', text: 'independent context' }],
  344. source: { kind: 'plugin', plugin: 'test' },
  345. })
  346. decision.resolve({ kind: 'block', reason: 'policy' })
  347. await idle
  348. const log = events(agent)
  349. expect(log.map(event => event.type)).toEqual(['user/message'])
  350. expect(log[0]?.type === 'user/message' && log[0].data.content)
  351. .toEqual([{ type: 'text', text: 'independent context' }])
  352. expect(adapter.requests).toEqual([])
  353. })
  354. it('retains rejected-admission context when its idle append fails', async () => {
  355. const adapter = new MockAdapter([textResponse('retried')])
  356. const ctx = await harness(adapter)
  357. const agent = ctx.agentLoop.create(SessionId('blocked-admission-append-failure'), {
  358. provider: 'mock',
  359. model: 'mock',
  360. })
  361. const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  362. vi.spyOn(agent.session, 'append').mockImplementationOnce(() => {
  363. throw new Error('append unavailable')
  364. })
  365. const entered = Promise.withResolvers<undefined>()
  366. const decision = Promise.withResolvers<PromptDecision>()
  367. const disposeBlock = ctx.on('agent/prompt-submit', async () => {
  368. entered.resolve(undefined)
  369. return decision.promise
  370. })
  371. agent.followup({ content: [{ type: 'text', text: 'blocked prompt' }], source: { kind: 'user' } })
  372. await entered.promise
  373. agent.inject({
  374. content: [{ type: 'text', text: 'retained context' }],
  375. source: { kind: 'plugin', plugin: 'test' },
  376. })
  377. decision.resolve({ kind: 'block', reason: 'policy' })
  378. await agent.whenIdle()
  379. expect(events(agent)).toEqual([])
  380. expect(warned).toHaveBeenCalledWith(expect.stringContaining('append unavailable'))
  381. disposeBlock()
  382. send(agent, 'resume')
  383. await waitForIdle(ctx, agent)
  384. expect(events(agent).some(event => event.type === 'user/message'
  385. && JSON.stringify(event.data.content).includes('retained context'))).toBe(true)
  386. })
  387. it('adjacent blocked and allowed prompts keep independent turn outcomes', async () => {
  388. const adapter = new MockAdapter([textResponse('ran once')])
  389. const ctx = await harness(adapter)
  390. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  391. ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next): Promise<PromptDecision> => {
  392. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  393. return text === 'secret' ? { kind: 'block', reason: 'policy: no secrets' } : next()
  394. })
  395. const reasons: TurnEndReason[] = []
  396. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  397. // The rejected admission is dropped; the allowed prompt owns the only turn.
  398. send(agent, 'secret')
  399. send(agent, 'safe')
  400. await waitForIdle(ctx, agent)
  401. const log = events(agent)
  402. // The allowed prompt became a user/message and drove exactly one model call.
  403. const userMsgs = log.filter(e => e.type === 'user/message')
  404. expect(userMsgs).toHaveLength(1)
  405. expect(userMsgs[0]?.type === 'user/message' && userMsgs[0].data.content).toEqual([{ type: 'text', text: 'safe' }])
  406. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  407. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  408. expect(reasons).toEqual([{ kind: 'completed' }])
  409. })
  410. it('a throwing prompt-submit listener drops that admission while an adjacent message survives', async () => {
  411. const adapter = new MockAdapter([textResponse('after')])
  412. const ctx = await harness(adapter)
  413. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  414. let threw = false
  415. ctx.on('agent/prompt-submit', async () => {
  416. if (!threw) { threw = true; throw new Error('prompt hook broke') }
  417. return { kind: 'allow' as const }
  418. })
  419. const errors: Error[] = []
  420. const reasons: TurnEndReason[] = []
  421. const statuses: string[] = []
  422. ctx.on('agent/error', (_a, _t, _s, error) => {
  423. if (error instanceof Error) errors.push(error)
  424. })
  425. ctx.on('agent/status', (subject, status) => { if (subject === agent) statuses.push(status) })
  426. ctx.on('session/event', (session, event) => {
  427. if (session === agent.session && event.type === 'turn/end') reasons.push(event.data.reason)
  428. })
  429. const idle = waitForIdle(ctx, agent)
  430. send(agent, 'first')
  431. send(agent, 'second')
  432. await idle
  433. expect(errors).toEqual([])
  434. const log = events(agent)
  435. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  436. expect(log.filter(e => e.type === 'turn/end')).toHaveLength(1)
  437. expect(reasons).toEqual([{ kind: 'completed' }])
  438. expect(statuses).toEqual(['running', 'idle'])
  439. expect(adapter.requests).toHaveLength(1)
  440. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('second')
  441. })
  442. })
  443. describe('agent/session-start', () => {
  444. it('fires once with source "startup" for a fresh create, before the first turn', async () => {
  445. const adapter = new MockAdapter([textResponse('ok')])
  446. const ctx = await harness(adapter)
  447. const sources: SessionStartSource[] = []
  448. ctx.on('agent/session-start', (_agent, source) => void sources.push(source))
  449. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  450. // fires synchronously at create, before any turn
  451. expect(sources).toEqual(['startup'])
  452. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  453. send(agent, 'go')
  454. await waitForIdle(ctx, agent)
  455. // still only one session-start
  456. expect(sources).toEqual(['startup'])
  457. })
  458. it('a session-start listener can inject context the first request sees', async () => {
  459. const adapter = new MockAdapter([textResponse('ok')])
  460. const ctx = await harness(adapter)
  461. ctx.on('agent/session-start', (agent) => {
  462. agent.inject({ content: [{ type: 'text', text: 'session preamble' }], source: { kind: 'plugin', plugin: 'test' } })
  463. })
  464. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  465. send(agent, 'go')
  466. await waitForIdle(ctx, agent)
  467. // the injected context reached the model on the first (only) request
  468. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  469. // and is recorded with the plugin source, never mislabeled as a user prompt
  470. const ctxMsg = events(agent).find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  471. expect(ctxMsg?.type === 'user/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  472. })
  473. it('a throwing session-start listener does not abort agent construction', async () => {
  474. const adapter = new MockAdapter([textResponse('ok')])
  475. const ctx = await harness(adapter)
  476. ctx.on('agent/session-start', () => { throw new Error('session-start hook broke') })
  477. // create must not throw — the listener error is contained/logged
  478. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  479. expect(agent.id).toBe(SessionId('a1'))
  480. // and the agent still runs
  481. send(agent, 'go')
  482. await waitForIdle(ctx, agent)
  483. expect(adapter.requests).toHaveLength(1)
  484. })
  485. })
  486. describe('tool additionalContexts buffering across a step', () => {
  487. it('appends each call\'s contexts only AFTER all tool/results, preserving adjacency', async () => {
  488. // One assistant step with TWO tool calls; the second model response stops.
  489. const twoCalls = [
  490. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  491. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  492. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  493. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  494. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  495. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  496. ]
  497. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  498. const ctx = await harness(adapter)
  499. ctx.tools.register(defineContentToolFixture({
  500. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  501. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  502. }))
  503. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  504. // Each call attaches one context naming itself.
  505. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  506. ({
  507. kind: 'accept',
  508. additionalContexts: [{
  509. content: [{ type: 'text', text: `ctx-${exec.callId}` }],
  510. source: { kind: 'plugin', plugin: 'p' },
  511. }],
  512. }))
  513. send(agent, 'go')
  514. await waitForIdle(ctx, agent)
  515. // Event order in the log: both tool/results, THEN both injected contexts —
  516. // never interleaved (which would break tool-call/result adjacency).
  517. const injected = events(agent).filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
  518. const seqs = events(agent)
  519. const firstResult = seqs.findIndex(e => e.type === 'tool/result')
  520. const lastResult = seqs.map(e => e.type).lastIndexOf('tool/result')
  521. const firstCtx = seqs.findIndex(e => e === injected[0])
  522. expect(firstResult).toBeGreaterThanOrEqual(0)
  523. expect(lastResult).toBeGreaterThan(firstResult) // two results
  524. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  525. // both contexts present
  526. const ctxTexts = injected
  527. .flatMap(e => (e.type === 'user/message' ? e.data.content : []))
  528. .map(b => (b.type === 'text' ? b.text : ''))
  529. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  530. })
  531. it('appends multiple contexts deferred by one composite tool after its outer result', async () => {
  532. const adapter = new MockAdapter([toolCallResponse('c1', 'composite', {}), textResponse('done')])
  533. const ctx = await harness(adapter)
  534. ctx.tools.register(defineContentToolFixture({
  535. name: 'composite', description: 'composite', parameters: {},
  536. async execute(_args, exec) {
  537. exec.deferContext({ content: [{ type: 'text', text: 'nested-a' }], source: { kind: 'plugin', plugin: 'a' } })
  538. exec.deferContext({ content: [{ type: 'text', text: 'nested-b' }], source: { kind: 'plugin', plugin: 'b' } })
  539. return [{ type: 'text', text: 'outer result' }]
  540. },
  541. }))
  542. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  543. send(agent, 'go')
  544. await waitForIdle(ctx, agent)
  545. const log = events(agent)
  546. const resultIndex = log.findIndex(event => event.type === 'tool/result')
  547. const contextEvents = log.filter(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
  548. expect(resultIndex).toBeGreaterThanOrEqual(0)
  549. expect(log.findIndex(event => event === contextEvents[0])).toBeGreaterThan(resultIndex)
  550. expect(contextEvents.map(event => event.type === 'user/message' && event.data.source)).toEqual([
  551. { kind: 'plugin', plugin: 'a' },
  552. { kind: 'plugin', plugin: 'b' },
  553. ])
  554. })
  555. })
  556. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  557. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  558. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  559. const ctx = await harness(adapter)
  560. let ran = false
  561. ctx.tools.register(defineContentToolFixture({
  562. name: 'danger', description: 'danger', parameters: {},
  563. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  564. }))
  565. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  566. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  567. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  568. return next()
  569. })
  570. send(agent, 'go')
  571. await waitForIdle(ctx, agent)
  572. expect(ran).toBe(false)
  573. const result = events(agent).find(e => e.type === 'tool/result')
  574. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  575. expect(result?.type === 'tool/result'
  576. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  577. })
  578. })
  579. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  580. // The whole point of the interception taxonomy: a "native hook" needs no dsh-hook-protocol,
  581. // no external command, no hook/* log — it is an ordinary cordis plugin subscribing to the
  582. // canonical events and returning typed decisions.
  583. const NativeGuard = {
  584. name: 'native-guard',
  585. apply(ctx: Context) {
  586. // 1. SessionStart: seed a standing instruction.
  587. ctx.on('agent/session-start', (agent, source) => {
  588. agent.inject({ content: [{ type: 'text', text: `policy active (started: ${source})` }], source: { kind: 'plugin', plugin: 'native-guard' } })
  589. })
  590. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  591. ctx.on('agent/prompt-submit', async (_agent, content, _source, _signal, next): Promise<PromptDecision> => {
  592. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  593. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  594. return next()
  595. })
  596. // 3. PreToolUse: deny a dangerous tool by name.
  597. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  598. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  599. return next()
  600. })
  601. // 4. PostToolUse: attach context after a tool runs.
  602. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  603. const decision = await next()
  604. if (decision.kind === 'accept') {
  605. return { kind: 'accept', additionalContexts: [{ content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' } }] }
  606. }
  607. return decision
  608. })
  609. },
  610. }
  611. it('all four seams fire for a real allowed turn with a tool call', async () => {
  612. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  613. const ctx = await harness(adapter)
  614. await ctx.plugin(NativeGuard)
  615. ctx.tools.register(defineContentToolFixture({
  616. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  617. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  618. }))
  619. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  620. send(agent, 'please echo hi')
  621. await waitForIdle(ctx, agent)
  622. const log = events(agent)
  623. // session-start preamble injected
  624. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin'
  625. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  626. // prompt allowed → user-sourced user/message recorded
  627. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'user')).toBe(true)
  628. // tool ran (echo allowed) and post-execute attached "audited" context
  629. expect(log.some(e => e.type === 'tool/result' && !e.data.isError)).toBe(true)
  630. expect(log.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin'
  631. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  632. // NO hook/* events — a native plugin needs none
  633. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  634. })
  635. it('the same plugin blocks a destructive prompt before a turn or model call', async () => {
  636. const adapter = new MockAdapter([textResponse('should not run')])
  637. const ctx = await harness(adapter)
  638. await ctx.plugin(NativeGuard)
  639. const agent = ctx.agentLoop.create(SessionId('a2'), { provider: 'mock', model: 'mock' })
  640. const reasons: TurnEndReason[] = []
  641. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  642. send(agent, 'run rm -rf /')
  643. await agent.whenIdle()
  644. expect(adapter.requests).toHaveLength(0)
  645. expect(reasons).toEqual([])
  646. })
  647. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  648. const adapter = new MockAdapter([textResponse('ok')])
  649. const ctx = await harness(adapter)
  650. const fiber = await ctx.plugin(NativeGuard)
  651. await fiber.dispose()
  652. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  653. const agent = ctx.agentLoop.create(SessionId('a3'), { provider: 'mock', model: 'mock' })
  654. send(agent, 'run rm -rf /')
  655. await waitForIdle(ctx, agent)
  656. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  657. expect(adapter.requests).toHaveLength(1)
  658. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  659. })
  660. })