@crewhaus/runtime-core 0.1.3 → 0.1.5
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 +368 -0
- package/dist/index.js +1976 -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/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-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 -2327
- 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,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
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
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
|
+
* Override the directory under which session metadata `.json` files and
|
|
150
|
+
* event-log `.jsonl` files live. Defaults to `.crewhaus/sessions`.
|
|
151
|
+
*/
|
|
152
|
+
sessionRootDir?: string;
|
|
153
|
+
/**
|
|
154
|
+
* Human-readable label for new sessions; persisted to the session JSON.
|
|
155
|
+
* Typically the spec `name`. Defaults to `(unnamed)`.
|
|
156
|
+
*/
|
|
157
|
+
sessionName?: string;
|
|
158
|
+
/**
|
|
159
|
+
* Target shape this session belongs to (`"cli"`, `"workflow"`, …); persisted
|
|
160
|
+
* to the session JSON for future filtering. Defaults to `"cli"`.
|
|
161
|
+
*/
|
|
162
|
+
sessionTarget?: string;
|
|
163
|
+
/**
|
|
164
|
+
* Resume an existing session: load its metadata, replay its event log
|
|
165
|
+
* into the message history (only `user_message` + `assistant_message`
|
|
166
|
+
* events; tool_use/tool_result are audit-only and already nested inside
|
|
167
|
+
* those messages), then continue the loop. Mutually exclusive with
|
|
168
|
+
* `seedMessages` (the resume payload becomes the seed). When the caller
|
|
169
|
+
* supplies a `runContext`, its `sessionId` must already match
|
|
170
|
+
* `resume.sessionId`; otherwise the runtime reseats the sessionId in
|
|
171
|
+
* the run context for this run.
|
|
172
|
+
*/
|
|
173
|
+
resume?: {
|
|
174
|
+
readonly sessionId: string;
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Section 11 — lifecycle hooks discovered from `.crewhaus/settings.json`.
|
|
178
|
+
* The runtime fires events at key moments (session-start, pre/post tool,
|
|
179
|
+
* pre/post model, pre/post compact, pre-slash, stop). A `deny` decision
|
|
180
|
+
* on `pre-tool` short-circuits with the hook's reason as the result; on
|
|
181
|
+
* `pre-model` it appends `[blocked by hook]` and ends the turn.
|
|
182
|
+
*/
|
|
183
|
+
hooks?: ReadonlyArray<HookDef>;
|
|
184
|
+
/**
|
|
185
|
+
* Section 11 — discovered skills, advertised in the system prompt. The
|
|
186
|
+
* caller is responsible for adding `createSkillTool(skills)` to the
|
|
187
|
+
* `tools` array; runtime-core only formats them into the system block.
|
|
188
|
+
*/
|
|
189
|
+
skills?: ReadonlyArray<SkillRef>;
|
|
190
|
+
/**
|
|
191
|
+
* Section 11 — slash-command registry. When the user input starts with
|
|
192
|
+
* `/<name>` and `<name>` is in this map, the body is expanded with
|
|
193
|
+
* `$ARGUMENTS` substitution before being sent to the model. Fires
|
|
194
|
+
* `pre-slash` first; deny falls through to the original input.
|
|
195
|
+
*/
|
|
196
|
+
slashCommands?: ReadonlyMap<string, SlashCommand>;
|
|
197
|
+
/**
|
|
198
|
+
* Section 13 — inline sub-agent definitions exposed via the `Task` tool.
|
|
199
|
+
* Threaded into the `RuntimeBridge` and surfaced to framework-aware
|
|
200
|
+
* tools (only `Task` today). Codegen sets this from the IR; ordinary
|
|
201
|
+
* runChatLoop callers leave it undefined.
|
|
202
|
+
*/
|
|
203
|
+
subAgents?: ReadonlyMap<string, SubAgentDefinition>;
|
|
204
|
+
/**
|
|
205
|
+
* Section 13 — sub-agent spawner injection. Codegen passes
|
|
206
|
+
* `spawnSubAgent` from `@crewhaus/sub-agent-spawner`. The runtime stamps
|
|
207
|
+
* it onto the bridge; the Task tool dispatches via it. Inverted-DI to
|
|
208
|
+
* avoid a runtime-core → sub-agent-spawner cycle (the spawner consumes
|
|
209
|
+
* runChatLoop).
|
|
210
|
+
*/
|
|
211
|
+
spawnSubAgent?: SpawnSubAgentFn;
|
|
212
|
+
/**
|
|
213
|
+
* Section 22 — crew orchestrator injection. The orchestrator
|
|
214
|
+
* implements `CrewMailbox` and threads itself in here per role-turn so
|
|
215
|
+
* the in-band Handoff and A2A SendMessage tools can record intent /
|
|
216
|
+
* make synchronous peer requests through `ctx.bridge.crewMailbox`.
|
|
217
|
+
* Inverted-DI to avoid a runtime-core → crew-orchestrator cycle (the
|
|
218
|
+
* orchestrator consumes runChatLoop).
|
|
219
|
+
*/
|
|
220
|
+
crewMailbox?: CrewMailbox;
|
|
221
|
+
/**
|
|
222
|
+
* Section 18 — set true when the bundle has wired a non-noop sandbox
|
|
223
|
+
* backend. The permission engine refuses to grant `allow` for tools
|
|
224
|
+
* with `requiresSandbox: true` unless this is set. Codegen flips this
|
|
225
|
+
* automatically when the spec lists any `requiresSandbox` tool.
|
|
226
|
+
*/
|
|
227
|
+
sandboxAvailable?: boolean;
|
|
228
|
+
/**
|
|
229
|
+
* Section 18 — when set, suspicious or malicious tool outputs are
|
|
230
|
+
* classified by an LLM after the regex/structural layers. The runtime
|
|
231
|
+
* supplies the function; the prompt-injection-detector calls it as
|
|
232
|
+
* a best-effort tier-3. When omitted (the common case), the classifier
|
|
233
|
+
* stays at tiers 1-2.
|
|
234
|
+
*/
|
|
235
|
+
promptInjectionLlmClassifier?: (text: string) => Promise<{
|
|
236
|
+
verdict: "clean" | "suspicious" | "malicious";
|
|
237
|
+
rationale?: string;
|
|
238
|
+
} | undefined>;
|
|
239
|
+
/**
|
|
240
|
+
* Pillar 3 intent gate — when supplied, runtime-core wires this judge
|
|
241
|
+
* into `evaluateJustification` for every tool call whose descriptor
|
|
242
|
+
* sets `requireJustification: true`. Defaults to the rule-based judge
|
|
243
|
+
* exported by `permission-engine`. Production deployments should pass
|
|
244
|
+
* an LLM-backed judge that compares the agent's stated justification
|
|
245
|
+
* against the session goal with model-quality reasoning.
|
|
246
|
+
*/
|
|
247
|
+
justificationJudge?: JustificationJudge;
|
|
248
|
+
/**
|
|
249
|
+
* Pillar 3 (FR-004) intent gate — durable audit sink. When supplied,
|
|
250
|
+
* every justification-evaluated tool call appends a
|
|
251
|
+
* `permission_justification_evaluated` record (verbatim payload) to this
|
|
252
|
+
* hash-chained sink IN ADDITION to publishing the `permission_decision`
|
|
253
|
+
* trace event. This is the durable, tamper-evident audit artifact the
|
|
254
|
+
* `permission_justification_evaluated` AuditKind was created for; the
|
|
255
|
+
* trace-bus event is ephemeral. Omitting it leaves the trace bus as the
|
|
256
|
+
* only surface (no behaviour change for existing callers). The CLI `run`
|
|
257
|
+
* path wires a real `@crewhaus/audit-log` instance rooted at
|
|
258
|
+
* `.crewhaus/audit`.
|
|
259
|
+
*/
|
|
260
|
+
justificationAuditSink?: JustificationAuditSink;
|
|
261
|
+
/**
|
|
262
|
+
* Pillar 3 sink-side fabric (FR-006) — pluggable egress-matching
|
|
263
|
+
* strategy. When supplied, every external-scope tool call routes its
|
|
264
|
+
* payload through this matcher inside `classifyEgress` instead of the
|
|
265
|
+
* built-in `SubstringEgressMatcher`. The matcher only decides *which*
|
|
266
|
+
* tagged data-lineage entries the payload contains; the per-origin/
|
|
267
|
+
* per-sink policy and the three audit outcomes (`egress-passed |
|
|
268
|
+
* egress-warned | egress-blocked`) are unchanged. Omitting it preserves
|
|
269
|
+
* the substring default (zero behaviour change for existing callers).
|
|
270
|
+
* Production deployments that opt into semantic detection pass an
|
|
271
|
+
* instance of `@crewhaus/egress-matcher-semantic`.
|
|
272
|
+
*/
|
|
273
|
+
egressMatcher?: EgressMatcher;
|
|
274
|
+
/**
|
|
275
|
+
* Pillar 3 sink-side — classify a tool sink as `"external-configured"` (a
|
|
276
|
+
* spec-declared sink → warn on non-user content) or `"external-dynamic"` (a
|
|
277
|
+
* runtime-joined sink → block on non-user content). Defaults to treating
|
|
278
|
+
* `mcp__*` sinks as dynamic and everything else as configured (#144); wire
|
|
279
|
+
* this to mark federation-joined or other runtime-discovered sinks dynamic.
|
|
280
|
+
*/
|
|
281
|
+
resolveSinkScope?: (toolName: string) => SinkScope;
|
|
282
|
+
/**
|
|
283
|
+
* Hard cap on the number of model→tool cycles in a single turn. The loop
|
|
284
|
+
* detector is advisory (it only injects a one-time warning and is defeated
|
|
285
|
+
* by trivial argument churn), so this is the ENFORCING bound: a prompt-
|
|
286
|
+
* injected model steered into an unbounded tool loop is aborted here rather
|
|
287
|
+
* than burning tokens/tool calls until a provider quota or OOM trips.
|
|
288
|
+
* Defaults to `DEFAULT_MAX_TOOL_ITERATIONS`; set higher for genuinely long
|
|
289
|
+
* agentic turns, or lower to tighten.
|
|
290
|
+
*/
|
|
291
|
+
maxToolIterations?: number;
|
|
292
|
+
/**
|
|
293
|
+
* Section 27 — wrap the resolved primary `ProviderAdapter` in a circuit
|
|
294
|
+
* breaker before any `stream()` call. When the breaker trips, subsequent
|
|
295
|
+
* model calls reject immediately rather than hammering a degraded
|
|
296
|
+
* upstream. Set via codegen when the spec lists `circuit_breaker:` opts.
|
|
297
|
+
*/
|
|
298
|
+
circuitBreaker?: {
|
|
299
|
+
readonly failureThreshold?: number;
|
|
300
|
+
readonly windowMs?: number;
|
|
301
|
+
readonly cooldownMs?: number;
|
|
302
|
+
};
|
|
303
|
+
/**
|
|
304
|
+
* Section 27 — pre-call rate gating. The runtime calls
|
|
305
|
+
* `rateLimiter.acquire(rateLimitKeys, 1)` before each model invocation.
|
|
306
|
+
* Codegen sets `rateLimitKeys` to `[provider, tenant?]` from the
|
|
307
|
+
* spec's tools/permissions/tenancy block. Without `rateLimiter` set,
|
|
308
|
+
* gating is skipped (no allow-list error).
|
|
309
|
+
*/
|
|
310
|
+
rateLimiter?: RateLimiter;
|
|
311
|
+
/** Keys to acquire per model call. Default: `[]`. */
|
|
312
|
+
rateLimitKeys?: ReadonlyArray<{
|
|
313
|
+
readonly dimension: "tenant" | "provider" | "tool";
|
|
314
|
+
readonly id: string;
|
|
315
|
+
}>;
|
|
316
|
+
/**
|
|
317
|
+
* Section 27 — when set, the system block array goes through
|
|
318
|
+
* `prompt-cache-manager.manage()` once at run start; if a fresh marker is
|
|
319
|
+
* injected the new `lastRotatedAt` is exposed via the returned bus event.
|
|
320
|
+
* Pass `0` (or omit) to force a refresh on the first turn.
|
|
321
|
+
*/
|
|
322
|
+
promptCacheLastRotatedAt?: number;
|
|
323
|
+
};
|
|
324
|
+
/**
|
|
325
|
+
* Runs the streaming chat loop and returns the terminal assistant text.
|
|
326
|
+
*
|
|
327
|
+
* - REPL mode (default): reads stdin in a loop, prints assistant turns to
|
|
328
|
+
* stdout, returns `""` when the loop exits.
|
|
329
|
+
* - Single-turn mode (`singleTurn: true`): runs one turn from the seeded
|
|
330
|
+
* message history and returns the concatenated text content of the final
|
|
331
|
+
* assistant message. Does not touch stdin.
|
|
332
|
+
*/
|
|
333
|
+
/**
|
|
334
|
+
* Resolve the root directory for session + event-log persistence (and the
|
|
335
|
+
* sub-agent storage it threads onward).
|
|
336
|
+
*
|
|
337
|
+
* Tenant isolation is MANDATORY at the storage layer, not cooperative: the
|
|
338
|
+
* managed daemon wraps every gateway request in `withTenant(...)`, so when a
|
|
339
|
+
* tenant context is active we use that tenant's path-rebased `sessionRoot`
|
|
340
|
+
* and never fall back to the process-global default — one tenant's prompts
|
|
341
|
+
* and transcripts can no longer land in another tenant's directory (#142).
|
|
342
|
+
*
|
|
343
|
+
* Precedence: an explicit per-call `optsRoot` (set only by trusted callers
|
|
344
|
+
* such as a target emitter or a test) wins; then the active tenant's
|
|
345
|
+
* `sessionRoot`; then `CREWHAUS_SESSION_DIR`; otherwise `undefined` (which
|
|
346
|
+
* lets `session-store` apply its own non-tenant default). The env var and the
|
|
347
|
+
* global default are only consulted OUTSIDE any tenant scope.
|
|
348
|
+
*/
|
|
349
|
+
export declare function resolveSessionRootDir(optsRoot: string | undefined): string | undefined;
|
|
350
|
+
/**
|
|
351
|
+
* Tenant-scoped root for the tool-result spill store, mirroring
|
|
352
|
+
* resolveSessionRootDir (#150). Inside a tenant scope the tenant's rebased
|
|
353
|
+
* `toolResultRoot` is used so one tenant's persisted tool outputs never share
|
|
354
|
+
* a directory with another's; otherwise `undefined` lets tool-result-store
|
|
355
|
+
* apply its own non-tenant default.
|
|
356
|
+
*/
|
|
357
|
+
export declare function resolveToolResultRoot(): string | undefined;
|
|
358
|
+
/**
|
|
359
|
+
* Default egress sink-scope. Runtime-joined MCP sinks (`mcp__*`) are the
|
|
360
|
+
* canonical dynamically-discovered external sink, and the model-destination
|
|
361
|
+
* built-ins above are dynamic by virtue of their model-chosen target — both
|
|
362
|
+
* classify as `"external-dynamic"` so the egress block tier is reachable for
|
|
363
|
+
* non-user-origin payloads (#144). Other spec-declared built-in sinks stay
|
|
364
|
+
* `"external-configured"` (warn). Override via `runChatLoop({ resolveSinkScope })`
|
|
365
|
+
* to mark federation-joined or other runtime sinks dynamic too.
|
|
366
|
+
*/
|
|
367
|
+
export declare function defaultSinkScope(toolName: string): SinkScope;
|
|
368
|
+
export declare function runChatLoop(opts: RunChatLoopOptions): Promise<string>;
|