@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.
- package/dist/cli-markdown.d.ts +56 -0
- package/dist/cli-markdown.js +164 -0
- package/dist/index.d.ts +376 -0
- package/dist/index.js +2044 -0
- package/dist/observability.d.ts +38 -0
- package/dist/observability.js +69 -0
- package/dist/project-memory.d.ts +28 -0
- package/dist/project-memory.js +104 -0
- package/dist/spinner.d.ts +106 -0
- package/dist/spinner.js +159 -0
- package/package.json +46 -43
- package/src/cli-markdown.test.ts +0 -207
- package/src/cli-markdown.ts +0 -190
- package/src/cost-inline.test.ts +0 -58
- package/src/cost-persist.test.ts +0 -113
- package/src/cost-wire-model.test.ts +0 -138
- package/src/index-coverage.test.ts +0 -1671
- package/src/index.test.ts +0 -2471
- package/src/index.ts +0 -2365
- package/src/observability-coverage.test.ts +0 -303
- package/src/observability.test.ts +0 -138
- package/src/observability.ts +0 -116
- package/src/project-memory-coverage.test.ts +0 -119
- package/src/project-memory.test.ts +0 -145
- package/src/project-memory.ts +0 -134
- package/src/tenant-isolation.test.ts +0 -80
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type CostTracker } from "@crewhaus/cost-tracker";
|
|
2
|
+
import { type AttachedMetrics } from "@crewhaus/metrics-collector";
|
|
3
|
+
import { type AttachedOtelExporter } from "@crewhaus/otel-exporter";
|
|
4
|
+
/**
|
|
5
|
+
* Section 15 — attach the default observability subscribers to a
|
|
6
|
+
* `TraceEventBus` based on environment variables. Returns a single `flushAll`
|
|
7
|
+
* the orchestrator awaits in its `finally` block.
|
|
8
|
+
*
|
|
9
|
+
* CREWHAUS_TRACE=pretty|json → structured-event-printer
|
|
10
|
+
* CREWHAUS_METRICS=stdout|... → metrics-collector (buffered stdout JSON / textfile / http)
|
|
11
|
+
* OTEL_EXPORTER_OTLP_ENDPOINT → otel-exporter (OTLP/HTTP, gen_ai/* attributes)
|
|
12
|
+
* CREWHAUS_COST_TRACKING=1 → cost-tracker (Section 27 — emits cost_accrual events)
|
|
13
|
+
* CREWHAUS_COST_INLINE=1 → CLI inline cost line per turn (requires CREWHAUS_COST_TRACKING)
|
|
14
|
+
*
|
|
15
|
+
* All are opt-in. With no env vars set this function returns a no-op
|
|
16
|
+
* `flushAll` so observability adds zero output and zero overhead.
|
|
17
|
+
*/
|
|
18
|
+
import type { RunContext } from "@crewhaus/run-context";
|
|
19
|
+
import { type AttachedPrinter } from "@crewhaus/structured-event-printer";
|
|
20
|
+
import type { CostAccrualEvent, TraceEventBus, Unsubscribe } from "@crewhaus/trace-event-bus";
|
|
21
|
+
export type AttachedSubscribers = {
|
|
22
|
+
printer: AttachedPrinter | undefined;
|
|
23
|
+
metrics: AttachedMetrics | undefined;
|
|
24
|
+
otel: AttachedOtelExporter | undefined;
|
|
25
|
+
costTracker: CostTracker | undefined;
|
|
26
|
+
costInlineUnsubscribe: Unsubscribe | undefined;
|
|
27
|
+
flushAll(): Promise<void>;
|
|
28
|
+
shutdownAll(): Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Format a single `cost_accrual` event as a one-line CLI status:
|
|
32
|
+
* `[💸 $0.0042 · 12.3k in / 1.1k out · model=claude-sonnet-4-6]`
|
|
33
|
+
*
|
|
34
|
+
* Exported so target-cli's emitted bundle can render the same format
|
|
35
|
+
* without re-implementing it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function formatCostInlineLine(ev: CostAccrualEvent): string;
|
|
38
|
+
export declare function attachDefaultSubscribers(bus: TraceEventBus, runContext: RunContext, env?: NodeJS.ProcessEnv): Promise<AttachedSubscribers>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createCostTracker, formatUsdMicros } from "@crewhaus/cost-tracker";
|
|
2
|
+
import { attachIfEnvSet as attachMetricsIfEnvSet, } from "@crewhaus/metrics-collector";
|
|
3
|
+
import { attachIfEnvSet as attachOtelIfEnvSet, } from "@crewhaus/otel-exporter";
|
|
4
|
+
import { attachIfEnvSet as attachPrinterIfEnvSet, } from "@crewhaus/structured-event-printer";
|
|
5
|
+
/**
|
|
6
|
+
* Format a single `cost_accrual` event as a one-line CLI status:
|
|
7
|
+
* `[💸 $0.0042 · 12.3k in / 1.1k out · model=claude-sonnet-4-6]`
|
|
8
|
+
*
|
|
9
|
+
* Exported so target-cli's emitted bundle can render the same format
|
|
10
|
+
* without re-implementing it.
|
|
11
|
+
*/
|
|
12
|
+
export function formatCostInlineLine(ev) {
|
|
13
|
+
const cost = formatUsdMicros(ev.costUsdMicros);
|
|
14
|
+
const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
|
|
15
|
+
return `[💸 ${cost} · ${fmtTokens(ev.inputTokens)} in / ${fmtTokens(ev.outputTokens)} out · model=${ev.modelId}]`;
|
|
16
|
+
}
|
|
17
|
+
export async function attachDefaultSubscribers(bus, runContext, env = process.env) {
|
|
18
|
+
const printer = attachPrinterIfEnvSet(bus, env);
|
|
19
|
+
const metrics = await attachMetricsIfEnvSet(bus, env);
|
|
20
|
+
const otel = attachOtelIfEnvSet(bus, env);
|
|
21
|
+
const costTracker = env["CREWHAUS_COST_TRACKING"] === "1" || env["CREWHAUS_COST_TRACKING"] === "true"
|
|
22
|
+
? createCostTracker(bus, {
|
|
23
|
+
...(env["CREWHAUS_TENANT_ID"] !== undefined
|
|
24
|
+
? { tenantId: env["CREWHAUS_TENANT_ID"] }
|
|
25
|
+
: {}),
|
|
26
|
+
})
|
|
27
|
+
: undefined;
|
|
28
|
+
// CLI inline cost line — opt-in via CREWHAUS_COST_INLINE=1. Subscribes to
|
|
29
|
+
// the `cost_accrual` events that cost-tracker emits, prints one tidy line
|
|
30
|
+
// per accrual, and stays out of the trace bus's main printer surface so
|
|
31
|
+
// it doesn't double-print when CREWHAUS_TRACE=pretty is also set.
|
|
32
|
+
const costInlineEnabled = (env["CREWHAUS_COST_INLINE"] === "1" || env["CREWHAUS_COST_INLINE"] === "true") &&
|
|
33
|
+
costTracker !== undefined;
|
|
34
|
+
let costInlineUnsubscribe;
|
|
35
|
+
if (costInlineEnabled) {
|
|
36
|
+
const handler = (event) => {
|
|
37
|
+
if (event.kind !== "cost_accrual")
|
|
38
|
+
return;
|
|
39
|
+
process.stdout.write(`${formatCostInlineLine(event)}\n`);
|
|
40
|
+
};
|
|
41
|
+
costInlineUnsubscribe = bus.subscribe(handler);
|
|
42
|
+
}
|
|
43
|
+
const flushAll = async () => {
|
|
44
|
+
printer?.finalize();
|
|
45
|
+
const tasks = [];
|
|
46
|
+
if (metrics)
|
|
47
|
+
tasks.push(metrics.flush().catch((err) => logFlushError(runContext, "metrics", err)));
|
|
48
|
+
if (otel)
|
|
49
|
+
tasks.push(otel.flush().catch((err) => logFlushError(runContext, "otel", err)));
|
|
50
|
+
tasks.push(bus.flush().catch((err) => logFlushError(runContext, "bus", err)));
|
|
51
|
+
await Promise.all(tasks);
|
|
52
|
+
};
|
|
53
|
+
const shutdownAll = async () => {
|
|
54
|
+
printer?.unsubscribe();
|
|
55
|
+
if (metrics) {
|
|
56
|
+
await metrics.shutdown().catch((err) => logFlushError(runContext, "metrics", err));
|
|
57
|
+
}
|
|
58
|
+
if (otel) {
|
|
59
|
+
await otel.shutdown().catch((err) => logFlushError(runContext, "otel", err));
|
|
60
|
+
}
|
|
61
|
+
costTracker?.unsubscribe();
|
|
62
|
+
costInlineUnsubscribe?.();
|
|
63
|
+
};
|
|
64
|
+
return { printer, metrics, otel, costTracker, costInlineUnsubscribe, flushAll, shutdownAll };
|
|
65
|
+
}
|
|
66
|
+
function logFlushError(runContext, name, err) {
|
|
67
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
68
|
+
runContext.logger.error("observability.flush_failed", { name, message });
|
|
69
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const CANONICAL_MEMORY_FILES: readonly ["AGENTS.md", "CLAUDE.md", "CODE-COMPANION.md", "AGENT.md"];
|
|
2
|
+
export declare const DEFAULT_PROJECT_MEMORY_CAP_BYTES: number;
|
|
3
|
+
export interface ProjectMemoryLoadOptions {
|
|
4
|
+
/** Override cwd. Defaults to `process.cwd()`. */
|
|
5
|
+
readonly cwd?: string;
|
|
6
|
+
/** Override the filename list. Defaults to `CANONICAL_MEMORY_FILES`. */
|
|
7
|
+
readonly filenames?: readonly string[];
|
|
8
|
+
/** Maximum total bytes across all loaded files. Defaults to 64 KB. */
|
|
9
|
+
readonly capBytes?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface LoadedMemoryFile {
|
|
12
|
+
readonly filename: string;
|
|
13
|
+
readonly content: string;
|
|
14
|
+
readonly truncated: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface ProjectMemoryLoadResult {
|
|
17
|
+
readonly files: readonly LoadedMemoryFile[];
|
|
18
|
+
/** Total content bytes across all files (post-truncation). */
|
|
19
|
+
readonly totalBytes: number;
|
|
20
|
+
/** Wrapped + concatenated content ready to prepend to the system prompt. */
|
|
21
|
+
readonly prompt: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Scan cwd for project-memory files and return the rendered prompt block.
|
|
25
|
+
* Returns `{ files: [], prompt: "" }` when no files matched — caller can
|
|
26
|
+
* conditionally skip the prepend without a length check.
|
|
27
|
+
*/
|
|
28
|
+
export declare function loadProjectMemory(opts?: ProjectMemoryLoadOptions): Promise<ProjectMemoryLoadResult>;
|
|
@@ -0,0 +1,104 @@
|
|
|
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
|
+
export const CANONICAL_MEMORY_FILES = [
|
|
39
|
+
"AGENTS.md",
|
|
40
|
+
"CLAUDE.md",
|
|
41
|
+
"CODE-COMPANION.md",
|
|
42
|
+
"AGENT.md",
|
|
43
|
+
];
|
|
44
|
+
export const DEFAULT_PROJECT_MEMORY_CAP_BYTES = 64 * 1024;
|
|
45
|
+
/**
|
|
46
|
+
* Scan cwd for project-memory files and return the rendered prompt block.
|
|
47
|
+
* Returns `{ files: [], prompt: "" }` when no files matched — caller can
|
|
48
|
+
* conditionally skip the prepend without a length check.
|
|
49
|
+
*/
|
|
50
|
+
export async function loadProjectMemory(opts = {}) {
|
|
51
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
52
|
+
const filenames = opts.filenames ?? CANONICAL_MEMORY_FILES;
|
|
53
|
+
const cap = opts.capBytes ?? DEFAULT_PROJECT_MEMORY_CAP_BYTES;
|
|
54
|
+
const matched = [];
|
|
55
|
+
for (const filename of filenames) {
|
|
56
|
+
const fullPath = join(cwd, filename);
|
|
57
|
+
if (!existsSync(fullPath))
|
|
58
|
+
continue;
|
|
59
|
+
try {
|
|
60
|
+
const st = await stat(fullPath);
|
|
61
|
+
if (!st.isFile())
|
|
62
|
+
continue;
|
|
63
|
+
matched.push({ filename, fullPath, size: st.size });
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
}
|
|
67
|
+
if (matched.length === 0) {
|
|
68
|
+
return { files: [], totalBytes: 0, prompt: "" };
|
|
69
|
+
}
|
|
70
|
+
const files = [];
|
|
71
|
+
let remaining = cap;
|
|
72
|
+
for (const m of matched) {
|
|
73
|
+
if (remaining <= 0)
|
|
74
|
+
break;
|
|
75
|
+
let content;
|
|
76
|
+
try {
|
|
77
|
+
content = await readFile(m.fullPath, "utf-8");
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
let truncated = false;
|
|
83
|
+
const contentBytes = Buffer.byteLength(content, "utf8");
|
|
84
|
+
if (contentBytes > remaining) {
|
|
85
|
+
// Truncate at the byte cap, then append a notice.
|
|
86
|
+
const buf = Buffer.from(content, "utf-8").subarray(0, remaining);
|
|
87
|
+
content = `${buf.toString("utf-8")}\n\n[...truncated to ${remaining} bytes; ${contentBytes - remaining} bytes omitted]`;
|
|
88
|
+
truncated = true;
|
|
89
|
+
}
|
|
90
|
+
// Pillar 3: classify with origin "user" — `pass` policy runs the
|
|
91
|
+
// classifier and emits trace events without modifying content.
|
|
92
|
+
await classifyBoundary(content, { origin: "user" }).catch(() => undefined);
|
|
93
|
+
files.push({ filename: m.filename, content, truncated });
|
|
94
|
+
remaining -= Buffer.byteLength(content, "utf8");
|
|
95
|
+
}
|
|
96
|
+
const sections = files
|
|
97
|
+
.map((f) => `<project_memory file="${f.filename}">\n${f.content}\n</project_memory>`)
|
|
98
|
+
.join("\n\n");
|
|
99
|
+
return {
|
|
100
|
+
files,
|
|
101
|
+
totalBytes: files.reduce((sum, f) => sum + Buffer.byteLength(f.content, "utf8"), 0),
|
|
102
|
+
prompt: sections,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transient "working" indicator for the interactive CLI surface.
|
|
3
|
+
*
|
|
4
|
+
* The chat loop has silent waits where the terminal would otherwise show
|
|
5
|
+
* nothing while the agent is busy:
|
|
6
|
+
* - waiting on the model's first token ("thinking")
|
|
7
|
+
* - running a tool to completion ("running bash")
|
|
8
|
+
* - retrying after a transient error / compacting context
|
|
9
|
+
*
|
|
10
|
+
* This module renders an animated spinner + a short label during those
|
|
11
|
+
* waits, then erases itself the moment real output begins so the streamed
|
|
12
|
+
* answer is never polluted by control codes.
|
|
13
|
+
*
|
|
14
|
+
* Design / safety:
|
|
15
|
+
* - **TTY-only, opt-out via env.** `isSpinnerEnabled()` returns false for
|
|
16
|
+
* piped/redirected stdout, `TERM=dumb`, and when `CREWHAUS_SPINNER` is set
|
|
17
|
+
* to a falsy value. Non-interactive runs (tests, CI, channel/voice/workflow
|
|
18
|
+
* targets, piped input) therefore get byte-identical output to before — the
|
|
19
|
+
* chat loop additionally disables it for `singleTurn` and injected-input
|
|
20
|
+
* runs (see `runChatLoop`). `NO_COLOR` degrades to a monochrome animation.
|
|
21
|
+
* - **Single line, redraw-in-place.** Each tick rewrites the current line
|
|
22
|
+
* with `\r` + clear-to-EOL. A `prefix` (e.g. `"agent> "`) is preserved
|
|
23
|
+
* across redraws and left behind on `stop()` so the assistant label
|
|
24
|
+
* survives and streamed text continues the same line.
|
|
25
|
+
* - **Foreign-write aware.** `write()` is the one sink every interactive
|
|
26
|
+
* stdout write should pass through while a spinner may be live: it erases
|
|
27
|
+
* the spinner line before emitting, so status lines (`[tool: …]`) and the
|
|
28
|
+
* animation never collide. The interval redraws on its next tick.
|
|
29
|
+
* - **Cursor-safe.** Hides the cursor while spinning and always restores it
|
|
30
|
+
* on `stop()`, so an aborted run never leaves the cursor hidden.
|
|
31
|
+
* - **Never holds the event loop open.** The interval is `unref()`'d.
|
|
32
|
+
* - **Zero deps, injectable.** Sink, clock, and timers are all overridable so
|
|
33
|
+
* the animation is deterministically testable without a real terminal.
|
|
34
|
+
*/
|
|
35
|
+
/** Minimal shape of a timer handle we depend on (Node `Timeout` / Bun `Timer`). */
|
|
36
|
+
interface IntervalHandle {
|
|
37
|
+
unref?: () => void;
|
|
38
|
+
}
|
|
39
|
+
export interface Spinner {
|
|
40
|
+
/**
|
|
41
|
+
* Begin spinning with `label`, or relabel + redraw if already active.
|
|
42
|
+
* No-op when the output is disabled. `prefix` (default: keep current) is
|
|
43
|
+
* redrawn on every frame and left on screen when the spinner stops, so a
|
|
44
|
+
* caller can write e.g. `"agent> "` and have it survive the animation.
|
|
45
|
+
*/
|
|
46
|
+
start(label: string, opts?: {
|
|
47
|
+
readonly prefix?: string;
|
|
48
|
+
}): void;
|
|
49
|
+
/** Update the label in place without restarting the animation. No-op when inactive. */
|
|
50
|
+
setLabel(label: string): void;
|
|
51
|
+
/**
|
|
52
|
+
* Erase the spinner glyph (keeping any `prefix`), restore the cursor, and
|
|
53
|
+
* stop the animation. Idempotent — safe to call when never started.
|
|
54
|
+
*/
|
|
55
|
+
stop(): void;
|
|
56
|
+
/** True while the animation is running. */
|
|
57
|
+
readonly active: boolean;
|
|
58
|
+
}
|
|
59
|
+
export interface CliOutput {
|
|
60
|
+
/**
|
|
61
|
+
* Spinner-aware stdout write. When a spinner is live, the current line is
|
|
62
|
+
* erased before `s` is emitted; the animation redraws on its next tick.
|
|
63
|
+
* When no spinner is active this is a plain pass-through to the sink.
|
|
64
|
+
*/
|
|
65
|
+
write(s: string): void;
|
|
66
|
+
/** The spinner bound to this output. */
|
|
67
|
+
readonly spinner: Spinner;
|
|
68
|
+
}
|
|
69
|
+
export interface CliOutputOptions {
|
|
70
|
+
/**
|
|
71
|
+
* Whether the spinner animates at all. When false, `start`/`setLabel`/`stop`
|
|
72
|
+
* are no-ops and `write` is a plain pass-through — so the byte stream is
|
|
73
|
+
* identical to having no spinner. Defaults to `isSpinnerEnabled()`.
|
|
74
|
+
*/
|
|
75
|
+
readonly enabled?: boolean;
|
|
76
|
+
/** Raw output sink. Defaults to `process.stdout.write`. */
|
|
77
|
+
readonly write?: (s: string) => void;
|
|
78
|
+
/** Animation frames. Defaults to a braille spinner. */
|
|
79
|
+
readonly frames?: readonly string[];
|
|
80
|
+
/** Frame interval in ms. Defaults to 80. */
|
|
81
|
+
readonly intervalMs?: number;
|
|
82
|
+
/** Emit ANSI color. Defaults to `!process.env.NO_COLOR`. */
|
|
83
|
+
readonly color?: boolean;
|
|
84
|
+
/** Monotonic clock for the elapsed-time readout. Defaults to `performance.now`. */
|
|
85
|
+
readonly now?: () => number;
|
|
86
|
+
/** Injectable `setInterval` (testing). Defaults to the global. */
|
|
87
|
+
readonly setIntervalImpl?: (fn: () => void, ms: number) => IntervalHandle;
|
|
88
|
+
/** Injectable `clearInterval` (testing). Defaults to the global. */
|
|
89
|
+
readonly clearIntervalImpl?: (handle: IntervalHandle) => void;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Construct a spinner-aware CLI output. The returned `write` and `spinner`
|
|
93
|
+
* share one line of the terminal: writes erase the live animation, and the
|
|
94
|
+
* animation redraws after them.
|
|
95
|
+
*/
|
|
96
|
+
export declare function createCliOutput(opts?: CliOutputOptions): CliOutput;
|
|
97
|
+
/**
|
|
98
|
+
* Decide whether the working-indicator spinner should animate, based on env
|
|
99
|
+
* and TTY. Centralized so callers don't repeat the parse.
|
|
100
|
+
*
|
|
101
|
+
* Disabled when: stdout is not a TTY (pipes, redirects, CI, tests); the
|
|
102
|
+
* terminal is `dumb`; or `CREWHAUS_SPINNER` is `0`/`false`/`off`/`no`. Any
|
|
103
|
+
* other explicit `CREWHAUS_SPINNER` value forces it on (still TTY-gated).
|
|
104
|
+
*/
|
|
105
|
+
export declare function isSpinnerEnabled(env?: NodeJS.ProcessEnv, isTTY?: boolean): boolean;
|
|
106
|
+
export {};
|
package/dist/spinner.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transient "working" indicator for the interactive CLI surface.
|
|
3
|
+
*
|
|
4
|
+
* The chat loop has silent waits where the terminal would otherwise show
|
|
5
|
+
* nothing while the agent is busy:
|
|
6
|
+
* - waiting on the model's first token ("thinking")
|
|
7
|
+
* - running a tool to completion ("running bash")
|
|
8
|
+
* - retrying after a transient error / compacting context
|
|
9
|
+
*
|
|
10
|
+
* This module renders an animated spinner + a short label during those
|
|
11
|
+
* waits, then erases itself the moment real output begins so the streamed
|
|
12
|
+
* answer is never polluted by control codes.
|
|
13
|
+
*
|
|
14
|
+
* Design / safety:
|
|
15
|
+
* - **TTY-only, opt-out via env.** `isSpinnerEnabled()` returns false for
|
|
16
|
+
* piped/redirected stdout, `TERM=dumb`, and when `CREWHAUS_SPINNER` is set
|
|
17
|
+
* to a falsy value. Non-interactive runs (tests, CI, channel/voice/workflow
|
|
18
|
+
* targets, piped input) therefore get byte-identical output to before — the
|
|
19
|
+
* chat loop additionally disables it for `singleTurn` and injected-input
|
|
20
|
+
* runs (see `runChatLoop`). `NO_COLOR` degrades to a monochrome animation.
|
|
21
|
+
* - **Single line, redraw-in-place.** Each tick rewrites the current line
|
|
22
|
+
* with `\r` + clear-to-EOL. A `prefix` (e.g. `"agent> "`) is preserved
|
|
23
|
+
* across redraws and left behind on `stop()` so the assistant label
|
|
24
|
+
* survives and streamed text continues the same line.
|
|
25
|
+
* - **Foreign-write aware.** `write()` is the one sink every interactive
|
|
26
|
+
* stdout write should pass through while a spinner may be live: it erases
|
|
27
|
+
* the spinner line before emitting, so status lines (`[tool: …]`) and the
|
|
28
|
+
* animation never collide. The interval redraws on its next tick.
|
|
29
|
+
* - **Cursor-safe.** Hides the cursor while spinning and always restores it
|
|
30
|
+
* on `stop()`, so an aborted run never leaves the cursor hidden.
|
|
31
|
+
* - **Never holds the event loop open.** The interval is `unref()`'d.
|
|
32
|
+
* - **Zero deps, injectable.** Sink, clock, and timers are all overridable so
|
|
33
|
+
* the animation is deterministically testable without a real terminal.
|
|
34
|
+
*/
|
|
35
|
+
const HIDE_CURSOR = "\x1b[?25l";
|
|
36
|
+
const SHOW_CURSOR = "\x1b[?25h";
|
|
37
|
+
/** Carriage return + erase-to-end-of-line: rewind and clear the live line. */
|
|
38
|
+
const CLEAR_LINE = "\r\x1b[K";
|
|
39
|
+
const DIM = "\x1b[2m";
|
|
40
|
+
const CYAN = "\x1b[36m";
|
|
41
|
+
const RESET = "\x1b[0m";
|
|
42
|
+
/** Classic braille spinner — one glyph wide, present in every modern font. */
|
|
43
|
+
const DEFAULT_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
44
|
+
const DEFAULT_INTERVAL_MS = 80;
|
|
45
|
+
/**
|
|
46
|
+
* Construct a spinner-aware CLI output. The returned `write` and `spinner`
|
|
47
|
+
* share one line of the terminal: writes erase the live animation, and the
|
|
48
|
+
* animation redraws after them.
|
|
49
|
+
*/
|
|
50
|
+
export function createCliOutput(opts = {}) {
|
|
51
|
+
const rawWrite = opts.write ?? ((s) => void process.stdout.write(s));
|
|
52
|
+
const enabled = opts.enabled ?? isSpinnerEnabled();
|
|
53
|
+
const frames = opts.frames && opts.frames.length > 0 ? opts.frames : DEFAULT_FRAMES;
|
|
54
|
+
const intervalMs = opts.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
55
|
+
const color = opts.color ?? !process.env["NO_COLOR"];
|
|
56
|
+
const now = opts.now ?? (() => performance.now());
|
|
57
|
+
const setIntervalImpl = opts.setIntervalImpl ??
|
|
58
|
+
((fn, ms) => setInterval(fn, ms));
|
|
59
|
+
const clearIntervalImpl = opts.clearIntervalImpl ??
|
|
60
|
+
((handle) => clearInterval(handle));
|
|
61
|
+
// Color helpers collapse to identity when color is off (NO_COLOR), so the
|
|
62
|
+
// animation still shows — just monochrome.
|
|
63
|
+
const dim = (s) => (color ? `${DIM}${s}${RESET}` : s);
|
|
64
|
+
const accent = (s) => (color ? `${CYAN}${s}${RESET}` : s);
|
|
65
|
+
let handle;
|
|
66
|
+
let frame = 0;
|
|
67
|
+
let label = "";
|
|
68
|
+
let prefix = "";
|
|
69
|
+
let startedAt = 0;
|
|
70
|
+
let active = false;
|
|
71
|
+
function render() {
|
|
72
|
+
const glyph = frames[frame % frames.length] ?? "";
|
|
73
|
+
const elapsedMs = now() - startedAt;
|
|
74
|
+
// Only surface elapsed seconds once it's worth reading, so quick turns
|
|
75
|
+
// don't flash "(0s)".
|
|
76
|
+
const elapsed = elapsedMs >= 1000 ? ` ${dim(`(${Math.floor(elapsedMs / 1000)}s)`)}` : "";
|
|
77
|
+
rawWrite(`${CLEAR_LINE}${prefix}${accent(glyph)} ${dim(`${label}…`)}${elapsed}`);
|
|
78
|
+
}
|
|
79
|
+
const spinner = {
|
|
80
|
+
get active() {
|
|
81
|
+
return active;
|
|
82
|
+
},
|
|
83
|
+
start(newLabel, startOpts) {
|
|
84
|
+
if (!enabled)
|
|
85
|
+
return;
|
|
86
|
+
label = newLabel;
|
|
87
|
+
if (startOpts?.prefix !== undefined)
|
|
88
|
+
prefix = startOpts.prefix;
|
|
89
|
+
if (active) {
|
|
90
|
+
render();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
active = true;
|
|
94
|
+
frame = 0;
|
|
95
|
+
startedAt = now();
|
|
96
|
+
rawWrite(HIDE_CURSOR);
|
|
97
|
+
render();
|
|
98
|
+
handle = setIntervalImpl(() => {
|
|
99
|
+
frame += 1;
|
|
100
|
+
render();
|
|
101
|
+
}, intervalMs);
|
|
102
|
+
// Never let the heartbeat keep an otherwise-idle process alive.
|
|
103
|
+
handle.unref?.();
|
|
104
|
+
},
|
|
105
|
+
setLabel(newLabel) {
|
|
106
|
+
if (!active)
|
|
107
|
+
return;
|
|
108
|
+
label = newLabel;
|
|
109
|
+
render();
|
|
110
|
+
},
|
|
111
|
+
stop() {
|
|
112
|
+
if (!active)
|
|
113
|
+
return;
|
|
114
|
+
active = false;
|
|
115
|
+
if (handle !== undefined) {
|
|
116
|
+
clearIntervalImpl(handle);
|
|
117
|
+
handle = undefined;
|
|
118
|
+
}
|
|
119
|
+
// Erase the glyph, keep the prefix, restore the cursor. The cursor sits
|
|
120
|
+
// right after `prefix`, so streamed text continues the same line.
|
|
121
|
+
rawWrite(`${CLEAR_LINE}${prefix}${SHOW_CURSOR}`);
|
|
122
|
+
prefix = "";
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
return {
|
|
126
|
+
spinner,
|
|
127
|
+
write(s) {
|
|
128
|
+
// Erase the live animation before foreign output so they never overlap;
|
|
129
|
+
// the interval redraws on its next tick (on whatever line we leave the
|
|
130
|
+
// cursor — newline-terminated status lines therefore stack cleanly above
|
|
131
|
+
// the animation).
|
|
132
|
+
if (active)
|
|
133
|
+
rawWrite(CLEAR_LINE);
|
|
134
|
+
rawWrite(s);
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Decide whether the working-indicator spinner should animate, based on env
|
|
140
|
+
* and TTY. Centralized so callers don't repeat the parse.
|
|
141
|
+
*
|
|
142
|
+
* Disabled when: stdout is not a TTY (pipes, redirects, CI, tests); the
|
|
143
|
+
* terminal is `dumb`; or `CREWHAUS_SPINNER` is `0`/`false`/`off`/`no`. Any
|
|
144
|
+
* other explicit `CREWHAUS_SPINNER` value forces it on (still TTY-gated).
|
|
145
|
+
*/
|
|
146
|
+
export function isSpinnerEnabled(env = process.env, isTTY = Boolean(process.stdout.isTTY)) {
|
|
147
|
+
const raw = env["CREWHAUS_SPINNER"];
|
|
148
|
+
if (raw !== undefined) {
|
|
149
|
+
const v = raw.trim().toLowerCase();
|
|
150
|
+
if (v === "0" || v === "false" || v === "off" || v === "no")
|
|
151
|
+
return false;
|
|
152
|
+
return isTTY;
|
|
153
|
+
}
|
|
154
|
+
if (!isTTY)
|
|
155
|
+
return false;
|
|
156
|
+
if ((env["TERM"] ?? "").toLowerCase() === "dumb")
|
|
157
|
+
return false;
|
|
158
|
+
return true;
|
|
159
|
+
}
|
package/package.json
CHANGED
|
@@ -1,59 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/runtime-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Minimal runtime imported by generated harness bundles",
|
|
6
|
-
"main": "
|
|
7
|
-
"types": "
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
-
".":
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
10
13
|
},
|
|
11
14
|
"scripts": {
|
|
12
15
|
"test": "bun test src"
|
|
13
16
|
},
|
|
14
17
|
"dependencies": {
|
|
15
18
|
"@anthropic-ai/sdk": "^0.96.0",
|
|
16
|
-
"@crewhaus/abort-controller": "0.1.
|
|
17
|
-
"@crewhaus/adapter-anthropic": "0.1.
|
|
18
|
-
"@crewhaus/agent-context-isolation": "0.1.
|
|
19
|
-
"@crewhaus/boundary-classifier": "0.1.
|
|
20
|
-
"@crewhaus/circuit-breaker": "0.1.
|
|
21
|
-
"@crewhaus/compaction-autocompact": "0.1.
|
|
22
|
-
"@crewhaus/compaction-snip": "0.1.
|
|
23
|
-
"@crewhaus/cost-tracker": "0.1.
|
|
24
|
-
"@crewhaus/egress-classifier": "0.1.
|
|
25
|
-
"@crewhaus/errors": "0.1.
|
|
26
|
-
"@crewhaus/event-log": "0.1.
|
|
27
|
-
"@crewhaus/hooks-engine": "0.1.
|
|
28
|
-
"@crewhaus/model-router": "0.1.
|
|
29
|
-
"@crewhaus/permission-engine": "0.1.
|
|
30
|
-
"@crewhaus/prompt-cache-manager": "0.1.
|
|
31
|
-
"@crewhaus/prompt-injection-detector": "0.1.
|
|
32
|
-
"@crewhaus/rate-limiter": "0.1.
|
|
33
|
-
"@crewhaus/recovery-engine": "0.1.
|
|
34
|
-
"@crewhaus/run-context": "0.1.
|
|
35
|
-
"@crewhaus/session-store": "0.1.
|
|
36
|
-
"@crewhaus/skills-registry": "0.1.
|
|
37
|
-
"@crewhaus/slash-commands": "0.1.
|
|
38
|
-
"@crewhaus/state-store": "0.1.
|
|
39
|
-
"@crewhaus/tenancy": "0.1.
|
|
40
|
-
"@crewhaus/token-budget": "0.1.
|
|
41
|
-
"@crewhaus/tool-catalog": "0.1.
|
|
42
|
-
"@crewhaus/tool-executor": "0.1.
|
|
43
|
-
"@crewhaus/tool-loop-detection": "0.1.
|
|
44
|
-
"@crewhaus/tool-orchestrator": "0.1.
|
|
45
|
-
"@crewhaus/tool-result-store": "0.1.
|
|
46
|
-
"@crewhaus/streaming-tool-executor": "0.1.
|
|
47
|
-
"@crewhaus/turn-state-machine": "0.1.
|
|
48
|
-
"@crewhaus/trace-event-bus": "0.1.
|
|
49
|
-
"@crewhaus/structured-event-printer": "0.1.
|
|
50
|
-
"@crewhaus/metrics-collector": "0.1.
|
|
51
|
-
"@crewhaus/otel-exporter": "0.1.
|
|
19
|
+
"@crewhaus/abort-controller": "0.1.6",
|
|
20
|
+
"@crewhaus/adapter-anthropic": "0.1.6",
|
|
21
|
+
"@crewhaus/agent-context-isolation": "0.1.6",
|
|
22
|
+
"@crewhaus/boundary-classifier": "0.1.6",
|
|
23
|
+
"@crewhaus/circuit-breaker": "0.1.6",
|
|
24
|
+
"@crewhaus/compaction-autocompact": "0.1.6",
|
|
25
|
+
"@crewhaus/compaction-snip": "0.1.6",
|
|
26
|
+
"@crewhaus/cost-tracker": "0.1.6",
|
|
27
|
+
"@crewhaus/egress-classifier": "0.1.6",
|
|
28
|
+
"@crewhaus/errors": "0.1.6",
|
|
29
|
+
"@crewhaus/event-log": "0.1.6",
|
|
30
|
+
"@crewhaus/hooks-engine": "0.1.6",
|
|
31
|
+
"@crewhaus/model-router": "0.1.6",
|
|
32
|
+
"@crewhaus/permission-engine": "0.1.6",
|
|
33
|
+
"@crewhaus/prompt-cache-manager": "0.1.6",
|
|
34
|
+
"@crewhaus/prompt-injection-detector": "0.1.6",
|
|
35
|
+
"@crewhaus/rate-limiter": "0.1.6",
|
|
36
|
+
"@crewhaus/recovery-engine": "0.1.6",
|
|
37
|
+
"@crewhaus/run-context": "0.1.6",
|
|
38
|
+
"@crewhaus/session-store": "0.1.6",
|
|
39
|
+
"@crewhaus/skills-registry": "0.1.6",
|
|
40
|
+
"@crewhaus/slash-commands": "0.1.6",
|
|
41
|
+
"@crewhaus/state-store": "0.1.6",
|
|
42
|
+
"@crewhaus/tenancy": "0.1.6",
|
|
43
|
+
"@crewhaus/token-budget": "0.1.6",
|
|
44
|
+
"@crewhaus/tool-catalog": "0.1.6",
|
|
45
|
+
"@crewhaus/tool-executor": "0.1.6",
|
|
46
|
+
"@crewhaus/tool-loop-detection": "0.1.6",
|
|
47
|
+
"@crewhaus/tool-orchestrator": "0.1.6",
|
|
48
|
+
"@crewhaus/tool-result-store": "0.1.6",
|
|
49
|
+
"@crewhaus/streaming-tool-executor": "0.1.6",
|
|
50
|
+
"@crewhaus/turn-state-machine": "0.1.6",
|
|
51
|
+
"@crewhaus/trace-event-bus": "0.1.6",
|
|
52
|
+
"@crewhaus/structured-event-printer": "0.1.6",
|
|
53
|
+
"@crewhaus/metrics-collector": "0.1.6",
|
|
54
|
+
"@crewhaus/otel-exporter": "0.1.6",
|
|
52
55
|
"zod-to-json-schema": "^3.23.5"
|
|
53
56
|
},
|
|
54
57
|
"devDependencies": {
|
|
55
|
-
"@crewhaus/logging": "0.1.
|
|
56
|
-
"@crewhaus/tool-builder": "0.1.
|
|
58
|
+
"@crewhaus/logging": "0.1.6",
|
|
59
|
+
"@crewhaus/tool-builder": "0.1.6",
|
|
57
60
|
"zod": "^3.23.8"
|
|
58
61
|
},
|
|
59
62
|
"license": "Apache-2.0",
|
|
@@ -74,5 +77,5 @@
|
|
|
74
77
|
"publishConfig": {
|
|
75
78
|
"access": "public"
|
|
76
79
|
},
|
|
77
|
-
"files": ["
|
|
80
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
78
81
|
}
|