theorum 0.1.2 → 0.1.4

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.
Files changed (150) hide show
  1. package/README.md +83 -27
  2. package/deno.json +57 -0
  3. package/deno.lock +469 -0
  4. package/docs/AGENT_PROFILE_CONTRACT.md +45 -18
  5. package/docs/CLI_SPEC.md +2 -2
  6. package/docs/SECRETS.md +27 -22
  7. package/mod.ts +95 -0
  8. package/package.json +37 -29
  9. package/src/cli/commands/profile.ts +57 -0
  10. package/src/cli/commands/run.ts +66 -0
  11. package/src/cli/commands/test.ts +195 -0
  12. package/src/cli/index.ts +161 -0
  13. package/src/cli/matrix/fixtures.ts +96 -0
  14. package/src/cli/matrix/synthesizer.ts +240 -0
  15. package/src/guardrails/error.ts +142 -0
  16. package/src/guardrails/injection.ts +254 -0
  17. package/src/guardrails/mod.ts +40 -0
  18. package/src/guardrails/quota.ts +87 -0
  19. package/src/guardrails/sanitize.ts +165 -0
  20. package/src/guardrails/sensitive.ts +96 -0
  21. package/src/host/mint-trace.ts +54 -0
  22. package/src/host/mod.ts +20 -0
  23. package/src/host/reply.ts +32 -0
  24. package/src/kernel/engine/assert.ts +29 -0
  25. package/src/kernel/engine/boundary.ts +75 -0
  26. package/src/kernel/engine/delta.ts +440 -0
  27. package/src/kernel/engine/hash.ts +11 -0
  28. package/src/kernel/engine/record.ts +8 -0
  29. package/src/kernel/engine/repair.ts +56 -0
  30. package/src/kernel/engine/runner/gates.ts +338 -0
  31. package/src/kernel/engine/runner/mod.ts +135 -0
  32. package/src/kernel/engine/runner/state.ts +31 -0
  33. package/src/kernel/engine/runner/steps.ts +183 -0
  34. package/src/kernel/engine/runner/stream.ts +83 -0
  35. package/src/kernel/engine/runner/tokens.ts +47 -0
  36. package/src/kernel/engine/runner/tools.ts +266 -0
  37. package/src/kernel/engine/runner.ts +7 -0
  38. package/src/kernel/engine/tree.ts +18 -0
  39. package/src/kernel/mod.ts +39 -0
  40. package/src/kernel/registry/attachments.ts +195 -0
  41. package/src/kernel/registry/catalog.ts +181 -0
  42. package/src/kernel/registry/ingress.ts +223 -0
  43. package/src/kernel/registry/profiles.ts +165 -0
  44. package/src/kernel/registry/provider-request.ts +31 -0
  45. package/src/kernel/registry/resolve.ts +290 -0
  46. package/src/kernel/registry/schemas.ts +29 -0
  47. package/src/kernel/registry/tools.ts +45 -0
  48. package/src/kernel/registry/vault.ts +26 -0
  49. package/src/kernel/types.ts +576 -0
  50. package/{esm/src/observability/mod.js → src/observability/mod.ts} +11 -2
  51. package/src/observability/spans.ts +70 -0
  52. package/src/observability/trace-attach.ts +96 -0
  53. package/src/observability/trace-record.ts +254 -0
  54. package/src/observability/trace-usage.ts +36 -0
  55. package/src/observability/trace.ts +143 -0
  56. package/src/presets/google.ts +147 -0
  57. package/src/presets/mod.ts +24 -0
  58. package/src/providers/create-provider.ts +64 -0
  59. package/src/providers/gemini-tape.ts +59 -0
  60. package/src/providers/google-tap.ts +57 -0
  61. package/src/providers/interactions.ts +182 -0
  62. package/src/providers/keys.ts +182 -0
  63. package/src/providers/mod.ts +12 -0
  64. package/src/providers/openrouter-mod.ts +16 -0
  65. package/src/providers/openrouter-payload.ts +232 -0
  66. package/src/providers/openrouter.ts +758 -0
  67. package/src/providers/pcm.ts +37 -0
  68. package/src/providers/provider.ts +206 -0
  69. package/src/providers/speech.ts +180 -0
  70. package/src/providers/sse.ts +59 -0
  71. package/esm/_dnt.polyfills.d.ts +0 -11
  72. package/esm/_dnt.polyfills.js +0 -15
  73. package/esm/_dnt.shims.d.ts +0 -5
  74. package/esm/_dnt.shims.js +0 -61
  75. package/esm/mod.d.ts +0 -37
  76. package/esm/mod.js +0 -35
  77. package/esm/package.json +0 -3
  78. package/esm/src/guardrails/error.d.ts +0 -35
  79. package/esm/src/guardrails/error.js +0 -116
  80. package/esm/src/guardrails/injection.d.ts +0 -12
  81. package/esm/src/guardrails/injection.js +0 -220
  82. package/esm/src/guardrails/keys.d.ts +0 -12
  83. package/esm/src/guardrails/keys.js +0 -132
  84. package/esm/src/guardrails/mod.d.ts +0 -14
  85. package/esm/src/guardrails/mod.js +0 -14
  86. package/esm/src/guardrails/sanitize.d.ts +0 -22
  87. package/esm/src/guardrails/sanitize.js +0 -133
  88. package/esm/src/guardrails/sensitive.d.ts +0 -12
  89. package/esm/src/guardrails/sensitive.js +0 -88
  90. package/esm/src/kernel/engine/boundary.d.ts +0 -10
  91. package/esm/src/kernel/engine/boundary.js +0 -55
  92. package/esm/src/kernel/engine/delta.d.ts +0 -8
  93. package/esm/src/kernel/engine/delta.js +0 -362
  94. package/esm/src/kernel/engine/hash.d.ts +0 -1
  95. package/esm/src/kernel/engine/hash.js +0 -9
  96. package/esm/src/kernel/engine/record.d.ts +0 -2
  97. package/esm/src/kernel/engine/record.js +0 -7
  98. package/esm/src/kernel/engine/repair.d.ts +0 -9
  99. package/esm/src/kernel/engine/repair.js +0 -38
  100. package/esm/src/kernel/engine/runner.d.ts +0 -14
  101. package/esm/src/kernel/engine/runner.js +0 -731
  102. package/esm/src/kernel/engine/tree.d.ts +0 -2
  103. package/esm/src/kernel/engine/tree.js +0 -17
  104. package/esm/src/kernel/mod.d.ts +0 -16
  105. package/esm/src/kernel/mod.js +0 -15
  106. package/esm/src/kernel/registry/catalog.d.ts +0 -24
  107. package/esm/src/kernel/registry/catalog.js +0 -213
  108. package/esm/src/kernel/registry/profiles.d.ts +0 -36
  109. package/esm/src/kernel/registry/profiles.js +0 -111
  110. package/esm/src/kernel/registry/resolve.d.ts +0 -20
  111. package/esm/src/kernel/registry/resolve.js +0 -235
  112. package/esm/src/kernel/registry/schemas.d.ts +0 -14
  113. package/esm/src/kernel/registry/schemas.js +0 -23
  114. package/esm/src/kernel/registry/tools.d.ts +0 -12
  115. package/esm/src/kernel/registry/tools.js +0 -36
  116. package/esm/src/kernel/types.d.ts +0 -497
  117. package/esm/src/kernel/types.js +0 -10
  118. package/esm/src/observability/mod.d.ts +0 -12
  119. package/esm/src/observability/spans.d.ts +0 -16
  120. package/esm/src/observability/spans.js +0 -56
  121. package/esm/src/observability/trace-attach.d.ts +0 -16
  122. package/esm/src/observability/trace-attach.js +0 -81
  123. package/esm/src/observability/trace-record.d.ts +0 -112
  124. package/esm/src/observability/trace-record.js +0 -140
  125. package/esm/src/observability/trace-usage.d.ts +0 -3
  126. package/esm/src/observability/trace-usage.js +0 -32
  127. package/esm/src/observability/trace.d.ts +0 -23
  128. package/esm/src/observability/trace.js +0 -121
  129. package/esm/src/providers/attachments.d.ts +0 -17
  130. package/esm/src/providers/attachments.js +0 -156
  131. package/esm/src/providers/gemini-tape.d.ts +0 -3
  132. package/esm/src/providers/gemini-tape.js +0 -46
  133. package/esm/src/providers/google-tap.d.ts +0 -3
  134. package/esm/src/providers/google-tap.js +0 -48
  135. package/esm/src/providers/interactions.d.ts +0 -5
  136. package/esm/src/providers/interactions.js +0 -127
  137. package/esm/src/providers/media.d.ts +0 -5
  138. package/esm/src/providers/media.js +0 -125
  139. package/esm/src/providers/mod.d.ts +0 -15
  140. package/esm/src/providers/mod.js +0 -13
  141. package/esm/src/providers/openrouter-payload.d.ts +0 -24
  142. package/esm/src/providers/openrouter-payload.js +0 -177
  143. package/esm/src/providers/openrouter.d.ts +0 -17
  144. package/esm/src/providers/openrouter.js +0 -332
  145. package/esm/src/providers/provider.d.ts +0 -13
  146. package/esm/src/providers/provider.js +0 -123
  147. package/esm/src/providers/sse.d.ts +0 -7
  148. package/esm/src/providers/sse.js +0 -53
  149. package/esm/src/providers/tts.d.ts +0 -24
  150. package/esm/src/providers/tts.js +0 -144
@@ -0,0 +1,161 @@
1
+ import { listProfilesCommand, showProfileCommand } from './commands/profile.ts';
2
+ import { runCommand } from './commands/run.ts';
3
+ import { testProfileCommand } from './commands/test.ts';
4
+
5
+ function printHelp(): void {
6
+ console.log(`
7
+ Theorum CLI - Profile Testing and Profile Inspection
8
+
9
+ USAGE:
10
+ theorum <command> [options]
11
+
12
+ COMMANDS:
13
+ test Run stress matrix or custom profile tests
14
+ --profile, -p <id> Target profile ID registered by your host app
15
+ --all, -a Test all registered profiles
16
+ --lite Minimal fast-path connectivity ping
17
+ --matrix Run all valid permutations for the profile
18
+ --mode <fast|smart> Reasoning mode override
19
+ --search Optional: set tool id googleSearch when allowlisted
20
+ --map Optional: set tool id googleMaps when allowlisted
21
+
22
+ run Execute a turn with real-time streaming output
23
+ --profile, -p <id> Target profile ID
24
+ --prompt <text> User prompt string
25
+ --mode <fast|smart> Reasoning mode
26
+ --search Optional: set tool id googleSearch when allowlisted
27
+ --map Optional: set tool id googleMaps when allowlisted
28
+
29
+ profile Inspect registered profile blueprints
30
+ list List all registered profiles
31
+ show <id> Show detailed JSON profile specification
32
+
33
+ help, --help, -h Show this help message
34
+ `);
35
+ }
36
+
37
+ interface ParsedFlags {
38
+ _: string[];
39
+ profile?: string;
40
+ p?: string;
41
+ prompt?: string;
42
+ mode?: string;
43
+ all?: boolean;
44
+ a?: boolean;
45
+ lite?: boolean;
46
+ matrix?: boolean;
47
+ search?: boolean;
48
+ map?: boolean;
49
+ help?: boolean;
50
+ [key: string]: unknown;
51
+ }
52
+
53
+ function parseLongFlag(arg: string, nextArg: string | undefined, flags: ParsedFlags): number {
54
+ const key = arg.slice(2);
55
+ if (nextArg && !nextArg.startsWith('-')) {
56
+ flags[key] = nextArg;
57
+ return 1;
58
+ }
59
+ flags[key] = true;
60
+ return 0;
61
+ }
62
+
63
+ function parseShortFlag(arg: string, nextArg: string | undefined, flags: ParsedFlags): number {
64
+ const key = arg.slice(1);
65
+ if (key === 'p' && nextArg) {
66
+ flags.profile = nextArg;
67
+ return 1;
68
+ }
69
+ if (key === 'a') flags.all = true;
70
+ else if (key === 'h') flags.help = true;
71
+ else flags[key] = true;
72
+ return 0;
73
+ }
74
+
75
+ function parseFlags(args: string[]): ParsedFlags {
76
+ const flags: ParsedFlags = { _: [] };
77
+ let i = 0;
78
+ while (i < args.length) {
79
+ const arg = args[i];
80
+ const next = args[i + 1];
81
+ if (arg.startsWith('--')) {
82
+ i += 1 + parseLongFlag(arg, next, flags);
83
+ } else if (arg.startsWith('-')) {
84
+ i += 1 + parseShortFlag(arg, next, flags);
85
+ } else {
86
+ flags._.push(arg);
87
+ i += 1;
88
+ }
89
+ }
90
+ return flags;
91
+ }
92
+
93
+ function extractProfileId(flags: ParsedFlags): string | undefined {
94
+ if (typeof flags.profile === 'string') return flags.profile;
95
+ if (typeof flags.p === 'string') return flags.p;
96
+ return undefined;
97
+ }
98
+
99
+ async function handleTest(flags: ParsedFlags): Promise<void> {
100
+ const profile = extractProfileId(flags);
101
+ const success = await testProfileCommand(profile, {
102
+ all: Boolean(flags.all || flags.a),
103
+ lite: Boolean(flags.lite),
104
+ matrix: Boolean(flags.matrix),
105
+ mode: typeof flags.mode === 'string' ? flags.mode : undefined,
106
+ search: flags.search ? true : undefined,
107
+ map: flags.map ? true : undefined,
108
+ });
109
+ if (!success) {
110
+ Deno.exit(1);
111
+ }
112
+ }
113
+
114
+ async function handleRun(flags: ParsedFlags): Promise<void> {
115
+ const profile = extractProfileId(flags);
116
+ if (!profile) {
117
+ console.error('Error: Profile ID required (e.g. `theorum run --profile your-profile`)');
118
+ Deno.exit(1);
119
+ }
120
+ const prompt = typeof flags.prompt === 'string' ? flags.prompt : flags._.slice(1).join(' ');
121
+ await runCommand({
122
+ profile,
123
+ prompt,
124
+ mode: typeof flags.mode === 'string' ? flags.mode : undefined,
125
+ search: Boolean(flags.search),
126
+ map: Boolean(flags.map),
127
+ });
128
+ }
129
+
130
+ function handleProfile(flags: ParsedFlags): void {
131
+ const sub = flags._[1] || 'list';
132
+ if (sub === 'list') {
133
+ listProfilesCommand();
134
+ return;
135
+ }
136
+ const id = sub === 'show' ? flags._[2] || flags.profile : sub;
137
+ if (typeof id !== 'string' || !id) {
138
+ console.error('Error: Profile ID required (e.g. `theorum profile show your-profile`)');
139
+ Deno.exit(1);
140
+ }
141
+ showProfileCommand(id);
142
+ }
143
+
144
+ export async function main(cliArgs = Deno.args): Promise<void> {
145
+ const flags = parseFlags(cliArgs);
146
+ const command = flags._[0] || (flags.help ? 'help' : 'help');
147
+
148
+ if (command === 'test') {
149
+ await handleTest(flags);
150
+ } else if (command === 'run') {
151
+ await handleRun(flags);
152
+ } else if (command === 'profile') {
153
+ handleProfile(flags);
154
+ } else {
155
+ printHelp();
156
+ }
157
+ }
158
+
159
+ if (import.meta.main) {
160
+ await main();
161
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Built-in synthetic media fixtures for zero-dependency matrix testing.
3
+ */
4
+
5
+ // 1x1 pixel PNG (base64)
6
+ export const FIXTURE_PNG_BASE64 =
7
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
8
+
9
+ // Minimal valid PDF-1.4 document (base64)
10
+ export const FIXTURE_PDF_BASE64 = btoa(
11
+ '%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj\n3 0 obj<</Type/Page/MediaBox[0 0 612 792]/Parent 2 0 R/Resources<<>>>>endobj\nxref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n0000000056 00000 n \n0000000111 00000 n \ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n188\n%%EOF\n',
12
+ );
13
+
14
+ // Minimal valid 16kHz 16-bit mono PCM/WAV (0.1s tone) (base64)
15
+ export function createSyntheticWavBase64(durationSec = 0.1, sampleRate = 16000): string {
16
+ const numSamples = Math.floor(sampleRate * durationSec);
17
+ const dataSize = numSamples * 2; // 16-bit = 2 bytes per sample
18
+ const buffer = new ArrayBuffer(44 + dataSize);
19
+ const view = new DataView(buffer);
20
+
21
+ // RIFF identifier
22
+ view.setUint8(0, 0x52); // R
23
+ view.setUint8(1, 0x49); // I
24
+ view.setUint8(2, 0x46); // F
25
+ view.setUint8(3, 0x46); // F
26
+ view.setUint32(4, 36 + dataSize, true); // file size - 8
27
+ view.setUint8(8, 0x57); // W
28
+ view.setUint8(9, 0x41); // A
29
+ view.setUint8(10, 0x56); // V
30
+ view.setUint8(11, 0x45); // E
31
+
32
+ // fmt subchunk
33
+ view.setUint8(12, 0x66); // f
34
+ view.setUint8(13, 0x6d); // m
35
+ view.setUint8(14, 0x74); // t
36
+ view.setUint8(15, 0x20); // ' '
37
+ view.setUint32(16, 16, true); // Subchunk1Size (16 for PCM)
38
+ view.setUint16(20, 1, true); // AudioFormat (1 = PCM)
39
+ view.setUint16(22, 1, true); // NumChannels (1 = Mono)
40
+ view.setUint32(24, sampleRate, true); // SampleRate
41
+ view.setUint32(28, sampleRate * 2, true); // ByteRate (SampleRate * NumChannels * BitsPerSample/8)
42
+ view.setUint16(32, 2, true); // BlockAlign (NumChannels * BitsPerSample/8)
43
+ view.setUint16(34, 16, true); // BitsPerSample (16 bits)
44
+
45
+ // data subchunk
46
+ view.setUint8(36, 0x64); // d
47
+ view.setUint8(37, 0x61); // a
48
+ view.setUint8(38, 0x74); // t
49
+ view.setUint8(39, 0x61); // a
50
+ view.setUint32(40, dataSize, true);
51
+
52
+ // Write a simple sine wave (440Hz)
53
+ const freq = 440;
54
+ for (let i = 0; i < numSamples; i++) {
55
+ const t = i / sampleRate;
56
+ const sample = Math.sin(2 * Math.PI * freq * t) * 0.2 * 32767;
57
+ view.setInt16(44 + i * 2, sample, true);
58
+ }
59
+
60
+ const bytes = new Uint8Array(buffer);
61
+ let binary = '';
62
+ for (let i = 0; i < bytes.byteLength; i++) {
63
+ binary += String.fromCharCode(bytes[i]);
64
+ }
65
+ return btoa(binary);
66
+ }
67
+
68
+ export const FIXTURE_WAV_BASE64 = createSyntheticWavBase64(0.1, 16000);
69
+
70
+ export const FIXTURE_CSV_BASE64 = btoa(
71
+ 'item_id,label,category,score\nitem_1,Alpha,test,0.95\nitem_2,Beta,test,0.88\n',
72
+ );
73
+
74
+ export const FIXTURE_TEXT_BASE64 = btoa(
75
+ 'This is a synthetic fixture text document for Theorum validation testing.\n',
76
+ );
77
+
78
+ export function getFixtureForMime(mime: string): { data: string; mimeType: string } | undefined {
79
+ const m = mime.toLowerCase().trim();
80
+ if (m.startsWith('image/')) {
81
+ return { data: FIXTURE_PNG_BASE64, mimeType: 'image/png' };
82
+ }
83
+ if (m === 'application/pdf') {
84
+ return { data: FIXTURE_PDF_BASE64, mimeType: 'application/pdf' };
85
+ }
86
+ if (m === 'audio/wav' || m === 'audio/x-wav' || m.startsWith('audio/')) {
87
+ return { data: FIXTURE_WAV_BASE64, mimeType: 'audio/wav' };
88
+ }
89
+ if (m === 'text/csv') {
90
+ return { data: FIXTURE_CSV_BASE64, mimeType: 'text/csv' };
91
+ }
92
+ if (m === 'text/plain') {
93
+ return { data: FIXTURE_TEXT_BASE64, mimeType: 'text/plain' };
94
+ }
95
+ return undefined;
96
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Stress / matrix turn synthesis for the THEORUM CLI.
3
+ *
4
+ * Tool enabling walks the profile allowlist and registered catalog metadata
5
+ * (`conflictsWith`). Google `--search` / `--map` flags remain as convenience
6
+ * aliases for `googleSearch` / `googleMaps` when those ids are allowed.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import { getTool } from '../../kernel/registry/catalog.ts';
12
+ import type { Profile, ToolId, TurnBlob, TurnRequest } from '../../kernel/types.ts';
13
+ import { FIXTURE_PNG_BASE64, FIXTURE_WAV_BASE64, getFixtureForMime } from './fixtures.ts';
14
+
15
+ export interface MatrixOptions {
16
+ lite?: boolean;
17
+ /** Convenience alias for enabling/disabling `googleSearch` when allowed. */
18
+ search?: boolean;
19
+ /** Convenience alias for enabling/disabling `googleMaps` when allowed. */
20
+ map?: boolean;
21
+ mode?: string;
22
+ attachmentPaths?: string[];
23
+ voicePath?: string;
24
+ }
25
+
26
+ export function synthesizeLiteCombo(profile: Profile): TurnRequest {
27
+ const select = profile.model.select?.fast ? 'fast' : undefined;
28
+ return {
29
+ profile: profile.id,
30
+ select,
31
+ tools: {},
32
+ input: {
33
+ text: `Ping test for profile ${profile.id}. Respond concisely with confirmation.`,
34
+ },
35
+ };
36
+ }
37
+
38
+ function resolveStressReasoning(profile: Profile): string | undefined {
39
+ if (profile.model.select?.smart) {
40
+ return 'smart';
41
+ }
42
+ if (profile.model.select) {
43
+ const keys = Object.keys(profile.model.select);
44
+ return keys[keys.length - 1];
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+ function isEnabled(active: Partial<Record<ToolId, boolean>>, id: ToolId): boolean {
50
+ return active[id] === true;
51
+ }
52
+
53
+ /** Drop tools whose registered `conflictsWith` siblings are also enabled. */
54
+ function applyRegisteredConflicts(
55
+ allowed: ToolId[],
56
+ active: Partial<Record<ToolId, boolean>>,
57
+ ): void {
58
+ for (const id of allowed) {
59
+ if (!isEnabled(active, id)) {
60
+ continue;
61
+ }
62
+ const conflicts = getTool(id)?.conflictsWith ?? [];
63
+ if (conflicts.some((other) => isEnabled(active, other))) {
64
+ active[id] = false;
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Enable allowlisted tools, optionally forcing one preferred tool and clearing
71
+ * what it conflicts with (and tools that conflict with it).
72
+ */
73
+ function resolveStressTools(allowed: ToolId[], prefer?: ToolId): Partial<Record<ToolId, boolean>> {
74
+ const active: Partial<Record<ToolId, boolean>> = {};
75
+ for (const t of allowed) {
76
+ active[t] = true;
77
+ }
78
+
79
+ if (prefer && allowed.includes(prefer)) {
80
+ active[prefer] = true;
81
+ for (const c of getTool(prefer)?.conflictsWith ?? []) {
82
+ if (allowed.includes(c)) {
83
+ active[c] = false;
84
+ }
85
+ }
86
+ for (const t of allowed) {
87
+ if (t === prefer) {
88
+ continue;
89
+ }
90
+ const otherConflicts: ToolId[] = getTool(t)?.conflictsWith ?? [];
91
+ if (otherConflicts.includes(prefer)) {
92
+ active[t] = false;
93
+ }
94
+ }
95
+ }
96
+
97
+ applyRegisteredConflicts(allowed, active);
98
+ return active;
99
+ }
100
+
101
+ /** Builtins on the allowlist that declare conflicts (candidates for matrix variants). */
102
+ function conflictingAllowlistedTools(allowed: ToolId[]): ToolId[] {
103
+ return allowed.filter((id) => {
104
+ const entry = getTool(id);
105
+ return entry?.kind === 'builtin' && (entry.conflictsWith?.length ?? 0) > 0;
106
+ });
107
+ }
108
+
109
+ function resolveStressAttachments(profile: Profile): TurnBlob[] {
110
+ const attachments: TurnBlob[] = [];
111
+ const accept = profile.inputs.attachments?.accept;
112
+ if (accept && accept.length > 0) {
113
+ const preferredMimes = ['image/png', 'application/pdf', 'text/plain'];
114
+ const chosenMime = preferredMimes.find((m) => accept.includes(m)) ?? accept[0];
115
+ const fixture = getFixtureForMime(chosenMime);
116
+ if (fixture) {
117
+ attachments.push(fixture);
118
+ } else {
119
+ attachments.push({ mimeType: 'image/png', data: FIXTURE_PNG_BASE64 });
120
+ }
121
+ }
122
+ return attachments;
123
+ }
124
+
125
+ function resolveStressVoice(profile: Profile): TurnBlob[] {
126
+ const voice: TurnBlob[] = [];
127
+ if (profile.inputs.voice?.accept && profile.inputs.voice.accept.length > 0) {
128
+ voice.push({ mimeType: 'audio/wav', data: FIXTURE_WAV_BASE64 });
129
+ }
130
+ return voice;
131
+ }
132
+
133
+ export function synthesizeStressCombo(
134
+ profile: Profile,
135
+ options: { preferTool?: ToolId } = {},
136
+ ): TurnRequest {
137
+ const select = resolveStressReasoning(profile);
138
+ const activeTools = resolveStressTools(profile.tools.allow ?? [], options.preferTool);
139
+ const attachments = resolveStressAttachments(profile);
140
+ const voice = resolveStressVoice(profile);
141
+ const promptText = `Execute comprehensive test turn for profile ${profile.id}. Validate all instructions and produce required outputs.`;
142
+
143
+ return {
144
+ profile: profile.id,
145
+ select,
146
+ tools: activeTools,
147
+ input: {
148
+ text: promptText,
149
+ attachments: attachments.length > 0 ? attachments : undefined,
150
+ voice: voice.length > 0 ? voice : undefined,
151
+ },
152
+ };
153
+ }
154
+
155
+ export function synthesizeMatrixCombos(
156
+ profile: Profile,
157
+ ): Array<{ name: string; req: TurnRequest }> {
158
+ const combos: Array<{ name: string; req: TurnRequest }> = [];
159
+ const allowed = profile.tools.allow ?? [];
160
+
161
+ combos.push({
162
+ name: 'Lite (connectivity)',
163
+ req: synthesizeLiteCombo(profile),
164
+ });
165
+
166
+ const primary = synthesizeStressCombo(profile);
167
+ combos.push({
168
+ name: 'Stress (all modalities + primary tools)',
169
+ req: primary,
170
+ });
171
+
172
+ // Variants: each allowlisted conflicting builtin that the primary pass dropped.
173
+ for (const id of conflictingAllowlistedTools(allowed)) {
174
+ if (primary.tools?.[id] === true) {
175
+ continue;
176
+ }
177
+ const variant = synthesizeStressCombo(profile, { preferTool: id });
178
+ if (variant.tools?.[id] !== true) {
179
+ continue;
180
+ }
181
+ combos.push({
182
+ name: `Conflict variant (${id} preferred)`,
183
+ req: variant,
184
+ });
185
+ }
186
+
187
+ return combos;
188
+ }
189
+
190
+ /** Map legacy Google CLI flags onto tool ids when the profile allowlists them. */
191
+ function applyGoogleFlagAliases(
192
+ active: Partial<Record<ToolId, boolean>>,
193
+ allowed: ToolId[],
194
+ options: MatrixOptions,
195
+ ): void {
196
+ if (options.search !== undefined && allowed.includes('googleSearch')) {
197
+ active.googleSearch = options.search;
198
+ }
199
+ if (options.map !== undefined && allowed.includes('googleMaps')) {
200
+ active.googleMaps = options.map;
201
+ }
202
+ }
203
+
204
+ function applyExplicitToolOverrides(
205
+ base: TurnRequest,
206
+ profile: Profile,
207
+ options: MatrixOptions,
208
+ ): void {
209
+ const allowed = profile.tools.allow ?? [];
210
+ base.tools = base.tools ?? {};
211
+ applyGoogleFlagAliases(base.tools, allowed, options);
212
+
213
+ // If map was explicitly requested on, prefer it against its registered conflicts.
214
+ if (options.map === true && allowed.includes('googleMaps')) {
215
+ const preferred = resolveStressTools(allowed, 'googleMaps');
216
+ for (const id of allowed) {
217
+ base.tools[id] = preferred[id] === true;
218
+ }
219
+ return;
220
+ }
221
+
222
+ applyRegisteredConflicts(allowed, base.tools);
223
+ }
224
+
225
+ export function buildCustomTurnRequest(profile: Profile, options: MatrixOptions): TurnRequest {
226
+ if (options.lite) {
227
+ return synthesizeLiteCombo(profile);
228
+ }
229
+
230
+ const base = synthesizeStressCombo(profile);
231
+ if (options.mode) {
232
+ base.select = options.mode;
233
+ }
234
+
235
+ if (options.search !== undefined || options.map !== undefined) {
236
+ applyExplicitToolOverrides(base, profile, options);
237
+ }
238
+
239
+ return base;
240
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Public-safe error mapping for THEORUM.
3
+ *
4
+ * Kernel internals may contain provider status text, tool names, or exception
5
+ * details. This module maps those failures to stable user-safe strings.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ /** Error class used for expected THEORUM contract failures. */
11
+ class TheorumError extends Error {
12
+ constructor(message = '', options?: ErrorOptions) {
13
+ super(message, options);
14
+ this.name = 'TheorumError';
15
+ }
16
+ }
17
+
18
+ /** Internal marker for provider or transport failure. */
19
+ const UPSTREAM_FAILED = 'upstream failed';
20
+ /** Generic safe fallback shown when details must not be surfaced. */
21
+ const PUBLIC_GENERIC = 'Something went wrong. Try again.';
22
+ /** Safe copy for transient provider unavailability. */
23
+ const PUBLIC_UNAVAILABLE = 'The model is unavailable. Try again.';
24
+ /** Safe copy for canary or egress disclosure violations. */
25
+ const PUBLIC_CANARY = "That reply wasn't safe to show. Try again.";
26
+ /** Safe copy for tool or permission denials. */
27
+ const PUBLIC_ACTION = "That action isn't available.";
28
+ /** Safe copy for unsupported MIME types. */
29
+ const PUBLIC_FILE_TYPE = "That file type isn't supported.";
30
+ /** Safe copy for oversized files. */
31
+ const PUBLIC_FILE_SIZE = 'That file is too large.';
32
+ /** Safe copy for too many files in one turn. */
33
+ const PUBLIC_FILE_COUNT = 'Too many files for one message.';
34
+ /** Safe copy for unsupported generated image dimensions. */
35
+ const PUBLIC_IMAGE_SIZE = "That image size isn't supported.";
36
+
37
+ const EXACT: Record<string, string> = {
38
+ [UPSTREAM_FAILED]: PUBLIC_UNAVAILABLE,
39
+ 'empty Gemini stream': PUBLIC_UNAVAILABLE,
40
+ 'canary leaked': PUBLIC_CANARY,
41
+ 'Turn withheld: egress disclosure violation': PUBLIC_CANARY,
42
+ 'expected JSON object': 'Something was wrong with that request.',
43
+ 'user input cannot be placed in the system block': PUBLIC_GENERIC,
44
+ 'attachment data must be base64': PUBLIC_FILE_TYPE,
45
+ 'attachment is too large': PUBLIC_FILE_SIZE,
46
+ 'attachments exceed the per-turn budget': PUBLIC_FILE_SIZE,
47
+ 'askUser.kind must be confirm, choice, or text': "That question isn't valid.",
48
+ 'askUser.prompt is required': 'That question needs a prompt.',
49
+ 'This profile does not accept text input': PUBLIC_ACTION,
50
+ };
51
+
52
+ interface ErrorRule {
53
+ match: (text: string) => boolean;
54
+ resolve: (text: string) => string;
55
+ }
56
+
57
+ const RULES: ErrorRule[] = [
58
+ {
59
+ match: (t) =>
60
+ /^(Gemini|OpenRouter|TTS|OpenRouter TTS|Speech) HTTP/.test(t) ||
61
+ t.includes('TTS HTTP') ||
62
+ t.includes('Speech HTTP'),
63
+ resolve: () => PUBLIC_UNAVAILABLE,
64
+ },
65
+ {
66
+ match: (t) =>
67
+ t.includes('not gated') ||
68
+ t.includes('not allowed') ||
69
+ t.includes('has no kernel executor') ||
70
+ t.includes('Unknown model select') ||
71
+ t.includes('Grounding tools'),
72
+ resolve: () => PUBLIC_ACTION,
73
+ },
74
+ {
75
+ match: (t) =>
76
+ t.includes('MIME') ||
77
+ t.includes('does not accept attachments') ||
78
+ t.includes('does not accept voice'),
79
+ resolve: () => PUBLIC_FILE_TYPE,
80
+ },
81
+ {
82
+ match: (t) => t.startsWith('At most'),
83
+ resolve: () => PUBLIC_FILE_COUNT,
84
+ },
85
+ {
86
+ match: (t) =>
87
+ (t.startsWith('Only ') && t.includes('file')) ||
88
+ t.startsWith('Each file must be') ||
89
+ t.startsWith('Those files together'),
90
+ resolve: (t) => t,
91
+ },
92
+ {
93
+ match: (t) => t.includes('attachment'),
94
+ resolve: () => PUBLIC_FILE_SIZE,
95
+ },
96
+ {
97
+ match: (t) => t.includes('aspect or size'),
98
+ resolve: () => PUBLIC_IMAGE_SIZE,
99
+ },
100
+ {
101
+ match: (t) => t.includes('must pin thinking') || t.includes('has no models'),
102
+ resolve: () => PUBLIC_GENERIC,
103
+ },
104
+ ];
105
+
106
+ function publicText(text: string): string {
107
+ const exact = EXACT[text];
108
+ if (exact) {
109
+ return exact;
110
+ }
111
+ for (const rule of RULES) {
112
+ if (rule.match(text)) {
113
+ return rule.resolve(text);
114
+ }
115
+ }
116
+ return PUBLIC_GENERIC;
117
+ }
118
+
119
+ /** Convert an unknown thrown value or internal message to user-safe text. */
120
+ function publicError(err: unknown): string {
121
+ if (typeof err === 'string') {
122
+ return publicText(err);
123
+ }
124
+ if (err instanceof TheorumError) {
125
+ return publicText(err.message);
126
+ }
127
+ return PUBLIC_UNAVAILABLE;
128
+ }
129
+
130
+ export {
131
+ PUBLIC_ACTION,
132
+ PUBLIC_CANARY,
133
+ PUBLIC_FILE_COUNT,
134
+ PUBLIC_FILE_SIZE,
135
+ PUBLIC_FILE_TYPE,
136
+ PUBLIC_GENERIC,
137
+ PUBLIC_IMAGE_SIZE,
138
+ PUBLIC_UNAVAILABLE,
139
+ publicError,
140
+ TheorumError,
141
+ UPSTREAM_FAILED,
142
+ };