interception.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService, { CallId } from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { type SessionEvent, type TurnEndReason } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool, type PostToolDecision, type PreToolDecision } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, {
  8. AgentId,
  9. type ContinuationDecision,
  10. type PromptDecision,
  11. type SessionStartSource,
  12. } from '@deepseek-ai/dsh-agent'
  13. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  14. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  15. /**
  16. * The interception seams introduced by the hooks taxonomy: `agent/prompt-submit`,
  17. * `agent/session-start`, the reshaped `agent/turn-continuation`
  18. * ({@link ContinuationDecision}), and the `tools/pre-execute` / `tools/post-execute`
  19. * split with `additionalContext` buffering. These verify the canonical event
  20. * surface a hook bridge (or a native plugin) programs against, WITHOUT any
  21. * external protocol — a native plugin uses the typed decisions directly.
  22. */
  23. async function harness(adapter: MockAdapter) {
  24. const ctx = new Context()
  25. await ctx.plugin(LlmService)
  26. await ctx.plugin(SessionStore)
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRegistry)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(AgentLoop, { agents: [] })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. function waitForIdle(ctx: Context, agent: ReactLoopAgent): Promise<void> {
  35. return new Promise((resolve) => {
  36. const dispose = ctx.on('agent/status', (subject, status) => {
  37. if (subject === agent && status === 'idle') {
  38. dispose()
  39. resolve()
  40. }
  41. })
  42. })
  43. }
  44. function send(agent: ReactLoopAgent, text: string) {
  45. agent.send([{ type: 'text', text }])
  46. }
  47. function events(agent: ReactLoopAgent): SessionEvent[] {
  48. return [...agent.session.events]
  49. }
  50. describe('agent/prompt-submit', () => {
  51. it('allow (default via next) records the user/message unchanged', async () => {
  52. const adapter = new MockAdapter([textResponse('ok')])
  53. const ctx = await harness(adapter)
  54. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  55. const seen: string[] = []
  56. ctx.on('agent/prompt-submit', async (_agent, content, _source, next) => {
  57. seen.push(content.map(b => (b.type === 'text' ? b.text : '')).join(''))
  58. return next()
  59. })
  60. send(agent, 'hello')
  61. await waitForIdle(ctx, agent)
  62. expect(seen).toEqual(['hello'])
  63. const userMsg = events(agent).find(e => e.type === 'user/message')
  64. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'hello' }])
  65. })
  66. it('allow with content REWRITES the prompt before it is recorded', async () => {
  67. const adapter = new MockAdapter([textResponse('ok')])
  68. const ctx = await harness(adapter)
  69. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  70. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  71. ({ kind: 'allow', content: [{ type: 'text', text: 'REWRITTEN' }] }))
  72. send(agent, 'original')
  73. await waitForIdle(ctx, agent)
  74. const userMsg = events(agent).find(e => e.type === 'user/message')
  75. expect(userMsg?.type === 'user/message' && userMsg.data.content).toEqual([{ type: 'text', text: 'REWRITTEN' }])
  76. // the rewritten prompt is what reached the model
  77. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('REWRITTEN')
  78. expect(JSON.stringify(adapter.requests[0]!.messages)).not.toContain('original')
  79. })
  80. it('allow with additionalContext injects a separate context/message into the turn', async () => {
  81. const adapter = new MockAdapter([textResponse('ok')])
  82. const ctx = await harness(adapter)
  83. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  84. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  85. ({
  86. kind: 'allow',
  87. additionalContext: { content: [{ type: 'text', text: 'extra ctx' }], source: { kind: 'plugin', plugin: 'test' } },
  88. }))
  89. send(agent, 'go')
  90. await waitForIdle(ctx, agent)
  91. const log = events(agent)
  92. const userMsg = log.find(e => e.type === 'user/message')
  93. const ctxMsg = log.find(e => e.type === 'context/message')
  94. expect(userMsg).toBeDefined()
  95. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.content).toEqual([{ type: 'text', text: 'extra ctx' }])
  96. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  97. // both the prompt and the injected context reach the model
  98. const sent = JSON.stringify(adapter.requests[0]!.messages)
  99. expect(sent).toContain('extra ctx')
  100. })
  101. it('a prompt-submit rewrite + additionalContext is VISIBLE to the agent/pre-step seam (merged ordering)', async () => {
  102. // The merge of the interception seams with master's compaction seam pins one
  103. // ordering: `agent/prompt-submit` runs (rewriting the prompt and injecting
  104. // context) BEFORE the step loop, and `agent/pre-step` fires INSIDE the step
  105. // before the single deriveMessages(). So a compaction listener on
  106. // `agent/pre-step` must observe the surface AFTER the prompt rewrite/inject —
  107. // otherwise it would measure/compact stale history. This cross-test proves
  108. // the two seams compose in the right order (each is covered in isolation
  109. // elsewhere; this asserts they see each other's effects on the same turn).
  110. const adapter = new MockAdapter([textResponse('ok')])
  111. const ctx = await harness(adapter)
  112. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  113. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  114. ({
  115. kind: 'allow',
  116. content: [{ type: 'text', text: 'REWRITTEN prompt' }],
  117. additionalContext: { content: [{ type: 'text', text: 'injected ctx' }], source: { kind: 'plugin', plugin: 'test' } },
  118. }))
  119. // The pre-step seam (where compaction lives) derives the surface it would act
  120. // on. Capture what it sees on the first step.
  121. let preStepDerived: string | undefined
  122. ctx.on('agent/pre-step', (subject, _turn, step) => {
  123. if (subject === agent && step === 1) preStepDerived = JSON.stringify(subject.session.deriveMessages())
  124. })
  125. send(agent, 'ORIGINAL prompt')
  126. await waitForIdle(ctx, agent)
  127. // The pre-step seam ran and saw BOTH the rewrite (not the original) and the
  128. // injected context — i.e. the prompt-submit effects landed before it.
  129. expect(preStepDerived).toBeDefined()
  130. expect(preStepDerived).toContain('REWRITTEN prompt')
  131. expect(preStepDerived).toContain('injected ctx')
  132. expect(preStepDerived).not.toContain('ORIGINAL prompt')
  133. })
  134. it('block drops the (only) prompt → zero-step turn ends rejected, model never called', async () => {
  135. const adapter = new MockAdapter([textResponse('should not run')])
  136. const ctx = await harness(adapter)
  137. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  138. ctx.on('agent/prompt-submit', async (): Promise<PromptDecision> =>
  139. ({ kind: 'block', reason: 'blocked by policy' }))
  140. const reasons: TurnEndReason[] = []
  141. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  142. send(agent, 'do something')
  143. await waitForIdle(ctx, agent)
  144. // the model was never called
  145. expect(adapter.requests).toHaveLength(0)
  146. // the turn opened and closed balanced, with no user/message and no step
  147. const log = events(agent)
  148. expect(log.some(e => e.type === 'turn/start')).toBe(true)
  149. expect(log.some(e => e.type === 'turn/end')).toBe(true)
  150. expect(log.some(e => e.type === 'user/message')).toBe(false)
  151. expect(log.some(e => e.type === 'step/start')).toBe(false)
  152. // the veto is recorded durably as a prompt/blocked in the open turn
  153. const blocked = log.find(e => e.type === 'prompt/blocked')
  154. expect(blocked?.type === 'prompt/blocked' && blocked.data).toMatchObject({
  155. content: [{ type: 'text', text: 'do something' }],
  156. reason: 'blocked by policy',
  157. })
  158. // ended rejected with the block reason
  159. expect(reasons).toEqual([{ kind: 'rejected', reason: 'blocked by policy' }])
  160. const turnEnd = log.findLast(e => e.type === 'turn/end')
  161. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'rejected', reason: 'blocked by policy' })
  162. })
  163. it('a mixed batch records a prompt/blocked for the vetoed prompt while the allowed one runs', async () => {
  164. // Two prompts queued into ONE turn: block "secret", allow "safe". The turn is
  165. // NOT rejected (a prompt was allowed), so without a durable prompt/blocked the
  166. // vetoed prompt and its reason would vanish from the log entirely.
  167. const adapter = new MockAdapter([textResponse('ran once')])
  168. const ctx = await harness(adapter)
  169. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  170. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  171. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  172. return text === 'secret' ? { kind: 'block', reason: 'policy: no secrets' } : next()
  173. })
  174. const reasons: TurnEndReason[] = []
  175. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  176. // both sends land before the loop drains → one batched turn
  177. send(agent, 'secret')
  178. send(agent, 'safe')
  179. await waitForIdle(ctx, agent)
  180. const log = events(agent)
  181. // the allowed prompt became a user/message and drove exactly one model call
  182. const userMsgs = log.filter(e => e.type === 'user/message')
  183. expect(userMsgs).toHaveLength(1)
  184. expect(userMsgs[0]?.type === 'user/message' && userMsgs[0].data.content).toEqual([{ type: 'text', text: 'safe' }])
  185. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  186. // the blocked prompt is durably recorded, with its content + reason
  187. const blocked = log.filter(e => e.type === 'prompt/blocked')
  188. expect(blocked).toHaveLength(1)
  189. expect(blocked[0]?.type === 'prompt/blocked' && blocked[0].data).toMatchObject({
  190. content: [{ type: 'text', text: 'secret' }],
  191. reason: 'policy: no secrets',
  192. })
  193. // the turn did NOT reject — a sibling was allowed — so the boundary reason
  194. // alone would not have preserved the block
  195. expect(reasons.some(r => r.kind === 'rejected')).toBe(false)
  196. })
  197. it('a throwing prompt-submit listener ends the turn balanced (error), loop survives', async () => {
  198. const adapter = new MockAdapter([textResponse('after')])
  199. const ctx = await harness(adapter)
  200. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  201. let threw = false
  202. ctx.on('agent/prompt-submit', async () => {
  203. if (!threw) { threw = true; throw new Error('prompt hook broke') }
  204. return { kind: 'allow' as const }
  205. })
  206. const errors: Error[] = []
  207. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  208. send(agent, 'first')
  209. await waitForIdle(ctx, agent)
  210. expect(errors.map(e => e.message)).toEqual(['prompt hook broke'])
  211. // turn balanced
  212. const log = events(agent)
  213. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  214. expect(log.filter(e => e.type === 'turn/end')).toHaveLength(1)
  215. // loop survives: a second prompt runs normally
  216. send(agent, 'second')
  217. await waitForIdle(ctx, agent)
  218. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  219. })
  220. })
  221. describe('agent/session-start', () => {
  222. it('fires once with source "startup" for a fresh create, before the first turn', async () => {
  223. const adapter = new MockAdapter([textResponse('ok')])
  224. const ctx = await harness(adapter)
  225. const sources: SessionStartSource[] = []
  226. ctx.on('agent/session-start', (_agent, source) => void sources.push(source))
  227. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  228. // fires synchronously at create, before any turn
  229. expect(sources).toEqual(['startup'])
  230. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  231. send(agent, 'go')
  232. await waitForIdle(ctx, agent)
  233. // still only one session-start
  234. expect(sources).toEqual(['startup'])
  235. })
  236. it('a session-start listener can inject context the first request sees', async () => {
  237. const adapter = new MockAdapter([textResponse('ok')])
  238. const ctx = await harness(adapter)
  239. ctx.on('agent/session-start', (agent) => {
  240. agent.inject([{ type: 'text', text: 'session preamble' }], { source: { kind: 'plugin', plugin: 'test' } })
  241. })
  242. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  243. send(agent, 'go')
  244. await waitForIdle(ctx, agent)
  245. // the injected context reached the model on the first (only) request
  246. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  247. // and is recorded with the plugin source, never mislabeled as a user prompt
  248. const ctxMsg = events(agent).find(e => e.type === 'context/message')
  249. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  250. })
  251. it('a throwing session-start listener does not abort agent construction', async () => {
  252. const adapter = new MockAdapter([textResponse('ok')])
  253. const ctx = await harness(adapter)
  254. ctx.on('agent/session-start', () => { throw new Error('session-start hook broke') })
  255. // create must not throw — the listener error is contained/logged
  256. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  257. expect(agent.id).toBe(AgentId('a1'))
  258. // and the agent still runs
  259. send(agent, 'go')
  260. await waitForIdle(ctx, agent)
  261. expect(adapter.requests).toHaveLength(1)
  262. })
  263. })
  264. describe('agent/turn-continuation (ContinuationDecision)', () => {
  265. it('a continue decision with a reason records next-step steering in the same turn', async () => {
  266. const adapter = new MockAdapter([textResponse('step 1 no tools'), textResponse('step 2')])
  267. const ctx = await harness(adapter)
  268. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  269. let forced = false
  270. ctx.on('agent/turn-continuation', async (_agent, _turn, _default, next): Promise<ContinuationDecision> => {
  271. if (!forced) {
  272. forced = true
  273. return { action: 'continue', reason: { content: [{ type: 'text', text: 'keep going on the goal' }], source: { kind: 'plugin', plugin: 'goal' } } }
  274. }
  275. return next()
  276. })
  277. send(agent, 'go')
  278. await waitForIdle(ctx, agent)
  279. const log = events(agent)
  280. // same turn, two steps
  281. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  282. expect(log.filter(e => e.type === 'step/start')).toHaveLength(2)
  283. // the reason was recorded as steering BEFORE step 2, with its plugin source
  284. const steering = log.find(e => e.type === 'steering/message')
  285. expect(steering?.type === 'steering/message' && steering.data.content).toEqual([{ type: 'text', text: 'keep going on the goal' }])
  286. expect(steering?.type === 'steering/message' && steering.data.source).toEqual({ kind: 'plugin', plugin: 'goal' })
  287. // and reached the next request
  288. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going on the goal')
  289. })
  290. it('a stop decision ends the turn even when the step had tool calls', async () => {
  291. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' })])
  292. const ctx = await harness(adapter)
  293. ctx.tools.register(defineTool({
  294. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  295. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  296. }))
  297. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  298. ctx.on('agent/turn-continuation', async (): Promise<ContinuationDecision> => ({ action: 'stop' }))
  299. send(agent, 'go')
  300. await waitForIdle(ctx, agent)
  301. // default would have continued (had tool calls), but the stop decision wins
  302. expect(adapter.requests).toHaveLength(1)
  303. expect(events(agent).some(e => e.type === 'tool/result')).toBe(true)
  304. })
  305. })
  306. describe('tools/post-execute additionalContext buffering across a multi-call step', () => {
  307. it('appends each call\'s additionalContext only AFTER all tool/results, preserving adjacency', async () => {
  308. // One assistant step with TWO tool calls; the second model response stops.
  309. const twoCalls = [
  310. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  311. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  312. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  313. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  314. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  315. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  316. ]
  317. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  318. const ctx = await harness(adapter)
  319. ctx.tools.register(defineTool({
  320. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  321. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  322. }))
  323. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  324. // Each call attaches additionalContext naming itself.
  325. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  326. ({ kind: 'accept', additionalContext: { content: [{ type: 'text', text: `ctx-${exec.callId}` }], source: { kind: 'plugin', plugin: 'p' } } }))
  327. send(agent, 'go')
  328. await waitForIdle(ctx, agent)
  329. // Event order in the log: both tool/results, THEN both context/messages —
  330. // never interleaved (which would break tool-call/result adjacency).
  331. const types = events(agent).map(e => e.type)
  332. const firstResult = types.indexOf('tool/result')
  333. const lastResult = types.lastIndexOf('tool/result')
  334. const firstCtx = types.indexOf('context/message')
  335. expect(firstResult).toBeGreaterThanOrEqual(0)
  336. expect(lastResult).toBeGreaterThan(firstResult) // two results
  337. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  338. // both contexts present
  339. const ctxTexts = events(agent)
  340. .filter(e => e.type === 'context/message')
  341. .flatMap(e => (e.type === 'context/message' ? e.data.content : []))
  342. .map(b => (b.type === 'text' ? b.text : ''))
  343. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  344. })
  345. })
  346. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  347. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  348. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  349. const ctx = await harness(adapter)
  350. let ran = false
  351. ctx.tools.register(defineTool({
  352. name: 'danger', description: 'danger', parameters: {},
  353. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  354. }))
  355. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  356. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  357. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  358. return next()
  359. })
  360. send(agent, 'go')
  361. await waitForIdle(ctx, agent)
  362. expect(ran).toBe(false)
  363. const result = events(agent).find(e => e.type === 'tool/result')
  364. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  365. expect(result?.type === 'tool/result'
  366. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  367. })
  368. })
  369. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  370. // The whole point of the interception taxonomy: a "native hook" needs no
  371. // dsh-hook-protocol, no external command, no hook/* log — it is an ordinary
  372. // cordis plugin subscribing to the canonical events and returning typed
  373. // decisions. This proves all four seams compose end-to-end through the REAL
  374. // loop, with NO hook/* SessionEvents involved (those belong to the bridge lib).
  375. const NativeGuard = {
  376. name: 'native-guard',
  377. apply(ctx: Context) {
  378. // 1. SessionStart: seed a standing instruction.
  379. ctx.on('agent/session-start', (agent, source) => {
  380. agent.inject(
  381. [{ type: 'text', text: `policy active (started: ${source})` }],
  382. { source: { kind: 'plugin', plugin: 'native-guard' } },
  383. )
  384. })
  385. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  386. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  387. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  388. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  389. return next()
  390. })
  391. // 3. PreToolUse: deny a dangerous tool by name.
  392. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  393. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  394. return next()
  395. })
  396. // 4. PostToolUse: attach context after a tool runs.
  397. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  398. const decision = await next()
  399. if (decision.kind === 'accept') {
  400. return { kind: 'accept', additionalContext: { content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' } } }
  401. }
  402. return decision
  403. })
  404. },
  405. }
  406. it('all four seams fire for a real allowed turn with a tool call', async () => {
  407. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  408. const ctx = await harness(adapter)
  409. await ctx.plugin(NativeGuard)
  410. ctx.tools.register(defineTool({
  411. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  412. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  413. }))
  414. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  415. send(agent, 'please echo hi')
  416. await waitForIdle(ctx, agent)
  417. const log = events(agent)
  418. // session-start preamble injected
  419. expect(log.some(e => e.type === 'context/message'
  420. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  421. // prompt allowed → user/message recorded
  422. expect(log.some(e => e.type === 'user/message')).toBe(true)
  423. // tool ran (echo allowed) and post-execute attached "audited" context
  424. expect(log.some(e => e.type === 'tool/result' && !e.data.isError)).toBe(true)
  425. expect(log.some(e => e.type === 'context/message'
  426. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  427. // NO hook/* events — a native plugin needs none
  428. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  429. })
  430. it('the same plugin blocks a destructive prompt → rejected turn, model never called', async () => {
  431. const adapter = new MockAdapter([textResponse('should not run')])
  432. const ctx = await harness(adapter)
  433. await ctx.plugin(NativeGuard)
  434. const agent = ctx.agentLoop.create(AgentId('a2'), { model: 'mock' })
  435. const reasons: TurnEndReason[] = []
  436. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  437. send(agent, 'run rm -rf /')
  438. await waitForIdle(ctx, agent)
  439. expect(adapter.requests).toHaveLength(0)
  440. expect(reasons).toEqual([{ kind: 'rejected', reason: 'destructive prompt blocked' }])
  441. })
  442. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  443. const adapter = new MockAdapter([textResponse('ok')])
  444. const ctx = await harness(adapter)
  445. const fiber = await ctx.plugin(NativeGuard)
  446. await fiber.dispose()
  447. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  448. const agent = ctx.agentLoop.create(AgentId('a3'), { model: 'mock' })
  449. send(agent, 'run rm -rf /')
  450. await waitForIdle(ctx, agent)
  451. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  452. expect(adapter.requests).toHaveLength(1)
  453. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  454. })
  455. })