@crewhaus/runtime-core 0.1.5 → 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/index.d.ts +8 -0
- package/dist/index.js +80 -12
- package/dist/spinner.d.ts +106 -0
- package/dist/spinner.js +159 -0
- package/package.json +39 -39
package/dist/index.d.ts
CHANGED
|
@@ -145,6 +145,14 @@ export type RunChatLoopOptions = {
|
|
|
145
145
|
* (mid-stream) rather than waiting for the full response. Default: false.
|
|
146
146
|
*/
|
|
147
147
|
streaming?: boolean;
|
|
148
|
+
/**
|
|
149
|
+
* Animate a "working" indicator (spinner + status label) on the otherwise
|
|
150
|
+
* silent waits — model thinking, tool execution, retry/compaction. When
|
|
151
|
+
* omitted, auto-enables only for an interactive REPL on a TTY with a
|
|
152
|
+
* spinner-friendly env (see `isSpinnerEnabled`); force off with `false`.
|
|
153
|
+
* `singleTurn` and injected-`input` runs never spin.
|
|
154
|
+
*/
|
|
155
|
+
spinner?: boolean;
|
|
148
156
|
/**
|
|
149
157
|
* Override the directory under which session metadata `.json` files and
|
|
150
158
|
* event-log `.jsonl` files live. Defaults to `.crewhaus/sessions`.
|
package/dist/index.js
CHANGED
|
@@ -32,6 +32,7 @@ import { zodToJsonSchema } from "zod-to-json-schema";
|
|
|
32
32
|
import { createCliMarkdownRenderer, isCliMarkdownEnabled, } from "./cli-markdown";
|
|
33
33
|
import { attachDefaultSubscribers } from "./observability";
|
|
34
34
|
import { loadProjectMemory } from "./project-memory";
|
|
35
|
+
import { createCliOutput, isSpinnerEnabled } from "./spinner";
|
|
35
36
|
/**
|
|
36
37
|
* Slice-scope runtime: a multi-turn streaming chat loop with prompt
|
|
37
38
|
* caching, tool execution, pre-turn context compaction, recovery taxonomy,
|
|
@@ -443,25 +444,39 @@ export async function runChatLoop(opts) {
|
|
|
443
444
|
const bus = runContext.eventBus;
|
|
444
445
|
void TraceEventBus; // keep type import alive for future direct constructions
|
|
445
446
|
const subscribers = await attachDefaultSubscribers(bus, runContext);
|
|
447
|
+
// Working-indicator spinner. Auto-enables only for an interactive REPL on a
|
|
448
|
+
// TTY (see `isSpinnerEnabled`); `singleTurn`/injected-`input`/piped runs stay
|
|
449
|
+
// byte-identical to before. `out.write` is the spinner-aware stdout sink:
|
|
450
|
+
// every interactive write that can land while the animation is live goes
|
|
451
|
+
// through it so the two never collide. `opts.spinner` overrides the auto
|
|
452
|
+
// decision.
|
|
453
|
+
const spinnerEnabled = opts.spinner ?? (opts.singleTurn !== true && opts.input === undefined && isSpinnerEnabled());
|
|
454
|
+
const out = createCliOutput({ enabled: spinnerEnabled });
|
|
446
455
|
// M2.1 — CLI markdown renderer (env-gated). When CREWHAUS_CLI_MARKDOWN=1,
|
|
447
456
|
// text-delta chunks flow through a streaming markdown → ANSI transform so
|
|
448
457
|
// the user sees rendered bold/italic/headers/lists/code-fences instead of
|
|
449
458
|
// raw asterisks. The renderer is line-buffered; chunks accumulate until a
|
|
450
459
|
// `\n` arrives, then the rendered line writes to stdout. `end()` is
|
|
451
|
-
// called after the per-turn `\n` to flush any tail content.
|
|
460
|
+
// called after the per-turn `\n` to flush any tail content. Its sink is the
|
|
461
|
+
// spinner-aware writer so a flushed line erases any live animation first.
|
|
452
462
|
const mdRenderer = isCliMarkdownEnabled()
|
|
453
|
-
? createCliMarkdownRenderer()
|
|
463
|
+
? createCliMarkdownRenderer({ write: (s) => out.write(s) })
|
|
454
464
|
: undefined;
|
|
455
465
|
const writeText = (chunk) => {
|
|
466
|
+
// First real assistant text ends the "thinking" wait; clear the spinner
|
|
467
|
+
// (idempotent on later chunks) before the answer streams.
|
|
468
|
+
out.spinner.stop();
|
|
456
469
|
if (mdRenderer)
|
|
457
470
|
mdRenderer.push(chunk);
|
|
458
471
|
else
|
|
459
|
-
|
|
472
|
+
out.write(chunk);
|
|
460
473
|
};
|
|
461
474
|
const endTurn = () => {
|
|
475
|
+
// Covers the no-text/no-tool case where the spinner is still up.
|
|
476
|
+
out.spinner.stop();
|
|
462
477
|
if (mdRenderer)
|
|
463
478
|
mdRenderer.end();
|
|
464
|
-
|
|
479
|
+
out.write("\n");
|
|
465
480
|
};
|
|
466
481
|
const eventLog = await openEventLog(sessionId, { rootDir: sessionRootDir });
|
|
467
482
|
// Section 27 — mirror per-call cost_accrual events from the trace bus into
|
|
@@ -656,6 +671,27 @@ export async function runChatLoop(opts) {
|
|
|
656
671
|
// signature.
|
|
657
672
|
const toolUseHistory = [];
|
|
658
673
|
const warnedLoopSignatures = new Set();
|
|
674
|
+
// Working-indicator bookkeeping for tool execution. A single shared spinner
|
|
675
|
+
// serves the whole loop, so the set tracks which tools are mid-flight to
|
|
676
|
+
// support the concurrent (read-only) partition: the label reflects how many
|
|
677
|
+
// run at once, and the animation only stops when the last one settles.
|
|
678
|
+
const activeToolNames = [];
|
|
679
|
+
const toolSpinnerLabel = () => activeToolNames.length === 1
|
|
680
|
+
? `running ${activeToolNames[0]}`
|
|
681
|
+
: `running ${activeToolNames.length} tools`;
|
|
682
|
+
const beginToolWork = (name) => {
|
|
683
|
+
activeToolNames.push(name);
|
|
684
|
+
out.spinner.start(toolSpinnerLabel());
|
|
685
|
+
};
|
|
686
|
+
const endToolWork = (name) => {
|
|
687
|
+
const i = activeToolNames.indexOf(name);
|
|
688
|
+
if (i >= 0)
|
|
689
|
+
activeToolNames.splice(i, 1);
|
|
690
|
+
if (activeToolNames.length === 0)
|
|
691
|
+
out.spinner.stop();
|
|
692
|
+
else
|
|
693
|
+
out.spinner.setLabel(toolSpinnerLabel());
|
|
694
|
+
};
|
|
659
695
|
/**
|
|
660
696
|
* Execute one tool_use block end-to-end: permission gate → executeTool
|
|
661
697
|
* with the per-tool abort signal → wrap large output through
|
|
@@ -666,7 +702,16 @@ export async function runChatLoop(opts) {
|
|
|
666
702
|
* path so the permission/abort/store contract is uniform.
|
|
667
703
|
*/
|
|
668
704
|
async function executeOneToolUse(tu) {
|
|
669
|
-
|
|
705
|
+
// End the "thinking" wait — but only when no tool is already mid-flight.
|
|
706
|
+
// The streaming executor dispatches concurrency-safe tools with overlap, so
|
|
707
|
+
// an unconditional stop here would tear down a sibling tool's live spinner;
|
|
708
|
+
// gate on the ref-count so we stop the thinking animation (none running)
|
|
709
|
+
// without disturbing a running-tools one. The header then goes through the
|
|
710
|
+
// spinner-aware sink, which erases+redraws around it so the persistent
|
|
711
|
+
// `[tool: …]` line sits cleanly above any animation that follows.
|
|
712
|
+
if (activeToolNames.length === 0)
|
|
713
|
+
out.spinner.stop();
|
|
714
|
+
out.write(`[tool: ${tu.name}]\n`);
|
|
670
715
|
await logEvent("tool_use", { id: tu.id, name: tu.name, input: tu.input });
|
|
671
716
|
const inputBytes = Buffer.byteLength(JSON.stringify(tu.input ?? null), "utf8");
|
|
672
717
|
const toolStartEnvelope = bus.envelope();
|
|
@@ -942,6 +987,10 @@ export async function runChatLoop(opts) {
|
|
|
942
987
|
...(opts.spawnSubAgent !== undefined ? { spawnSubAgent: opts.spawnSubAgent } : {}),
|
|
943
988
|
...(opts.crewMailbox !== undefined ? { crewMailbox: opts.crewMailbox } : {}),
|
|
944
989
|
};
|
|
990
|
+
// Spin "running <tool>…" for exactly the execution window — started after
|
|
991
|
+
// every gate (permission/justification/egress) so it never overlaps the
|
|
992
|
+
// approval prompt, and torn down in `.finally` on success or throw.
|
|
993
|
+
beginToolWork(tu.name);
|
|
945
994
|
const raw = await executeTool(tool, tu.input, {
|
|
946
995
|
toolUseId: tu.id,
|
|
947
996
|
signal: toolAbort.signal,
|
|
@@ -969,7 +1018,7 @@ export async function runChatLoop(opts) {
|
|
|
969
1018
|
bytes: Buffer.byteLength(chunk, "utf8"),
|
|
970
1019
|
}, { ephemeral: true });
|
|
971
1020
|
},
|
|
972
|
-
});
|
|
1021
|
+
}).finally(() => endToolWork(tu.name));
|
|
973
1022
|
const toolResultRoot = resolveToolResultRoot();
|
|
974
1023
|
const stored = await storeAndPreview({ toolUseId: raw.toolUseId, content: raw.content, isError: raw.isError }, {
|
|
975
1024
|
runId: runContext.runId,
|
|
@@ -1201,7 +1250,7 @@ export async function runChatLoop(opts) {
|
|
|
1201
1250
|
}
|
|
1202
1251
|
switch (state.kind) {
|
|
1203
1252
|
case "NeedModel": {
|
|
1204
|
-
|
|
1253
|
+
out.write("agent> ");
|
|
1205
1254
|
// Section 11 — pre-model hook. Deny short-circuits the turn with
|
|
1206
1255
|
// a synthetic "[blocked by hook]" assistant message so the loop
|
|
1207
1256
|
// exits cleanly (state transitions through ModelReturnedText →
|
|
@@ -1213,7 +1262,7 @@ export async function runChatLoop(opts) {
|
|
|
1213
1262
|
});
|
|
1214
1263
|
if (!preModel.allowed) {
|
|
1215
1264
|
const blockedText = `[blocked by hook] ${preModel.reason ?? "denied"}`;
|
|
1216
|
-
|
|
1265
|
+
out.write(`${blockedText}\n`);
|
|
1217
1266
|
const blockedBlock = {
|
|
1218
1267
|
type: "text",
|
|
1219
1268
|
text: blockedText,
|
|
@@ -1225,6 +1274,12 @@ export async function runChatLoop(opts) {
|
|
|
1225
1274
|
state = transition(state, { kind: "ModelReturnedText" });
|
|
1226
1275
|
break;
|
|
1227
1276
|
}
|
|
1277
|
+
// Animate "thinking…" through the model wait. The `agent> ` prefix
|
|
1278
|
+
// is kept across redraws and left behind when the spinner stops on
|
|
1279
|
+
// the first text delta (`writeText`) or tool header — so the silent
|
|
1280
|
+
// gap before the model responds now shows live progress. Cleared in
|
|
1281
|
+
// the catch below on any model-call error.
|
|
1282
|
+
out.spinner.start("thinking", { prefix: "agent> " });
|
|
1228
1283
|
try {
|
|
1229
1284
|
// Section 27 — rate-limit the model call before opening the
|
|
1230
1285
|
// stream. The keys are caller-configured (typically
|
|
@@ -1467,6 +1522,8 @@ export async function runChatLoop(opts) {
|
|
|
1467
1522
|
}
|
|
1468
1523
|
}
|
|
1469
1524
|
catch (err) {
|
|
1525
|
+
// Tear down the "thinking" animation before any error/abort output.
|
|
1526
|
+
out.spinner.stop();
|
|
1470
1527
|
if (isAbortError(err)) {
|
|
1471
1528
|
state = transition(state, { kind: "Aborted" });
|
|
1472
1529
|
break;
|
|
@@ -1537,6 +1594,8 @@ export async function runChatLoop(opts) {
|
|
|
1537
1594
|
case "compact": {
|
|
1538
1595
|
const before = messages.length;
|
|
1539
1596
|
await fireHook("pre-compact", { kind: "reactive", before });
|
|
1597
|
+
// Reactive compaction summarizes via a model call — show the wait.
|
|
1598
|
+
out.spinner.start("compacting context");
|
|
1540
1599
|
const compacted = await forceCompact({
|
|
1541
1600
|
messages,
|
|
1542
1601
|
adapter: compactionAdapter,
|
|
@@ -1544,7 +1603,7 @@ export async function runChatLoop(opts) {
|
|
|
1544
1603
|
snipKeepHead,
|
|
1545
1604
|
snipKeepTail,
|
|
1546
1605
|
logger: runContext.logger,
|
|
1547
|
-
});
|
|
1606
|
+
}).finally(() => out.spinner.stop());
|
|
1548
1607
|
messages.length = 0;
|
|
1549
1608
|
messages.push(...compacted);
|
|
1550
1609
|
await logEvent("compaction", {
|
|
@@ -1569,7 +1628,10 @@ export async function runChatLoop(opts) {
|
|
|
1569
1628
|
break;
|
|
1570
1629
|
}
|
|
1571
1630
|
case "retry":
|
|
1631
|
+
// Surface the back-off wait instead of stalling silently.
|
|
1632
|
+
out.spinner.start("retrying");
|
|
1572
1633
|
await new Promise((resolve) => setTimeout(resolve, action.delayMs));
|
|
1634
|
+
out.spinner.stop();
|
|
1573
1635
|
state = transition(state, { kind: "RecoveryDone" });
|
|
1574
1636
|
break;
|
|
1575
1637
|
case "continue": {
|
|
@@ -1695,6 +1757,7 @@ export async function runChatLoop(opts) {
|
|
|
1695
1757
|
.join("");
|
|
1696
1758
|
}
|
|
1697
1759
|
finally {
|
|
1760
|
+
out.spinner.stop();
|
|
1698
1761
|
await fireHook("stop", {
|
|
1699
1762
|
sessionId,
|
|
1700
1763
|
turnCount: runContext.turnNumber,
|
|
@@ -1777,13 +1840,15 @@ export async function runChatLoop(opts) {
|
|
|
1777
1840
|
const shouldInstallSigint = opts.installSigintHandler ?? opts.input === undefined;
|
|
1778
1841
|
let sigintPresses = 0;
|
|
1779
1842
|
const sigintHandler = () => {
|
|
1843
|
+
// Clear any live animation (and restore the cursor) before the notice.
|
|
1844
|
+
out.spinner.stop();
|
|
1780
1845
|
sigintPresses += 1;
|
|
1781
1846
|
if (sigintPresses === 1) {
|
|
1782
|
-
|
|
1847
|
+
out.write("\n[turn aborted; press Ctrl-C again to exit]\n");
|
|
1783
1848
|
turnAbort.abort();
|
|
1784
1849
|
}
|
|
1785
1850
|
else {
|
|
1786
|
-
|
|
1851
|
+
out.write("\n[exiting]\n");
|
|
1787
1852
|
process.exit(130);
|
|
1788
1853
|
}
|
|
1789
1854
|
};
|
|
@@ -1881,9 +1946,11 @@ export async function runChatLoop(opts) {
|
|
|
1881
1946
|
await runOneTurn(messages);
|
|
1882
1947
|
}
|
|
1883
1948
|
catch (err) {
|
|
1949
|
+
// Defensive: tear down any animation a thrown turn left spinning.
|
|
1950
|
+
out.spinner.stop();
|
|
1884
1951
|
if (isAbortError(err)) {
|
|
1885
1952
|
// Already-handled abort; loop back to the prompt.
|
|
1886
|
-
|
|
1953
|
+
out.write("\n[turn aborted]\n");
|
|
1887
1954
|
}
|
|
1888
1955
|
else {
|
|
1889
1956
|
throw err;
|
|
@@ -1901,6 +1968,7 @@ export async function runChatLoop(opts) {
|
|
|
1901
1968
|
}
|
|
1902
1969
|
}
|
|
1903
1970
|
finally {
|
|
1971
|
+
out.spinner.stop();
|
|
1904
1972
|
await fireHook("stop", {
|
|
1905
1973
|
sessionId,
|
|
1906
1974
|
turnCount: runContext.turnNumber,
|
|
@@ -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,6 +1,6 @@
|
|
|
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
6
|
"main": "dist/index.js",
|
|
@@ -16,47 +16,47 @@
|
|
|
16
16
|
},
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@anthropic-ai/sdk": "^0.96.0",
|
|
19
|
-
"@crewhaus/abort-controller": "0.1.
|
|
20
|
-
"@crewhaus/adapter-anthropic": "0.1.
|
|
21
|
-
"@crewhaus/agent-context-isolation": "0.1.
|
|
22
|
-
"@crewhaus/boundary-classifier": "0.1.
|
|
23
|
-
"@crewhaus/circuit-breaker": "0.1.
|
|
24
|
-
"@crewhaus/compaction-autocompact": "0.1.
|
|
25
|
-
"@crewhaus/compaction-snip": "0.1.
|
|
26
|
-
"@crewhaus/cost-tracker": "0.1.
|
|
27
|
-
"@crewhaus/egress-classifier": "0.1.
|
|
28
|
-
"@crewhaus/errors": "0.1.
|
|
29
|
-
"@crewhaus/event-log": "0.1.
|
|
30
|
-
"@crewhaus/hooks-engine": "0.1.
|
|
31
|
-
"@crewhaus/model-router": "0.1.
|
|
32
|
-
"@crewhaus/permission-engine": "0.1.
|
|
33
|
-
"@crewhaus/prompt-cache-manager": "0.1.
|
|
34
|
-
"@crewhaus/prompt-injection-detector": "0.1.
|
|
35
|
-
"@crewhaus/rate-limiter": "0.1.
|
|
36
|
-
"@crewhaus/recovery-engine": "0.1.
|
|
37
|
-
"@crewhaus/run-context": "0.1.
|
|
38
|
-
"@crewhaus/session-store": "0.1.
|
|
39
|
-
"@crewhaus/skills-registry": "0.1.
|
|
40
|
-
"@crewhaus/slash-commands": "0.1.
|
|
41
|
-
"@crewhaus/state-store": "0.1.
|
|
42
|
-
"@crewhaus/tenancy": "0.1.
|
|
43
|
-
"@crewhaus/token-budget": "0.1.
|
|
44
|
-
"@crewhaus/tool-catalog": "0.1.
|
|
45
|
-
"@crewhaus/tool-executor": "0.1.
|
|
46
|
-
"@crewhaus/tool-loop-detection": "0.1.
|
|
47
|
-
"@crewhaus/tool-orchestrator": "0.1.
|
|
48
|
-
"@crewhaus/tool-result-store": "0.1.
|
|
49
|
-
"@crewhaus/streaming-tool-executor": "0.1.
|
|
50
|
-
"@crewhaus/turn-state-machine": "0.1.
|
|
51
|
-
"@crewhaus/trace-event-bus": "0.1.
|
|
52
|
-
"@crewhaus/structured-event-printer": "0.1.
|
|
53
|
-
"@crewhaus/metrics-collector": "0.1.
|
|
54
|
-
"@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",
|
|
55
55
|
"zod-to-json-schema": "^3.23.5"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
|
-
"@crewhaus/logging": "0.1.
|
|
59
|
-
"@crewhaus/tool-builder": "0.1.
|
|
58
|
+
"@crewhaus/logging": "0.1.6",
|
|
59
|
+
"@crewhaus/tool-builder": "0.1.6",
|
|
60
60
|
"zod": "^3.23.8"
|
|
61
61
|
},
|
|
62
62
|
"license": "Apache-2.0",
|