interception.spec.ts 35 KB

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