@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.
@@ -0,0 +1,56 @@
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
+ export interface StreamRenderer {
29
+ /** Push an incoming text chunk. Renders + flushes completed lines. */
30
+ push(chunk: string): void;
31
+ /** Flush any remaining buffered content (no newline appended). */
32
+ end(): void;
33
+ }
34
+ export interface RendererOptions {
35
+ /** Override the output sink. Defaults to `process.stdout.write`. */
36
+ readonly write?: (s: string) => void;
37
+ }
38
+ /**
39
+ * Construct a streaming markdown renderer. Returns a `StreamRenderer` with
40
+ * `push(chunk)` and `end()` methods.
41
+ *
42
+ * Usage:
43
+ * ```ts
44
+ * const r = createCliMarkdownRenderer();
45
+ * r.push("hello **world**\n");
46
+ * r.push("`code` ");
47
+ * r.push("done\n");
48
+ * r.end();
49
+ * ```
50
+ */
51
+ export declare function createCliMarkdownRenderer(opts?: RendererOptions): StreamRenderer;
52
+ /**
53
+ * Decide whether to activate the CLI markdown renderer based on env.
54
+ * Centralized so callers don't repeat the parse.
55
+ */
56
+ export declare function isCliMarkdownEnabled(env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,164 @@
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
+ const RESET = "\x1b[0m";
29
+ const BOLD = "\x1b[1m";
30
+ const DIM = "\x1b[2m";
31
+ const ITALIC = "\x1b[3m";
32
+ const CYAN = "\x1b[36m";
33
+ const MAGENTA = "\x1b[35m";
34
+ const YELLOW = "\x1b[33m";
35
+ const GREEN = "\x1b[32m";
36
+ /** Heading levels 1..6 → color + bold. Level 0 is "no heading". */
37
+ const HEADING_COLORS = [
38
+ "",
39
+ `${BOLD}${CYAN}`, // h1
40
+ `${BOLD}${MAGENTA}`, // h2
41
+ `${BOLD}${YELLOW}`, // h3
42
+ BOLD, // h4
43
+ BOLD, // h5
44
+ BOLD, // h6
45
+ ];
46
+ /**
47
+ * Construct a streaming markdown renderer. Returns a `StreamRenderer` with
48
+ * `push(chunk)` and `end()` methods.
49
+ *
50
+ * Usage:
51
+ * ```ts
52
+ * const r = createCliMarkdownRenderer();
53
+ * r.push("hello **world**\n");
54
+ * r.push("`code` ");
55
+ * r.push("done\n");
56
+ * r.end();
57
+ * ```
58
+ */
59
+ export function createCliMarkdownRenderer(opts = {}) {
60
+ const write = opts.write ?? ((s) => process.stdout.write(s));
61
+ let buf = "";
62
+ let inCodeFence = false;
63
+ let codeFenceLang = "";
64
+ function flushLine(line) {
65
+ write(`${renderLine(line)}\n`);
66
+ }
67
+ function renderLine(line) {
68
+ // Code-fence delimiter — toggles state, dims the fence itself.
69
+ const fence = /^(\s*)```\s*(\S*)\s*$/.exec(line);
70
+ if (fence) {
71
+ if (!inCodeFence) {
72
+ inCodeFence = true;
73
+ codeFenceLang = fence[2] ?? "";
74
+ return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${codeFenceLang}${RESET}`;
75
+ }
76
+ inCodeFence = false;
77
+ const langSuffix = codeFenceLang ? ` (${codeFenceLang})` : "";
78
+ codeFenceLang = "";
79
+ return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${langSuffix}${RESET}`;
80
+ }
81
+ if (inCodeFence) {
82
+ // Inside a fenced block — dim everything; preserve indentation.
83
+ return `${DIM}${line}${RESET}`;
84
+ }
85
+ // Headings
86
+ const heading = /^(\s*)(#{1,6})\s+(.*)$/.exec(line);
87
+ if (heading) {
88
+ const indent = heading[1] ?? "";
89
+ const level = (heading[2] ?? "").length;
90
+ const text = heading[3] ?? "";
91
+ const color = HEADING_COLORS[level] ?? BOLD;
92
+ return `${indent}${color}${renderInline(text)}${RESET}`;
93
+ }
94
+ // Unordered list bullets — replace marker with a pretty bullet.
95
+ const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
96
+ if (bullet) {
97
+ return `${bullet[1] ?? ""}${CYAN}•${RESET} ${renderInline(bullet[2] ?? "")}`;
98
+ }
99
+ // Ordered list — keep the number, color it.
100
+ const numbered = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
101
+ if (numbered) {
102
+ return `${numbered[1] ?? ""}${CYAN}${numbered[2]}.${RESET} ${renderInline(numbered[3] ?? "")}`;
103
+ }
104
+ // Blockquote
105
+ const quote = /^(\s*)>\s?(.*)$/.exec(line);
106
+ if (quote) {
107
+ return `${quote[1] ?? ""}${DIM}│${RESET} ${ITALIC}${renderInline(quote[2] ?? "")}${RESET}`;
108
+ }
109
+ // Horizontal rule
110
+ if (/^\s*(-{3,}|_{3,}|\*{3,})\s*$/.test(line)) {
111
+ return `${DIM}${"─".repeat(40)}${RESET}`;
112
+ }
113
+ return renderInline(line);
114
+ }
115
+ function renderInline(text) {
116
+ // Backtick-quoted inline code first (so its content isn't bold/italic-mangled).
117
+ // We do a placeholder-swap pass: extract code spans, then re-insert after styling.
118
+ const codeSpans = [];
119
+ let working = text.replace(/`([^`]+?)`/g, (_match, content) => {
120
+ codeSpans.push(content);
121
+ return ` CODE${codeSpans.length - 1} `;
122
+ });
123
+ // Bold: **text** or __text__ — non-greedy, doesn't span newlines.
124
+ working = working.replace(/\*\*([^*\n]+?)\*\*/g, (_m, t) => `${BOLD}${t}${RESET}`);
125
+ working = working.replace(/__([^_\n]+?)__/g, (_m, t) => `${BOLD}${t}${RESET}`);
126
+ // Italic: *text* or _text_ — guarded by word-boundary lookarounds so
127
+ // list bullets ("- foo") and snake_case identifiers don't false-match.
128
+ working = working.replace(/(^|[^*\w])\*([^*\n]+?)\*(?!\w)/g, (_m, p, t) => `${p}${ITALIC}${t}${RESET}`);
129
+ working = working.replace(/(^|[^_\w])_([^_\n]+?)_(?!\w)/g, (_m, p, t) => `${p}${ITALIC}${t}${RESET}`);
130
+ // Restore inline code spans with styling.
131
+ working = working.replace(/ CODE(\d+) /g, (_m, idx) => {
132
+ const content = codeSpans[Number(idx)] ?? "";
133
+ return `${DIM}${CYAN}\`${content}\`${RESET}`;
134
+ });
135
+ return working;
136
+ }
137
+ return {
138
+ push(chunk) {
139
+ buf += chunk;
140
+ let nl = buf.indexOf("\n");
141
+ while (nl !== -1) {
142
+ const line = buf.slice(0, nl);
143
+ buf = buf.slice(nl + 1);
144
+ flushLine(line);
145
+ nl = buf.indexOf("\n");
146
+ }
147
+ },
148
+ end() {
149
+ if (buf.length > 0) {
150
+ // Tail content with no terminating newline — render in place.
151
+ write(renderLine(buf));
152
+ buf = "";
153
+ }
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * Decide whether to activate the CLI markdown renderer based on env.
159
+ * Centralized so callers don't repeat the parse.
160
+ */
161
+ export function isCliMarkdownEnabled(env = process.env) {
162
+ const v = env["CREWHAUS_CLI_MARKDOWN"];
163
+ return v === "1" || v === "true";
164
+ }
@@ -0,0 +1,376 @@
1
+ import type Anthropic from "@anthropic-ai/sdk";
2
+ import { type ProviderAdapter } from "@crewhaus/adapter-anthropic";
3
+ import type { CrewMailbox, SpawnSubAgentFn, SubAgentDefinition } from "@crewhaus/agent-context-isolation";
4
+ import { type EgressMatcher, type SinkScope } from "@crewhaus/egress-classifier";
5
+ import { type EventLog } from "@crewhaus/event-log";
6
+ import { type HookDef } from "@crewhaus/hooks-engine";
7
+ import { type JustificationJudge, type PermissionMode, type RuleSet } from "@crewhaus/permission-engine";
8
+ import type { RateLimiter } from "@crewhaus/rate-limiter";
9
+ import { type RunContext } from "@crewhaus/run-context";
10
+ import { type SkillRef } from "@crewhaus/skills-registry";
11
+ import { type SlashCommand } from "@crewhaus/slash-commands";
12
+ import type { RegisteredTool } from "@crewhaus/tool-catalog";
13
+ export { CLAUDE_CODE_HEADERS, CLAUDE_CODE_SYSTEM_PREFIX, OAUTH_BETAS, createAnthropicClient, resolveAuth, } from "@crewhaus/adapter-anthropic";
14
+ export type { ResolvedAuth } from "@crewhaus/adapter-anthropic";
15
+ /**
16
+ * Reconcile a message history by dropping "orphan" `tool_use` blocks — a
17
+ * `tool_use` with no answering `tool_result` anywhere later in the
18
+ * conversation. The Claude Messages API requires every `tool_use` to be
19
+ * followed by a matching `tool_result`; an orphan makes every subsequent
20
+ * request 400 with `tool_use` ids "found without `tool_result` blocks
21
+ * immediately after". Orphans are born when the model is cut off mid-`tool_use`
22
+ * by `stop_reason: "max_tokens"`: the partial call is never executed (so a
23
+ * result is never logged) and its input is truncated / `__parse_error`
24
+ * garbage, so the only safe reconciliation is to drop it and let the model
25
+ * re-issue the call. An assistant message left empty after stripping is
26
+ * removed entirely.
27
+ *
28
+ * Idempotent and a no-op on healthy histories. Applied on `--resume` replay
29
+ * (so a session bricked by a pre-fix runtime self-heals) and by the
30
+ * `tombstone` recovery action (a universal backstop for any path that still
31
+ * commits an orphan).
32
+ */
33
+ export declare function sanitizeOrphanToolUses(messages: ReadonlyArray<Anthropic.MessageParam>): {
34
+ messages: Anthropic.MessageParam[];
35
+ removed: number;
36
+ };
37
+ /**
38
+ * Walk an `EventLog` and reconstruct the SDK message history. Only
39
+ * `user_message` and `assistant_message` events contribute — `tool_use`
40
+ * and `tool_result` events are audit-only because the same data already
41
+ * lives inside the assistant/user message content arrays. `error` and
42
+ * `compaction` events are observability-only and skipped.
43
+ *
44
+ * Exported so consumers (the `--resume` path in `apps/cli`, the T4
45
+ * replay test, and any future inspector) can reproduce the same history
46
+ * the runtime would build.
47
+ */
48
+ export declare function replayMessageHistory(log: EventLog): Promise<Anthropic.MessageParam[]>;
49
+ /**
50
+ * Pillar 3 (FR-004) intent gate — the durable audit sink the justification
51
+ * gate appends to. Structurally a subset of `@crewhaus/audit-log`'s
52
+ * `AuditLog` (its `append({ kind, payload })`), declared here as a minimal
53
+ * interface so runtime-core does NOT take a dependency on (or a cycle with)
54
+ * `@crewhaus/audit-log`. The CLI/codegen passes a real `openAuditLog(...)`
55
+ * instance; tests pass an in-memory or tmp-dir-backed one. When omitted (the
56
+ * default for every existing caller), the gate writes nothing durable and the
57
+ * trace-bus `permission_decision` event remains the only surface — i.e. zero
58
+ * behaviour change unless a caller opts in.
59
+ *
60
+ * The `kind` the gate appends is exactly `"permission_justification_evaluated"`,
61
+ * the AuditKind `@crewhaus/audit-log` reserves for this signal; the payload is
62
+ * the documented verbatim shape `{ toolName, justification, verdict, reason,
63
+ * judgeModel, confidence? }` (the justification IS the audit artifact — stored
64
+ * verbatim, never redacted).
65
+ */
66
+ export type JustificationAuditSink = {
67
+ append(input: {
68
+ readonly kind: "permission_justification_evaluated";
69
+ readonly payload: unknown;
70
+ }): Promise<unknown>;
71
+ };
72
+ export type RunChatLoopOptions = {
73
+ model: string;
74
+ instructions: string;
75
+ maxTokens?: number;
76
+ /**
77
+ * Section 17 — optional override for the model used by
78
+ * `compaction-autocompact`. When undefined, compaction reuses
79
+ * `opts.model` (and therefore the same adapter). Set to a different
80
+ * model string (or even a different provider via the prefix
81
+ * conventions, e.g. `openai/gpt-4o-mini`) to route compaction
82
+ * elsewhere.
83
+ */
84
+ compactionModel?: string;
85
+ /**
86
+ * Test injection backdoor: pre-built ProviderAdapter that bypasses
87
+ * the model-router. When set, `model` is still the user-facing
88
+ * `agent.model` (used for trace events and as the `req.model` field
89
+ * passed to the adapter), but no router lookup happens.
90
+ *
91
+ * Used by sub-agent-spawner.test.ts and runtime-core.test.ts to
92
+ * inject scripted adapters; replaces the previous `client` /
93
+ * `isOAuth` injection contract.
94
+ */
95
+ _adapter?: ProviderAdapter;
96
+ /**
97
+ * Section 17 — same as `_adapter` but for the compaction model.
98
+ * When omitted, defaults to `_adapter` (or the routed primary).
99
+ */
100
+ _compactionAdapter?: ProviderAdapter;
101
+ /** Override the input stream (testing). Defaults to process.stdin. */
102
+ input?: NodeJS.ReadableStream;
103
+ /** Tools the model may invoke. When empty/undefined, tools are not advertised. */
104
+ tools?: ReadonlyArray<RegisteredTool>;
105
+ /** Per-run identity, abort signal, and logger. Defaults to a fresh `createRunContext()`. */
106
+ runContext?: RunContext;
107
+ /** Context-window limit in tokens. Defaults to 200_000 (Claude opus/sonnet 4.x). */
108
+ contextLimit?: number;
109
+ /** Fraction of `contextLimit` at which compaction kicks in. Defaults to 0.85. */
110
+ compactionThreshold?: number;
111
+ /** Number of head messages to keep when snipping. Defaults to 4. */
112
+ snipKeepHead?: number;
113
+ /** Number of tail messages to keep when snipping. Defaults to 20. */
114
+ snipKeepTail?: number;
115
+ /**
116
+ * Pre-loaded conversation history. In `singleTurn` mode this is the
117
+ * entire input; the last entry must be `role: "user"`.
118
+ */
119
+ seedMessages?: ReadonlyArray<Anthropic.MessageParam>;
120
+ /**
121
+ * Single-shot mode: run exactly one user→assistant turn (with the tool
122
+ * inner-loop until Done) using `seedMessages`, then return the terminal
123
+ * assistant text. Skips the stdin REPL entirely. Used by the workflow
124
+ * target to run each step as a discrete turn.
125
+ */
126
+ singleTurn?: boolean;
127
+ /**
128
+ * Permission mode. Defaults to "default" (ask for tools without an
129
+ * explicit allow rule). The `bypass` mode is only legal when supplied
130
+ * directly by the runtime caller (the CLI flag parser); the spec/config
131
+ * loaders reject bypass at parse time.
132
+ */
133
+ permissionMode?: PermissionMode;
134
+ /** Layered rule sources. Defaults to `{ ..., builtin: BUILTIN_DEFAULT_RULES }`. */
135
+ permissionRules?: RuleSet;
136
+ /**
137
+ * Install a SIGINT handler that aborts the current turn on first press
138
+ * and exits on the second. Defaults to true in REPL mode when stdin is
139
+ * a TTY; defaults to false otherwise (singleTurn, piped input, tests).
140
+ */
141
+ installSigintHandler?: boolean;
142
+ /**
143
+ * When true, drive the model stream with `@crewhaus/streaming-tool-executor`
144
+ * so tool execution starts as soon as each `tool_use` block completes
145
+ * (mid-stream) rather than waiting for the full response. Default: false.
146
+ */
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;
156
+ /**
157
+ * Override the directory under which session metadata `.json` files and
158
+ * event-log `.jsonl` files live. Defaults to `.crewhaus/sessions`.
159
+ */
160
+ sessionRootDir?: string;
161
+ /**
162
+ * Human-readable label for new sessions; persisted to the session JSON.
163
+ * Typically the spec `name`. Defaults to `(unnamed)`.
164
+ */
165
+ sessionName?: string;
166
+ /**
167
+ * Target shape this session belongs to (`"cli"`, `"workflow"`, …); persisted
168
+ * to the session JSON for future filtering. Defaults to `"cli"`.
169
+ */
170
+ sessionTarget?: string;
171
+ /**
172
+ * Resume an existing session: load its metadata, replay its event log
173
+ * into the message history (only `user_message` + `assistant_message`
174
+ * events; tool_use/tool_result are audit-only and already nested inside
175
+ * those messages), then continue the loop. Mutually exclusive with
176
+ * `seedMessages` (the resume payload becomes the seed). When the caller
177
+ * supplies a `runContext`, its `sessionId` must already match
178
+ * `resume.sessionId`; otherwise the runtime reseats the sessionId in
179
+ * the run context for this run.
180
+ */
181
+ resume?: {
182
+ readonly sessionId: string;
183
+ };
184
+ /**
185
+ * Section 11 — lifecycle hooks discovered from `.crewhaus/settings.json`.
186
+ * The runtime fires events at key moments (session-start, pre/post tool,
187
+ * pre/post model, pre/post compact, pre-slash, stop). A `deny` decision
188
+ * on `pre-tool` short-circuits with the hook's reason as the result; on
189
+ * `pre-model` it appends `[blocked by hook]` and ends the turn.
190
+ */
191
+ hooks?: ReadonlyArray<HookDef>;
192
+ /**
193
+ * Section 11 — discovered skills, advertised in the system prompt. The
194
+ * caller is responsible for adding `createSkillTool(skills)` to the
195
+ * `tools` array; runtime-core only formats them into the system block.
196
+ */
197
+ skills?: ReadonlyArray<SkillRef>;
198
+ /**
199
+ * Section 11 — slash-command registry. When the user input starts with
200
+ * `/<name>` and `<name>` is in this map, the body is expanded with
201
+ * `$ARGUMENTS` substitution before being sent to the model. Fires
202
+ * `pre-slash` first; deny falls through to the original input.
203
+ */
204
+ slashCommands?: ReadonlyMap<string, SlashCommand>;
205
+ /**
206
+ * Section 13 — inline sub-agent definitions exposed via the `Task` tool.
207
+ * Threaded into the `RuntimeBridge` and surfaced to framework-aware
208
+ * tools (only `Task` today). Codegen sets this from the IR; ordinary
209
+ * runChatLoop callers leave it undefined.
210
+ */
211
+ subAgents?: ReadonlyMap<string, SubAgentDefinition>;
212
+ /**
213
+ * Section 13 — sub-agent spawner injection. Codegen passes
214
+ * `spawnSubAgent` from `@crewhaus/sub-agent-spawner`. The runtime stamps
215
+ * it onto the bridge; the Task tool dispatches via it. Inverted-DI to
216
+ * avoid a runtime-core → sub-agent-spawner cycle (the spawner consumes
217
+ * runChatLoop).
218
+ */
219
+ spawnSubAgent?: SpawnSubAgentFn;
220
+ /**
221
+ * Section 22 — crew orchestrator injection. The orchestrator
222
+ * implements `CrewMailbox` and threads itself in here per role-turn so
223
+ * the in-band Handoff and A2A SendMessage tools can record intent /
224
+ * make synchronous peer requests through `ctx.bridge.crewMailbox`.
225
+ * Inverted-DI to avoid a runtime-core → crew-orchestrator cycle (the
226
+ * orchestrator consumes runChatLoop).
227
+ */
228
+ crewMailbox?: CrewMailbox;
229
+ /**
230
+ * Section 18 — set true when the bundle has wired a non-noop sandbox
231
+ * backend. The permission engine refuses to grant `allow` for tools
232
+ * with `requiresSandbox: true` unless this is set. Codegen flips this
233
+ * automatically when the spec lists any `requiresSandbox` tool.
234
+ */
235
+ sandboxAvailable?: boolean;
236
+ /**
237
+ * Section 18 — when set, suspicious or malicious tool outputs are
238
+ * classified by an LLM after the regex/structural layers. The runtime
239
+ * supplies the function; the prompt-injection-detector calls it as
240
+ * a best-effort tier-3. When omitted (the common case), the classifier
241
+ * stays at tiers 1-2.
242
+ */
243
+ promptInjectionLlmClassifier?: (text: string) => Promise<{
244
+ verdict: "clean" | "suspicious" | "malicious";
245
+ rationale?: string;
246
+ } | undefined>;
247
+ /**
248
+ * Pillar 3 intent gate — when supplied, runtime-core wires this judge
249
+ * into `evaluateJustification` for every tool call whose descriptor
250
+ * sets `requireJustification: true`. Defaults to the rule-based judge
251
+ * exported by `permission-engine`. Production deployments should pass
252
+ * an LLM-backed judge that compares the agent's stated justification
253
+ * against the session goal with model-quality reasoning.
254
+ */
255
+ justificationJudge?: JustificationJudge;
256
+ /**
257
+ * Pillar 3 (FR-004) intent gate — durable audit sink. When supplied,
258
+ * every justification-evaluated tool call appends a
259
+ * `permission_justification_evaluated` record (verbatim payload) to this
260
+ * hash-chained sink IN ADDITION to publishing the `permission_decision`
261
+ * trace event. This is the durable, tamper-evident audit artifact the
262
+ * `permission_justification_evaluated` AuditKind was created for; the
263
+ * trace-bus event is ephemeral. Omitting it leaves the trace bus as the
264
+ * only surface (no behaviour change for existing callers). The CLI `run`
265
+ * path wires a real `@crewhaus/audit-log` instance rooted at
266
+ * `.crewhaus/audit`.
267
+ */
268
+ justificationAuditSink?: JustificationAuditSink;
269
+ /**
270
+ * Pillar 3 sink-side fabric (FR-006) — pluggable egress-matching
271
+ * strategy. When supplied, every external-scope tool call routes its
272
+ * payload through this matcher inside `classifyEgress` instead of the
273
+ * built-in `SubstringEgressMatcher`. The matcher only decides *which*
274
+ * tagged data-lineage entries the payload contains; the per-origin/
275
+ * per-sink policy and the three audit outcomes (`egress-passed |
276
+ * egress-warned | egress-blocked`) are unchanged. Omitting it preserves
277
+ * the substring default (zero behaviour change for existing callers).
278
+ * Production deployments that opt into semantic detection pass an
279
+ * instance of `@crewhaus/egress-matcher-semantic`.
280
+ */
281
+ egressMatcher?: EgressMatcher;
282
+ /**
283
+ * Pillar 3 sink-side — classify a tool sink as `"external-configured"` (a
284
+ * spec-declared sink → warn on non-user content) or `"external-dynamic"` (a
285
+ * runtime-joined sink → block on non-user content). Defaults to treating
286
+ * `mcp__*` sinks as dynamic and everything else as configured (#144); wire
287
+ * this to mark federation-joined or other runtime-discovered sinks dynamic.
288
+ */
289
+ resolveSinkScope?: (toolName: string) => SinkScope;
290
+ /**
291
+ * Hard cap on the number of model→tool cycles in a single turn. The loop
292
+ * detector is advisory (it only injects a one-time warning and is defeated
293
+ * by trivial argument churn), so this is the ENFORCING bound: a prompt-
294
+ * injected model steered into an unbounded tool loop is aborted here rather
295
+ * than burning tokens/tool calls until a provider quota or OOM trips.
296
+ * Defaults to `DEFAULT_MAX_TOOL_ITERATIONS`; set higher for genuinely long
297
+ * agentic turns, or lower to tighten.
298
+ */
299
+ maxToolIterations?: number;
300
+ /**
301
+ * Section 27 — wrap the resolved primary `ProviderAdapter` in a circuit
302
+ * breaker before any `stream()` call. When the breaker trips, subsequent
303
+ * model calls reject immediately rather than hammering a degraded
304
+ * upstream. Set via codegen when the spec lists `circuit_breaker:` opts.
305
+ */
306
+ circuitBreaker?: {
307
+ readonly failureThreshold?: number;
308
+ readonly windowMs?: number;
309
+ readonly cooldownMs?: number;
310
+ };
311
+ /**
312
+ * Section 27 — pre-call rate gating. The runtime calls
313
+ * `rateLimiter.acquire(rateLimitKeys, 1)` before each model invocation.
314
+ * Codegen sets `rateLimitKeys` to `[provider, tenant?]` from the
315
+ * spec's tools/permissions/tenancy block. Without `rateLimiter` set,
316
+ * gating is skipped (no allow-list error).
317
+ */
318
+ rateLimiter?: RateLimiter;
319
+ /** Keys to acquire per model call. Default: `[]`. */
320
+ rateLimitKeys?: ReadonlyArray<{
321
+ readonly dimension: "tenant" | "provider" | "tool";
322
+ readonly id: string;
323
+ }>;
324
+ /**
325
+ * Section 27 — when set, the system block array goes through
326
+ * `prompt-cache-manager.manage()` once at run start; if a fresh marker is
327
+ * injected the new `lastRotatedAt` is exposed via the returned bus event.
328
+ * Pass `0` (or omit) to force a refresh on the first turn.
329
+ */
330
+ promptCacheLastRotatedAt?: number;
331
+ };
332
+ /**
333
+ * Runs the streaming chat loop and returns the terminal assistant text.
334
+ *
335
+ * - REPL mode (default): reads stdin in a loop, prints assistant turns to
336
+ * stdout, returns `""` when the loop exits.
337
+ * - Single-turn mode (`singleTurn: true`): runs one turn from the seeded
338
+ * message history and returns the concatenated text content of the final
339
+ * assistant message. Does not touch stdin.
340
+ */
341
+ /**
342
+ * Resolve the root directory for session + event-log persistence (and the
343
+ * sub-agent storage it threads onward).
344
+ *
345
+ * Tenant isolation is MANDATORY at the storage layer, not cooperative: the
346
+ * managed daemon wraps every gateway request in `withTenant(...)`, so when a
347
+ * tenant context is active we use that tenant's path-rebased `sessionRoot`
348
+ * and never fall back to the process-global default — one tenant's prompts
349
+ * and transcripts can no longer land in another tenant's directory (#142).
350
+ *
351
+ * Precedence: an explicit per-call `optsRoot` (set only by trusted callers
352
+ * such as a target emitter or a test) wins; then the active tenant's
353
+ * `sessionRoot`; then `CREWHAUS_SESSION_DIR`; otherwise `undefined` (which
354
+ * lets `session-store` apply its own non-tenant default). The env var and the
355
+ * global default are only consulted OUTSIDE any tenant scope.
356
+ */
357
+ export declare function resolveSessionRootDir(optsRoot: string | undefined): string | undefined;
358
+ /**
359
+ * Tenant-scoped root for the tool-result spill store, mirroring
360
+ * resolveSessionRootDir (#150). Inside a tenant scope the tenant's rebased
361
+ * `toolResultRoot` is used so one tenant's persisted tool outputs never share
362
+ * a directory with another's; otherwise `undefined` lets tool-result-store
363
+ * apply its own non-tenant default.
364
+ */
365
+ export declare function resolveToolResultRoot(): string | undefined;
366
+ /**
367
+ * Default egress sink-scope. Runtime-joined MCP sinks (`mcp__*`) are the
368
+ * canonical dynamically-discovered external sink, and the model-destination
369
+ * built-ins above are dynamic by virtue of their model-chosen target — both
370
+ * classify as `"external-dynamic"` so the egress block tier is reachable for
371
+ * non-user-origin payloads (#144). Other spec-declared built-in sinks stay
372
+ * `"external-configured"` (warn). Override via `runChatLoop({ resolveSinkScope })`
373
+ * to mark federation-joined or other runtime sinks dynamic too.
374
+ */
375
+ export declare function defaultSinkScope(toolName: string): SinkScope;
376
+ export declare function runChatLoop(opts: RunChatLoopOptions): Promise<string>;