theorum 0.1.2

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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +338 -0
  3. package/docs/AGENT_PROFILE_CONTRACT.md +161 -0
  4. package/docs/CLI_SPEC.md +183 -0
  5. package/docs/SECRETS.md +55 -0
  6. package/esm/_dnt.polyfills.d.ts +11 -0
  7. package/esm/_dnt.polyfills.js +15 -0
  8. package/esm/_dnt.shims.d.ts +5 -0
  9. package/esm/_dnt.shims.js +61 -0
  10. package/esm/mod.d.ts +37 -0
  11. package/esm/mod.js +35 -0
  12. package/esm/package.json +3 -0
  13. package/esm/src/guardrails/error.d.ts +35 -0
  14. package/esm/src/guardrails/error.js +116 -0
  15. package/esm/src/guardrails/injection.d.ts +12 -0
  16. package/esm/src/guardrails/injection.js +220 -0
  17. package/esm/src/guardrails/keys.d.ts +12 -0
  18. package/esm/src/guardrails/keys.js +132 -0
  19. package/esm/src/guardrails/mod.d.ts +14 -0
  20. package/esm/src/guardrails/mod.js +14 -0
  21. package/esm/src/guardrails/sanitize.d.ts +22 -0
  22. package/esm/src/guardrails/sanitize.js +133 -0
  23. package/esm/src/guardrails/sensitive.d.ts +12 -0
  24. package/esm/src/guardrails/sensitive.js +88 -0
  25. package/esm/src/kernel/engine/boundary.d.ts +10 -0
  26. package/esm/src/kernel/engine/boundary.js +55 -0
  27. package/esm/src/kernel/engine/delta.d.ts +8 -0
  28. package/esm/src/kernel/engine/delta.js +362 -0
  29. package/esm/src/kernel/engine/hash.d.ts +1 -0
  30. package/esm/src/kernel/engine/hash.js +9 -0
  31. package/esm/src/kernel/engine/record.d.ts +2 -0
  32. package/esm/src/kernel/engine/record.js +7 -0
  33. package/esm/src/kernel/engine/repair.d.ts +9 -0
  34. package/esm/src/kernel/engine/repair.js +38 -0
  35. package/esm/src/kernel/engine/runner.d.ts +14 -0
  36. package/esm/src/kernel/engine/runner.js +731 -0
  37. package/esm/src/kernel/engine/tree.d.ts +2 -0
  38. package/esm/src/kernel/engine/tree.js +17 -0
  39. package/esm/src/kernel/mod.d.ts +16 -0
  40. package/esm/src/kernel/mod.js +15 -0
  41. package/esm/src/kernel/registry/catalog.d.ts +24 -0
  42. package/esm/src/kernel/registry/catalog.js +213 -0
  43. package/esm/src/kernel/registry/profiles.d.ts +36 -0
  44. package/esm/src/kernel/registry/profiles.js +111 -0
  45. package/esm/src/kernel/registry/resolve.d.ts +20 -0
  46. package/esm/src/kernel/registry/resolve.js +235 -0
  47. package/esm/src/kernel/registry/schemas.d.ts +14 -0
  48. package/esm/src/kernel/registry/schemas.js +23 -0
  49. package/esm/src/kernel/registry/tools.d.ts +12 -0
  50. package/esm/src/kernel/registry/tools.js +36 -0
  51. package/esm/src/kernel/types.d.ts +497 -0
  52. package/esm/src/kernel/types.js +10 -0
  53. package/esm/src/observability/mod.d.ts +12 -0
  54. package/esm/src/observability/mod.js +10 -0
  55. package/esm/src/observability/spans.d.ts +16 -0
  56. package/esm/src/observability/spans.js +56 -0
  57. package/esm/src/observability/trace-attach.d.ts +16 -0
  58. package/esm/src/observability/trace-attach.js +81 -0
  59. package/esm/src/observability/trace-record.d.ts +112 -0
  60. package/esm/src/observability/trace-record.js +140 -0
  61. package/esm/src/observability/trace-usage.d.ts +3 -0
  62. package/esm/src/observability/trace-usage.js +32 -0
  63. package/esm/src/observability/trace.d.ts +23 -0
  64. package/esm/src/observability/trace.js +121 -0
  65. package/esm/src/providers/attachments.d.ts +17 -0
  66. package/esm/src/providers/attachments.js +156 -0
  67. package/esm/src/providers/gemini-tape.d.ts +3 -0
  68. package/esm/src/providers/gemini-tape.js +46 -0
  69. package/esm/src/providers/google-tap.d.ts +3 -0
  70. package/esm/src/providers/google-tap.js +48 -0
  71. package/esm/src/providers/interactions.d.ts +5 -0
  72. package/esm/src/providers/interactions.js +127 -0
  73. package/esm/src/providers/media.d.ts +5 -0
  74. package/esm/src/providers/media.js +125 -0
  75. package/esm/src/providers/mod.d.ts +15 -0
  76. package/esm/src/providers/mod.js +13 -0
  77. package/esm/src/providers/openrouter-payload.d.ts +24 -0
  78. package/esm/src/providers/openrouter-payload.js +177 -0
  79. package/esm/src/providers/openrouter.d.ts +17 -0
  80. package/esm/src/providers/openrouter.js +332 -0
  81. package/esm/src/providers/provider.d.ts +13 -0
  82. package/esm/src/providers/provider.js +123 -0
  83. package/esm/src/providers/sse.d.ts +7 -0
  84. package/esm/src/providers/sse.js +53 -0
  85. package/esm/src/providers/tts.d.ts +24 -0
  86. package/esm/src/providers/tts.js +144 -0
  87. package/package.json +48 -0
@@ -0,0 +1,332 @@
1
+ /**
2
+ * OpenRouter-compatible streaming provider adapter.
3
+ *
4
+ * This module maps THEORUM requests to OpenAI-style chat completions, including
5
+ * reasoning deltas, tool calls, citations, structured output, and token usage.
6
+ *
7
+ * @module
8
+ */
9
+ import "../../_dnt.polyfills.js";
10
+ import { publicError, TheorumError } from '../guardrails/error.js';
11
+ import { tryStructured } from '../kernel/engine/delta.js';
12
+ import { resolveOpenRouterModel, toOpenRouterPayload, } from './openrouter-payload.js';
13
+ import { takeSsePayloads } from './sse.js';
14
+ const HTTP_OK = 200;
15
+ const DEFAULT_OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1';
16
+ async function* readSseLines(res) {
17
+ if (!res.body) {
18
+ throw new TheorumError('empty OpenRouter stream');
19
+ }
20
+ const reader = res.body.getReader();
21
+ const decoder = new TextDecoder();
22
+ let buffer = '';
23
+ let pendingEvent = '';
24
+ while (true) {
25
+ const { done, value } = await reader.read();
26
+ if (done) {
27
+ break;
28
+ }
29
+ buffer += decoder.decode(value, { stream: true });
30
+ const taken = takeSsePayloads(buffer, pendingEvent);
31
+ buffer = taken.rest;
32
+ pendingEvent = taken.pendingEvent;
33
+ for (const payload of taken.payloads) {
34
+ yield payload;
35
+ }
36
+ }
37
+ }
38
+ function extractReasoning(delta) {
39
+ if (typeof delta.reasoning === 'string') {
40
+ return delta.reasoning;
41
+ }
42
+ if (typeof delta.thinking === 'string') {
43
+ return delta.thinking;
44
+ }
45
+ return undefined;
46
+ }
47
+ function applyToolCallObject(callObj, toolMap) {
48
+ let index = 0;
49
+ if (typeof callObj.index === 'number') {
50
+ index = callObj.index;
51
+ }
52
+ const current = toolMap.get(index) ?? { index, arguments: '' };
53
+ if (typeof callObj.id === 'string') {
54
+ current.id = callObj.id;
55
+ }
56
+ const fn = callObj.function;
57
+ if (fn) {
58
+ if (typeof fn.name === 'string') {
59
+ current.name = (current.name ?? '') + fn.name;
60
+ }
61
+ if (typeof fn.arguments === 'string') {
62
+ current.arguments += fn.arguments;
63
+ }
64
+ }
65
+ toolMap.set(index, current);
66
+ }
67
+ function processToolCalls(rawCalls, toolMap) {
68
+ for (const rawCall of rawCalls) {
69
+ if (rawCall && typeof rawCall === 'object') {
70
+ applyToolCallObject(rawCall, toolMap);
71
+ }
72
+ }
73
+ }
74
+ function processDelta(delta, acc) {
75
+ const events = [];
76
+ const reasoning = extractReasoning(delta);
77
+ if (reasoning) {
78
+ events.push({ type: 'thought', text: reasoning });
79
+ }
80
+ if (typeof delta.content === 'string') {
81
+ acc.text += delta.content;
82
+ events.push({ type: 'text', text: delta.content });
83
+ }
84
+ if (Array.isArray(delta.tool_calls)) {
85
+ processToolCalls(delta.tool_calls, acc.toolCalls);
86
+ }
87
+ const evidence = evidenceFromRecord(delta);
88
+ if (evidence && !acc.evidenceSeen) {
89
+ acc.evidenceSeen = true;
90
+ events.push(evidence);
91
+ }
92
+ return events;
93
+ }
94
+ function stringArray(value) {
95
+ if (!Array.isArray(value)) {
96
+ return undefined;
97
+ }
98
+ const out = value.filter((item) => typeof item === 'string');
99
+ return out.length > 0 ? out : undefined;
100
+ }
101
+ function recordField(record, key) {
102
+ const value = record[key];
103
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
104
+ return value;
105
+ }
106
+ return undefined;
107
+ }
108
+ function firstEvidenceRaw(record) {
109
+ for (const key of [
110
+ 'annotations',
111
+ 'citations',
112
+ 'search_results',
113
+ 'searchResults',
114
+ 'provider_metadata',
115
+ 'providerMetadata',
116
+ ]) {
117
+ const value = record[key];
118
+ if (value !== undefined) {
119
+ return value;
120
+ }
121
+ }
122
+ return undefined;
123
+ }
124
+ function evidenceCitations(record) {
125
+ return (stringArray(record.citations) ??
126
+ stringArray(recordField(record, 'provider_metadata')?.citations) ??
127
+ stringArray(recordField(record, 'providerMetadata')?.citations));
128
+ }
129
+ function evidenceAnnotations(record) {
130
+ return Array.isArray(record.annotations) ? record.annotations : undefined;
131
+ }
132
+ function evidenceFromRecord(record) {
133
+ if (firstEvidenceRaw(record) === undefined) {
134
+ return undefined;
135
+ }
136
+ return {
137
+ type: 'evidence',
138
+ evidence: {
139
+ provider: 'openrouter',
140
+ raw: record,
141
+ citations: evidenceCitations(record),
142
+ annotations: evidenceAnnotations(record),
143
+ },
144
+ };
145
+ }
146
+ function parseUsage(usageRaw) {
147
+ if (!usageRaw || typeof usageRaw !== 'object') {
148
+ return undefined;
149
+ }
150
+ const u = usageRaw;
151
+ let input = 0;
152
+ if (typeof u.prompt_tokens === 'number') {
153
+ input = u.prompt_tokens;
154
+ }
155
+ let output = 0;
156
+ if (typeof u.completion_tokens === 'number') {
157
+ output = u.completion_tokens;
158
+ }
159
+ let total = input + output;
160
+ if (typeof u.total_tokens === 'number') {
161
+ total = u.total_tokens;
162
+ }
163
+ return { input, output, total };
164
+ }
165
+ function parseToolArgs(rawArgs) {
166
+ try {
167
+ return JSON.parse(rawArgs);
168
+ }
169
+ catch {
170
+ return { _raw: rawArgs };
171
+ }
172
+ }
173
+ function emitRemainingTools(acc) {
174
+ const events = [];
175
+ for (const tool of acc.toolCalls.values()) {
176
+ if (tool.name) {
177
+ let args;
178
+ if (tool.arguments) {
179
+ args = parseToolArgs(tool.arguments);
180
+ }
181
+ events.push({
182
+ type: 'tool',
183
+ tool: {
184
+ name: tool.name,
185
+ arguments: args,
186
+ ...(tool.id ? { id: tool.id } : {}),
187
+ },
188
+ });
189
+ }
190
+ }
191
+ return events;
192
+ }
193
+ function buildHeaders(apiKey, config) {
194
+ const headers = {
195
+ 'Content-Type': 'application/json',
196
+ Authorization: `Bearer ${apiKey}`,
197
+ };
198
+ if (config.siteUrl) {
199
+ headers['HTTP-Referer'] = config.siteUrl;
200
+ }
201
+ if (config.siteName) {
202
+ headers['X-Title'] = config.siteName;
203
+ }
204
+ return headers;
205
+ }
206
+ async function postOpenRouter(req, config, apiKey) {
207
+ const baseUrl = config.baseUrl ?? DEFAULT_OPENROUTER_BASE_URL;
208
+ const url = `${baseUrl.replace(/\/+$/, '')}/chat/completions`;
209
+ const fetchFn = config.fetch ?? fetch;
210
+ const headers = buildHeaders(apiKey, config);
211
+ const body = JSON.stringify(toOpenRouterPayload(req, config));
212
+ return await fetchFn(url, { method: 'POST', headers, body });
213
+ }
214
+ function processChoiceDeltas(choices, acc) {
215
+ if (!Array.isArray(choices)) {
216
+ return [];
217
+ }
218
+ const events = [];
219
+ for (const choice of choices) {
220
+ events.push(...processChoiceDelta(choice, acc));
221
+ }
222
+ return events;
223
+ }
224
+ function processChoiceDelta(choice, acc) {
225
+ if (!choice || typeof choice !== 'object') {
226
+ return [];
227
+ }
228
+ const c = choice;
229
+ const events = processChoiceDeltaPayload(c.delta, acc);
230
+ const evidence = evidenceFromChoiceMessage(c.message, acc);
231
+ if (evidence) {
232
+ events.push(evidence);
233
+ }
234
+ return events;
235
+ }
236
+ function processChoiceDeltaPayload(delta, acc) {
237
+ if (!delta || typeof delta !== 'object') {
238
+ return [];
239
+ }
240
+ return processDelta(delta, acc);
241
+ }
242
+ function evidenceFromChoiceMessage(message, acc) {
243
+ if (!message || typeof message !== 'object') {
244
+ return undefined;
245
+ }
246
+ const evidence = evidenceFromRecord(message);
247
+ if (!evidence || acc.evidenceSeen) {
248
+ return undefined;
249
+ }
250
+ acc.evidenceSeen = true;
251
+ return evidence;
252
+ }
253
+ function* yieldRemainingStreamEvents(req, acc) {
254
+ for (const ev of emitRemainingTools(acc)) {
255
+ yield ev;
256
+ }
257
+ if (req.structured && acc.text) {
258
+ const structured = tryStructured(acc.text);
259
+ if (structured) {
260
+ yield structured;
261
+ }
262
+ }
263
+ yield { type: 'done' };
264
+ }
265
+ function evidenceFromPayload(payload, acc) {
266
+ const evidence = evidenceFromRecord(payload);
267
+ if (!evidence || acc.evidenceSeen) {
268
+ return undefined;
269
+ }
270
+ acc.evidenceSeen = true;
271
+ return evidence;
272
+ }
273
+ function* eventsFromPayload(payload, acc) {
274
+ const evidence = evidenceFromPayload(payload, acc);
275
+ if (evidence) {
276
+ yield evidence;
277
+ }
278
+ for (const ev of processChoiceDeltas(payload.choices, acc)) {
279
+ yield ev;
280
+ }
281
+ }
282
+ async function* streamOpenRouter(req, config) {
283
+ const apiKey = resolveOpenRouterApiKey(config.apiKey);
284
+ if (!apiKey) {
285
+ yield { type: 'error', error: publicError('missing OpenRouter API key') };
286
+ return;
287
+ }
288
+ try {
289
+ const res = await postOpenRouter(req, config, apiKey);
290
+ if (res.status !== HTTP_OK) {
291
+ yield { type: 'error', error: publicError(`OpenRouter HTTP ${String(res.status)}`) };
292
+ return;
293
+ }
294
+ const acc = { text: '', toolCalls: new Map(), evidenceSeen: false };
295
+ let emittedTokens = false;
296
+ let sawPayload = false;
297
+ for await (const payload of readSseLines(res)) {
298
+ sawPayload = true;
299
+ req.tapGemini?.(payload);
300
+ for (const ev of eventsFromPayload(payload, acc)) {
301
+ yield ev;
302
+ }
303
+ const usage = parseUsage(payload.usage);
304
+ if (usage && !emittedTokens) {
305
+ emittedTokens = true;
306
+ yield { type: 'tokens', tokens: usage };
307
+ }
308
+ }
309
+ if (!sawPayload) {
310
+ yield { type: 'error', error: publicError('empty OpenRouter stream') };
311
+ return;
312
+ }
313
+ yield* yieldRemainingStreamEvents(req, acc);
314
+ }
315
+ catch (err) {
316
+ yield { type: 'error', error: publicError(err) };
317
+ }
318
+ }
319
+ /** Resolve an OpenRouter API key supplied explicitly by the host application. */
320
+ export function resolveOpenRouterApiKey(explicitKey) {
321
+ if (explicitKey?.trim()) {
322
+ return explicitKey.trim();
323
+ }
324
+ return undefined;
325
+ }
326
+ /** Create a `ModelProvider` backed by OpenRouter-compatible chat completions. */
327
+ function createOpenRouterProvider(config = {}) {
328
+ return {
329
+ complete: (req) => streamOpenRouter(req, config),
330
+ };
331
+ }
332
+ export { createOpenRouterProvider, resolveOpenRouterModel, toOpenRouterPayload };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Google Interactions provider adapter.
3
+ *
4
+ * This adapter converts THEORUM's provider-neutral request into the Google
5
+ * Interactions wire format and streams normalized `TurnEvent` objects.
6
+ *
7
+ * @module
8
+ */
9
+ import { type GeminiTransport } from '../guardrails/keys.js';
10
+ import type { ModelProvider } from '../kernel/types.js';
11
+ /** Create a `ModelProvider` backed by Google Interactions streaming. */
12
+ declare function createInteractionsProvider(transport: GeminiTransport): ModelProvider;
13
+ export { createInteractionsProvider };
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Google Interactions provider adapter.
3
+ *
4
+ * This adapter converts THEORUM's provider-neutral request into the Google
5
+ * Interactions wire format and streams normalized `TurnEvent` objects.
6
+ *
7
+ * @module
8
+ */
9
+ import { publicError, TheorumError } from '../guardrails/error.js';
10
+ import { fetchGemini } from '../guardrails/keys.js';
11
+ import { eventsFromComplete, eventsFromDelta, extractTokenEvent, groundingFromEvent, tryStructured, } from '../kernel/engine/delta.js';
12
+ import { tapFetch } from './google-tap.js';
13
+ import { toInteractionsBody } from './interactions.js';
14
+ import { INTERACTIONS_URL, takeSsePayloads } from './sse.js';
15
+ const HTTP_OK = 200;
16
+ async function* readSseRecords(res) {
17
+ if (!res.body) {
18
+ throw new TheorumError('empty Gemini stream');
19
+ }
20
+ const reader = res.body.getReader();
21
+ const decoder = new TextDecoder();
22
+ yield* pumpSse(reader, decoder, '', '');
23
+ }
24
+ async function* pumpSse(reader, decoder, buffer, pendingEvent) {
25
+ const { done, value } = await reader.read();
26
+ if (done) {
27
+ return;
28
+ }
29
+ const next = buffer + decoder.decode(value, { stream: true });
30
+ const taken = takeSsePayloads(next, pendingEvent);
31
+ for (const payload of taken.payloads) {
32
+ yield payload;
33
+ }
34
+ yield* pumpSse(reader, decoder, taken.rest, taken.pendingEvent);
35
+ }
36
+ function eventType(event) {
37
+ return String(event.event_type ?? event.type ?? '');
38
+ }
39
+ function isDeltaEvent(kind) {
40
+ return kind === 'content.delta' || kind === 'step.delta';
41
+ }
42
+ function isCompleteEvent(kind) {
43
+ return (kind === 'interaction.complete' ||
44
+ kind === 'interaction.completed' ||
45
+ kind.startsWith('interaction.'));
46
+ }
47
+ function foldDeltaPayload(event, acc) {
48
+ const deltaEvents = eventsFromDelta(event.delta);
49
+ for (const item of deltaEvents) {
50
+ if (item.type === 'text' && item.text) {
51
+ acc.text += item.text;
52
+ }
53
+ }
54
+ return deltaEvents;
55
+ }
56
+ function foldPayload(event, acc) {
57
+ const kind = eventType(event);
58
+ const events = [];
59
+ if (isDeltaEvent(kind)) {
60
+ events.push(...foldDeltaPayload(event, acc));
61
+ }
62
+ else if (isCompleteEvent(kind)) {
63
+ events.push(...eventsFromComplete(event, acc.text.length > 0));
64
+ }
65
+ // Also check if usage was included on the event directly
66
+ if (!events.some((e) => e.type === 'tokens')) {
67
+ const tokenEvent = extractTokenEvent(event);
68
+ if (tokenEvent) {
69
+ events.push(tokenEvent);
70
+ }
71
+ }
72
+ const groundingEvent = groundingFromEvent(event);
73
+ if (groundingEvent && !events.some((e) => e.type === 'grounding')) {
74
+ events.push(groundingEvent);
75
+ }
76
+ return events;
77
+ }
78
+ function withTap(req, transport) {
79
+ return {
80
+ ...transport,
81
+ fetch: tapFetch(req.tapGemini, transport.fetch),
82
+ };
83
+ }
84
+ async function* streamComplete(req, transport) {
85
+ const res = await fetchGemini(INTERACTIONS_URL, { method: 'POST', body: JSON.stringify(toInteractionsBody(req)) }, req.geminiBucket, withTap(req, transport));
86
+ if (res.status !== HTTP_OK) {
87
+ const errorBody = await res.text().catch(() => '');
88
+ yield {
89
+ type: 'error',
90
+ error: publicError(`Gemini HTTP ${String(res.status)}: ${errorBody}`),
91
+ };
92
+ return;
93
+ }
94
+ const acc = { text: '' };
95
+ for await (const payload of readSseRecords(res)) {
96
+ req.tapGemini?.(payload);
97
+ const events = foldPayload(payload, acc);
98
+ for (const event of events) {
99
+ yield event;
100
+ }
101
+ }
102
+ if (req.structured && acc.text) {
103
+ const structured = tryStructured(acc.text);
104
+ if (structured) {
105
+ yield structured;
106
+ }
107
+ }
108
+ }
109
+ async function* streamGuarded(req, transport) {
110
+ try {
111
+ yield* streamComplete(req, transport);
112
+ }
113
+ catch (err) {
114
+ yield { type: 'error', error: publicError(err) };
115
+ }
116
+ }
117
+ /** Create a `ModelProvider` backed by Google Interactions streaming. */
118
+ function createInteractionsProvider(transport) {
119
+ return {
120
+ complete: (req) => streamGuarded(req, transport),
121
+ };
122
+ }
123
+ export { createInteractionsProvider };
@@ -0,0 +1,7 @@
1
+ declare const INTERACTIONS_URL = "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse";
2
+ declare function takeSsePayloads(buffer: string, pendingEvent?: string): {
3
+ rest: string;
4
+ payloads: Record<string, unknown>[];
5
+ pendingEvent: string;
6
+ };
7
+ export { INTERACTIONS_URL, takeSsePayloads };
@@ -0,0 +1,53 @@
1
+ const INTERACTIONS_URL = 'https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse';
2
+ const DATA_PREFIX = 'data: ';
3
+ const EVENT_PREFIX = 'event: ';
4
+ const DONE = '[DONE]';
5
+ function asObject(parsed) {
6
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
7
+ return parsed;
8
+ }
9
+ return undefined;
10
+ }
11
+ function dataRecord(raw, sseEvent) {
12
+ const data = raw.slice(DATA_PREFIX.length).trim();
13
+ const row = {};
14
+ if (sseEvent) {
15
+ row.sseEvent = sseEvent;
16
+ }
17
+ if (!data || data === DONE) {
18
+ row.eventType = 'sse_done';
19
+ return row;
20
+ }
21
+ try {
22
+ const parsed = JSON.parse(data);
23
+ const obj = asObject(parsed);
24
+ if (obj) {
25
+ return { ...obj, ...row };
26
+ }
27
+ row.eventType = 'sse_unparsed';
28
+ row.data = parsed;
29
+ return row;
30
+ }
31
+ catch {
32
+ row.eventType = 'sse_unparsed';
33
+ row.data = data;
34
+ return row;
35
+ }
36
+ }
37
+ function takeSsePayloads(buffer, pendingEvent = '') {
38
+ const payloads = [];
39
+ const chunks = buffer.split('\n');
40
+ const rest = chunks.pop() ?? '';
41
+ let sseEvent = pendingEvent;
42
+ for (const line of chunks) {
43
+ if (line.startsWith(EVENT_PREFIX)) {
44
+ sseEvent = line.slice(EVENT_PREFIX.length).trim();
45
+ }
46
+ else if (line.startsWith(DATA_PREFIX)) {
47
+ payloads.push(dataRecord(line, sseEvent));
48
+ sseEvent = '';
49
+ }
50
+ }
51
+ return { rest, payloads, pendingEvent: sseEvent };
52
+ }
53
+ export { INTERACTIONS_URL, takeSsePayloads };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * OpenRouter TTS provider utilities.
3
+ *
4
+ * Provides direct text-to-speech streaming and a `ModelProvider` wrapper for
5
+ * voice output profiles.
6
+ *
7
+ * @module
8
+ */
9
+ import type { ModelProvider, ProviderCompleteRequest, TurnEvent } from '../kernel/types.js';
10
+ /** Wrap raw PCM bytes in a RIFF/WAVE container. */
11
+ export declare function wrapPcmAsWav(pcm: Uint8Array, sampleRate?: number): Uint8Array;
12
+ /** Host-supplied OpenRouter TTS configuration. */
13
+ export interface OpenRouterTtsConfig {
14
+ apiKey?: string;
15
+ voiceName?: string;
16
+ baseUrl?: string;
17
+ siteUrl?: string;
18
+ siteName?: string;
19
+ fetch?: typeof fetch;
20
+ }
21
+ /** Stream one OpenRouter TTS synthesis request as THEORUM events. */
22
+ export declare function streamOpenRouterTts(req: ProviderCompleteRequest, config?: OpenRouterTtsConfig): AsyncGenerator<TurnEvent>;
23
+ /** Create a `ModelProvider` that emits TTS media events. */
24
+ export declare function createOpenRouterTtsProvider(config?: OpenRouterTtsConfig): ModelProvider;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * OpenRouter TTS provider utilities.
3
+ *
4
+ * Provides direct text-to-speech streaming and a `ModelProvider` wrapper for
5
+ * voice output profiles.
6
+ *
7
+ * @module
8
+ */
9
+ import { publicError } from '../guardrails/error.js';
10
+ import { resolveOpenRouterApiKey } from './openrouter.js';
11
+ const SAMPLE_RATE = 24000;
12
+ const TTS_MODEL = 'google/gemini-3.1-flash-tts-preview';
13
+ const HTTP_OK = 200;
14
+ function bytesToBase64(bytes) {
15
+ let bin = '';
16
+ for (let i = 0; i < bytes.length; i++)
17
+ bin += String.fromCharCode(bytes[i]);
18
+ return btoa(bin);
19
+ }
20
+ function writeAscii(view, offset, str) {
21
+ for (let i = 0; i < str.length; i++)
22
+ view.setUint8(offset + i, str.charCodeAt(i));
23
+ }
24
+ /** Wrap raw PCM bytes in a RIFF/WAVE container. */
25
+ export function wrapPcmAsWav(pcm, sampleRate = SAMPLE_RATE) {
26
+ const numChannels = 1;
27
+ const bitsPerSample = 16;
28
+ const byteRate = (sampleRate * numChannels * bitsPerSample) / 8;
29
+ const blockAlign = (numChannels * bitsPerSample) / 8;
30
+ const dataSize = pcm.length;
31
+ const buf = new ArrayBuffer(44 + dataSize);
32
+ const view = new DataView(buf);
33
+ writeAscii(view, 0, 'RIFF');
34
+ view.setUint32(4, 36 + dataSize, true);
35
+ writeAscii(view, 8, 'WAVE');
36
+ writeAscii(view, 12, 'fmt ');
37
+ view.setUint32(16, 16, true);
38
+ view.setUint16(20, 1, true); // PCM
39
+ view.setUint16(22, numChannels, true);
40
+ view.setUint32(24, sampleRate, true);
41
+ view.setUint32(28, byteRate, true);
42
+ view.setUint16(32, blockAlign, true);
43
+ view.setUint16(34, bitsPerSample, true);
44
+ writeAscii(view, 36, 'data');
45
+ view.setUint32(40, dataSize, true);
46
+ new Uint8Array(buf, 44).set(pcm);
47
+ return new Uint8Array(buf);
48
+ }
49
+ function extractInputText(input) {
50
+ return input
51
+ .filter((p) => p.type === 'text')
52
+ .map((p) => (p.type === 'text' ? p.text : ''))
53
+ .join(' ')
54
+ .trim();
55
+ }
56
+ function buildHeaders(apiKey, config) {
57
+ const headers = {
58
+ Authorization: `Bearer ${apiKey}`,
59
+ 'Content-Type': 'application/json',
60
+ };
61
+ if (config.siteUrl) {
62
+ headers['HTTP-Referer'] = config.siteUrl;
63
+ }
64
+ if (config.siteName) {
65
+ headers['X-Title'] = config.siteName;
66
+ }
67
+ return headers;
68
+ }
69
+ function buildPayload(text, voiceSpec, configVoiceName) {
70
+ const voice = voiceSpec?.voice ?? configVoiceName;
71
+ const responseFormat = voiceSpec?.responseFormat ?? 'pcm';
72
+ const payload = {
73
+ model: TTS_MODEL,
74
+ input: text,
75
+ response_format: responseFormat,
76
+ };
77
+ if (voice) {
78
+ payload.voice = voice;
79
+ }
80
+ return payload;
81
+ }
82
+ async function requestTts(apiKey, text, req, config) {
83
+ const fetchFn = config.fetch ?? fetch;
84
+ const baseUrl = config.baseUrl?.replace(/\/+$/, '') ?? 'https://openrouter.ai/api/v1';
85
+ const url = `${baseUrl}/audio/speech`;
86
+ return await fetchFn(url, {
87
+ method: 'POST',
88
+ headers: buildHeaders(apiKey, config),
89
+ body: JSON.stringify(buildPayload(text, req.voice, config.voiceName)),
90
+ });
91
+ }
92
+ function* yieldTtsSuccess(rawBytes, text, responseFormat) {
93
+ let mediaMime = 'audio/mpeg';
94
+ let mediaBytes = rawBytes;
95
+ if (responseFormat === 'pcm') {
96
+ mediaMime = 'audio/wav';
97
+ mediaBytes = wrapPcmAsWav(rawBytes);
98
+ }
99
+ yield {
100
+ type: 'media',
101
+ media: { mimeType: mediaMime, data: bytesToBase64(mediaBytes) },
102
+ };
103
+ const inputTokens = Math.max(1, Math.round(text.length / 4));
104
+ const outputTokens = Math.max(1, Math.round(rawBytes.length / 100));
105
+ yield {
106
+ type: 'tokens',
107
+ tokens: { input: inputTokens, output: outputTokens, total: inputTokens + outputTokens },
108
+ };
109
+ yield { type: 'done' };
110
+ }
111
+ /** Stream one OpenRouter TTS synthesis request as THEORUM events. */
112
+ export async function* streamOpenRouterTts(req, config = {}) {
113
+ const apiKey = resolveOpenRouterApiKey(config.apiKey);
114
+ if (!apiKey) {
115
+ yield { type: 'error', error: publicError('missing OpenRouter API key for TTS') };
116
+ return;
117
+ }
118
+ const text = extractInputText(req.input);
119
+ if (!text) {
120
+ yield { type: 'error', error: publicError('empty text for TTS') };
121
+ return;
122
+ }
123
+ const res = await requestTts(apiKey, text, req, config);
124
+ if (res.status !== HTTP_OK) {
125
+ yield { type: 'error', error: publicError(`OpenRouter TTS HTTP ${String(res.status)}`) };
126
+ return;
127
+ }
128
+ const arrayBuffer = await res.arrayBuffer();
129
+ const rawBytes = new Uint8Array(arrayBuffer);
130
+ if (rawBytes.length === 0) {
131
+ yield { type: 'error', error: publicError('no audio returned from TTS') };
132
+ return;
133
+ }
134
+ const responseFormat = req.voice?.responseFormat ?? 'pcm';
135
+ for (const ev of yieldTtsSuccess(rawBytes, text, responseFormat)) {
136
+ yield ev;
137
+ }
138
+ }
139
+ /** Create a `ModelProvider` that emits TTS media events. */
140
+ export function createOpenRouterTtsProvider(config = {}) {
141
+ return {
142
+ complete: (req) => streamOpenRouterTts(req, config),
143
+ };
144
+ }