@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.
@@ -0,0 +1,138 @@
1
+ /**
2
+ * T3 — single-turn `runChatLoop` round-trip emits the expected ordered
3
+ * sequence of TraceEvents under one traceId.
4
+ */
5
+ import { describe, expect, test } from "bun:test";
6
+ import type Anthropic from "@anthropic-ai/sdk";
7
+ import { createRunContext } from "@crewhaus/run-context";
8
+ import { buildTool } from "@crewhaus/tool-builder";
9
+ import type { TraceEvent, TraceEventKind } from "@crewhaus/trace-event-bus";
10
+ import { z } from "zod";
11
+ import { runChatLoop } from "./index";
12
+
13
+ function makeOneTurnAdapter(
14
+ toolUseId: string,
15
+ ): import("@crewhaus/adapter-anthropic").ProviderAdapter {
16
+ let i = 0;
17
+ return {
18
+ providerId: "anthropic",
19
+ features: {
20
+ caching: "explicit",
21
+ tool_use: true,
22
+ vision: true,
23
+ thinking: true,
24
+ web_search: true,
25
+ },
26
+ estimateTokens: () => 0,
27
+ stream: () => {
28
+ const isFirst = i === 0;
29
+ i += 1;
30
+ return (async function* () {
31
+ yield {
32
+ kind: "message_start",
33
+ usage: { input: isFirst ? 100 : 150, output: 0 },
34
+ } as const;
35
+ if (isFirst) {
36
+ yield {
37
+ kind: "content_block_start",
38
+ index: 0,
39
+ block: { type: "tool_use", id: toolUseId, name: "noop", input: {} },
40
+ } as const;
41
+ yield {
42
+ kind: "content_block_delta",
43
+ index: 0,
44
+ delta: { type: "input_json_delta", partial_json: JSON.stringify({ x: 1 }) },
45
+ } as const;
46
+ yield { kind: "content_block_stop", index: 0 } as const;
47
+ yield {
48
+ kind: "message_delta",
49
+ stopReason: "tool_use",
50
+ usage: { input: 100, output: 30 },
51
+ } as const;
52
+ } else {
53
+ yield {
54
+ kind: "content_block_start",
55
+ index: 0,
56
+ block: { type: "text", text: "" },
57
+ } as const;
58
+ yield {
59
+ kind: "content_block_delta",
60
+ index: 0,
61
+ delta: { type: "text_delta", text: "done" },
62
+ } as const;
63
+ yield { kind: "content_block_stop", index: 0 } as const;
64
+ yield {
65
+ kind: "message_delta",
66
+ stopReason: "end_turn",
67
+ usage: { input: 150, output: 10 },
68
+ } as const;
69
+ }
70
+ yield { kind: "message_stop" } as const;
71
+ })();
72
+ },
73
+ };
74
+ }
75
+
76
+ describe("runChatLoop observability", () => {
77
+ test("single turn with one tool call emits the expected event sequence", async () => {
78
+ const noop = buildTool({
79
+ name: "noop",
80
+ description: "does nothing",
81
+ inputSchema: z.object({ x: z.number() }),
82
+ execute: async () => "ok",
83
+ });
84
+ const runContext = createRunContext();
85
+ const seen: TraceEvent[] = [];
86
+ runContext.eventBus.subscribe((e) => {
87
+ seen.push(e);
88
+ });
89
+
90
+ await runChatLoop({
91
+ model: "test-model",
92
+ instructions: "test",
93
+ _adapter: makeOneTurnAdapter("toolu_a"),
94
+ runContext,
95
+ singleTurn: true,
96
+ seedMessages: [{ role: "user", content: "hello" }],
97
+ tools: [noop],
98
+ permissionMode: "default",
99
+ });
100
+
101
+ const kinds = seen.map((e) => e.kind);
102
+ // Permissive ordering check: the spine of the run should appear in this order.
103
+ const wantOrder: TraceEventKind[] = [
104
+ "turn_start",
105
+ "model_request",
106
+ "model_response",
107
+ "tool_call_start",
108
+ "permission_decision",
109
+ "tool_call_end",
110
+ "model_request",
111
+ "model_response",
112
+ "turn_end",
113
+ ];
114
+ let cursor = 0;
115
+ for (const target of wantOrder) {
116
+ const idx = kinds.indexOf(target, cursor);
117
+ expect(idx).toBeGreaterThanOrEqual(cursor);
118
+ cursor = idx + 1;
119
+ }
120
+
121
+ // All events share one traceId.
122
+ const traceIds = new Set(seen.map((e) => e.traceId));
123
+ expect(traceIds.size).toBe(1);
124
+
125
+ // Tool span ids match for the start/end pair.
126
+ const toolStart = seen.find((e) => e.kind === "tool_call_start" && e.toolUseId === "toolu_a");
127
+ const toolEnd = seen.find((e) => e.kind === "tool_call_end" && e.toolUseId === "toolu_a");
128
+ expect(toolStart?.spanId).toBeDefined();
129
+ expect(toolEnd?.spanId).toBe(toolStart?.spanId);
130
+
131
+ // The non-streaming path carries usage onto model_response.
132
+ const response = seen.find(
133
+ (e): e is Extract<TraceEvent, { kind: "model_response" }> => e.kind === "model_response",
134
+ );
135
+ expect(response?.usage.input).toBe(100);
136
+ expect(response?.usage.output).toBe(30);
137
+ });
138
+ });
@@ -0,0 +1,116 @@
1
+ import { type CostTracker, createCostTracker, formatUsdMicros } from "@crewhaus/cost-tracker";
2
+ import {
3
+ type AttachedMetrics,
4
+ attachIfEnvSet as attachMetricsIfEnvSet,
5
+ } from "@crewhaus/metrics-collector";
6
+ import {
7
+ type AttachedOtelExporter,
8
+ attachIfEnvSet as attachOtelIfEnvSet,
9
+ } from "@crewhaus/otel-exporter";
10
+ /**
11
+ * Section 15 — attach the default observability subscribers to a
12
+ * `TraceEventBus` based on environment variables. Returns a single `flushAll`
13
+ * the orchestrator awaits in its `finally` block.
14
+ *
15
+ * CREWHAUS_TRACE=pretty|json → structured-event-printer
16
+ * CREWHAUS_METRICS=stdout|... → metrics-collector (buffered stdout JSON / textfile / http)
17
+ * OTEL_EXPORTER_OTLP_ENDPOINT → otel-exporter (OTLP/HTTP, gen_ai/* attributes)
18
+ * CREWHAUS_COST_TRACKING=1 → cost-tracker (Section 27 — emits cost_accrual events)
19
+ * CREWHAUS_COST_INLINE=1 → CLI inline cost line per turn (requires CREWHAUS_COST_TRACKING)
20
+ *
21
+ * All are opt-in. With no env vars set this function returns a no-op
22
+ * `flushAll` so observability adds zero output and zero overhead.
23
+ */
24
+ import type { RunContext } from "@crewhaus/run-context";
25
+ import {
26
+ type AttachedPrinter,
27
+ attachIfEnvSet as attachPrinterIfEnvSet,
28
+ } from "@crewhaus/structured-event-printer";
29
+ import type {
30
+ CostAccrualEvent,
31
+ TraceEvent,
32
+ TraceEventBus,
33
+ Unsubscribe,
34
+ } from "@crewhaus/trace-event-bus";
35
+
36
+ export type AttachedSubscribers = {
37
+ printer: AttachedPrinter | undefined;
38
+ metrics: AttachedMetrics | undefined;
39
+ otel: AttachedOtelExporter | undefined;
40
+ costTracker: CostTracker | undefined;
41
+ costInlineUnsubscribe: Unsubscribe | undefined;
42
+ flushAll(): Promise<void>;
43
+ shutdownAll(): Promise<void>;
44
+ };
45
+
46
+ /**
47
+ * Format a single `cost_accrual` event as a one-line CLI status:
48
+ * `[💸 $0.0042 · 12.3k in / 1.1k out · model=claude-sonnet-4-6]`
49
+ *
50
+ * Exported so target-cli's emitted bundle can render the same format
51
+ * without re-implementing it.
52
+ */
53
+ export function formatCostInlineLine(ev: CostAccrualEvent): string {
54
+ const cost = formatUsdMicros(ev.costUsdMicros);
55
+ const fmtTokens = (n: number): string => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
56
+ return `[💸 ${cost} · ${fmtTokens(ev.inputTokens)} in / ${fmtTokens(ev.outputTokens)} out · model=${ev.modelId}]`;
57
+ }
58
+
59
+ export async function attachDefaultSubscribers(
60
+ bus: TraceEventBus,
61
+ runContext: RunContext,
62
+ env: NodeJS.ProcessEnv = process.env,
63
+ ): Promise<AttachedSubscribers> {
64
+ const printer = attachPrinterIfEnvSet(bus, env);
65
+ const metrics = await attachMetricsIfEnvSet(bus, env);
66
+ const otel = attachOtelIfEnvSet(bus, env);
67
+ const costTracker =
68
+ env["CREWHAUS_COST_TRACKING"] === "1" || env["CREWHAUS_COST_TRACKING"] === "true"
69
+ ? createCostTracker(bus, {
70
+ ...(env["CREWHAUS_TENANT_ID"] !== undefined
71
+ ? { tenantId: env["CREWHAUS_TENANT_ID"] }
72
+ : {}),
73
+ })
74
+ : undefined;
75
+ // CLI inline cost line — opt-in via CREWHAUS_COST_INLINE=1. Subscribes to
76
+ // the `cost_accrual` events that cost-tracker emits, prints one tidy line
77
+ // per accrual, and stays out of the trace bus's main printer surface so
78
+ // it doesn't double-print when CREWHAUS_TRACE=pretty is also set.
79
+ const costInlineEnabled =
80
+ (env["CREWHAUS_COST_INLINE"] === "1" || env["CREWHAUS_COST_INLINE"] === "true") &&
81
+ costTracker !== undefined;
82
+ let costInlineUnsubscribe: Unsubscribe | undefined;
83
+ if (costInlineEnabled) {
84
+ const handler = (event: TraceEvent): void => {
85
+ if (event.kind !== "cost_accrual") return;
86
+ process.stdout.write(`${formatCostInlineLine(event as CostAccrualEvent)}\n`);
87
+ };
88
+ costInlineUnsubscribe = bus.subscribe(handler);
89
+ }
90
+ const flushAll = async (): Promise<void> => {
91
+ printer?.finalize();
92
+ const tasks: Promise<void>[] = [];
93
+ if (metrics)
94
+ tasks.push(metrics.flush().catch((err) => logFlushError(runContext, "metrics", err)));
95
+ if (otel) tasks.push(otel.flush().catch((err) => logFlushError(runContext, "otel", err)));
96
+ tasks.push(bus.flush().catch((err) => logFlushError(runContext, "bus", err)));
97
+ await Promise.all(tasks);
98
+ };
99
+ const shutdownAll = async (): Promise<void> => {
100
+ printer?.unsubscribe();
101
+ if (metrics) {
102
+ await metrics.shutdown().catch((err) => logFlushError(runContext, "metrics", err));
103
+ }
104
+ if (otel) {
105
+ await otel.shutdown().catch((err) => logFlushError(runContext, "otel", err));
106
+ }
107
+ costTracker?.unsubscribe();
108
+ costInlineUnsubscribe?.();
109
+ };
110
+ return { printer, metrics, otel, costTracker, costInlineUnsubscribe, flushAll, shutdownAll };
111
+ }
112
+
113
+ function logFlushError(runContext: RunContext, name: string, err: unknown): void {
114
+ const message = err instanceof Error ? err.message : String(err);
115
+ runContext.logger.error("observability.flush_failed", { name, message });
116
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Tests for the project-memory auto-loader. Covers:
3
+ * - File discovery in cwd (AGENTS.md, CLAUDE.md, CODE-COMPANION.md, AGENT.md)
4
+ * - Multi-file concatenation with envelope tags
5
+ * - Cap-byte truncation with notice
6
+ * - Graceful no-match (empty result; non-erroring)
7
+ * - Boundary classification with user origin (smoke — full classifier
8
+ * tests live in boundary-classifier package).
9
+ */
10
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
12
+ import { mkdtempSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ CANONICAL_MEMORY_FILES,
17
+ DEFAULT_PROJECT_MEMORY_CAP_BYTES,
18
+ loadProjectMemory,
19
+ } from "./project-memory";
20
+
21
+ let workdir: string;
22
+
23
+ beforeAll(() => {
24
+ workdir = mkdtempSync(join(tmpdir(), "crewhaus-project-memory-"));
25
+ });
26
+
27
+ afterAll(() => {
28
+ rmSync(workdir, { recursive: true, force: true });
29
+ });
30
+
31
+ function setUpWorkdir(files: Record<string, string>): string {
32
+ const dir = mkdtempSync(join(workdir, "case-"));
33
+ for (const [name, content] of Object.entries(files)) {
34
+ writeFileSync(join(dir, name), content);
35
+ }
36
+ return dir;
37
+ }
38
+
39
+ describe("loadProjectMemory", () => {
40
+ test("returns empty result when no memory files present", async () => {
41
+ const dir = setUpWorkdir({ "unrelated.md": "ignored", "package.json": "{}" });
42
+ const result = await loadProjectMemory({ cwd: dir });
43
+ expect(result.files).toEqual([]);
44
+ expect(result.prompt).toBe("");
45
+ expect(result.totalBytes).toBe(0);
46
+ });
47
+
48
+ test("loads AGENTS.md when present", async () => {
49
+ const dir = setUpWorkdir({ "AGENTS.md": "# Project Neutral\nHandles the thing." });
50
+ const result = await loadProjectMemory({ cwd: dir });
51
+ expect(result.files.length).toBe(1);
52
+ expect(result.files[0]?.filename).toBe("AGENTS.md");
53
+ expect(result.files[0]?.content).toContain("# Project Neutral");
54
+ expect(result.files[0]?.truncated).toBe(false);
55
+ expect(result.prompt).toContain('<project_memory file="AGENTS.md">');
56
+ expect(result.prompt).toContain("</project_memory>");
57
+ });
58
+
59
+ test("loads CLAUDE.md when present", async () => {
60
+ const dir = setUpWorkdir({ "CLAUDE.md": "# Project X\nDoes the thing." });
61
+ const result = await loadProjectMemory({ cwd: dir });
62
+ expect(result.files.length).toBe(1);
63
+ expect(result.files[0]?.filename).toBe("CLAUDE.md");
64
+ expect(result.files[0]?.content).toContain("# Project X");
65
+ expect(result.files[0]?.truncated).toBe(false);
66
+ expect(result.prompt).toContain('<project_memory file="CLAUDE.md">');
67
+ expect(result.prompt).toContain("</project_memory>");
68
+ });
69
+
70
+ test("loads multiple memory files in canonical priority order", async () => {
71
+ const dir = setUpWorkdir({
72
+ "AGENTS.md": "# agents content",
73
+ "CLAUDE.md": "# claude content",
74
+ "CODE-COMPANION.md": "# code companion content",
75
+ "AGENT.md": "# agent content",
76
+ });
77
+ const result = await loadProjectMemory({ cwd: dir });
78
+ expect(result.files.map((f) => f.filename)).toEqual([
79
+ "AGENTS.md",
80
+ "CLAUDE.md",
81
+ "CODE-COMPANION.md",
82
+ "AGENT.md",
83
+ ]);
84
+ expect(result.prompt).toContain('<project_memory file="AGENTS.md">');
85
+ expect(result.prompt).toContain('<project_memory file="CLAUDE.md">');
86
+ expect(result.prompt).toContain('<project_memory file="CODE-COMPANION.md">');
87
+ expect(result.prompt).toContain('<project_memory file="AGENT.md">');
88
+ });
89
+
90
+ test("truncates content exceeding capBytes with a notice", async () => {
91
+ const dir = setUpWorkdir({ "CLAUDE.md": "x".repeat(200) });
92
+ const result = await loadProjectMemory({ cwd: dir, capBytes: 50 });
93
+ expect(result.files.length).toBe(1);
94
+ expect(result.files[0]?.truncated).toBe(true);
95
+ expect(result.files[0]?.content).toContain("[...truncated to 50 bytes");
96
+ });
97
+
98
+ test("stops loading once total cap exhausted", async () => {
99
+ const dir = setUpWorkdir({
100
+ "CLAUDE.md": "a".repeat(100),
101
+ "CODE-COMPANION.md": "b".repeat(100),
102
+ "AGENT.md": "c".repeat(100),
103
+ });
104
+ const result = await loadProjectMemory({ cwd: dir, capBytes: 150 });
105
+ expect(result.files.length).toBeGreaterThan(0);
106
+ expect(result.totalBytes).toBeLessThanOrEqual(150 + 200); // truncation suffix adds bytes
107
+ });
108
+
109
+ test("ignores non-canonical filenames", async () => {
110
+ // Note: avoid case-only-different names — macOS is case-insensitive
111
+ // by default so "Claude.md" would collide with "CLAUDE.md".
112
+ const dir = setUpWorkdir({
113
+ "MEMORY.md": "should be ignored",
114
+ "PROJECT.md": "also ignored",
115
+ });
116
+ const result = await loadProjectMemory({ cwd: dir });
117
+ expect(result.files).toEqual([]);
118
+ });
119
+
120
+ test("honors filenames override", async () => {
121
+ const dir = setUpWorkdir({ "PROJECT.md": "custom content" });
122
+ const result = await loadProjectMemory({ cwd: dir, filenames: ["PROJECT.md"] });
123
+ expect(result.files.length).toBe(1);
124
+ expect(result.files[0]?.filename).toBe("PROJECT.md");
125
+ });
126
+
127
+ test("returns valid result when cwd doesn't exist (no throw)", async () => {
128
+ const result = await loadProjectMemory({ cwd: "/this/path/does/not/exist/anywhere" });
129
+ expect(result.files).toEqual([]);
130
+ expect(result.prompt).toBe("");
131
+ });
132
+
133
+ test("CANONICAL_MEMORY_FILES exports the right list", () => {
134
+ expect(CANONICAL_MEMORY_FILES).toEqual([
135
+ "AGENTS.md",
136
+ "CLAUDE.md",
137
+ "CODE-COMPANION.md",
138
+ "AGENT.md",
139
+ ]);
140
+ });
141
+
142
+ test("DEFAULT_PROJECT_MEMORY_CAP_BYTES is 64 KB", () => {
143
+ expect(DEFAULT_PROJECT_MEMORY_CAP_BYTES).toBe(64 * 1024);
144
+ });
145
+ });
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Auto-loaded project memory — M3.1 of the heavy-hitter plan.
3
+ *
4
+ * At session-start, the runtime looks for canonical "project memory"
5
+ * files in the current working directory and prepends their contents
6
+ * to the system prompt. Follows the vendor-neutral agents.md convention
7
+ * (https://agents.md) and is compatible with Claude Code's CLAUDE.md
8
+ * auto-load behaviour.
9
+ *
10
+ * Files searched (in priority order, all matches are loaded):
11
+ * - AGENTS.md (vendor-neutral convention — agents.md)
12
+ * - CLAUDE.md (Claude Code convention)
13
+ * - CODE-COMPANION.md (hello-code demo convention)
14
+ * - AGENT.md (legacy singular form; retained for compatibility)
15
+ *
16
+ * Each file's contents are wrapped in:
17
+ * <project_memory file="AGENTS.md">
18
+ * ...contents...
19
+ * </project_memory>
20
+ *
21
+ * Multiple files concatenate with blank-line separators.
22
+ *
23
+ * Pillar 3 — Security fabric: every file's contents are classified via
24
+ * `boundary-classifier` with origin `"user"` (the developer owns their
25
+ * repo). The user-origin default policy is `"pass"`, so classification
26
+ * RUNS (and logs trace events) without blocking — which is the right
27
+ * stance for a developer-trusted source. If a future deployment wants
28
+ * strict policy on these files, pass `severity: "block"` via opts.
29
+ *
30
+ * Size cap: 64 KB total across all matched files. Larger files load
31
+ * the first N bytes plus a `[...truncated]` notice — the prompt cache
32
+ * is more valuable than the tail of a large memory file.
33
+ */
34
+ import { existsSync } from "node:fs";
35
+ import { readFile, stat } from "node:fs/promises";
36
+ import { join } from "node:path";
37
+ import { classifyBoundary } from "@crewhaus/boundary-classifier";
38
+
39
+ export const CANONICAL_MEMORY_FILES = [
40
+ "AGENTS.md",
41
+ "CLAUDE.md",
42
+ "CODE-COMPANION.md",
43
+ "AGENT.md",
44
+ ] as const;
45
+
46
+ export const DEFAULT_PROJECT_MEMORY_CAP_BYTES = 64 * 1024;
47
+
48
+ export interface ProjectMemoryLoadOptions {
49
+ /** Override cwd. Defaults to `process.cwd()`. */
50
+ readonly cwd?: string;
51
+ /** Override the filename list. Defaults to `CANONICAL_MEMORY_FILES`. */
52
+ readonly filenames?: readonly string[];
53
+ /** Maximum total bytes across all loaded files. Defaults to 64 KB. */
54
+ readonly capBytes?: number;
55
+ }
56
+
57
+ export interface LoadedMemoryFile {
58
+ readonly filename: string;
59
+ readonly content: string;
60
+ readonly truncated: boolean;
61
+ }
62
+
63
+ export interface ProjectMemoryLoadResult {
64
+ readonly files: readonly LoadedMemoryFile[];
65
+ /** Total content bytes across all files (post-truncation). */
66
+ readonly totalBytes: number;
67
+ /** Wrapped + concatenated content ready to prepend to the system prompt. */
68
+ readonly prompt: string;
69
+ }
70
+
71
+ /**
72
+ * Scan cwd for project-memory files and return the rendered prompt block.
73
+ * Returns `{ files: [], prompt: "" }` when no files matched — caller can
74
+ * conditionally skip the prepend without a length check.
75
+ */
76
+ export async function loadProjectMemory(
77
+ opts: ProjectMemoryLoadOptions = {},
78
+ ): Promise<ProjectMemoryLoadResult> {
79
+ const cwd = opts.cwd ?? process.cwd();
80
+ const filenames = opts.filenames ?? CANONICAL_MEMORY_FILES;
81
+ const cap = opts.capBytes ?? DEFAULT_PROJECT_MEMORY_CAP_BYTES;
82
+
83
+ const matched: { filename: string; fullPath: string; size: number }[] = [];
84
+ for (const filename of filenames) {
85
+ const fullPath = join(cwd, filename);
86
+ if (!existsSync(fullPath)) continue;
87
+ try {
88
+ const st = await stat(fullPath);
89
+ if (!st.isFile()) continue;
90
+ matched.push({ filename, fullPath, size: st.size });
91
+ } catch {}
92
+ }
93
+
94
+ if (matched.length === 0) {
95
+ return { files: [], totalBytes: 0, prompt: "" };
96
+ }
97
+
98
+ const files: LoadedMemoryFile[] = [];
99
+ let remaining = cap;
100
+ for (const m of matched) {
101
+ if (remaining <= 0) break;
102
+ let content: string;
103
+ try {
104
+ content = await readFile(m.fullPath, "utf-8");
105
+ } catch {
106
+ continue;
107
+ }
108
+ let truncated = false;
109
+ const contentBytes = Buffer.byteLength(content, "utf8");
110
+ if (contentBytes > remaining) {
111
+ // Truncate at the byte cap, then append a notice.
112
+ const buf = Buffer.from(content, "utf-8").subarray(0, remaining);
113
+ content = `${buf.toString("utf-8")}\n\n[...truncated to ${remaining} bytes; ${
114
+ contentBytes - remaining
115
+ } bytes omitted]`;
116
+ truncated = true;
117
+ }
118
+ // Pillar 3: classify with origin "user" — `pass` policy runs the
119
+ // classifier and emits trace events without modifying content.
120
+ await classifyBoundary(content, { origin: "user" }).catch(() => undefined);
121
+ files.push({ filename: m.filename, content, truncated });
122
+ remaining -= Buffer.byteLength(content, "utf8");
123
+ }
124
+
125
+ const sections = files
126
+ .map((f) => `<project_memory file="${f.filename}">\n${f.content}\n</project_memory>`)
127
+ .join("\n\n");
128
+
129
+ return {
130
+ files,
131
+ totalBytes: files.reduce((sum, f) => sum + Buffer.byteLength(f.content, "utf8"), 0),
132
+ prompt: sections,
133
+ };
134
+ }