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
package/docs/SECRETS.md CHANGED
@@ -9,39 +9,44 @@ Host applications own credentials, runtime configuration, and secret storage. Th
9
9
  - Do not create `.env` files in this repository.
10
10
  - Do not commit key templates to this repository.
11
11
  - Do not teach Theorum to discover keys from the shell or process environment.
12
- - Business applications pass credentials into provider constructors or transport objects.
12
+ - Business applications pass credentials into `createProvider`.
13
13
 
14
- ## 2. OpenRouter
14
+ ## 2. Single door: `createProvider`
15
15
 
16
16
  ```ts
17
- import { createOpenRouterProvider } from 'theorum/openrouter';
18
-
19
- const provider = createOpenRouterProvider({
20
- apiKey: hostResolvedOpenRouterKey,
21
- });
22
- ```
23
-
24
- ## 3. Google Interactions
25
-
26
- ```ts
27
- import { createInteractionsProvider } from 'theorum/providers';
28
-
29
- const provider = createInteractionsProvider({
30
- vault: {
31
- freeA: hostResolvedFreeAKey,
32
- freeB: hostResolvedFreeBKey,
33
- freeC: hostResolvedFreeCKey,
34
- paid: hostResolvedPaidKey,
17
+ import { createProvider, runTurn } from 'theorum';
18
+
19
+ const provider = createProvider(profile, {
20
+ // geminiInteractions / google
21
+ gemini: {
22
+ vault: {
23
+ freeA: hostResolvedFreeAKey,
24
+ freeB: hostResolvedFreeBKey,
25
+ freeC: hostResolvedFreeCKey,
26
+ paid: hostResolvedPaidKey,
27
+ },
28
+ },
29
+ // openAi / openrouter (chat or speech role — same credentials)
30
+ openRouter: {
31
+ apiKey: hostResolvedOpenRouterKey,
35
32
  },
36
33
  });
34
+
35
+ for await (const event of runTurn({ profile: profile.id, input: { text: '…' } }, provider)) {
36
+ // …
37
+ }
37
38
  ```
38
39
 
39
- ## 4. Tracing
40
+ `createProvider` picks the transport from `profile.model.protocol` / `provider` (and whether the profile is a speech role). Hosts do not choose a separate speech constructor.
41
+
42
+ ## 3. Tracing
40
43
 
41
44
  Tracing is silent by default. Hosts opt in by passing a sink to `runTurn`.
42
45
 
43
46
  ```ts
44
- import { jsonlSink, runTurn } from 'theorum';
47
+ import { createProvider, jsonlSink, runTurn } from 'theorum';
48
+
49
+ const provider = createProvider(profile, { openRouter: { apiKey: hostResolvedOpenRouterKey } });
45
50
 
46
51
  for await (const event of runTurn(request, provider, jsonlSink(hostTraceDir))) {
47
52
  // stream events
package/mod.ts ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * THEORUM public API.
3
+ *
4
+ * Import this entrypoint when an application wants the complete kernel surface:
5
+ * profile registration, turn execution, provider constructors, guardrails,
6
+ * observability sinks, and public type contracts.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { defineProfile, registerProfile, runTurn } from "jsr:@theorum/core";
11
+ *
12
+ * const profile = defineProfile({
13
+ * id: "assistant.basic",
14
+ * model: {
15
+ * allow: ["gemini35FlashLite"],
16
+ * config: {
17
+ * gemini35FlashLite: {
18
+ * apiId: "gemini-3.5-flash-lite",
19
+ * thinking: { on: "high", off: "minimal" },
20
+ * thinkingLevels: ["minimal", "low", "medium", "high"],
21
+ * summaries: { on: "auto", off: "none" },
22
+ * maxOutputTokens: 8192,
23
+ * temperature: 1,
24
+ * keyBuiltins: [],
25
+ * },
26
+ * },
27
+ * },
28
+ * tools: { allow: [] },
29
+ * inputs: { text: true },
30
+ * outputs: {},
31
+ * guardrails: { quota: { perDay: 100 } },
32
+ * });
33
+ *
34
+ * registerProfile(profile);
35
+ * ```
36
+ *
37
+ * @module
38
+ */
39
+
40
+ export { publicError, TheorumError } from './src/guardrails/error.ts';
41
+ export type { QuotaSlotStatus } from './src/guardrails/quota.ts';
42
+ export {
43
+ clientIp,
44
+ quotaMessage,
45
+ releaseSlot,
46
+ resetSlots,
47
+ skipQuota,
48
+ takeSlot,
49
+ } from './src/guardrails/quota.ts';
50
+ export {
51
+ PROJECT_ID_MAX,
52
+ sanitizeProjectId,
53
+ sanitizeText,
54
+ sanitizeTurnRequest,
55
+ } from './src/guardrails/sanitize.ts';
56
+ export { runTurn } from './src/kernel/engine/runner.ts';
57
+ export {
58
+ CATALOG,
59
+ clampThinkingLevel,
60
+ clampThinkingLevelForApiId,
61
+ geminiKindForMime,
62
+ getTool,
63
+ listBuiltinIds,
64
+ mimeAllowed,
65
+ mimeEssence,
66
+ modelEntryByApiId,
67
+ registerTools,
68
+ requireModelSpec,
69
+ resetTools,
70
+ } from './src/kernel/registry/catalog.ts';
71
+ export type { ProfileDefinition } from './src/kernel/registry/profiles.ts';
72
+ export {
73
+ clearProfiles,
74
+ defineProfile,
75
+ getProfile,
76
+ hasProfile,
77
+ listProfiles,
78
+ registerProfile,
79
+ registerProfiles,
80
+ } from './src/kernel/registry/profiles.ts';
81
+ export { projectProfile, resolveTurn } from './src/kernel/registry/resolve.ts';
82
+ export { getStructured, registerStructured } from './src/kernel/registry/schemas.ts';
83
+ export { executeTool } from './src/kernel/registry/tools.ts';
84
+ export type * from './src/kernel/types.ts';
85
+ export {
86
+ jsonlSink,
87
+ memorySink,
88
+ noopSink,
89
+ resolveTraceDir,
90
+ sinkFromDir,
91
+ writeTrace,
92
+ } from './src/observability/trace.ts';
93
+ export type { TraceRecord } from './src/observability/trace-record.ts';
94
+ export type { CreateProviderOptions, GeminiTransport, GeminiVault } from './src/providers/mod.ts';
95
+ export { createProvider } from './src/providers/mod.ts';
package/package.json CHANGED
@@ -1,7 +1,9 @@
1
1
  {
2
2
  "name": "theorum",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, dynamic tools, provider adapters, guardrails, and host-injected traces.",
5
+ "license": "MIT",
6
+ "type": "module",
5
7
  "keywords": [
6
8
  "agent",
7
9
  "ai",
@@ -13,36 +15,42 @@
13
15
  "openrouter",
14
16
  "gemini"
15
17
  ],
16
- "license": "MIT",
17
- "module": "./esm/mod.js",
18
18
  "exports": {
19
- ".": {
20
- "import": "./esm/mod.js"
21
- },
22
- "./kernel": {
23
- "import": "./esm/src/kernel/mod.js"
24
- },
25
- "./providers": {
26
- "import": "./esm/src/providers/mod.js"
27
- },
28
- "./openrouter": {
29
- "import": "./esm/src/providers/openrouter.js"
30
- },
31
- "./guardrails": {
32
- "import": "./esm/src/guardrails/mod.js"
33
- },
34
- "./observability": {
35
- "import": "./esm/src/observability/mod.js"
36
- }
19
+ ".": "./mod.ts",
20
+ "./kernel": "./src/kernel/mod.ts",
21
+ "./providers": "./src/providers/mod.ts",
22
+ "./openrouter": "./src/providers/openrouter-mod.ts",
23
+ "./guardrails": "./src/guardrails/mod.ts",
24
+ "./observability": "./src/observability/mod.ts",
25
+ "./host": "./src/host/mod.ts",
26
+ "./cli": "./src/cli/index.ts",
27
+ "./presets": "./src/presets/mod.ts",
28
+ "./presets/google": "./src/presets/google.ts"
37
29
  },
38
- "scripts": {},
39
- "type": "module",
40
- "sideEffects": false,
30
+ "files": [
31
+ "README.md",
32
+ "deno.json",
33
+ "deno.lock",
34
+ "docs/",
35
+ "mod.ts",
36
+ "src/"
37
+ ],
41
38
  "dependencies": {
42
- "@deno/shim-deno": "~0.18.0"
39
+ "@openrouter/ai-sdk-provider": "1.5.4",
40
+ "ai": "5.0.244"
43
41
  },
44
- "devDependencies": {
45
- "@types/node": "^20.9.0"
42
+ "scripts": {
43
+ "build:npm": "deno run --allow-read --allow-write --allow-env --allow-net --allow-run=npm scripts/build-npm.ts",
44
+ "test": "deno test --allow-read --allow-write --allow-net",
45
+ "coverage": "rm -rf coverage && deno test --allow-read --allow-write --allow-net --coverage=coverage tests/ && deno coverage coverage --lcov --output=coverage/lcov.info && node scripts/lcov-to-istanbul.mjs",
46
+ "lint:biome": "biome check .",
47
+ "lint:ast-grep": "ast-grep scan",
48
+ "lint:fallow": "npm run coverage && fallow audit && fallow health && fallow dupes && fallow dead-code",
49
+ "lint": "npm run lint:biome && npm run lint:ast-grep && npm run lint:fallow"
46
50
  },
47
- "_generatedBy": "dnt@0.43.2"
48
- }
51
+ "devDependencies": {
52
+ "@biomejs/biome": "^2.5.8",
53
+ "@ast-grep/cli": "^0.41.0",
54
+ "fallow": "3.17.0"
55
+ }
56
+ }
@@ -0,0 +1,57 @@
1
+ import { getProfile, listProfiles } from '../../kernel/registry/profiles.ts';
2
+ import type { Profile } from '../../kernel/types.ts';
3
+
4
+ function formatProfileInputs(p: Profile): string {
5
+ const inputs: string[] = [];
6
+ if (p.inputs.text !== false) inputs.push('text');
7
+ if (p.inputs.voice) inputs.push('voice');
8
+ if (p.inputs.attachments) inputs.push(`attachments [${p.inputs.attachments.accept?.join(', ')}]`);
9
+ return inputs.join(' | ');
10
+ }
11
+
12
+ function printProfileCard(p: Profile): void {
13
+ const tools = p.tools.allow?.length ? p.tools.allow.join(', ') : 'none';
14
+ const models = p.model.allow?.join(', ') || 'default';
15
+ const structured =
16
+ typeof p.outputs.structured === 'string'
17
+ ? p.outputs.structured
18
+ : p.outputs.structured
19
+ ? 'custom'
20
+ : 'none';
21
+
22
+ console.log(` • Profile: ${p.id.padEnd(16)} (handle: ${p.identity.handle})`);
23
+ console.log(` - Models: ${models}`);
24
+ console.log(` - Inputs: ${formatProfileInputs(p)}`);
25
+ console.log(` - Tools: ${tools}`);
26
+ console.log(` - Structured: ${structured}`);
27
+ console.log(` - Key Bucket: ${p.model.key ?? 'freeA'}`);
28
+ console.log('-'.repeat(70));
29
+ }
30
+
31
+ export function listProfilesCommand(): void {
32
+ const profiles = listProfiles();
33
+ console.log('\n Registered Theorum Profiles:');
34
+ console.log('='.repeat(70));
35
+ if (profiles.length === 0) {
36
+ console.log(' (No profiles registered in runtime)');
37
+ console.log(`${'='.repeat(70)}\n`);
38
+ return;
39
+ }
40
+
41
+ for (const p of profiles) {
42
+ printProfileCard(p);
43
+ }
44
+ console.log(`Total: ${profiles.length} profiles registered.\n`);
45
+ }
46
+
47
+ export function showProfileCommand(profileId: string): void {
48
+ try {
49
+ const profile = getProfile(profileId);
50
+ console.log(`\n Profile Details: ${profileId}`);
51
+ console.log('='.repeat(70));
52
+ console.log(JSON.stringify(profile, null, 2));
53
+ console.log(`${'='.repeat(70)}\n`);
54
+ } catch (err) {
55
+ console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`);
56
+ }
57
+ }
@@ -0,0 +1,66 @@
1
+ import { runTurn } from '../../kernel/engine/runner.ts';
2
+ import { getProfile } from '../../kernel/registry/profiles.ts';
3
+ import type { ModelProvider, TurnEvent, TurnRequest } from '../../kernel/types.ts';
4
+
5
+ export interface RunOptions {
6
+ profile: string;
7
+ prompt?: string;
8
+ mode?: string;
9
+ search?: boolean;
10
+ map?: boolean;
11
+ provider?: ModelProvider;
12
+ }
13
+
14
+ function handleRunEvent(event: TurnEvent): void {
15
+ if (event.type === 'thought' && event.text) {
16
+ Deno.stdout.write(new TextEncoder().encode(`\x1b[2m${event.text}\x1b[0m`));
17
+ } else if (event.type === 'text' && event.text) {
18
+ Deno.stdout.write(new TextEncoder().encode(event.text));
19
+ } else if (event.type === 'tool' && event.tool) {
20
+ console.log(`\n\x1b[33m⚡ [Tool Call] ${event.tool.name}\x1b[0m:`, event.tool.arguments);
21
+ } else if (event.type === 'structured' && event.structured) {
22
+ console.log('\n\x1b[32m✓ [Structured Output]\x1b[0m:');
23
+ console.log(JSON.stringify(event.structured, null, 2));
24
+ } else if (event.type === 'media' && event.media) {
25
+ console.log(`\n\x1b[34m🖼 [Media Output]\x1b[0m (${event.media.mimeType})`);
26
+ } else if (event.type === 'error' && event.error) {
27
+ console.error(`\n\x1b[31m✗ Error\x1b[0m: ${event.error}`);
28
+ }
29
+ }
30
+
31
+ export async function runCommand(options: RunOptions): Promise<void> {
32
+ getProfile(options.profile);
33
+ const provider = options.provider;
34
+ if (!provider) {
35
+ console.error(
36
+ '\n\x1b[31mExecution Failed\x1b[0m: Theorum CLI does not create providers or read keys. Run turns from a host app with an explicit ModelProvider.\n',
37
+ );
38
+ return;
39
+ }
40
+
41
+ const prompt = options.prompt || 'Hello! Please introduce your capabilities.';
42
+ const tools: Record<string, boolean> = {};
43
+ if (options.search) tools.googleSearch = true;
44
+ if (options.map) tools.googleMaps = true;
45
+
46
+ const req: TurnRequest = {
47
+ profile: options.profile,
48
+ select: options.mode,
49
+ tools: Object.keys(tools).length > 0 ? tools : undefined,
50
+ input: { text: prompt },
51
+ };
52
+
53
+ console.log(`\n▶ [RUNNING TURN] Profile: ${options.profile} (${options.mode ?? 'default'})`);
54
+ console.log(`Prompt: "${prompt}"\n`);
55
+
56
+ try {
57
+ for await (const event of runTurn(req, provider)) {
58
+ handleRunEvent(event);
59
+ }
60
+ console.log('\n');
61
+ } catch (err) {
62
+ console.error(
63
+ `\n\x1b[31mExecution Failed\x1b[0m: ${err instanceof Error ? err.message : String(err)}\n`,
64
+ );
65
+ }
66
+ }
@@ -0,0 +1,195 @@
1
+ import { runTurn } from '../../kernel/engine/runner.ts';
2
+ import { getProfile, listProfiles } from '../../kernel/registry/profiles.ts';
3
+ import type { ModelProvider, Profile, TurnEvent, TurnRequest } from '../../kernel/types.ts';
4
+ import {
5
+ buildCustomTurnRequest,
6
+ type MatrixOptions,
7
+ synthesizeMatrixCombos,
8
+ } from '../matrix/synthesizer.ts';
9
+
10
+ export interface TestRunResult {
11
+ passed: boolean;
12
+ name: string;
13
+ durationSec: number;
14
+ tokensTotal?: number;
15
+ error?: string;
16
+ }
17
+
18
+ interface TestExecutionAccumulator {
19
+ totalTokens: number;
20
+ hasError: boolean;
21
+ errorMessage: string;
22
+ }
23
+
24
+ function printTestHeader(req: TurnRequest, testName: string): void {
25
+ const activeTools = Object.entries(req.tools ?? {})
26
+ .filter(([, v]) => Boolean(v))
27
+ .map(([k]) => k)
28
+ .join(', ');
29
+
30
+ console.log(`\n▶ [THEORUM TEST] ${testName}`);
31
+ console.log(` Profile: ${req.profile} (Mode: ${req.select ?? 'default'})`);
32
+ console.log(` Tools: ${activeTools || 'none'}`);
33
+ console.log(
34
+ ` Attachments: ${req.input?.attachments?.length ?? 0} file(s) | Voice: ${req.input?.voice?.length ? 'yes' : 'no'}`,
35
+ );
36
+ console.log(` ${'-'.repeat(60)}`);
37
+ }
38
+
39
+ function processTestEvent(event: TurnEvent, acc: TestExecutionAccumulator): void {
40
+ if (event.type === 'thought' && event.text) {
41
+ Deno.stdout.write(new TextEncoder().encode('.'));
42
+ } else if (event.type === 'tool' && event.tool) {
43
+ console.log(
44
+ `\n ⚡ [Tool Dispatched] ${event.tool.name}(${JSON.stringify(event.tool.arguments ?? {})})`,
45
+ );
46
+ } else if (event.type === 'structured') {
47
+ console.log(`\n ✓ [Structured Schema Validated]`);
48
+ } else if (event.type === 'media') {
49
+ console.log(`\n ✓ [Media Generated] (${event.media?.mimeType})`);
50
+ } else if (event.type === 'tokens' && event.tokens) {
51
+ acc.totalTokens = event.tokens.total;
52
+ } else if (event.type === 'error' && event.error) {
53
+ acc.hasError = true;
54
+ acc.errorMessage = event.error;
55
+ console.error(`\n [Test Error Detail]: ${event.error}`);
56
+ }
57
+ }
58
+
59
+ function printTestResult(
60
+ passed: boolean,
61
+ durationSec: number,
62
+ acc: TestExecutionAccumulator,
63
+ ): void {
64
+ if (passed) {
65
+ console.log(
66
+ `\n ✓ STATUS: PASSED (took ${durationSec.toFixed(2)}s, ${acc.totalTokens ? `${acc.totalTokens} tokens` : 'ok'})`,
67
+ );
68
+ } else {
69
+ console.log(`\n ✗ STATUS: FAILED: ${acc.errorMessage} (${durationSec.toFixed(2)}s)`);
70
+ }
71
+ }
72
+
73
+ export async function executeSingleTest(
74
+ req: TurnRequest,
75
+ testName: string,
76
+ provider?: ModelProvider,
77
+ ): Promise<TestRunResult> {
78
+ const start = Date.now();
79
+ getProfile(req.profile);
80
+ printTestHeader(req, testName);
81
+
82
+ const acc: TestExecutionAccumulator = {
83
+ totalTokens: 0,
84
+ hasError: false,
85
+ errorMessage: '',
86
+ };
87
+
88
+ try {
89
+ if (!provider) {
90
+ throw new Error(
91
+ 'Theorum CLI does not create providers or read keys. Pass an explicit ModelProvider from the host app.',
92
+ );
93
+ }
94
+ for await (const event of runTurn(req, provider)) {
95
+ processTestEvent(event, acc);
96
+ }
97
+ } catch (err) {
98
+ acc.hasError = true;
99
+ acc.errorMessage = err instanceof Error ? err.message : String(err);
100
+ }
101
+
102
+ const durationSec = (Date.now() - start) / 1000;
103
+ const passed = !acc.hasError;
104
+ printTestResult(passed, durationSec, acc);
105
+
106
+ return {
107
+ passed,
108
+ name: testName,
109
+ durationSec,
110
+ tokensTotal: acc.totalTokens,
111
+ error: acc.errorMessage,
112
+ };
113
+ }
114
+
115
+ function resolveTargetProfiles(
116
+ profileId: string | undefined,
117
+ all: boolean | undefined,
118
+ ): Profile[] | null {
119
+ if (all) {
120
+ return listProfiles();
121
+ }
122
+ if (profileId) {
123
+ try {
124
+ return [getProfile(profileId)];
125
+ } catch (err) {
126
+ console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`);
127
+ return null;
128
+ }
129
+ }
130
+ console.error(
131
+ 'Error: Please specify a profile ID (e.g. `theorum test --profile your-profile`) or `--all`.',
132
+ );
133
+ return null;
134
+ }
135
+
136
+ async function runProfileMatrix(
137
+ profile: Profile,
138
+ provider?: ModelProvider,
139
+ ): Promise<TestRunResult[]> {
140
+ const results: TestRunResult[] = [];
141
+ const combos = synthesizeMatrixCombos(profile);
142
+ for (const combo of combos) {
143
+ const res = await executeSingleTest(combo.req, `${profile.id} [${combo.name}]`, provider);
144
+ results.push(res);
145
+ }
146
+ return results;
147
+ }
148
+
149
+ async function runProfileSingle(
150
+ profile: Profile,
151
+ options: MatrixOptions,
152
+ provider?: ModelProvider,
153
+ ): Promise<TestRunResult> {
154
+ const req = buildCustomTurnRequest(profile, options);
155
+ const testName = options.lite ? `${profile.id} [Lite]` : `${profile.id} [Stress Combo]`;
156
+ return await executeSingleTest(req, testName, provider);
157
+ }
158
+
159
+ function printSummaryReport(results: TestRunResult[]): boolean {
160
+ console.log(`\n${'='.repeat(70)}`);
161
+ console.log(' TEST SUMMARY:');
162
+ console.log('='.repeat(70));
163
+ let allPassed = true;
164
+ for (const r of results) {
165
+ const status = r.passed ? '✓ PASSED' : '✗ FAILED';
166
+ console.log(` ${status.padEnd(10)} ${r.name.padEnd(45)} (${r.durationSec.toFixed(2)}s)`);
167
+ if (!r.passed) {
168
+ allPassed = false;
169
+ if (r.error) console.log(` Reason: ${r.error}`);
170
+ }
171
+ }
172
+ console.log(`${'='.repeat(70)}\n`);
173
+ return allPassed;
174
+ }
175
+
176
+ export async function testProfileCommand(
177
+ profileId?: string,
178
+ options: MatrixOptions & { all?: boolean; matrix?: boolean; provider?: ModelProvider } = {},
179
+ ): Promise<boolean> {
180
+ const targetProfiles = resolveTargetProfiles(profileId, options.all);
181
+ if (!targetProfiles || targetProfiles.length === 0) {
182
+ return false;
183
+ }
184
+
185
+ const results: TestRunResult[] = [];
186
+ for (const profile of targetProfiles) {
187
+ if (options.matrix) {
188
+ results.push(...(await runProfileMatrix(profile, options.provider)));
189
+ } else {
190
+ results.push(await runProfileSingle(profile, options, options.provider));
191
+ }
192
+ }
193
+
194
+ return printSummaryReport(results);
195
+ }