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,181 @@
1
+ /**
2
+ * Tool catalog and MIME helpers.
3
+ *
4
+ * Model wire metadata is host-owned on `profile.model.config`. This module only
5
+ * keeps builtin/custom tool descriptors and shared MIME utilities.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ import { TheorumError } from '../../guardrails/error.ts';
11
+ import type {
12
+ BuiltinToolId,
13
+ Catalog,
14
+ GeminiInputKind,
15
+ ModelId,
16
+ ModelSpec,
17
+ Profile,
18
+ ThinkingLevel,
19
+ ToolCatalogEntry,
20
+ ToolId,
21
+ } from '../types.ts';
22
+
23
+ const ASK_USER_SCHEMA = {
24
+ type: 'object',
25
+ properties: {
26
+ kind: { type: 'string', enum: ['confirm', 'choice', 'text'] },
27
+ prompt: { type: 'string' },
28
+ options: { type: 'array', items: { type: 'string' } },
29
+ },
30
+ required: ['kind', 'prompt'],
31
+ };
32
+
33
+ /** Harness tools that always ship with THEORUM. */
34
+ const HARNESS_TOOLS: Record<ToolId, ToolCatalogEntry> = {
35
+ askUser: { kind: 'custom', ui: true, schema: ASK_USER_SCHEMA },
36
+ };
37
+
38
+ /** Live tool catalog. Starts with harness tools; presets/hosts register more. */
39
+ const CATALOG: Catalog = {
40
+ tools: { ...HARNESS_TOOLS },
41
+ };
42
+
43
+ /** Register or replace tool descriptors (idempotent per id). */
44
+ function registerTools(entries: Record<string, ToolCatalogEntry>): void {
45
+ Object.assign(CATALOG.tools, entries);
46
+ }
47
+
48
+ /** Look up one registered tool descriptor. */
49
+ function getTool(id: ToolId): ToolCatalogEntry | undefined {
50
+ return CATALOG.tools[id];
51
+ }
52
+
53
+ /** Ids of all registered provider builtins. */
54
+ function listBuiltinIds(): BuiltinToolId[] {
55
+ return Object.entries(CATALOG.tools)
56
+ .filter(([, entry]) => entry.kind === 'builtin')
57
+ .map(([id]) => id);
58
+ }
59
+
60
+ /** Restore harness-only tools (tests / host reloads). */
61
+ function resetTools(): void {
62
+ for (const id of Object.keys(CATALOG.tools)) {
63
+ delete CATALOG.tools[id];
64
+ }
65
+ Object.assign(CATALOG.tools, HARNESS_TOOLS);
66
+ }
67
+
68
+ /** Gemini Interactions inline MIME → part type (adapter wire map). */
69
+ const GEMINI_INPUT_KINDS: Record<string, GeminiInputKind> = {
70
+ 'image/png': 'image',
71
+ 'image/jpeg': 'image',
72
+ 'image/jpg': 'image',
73
+ 'image/webp': 'image',
74
+ 'image/heic': 'image',
75
+ 'image/heif': 'image',
76
+ 'audio/wav': 'audio',
77
+ 'audio/x-wav': 'audio',
78
+ 'audio/mpeg': 'audio',
79
+ 'audio/mp3': 'audio',
80
+ 'audio/aiff': 'audio',
81
+ 'audio/aac': 'audio',
82
+ 'audio/ogg': 'audio',
83
+ 'audio/flac': 'audio',
84
+ 'audio/webm': 'audio',
85
+ 'audio/mp4': 'audio',
86
+ 'audio/pcm': 'audio',
87
+ 'video/mp4': 'video',
88
+ 'video/mpeg': 'video',
89
+ 'video/quicktime': 'video',
90
+ 'video/x-msvideo': 'video',
91
+ 'video/x-flv': 'video',
92
+ 'video/mpg': 'video',
93
+ 'video/webm': 'video',
94
+ 'video/wmv': 'video',
95
+ 'video/x-ms-wmv': 'video',
96
+ 'video/3gpp': 'video',
97
+ 'application/pdf': 'document',
98
+ 'text/plain': 'document',
99
+ 'text/csv': 'document',
100
+ 'text/markdown': 'document',
101
+ 'text/html': 'document',
102
+ 'application/json': 'document',
103
+ };
104
+
105
+ function mimeEssence(mime: string): string {
106
+ const [base] = mime.split(';');
107
+ return (base ?? '').trim().toLowerCase();
108
+ }
109
+
110
+ function mimeAllowed(accept: string[], mime: string): boolean {
111
+ const actual = mimeEssence(mime);
112
+ return accept.some((rule) => {
113
+ const allowed = mimeEssence(rule);
114
+ if (allowed.endsWith('/*')) {
115
+ return actual.startsWith(allowed.slice(0, -1));
116
+ }
117
+ return allowed === actual;
118
+ });
119
+ }
120
+
121
+ function geminiKindForMime(mime: string): GeminiInputKind | undefined {
122
+ return GEMINI_INPUT_KINDS[mimeEssence(mime)];
123
+ }
124
+
125
+ /** Require a host-declared model spec for an allowed profile model id. */
126
+ function requireModelSpec(profile: Profile, modelId: ModelId): ModelSpec {
127
+ const spec = profile.model.config[modelId];
128
+ if (!spec) {
129
+ throw new TheorumError(`Profile ${profile.id} has no model spec for '${modelId}'`);
130
+ }
131
+ return spec;
132
+ }
133
+
134
+ function clampLevels(entry: ModelSpec | undefined, level: ThinkingLevel): ThinkingLevel {
135
+ if (!entry?.thinkingLevels || entry.thinkingLevels.length === 0) {
136
+ return level;
137
+ }
138
+ if (entry.thinkingLevels.includes(level)) {
139
+ return level;
140
+ }
141
+ const fallback = entry.thinking.off;
142
+ if (entry.thinkingLevels.includes(fallback)) {
143
+ return fallback;
144
+ }
145
+ const first = entry.thinkingLevels[0];
146
+ return first ?? level;
147
+ }
148
+
149
+ /** Clamp a requested thinking level to what the model spec accepts. */
150
+ function clampThinkingLevel(spec: ModelSpec, level: ThinkingLevel): ThinkingLevel {
151
+ return clampLevels(spec, level);
152
+ }
153
+
154
+ /** Look up a model spec by provider-native API id within a host specs map. */
155
+ function modelEntryByApiId(specs: Record<string, ModelSpec>, apiId: string): ModelSpec | undefined {
156
+ return Object.values(specs).find((m) => m.apiId === apiId);
157
+ }
158
+
159
+ /** Clamp thinking level using a provider-native API id within a host specs map. */
160
+ function clampThinkingLevelForApiId(
161
+ specs: Record<string, ModelSpec>,
162
+ apiId: string,
163
+ level: ThinkingLevel,
164
+ ): ThinkingLevel {
165
+ return clampLevels(modelEntryByApiId(specs, apiId), level);
166
+ }
167
+
168
+ export {
169
+ CATALOG,
170
+ clampThinkingLevel,
171
+ clampThinkingLevelForApiId,
172
+ geminiKindForMime,
173
+ getTool,
174
+ listBuiltinIds,
175
+ mimeAllowed,
176
+ mimeEssence,
177
+ modelEntryByApiId,
178
+ registerTools,
179
+ requireModelSpec,
180
+ resetTools,
181
+ };
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Kernel ingress: input parts, image pins, and speech-role checks.
3
+ *
4
+ * Owned by the kernel so `resolveTurn` does not import provider adapters.
5
+ *
6
+ * @module
7
+ */
8
+
9
+ import { TheorumError } from '../../guardrails/error.ts';
10
+ import { wrapUserData } from '../engine/boundary.ts';
11
+ import { synthesizeRepairPrompt } from '../engine/repair.ts';
12
+ import type {
13
+ BuiltinToolId,
14
+ GeminiInputKind,
15
+ ImageResponseFormat,
16
+ InteractionPart,
17
+ ModelId,
18
+ Profile,
19
+ TurnBlob,
20
+ TurnRequest,
21
+ } from '../types.ts';
22
+ import { assertAttachmentLimits, requireMediaLimits } from './attachments.ts';
23
+ import { geminiKindForMime, mimeAllowed, mimeEssence } from './catalog.ts';
24
+
25
+ function listedValue(allowed: string[] | undefined, value: string | undefined): string | undefined {
26
+ if (!value) {
27
+ return undefined;
28
+ }
29
+ if (!allowed || allowed.length === 0) {
30
+ return value;
31
+ }
32
+ if (allowed.includes(value)) {
33
+ return value;
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ function resolveSlotOrPin(
39
+ profileId: string,
40
+ label: string,
41
+ slotValue: string | undefined,
42
+ pin: string | undefined,
43
+ allow: string[] | undefined,
44
+ ): string | undefined {
45
+ if (slotValue !== undefined) {
46
+ const fromSlot = listedValue(allow, slotValue);
47
+ if (!fromSlot) {
48
+ throw new TheorumError(`Unknown image ${label} for ${profileId}`);
49
+ }
50
+ return fromSlot;
51
+ }
52
+ if (pin === undefined) {
53
+ return undefined;
54
+ }
55
+ const fromPin = listedValue(allow, pin);
56
+ if (!fromPin) {
57
+ throw new TheorumError(`Unknown image ${label} for ${profileId}`);
58
+ }
59
+ return fromPin;
60
+ }
61
+
62
+ function assertImageRole(profile: Profile): NonNullable<Profile['outputs']['image']> {
63
+ const pins = profile.outputs.image;
64
+ if (!pins) {
65
+ throw new TheorumError(
66
+ `Profile ${profile.id} requests image output but does not set outputs.image`,
67
+ );
68
+ }
69
+ assertExclusiveNativeOutput(profile, 'image');
70
+ return pins;
71
+ }
72
+
73
+ function assertSpeechRole(profile: Profile): void {
74
+ if (!profile.outputs.speech) {
75
+ return;
76
+ }
77
+ assertExclusiveNativeOutput(profile, 'speech');
78
+ if (profile.outputs.speech.format === 'mp3' && profile.model.protocol === 'geminiInteractions') {
79
+ throw new TheorumError(
80
+ `Profile ${profile.id}: outputs.speech.format 'mp3' requires protocol 'openAi' ` +
81
+ `(geminiInteractions speech returns PCM and emits WAV)`,
82
+ );
83
+ }
84
+ }
85
+
86
+ function assertExclusiveNativeOutput(profile: Profile, kind: 'image' | 'speech'): void {
87
+ const other = kind === 'image' ? 'speech' : 'image';
88
+ if (profile.outputs[other]) {
89
+ throw new TheorumError(
90
+ `Profile ${profile.id} cannot mix outputs.${kind} with outputs.${other}`,
91
+ );
92
+ }
93
+ if (profile.outputs.structured !== null && profile.outputs.structured !== undefined) {
94
+ throw new TheorumError(
95
+ `Profile ${profile.id} cannot mix structured JSON with native ${kind} output`,
96
+ );
97
+ }
98
+ }
99
+
100
+ function resolveImageFormat(
101
+ profile: Profile,
102
+ _model: ModelId,
103
+ slots?: Record<string, string>,
104
+ ): ImageResponseFormat | null {
105
+ if (!profile.outputs.image) {
106
+ return null;
107
+ }
108
+ const pins = assertImageRole(profile);
109
+ const aspectRatio = resolveSlotOrPin(
110
+ profile.id,
111
+ 'aspect',
112
+ slots?.aspectRatio,
113
+ pins.aspectRatio,
114
+ profile.inputs.slots?.aspectRatio,
115
+ );
116
+ const size = resolveSlotOrPin(
117
+ profile.id,
118
+ 'size',
119
+ slots?.size,
120
+ pins.size,
121
+ profile.inputs.slots?.size,
122
+ );
123
+ if (!(aspectRatio && size)) {
124
+ throw new TheorumError(`Unknown image aspect or size for ${profile.id}`);
125
+ }
126
+ return {
127
+ type: 'image',
128
+ mimeType: pins.mimeType ?? 'image/jpeg',
129
+ aspectRatio,
130
+ size,
131
+ };
132
+ }
133
+
134
+ function assertGeminiMime(mime: string): GeminiInputKind {
135
+ const kind = geminiKindForMime(mime);
136
+ if (!kind) {
137
+ throw new TheorumError(`MIME '${mime}' is not a Gemini input type`);
138
+ }
139
+ return kind;
140
+ }
141
+
142
+ function mediaParts(
143
+ profile: Profile,
144
+ model: ModelId,
145
+ blobs: TurnBlob[],
146
+ channel: 'attachments' | 'voice',
147
+ ): InteractionPart[] {
148
+ const accept =
149
+ channel === 'voice' ? profile.inputs.voice?.accept : profile.inputs.attachments?.accept;
150
+ if (!accept) {
151
+ throw new TheorumError(`Profile ${profile.id} does not accept ${channel}`);
152
+ }
153
+ const maxInputImages = profile.outputs.image?.maxInputImages;
154
+ const imageCount = blobs.filter((blob) => geminiKindForMime(blob.mimeType) === 'image').length;
155
+ if (maxInputImages !== undefined && imageCount > maxInputImages) {
156
+ throw new TheorumError(`At most ${maxInputImages} reference images on ${model}`);
157
+ }
158
+ return blobs.map((blob) => {
159
+ const kind = assertGeminiMime(blob.mimeType);
160
+ if (!mimeAllowed(accept, blob.mimeType)) {
161
+ throw new TheorumError(`MIME '${blob.mimeType}' is not accepted on ${profile.id}`);
162
+ }
163
+ const essence = mimeEssence(blob.mimeType);
164
+ return {
165
+ type: kind,
166
+ mimeType: essence === 'image/jpg' ? 'image/jpeg' : essence,
167
+ data: blob.data,
168
+ };
169
+ });
170
+ }
171
+
172
+ function extractTextPart(profile: Profile, req: TurnRequest): InteractionPart | null {
173
+ const { text, repair, history } = req.input ?? {};
174
+ if (profile.inputs.text === false) {
175
+ if (text) {
176
+ throw new TheorumError(`Profile ${profile.id} does not accept text input`);
177
+ }
178
+ return null;
179
+ }
180
+ let promptText = text;
181
+ if (repair) {
182
+ promptText = synthesizeRepairPrompt({ profile, repair, history });
183
+ }
184
+ if (!promptText) {
185
+ return null;
186
+ }
187
+ return { type: 'text', text: wrapUserData(promptText) };
188
+ }
189
+
190
+ function extractMediaParts(profile: Profile, model: ModelId, req: TurnRequest): InteractionPart[] {
191
+ const { attachments, voice } = req.input ?? {};
192
+ const files = attachments ?? [];
193
+ const clips = voice ?? [];
194
+ if (files.length + clips.length > 0) {
195
+ assertAttachmentLimits([...files, ...clips], requireMediaLimits(profile));
196
+ }
197
+ const parts: InteractionPart[] = [];
198
+ if (files.length > 0) {
199
+ parts.push(...mediaParts(profile, model, files, 'attachments'));
200
+ }
201
+ if (clips.length > 0) {
202
+ parts.push(...mediaParts(profile, model, clips, 'voice'));
203
+ }
204
+ return parts;
205
+ }
206
+
207
+ function resolveInputParts(profile: Profile, model: ModelId, req: TurnRequest): InteractionPart[] {
208
+ const parts: InteractionPart[] = [];
209
+ const textPart = extractTextPart(profile, req);
210
+ if (textPart) {
211
+ parts.push(textPart);
212
+ }
213
+ parts.push(...extractMediaParts(profile, model, req));
214
+ return parts;
215
+ }
216
+
217
+ function assertImageGrounding(profile: Profile, model: ModelId, builtins: BuiltinToolId[]): void {
218
+ if (profile.outputs.image?.allowsGrounding === false && builtins.length > 0) {
219
+ throw new TheorumError(`Grounding tools are not valid on ${model}`);
220
+ }
221
+ }
222
+
223
+ export { assertImageGrounding, assertSpeechRole, resolveImageFormat, resolveInputParts };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Runtime profile registry for host-owned THEORUM profiles.
3
+ *
4
+ * THEORUM ships profile types and defaults, not application profiles. Host apps
5
+ * register their profiles at process startup or test setup.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ import { TheorumError } from '../../guardrails/error.ts';
11
+ import type { ModelId, Profile } from '../types.ts';
12
+
13
+ const profiles = new Map<string, Profile>();
14
+
15
+ /** Host-authored profile definition, with defaults applied to omitted sections. */
16
+ export type ProfileDefinition = {
17
+ id: Profile['id'];
18
+ identity?: Partial<Profile['identity']>;
19
+ model: Partial<Profile['model']> & Pick<Profile['model'], 'allow' | 'config'>;
20
+ tools?: Partial<Profile['tools']>;
21
+ inputs?: Partial<Profile['inputs']>;
22
+ outputs?: Partial<Profile['outputs']>;
23
+ guardrails?: Partial<Profile['guardrails']>;
24
+ };
25
+
26
+ function assertModelSpecs(
27
+ profileId: string,
28
+ allow: ModelId[],
29
+ config: Profile['model']['config'],
30
+ ): void {
31
+ for (const id of allow) {
32
+ if (!config[id]) {
33
+ throw new TheorumError(`Profile ${profileId} allowlists '${id}' without a model spec`);
34
+ }
35
+ }
36
+ }
37
+
38
+ function buildDefaultIdentity(
39
+ id: Profile['id'],
40
+ identity?: Partial<Profile['identity']>,
41
+ ): Profile['identity'] {
42
+ return {
43
+ handle: identity?.handle ?? id,
44
+ chat: identity?.chat,
45
+ system: identity?.system,
46
+ systemByRole: identity?.systemByRole,
47
+ };
48
+ }
49
+
50
+ function buildDefaultModel(profileId: string, model: ProfileDefinition['model']): Profile['model'] {
51
+ assertModelSpecs(profileId, model.allow, model.config);
52
+ return {
53
+ protocol: model.protocol ?? 'geminiInteractions',
54
+ provider: model.provider ?? 'google',
55
+ allow: model.allow,
56
+ config: model.config,
57
+ thinking: model.thinking ?? 'minimal',
58
+ controls: model.controls ?? [],
59
+ maxSteps: model.maxSteps ?? 1,
60
+ key: model.key ?? 'freeA',
61
+ select: model.select,
62
+ };
63
+ }
64
+
65
+ function buildDefaultInputs(inputs?: Partial<Profile['inputs']>): Profile['inputs'] {
66
+ return {
67
+ text: inputs?.text ?? true,
68
+ attachments: inputs?.attachments,
69
+ voice: inputs?.voice,
70
+ maxFiles: inputs?.maxFiles,
71
+ maxBytes: inputs?.maxBytes,
72
+ maxTurnBytes: inputs?.maxTurnBytes,
73
+ limitsByMime: inputs?.limitsByMime,
74
+ slots: inputs?.slots,
75
+ };
76
+ }
77
+
78
+ function buildDefaultOutputs(outputs?: Partial<Profile['outputs']>): Profile['outputs'] {
79
+ return {
80
+ structured: outputs?.structured ?? null,
81
+ image: outputs?.image,
82
+ speech: outputs?.speech,
83
+ validation: outputs?.validation,
84
+ streaming: outputs?.streaming,
85
+ };
86
+ }
87
+
88
+ function buildDefaultGuardrails(
89
+ guardrails?: Partial<Profile['guardrails']>,
90
+ ): Profile['guardrails'] {
91
+ return {
92
+ quota: guardrails?.quota,
93
+ canary: guardrails?.canary ?? true,
94
+ sanitizeInput: guardrails?.sanitizeInput ?? true,
95
+ redactSensitive: guardrails?.redactSensitive ?? true,
96
+ egress: guardrails?.egress,
97
+ };
98
+ }
99
+
100
+ /** Define a typed profile with stable defaults for optional properties. */
101
+ function defineProfile(input: ProfileDefinition): Profile {
102
+ return {
103
+ id: input.id,
104
+ identity: buildDefaultIdentity(input.id, input.identity),
105
+ model: buildDefaultModel(input.id, input.model),
106
+ tools: { allow: input.tools?.allow ?? [] },
107
+ inputs: buildDefaultInputs(input.inputs),
108
+ outputs: buildDefaultOutputs(input.outputs),
109
+ guardrails: buildDefaultGuardrails(input.guardrails),
110
+ };
111
+ }
112
+
113
+ /** Register one host-owned profile in the process-local registry. */
114
+ function registerProfile(profileInput: Profile | ProfileDefinition): void {
115
+ const profile = defineProfile(profileInput);
116
+ assertModelSpecs(profile.id, profile.model.allow, profile.model.config);
117
+ const { attachments, voice, maxFiles, maxBytes, maxTurnBytes } = profile.inputs;
118
+ if (attachments || voice) {
119
+ if (!(maxFiles && maxBytes && maxTurnBytes)) {
120
+ throw new TheorumError(`Profile ${profile.id} must set maxFiles, maxBytes, and maxTurnBytes`);
121
+ }
122
+ }
123
+ profiles.set(profile.id, profile);
124
+ }
125
+
126
+ /** Register several host-owned profiles in order. */
127
+ function registerProfiles(profilesList: Array<Profile | ProfileDefinition>): void {
128
+ for (const p of profilesList) {
129
+ registerProfile(p);
130
+ }
131
+ }
132
+
133
+ /** Return whether a profile id is currently registered. */
134
+ function hasProfile(id: string): boolean {
135
+ return profiles.has(id);
136
+ }
137
+
138
+ /** List all currently registered profiles. */
139
+ function listProfiles(): Profile[] {
140
+ return Array.from(profiles.values());
141
+ }
142
+
143
+ /** Clear the process-local registry; intended for tests and host reloads. */
144
+ function clearProfiles(): void {
145
+ profiles.clear();
146
+ }
147
+
148
+ /** Fetch a registered profile or throw a `TheorumError`. */
149
+ function getProfile(id: string): Profile {
150
+ const profile = profiles.get(id);
151
+ if (!profile) {
152
+ throw new TheorumError(`Unknown profile '${id}'`);
153
+ }
154
+ return profile;
155
+ }
156
+
157
+ export {
158
+ clearProfiles,
159
+ defineProfile,
160
+ getProfile,
161
+ hasProfile,
162
+ listProfiles,
163
+ registerProfile,
164
+ registerProfiles,
165
+ };
@@ -0,0 +1,31 @@
1
+ import type { ProviderCompleteRequest, ResolvedGeneration } from '../types.ts';
2
+
3
+ /** Build the provider request projection shared by execution and tracing. */
4
+ function providerCompleteRequest(
5
+ generation: ResolvedGeneration,
6
+ system: string,
7
+ ): ProviderCompleteRequest {
8
+ return {
9
+ model: generation.model,
10
+ apiId: generation.apiId,
11
+ openRouterId: generation.openRouterId,
12
+ previousInteractionId: generation.previousInteractionId,
13
+ store: generation.store,
14
+ thinking: generation.thinking,
15
+ summaries: generation.summaries,
16
+ maxOutputTokens: generation.maxOutputTokens,
17
+ temperature: generation.temperature,
18
+ builtins: generation.builtins,
19
+ system,
20
+ input: generation.input,
21
+ history: generation.history,
22
+ dynamicTools: generation.dynamicTools,
23
+ dynamicToolLoader: generation.dynamicToolLoader,
24
+ structured: generation.structured,
25
+ image: generation.image,
26
+ speech: generation.speech,
27
+ geminiBucket: generation.geminiBucket,
28
+ };
29
+ }
30
+
31
+ export { providerCompleteRequest };