approval.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import type { Agent } from '@deepseek-ai/dsh-agent'
  4. import { CallId } from '@deepseek-ai/dsh-llm'
  5. import { carrierKeyOf, createScope } from '@deepseek-ai/dsh-scope'
  6. import type { Scope } from '@deepseek-ai/dsh-scope'
  7. import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ApprovalService, { ApprovalOutcome, ApprovalRequest, effectiveApprovalPolicy, setApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
  11. /**
  12. * A minimal Agent stand-in — the service only reaches `agent.session.append`
  13. * and folds `.events`. Seeded inside an open turn by default (request()'s
  14. * turn-enclosure precondition); pass `seed` to stage idle/closed logs.
  15. * Returns the recorded audit appends alongside the fake.
  16. */
  17. function fakeAgent(seed: Array<{ type: string }> = [{ type: 'turn/start' }, { type: 'user/message' }]): { agent: Agent; appended: Array<{ type: string; data: Record<string, unknown> }> } {
  18. const appended: Array<{ type: string; data: Record<string, unknown> }> = []
  19. const agent = {
  20. session: {
  21. events: seed,
  22. append: (type: string, data: Record<string, unknown>) => {
  23. appended.push({ type, data })
  24. return { type, data } as unknown as SessionEvent
  25. },
  26. },
  27. } as unknown as Agent
  28. return { agent, appended }
  29. }
  30. async function mounted(): Promise<Context> {
  31. const ctx = new Context()
  32. await ctx.plugin(ApprovalService)
  33. return ctx
  34. }
  35. function requestOf(agent: Agent, overrides: Partial<ApprovalRequest> = {}): ApprovalRequest {
  36. return { agent, toolName: 'echo', ...overrides }
  37. }
  38. describe('ApprovalService.request', () => {
  39. it('throws before appending anything when no turn has ever opened (idle ask)', async () => {
  40. const ctx = await mounted()
  41. const { agent, appended } = fakeAgent([])
  42. await expect(ctx.approval.request(requestOf(agent))).rejects.toThrow(/outside an open turn/)
  43. expect(appended).toHaveLength(0)
  44. })
  45. it('throws between turns — a closed turn does not satisfy the enclosure precondition', async () => {
  46. const ctx = await mounted()
  47. const { agent, appended } = fakeAgent([{ type: 'turn/start' }, { type: 'turn/end' }])
  48. await expect(ctx.approval.request(requestOf(agent))).rejects.toThrow(/outside an open turn/)
  49. expect(appended).toHaveLength(0)
  50. })
  51. it('fails closed to unavailable when nobody listens, auditing the asked/decided pair', async () => {
  52. const ctx = await mounted()
  53. const { agent, appended } = fakeAgent()
  54. const outcome = await ctx.approval.request(requestOf(agent, { callId: CallId('call-1'), reason: 'hook says ask' }))
  55. expect(outcome).toBe('unavailable')
  56. expect(appended.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
  57. const [asked, decided] = appended
  58. expect(asked?.data).toMatchObject({ toolName: 'echo', callId: 'call-1', reason: 'hook says ask' })
  59. expect(decided?.data).toMatchObject({ outcome: 'unavailable' })
  60. expect(decided?.data['id']).toBe(asked?.data['id'])
  61. })
  62. it('omits absent optional fields from the asked audit event', async () => {
  63. const ctx = await mounted()
  64. const { agent, appended } = fakeAgent()
  65. await ctx.approval.request(requestOf(agent))
  66. expect(Object.keys(appended[0]?.data ?? {}).sort()).toEqual(['id', 'toolName'])
  67. })
  68. it('borrows the exact readonly request for scoped dispatch and audit', async () => {
  69. const ctx = await mounted()
  70. const { agent, appended } = fakeAgent()
  71. let scope!: Scope
  72. const scopeFiber = await ctx.plugin(Object.assign((inner: Context) => {
  73. scope = createScope(inner, agent)
  74. }, { inject: ['approval'] }))
  75. let received: ApprovalRequest | undefined
  76. let carrier: unknown
  77. scope.ctx.on('approval/request', function (req) {
  78. received = req
  79. carrier = carrierKeyOf(this)
  80. return Promise.resolve<ApprovalOutcome>('allowed-once')
  81. })
  82. const request = requestOf(agent, {
  83. toolName: 'scoped-tool',
  84. callId: CallId('scoped-call'),
  85. reason: 'scoped reason',
  86. })
  87. await expect(ctx.approval.request(request)).resolves.toBe('allowed-once')
  88. expect(carrier).toBe(agent)
  89. expect(received).toBe(request)
  90. expect(appended).toHaveLength(2)
  91. expect(appended[0]?.data).toMatchObject({
  92. toolName: 'scoped-tool',
  93. callId: 'scoped-call',
  94. reason: 'scoped reason',
  95. })
  96. expect(appended[1]?.data).toMatchObject({ outcome: 'allowed-once' })
  97. expect(appended[1]?.data['id']).toBe(appended[0]?.data['id'])
  98. await scopeFiber.dispose()
  99. })
  100. it('contains an approval/asked observer throw after append and still completes the pair', async () => {
  101. const ctx = new Context()
  102. await ctx.plugin(SessionStore)
  103. await ctx.plugin(ApprovalService)
  104. const session = ctx.sessions.create(SessionId('asked-observer-throw'))
  105. session.append('turn/start', { turn: 1 })
  106. const agent = { session } as unknown as Agent
  107. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  108. ctx.on('session/event', (_session, event) => {
  109. if (event.type === 'approval/asked') throw new Error('observer failed after asked append')
  110. })
  111. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  112. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('allowed-once')
  113. const audit = session.events.filter(event => event.type.startsWith('approval/'))
  114. const asked = session.events.find((event): event is SessionEvent<'approval/asked'> => event.type === 'approval/asked')
  115. const decided = session.events.find((event): event is SessionEvent<'approval/decided'> => event.type === 'approval/decided')
  116. expect(audit.map(event => event.type)).toEqual(['approval/asked', 'approval/decided'])
  117. expect(decided?.data.id).toBe(asked?.data.id)
  118. expect(warn).toHaveBeenCalledWith(expect.stringContaining('session/event listener threw: Error: observer failed after asked append'))
  119. })
  120. it('contains an approval/decided observer throw after append and still resolves', async () => {
  121. const ctx = new Context()
  122. await ctx.plugin(SessionStore)
  123. await ctx.plugin(ApprovalService)
  124. const session = ctx.sessions.create(SessionId('decided-observer-throw'))
  125. session.append('turn/start', { turn: 1 })
  126. const agent = { session } as unknown as Agent
  127. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  128. ctx.on('session/event', (_session, event) => {
  129. if (event.type === 'approval/decided') throw new Error('observer failed after decided append')
  130. })
  131. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
  132. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('rejected')
  133. const audit = session.events.filter(event => event.type.startsWith('approval/'))
  134. const asked = session.events.find((event): event is SessionEvent<'approval/asked'> => event.type === 'approval/asked')
  135. const decided = session.events.find((event): event is SessionEvent<'approval/decided'> => event.type === 'approval/decided')
  136. expect(audit.map(event => event.type)).toEqual(['approval/asked', 'approval/decided'])
  137. expect(decided?.data).toMatchObject({ id: asked?.data.id, outcome: 'rejected' })
  138. expect(warn).toHaveBeenCalledWith(expect.stringContaining('session/event listener threw: Error: observer failed after decided append'))
  139. })
  140. it('propagates an append failure that prevented audit log growth', async () => {
  141. const ctx = await mounted()
  142. const failure = new Error('append failed before log growth')
  143. const agent = {
  144. session: {
  145. events: [{ type: 'turn/start' }],
  146. append: () => { throw failure },
  147. },
  148. } as unknown as Agent
  149. await expect(ctx.approval.request(requestOf(agent))).rejects.toBe(failure)
  150. })
  151. it('returns the first answering listener outcome (single decision slot)', async () => {
  152. const ctx = await mounted()
  153. const { agent } = fakeAgent()
  154. let secondRan = false
  155. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  156. ctx.on('approval/request', () => {
  157. secondRan = true
  158. return Promise.resolve<ApprovalOutcome>('rejected')
  159. })
  160. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('allowed-once')
  161. expect(secondRan).toBe(false)
  162. })
  163. it('lets a non-owning listener delegate via next() down to the fail-closed default', async () => {
  164. const ctx = await mounted()
  165. const { agent } = fakeAgent()
  166. ctx.on('approval/request', (_req, next) => next())
  167. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('unavailable')
  168. })
  169. it('dispatches to global and matching agent-scoped listeners, never a foreign scope', async () => {
  170. const ctx = await mounted()
  171. const { agent: agentA } = fakeAgent()
  172. const { agent: agentB } = fakeAgent()
  173. let scopeA!: Scope
  174. let scopeB!: Scope
  175. const scopesFiber = await ctx.plugin(Object.assign((inner: Context) => {
  176. scopeA = createScope(inner, agentA)
  177. scopeB = createScope(inner, agentB)
  178. }, { inject: ['approval'] }))
  179. const heard: string[] = []
  180. ctx.on('approval/request', (req, next) => {
  181. heard.push(req.agent === agentA ? 'global:A' : 'global:B')
  182. return next()
  183. })
  184. scopeA.ctx.on('approval/request', (_req, next) => {
  185. heard.push('scoped:A')
  186. return next()
  187. })
  188. scopeB.ctx.on('approval/request', (_req, next) => {
  189. heard.push('scoped:B')
  190. return next()
  191. })
  192. await expect(ctx.approval.request(requestOf(agentA))).resolves.toBe('unavailable')
  193. await expect(ctx.approval.request(requestOf(agentB))).resolves.toBe('unavailable')
  194. expect(heard).toEqual(['global:A', 'scoped:A', 'global:B', 'scoped:B'])
  195. await scopesFiber.dispose()
  196. })
  197. it('keys the scoped dispatch carrier to the exact request agent', async () => {
  198. const ctx = await mounted()
  199. const { agent } = fakeAgent()
  200. let scope!: Scope
  201. const scopeFiber = await ctx.plugin(Object.assign((inner: Context) => {
  202. scope = createScope(inner, agent)
  203. }, { inject: ['approval'] }))
  204. let seenKey: object | undefined
  205. scope.ctx.on('approval/request', function (req, next) {
  206. seenKey = carrierKeyOf(this)
  207. expect(req.agent).toBe(agent)
  208. return next()
  209. })
  210. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('unavailable')
  211. expect(seenKey).toBe(agent)
  212. await scopeFiber.dispose()
  213. })
  214. it('contains a throwing answerer as unavailable', async () => {
  215. const ctx = await mounted()
  216. const { agent, appended } = fakeAgent()
  217. ctx.on('approval/request', () => Promise.reject(new Error('transport died')))
  218. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('unavailable')
  219. expect(appended[1]?.data).toMatchObject({ outcome: 'unavailable' })
  220. })
  221. it('normalizes a rogue non-vocabulary answer to unavailable', async () => {
  222. const ctx = await mounted()
  223. const { agent } = fakeAgent()
  224. // A JS answerer can return anything; the seam must not leak it into
  225. // callers' closed-union switches.
  226. ctx.on('approval/request', () => Promise.resolve('yolo' as ApprovalOutcome))
  227. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('unavailable')
  228. })
  229. it('settles cancelled immediately on an already-aborted signal without asking anyone', async () => {
  230. const ctx = await mounted()
  231. const { agent, appended } = fakeAgent()
  232. let asked = false
  233. ctx.on('approval/request', () => {
  234. asked = true
  235. return Promise.resolve<ApprovalOutcome>('allowed-once')
  236. })
  237. const outcome = await ctx.approval.request(requestOf(agent, { signal: AbortSignal.abort() }))
  238. expect(outcome).toBe('cancelled')
  239. expect(asked).toBe(false)
  240. expect(appended.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
  241. expect(appended[1]?.data).toMatchObject({ outcome: 'cancelled' })
  242. })
  243. it('resolves cancelled when the signal aborts mid-question and discards the late answer', async () => {
  244. const ctx = await mounted()
  245. const { agent, appended } = fakeAgent()
  246. let settleLate: ((outcome: ApprovalOutcome) => void) | undefined
  247. ctx.on('approval/request', () => new Promise<ApprovalOutcome>((resolve) => { settleLate = resolve }))
  248. const controller = new AbortController()
  249. const pending = ctx.approval.request(requestOf(agent, { signal: controller.signal }))
  250. controller.abort()
  251. await expect(pending).resolves.toBe('cancelled')
  252. // The answerer settles after the fact: no second decided event appears.
  253. settleLate?.('allowed-once')
  254. await Promise.resolve()
  255. expect(appended.filter(e => e.type === 'approval/decided')).toHaveLength(1)
  256. expect(appended[1]?.data).toMatchObject({ outcome: 'cancelled' })
  257. })
  258. it('discards a late REJECTION after abort without an unhandled rejection', async () => {
  259. const ctx = await mounted()
  260. const { agent } = fakeAgent()
  261. let rejectLate: ((error: Error) => void) | undefined
  262. ctx.on('approval/request', () => new Promise<ApprovalOutcome>((_resolve, reject) => { rejectLate = reject }))
  263. const controller = new AbortController()
  264. const pending = ctx.approval.request(requestOf(agent, { signal: controller.signal }))
  265. controller.abort()
  266. await expect(pending).resolves.toBe('cancelled')
  267. rejectLate?.(new Error('answered too late'))
  268. // Drain microtasks: the contained rejection must not escape the seam.
  269. await new Promise((resolve) => { setTimeout(resolve, 0) })
  270. })
  271. it('resolves the answer when the signal never aborts', async () => {
  272. const ctx = await mounted()
  273. const { agent } = fakeAgent()
  274. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('rejected'))
  275. const controller = new AbortController()
  276. await expect(ctx.approval.request(requestOf(agent, { signal: controller.signal }))).resolves.toBe('rejected')
  277. })
  278. it('issues a fresh id per request', async () => {
  279. const ctx = await mounted()
  280. const { agent, appended } = fakeAgent()
  281. await ctx.approval.request(requestOf(agent))
  282. await ctx.approval.request(requestOf(agent))
  283. const ids = appended.filter(e => e.type === 'approval/asked').map(e => e.data['id'])
  284. expect(ids).toHaveLength(2)
  285. expect(ids[0]).not.toBe(ids[1])
  286. })
  287. it('drops a disposed plugin listener from the chain (HMR safety)', async () => {
  288. const ctx = await mounted()
  289. const { agent } = fakeAgent()
  290. const fiber = await ctx.plugin((inner: Context) => {
  291. inner.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  292. })
  293. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('allowed-once')
  294. await fiber.dispose()
  295. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('unavailable')
  296. })
  297. })
  298. describe('approval policy (the approval/policy fold)', () => {
  299. const NEVER_SENTENCE = 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).'
  300. const ASK_SENTENCE = 'Approval policy: ask. Operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.'
  301. /**
  302. * An agent stand-in over a REAL Session — gate and context fold real events;
  303. * the opened turn satisfies request()'s enclosure precondition.
  304. */
  305. function sessionAgent(id: string): { agent: Agent; session: Session } {
  306. const session = Session.create(SessionId(id))
  307. session.append('turn/start', { turn: 1 })
  308. const agent = { id, session } as unknown as Agent
  309. return { agent, session }
  310. }
  311. it('folds to the last event, or undefined without one', () => {
  312. const { session } = sessionAgent('sess-fold')
  313. expect(effectiveApprovalPolicy(session.events)).toBeUndefined()
  314. setApprovalPolicy(session, 'never')
  315. setApprovalPolicy(session, 'ask')
  316. expect(effectiveApprovalPolicy(session.events)).toBe('ask')
  317. expect(session.events.at(-1)).toMatchObject({ type: 'approval/policy', data: { policy: 'ask' } })
  318. })
  319. it('rejects a policy outside the closed vocabulary before appending', () => {
  320. const append = vi.fn()
  321. const session = { append } as unknown as Session
  322. expect(() => { setApprovalPolicy(session, 'sometimes' as Parameters<typeof setApprovalPolicy>[1]) })
  323. .toThrow('approval policy must be one of "ask" or "never"')
  324. expect(append).not.toHaveBeenCalled()
  325. })
  326. it('defaults a schema-less construction to ask (the ?? narrows the optional TYPE)', async () => {
  327. // Direct construction bypasses the plugin schema (the SystemPrompt-test
  328. // precedent for covering a defaulted Config field's type-narrowing ??).
  329. const ctx = new Context()
  330. const service = new ApprovalService(ctx, {})
  331. const { agent } = sessionAgent('sess-bare-config')
  332. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  333. await expect(service.request({ agent, toolName: 'echo' })).resolves.toBe('allowed-once')
  334. })
  335. it('contains an answerer that throws SYNCHRONOUSLY as unavailable', async () => {
  336. const ctx = new Context()
  337. await ctx.plugin(ApprovalService)
  338. const { agent } = sessionAgent('sess-syncthrow')
  339. ctx.on('approval/request', () => { throw new Error('sync bug') })
  340. await expect(ctx.approval.request({ agent, toolName: 'echo' })).resolves.toBe('unavailable')
  341. })
  342. it('a never config rejects deterministically without consulting any answerer', async () => {
  343. const ctx = new Context()
  344. await ctx.plugin(ApprovalService, { policy: 'never' })
  345. const consulted = vi.fn()
  346. ctx.on('approval/request', (_req, next) => { consulted(); return next() })
  347. const { agent, session } = sessionAgent('sess-gate-1')
  348. await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('rejected')
  349. expect(consulted).not.toHaveBeenCalled()
  350. // The audit pair still lands on the session log.
  351. expect(session.events.filter(e => e.type === 'approval/asked')).toHaveLength(1)
  352. expect(session.events.filter(e => e.type === 'approval/decided')).toHaveLength(1)
  353. })
  354. it('the gate decides FIRST even against an answerer registered before the service (prepend)', async () => {
  355. const ctx = new Context()
  356. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  357. await ctx.plugin(ApprovalService, { policy: 'never' })
  358. const { agent } = sessionAgent('sess-gate-2')
  359. await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('rejected')
  360. })
  361. it('never is unbypassable even by an answerer PREPENDED after the service mounts', async () => {
  362. // Cordis prepend unshifts ahead of every existing listener, including any gate LISTENER the
  363. // service could register — which is exactly why the 'never' decision lives inside request()
  364. // instead. This eager grant would bypass a listener-based gate and therefore must never run.
  365. const ctx = new Context()
  366. await ctx.plugin(ApprovalService, { policy: 'never' })
  367. const consulted = vi.fn()
  368. ctx.on('approval/request', () => { consulted(); return Promise.resolve<ApprovalOutcome>('allowed-once') }, { prepend: true })
  369. const { agent, appended } = fakeAgent()
  370. await expect(ctx.approval.request(requestOf(agent))).resolves.toBe('rejected')
  371. expect(consulted).not.toHaveBeenCalled()
  372. expect(appended.map(e => e.type)).toEqual(['approval/asked', 'approval/decided'])
  373. })
  374. it('a session override outranks the configured default, in both directions', async () => {
  375. const ctx = new Context()
  376. await ctx.plugin(ApprovalService, { policy: 'never' })
  377. ctx.on('approval/request', () => Promise.resolve<ApprovalOutcome>('allowed-once'))
  378. const { agent, session } = sessionAgent('sess-gate-3')
  379. expect(ctx.approval.overrideOf(session)).toBeUndefined()
  380. setApprovalPolicy(session, 'ask')
  381. expect(ctx.approval.overrideOf(session)).toBe('ask')
  382. await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('allowed-once')
  383. setApprovalPolicy(session, 'never')
  384. await expect(ctx.approval.request({ agent, toolName: 'bash' })).resolves.toBe('rejected')
  385. })
  386. it('queues a live policy switch for the next model step', async () => {
  387. const ctx = new Context()
  388. await ctx.plugin(ApprovalService)
  389. const { agent, session } = sessionAgent('sess-policy-notice')
  390. const inject = vi.fn<Agent['inject']>()
  391. const liveAgent = { ...agent, inject } as Agent
  392. ctx.approval.setPolicy(liveAgent, 'never')
  393. ctx.approval.setPolicy(liveAgent, 'never')
  394. expect(effectiveApprovalPolicy(session.events)).toBe('never')
  395. expect(inject).toHaveBeenCalledOnce()
  396. expect(inject.mock.calls[0]?.[0]).toMatchObject({
  397. content: [{
  398. type: 'text',
  399. text: 'The approval policy changed from "ask" to "never" (changed by the user).',
  400. }],
  401. source: { kind: 'plugin', plugin: 'user-approval' },
  402. })
  403. })
  404. it('contributes the complete current ask or never policy as cache-safe context', async () => {
  405. const ctx = new Context()
  406. await ctx.plugin(SystemPrompt)
  407. await ctx.plugin(ApprovalService)
  408. const askAgent = sessionAgent('sess-sect-ask').agent
  409. const { agent: neverAgent, session } = sessionAgent('sess-sect-never')
  410. setApprovalPolicy(session, 'never')
  411. const contextFor = async (context: object) =>
  412. (await ctx.systemPrompt.assemble(context)).contexts.find(entry => entry.name === 'approval:policy')?.text
  413. expect(await contextFor({ agent: askAgent })).toBe(ASK_SENTENCE)
  414. expect(await contextFor({ agent: neverAgent })).toBe(NEVER_SENTENCE)
  415. // A bare assemble (no agent) has no session to state.
  416. expect(await contextFor({})).toBe('')
  417. })
  418. it('reflects the latest durable switch in cache-safe context and stays byte-stable while unchanged', async () => {
  419. const ctx = new Context()
  420. await ctx.plugin(SystemPrompt)
  421. await ctx.plugin(ApprovalService)
  422. const { agent, session } = sessionAgent('sess-context-switch')
  423. const contextFor = async () =>
  424. (await ctx.systemPrompt.assemble({ agent })).contexts.find(entry => entry.name === 'approval:policy')?.text
  425. expect(await contextFor()).toBe(ASK_SENTENCE)
  426. expect(await contextFor()).toBe(ASK_SENTENCE)
  427. setApprovalPolicy(session, 'never')
  428. setApprovalPolicy(session, 'ask')
  429. setApprovalPolicy(session, 'never')
  430. expect(await contextFor()).toBe(NEVER_SENTENCE)
  431. expect(await contextFor()).toBe(NEVER_SENTENCE)
  432. })
  433. it('disposes the runtime-context contribution with the service', async () => {
  434. const ctx = new Context()
  435. await ctx.plugin(SystemPrompt)
  436. const fiber = await ctx.plugin(ApprovalService)
  437. const { agent } = sessionAgent('sess-hmr-service-live')
  438. const contextFor = async () =>
  439. (await ctx.systemPrompt.assemble({ agent })).contexts.find(context => context.name === 'approval:policy')
  440. expect(await contextFor()).toBeDefined()
  441. await fiber.dispose()
  442. expect(await contextFor()).toBeUndefined()
  443. })
  444. })