interception.spec.ts 22 KB

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