1
0

interception.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. // ended rejected with the block reason
  153. expect(reasons).toEqual([{ kind: 'rejected', reason: 'blocked by policy' }])
  154. const turnEnd = log.findLast(e => e.type === 'turn/end')
  155. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'rejected', reason: 'blocked by policy' })
  156. })
  157. it('a throwing prompt-submit listener ends the turn balanced (error), loop survives', async () => {
  158. const adapter = new MockAdapter([textResponse('after')])
  159. const ctx = await harness(adapter)
  160. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  161. let threw = false
  162. ctx.on('agent/prompt-submit', async () => {
  163. if (!threw) { threw = true; throw new Error('prompt hook broke') }
  164. return { kind: 'allow' as const }
  165. })
  166. const errors: Error[] = []
  167. ctx.on('agent/error', (_a, _t, _s, error) => void errors.push(error))
  168. send(agent, 'first')
  169. await waitForIdle(ctx, agent)
  170. expect(errors.map(e => e.message)).toEqual(['prompt hook broke'])
  171. // turn balanced
  172. const log = events(agent)
  173. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  174. expect(log.filter(e => e.type === 'turn/end')).toHaveLength(1)
  175. // loop survives: a second prompt runs normally
  176. send(agent, 'second')
  177. await waitForIdle(ctx, agent)
  178. expect(adapter.requests.length).toBeGreaterThanOrEqual(1)
  179. })
  180. })
  181. describe('agent/session-start', () => {
  182. it('fires once with source "startup" for a fresh create, before the first turn', async () => {
  183. const adapter = new MockAdapter([textResponse('ok')])
  184. const ctx = await harness(adapter)
  185. const sources: SessionStartSource[] = []
  186. ctx.on('agent/session-start', (_agent, source) => void sources.push(source))
  187. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  188. // fires synchronously at create, before any turn
  189. expect(sources).toEqual(['startup'])
  190. expect(events(agent).some(e => e.type === 'turn/start')).toBe(false)
  191. send(agent, 'go')
  192. await waitForIdle(ctx, agent)
  193. // still only one session-start
  194. expect(sources).toEqual(['startup'])
  195. })
  196. it('a session-start listener can inject context the first request sees', async () => {
  197. const adapter = new MockAdapter([textResponse('ok')])
  198. const ctx = await harness(adapter)
  199. ctx.on('agent/session-start', (agent) => {
  200. agent.inject([{ type: 'text', text: 'session preamble' }], { source: { kind: 'plugin', plugin: 'test' } })
  201. })
  202. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  203. send(agent, 'go')
  204. await waitForIdle(ctx, agent)
  205. // the injected context reached the model on the first (only) request
  206. expect(JSON.stringify(adapter.requests[0]!.messages)).toContain('session preamble')
  207. // and is recorded with the plugin source, never mislabeled as a user prompt
  208. const ctxMsg = events(agent).find(e => e.type === 'context/message')
  209. expect(ctxMsg?.type === 'context/message' && ctxMsg.data.source).toEqual({ kind: 'plugin', plugin: 'test' })
  210. })
  211. it('a throwing session-start listener does not abort agent construction', async () => {
  212. const adapter = new MockAdapter([textResponse('ok')])
  213. const ctx = await harness(adapter)
  214. ctx.on('agent/session-start', () => { throw new Error('session-start hook broke') })
  215. // create must not throw — the listener error is contained/logged
  216. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  217. expect(agent.id).toBe(AgentId('a1'))
  218. // and the agent still runs
  219. send(agent, 'go')
  220. await waitForIdle(ctx, agent)
  221. expect(adapter.requests).toHaveLength(1)
  222. })
  223. })
  224. describe('agent/turn-continuation (ContinuationDecision)', () => {
  225. it('a continue decision with a reason records next-step steering in the same turn', async () => {
  226. const adapter = new MockAdapter([textResponse('step 1 no tools'), textResponse('step 2')])
  227. const ctx = await harness(adapter)
  228. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  229. let forced = false
  230. ctx.on('agent/turn-continuation', async (_agent, _turn, _default, next): Promise<ContinuationDecision> => {
  231. if (!forced) {
  232. forced = true
  233. return { action: 'continue', reason: { content: [{ type: 'text', text: 'keep going on the goal' }], source: { kind: 'plugin', plugin: 'goal' } } }
  234. }
  235. return next()
  236. })
  237. send(agent, 'go')
  238. await waitForIdle(ctx, agent)
  239. const log = events(agent)
  240. // same turn, two steps
  241. expect(log.filter(e => e.type === 'turn/start')).toHaveLength(1)
  242. expect(log.filter(e => e.type === 'step/start')).toHaveLength(2)
  243. // the reason was recorded as steering BEFORE step 2, with its plugin source
  244. const steering = log.find(e => e.type === 'steering/message')
  245. expect(steering?.type === 'steering/message' && steering.data.content).toEqual([{ type: 'text', text: 'keep going on the goal' }])
  246. expect(steering?.type === 'steering/message' && steering.data.source).toEqual({ kind: 'plugin', plugin: 'goal' })
  247. // and reached the next request
  248. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going on the goal')
  249. })
  250. it('a stop decision ends the turn even when the step had tool calls', async () => {
  251. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' })])
  252. const ctx = await harness(adapter)
  253. ctx.tools.register(defineTool({
  254. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  255. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  256. }))
  257. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  258. ctx.on('agent/turn-continuation', async (): Promise<ContinuationDecision> => ({ action: 'stop' }))
  259. send(agent, 'go')
  260. await waitForIdle(ctx, agent)
  261. // default would have continued (had tool calls), but the stop decision wins
  262. expect(adapter.requests).toHaveLength(1)
  263. expect(events(agent).some(e => e.type === 'tool/result')).toBe(true)
  264. })
  265. })
  266. describe('tools/post-execute additionalContext buffering across a multi-call step', () => {
  267. it('appends each call\'s additionalContext only AFTER all tool/results, preserving adjacency', async () => {
  268. // One assistant step with TWO tool calls; the second model response stops.
  269. const twoCalls = [
  270. { type: 'block-start' as const, index: 0, blockType: 'tool-call' as const },
  271. { type: 'block-end' as const, index: 0, block: { type: 'tool-call' as const, id: CallId('c1'), name: 'echo', arguments: '{"text":"a"}' } },
  272. { type: 'block-start' as const, index: 1, blockType: 'tool-call' as const },
  273. { type: 'block-end' as const, index: 1, block: { type: 'tool-call' as const, id: CallId('c2'), name: 'echo', arguments: '{"text":"b"}' } },
  274. { type: 'usage' as const, usage: { inputTokens: 5, outputTokens: 5 } },
  275. { type: 'finish' as const, reason: { kind: 'tool-calls' as const } },
  276. ]
  277. const adapter = new MockAdapter([twoCalls, textResponse('done')])
  278. const ctx = await harness(adapter)
  279. ctx.tools.register(defineTool({
  280. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  281. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  282. }))
  283. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  284. // Each call attaches additionalContext naming itself.
  285. ctx.on('tools/post-execute', async (exec, _result): Promise<PostToolDecision> =>
  286. ({ kind: 'accept', additionalContext: { content: [{ type: 'text', text: `ctx-${exec.callId}` }], source: { kind: 'plugin', plugin: 'p' } } }))
  287. send(agent, 'go')
  288. await waitForIdle(ctx, agent)
  289. // Event order in the log: both tool/results, THEN both context/messages —
  290. // never interleaved (which would break tool-call/result adjacency).
  291. const types = events(agent).map(e => e.type)
  292. const firstResult = types.indexOf('tool/result')
  293. const lastResult = types.lastIndexOf('tool/result')
  294. const firstCtx = types.indexOf('context/message')
  295. expect(firstResult).toBeGreaterThanOrEqual(0)
  296. expect(lastResult).toBeGreaterThan(firstResult) // two results
  297. expect(firstCtx).toBeGreaterThan(lastResult) // context only after ALL results
  298. // both contexts present
  299. const ctxTexts = events(agent)
  300. .filter(e => e.type === 'context/message')
  301. .flatMap(e => (e.type === 'context/message' ? e.data.content : []))
  302. .map(b => (b.type === 'text' ? b.text : ''))
  303. expect(ctxTexts).toEqual(['ctx-c1', 'ctx-c2'])
  304. })
  305. })
  306. describe('tools/pre-execute gate (native-plugin permission pattern, end-to-end through the loop)', () => {
  307. it('deny short-circuits dispatch into an isError result the model sees', async () => {
  308. const adapter = new MockAdapter([toolCallResponse('c1', 'danger', {}), textResponse('ok')])
  309. const ctx = await harness(adapter)
  310. let ran = false
  311. ctx.tools.register(defineTool({
  312. name: 'danger', description: 'danger', parameters: {},
  313. async execute() { ran = true; return [{ type: 'text', text: 'should not run' }] },
  314. }))
  315. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  316. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  317. if (exec.name === 'danger') return { kind: 'deny', reason: 'blocked dangerous tool' }
  318. return next()
  319. })
  320. send(agent, 'go')
  321. await waitForIdle(ctx, agent)
  322. expect(ran).toBe(false)
  323. const result = events(agent).find(e => e.type === 'tool/result')
  324. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  325. expect(result?.type === 'tool/result'
  326. && result.data.content.some(b => b.type === 'text' && b.text.includes('blocked dangerous tool'))).toBe(true)
  327. })
  328. })
  329. describe('worked example: a native hook plugin is just a cordis plugin on the seams', () => {
  330. // The whole point of the interception taxonomy: a "native hook" needs no
  331. // dsh-hook-protocol, no external command, no hook/* log — it is an ordinary
  332. // cordis plugin subscribing to the canonical events and returning typed
  333. // decisions. This proves all four seams compose end-to-end through the REAL
  334. // loop, with NO hook/* SessionEvents involved (those belong to the bridge lib).
  335. const NativeGuard = {
  336. name: 'native-guard',
  337. apply(ctx: Context) {
  338. // 1. SessionStart: seed a standing instruction.
  339. ctx.on('agent/session-start', (agent, source) => {
  340. agent.inject(
  341. [{ type: 'text', text: `policy active (started: ${source})` }],
  342. { source: { kind: 'plugin', plugin: 'native-guard' } },
  343. )
  344. })
  345. // 2. PromptSubmit: block a forbidden prompt, annotate the rest.
  346. ctx.on('agent/prompt-submit', async (_agent, content, _source, next): Promise<PromptDecision> => {
  347. const text = content.map(b => (b.type === 'text' ? b.text : '')).join('')
  348. if (text.includes('rm -rf')) return { kind: 'block', reason: 'destructive prompt blocked' }
  349. return next()
  350. })
  351. // 3. PreToolUse: deny a dangerous tool by name.
  352. ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
  353. if (exec.name === 'danger') return { kind: 'deny', reason: 'danger tool denied' }
  354. return next()
  355. })
  356. // 4. PostToolUse: attach context after a tool runs.
  357. ctx.on('tools/post-execute', async (_exec, _result, next): Promise<PostToolDecision> => {
  358. const decision = await next()
  359. if (decision.kind === 'accept') {
  360. return { kind: 'accept', additionalContext: { content: [{ type: 'text', text: 'audited' }], source: { kind: 'plugin', plugin: 'native-guard' } } }
  361. }
  362. return decision
  363. })
  364. },
  365. }
  366. it('all four seams fire for a real allowed turn with a tool call', async () => {
  367. const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'hi' }), textResponse('done')])
  368. const ctx = await harness(adapter)
  369. await ctx.plugin(NativeGuard)
  370. ctx.tools.register(defineTool({
  371. name: 'echo', description: 'echo', parameters: { text: { type: 'string' } },
  372. async execute(args) { return [{ type: 'text', text: String(args.text) }] },
  373. }))
  374. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  375. send(agent, 'please echo hi')
  376. await waitForIdle(ctx, agent)
  377. const log = events(agent)
  378. // session-start preamble injected
  379. expect(log.some(e => e.type === 'context/message'
  380. && e.data.content.some(b => b.type === 'text' && b.text.includes('policy active (started: startup)')))).toBe(true)
  381. // prompt allowed → user/message recorded
  382. expect(log.some(e => e.type === 'user/message')).toBe(true)
  383. // tool ran (echo allowed) and post-execute attached "audited" context
  384. expect(log.some(e => e.type === 'tool/result' && !e.data.isError)).toBe(true)
  385. expect(log.some(e => e.type === 'context/message'
  386. && e.data.content.some(b => b.type === 'text' && b.text === 'audited'))).toBe(true)
  387. // NO hook/* events — a native plugin needs none
  388. expect(log.some(e => e.type.startsWith('hook/'))).toBe(false)
  389. })
  390. it('the same plugin blocks a destructive prompt → rejected turn, model never called', async () => {
  391. const adapter = new MockAdapter([textResponse('should not run')])
  392. const ctx = await harness(adapter)
  393. await ctx.plugin(NativeGuard)
  394. const agent = ctx.agentLoop.create(AgentId('a2'), { model: 'mock' })
  395. const reasons: TurnEndReason[] = []
  396. ctx.on('session/event', (_s, event: SessionEvent) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  397. send(agent, 'run rm -rf /')
  398. await waitForIdle(ctx, agent)
  399. expect(adapter.requests).toHaveLength(0)
  400. expect(reasons).toEqual([{ kind: 'rejected', reason: 'destructive prompt blocked' }])
  401. })
  402. it('HMR-safety: disposing the plugin fiber removes all four listeners', async () => {
  403. const adapter = new MockAdapter([textResponse('ok')])
  404. const ctx = await harness(adapter)
  405. const fiber = await ctx.plugin(NativeGuard)
  406. await fiber.dispose()
  407. // After disposal, a destructive prompt is NOT blocked (the listener is gone).
  408. const agent = ctx.agentLoop.create(AgentId('a3'), { model: 'mock' })
  409. send(agent, 'run rm -rf /')
  410. await waitForIdle(ctx, agent)
  411. // the prompt ran (not rejected) — proving the prompt-submit listener was disposed
  412. expect(adapter.requests).toHaveLength(1)
  413. expect(events(agent).some(e => e.type === 'user/message')).toBe(true)
  414. })
  415. })