compact-basic.spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import BasicCompactService from '@deepseek-ai/dsh-compact-basic'
  4. import type { BasicCompactConfig } from '@deepseek-ai/dsh-compact-basic'
  5. import { selectCompactableRange } from '@deepseek-ai/dsh-compact-basic/src/region.ts'
  6. import { resolveConfig } from '@deepseek-ai/dsh-compact-basic/src/config.ts'
  7. import type { CompactionResult } from '@deepseek-ai/dsh-compact'
  8. import LlmService, { CallId, LlmAdapter } from '@deepseek-ai/dsh-llm'
  9. import type { ContentBlock, GenerateOptions, Message, StreamChunk } from '@deepseek-ai/dsh-llm'
  10. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  11. import TokenMeterService from '@deepseek-ai/dsh-token-meter'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. const SIGNAL = new AbortController().signal
  14. const MODEL = 'test-model'
  15. function createContext(contextWindow = 1_000): Context {
  16. const ctx = new Context()
  17. void new TokenMeterService(ctx, { contextWindow })
  18. return ctx
  19. }
  20. function agent(session: Session, model?: string): Agent {
  21. return { session, options: model === undefined ? {} : { provider: model, model } } as Agent
  22. }
  23. /** Closed two-message turns followed by one open turn for durable compaction events. */
  24. function conversation(turns = 4, text = 'fixture '.repeat(40).trim()): Session {
  25. const session = new Session(SessionId(`conversation-${turns}`))
  26. for (let turn = 1; turn <= turns; turn += 1) {
  27. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  28. session.append('user/message', {
  29. content: [{ type: 'text', text: `${text} user ${turn}` }],
  30. source: { kind: 'user' },
  31. }, { surfaceOp: 'append' })
  32. session.append('step/start', { turn, step: 1 })
  33. session.append('assistant/message', {
  34. provenance: { provider: MODEL, model: MODEL },
  35. turn,
  36. step: 1,
  37. content: [{ type: 'text', text: `${text} assistant ${turn}` }],
  38. }, { surfaceOp: 'append' })
  39. session.append('step/end', { turn, step: 1 })
  40. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  41. }
  42. session.append('turn/start', {
  43. turn: turns + 1,
  44. trigger: { kind: 'message', source: { kind: 'user' } },
  45. })
  46. return session
  47. }
  48. function toolConversation(): Session {
  49. const session = new Session(SessionId('tools'))
  50. for (let turn = 1; turn <= 3; turn += 1) {
  51. const callId = CallId(`call-${turn}`)
  52. session.append('turn/start', { turn, trigger: { kind: 'message', source: { kind: 'user' } } })
  53. session.append('user/message', {
  54. content: [{ type: 'text', text: `request ${turn} `.repeat(300) }],
  55. source: { kind: 'user' },
  56. }, { surfaceOp: 'append' })
  57. session.append('step/start', { turn, step: 1 })
  58. session.append('assistant/message', {
  59. provenance: { provider: MODEL, model: MODEL },
  60. turn,
  61. step: 1,
  62. content: [
  63. { type: 'text', text: `calling ${turn} `.repeat(300) },
  64. { type: 'tool-call', id: callId, name: 'read', arguments: '{}' },
  65. ],
  66. }, { surfaceOp: 'append' })
  67. session.append('tool/call', { turn, step: 1, callId, name: 'read', arguments: '{}' })
  68. session.append('tool/result', {
  69. turn,
  70. step: 1,
  71. callId,
  72. content: [{ type: 'text', text: `result ${turn} `.repeat(300) }],
  73. isError: false,
  74. }, { surfaceOp: 'append' })
  75. session.append('step/end', { turn, step: 1 })
  76. session.append('turn/end', { turn, reason: { kind: 'completed' } })
  77. }
  78. session.append('turn/start', { turn: 4, trigger: { kind: 'message', source: { kind: 'user' } } })
  79. return session
  80. }
  81. class TestCompactService extends BasicCompactService {
  82. summary: ContentBlock[] = [{ type: 'text', text: 'small checkpoint' }]
  83. summaryProvider = 'summary-provider'
  84. summaryModel = 'summary-model'
  85. error: unknown
  86. mutateDuringSummary: (() => void) | undefined
  87. calls: Array<{ text: string; signal: AbortSignal | undefined }> = []
  88. override async summarize(
  89. text: string,
  90. _agent: Agent,
  91. signal?: AbortSignal,
  92. ): Promise<{ summary: ContentBlock[]; provider: string; model: string; maxTokens?: number }> {
  93. this.calls.push({ text, signal })
  94. this.mutateDuringSummary?.()
  95. if (this.error !== undefined) throw this.error
  96. return {
  97. summary: this.summary,
  98. provider: this.summaryProvider,
  99. model: this.summaryModel,
  100. maxTokens: 123,
  101. }
  102. }
  103. }
  104. function service(
  105. config: BasicCompactConfig = { auto: false },
  106. ctx = createContext(),
  107. ): TestCompactService {
  108. return new TestCompactService(ctx, config)
  109. }
  110. async function compactIfNeeded(
  111. compact: BasicCompactService,
  112. session: Session,
  113. model: string | undefined = MODEL,
  114. system = '',
  115. prefix: readonly Message[] = [],
  116. ): Promise<CompactionResult | null> {
  117. return compact.compactIfNeeded(agent(session, model), system, prefix, SIGNAL)
  118. }
  119. describe('compact configuration and defaults', () => {
  120. it('uses low-friction service-wide defaults', () => {
  121. const ctx = createContext()
  122. const resolved = resolveConfig({}, ctx.tokenMeter)
  123. expect(resolved).toEqual({
  124. thresholdRatio: 0.8,
  125. retainTokens: 160,
  126. summarizationProvider: '',
  127. summarizationModel: '',
  128. maxTokens: 8192,
  129. compactionRetries: 1,
  130. auto: true,
  131. })
  132. expect(Object.isFrozen(resolved)).toBe(true)
  133. })
  134. it('resolves threshold and retention overrides independently', () => {
  135. const ctx = createContext()
  136. const thresholdOnly = resolveConfig({
  137. thresholdRatio: 0.5,
  138. }, ctx.tokenMeter)
  139. expect(thresholdOnly).toMatchObject({
  140. thresholdRatio: 0.5,
  141. retainTokens: 160,
  142. })
  143. const retentionOnly = resolveConfig({
  144. retainTokens: 70,
  145. }, ctx.tokenMeter)
  146. expect(retentionOnly).toMatchObject({
  147. thresholdRatio: 0.8,
  148. retainTokens: 70,
  149. })
  150. })
  151. it('validates common values and pressure-policy invariants', () => {
  152. const ctx = createContext()
  153. const bad = [
  154. [{ maxTokens: 0 }, /maxTokens/],
  155. [{ compactionRetries: -1 }, /compactionRetries/],
  156. [{ auto: 'yes' }, /auto must be a boolean/],
  157. [{ summarizationProvider: 1 }, /summarizationProvider must be a string/],
  158. [{ summarizationModel: 1 }, /summarizationModel must be a string/],
  159. [{ summarizationProvider: MODEL }, /must both be set or both be empty/],
  160. [{ summarizationModel: MODEL }, /must both be set or both be empty/],
  161. [{ thresholdRatio: 0 }, /number in \(0, 1\]/],
  162. [{ thresholdRatio: 1.1 }, /number in \(0, 1\]/],
  163. [{ retainTokens: -1 }, /non-negative integer/],
  164. [{ thresholdRatio: 0.5, retainTokens: 500 }, /less than threshold/],
  165. [{ models: { [MODEL]: { retainTokens: 10 } } }, /BasicCompactConfig: unknown key "models"/],
  166. [{ thresholdRato: 0.5 }, /BasicCompactConfig: unknown key "thresholdRato"/],
  167. ] as Array<[unknown, RegExp]>
  168. for (const [config, pattern] of bad) {
  169. expect(() => resolveConfig(config as BasicCompactConfig, ctx.tokenMeter)).toThrow(pattern)
  170. }
  171. })
  172. })
  173. describe('pressure measurement and retention', () => {
  174. const compactConfig: BasicCompactConfig = {
  175. auto: false,
  176. thresholdRatio: 0.5,
  177. retainTokens: 180,
  178. }
  179. it('skips the provisional check only when no routed or fallback model exists', async () => {
  180. const compact = service(compactConfig)
  181. const session = conversation()
  182. expect(await compact.compactIfNeeded(agent(session), '', [], SIGNAL)).toBeNull()
  183. expect(compact.calls).toHaveLength(0)
  184. })
  185. it('meters any routed model without profile resolution', async () => {
  186. const compact = service(compactConfig)
  187. await expect(compactIfNeeded(compact, conversation(), 'unlisted-model'))
  188. .resolves.not.toBeNull()
  189. })
  190. it('does nothing below threshold and compacts a priced head above threshold', async () => {
  191. const compact = service(compactConfig)
  192. expect(await compactIfNeeded(compact, conversation(2))).toBeNull()
  193. const session = conversation(4)
  194. const result = await compactIfNeeded(compact, session)
  195. expect(result).not.toBeNull()
  196. expect(result?.shadowedSeqs.length).toBeGreaterThan(2)
  197. expect(session.surface.nodes.length).toBeLessThan(8)
  198. })
  199. it('counts the current prompt and request prefix without putting either on the surface', async () => {
  200. const compact = service({
  201. auto: false,
  202. thresholdRatio: 0.7,
  203. retainTokens: 50,
  204. })
  205. const session = conversation(2, 'x'.repeat(200))
  206. expect(await compactIfNeeded(compact, session)).toBeNull()
  207. const prefix: Message[] = [{
  208. role: 'user',
  209. content: [{ type: 'text', text: 'p'.repeat(1_000) }],
  210. }]
  211. const result = await compactIfNeeded(compact, session, MODEL, 's'.repeat(1_000), prefix)
  212. expect(result).not.toBeNull()
  213. expect(prefix).toHaveLength(1)
  214. expect(session.events.some(event => event.type === 'context/message')).toBe(false)
  215. })
  216. it('uses the latest logged routed model in the provisional request envelope', async () => {
  217. const ctx = createContext()
  218. const compact = service({
  219. auto: false,
  220. thresholdRatio: 0.5,
  221. retainTokens: 180,
  222. }, ctx)
  223. const session = conversation(4)
  224. session.append('request/header', {
  225. header: { config: { provider: 'actual', model: 'actual' } },
  226. reason: 'initial',
  227. })
  228. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  229. const result = await compactIfNeeded(compact, session, 'fallback')
  230. expect(result).not.toBeNull()
  231. expect(measure.mock.calls[0]?.[1]?.config.provider).toBe('actual')
  232. expect(measure.mock.calls[0]?.[1]?.config.model).toBe('actual')
  233. })
  234. it('declines when envelope pressure is high but the surface has no compactable range', async () => {
  235. const compact = service(compactConfig)
  236. const empty = new Session(SessionId('empty'))
  237. expect(await compactIfNeeded(compact, empty, MODEL, 'x'.repeat(100_000))).toBeNull()
  238. const retained = conversation(1)
  239. expect(await compactIfNeeded(compact, retained, MODEL, 'x'.repeat(100_000))).toBeNull()
  240. })
  241. it('uses one unified measurement for each pressure-and-retention decision', async () => {
  242. const ctx = createContext()
  243. const compact = service(compactConfig, ctx)
  244. const measure = vi.spyOn(ctx.tokenMeter, 'measure')
  245. const stop = new Error('stop after first decision')
  246. vi.spyOn(compact, 'compactRegion').mockRejectedValueOnce(stop)
  247. await expect(compactIfNeeded(compact, conversation(4))).rejects.toBe(stop)
  248. expect(measure).toHaveBeenCalledTimes(1)
  249. })
  250. it('bounds retries when a shrinking checkpoint remains above threshold', async () => {
  251. const compact = service({
  252. auto: false,
  253. compactionRetries: 0,
  254. thresholdRatio: 0.3,
  255. retainTokens: 180,
  256. })
  257. compact.summary = Array.from({ length: 7 }, (_, index) => ({
  258. type: 'text',
  259. text: `summary ${index}`,
  260. }))
  261. await expect(compactIfNeeded(compact, conversation(4)))
  262. .rejects.toThrow(/still above threshold after 1 compaction attempts/)
  263. })
  264. it('rounds a retention cut head-ward to preserve tool-call/result pairing', async () => {
  265. const compact = service({
  266. auto: false,
  267. thresholdRatio: 0.8,
  268. retainTokens: 80,
  269. }, createContext(4_000))
  270. const session = toolConversation()
  271. const result = await compactIfNeeded(compact, session)
  272. expect(result).not.toBeNull()
  273. const messages = session.deriveMessages()
  274. const calls = new Set<string>()
  275. for (const message of messages) {
  276. for (const block of message.content) {
  277. if (block.type === 'tool-call') calls.add(block.id)
  278. if (block.type === 'tool-result') expect(calls.has(block.toolCallId)).toBe(true)
  279. }
  280. }
  281. })
  282. it('rejects a priced surface that is not the current positional surface', () => {
  283. const ctx = createContext()
  284. const session = conversation(2)
  285. const priced = ctx.tokenMeter.measure(session)
  286. expect(() => selectCompactableRange(session, {
  287. ...priced,
  288. nodes: priced.nodes.slice(1),
  289. }, 1)).toThrow(/does not match/)
  290. })
  291. it('declines when rounding a cut would consume the only tool pair', () => {
  292. const ctx = createContext()
  293. const session = new Session(SessionId('one-tool-pair'))
  294. const callId = CallId('only')
  295. session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  296. session.append('step/start', { turn: 1, step: 1 })
  297. session.append('assistant/message', {
  298. provenance: { provider: MODEL, model: MODEL },
  299. turn: 1,
  300. step: 1,
  301. content: [{ type: 'tool-call', id: callId, name: 'read', arguments: '{}' }],
  302. }, { surfaceOp: 'append' })
  303. session.append('tool/call', { turn: 1, step: 1, callId, name: 'read', arguments: '{}' })
  304. session.append('tool/result', {
  305. turn: 1,
  306. step: 1,
  307. callId,
  308. content: [{ type: 'text', text: 'result' }],
  309. isError: false,
  310. }, { surfaceOp: 'append' })
  311. session.append('step/end', { turn: 1, step: 1 })
  312. const priced = ctx.tokenMeter.measure(session)
  313. expect(selectCompactableRange(session, priced, 1)).toBeNull()
  314. })
  315. })
  316. describe('compaction region transaction', () => {
  317. it('lands a framed, replayable checkpoint with exact pricing provenance', async () => {
  318. const compact = service()
  319. const session = conversation(3)
  320. const before = [...session.surface.nodes]
  321. const result = await compact.compactRegion(
  322. before[0]!,
  323. before[3]!,
  324. agent(session, MODEL),
  325. SIGNAL,
  326. )
  327. expect(result.shadowedSeqs).toEqual(before.slice(0, 4))
  328. expect(result.shadowedTokenCount).toBeGreaterThan(0)
  329. expect(compact.calls[0]).toMatchObject({ signal: SIGNAL })
  330. expect(compact.calls[0]?.text).toContain('fixture user 1')
  331. const summary = session.events.findLast(event => event.type === 'compact/summary')
  332. expect(summary?.data).toMatchObject({
  333. shadowedSeqs: result.shadowedSeqs,
  334. shadowedTokenCount: result.shadowedTokenCount,
  335. provider: 'summary-provider',
  336. model: 'summary-model',
  337. maxTokens: 123,
  338. })
  339. const head = session.deriveMessages()[0]!
  340. expect(head.content[0]?.type).toBe('text')
  341. expect(head.content[0]?.type === 'text' ? head.content[0].text : '').toContain('<compacted-summary>')
  342. expect(head.content.at(-1)).toEqual({ type: 'text', text: '</compacted-summary>' })
  343. const replay = new Session(SessionId('replay'), [...session.events])
  344. expect(replay.deriveMessages()).toEqual(session.deriveMessages())
  345. })
  346. it.each([
  347. ['start missing', 9_001, undefined, /start seq 9001 not found/],
  348. ['end missing', undefined, 9_002, /end seq 9002 not found/],
  349. ])('rejects %s', async (_label, startOverride, endOverride, pattern) => {
  350. const compact = service()
  351. const session = conversation(2)
  352. const nodes = session.surface.nodes
  353. await expect(compact.compactRegion(
  354. startOverride ?? nodes[0]!,
  355. endOverride ?? nodes[1]!,
  356. agent(session, MODEL),
  357. )).rejects.toThrow(pattern)
  358. })
  359. it('rejects reversed and tool-unbalanced positional boundaries', async () => {
  360. const compact = service()
  361. const plain = conversation(2)
  362. const nodes = plain.surface.nodes
  363. await expect(compact.compactRegion(
  364. nodes[2]!,
  365. nodes[1]!,
  366. agent(plain, MODEL),
  367. )).rejects.toThrow(/is after end/)
  368. const tools = toolConversation()
  369. const toolNodes = tools.surface.nodes
  370. await expect(compact.compactRegion(
  371. toolNodes[2]!,
  372. toolNodes[4]!,
  373. agent(tools, MODEL),
  374. )).rejects.toThrow(/start seq .* not a balanced boundary/)
  375. await expect(compact.compactRegion(
  376. toolNodes[0]!,
  377. toolNodes[1]!,
  378. agent(tools, MODEL),
  379. )).rejects.toThrow(/end seq .* not a balanced boundary/)
  380. })
  381. it('requires an open turn and an idle compaction bracket', async () => {
  382. const compact = service()
  383. const closed = conversation(1)
  384. closed.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
  385. const nodes = closed.surface.nodes
  386. await expect(compact.compactRegion(
  387. nodes[0]!,
  388. nodes[1]!,
  389. agent(closed, MODEL),
  390. )).rejects.toThrow(/no open turn/)
  391. const locked = conversation(1)
  392. locked.append('compact/start', { turn: 2 })
  393. const lockedNodes = locked.surface.nodes
  394. await expect(compact.compactRegion(
  395. lockedNodes[0]!,
  396. lockedNodes[1]!,
  397. agent(locked, MODEL),
  398. )).rejects.toThrow(/already in progress/)
  399. })
  400. it('rejects a session with no turn boundary at all', async () => {
  401. const compact = service()
  402. const session = new Session(SessionId('turnless'))
  403. session.append('user/message', {
  404. content: [{ type: 'text', text: 'orphan' }],
  405. source: { kind: 'user' },
  406. }, { surfaceOp: 'append' })
  407. const node = session.surface.nodes[0]!
  408. await expect(compact.compactRegion(
  409. node,
  410. node,
  411. agent(session, MODEL),
  412. )).rejects.toThrow(/no open turn/)
  413. })
  414. it('rejects a meter snapshot that changed before summarization began', async () => {
  415. const ctx = createContext()
  416. const meter = ctx.tokenMeter
  417. const original = meter.measure.bind(meter)
  418. vi.spyOn(meter, 'measure').mockImplementationOnce((session) => {
  419. const measurement = original(session)
  420. return { ...measurement, nodes: measurement.nodes.slice(1) }
  421. })
  422. const compact = service({ auto: false }, ctx)
  423. const session = conversation(2)
  424. const nodes = session.surface.nodes
  425. await expect(compact.compactRegion(
  426. nodes[0]!,
  427. nodes[2]!,
  428. agent(session, MODEL),
  429. )).rejects.toThrow(/selected surface changed/)
  430. })
  431. it('records summarizer failures without mutating the surface', async () => {
  432. const compact = service()
  433. compact.error = new Error('summary unavailable')
  434. const session = conversation(2)
  435. const before = session.surface.nodes
  436. await expect(compact.compactRegion(
  437. before[0]!,
  438. before[2]!,
  439. agent(session, MODEL),
  440. )).rejects.toThrow('summary unavailable')
  441. expect(session.surface.nodes).toEqual(before)
  442. expect(session.events.findLast(event => event.type === 'compact/end')?.data)
  443. .toMatchObject({ error: 'summary unavailable' })
  444. })
  445. it('stringifies non-Error failures in the durable end bracket', async () => {
  446. const compact = service()
  447. compact.error = 'plain failure'
  448. const session = conversation(2)
  449. const nodes = session.surface.nodes
  450. await expect(compact.compactRegion(
  451. nodes[0]!,
  452. nodes[2]!,
  453. agent(session, MODEL),
  454. )).rejects.toBe('plain failure')
  455. expect(session.events.findLast(event => event.type === 'compact/end')?.data)
  456. .toMatchObject({ error: 'plain failure' })
  457. })
  458. it('rejects concurrent durable appends before committing the replacement', async () => {
  459. const compact = service()
  460. const session = conversation(2)
  461. compact.mutateDuringSummary = () => {
  462. session.append('request/header', {
  463. header: { config: { provider: MODEL, model: MODEL } },
  464. reason: 'initial',
  465. })
  466. }
  467. const nodes = session.surface.nodes
  468. await expect(compact.compactRegion(
  469. nodes[0]!,
  470. nodes[2]!,
  471. agent(session, MODEL),
  472. )).rejects.toThrow(/session log changed/)
  473. expect(session.events.some(event => event.type === 'compact/summary')).toBe(false)
  474. })
  475. it('rejects a non-shrinking framed summary under the conversation meter', async () => {
  476. const compact = service()
  477. compact.summary = Array.from({ length: 100 }, (_, index) => ({
  478. type: 'text',
  479. text: `verbose ${index}`,
  480. }))
  481. const session = conversation(2)
  482. const nodes = session.surface.nodes
  483. await expect(compact.compactRegion(
  484. nodes[0]!,
  485. nodes[2]!,
  486. agent(session, MODEL),
  487. )).rejects.toThrow(/summary is not smaller/)
  488. expect(session.events.some(event => event.type === 'compact/summary')).toBe(false)
  489. })
  490. it('lets a model-independent custom summarizer compact without a conversation model', async () => {
  491. const compact = service()
  492. const session = conversation(1)
  493. const nodes = session.surface.nodes
  494. await expect(compact.compactRegion(
  495. nodes[0]!,
  496. nodes[1]!,
  497. agent(session),
  498. )).resolves.toMatchObject({ shadowedSeqs: [nodes[0]!, nodes[1]!] })
  499. })
  500. })
  501. class ScriptedAdapter extends LlmAdapter {
  502. lastOptions: GenerateOptions | undefined
  503. constructor(
  504. private readonly blocks: readonly ContentBlock[],
  505. private readonly finish: (StreamChunk & { type: 'finish' })['reason'] = { kind: 'stop' },
  506. ) {
  507. super()
  508. }
  509. override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
  510. this.lastOptions = options
  511. for (const [index, block] of this.blocks.entries()) {
  512. yield { type: 'block-start', index, blockType: block.type }
  513. if (block.type === 'text') {
  514. yield { type: 'text-delta', index, text: block.text }
  515. } else if (block.type === 'reasoning') {
  516. yield { type: 'reasoning-delta', index, text: block.text }
  517. } else {
  518. yield { type: 'block-end', index, block }
  519. }
  520. }
  521. yield { type: 'finish', reason: this.finish }
  522. }
  523. }
  524. class ExposedCompactService extends BasicCompactService {
  525. runSummarize(
  526. text: string,
  527. owner: Agent,
  528. signal?: AbortSignal,
  529. ): Promise<{ summary: ContentBlock[]; provider: string; model: string; maxTokens?: number }> {
  530. return this.summarize(text, owner, signal)
  531. }
  532. }
  533. async function summarizerHarness(
  534. blocks: readonly ContentBlock[],
  535. finish?: (StreamChunk & { type: 'finish' })['reason'],
  536. model = MODEL,
  537. config: BasicCompactConfig = { auto: false },
  538. ): Promise<{ ctx: Context; adapter: ScriptedAdapter; compact: ExposedCompactService }> {
  539. const ctx = new Context()
  540. await ctx.plugin(LlmService)
  541. void new TokenMeterService(ctx, { contextWindow: 1_000 })
  542. const adapter = new ScriptedAdapter(blocks, finish)
  543. ctx.llm.registerAdapter([model], adapter)
  544. const compact = new ExposedCompactService(ctx, config)
  545. return { ctx, adapter, compact }
  546. }
  547. describe('default one-shot summarizer', () => {
  548. it('uses configured model/default cap, forwards cancellation, and keeps only safe text', async () => {
  549. const { adapter, compact } = await summarizerHarness([
  550. { type: 'reasoning', text: 'private' },
  551. { type: 'text', text: 'public summary' },
  552. { type: 'tool-call', id: CallId('unexpected'), name: 'x', arguments: '{}' },
  553. ], undefined, MODEL, {
  554. auto: false,
  555. summarizationProvider: MODEL,
  556. summarizationModel: MODEL,
  557. maxTokens: 321,
  558. })
  559. const session = conversation(1)
  560. const output = await compact.runSummarize('transcript', agent(session, 'fallback'), SIGNAL)
  561. expect(output).toEqual({
  562. summary: [{ type: 'text', text: 'public summary' }],
  563. provider: MODEL,
  564. model: MODEL,
  565. maxTokens: 321,
  566. })
  567. expect(adapter.lastOptions).toMatchObject({
  568. provider: MODEL,
  569. model: MODEL,
  570. maxTokens: 321,
  571. signal: SIGNAL,
  572. sessionId: session.id,
  573. })
  574. expect(adapter.lastOptions?.system).toContain('## Primary Request and Intent')
  575. })
  576. it('resolves the latest routed provider/model before the AgentOptions pair', async () => {
  577. const { adapter, compact } = await summarizerHarness([{ type: 'text', text: 'summary' }], undefined, 'routed')
  578. const session = conversation(1)
  579. session.append('request/header', {
  580. header: { config: { provider: 'routed', model: 'routed' } },
  581. reason: 'initial',
  582. })
  583. const output = await compact.runSummarize('history', agent(session, 'fallback'))
  584. expect(output.provider).toBe('routed')
  585. expect(output.model).toBe('routed')
  586. expect(adapter.lastOptions?.provider).toBe('routed')
  587. expect(adapter.lastOptions?.model).toBe('routed')
  588. })
  589. it('fails clearly when no complete summarization target can be resolved', async () => {
  590. const ctx = new Context()
  591. await ctx.plugin(LlmService)
  592. void new TokenMeterService(ctx)
  593. const compact = new ExposedCompactService(ctx, { auto: false })
  594. await expect(compact.runSummarize('history', agent(new Session(SessionId('model-less')))))
  595. .rejects.toThrow(/no provider\/model available for summarization/)
  596. })
  597. it.each([
  598. [{ kind: 'error', message: 'provider failed', code: 'PROVIDER' }, 'PROVIDER', /provider failed/],
  599. [{ kind: 'error', message: 'opaque' }, undefined, /opaque/],
  600. [{ kind: 'aborted' }, 'ABORTED', /aborted/],
  601. [{ kind: 'max-tokens' }, 'MAX_TOKENS', /token cap/],
  602. ] as Array<[(StreamChunk & { type: 'finish' })['reason'], string | undefined, RegExp]>) (
  603. 'rejects terminal finish %#',
  604. async (finish, code, pattern) => {
  605. const { compact } = await summarizerHarness([], finish)
  606. let thrown: unknown
  607. try {
  608. await compact.runSummarize('history', agent(conversation(1), MODEL))
  609. } catch (error: unknown) {
  610. thrown = error
  611. }
  612. expect(thrown).toBeInstanceOf(Error)
  613. expect((thrown as Error).message).toMatch(pattern)
  614. expect((thrown as Error & { code?: string }).code).toBe(code)
  615. },
  616. )
  617. it('rejects empty or reasoning-only successful output', async () => {
  618. const { compact } = await summarizerHarness([{ type: 'reasoning', text: 'private' }])
  619. await expect(compact.runSummarize('history', agent(conversation(1), MODEL)))
  620. .rejects.toThrow(/no text summary content/)
  621. })
  622. })
  623. describe('automatic listener and loader composition', () => {
  624. function preStep(ctx: Context, owner: Agent): Promise<unknown> {
  625. return ctx.serial('agent/pre-step', owner, 1, 1, '', [], SIGNAL)
  626. }
  627. it('compacts above threshold and remains idle below it', async () => {
  628. const ctx = createContext()
  629. const compact = new TestCompactService(ctx, {
  630. thresholdRatio: 0.5,
  631. retainTokens: 180,
  632. })
  633. const pressured = conversation(4)
  634. await preStep(ctx, agent(pressured, MODEL))
  635. expect(pressured.events.some(event => event.type === 'compact/summary')).toBe(true)
  636. const small = conversation(1)
  637. await preStep(ctx, agent(small, MODEL))
  638. expect(small.events.some(event => event.type === 'compact/start')).toBe(false)
  639. expect(compact.calls).toHaveLength(1)
  640. })
  641. it('warns and continues after operational failures, including non-Errors', async () => {
  642. const ctx = createContext()
  643. const warnings: string[] = []
  644. ctx.logger.warn = ((message: string) => void warnings.push(message)) as typeof ctx.logger.warn
  645. const compact = new TestCompactService(ctx, {
  646. thresholdRatio: 0.5,
  647. retainTokens: 180,
  648. })
  649. compact.error = 'temporary failure'
  650. const session = conversation(4)
  651. await expect(preStep(ctx, agent(session, MODEL))).resolves.toBeUndefined()
  652. expect(warnings).toContainEqual(expect.stringContaining('temporary failure'))
  653. expect(session.events.some(event => event.type === 'compact/summary')).toBe(false)
  654. })
  655. it('auto:false installs no listener', async () => {
  656. const ctx = createContext()
  657. void new TestCompactService(ctx, {
  658. auto: false,
  659. thresholdRatio: 0.5,
  660. retainTokens: 180,
  661. })
  662. const session = conversation(4)
  663. await preStep(ctx, agent(session, MODEL))
  664. expect(session.events.some(event => event.type === 'compact/start')).toBe(false)
  665. })
  666. it('loads and disposes the real zero-config service stack', async () => {
  667. const ctx = new Context()
  668. await ctx.plugin(LlmService)
  669. const meterFiber = await ctx.plugin(TokenMeterService)
  670. const compactFiber = await ctx.plugin(BasicCompactService, { auto: false })
  671. expect(ctx.tokenMeter.contextWindow).toBe(128_000)
  672. expect(ctx.get('compact')).toBeInstanceOf(BasicCompactService)
  673. await compactFiber.dispose()
  674. expect(ctx.get('compact')).toBeUndefined()
  675. await meterFiber.dispose()
  676. expect(ctx.get('tokenMeter')).toBeUndefined()
  677. })
  678. it('removes its automatic listener with the plugin fiber', async () => {
  679. const ctx = new Context()
  680. await ctx.plugin(LlmService)
  681. await ctx.plugin(TokenMeterService, { contextWindow: 1_000 })
  682. const fiber = await ctx.plugin(TestCompactService, {
  683. thresholdRatio: 0.5,
  684. retainTokens: 180,
  685. })
  686. await fiber.dispose()
  687. const session = conversation(4)
  688. await preStep(ctx, agent(session, MODEL))
  689. expect(session.events.some(event => event.type === 'compact/start')).toBe(false)
  690. })
  691. })