interception.spec.ts 34 KB

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