@crewhaus/runtime-core 0.1.0
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.
- package/package.json +82 -0
- package/src/cli-markdown.test.ts +173 -0
- package/src/cli-markdown.ts +190 -0
- package/src/cost-inline.test.ts +58 -0
- package/src/index.test.ts +1541 -0
- package/src/index.ts +2025 -0
- package/src/observability.test.ts +138 -0
- package/src/observability.ts +116 -0
- package/src/project-memory.test.ts +145 -0
- package/src/project-memory.ts +134 -0
package/package.json
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@crewhaus/runtime-core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Minimal runtime imported by generated harness bundles",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.ts"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "bun test src"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@anthropic-ai/sdk": "^0.96.0",
|
|
16
|
+
"@crewhaus/abort-controller": "0.0.0",
|
|
17
|
+
"@crewhaus/adapter-anthropic": "0.0.0",
|
|
18
|
+
"@crewhaus/agent-context-isolation": "0.0.0",
|
|
19
|
+
"@crewhaus/boundary-classifier": "0.0.0",
|
|
20
|
+
"@crewhaus/circuit-breaker": "0.0.0",
|
|
21
|
+
"@crewhaus/compaction-autocompact": "0.0.0",
|
|
22
|
+
"@crewhaus/compaction-snip": "0.0.0",
|
|
23
|
+
"@crewhaus/cost-tracker": "0.0.0",
|
|
24
|
+
"@crewhaus/egress-classifier": "0.0.0",
|
|
25
|
+
"@crewhaus/errors": "0.0.0",
|
|
26
|
+
"@crewhaus/event-log": "0.0.0",
|
|
27
|
+
"@crewhaus/hooks-engine": "0.0.0",
|
|
28
|
+
"@crewhaus/model-router": "0.0.0",
|
|
29
|
+
"@crewhaus/permission-engine": "0.0.0",
|
|
30
|
+
"@crewhaus/prompt-cache-manager": "0.0.0",
|
|
31
|
+
"@crewhaus/prompt-injection-detector": "0.0.0",
|
|
32
|
+
"@crewhaus/rate-limiter": "0.0.0",
|
|
33
|
+
"@crewhaus/recovery-engine": "0.0.0",
|
|
34
|
+
"@crewhaus/run-context": "0.0.0",
|
|
35
|
+
"@crewhaus/session-store": "0.0.0",
|
|
36
|
+
"@crewhaus/skills-registry": "0.0.0",
|
|
37
|
+
"@crewhaus/slash-commands": "0.0.0",
|
|
38
|
+
"@crewhaus/state-store": "0.0.0",
|
|
39
|
+
"@crewhaus/token-budget": "0.0.0",
|
|
40
|
+
"@crewhaus/tool-catalog": "0.0.0",
|
|
41
|
+
"@crewhaus/tool-executor": "0.0.0",
|
|
42
|
+
"@crewhaus/tool-loop-detection": "0.0.0",
|
|
43
|
+
"@crewhaus/tool-orchestrator": "0.0.0",
|
|
44
|
+
"@crewhaus/tool-result-store": "0.0.0",
|
|
45
|
+
"@crewhaus/streaming-tool-executor": "0.0.0",
|
|
46
|
+
"@crewhaus/turn-state-machine": "0.0.0",
|
|
47
|
+
"@crewhaus/trace-event-bus": "0.0.0",
|
|
48
|
+
"@crewhaus/structured-event-printer": "0.0.0",
|
|
49
|
+
"@crewhaus/metrics-collector": "0.0.0",
|
|
50
|
+
"@crewhaus/otel-exporter": "0.0.0",
|
|
51
|
+
"zod-to-json-schema": "^3.23.5"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@crewhaus/logging": "0.0.0",
|
|
55
|
+
"@crewhaus/tool-builder": "0.0.0",
|
|
56
|
+
"zod": "^3.23.8"
|
|
57
|
+
},
|
|
58
|
+
"license": "Apache-2.0",
|
|
59
|
+
"author": {
|
|
60
|
+
"name": "Max Meier",
|
|
61
|
+
"email": "max@studiomax.io",
|
|
62
|
+
"url": "https://studiomax.io"
|
|
63
|
+
},
|
|
64
|
+
"repository": {
|
|
65
|
+
"type": "git",
|
|
66
|
+
"url": "git+https://github.com/crewhaus/factory.git",
|
|
67
|
+
"directory": "packages/runtime-core"
|
|
68
|
+
},
|
|
69
|
+
"homepage": "https://github.com/crewhaus/factory/tree/main/packages/runtime-core#readme",
|
|
70
|
+
"bugs": {
|
|
71
|
+
"url": "https://github.com/crewhaus/factory/issues"
|
|
72
|
+
},
|
|
73
|
+
"publishConfig": {
|
|
74
|
+
"access": "restricted"
|
|
75
|
+
},
|
|
76
|
+
"files": [
|
|
77
|
+
"src",
|
|
78
|
+
"README.md",
|
|
79
|
+
"LICENSE",
|
|
80
|
+
"NOTICE"
|
|
81
|
+
]
|
|
82
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
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, 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("does not false-match snake_case identifiers as italic", () => {
|
|
139
|
+
const c = capture();
|
|
140
|
+
const r = createCliMarkdownRenderer({ write: c.write });
|
|
141
|
+
r.push("call foo_bar_baz now\n");
|
|
142
|
+
expect(strip(c.out())).toBe("call foo_bar_baz now\n");
|
|
143
|
+
// No italic markers because _foo_bar_baz_ isn't a closed pair.
|
|
144
|
+
expect(c.out()).not.toContain("\x1b[3m");
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("nested code-fence inside list-item not double-rendered", () => {
|
|
148
|
+
const c = capture();
|
|
149
|
+
const r = createCliMarkdownRenderer({ write: c.write });
|
|
150
|
+
r.push("- item one\n ```\n code\n ```\n- item two\n");
|
|
151
|
+
const stripped = strip(c.out());
|
|
152
|
+
expect(stripped).toContain("• item one");
|
|
153
|
+
expect(stripped).toContain("code");
|
|
154
|
+
expect(stripped).toContain("• item two");
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe("isCliMarkdownEnabled", () => {
|
|
159
|
+
test("returns false when env var is unset", () => {
|
|
160
|
+
expect(isCliMarkdownEnabled({})).toBe(false);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("returns true for '1' and 'true' (case sensitive)", () => {
|
|
164
|
+
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "1" })).toBe(true);
|
|
165
|
+
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "true" })).toBe(true);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test("returns false for falsy strings", () => {
|
|
169
|
+
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "0" })).toBe(false);
|
|
170
|
+
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "false" })).toBe(false);
|
|
171
|
+
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "" })).toBe(false);
|
|
172
|
+
});
|
|
173
|
+
});
|
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
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
|
+
});
|