/** * plugins/workflow-runner/test/apiResourceLedger.test.ts —— 资源账本与重放安全 * * 守两件事: * 1. 每次 `agent()` / `llm()` 的用量真的记进 `ctx.resourceLedger`(预算闸的刻度)。 * 2. **断点续跑重放时不重复记账** —— 这是最容易写错、也最难发现的一条: * 记账代码若挪到 `journaled()` 回调外面,每 resume 一次就把历史用量再加一遍, * 跑几次之后预算凭空耗尽,而现场看起来一切正常。 * * 用 DI 注入 chat stub(本仓库纪律:不用 mock.module,它会全局泄漏)。 */ import { afterEach, describe, expect, test } from 'bun:test'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { LoopEvent } from '../../../src/plugin-sdk.js'; import { createWorkflowContext } from '../src/runtime/context.js'; import { Journal } from '../src/journal.js'; import type { RunContext } from '../src/types.js'; import { WorkflowState } from '../src/workflowState.js'; const dirs: string[] = []; afterEach(() => { for (const d of dirs.splice(0)) { try { rmSync(d, { recursive: true, force: true, maxRetries: 3 }); } catch { /* Windows 偶发 EBUSY */ } } }); /** 每次调用都回报固定用量的 chat stub。 */ function chatReporting(inputTokens: number, outputTokens: number) { return async function* () { yield { type: 'text_delta' as const, delta: '做完了' }; yield { type: 'done' as const, stopReason: 'stop' as const, promptTokens: inputTokens, outputTokens }; }; } /** 完全不回报 usage 的 chat stub(很多兼容 provider 就是这样)。 */ function chatSilent() { return async function* () { yield { type: 'text_delta' as const, delta: '做完了' }; yield { type: 'done' as const, stopReason: 'stop' as const }; }; } async function harness(chat: RunContext['chat'], opts: { workDir?: string } = {}) { const wd = opts.workDir ?? mkdtempSync(join(tmpdir(), 'wf-ledger-')); if (!opts.workDir) dirs.push(wd); const state = new WorkflowState(wd, 'demo', 's1'); await state.init({ goal: '账本测试' }, 'hash-v1', []); const journal = new Journal(state.journalPath, { bundleHash: 'test', rootRunId: 'test-root' }); await journal.load(); const events: LoopEvent[] = []; const ctx = { provider: { name: 'test' }, history: [{ role: 'system', content: 'sys' }], cwd: wd, tools: [], chat, } as unknown as RunContext; const globals = createWorkflowContext({ ctx, state, journal, emit: (ev) => events.push(ev), args: {}, workflowName: 'demo', session: 's1', task: state.taskId, }); return { globals, ctx, events, workDir: wd }; } describe('资源账本', () => { test('★ agent() 的用量记进 ctx.resourceLedger', async () => { const h = await harness(chatReporting(500, 60)); await h.globals.model.agent('干点什么'); expect(h.ctx.resourceLedger?.inputTokens).toBe(500); expect(h.ctx.resourceLedger?.outputTokens).toBe(60); expect(h.ctx.resourceLedger?.trustworthy).toBe(true); }); test('★ 多次调用累计', async () => { const h = await harness(chatReporting(100, 10)); await h.globals.model.agent('第一件事'); await h.globals.model.agent('第二件事'); await h.globals.model.generate('顺便总结一下'); expect(h.ctx.resourceLedger?.inputTokens).toBe(300); expect(h.ctx.resourceLedger?.outputTokens).toBe(30); }); test('★ provider 不报 usage → trustworthy 拉黑,而不是假装花了 0', async () => { const h = await harness(chatSilent()); await h.globals.model.agent('干点什么'); // 记 0 是事实(不知道),但必须让消费方知道这份账偏低 —— // 否则预算闸会拿着一份永远为 0 的账本一路放行。 expect(h.ctx.resourceLedger?.trustworthy).toBe(false); }); test('★★ 重放不重复记账 —— 记账必须待在 journaled 回调内部', async () => { // 第一次跑:真实执行,写账本 + 记用量。 const first = await harness(chatReporting(1_000, 100)); await first.globals.model.agent('唯一的一次调用'); expect(first.ctx.resourceLedger?.inputTokens).toBe(1_000); // 第二次跑:**同一个工作目录**,账本命中重放。 // journal.step 命中时直接 return prev.result,根本不调 run() —— // 所以只要记账在回调内部,重放就天然不会重复计。 const second = await harness(chatReporting(1_000, 100), { workDir: first.workDir }); await second.globals.model.agent('唯一的一次调用'); // 重放这一次没有真的发请求,也就不该记账。 // 若把 recordCallUsage 挪到 journaled 外面,这里会变成 1_000(重复计一遍)。 expect(second.ctx.resourceLedger?.inputTokens ?? 0).toBe(0); }); test('重放之后新增的调用照常记账 —— 不能因为重放过就整体哑火', async () => { const first = await harness(chatReporting(200, 20)); await first.globals.model.agent('第一步'); const second = await harness(chatReporting(200, 20), { workDir: first.workDir }); await second.globals.model.agent('第一步'); // 命中重放,不记 await second.globals.model.agent('第二步'); // 新调用,真跑,要记 expect(second.ctx.resourceLedger?.inputTokens).toBe(200); }); }); /** * ── 预算闸的语义边界(用户决策的硬约束)─────────────────────────────── * * 产品决策原话:「一轮对话一旦开始,过程中即使到额度了只要 TAOR 循环不结束 * 也不停止不检查预算…比起严格限制预算,我更重视让 agent 把一次对话完成不打断, * 至少做完到一个节点。」 * * 所以这里既要证明 `budget()` 能报数,也要**反证**它不会打断执行 —— * 后者是容易在后续重构中被「顺手加个检查」破坏的那一半。 */ describe('budget() 的语义边界', () => { test('没设上限时 remaining 是 Infinity、exhausted 为 false', async () => { const h = await harness(chatReporting(10_000, 1_000)); await h.globals.model.agent('花点钱'); const b = (await h.globals.state.budget()) as Record; // ⚠️ 用 0 表示「无限」会让没设预算的运行被判成「一开始就超了」,一轮都跑不了。 expect(b.limit).toBeNull(); expect(b.remaining).toBe(Number.POSITIVE_INFINITY); expect(b.exhausted).toBe(false); expect(b.used).toBe(11_000); }); test('★ 反证:超预算**不会**中断进行中的 TAOR 循环', async () => { // 造一个「一轮里连调两次」的场景。即使第一次就把预算花超, // 第二次调用照样必须完成 —— 引擎内核不做任何预算检查, // 停不停由脚本在**下一轮开头**自己决定。 const h = await harness(chatReporting(1_000_000, 1_000_000)); h.ctx.resourceLedger = { inputTokens: 0, outputTokens: 0, limit: 1, trustworthy: true, }; await h.globals.model.agent('第一次调用,一次就爆预算'); const mid = (await h.globals.state.budget()) as Record; expect(mid.exhausted).toBe(true); // 关键断言:已经 exhausted 了,agent() 仍然正常执行并返回,不抛不挂。 const out = await h.globals.model.agent('第二次调用,预算已爆但必须跑完'); expect(typeof out).toBe('string'); expect(out).toContain('做完了'); }); test('trustworthy 会跟着账本一起透出,供脚本如实告知用户', async () => { const h = await harness(chatSilent()); await h.globals.model.agent('provider 不报 usage'); const b = (await h.globals.state.budget()) as Record; expect(b.trustworthy).toBe(false); }); });