@crewhaus/runtime-core 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,207 +0,0 @@
1
- /**
2
- * Unit tests for the CLI markdown → ANSI streaming renderer.
3
- * Covers: streaming buffer + flush, headings, lists, code fences,
4
- * inline bold/italic/code, blockquotes, and graceful handling of
5
- * tokens split across chunks.
6
- */
7
- import { describe, expect, spyOn, test } from "bun:test";
8
- import { createCliMarkdownRenderer, isCliMarkdownEnabled } from "./cli-markdown";
9
-
10
- function capture(): { write: (s: string) => void; out: () => string } {
11
- let buf = "";
12
- return {
13
- write: (s: string) => {
14
- buf += s;
15
- },
16
- out: () => buf,
17
- };
18
- }
19
-
20
- // Strip ANSI escape sequences so we can assert on plain content
21
- // while still letting other tests verify the escape codes are present.
22
- function strip(s: string): string {
23
- // biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape detection is intentional — the renderer's output IS the control sequences we want to strip.
24
- return s.replace(/\x1b\[[0-9;]*m/g, "");
25
- }
26
-
27
- describe("createCliMarkdownRenderer", () => {
28
- test("plain text passes through line by line", () => {
29
- const c = capture();
30
- const r = createCliMarkdownRenderer({ write: c.write });
31
- r.push("hello\nworld\n");
32
- expect(c.out()).toBe("hello\nworld\n");
33
- });
34
-
35
- test("incomplete line is buffered, flushed by end()", () => {
36
- const c = capture();
37
- const r = createCliMarkdownRenderer({ write: c.write });
38
- r.push("partial");
39
- expect(c.out()).toBe("");
40
- r.end();
41
- expect(c.out()).toBe("partial");
42
- });
43
-
44
- test("bold renders with ANSI bold", () => {
45
- const c = capture();
46
- const r = createCliMarkdownRenderer({ write: c.write });
47
- r.push("hello **world** done\n");
48
- expect(c.out()).toContain("\x1b[1m");
49
- expect(strip(c.out())).toBe("hello world done\n");
50
- });
51
-
52
- test("italic with single asterisks", () => {
53
- const c = capture();
54
- const r = createCliMarkdownRenderer({ write: c.write });
55
- r.push("the *quick* fox\n");
56
- expect(c.out()).toContain("\x1b[3m");
57
- expect(strip(c.out())).toBe("the quick fox\n");
58
- });
59
-
60
- test("inline code preserves backticks", () => {
61
- const c = capture();
62
- const r = createCliMarkdownRenderer({ write: c.write });
63
- r.push("use `npm install` here\n");
64
- expect(strip(c.out())).toBe("use `npm install` here\n");
65
- });
66
-
67
- test("headings get bold + level color", () => {
68
- const c = capture();
69
- const r = createCliMarkdownRenderer({ write: c.write });
70
- r.push("# H1\n## H2\n### H3\n");
71
- expect(c.out().split("\n").length).toBe(4);
72
- // Each header line starts with a bold marker.
73
- const lines = c.out().split("\n");
74
- expect(lines[0]).toContain("\x1b[1m");
75
- expect(lines[1]).toContain("\x1b[1m");
76
- expect(lines[2]).toContain("\x1b[1m");
77
- expect(strip(c.out())).toBe("H1\nH2\nH3\n");
78
- });
79
-
80
- test("unordered list bullets render with • marker", () => {
81
- const c = capture();
82
- const r = createCliMarkdownRenderer({ write: c.write });
83
- r.push("- one\n- two\n* three\n");
84
- const stripped = strip(c.out());
85
- expect(stripped).toContain("• one");
86
- expect(stripped).toContain("• two");
87
- expect(stripped).toContain("• three");
88
- });
89
-
90
- test("ordered list numbers survive with color", () => {
91
- const c = capture();
92
- const r = createCliMarkdownRenderer({ write: c.write });
93
- r.push("1. first\n2. second\n");
94
- const stripped = strip(c.out());
95
- expect(stripped).toContain("1. first");
96
- expect(stripped).toContain("2. second");
97
- });
98
-
99
- test("code fence toggles dim block, multi-line", () => {
100
- const c = capture();
101
- const r = createCliMarkdownRenderer({ write: c.write });
102
- r.push("```python\nprint('hi')\nx = 1\n```\nback to text\n");
103
- const stripped = strip(c.out());
104
- expect(stripped).toContain("```python");
105
- expect(stripped).toContain("print('hi')");
106
- expect(stripped).toContain("x = 1");
107
- expect(stripped).toContain("```");
108
- expect(stripped).toContain("back to text");
109
- // Dim marker should appear in the code-block lines.
110
- expect(c.out()).toContain("\x1b[2m");
111
- });
112
-
113
- test("chunk-boundary safety: bold marker split across pushes", () => {
114
- const c = capture();
115
- const r = createCliMarkdownRenderer({ write: c.write });
116
- r.push("hello *");
117
- r.push("*world*");
118
- r.push("* done\n");
119
- expect(strip(c.out())).toBe("hello world done\n");
120
- expect(c.out()).toContain("\x1b[1m");
121
- });
122
-
123
- test("blockquote renders with vertical-bar prefix and italic", () => {
124
- const c = capture();
125
- const r = createCliMarkdownRenderer({ write: c.write });
126
- r.push("> a quote here\n");
127
- expect(strip(c.out())).toContain("│ a quote here");
128
- expect(c.out()).toContain("\x1b[3m");
129
- });
130
-
131
- test("horizontal rule renders as a divider", () => {
132
- const c = capture();
133
- const r = createCliMarkdownRenderer({ write: c.write });
134
- r.push("---\n");
135
- expect(strip(c.out())).toMatch(/^─{40}/);
136
- });
137
-
138
- test("underscore bold (__x__) and underscore italic (_x_) render", () => {
139
- const c = capture();
140
- const r = createCliMarkdownRenderer({ write: c.write });
141
- // __bold__ exercises the __...__ replace callback; a closed _italic_ pair
142
- // (word-boundary guarded) exercises the _..._ replace callback. Both are
143
- // distinct from the asterisk variants the other tests cover.
144
- r.push("make __this__ and _that_ pop\n");
145
- expect(strip(c.out())).toBe("make this and that pop\n");
146
- expect(c.out()).toContain("\x1b[1m"); // bold from __this__
147
- expect(c.out()).toContain("\x1b[3m"); // italic from _that_
148
- });
149
-
150
- test("does not false-match snake_case identifiers as italic", () => {
151
- const c = capture();
152
- const r = createCliMarkdownRenderer({ write: c.write });
153
- r.push("call foo_bar_baz now\n");
154
- expect(strip(c.out())).toBe("call foo_bar_baz now\n");
155
- // No italic markers because _foo_bar_baz_ isn't a closed pair.
156
- expect(c.out()).not.toContain("\x1b[3m");
157
- });
158
-
159
- test("nested code-fence inside list-item not double-rendered", () => {
160
- const c = capture();
161
- const r = createCliMarkdownRenderer({ write: c.write });
162
- r.push("- item one\n ```\n code\n ```\n- item two\n");
163
- const stripped = strip(c.out());
164
- expect(stripped).toContain("• item one");
165
- expect(stripped).toContain("code");
166
- expect(stripped).toContain("• item two");
167
- });
168
-
169
- test("defaults to process.stdout.write when no write override is supplied", () => {
170
- // Exercises the default sink arrow `(s) => process.stdout.write(s)` that
171
- // every other test bypasses by passing an explicit `write`. We spy on
172
- // stdout so nothing actually prints to the test console.
173
- const written: string[] = [];
174
- const spy = spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
175
- written.push(String(chunk));
176
- return true;
177
- }) as typeof process.stdout.write);
178
- try {
179
- const r = createCliMarkdownRenderer(); // no opts → default write
180
- r.push("plain line\n"); // flushes a completed line via the default sink
181
- r.push("tail-no-newline");
182
- r.end(); // flushes the buffered tail via the default sink
183
- } finally {
184
- spy.mockRestore();
185
- }
186
- const joined = strip(written.join(""));
187
- expect(joined).toContain("plain line");
188
- expect(joined).toContain("tail-no-newline");
189
- });
190
- });
191
-
192
- describe("isCliMarkdownEnabled", () => {
193
- test("returns false when env var is unset", () => {
194
- expect(isCliMarkdownEnabled({})).toBe(false);
195
- });
196
-
197
- test("returns true for '1' and 'true' (case sensitive)", () => {
198
- expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "1" })).toBe(true);
199
- expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "true" })).toBe(true);
200
- });
201
-
202
- test("returns false for falsy strings", () => {
203
- expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "0" })).toBe(false);
204
- expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "false" })).toBe(false);
205
- expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "" })).toBe(false);
206
- });
207
- });
@@ -1,190 +0,0 @@
1
- /**
2
- * Streaming markdown → ANSI renderer for CLI target stdout output.
3
- *
4
- * Activated when `CREWHAUS_CLI_MARKDOWN=1` is set. Wraps the model's
5
- * text-delta stream so the user sees rendered markdown (bold, italic,
6
- * headers, lists, code fences, inline code) instead of raw asterisks.
7
- *
8
- * Design notes:
9
- * - **Line-buffered**: chunks accumulate until a `\n` arrives, then the
10
- * full line renders and flushes. Trades per-character streaming feel
11
- * for stable rendering — the model can split a `**` marker across
12
- * chunks, so per-character pass-through would emit half-tokens.
13
- * - **Stateful**: tracks code-fence state across lines so multi-line
14
- * ```code blocks``` render as a unit (dim color, optional language tag).
15
- * - **Zero deps**: pure ANSI escape codes; works in any terminal that
16
- * supports VT100 (essentially every terminal in active use).
17
- *
18
- * Limitations (acceptable for v1; document in demo READMEs):
19
- * - Per-line buffering means responses appear in line chunks, not
20
- * character-by-character. For most chat responses (< 20 lines) this
21
- * is imperceptible. Long generations may feel slightly chunked.
22
- * - Nested markup (e.g. `**bold *italic*?**`) renders the outermost
23
- * correctly; nested handling is best-effort.
24
- * - No table rendering, no image alt rendering, no link highlighting
25
- * (links pass through as plain text — terminals already
26
- * auto-linkify URLs).
27
- */
28
-
29
- const RESET = "\x1b[0m";
30
- const BOLD = "\x1b[1m";
31
- const DIM = "\x1b[2m";
32
- const ITALIC = "\x1b[3m";
33
- const CYAN = "\x1b[36m";
34
- const MAGENTA = "\x1b[35m";
35
- const YELLOW = "\x1b[33m";
36
- const GREEN = "\x1b[32m";
37
-
38
- /** Heading levels 1..6 → color + bold. Level 0 is "no heading". */
39
- const HEADING_COLORS: readonly string[] = [
40
- "",
41
- `${BOLD}${CYAN}`, // h1
42
- `${BOLD}${MAGENTA}`, // h2
43
- `${BOLD}${YELLOW}`, // h3
44
- BOLD, // h4
45
- BOLD, // h5
46
- BOLD, // h6
47
- ];
48
-
49
- export interface StreamRenderer {
50
- /** Push an incoming text chunk. Renders + flushes completed lines. */
51
- push(chunk: string): void;
52
- /** Flush any remaining buffered content (no newline appended). */
53
- end(): void;
54
- }
55
-
56
- export interface RendererOptions {
57
- /** Override the output sink. Defaults to `process.stdout.write`. */
58
- readonly write?: (s: string) => void;
59
- }
60
-
61
- /**
62
- * Construct a streaming markdown renderer. Returns a `StreamRenderer` with
63
- * `push(chunk)` and `end()` methods.
64
- *
65
- * Usage:
66
- * ```ts
67
- * const r = createCliMarkdownRenderer();
68
- * r.push("hello **world**\n");
69
- * r.push("`code` ");
70
- * r.push("done\n");
71
- * r.end();
72
- * ```
73
- */
74
- export function createCliMarkdownRenderer(opts: RendererOptions = {}): StreamRenderer {
75
- const write = opts.write ?? ((s: string) => process.stdout.write(s));
76
- let buf = "";
77
- let inCodeFence = false;
78
- let codeFenceLang = "";
79
-
80
- function flushLine(line: string): void {
81
- write(`${renderLine(line)}\n`);
82
- }
83
-
84
- function renderLine(line: string): string {
85
- // Code-fence delimiter — toggles state, dims the fence itself.
86
- const fence = /^(\s*)```\s*(\S*)\s*$/.exec(line);
87
- if (fence) {
88
- if (!inCodeFence) {
89
- inCodeFence = true;
90
- codeFenceLang = fence[2] ?? "";
91
- return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${codeFenceLang}${RESET}`;
92
- }
93
- inCodeFence = false;
94
- const langSuffix = codeFenceLang ? ` (${codeFenceLang})` : "";
95
- codeFenceLang = "";
96
- return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${langSuffix}${RESET}`;
97
- }
98
- if (inCodeFence) {
99
- // Inside a fenced block — dim everything; preserve indentation.
100
- return `${DIM}${line}${RESET}`;
101
- }
102
- // Headings
103
- const heading = /^(\s*)(#{1,6})\s+(.*)$/.exec(line);
104
- if (heading) {
105
- const indent = heading[1] ?? "";
106
- const level = (heading[2] ?? "").length;
107
- const text = heading[3] ?? "";
108
- const color = HEADING_COLORS[level] ?? BOLD;
109
- return `${indent}${color}${renderInline(text)}${RESET}`;
110
- }
111
- // Unordered list bullets — replace marker with a pretty bullet.
112
- const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
113
- if (bullet) {
114
- return `${bullet[1] ?? ""}${CYAN}•${RESET} ${renderInline(bullet[2] ?? "")}`;
115
- }
116
- // Ordered list — keep the number, color it.
117
- const numbered = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
118
- if (numbered) {
119
- return `${numbered[1] ?? ""}${CYAN}${numbered[2]}.${RESET} ${renderInline(numbered[3] ?? "")}`;
120
- }
121
- // Blockquote
122
- const quote = /^(\s*)>\s?(.*)$/.exec(line);
123
- if (quote) {
124
- return `${quote[1] ?? ""}${DIM}│${RESET} ${ITALIC}${renderInline(quote[2] ?? "")}${RESET}`;
125
- }
126
- // Horizontal rule
127
- if (/^\s*(-{3,}|_{3,}|\*{3,})\s*$/.test(line)) {
128
- return `${DIM}${"─".repeat(40)}${RESET}`;
129
- }
130
- return renderInline(line);
131
- }
132
-
133
- function renderInline(text: string): string {
134
- // Backtick-quoted inline code first (so its content isn't bold/italic-mangled).
135
- // We do a placeholder-swap pass: extract code spans, then re-insert after styling.
136
- const codeSpans: string[] = [];
137
- let working = text.replace(/`([^`]+?)`/g, (_match, content) => {
138
- codeSpans.push(content as string);
139
- return ` CODE${codeSpans.length - 1} `;
140
- });
141
- // Bold: **text** or __text__ — non-greedy, doesn't span newlines.
142
- working = working.replace(/\*\*([^*\n]+?)\*\*/g, (_m, t) => `${BOLD}${t}${RESET}`);
143
- working = working.replace(/__([^_\n]+?)__/g, (_m, t) => `${BOLD}${t}${RESET}`);
144
- // Italic: *text* or _text_ — guarded by word-boundary lookarounds so
145
- // list bullets ("- foo") and snake_case identifiers don't false-match.
146
- working = working.replace(
147
- /(^|[^*\w])\*([^*\n]+?)\*(?!\w)/g,
148
- (_m, p, t) => `${p}${ITALIC}${t}${RESET}`,
149
- );
150
- working = working.replace(
151
- /(^|[^_\w])_([^_\n]+?)_(?!\w)/g,
152
- (_m, p, t) => `${p}${ITALIC}${t}${RESET}`,
153
- );
154
- // Restore inline code spans with styling.
155
- working = working.replace(/ CODE(\d+) /g, (_m, idx) => {
156
- const content = codeSpans[Number(idx)] ?? "";
157
- return `${DIM}${CYAN}\`${content}\`${RESET}`;
158
- });
159
- return working;
160
- }
161
-
162
- return {
163
- push(chunk: string): void {
164
- buf += chunk;
165
- let nl = buf.indexOf("\n");
166
- while (nl !== -1) {
167
- const line = buf.slice(0, nl);
168
- buf = buf.slice(nl + 1);
169
- flushLine(line);
170
- nl = buf.indexOf("\n");
171
- }
172
- },
173
- end(): void {
174
- if (buf.length > 0) {
175
- // Tail content with no terminating newline — render in place.
176
- write(renderLine(buf));
177
- buf = "";
178
- }
179
- },
180
- };
181
- }
182
-
183
- /**
184
- * Decide whether to activate the CLI markdown renderer based on env.
185
- * Centralized so callers don't repeat the parse.
186
- */
187
- export function isCliMarkdownEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
188
- const v = env["CREWHAUS_CLI_MARKDOWN"];
189
- return v === "1" || v === "true";
190
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * Unit tests for `formatCostInlineLine` — the CLI-target cost ribbon
3
- * emitted when `CREWHAUS_COST_INLINE=1` and `CREWHAUS_COST_TRACKING=1`
4
- * are both set. The integration path is exercised by the T3 trace-event
5
- * test in observability.test.ts.
6
- */
7
- import { describe, expect, test } from "bun:test";
8
- import type { CostAccrualEvent } from "@crewhaus/trace-event-bus";
9
- import { formatCostInlineLine } from "./observability";
10
-
11
- function makeEvent(overrides: Partial<CostAccrualEvent> = {}): CostAccrualEvent {
12
- return {
13
- kind: "cost_accrual",
14
- traceId: "trace_a",
15
- runId: "run_a",
16
- sessionId: "sess_0000000000000001",
17
- timestamp: 0,
18
- provider: "anthropic",
19
- modelId: "claude-sonnet-4-6",
20
- inputTokens: 12_345,
21
- outputTokens: 678,
22
- cachedReadTokens: 0,
23
- costUsdMicros: 4_200, // $0.0042
24
- ...overrides,
25
- } as CostAccrualEvent;
26
- }
27
-
28
- describe("formatCostInlineLine", () => {
29
- test("renders the dollar amount with 4-digit precision", () => {
30
- expect(formatCostInlineLine(makeEvent({ costUsdMicros: 4_200 }))).toContain("$0.0042");
31
- expect(formatCostInlineLine(makeEvent({ costUsdMicros: 1_500_000 }))).toContain("$1.5000");
32
- expect(formatCostInlineLine(makeEvent({ costUsdMicros: 0 }))).toContain("$0.0000");
33
- });
34
-
35
- test("formats token counts above 1k with one decimal place", () => {
36
- const line = formatCostInlineLine(makeEvent({ inputTokens: 12_345, outputTokens: 678 }));
37
- expect(line).toContain("12.3k in");
38
- expect(line).toContain("678 out"); // below 1k stays raw
39
- });
40
-
41
- test("includes the model id for visibility on model swaps", () => {
42
- const claudeLine = formatCostInlineLine(makeEvent({ modelId: "claude-opus-4-7" }));
43
- expect(claudeLine).toContain("model=claude-opus-4-7");
44
-
45
- const gptLine = formatCostInlineLine(makeEvent({ modelId: "gpt-4o-2024-11-20" }));
46
- expect(gptLine).toContain("model=gpt-4o-2024-11-20");
47
- });
48
-
49
- test("output is a single line (no embedded newlines)", () => {
50
- const line = formatCostInlineLine(makeEvent());
51
- expect(line).not.toContain("\n");
52
- });
53
-
54
- test("starts with the dollar emoji marker so users can grep for it", () => {
55
- const line = formatCostInlineLine(makeEvent());
56
- expect(line.startsWith("[💸 ")).toBe(true);
57
- });
58
- });
@@ -1,113 +0,0 @@
1
- /**
2
- * Section 27 — cost_accrual persistence into the session JSONL.
3
- *
4
- * When CREWHAUS_COST_TRACKING is on, the runtime mirrors each per-call
5
- * cost_accrual the trace bus carries into the session event-log so
6
- * `crewhaus cost-summary --session <id>` can sum spend after the run. These
7
- * tests drive the real `runChatLoop` (stub adapter) and assert the JSONL
8
- * envelope shape and the env-gating.
9
- */
10
- import { afterEach, beforeEach, describe, expect, test } from "bun:test";
11
- import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
12
- import { tmpdir } from "node:os";
13
- import { join } from "node:path";
14
- import type { ProviderAdapter } from "@crewhaus/adapter-anthropic";
15
- import { createRunContext } from "@crewhaus/run-context";
16
- import type { ProviderId } from "@crewhaus/trace-event-bus";
17
- import { runChatLoop } from "./index";
18
-
19
- /** Single text-only turn: 100 input tokens, 10 output tokens. */
20
- function makeTextAdapter(providerId: ProviderId): ProviderAdapter {
21
- return {
22
- providerId,
23
- features: {
24
- caching: "explicit",
25
- tool_use: true,
26
- vision: true,
27
- thinking: false,
28
- web_search: false,
29
- },
30
- estimateTokens: () => 0,
31
- stream: () =>
32
- (async function* () {
33
- yield { kind: "message_start", usage: { input: 100, output: 0 } } as const;
34
- yield {
35
- kind: "content_block_start",
36
- index: 0,
37
- block: { type: "text", text: "" },
38
- } as const;
39
- yield {
40
- kind: "content_block_delta",
41
- index: 0,
42
- delta: { type: "text_delta", text: "ok" },
43
- } as const;
44
- yield { kind: "content_block_stop", index: 0 } as const;
45
- yield {
46
- kind: "message_delta",
47
- stopReason: "end_turn",
48
- usage: { input: 100, output: 10 },
49
- } as const;
50
- yield { kind: "message_stop" } as const;
51
- })(),
52
- };
53
- }
54
-
55
- let sessionRoot: string;
56
- const savedTracking = process.env["CREWHAUS_COST_TRACKING"];
57
-
58
- beforeEach(() => {
59
- sessionRoot = mkdtempSync(join(tmpdir(), "crewhaus-cost-persist-"));
60
- });
61
- afterEach(() => {
62
- rmSync(sessionRoot, { recursive: true, force: true });
63
- process.env["CREWHAUS_COST_TRACKING"] = savedTracking;
64
- });
65
-
66
- async function runOnce(): Promise<void> {
67
- await runChatLoop({
68
- model: "claude-sonnet-4-6",
69
- instructions: "test",
70
- _adapter: makeTextAdapter("anthropic"),
71
- runContext: createRunContext(),
72
- singleTurn: true,
73
- seedMessages: [{ role: "user", content: "hello" }],
74
- sessionRootDir: sessionRoot,
75
- });
76
- }
77
-
78
- type AccrualLine = {
79
- kind: string;
80
- payload?: { provider?: string; modelId?: string; costUsdMicros?: number };
81
- };
82
-
83
- function readCostAccruals(): AccrualLine[] {
84
- const accruals: AccrualLine[] = [];
85
- for (const file of readdirSync(sessionRoot).filter((f) => f.endsWith(".jsonl"))) {
86
- for (const line of readFileSync(join(sessionRoot, file), "utf-8").split("\n")) {
87
- if (line === "") continue;
88
- const ev = JSON.parse(line) as AccrualLine;
89
- if (ev.kind === "cost_accrual") accruals.push(ev);
90
- }
91
- }
92
- return accruals;
93
- }
94
-
95
- describe("cost_accrual persistence into the session JSONL (Section 27)", () => {
96
- test("persists a per-call cost_accrual (envelope shape) when CREWHAUS_COST_TRACKING=1", async () => {
97
- process.env["CREWHAUS_COST_TRACKING"] = "1";
98
- await runOnce();
99
- const accruals = readCostAccruals();
100
- expect(accruals.length).toBe(1);
101
- // event-log wraps the event; cost fields live under `payload`.
102
- expect(accruals[0]?.payload?.provider).toBe("anthropic");
103
- expect(accruals[0]?.payload?.modelId).toBe("claude-sonnet-4-6");
104
- // claude-sonnet-4 row: 100 in × $3/M + 10 out × $15/M = 450 micros.
105
- expect(accruals[0]?.payload?.costUsdMicros).toBe(450);
106
- });
107
-
108
- test("writes no cost_accrual line when cost tracking is disabled", async () => {
109
- process.env["CREWHAUS_COST_TRACKING"] = undefined;
110
- await runOnce();
111
- expect(readCostAccruals().length).toBe(0);
112
- });
113
- });