theorum 0.1.3 → 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.
- package/README.md +30 -9
- package/deno.json +57 -0
- package/deno.lock +469 -0
- package/{esm/mod.d.ts → mod.ts} +57 -15
- package/package.json +35 -44
- package/src/cli/commands/profile.ts +57 -0
- package/src/cli/commands/run.ts +66 -0
- package/src/cli/commands/test.ts +195 -0
- package/src/cli/index.ts +161 -0
- package/src/cli/matrix/fixtures.ts +96 -0
- package/src/cli/matrix/synthesizer.ts +240 -0
- package/src/guardrails/error.ts +142 -0
- package/src/guardrails/injection.ts +254 -0
- package/src/guardrails/mod.ts +40 -0
- package/src/guardrails/quota.ts +87 -0
- package/src/guardrails/sanitize.ts +165 -0
- package/src/guardrails/sensitive.ts +96 -0
- package/src/host/mint-trace.ts +54 -0
- package/{esm/src/host/mod.js → src/host/mod.ts} +11 -3
- package/src/host/reply.ts +32 -0
- package/src/kernel/engine/assert.ts +29 -0
- package/src/kernel/engine/boundary.ts +75 -0
- package/src/kernel/engine/delta.ts +440 -0
- package/src/kernel/engine/hash.ts +11 -0
- package/src/kernel/engine/record.ts +8 -0
- package/src/kernel/engine/repair.ts +56 -0
- package/src/kernel/engine/runner/gates.ts +338 -0
- package/src/kernel/engine/runner/mod.ts +135 -0
- package/src/kernel/engine/runner/state.ts +31 -0
- package/src/kernel/engine/runner/steps.ts +183 -0
- package/src/kernel/engine/runner/stream.ts +83 -0
- package/src/kernel/engine/runner/tokens.ts +47 -0
- package/src/kernel/engine/runner/tools.ts +266 -0
- package/{esm/src/kernel/engine/runner.d.ts → src/kernel/engine/runner.ts} +2 -1
- package/src/kernel/engine/tree.ts +18 -0
- package/src/kernel/mod.ts +39 -0
- package/src/kernel/registry/attachments.ts +195 -0
- package/src/kernel/registry/catalog.ts +181 -0
- package/src/kernel/registry/ingress.ts +223 -0
- package/src/kernel/registry/profiles.ts +165 -0
- package/src/kernel/registry/provider-request.ts +31 -0
- package/src/kernel/registry/resolve.ts +290 -0
- package/src/kernel/registry/schemas.ts +29 -0
- package/src/kernel/registry/tools.ts +45 -0
- package/{esm/src/kernel/registry/vault.d.ts → src/kernel/registry/vault.ts} +17 -2
- package/src/kernel/types.ts +576 -0
- package/{esm/src/observability/mod.js → src/observability/mod.ts} +11 -2
- package/src/observability/spans.ts +70 -0
- package/src/observability/trace-attach.ts +96 -0
- package/src/observability/trace-record.ts +254 -0
- package/src/observability/trace-usage.ts +36 -0
- package/src/observability/trace.ts +143 -0
- package/src/presets/google.ts +147 -0
- package/src/presets/mod.ts +24 -0
- package/src/providers/create-provider.ts +64 -0
- package/src/providers/gemini-tape.ts +59 -0
- package/src/providers/google-tap.ts +57 -0
- package/src/providers/interactions.ts +182 -0
- package/src/providers/keys.ts +182 -0
- package/{esm/src/providers/mod.js → src/providers/mod.ts} +4 -2
- package/{esm/src/providers/openrouter-mod.js → src/providers/openrouter-mod.ts} +7 -3
- package/src/providers/openrouter-payload.ts +232 -0
- package/src/providers/openrouter.ts +758 -0
- package/src/providers/pcm.ts +37 -0
- package/src/providers/provider.ts +206 -0
- package/src/providers/speech.ts +180 -0
- package/src/providers/sse.ts +59 -0
- package/esm/_dnt.polyfills.d.ts +0 -110
- package/esm/_dnt.polyfills.js +0 -144
- package/esm/_dnt.shims.d.ts +0 -5
- package/esm/_dnt.shims.js +0 -61
- package/esm/mod.js +0 -49
- package/esm/package.json +0 -3
- package/esm/src/cli/commands/profile.d.ts +0 -2
- package/esm/src/cli/commands/profile.js +0 -53
- package/esm/src/cli/commands/run.d.ts +0 -10
- package/esm/src/cli/commands/run.js +0 -55
- package/esm/src/cli/commands/test.d.ts +0 -15
- package/esm/src/cli/commands/test.js +0 -140
- package/esm/src/cli/index.d.ts +0 -4
- package/esm/src/cli/index.js +0 -148
- package/esm/src/cli/matrix/fixtures.d.ts +0 -13
- package/esm/src/cli/matrix/fixtures.js +0 -77
- package/esm/src/cli/matrix/synthesizer.d.ts +0 -29
- package/esm/src/cli/matrix/synthesizer.js +0 -187
- package/esm/src/guardrails/error.d.ts +0 -33
- package/esm/src/guardrails/error.js +0 -114
- package/esm/src/guardrails/injection.d.ts +0 -12
- package/esm/src/guardrails/injection.js +0 -220
- package/esm/src/guardrails/mod.d.ts +0 -14
- package/esm/src/guardrails/mod.js +0 -14
- package/esm/src/guardrails/sanitize.d.ts +0 -22
- package/esm/src/guardrails/sanitize.js +0 -133
- package/esm/src/guardrails/sensitive.d.ts +0 -12
- package/esm/src/guardrails/sensitive.js +0 -88
- package/esm/src/host/mint-trace.d.ts +0 -27
- package/esm/src/host/mint-trace.js +0 -33
- package/esm/src/host/mod.d.ts +0 -13
- package/esm/src/host/reply.d.ts +0 -14
- package/esm/src/host/reply.js +0 -27
- package/esm/src/kernel/engine/boundary.d.ts +0 -10
- package/esm/src/kernel/engine/boundary.js +0 -55
- package/esm/src/kernel/engine/delta.d.ts +0 -8
- package/esm/src/kernel/engine/delta.js +0 -389
- package/esm/src/kernel/engine/hash.d.ts +0 -1
- package/esm/src/kernel/engine/hash.js +0 -9
- package/esm/src/kernel/engine/record.d.ts +0 -2
- package/esm/src/kernel/engine/record.js +0 -7
- package/esm/src/kernel/engine/repair.d.ts +0 -7
- package/esm/src/kernel/engine/repair.js +0 -38
- package/esm/src/kernel/engine/runner/gates.d.ts +0 -4
- package/esm/src/kernel/engine/runner/gates.js +0 -206
- package/esm/src/kernel/engine/runner/mod.d.ts +0 -14
- package/esm/src/kernel/engine/runner/mod.js +0 -103
- package/esm/src/kernel/engine/runner/state.d.ts +0 -16
- package/esm/src/kernel/engine/runner/state.js +0 -8
- package/esm/src/kernel/engine/runner/steps.d.ts +0 -15
- package/esm/src/kernel/engine/runner/steps.js +0 -119
- package/esm/src/kernel/engine/runner/stream.d.ts +0 -11
- package/esm/src/kernel/engine/runner/stream.js +0 -65
- package/esm/src/kernel/engine/runner/tokens.d.ts +0 -3
- package/esm/src/kernel/engine/runner/tokens.js +0 -38
- package/esm/src/kernel/engine/runner/tools.d.ts +0 -13
- package/esm/src/kernel/engine/runner/tools.js +0 -197
- package/esm/src/kernel/engine/runner.js +0 -6
- package/esm/src/kernel/engine/tree.d.ts +0 -2
- package/esm/src/kernel/engine/tree.js +0 -17
- package/esm/src/kernel/mod.d.ts +0 -18
- package/esm/src/kernel/mod.js +0 -16
- package/esm/src/kernel/registry/attachments.d.ts +0 -16
- package/esm/src/kernel/registry/attachments.js +0 -156
- package/esm/src/kernel/registry/catalog.d.ts +0 -31
- package/esm/src/kernel/registry/catalog.js +0 -135
- package/esm/src/kernel/registry/ingress.d.ts +0 -13
- package/esm/src/kernel/registry/ingress.js +0 -163
- package/esm/src/kernel/registry/profiles.d.ts +0 -34
- package/esm/src/kernel/registry/profiles.js +0 -120
- package/esm/src/kernel/registry/provider-request.d.ts +0 -4
- package/esm/src/kernel/registry/provider-request.js +0 -25
- package/esm/src/kernel/registry/resolve.d.ts +0 -19
- package/esm/src/kernel/registry/resolve.js +0 -217
- package/esm/src/kernel/registry/schemas.d.ts +0 -14
- package/esm/src/kernel/registry/schemas.js +0 -23
- package/esm/src/kernel/registry/tools.d.ts +0 -12
- package/esm/src/kernel/registry/tools.js +0 -36
- package/esm/src/kernel/registry/vault.js +0 -18
- package/esm/src/kernel/types.d.ts +0 -521
- package/esm/src/kernel/types.js +0 -10
- package/esm/src/observability/mod.d.ts +0 -12
- package/esm/src/observability/spans.d.ts +0 -16
- package/esm/src/observability/spans.js +0 -56
- package/esm/src/observability/trace-attach.d.ts +0 -16
- package/esm/src/observability/trace-attach.js +0 -67
- package/esm/src/observability/trace-record.d.ts +0 -112
- package/esm/src/observability/trace-record.js +0 -140
- package/esm/src/observability/trace-usage.d.ts +0 -3
- package/esm/src/observability/trace-usage.js +0 -32
- package/esm/src/observability/trace.d.ts +0 -23
- package/esm/src/observability/trace.js +0 -121
- package/esm/src/presets/google.d.ts +0 -50
- package/esm/src/presets/google.js +0 -96
- package/esm/src/presets/mod.d.ts +0 -11
- package/esm/src/presets/mod.js +0 -10
- package/esm/src/providers/create-provider.d.ts +0 -29
- package/esm/src/providers/create-provider.js +0 -38
- package/esm/src/providers/gemini-tape.d.ts +0 -2
- package/esm/src/providers/gemini-tape.js +0 -46
- package/esm/src/providers/google-tap.d.ts +0 -3
- package/esm/src/providers/google-tap.js +0 -48
- package/esm/src/providers/interactions.d.ts +0 -5
- package/esm/src/providers/interactions.js +0 -152
- package/esm/src/providers/keys.d.ts +0 -19
- package/esm/src/providers/keys.js +0 -129
- package/esm/src/providers/mod.d.ts +0 -12
- package/esm/src/providers/openrouter-mod.d.ts +0 -13
- package/esm/src/providers/openrouter-payload.d.ts +0 -32
- package/esm/src/providers/openrouter-payload.js +0 -179
- package/esm/src/providers/openrouter.d.ts +0 -15
- package/esm/src/providers/openrouter.js +0 -589
- package/esm/src/providers/pcm.d.ts +0 -7
- package/esm/src/providers/pcm.js +0 -35
- package/esm/src/providers/provider.d.ts +0 -15
- package/esm/src/providers/provider.js +0 -166
- package/esm/src/providers/speech.d.ts +0 -23
- package/esm/src/providers/speech.js +0 -125
- package/esm/src/providers/sse.d.ts +0 -7
- package/esm/src/providers/sse.js +0 -53
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PCM → WAV helpers shared by speech transports.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const SAMPLE_RATE = 24000;
|
|
8
|
+
|
|
9
|
+
function writeAscii(view: DataView, offset: number, str: string): void {
|
|
10
|
+
for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Wrap raw PCM bytes in a RIFF/WAVE container. */
|
|
14
|
+
export function wrapPcmAsWav(pcm: Uint8Array, sampleRate = SAMPLE_RATE): Uint8Array {
|
|
15
|
+
const numChannels = 1;
|
|
16
|
+
const bitsPerSample = 16;
|
|
17
|
+
const byteRate = (sampleRate * numChannels * bitsPerSample) / 8;
|
|
18
|
+
const blockAlign = (numChannels * bitsPerSample) / 8;
|
|
19
|
+
const dataSize = pcm.length;
|
|
20
|
+
const buf = new ArrayBuffer(44 + dataSize);
|
|
21
|
+
const view = new DataView(buf);
|
|
22
|
+
writeAscii(view, 0, 'RIFF');
|
|
23
|
+
view.setUint32(4, 36 + dataSize, true);
|
|
24
|
+
writeAscii(view, 8, 'WAVE');
|
|
25
|
+
writeAscii(view, 12, 'fmt ');
|
|
26
|
+
view.setUint32(16, 16, true);
|
|
27
|
+
view.setUint16(20, 1, true); // PCM
|
|
28
|
+
view.setUint16(22, numChannels, true);
|
|
29
|
+
view.setUint32(24, sampleRate, true);
|
|
30
|
+
view.setUint32(28, byteRate, true);
|
|
31
|
+
view.setUint16(32, blockAlign, true);
|
|
32
|
+
view.setUint16(34, bitsPerSample, true);
|
|
33
|
+
writeAscii(view, 36, 'data');
|
|
34
|
+
view.setUint32(40, dataSize, true);
|
|
35
|
+
new Uint8Array(buf, 44).set(pcm);
|
|
36
|
+
return new Uint8Array(buf);
|
|
37
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
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
|
+
* Speech-role turns use `response_format: audio` + `speech_config` (same
|
|
7
|
+
* transport as chat/image).
|
|
8
|
+
*
|
|
9
|
+
* @module
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { publicError, TheorumError } from '../guardrails/error.ts';
|
|
13
|
+
import {
|
|
14
|
+
eventsFromComplete,
|
|
15
|
+
eventsFromDelta,
|
|
16
|
+
extractTokenEvent,
|
|
17
|
+
groundingFromEvent,
|
|
18
|
+
tryStructured,
|
|
19
|
+
} from '../kernel/engine/delta.ts';
|
|
20
|
+
import type { ModelProvider, ProviderCompleteRequest, TurnEvent } from '../kernel/types.ts';
|
|
21
|
+
import { tapFetch } from './google-tap.ts';
|
|
22
|
+
import { toInteractionsBody } from './interactions.ts';
|
|
23
|
+
import { fetchGemini, type GeminiTransport } from './keys.ts';
|
|
24
|
+
import { wrapPcmAsWav } from './pcm.ts';
|
|
25
|
+
import { INTERACTIONS_URL, takeSsePayloads } from './sse.ts';
|
|
26
|
+
|
|
27
|
+
const HTTP_OK = 200;
|
|
28
|
+
|
|
29
|
+
function base64ToBytes(data: string): Uint8Array {
|
|
30
|
+
const bin = atob(data);
|
|
31
|
+
const out = new Uint8Array(bin.length);
|
|
32
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function bytesToBase64(bytes: Uint8Array): string {
|
|
37
|
+
let bin = '';
|
|
38
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
|
39
|
+
return btoa(bin);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isRawPcmMime(mime: string): boolean {
|
|
43
|
+
const lower = mime.toLowerCase();
|
|
44
|
+
return lower === 'audio/pcm' || lower === 'audio/l16' || lower === 'audio/raw';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Google TTS returns raw PCM; wrap as WAV for hosts (matches OpenRouter pcm path). */
|
|
48
|
+
function normalizeSpeechMedia(event: TurnEvent, speech: boolean): TurnEvent {
|
|
49
|
+
if (!(speech && event.type === 'media' && event.media)) {
|
|
50
|
+
return event;
|
|
51
|
+
}
|
|
52
|
+
const { mimeType, data } = event.media;
|
|
53
|
+
if (!isRawPcmMime(mimeType)) {
|
|
54
|
+
return event;
|
|
55
|
+
}
|
|
56
|
+
const wav = wrapPcmAsWav(base64ToBytes(data));
|
|
57
|
+
return {
|
|
58
|
+
type: 'media',
|
|
59
|
+
media: { mimeType: 'audio/wav', data: bytesToBase64(wav) },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function* readSseRecords(res: Response): AsyncGenerator<Record<string, unknown>> {
|
|
64
|
+
if (!res.body) {
|
|
65
|
+
throw new TheorumError('empty Gemini stream');
|
|
66
|
+
}
|
|
67
|
+
const reader = res.body.getReader();
|
|
68
|
+
const decoder = new TextDecoder();
|
|
69
|
+
yield* pumpSse(reader, decoder, '', '');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function* pumpSse(
|
|
73
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
74
|
+
decoder: TextDecoder,
|
|
75
|
+
buffer: string,
|
|
76
|
+
pendingEvent: string,
|
|
77
|
+
): AsyncGenerator<Record<string, unknown>> {
|
|
78
|
+
const { done, value } = await reader.read();
|
|
79
|
+
if (done) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const next = buffer + decoder.decode(value, { stream: true });
|
|
83
|
+
const taken = takeSsePayloads(next, pendingEvent);
|
|
84
|
+
for (const payload of taken.payloads) {
|
|
85
|
+
yield payload;
|
|
86
|
+
}
|
|
87
|
+
yield* pumpSse(reader, decoder, taken.rest, taken.pendingEvent);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function eventType(event: Record<string, unknown>): string {
|
|
91
|
+
return String(event.event_type ?? event.type ?? '');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isDeltaEvent(kind: string): boolean {
|
|
95
|
+
return kind === 'content.delta' || kind === 'step.delta';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isCompleteEvent(kind: string): boolean {
|
|
99
|
+
return (
|
|
100
|
+
kind === 'interaction.complete' ||
|
|
101
|
+
kind === 'interaction.completed' ||
|
|
102
|
+
kind.startsWith('interaction.')
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function foldDeltaPayload(event: Record<string, unknown>, acc: { text: string }): TurnEvent[] {
|
|
107
|
+
const deltaEvents = eventsFromDelta(event.delta);
|
|
108
|
+
for (const item of deltaEvents) {
|
|
109
|
+
if (item.type === 'text' && item.text) {
|
|
110
|
+
acc.text += item.text;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return deltaEvents;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function foldPayload(event: Record<string, unknown>, acc: { text: string }): TurnEvent[] {
|
|
117
|
+
const kind = eventType(event);
|
|
118
|
+
const events: TurnEvent[] = [];
|
|
119
|
+
if (isDeltaEvent(kind)) {
|
|
120
|
+
events.push(...foldDeltaPayload(event, acc));
|
|
121
|
+
} else if (isCompleteEvent(kind)) {
|
|
122
|
+
events.push(...eventsFromComplete(event, acc.text.length > 0));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Also check if usage was included on the event directly
|
|
126
|
+
if (!events.some((e) => e.type === 'tokens')) {
|
|
127
|
+
const tokenEvent = extractTokenEvent(event);
|
|
128
|
+
if (tokenEvent) {
|
|
129
|
+
events.push(tokenEvent);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const groundingEvent = groundingFromEvent(event);
|
|
133
|
+
if (groundingEvent && !events.some((e) => e.type === 'grounding')) {
|
|
134
|
+
events.push(groundingEvent);
|
|
135
|
+
}
|
|
136
|
+
return events;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function withTap(req: ProviderCompleteRequest, transport: GeminiTransport): GeminiTransport {
|
|
140
|
+
return {
|
|
141
|
+
...transport,
|
|
142
|
+
fetch: tapFetch(req.tapGemini, transport.fetch),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function* streamComplete(
|
|
147
|
+
req: ProviderCompleteRequest,
|
|
148
|
+
transport: GeminiTransport,
|
|
149
|
+
): AsyncGenerator<TurnEvent> {
|
|
150
|
+
if (!req.geminiBucket) {
|
|
151
|
+
yield {
|
|
152
|
+
type: 'error',
|
|
153
|
+
error: publicError('missing Gemini vault bucket for Interactions'),
|
|
154
|
+
};
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const res = await fetchGemini(
|
|
158
|
+
INTERACTIONS_URL,
|
|
159
|
+
{ method: 'POST', body: JSON.stringify(toInteractionsBody(req)) },
|
|
160
|
+
req.geminiBucket,
|
|
161
|
+
withTap(req, transport),
|
|
162
|
+
);
|
|
163
|
+
if (res.status !== HTTP_OK) {
|
|
164
|
+
const errorBody = await res.text().catch(() => '');
|
|
165
|
+
yield {
|
|
166
|
+
type: 'error',
|
|
167
|
+
error: publicError(`Gemini HTTP ${String(res.status)}: ${errorBody}`),
|
|
168
|
+
};
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const acc = { text: '' };
|
|
172
|
+
const speech = Boolean(req.speech);
|
|
173
|
+
for await (const payload of readSseRecords(res)) {
|
|
174
|
+
req.tapGemini?.(payload);
|
|
175
|
+
const events = foldPayload(payload, acc);
|
|
176
|
+
for (const event of events) {
|
|
177
|
+
yield normalizeSpeechMedia(event, speech);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (req.structured && acc.text) {
|
|
181
|
+
const structured = tryStructured(acc.text);
|
|
182
|
+
if (structured) {
|
|
183
|
+
yield structured;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function* streamGuarded(
|
|
189
|
+
req: ProviderCompleteRequest,
|
|
190
|
+
transport: GeminiTransport,
|
|
191
|
+
): AsyncGenerator<TurnEvent> {
|
|
192
|
+
try {
|
|
193
|
+
yield* streamComplete(req, transport);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
yield { type: 'error', error: publicError(err) };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Create a `ModelProvider` backed by Google Interactions streaming. */
|
|
200
|
+
function createInteractionsProvider(transport: GeminiTransport): ModelProvider {
|
|
201
|
+
return {
|
|
202
|
+
complete: (req) => streamGuarded(req, transport),
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export { createInteractionsProvider };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible `/audio/speech` transport (internal).
|
|
3
|
+
*
|
|
4
|
+
* Hosts use `createProvider(profile, { openRouter })` — this module is selected
|
|
5
|
+
* when the profile is an openAi speech role. Not a separate public door.
|
|
6
|
+
*
|
|
7
|
+
* @module
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { publicError } from '../guardrails/error.ts';
|
|
11
|
+
import type {
|
|
12
|
+
InteractionPart,
|
|
13
|
+
ModelProvider,
|
|
14
|
+
ProfileSpeechSpec,
|
|
15
|
+
ProviderCompleteRequest,
|
|
16
|
+
SpeechAudioFormat,
|
|
17
|
+
TurnEvent,
|
|
18
|
+
} from '../kernel/types.ts';
|
|
19
|
+
import { wrapPcmAsWav } from './pcm.ts';
|
|
20
|
+
|
|
21
|
+
const HTTP_OK = 200;
|
|
22
|
+
|
|
23
|
+
function bytesToBase64(bytes: Uint8Array): string {
|
|
24
|
+
let bin = '';
|
|
25
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
|
26
|
+
return btoa(bin);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Credentials for the openAi speech path (same shape as OpenRouter chat config + voice). */
|
|
30
|
+
export interface SpeechProviderConfig {
|
|
31
|
+
apiKey?: string;
|
|
32
|
+
/** Fallback TTS voice when the profile does not pin `outputs.speech.voice`. */
|
|
33
|
+
voice?: string;
|
|
34
|
+
baseUrl?: string;
|
|
35
|
+
siteUrl?: string;
|
|
36
|
+
siteName?: string;
|
|
37
|
+
fetch?: typeof fetch;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function extractInputText(input: InteractionPart[]): string {
|
|
41
|
+
return input
|
|
42
|
+
.filter((p) => p.type === 'text')
|
|
43
|
+
.map((p) => (p.type === 'text' ? p.text : ''))
|
|
44
|
+
.join(' ')
|
|
45
|
+
.trim();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function resolveSpeechWireModel(req: ProviderCompleteRequest): string {
|
|
49
|
+
if (req.openRouterId) {
|
|
50
|
+
return req.openRouterId;
|
|
51
|
+
}
|
|
52
|
+
if (req.apiId.includes('/')) {
|
|
53
|
+
return req.apiId;
|
|
54
|
+
}
|
|
55
|
+
if (req.apiId) {
|
|
56
|
+
return `google/${req.apiId}`;
|
|
57
|
+
}
|
|
58
|
+
return String(req.model);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function buildHeaders(apiKey: string, config: SpeechProviderConfig): Record<string, string> {
|
|
62
|
+
const headers: Record<string, string> = {
|
|
63
|
+
Authorization: `Bearer ${apiKey}`,
|
|
64
|
+
'Content-Type': 'application/json',
|
|
65
|
+
};
|
|
66
|
+
if (config.siteUrl) {
|
|
67
|
+
headers['HTTP-Referer'] = config.siteUrl;
|
|
68
|
+
}
|
|
69
|
+
if (config.siteName) {
|
|
70
|
+
headers['X-Title'] = config.siteName;
|
|
71
|
+
}
|
|
72
|
+
return headers;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function buildPayload(
|
|
76
|
+
req: ProviderCompleteRequest,
|
|
77
|
+
text: string,
|
|
78
|
+
speech: ProfileSpeechSpec | undefined,
|
|
79
|
+
configVoice?: string,
|
|
80
|
+
): Record<string, unknown> {
|
|
81
|
+
const voice = speech?.voice ?? configVoice;
|
|
82
|
+
const format: SpeechAudioFormat = speech?.format ?? 'pcm';
|
|
83
|
+
const payload: Record<string, unknown> = {
|
|
84
|
+
model: resolveSpeechWireModel(req),
|
|
85
|
+
input: text,
|
|
86
|
+
response_format: format,
|
|
87
|
+
};
|
|
88
|
+
if (voice) {
|
|
89
|
+
payload.voice = voice;
|
|
90
|
+
}
|
|
91
|
+
return payload;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function requestSpeech(
|
|
95
|
+
apiKey: string,
|
|
96
|
+
text: string,
|
|
97
|
+
req: ProviderCompleteRequest,
|
|
98
|
+
config: SpeechProviderConfig,
|
|
99
|
+
): Promise<Response> {
|
|
100
|
+
const fetchFn = config.fetch ?? fetch;
|
|
101
|
+
const baseUrl = config.baseUrl?.replace(/\/+$/, '') ?? 'https://openrouter.ai/api/v1';
|
|
102
|
+
const url = `${baseUrl}/audio/speech`;
|
|
103
|
+
return await fetchFn(url, {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: buildHeaders(apiKey, config),
|
|
106
|
+
body: JSON.stringify(buildPayload(req, text, req.speech, config.voice)),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function* yieldSpeechSuccess(
|
|
111
|
+
rawBytes: Uint8Array,
|
|
112
|
+
text: string,
|
|
113
|
+
format: SpeechAudioFormat,
|
|
114
|
+
): Generator<TurnEvent> {
|
|
115
|
+
let mediaMime = 'audio/mpeg';
|
|
116
|
+
let mediaBytes = rawBytes;
|
|
117
|
+
|
|
118
|
+
if (format === 'pcm') {
|
|
119
|
+
mediaMime = 'audio/wav';
|
|
120
|
+
mediaBytes = wrapPcmAsWav(rawBytes);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
yield {
|
|
124
|
+
type: 'media',
|
|
125
|
+
media: { mimeType: mediaMime, data: bytesToBase64(mediaBytes) },
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const inputTokens = Math.max(1, Math.round(text.length / 4));
|
|
129
|
+
const outputTokens = Math.max(1, Math.round(rawBytes.length / 100));
|
|
130
|
+
yield {
|
|
131
|
+
type: 'tokens',
|
|
132
|
+
tokens: { input: inputTokens, output: outputTokens, total: inputTokens + outputTokens },
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
yield { type: 'done' };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function* streamSpeech(
|
|
139
|
+
req: ProviderCompleteRequest,
|
|
140
|
+
config: SpeechProviderConfig = {},
|
|
141
|
+
): AsyncGenerator<TurnEvent> {
|
|
142
|
+
const apiKey = config.apiKey?.trim() || undefined;
|
|
143
|
+
if (!apiKey) {
|
|
144
|
+
yield { type: 'error', error: publicError('missing API key for speech') };
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const text = extractInputText(req.input);
|
|
149
|
+
if (!text) {
|
|
150
|
+
yield { type: 'error', error: publicError('empty text for speech') };
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const res = await requestSpeech(apiKey, text, req, config);
|
|
155
|
+
if (res.status !== HTTP_OK) {
|
|
156
|
+
yield { type: 'error', error: publicError(`Speech HTTP ${String(res.status)}`) };
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const arrayBuffer = await res.arrayBuffer();
|
|
161
|
+
const rawBytes = new Uint8Array(arrayBuffer);
|
|
162
|
+
if (rawBytes.length === 0) {
|
|
163
|
+
yield { type: 'error', error: publicError('no audio returned from speech') };
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const format = req.speech?.format ?? 'pcm';
|
|
168
|
+
for (const ev of yieldSpeechSuccess(rawBytes, text, format)) {
|
|
169
|
+
yield ev;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Internal ModelProvider for openAi speech roles. */
|
|
174
|
+
function createSpeechProvider(config: SpeechProviderConfig = {}): ModelProvider {
|
|
175
|
+
return {
|
|
176
|
+
complete: (req: ProviderCompleteRequest) => streamSpeech(req, config),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export { createSpeechProvider, streamSpeech };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const INTERACTIONS_URL = 'https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse';
|
|
2
|
+
|
|
3
|
+
const DATA_PREFIX = 'data: ';
|
|
4
|
+
const EVENT_PREFIX = 'event: ';
|
|
5
|
+
const DONE = '[DONE]';
|
|
6
|
+
|
|
7
|
+
function asObject(parsed: unknown): Record<string, unknown> | undefined {
|
|
8
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
9
|
+
return parsed as Record<string, unknown>;
|
|
10
|
+
}
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function dataRecord(raw: string, sseEvent: string): Record<string, unknown> {
|
|
15
|
+
const data = raw.slice(DATA_PREFIX.length).trim();
|
|
16
|
+
const row: Record<string, unknown> = {};
|
|
17
|
+
if (sseEvent) {
|
|
18
|
+
row.sseEvent = sseEvent;
|
|
19
|
+
}
|
|
20
|
+
if (!data || data === DONE) {
|
|
21
|
+
row.eventType = 'sse_done';
|
|
22
|
+
return row;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const parsed: unknown = JSON.parse(data);
|
|
26
|
+
const obj = asObject(parsed);
|
|
27
|
+
if (obj) {
|
|
28
|
+
return { ...obj, ...row };
|
|
29
|
+
}
|
|
30
|
+
row.eventType = 'sse_unparsed';
|
|
31
|
+
row.data = parsed;
|
|
32
|
+
return row;
|
|
33
|
+
} catch {
|
|
34
|
+
row.eventType = 'sse_unparsed';
|
|
35
|
+
row.data = data;
|
|
36
|
+
return row;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function takeSsePayloads(
|
|
41
|
+
buffer: string,
|
|
42
|
+
pendingEvent = '',
|
|
43
|
+
): { rest: string; payloads: Record<string, unknown>[]; pendingEvent: string } {
|
|
44
|
+
const payloads: Record<string, unknown>[] = [];
|
|
45
|
+
const chunks = buffer.split('\n');
|
|
46
|
+
const rest = chunks.pop() ?? '';
|
|
47
|
+
let sseEvent = pendingEvent;
|
|
48
|
+
for (const line of chunks) {
|
|
49
|
+
if (line.startsWith(EVENT_PREFIX)) {
|
|
50
|
+
sseEvent = line.slice(EVENT_PREFIX.length).trim();
|
|
51
|
+
} else if (line.startsWith(DATA_PREFIX)) {
|
|
52
|
+
payloads.push(dataRecord(line, sseEvent));
|
|
53
|
+
sseEvent = '';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { rest, payloads, pendingEvent: sseEvent };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export { INTERACTIONS_URL, takeSsePayloads };
|
package/esm/_dnt.polyfills.d.ts
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
declare global {
|
|
2
|
-
interface Object {
|
|
3
|
-
/**
|
|
4
|
-
* Determines whether an object has a property with the specified name.
|
|
5
|
-
* @param o An object.
|
|
6
|
-
* @param v A property name.
|
|
7
|
-
*/
|
|
8
|
-
hasOwn(o: object, v: PropertyKey): boolean;
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
export {};
|
|
12
|
-
/**
|
|
13
|
-
* Based on [import-meta-ponyfill](https://github.com/gaubee/import-meta-ponyfill),
|
|
14
|
-
* but instead of using npm to install additional dependencies,
|
|
15
|
-
* this approach manually consolidates cjs/mjs/d.ts into a single file.
|
|
16
|
-
*
|
|
17
|
-
* Note that this code might be imported multiple times
|
|
18
|
-
* (for example, both dnt.test.polyfills.ts and dnt.polyfills.ts contain this code;
|
|
19
|
-
* or Node.js might dynamically clear the cache and then force a require).
|
|
20
|
-
* Therefore, it's important to avoid redundant writes to global objects.
|
|
21
|
-
* Additionally, consider that commonjs is used alongside esm,
|
|
22
|
-
* so the two ponyfill functions are stored independently in two separate global objects.
|
|
23
|
-
*/
|
|
24
|
-
import { createRequire } from "node:module";
|
|
25
|
-
import { type URL } from "node:url";
|
|
26
|
-
declare global {
|
|
27
|
-
interface ImportMeta {
|
|
28
|
-
/** A string representation of the fully qualified module URL. When the
|
|
29
|
-
* module is loaded locally, the value will be a file URL (e.g.
|
|
30
|
-
* `file:///path/module.ts`).
|
|
31
|
-
*
|
|
32
|
-
* You can also parse the string as a URL to determine more information about
|
|
33
|
-
* how the current module was loaded. For example to determine if a module was
|
|
34
|
-
* local or not:
|
|
35
|
-
*
|
|
36
|
-
* ```ts
|
|
37
|
-
* const url = new URL(import.meta.url);
|
|
38
|
-
* if (url.protocol === "file:") {
|
|
39
|
-
* console.log("this module was loaded locally");
|
|
40
|
-
* }
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
url: string;
|
|
44
|
-
/**
|
|
45
|
-
* A function that returns resolved specifier as if it would be imported
|
|
46
|
-
* using `import(specifier)`.
|
|
47
|
-
*
|
|
48
|
-
* ```ts
|
|
49
|
-
* console.log(import.meta.resolve("./foo.js"));
|
|
50
|
-
* // file:///dev/foo.js
|
|
51
|
-
* ```
|
|
52
|
-
*
|
|
53
|
-
* @param specifier The module specifier to resolve relative to `parent`.
|
|
54
|
-
* @param parent The absolute parent module URL to resolve from.
|
|
55
|
-
* @returns The absolute (`file:`) URL string for the resolved module.
|
|
56
|
-
*/
|
|
57
|
-
resolve(specifier: string, parent?: string | URL | undefined): string;
|
|
58
|
-
/** A flag that indicates if the current module is the main module that was
|
|
59
|
-
* called when starting the program under Deno.
|
|
60
|
-
*
|
|
61
|
-
* ```ts
|
|
62
|
-
* if (import.meta.main) {
|
|
63
|
-
* // this was loaded as the main module, maybe do some bootstrapping
|
|
64
|
-
* }
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
main: boolean;
|
|
68
|
-
/** The absolute path of the current module.
|
|
69
|
-
*
|
|
70
|
-
* This property is only provided for local modules (ie. using `file://` URLs).
|
|
71
|
-
*
|
|
72
|
-
* Example:
|
|
73
|
-
* ```
|
|
74
|
-
* // Unix
|
|
75
|
-
* console.log(import.meta.filename); // /home/alice/my_module.ts
|
|
76
|
-
*
|
|
77
|
-
* // Windows
|
|
78
|
-
* console.log(import.meta.filename); // C:\alice\my_module.ts
|
|
79
|
-
* ```
|
|
80
|
-
*/
|
|
81
|
-
filename: string;
|
|
82
|
-
/** The absolute path of the directory containing the current module.
|
|
83
|
-
*
|
|
84
|
-
* This property is only provided for local modules (ie. using `file://` URLs).
|
|
85
|
-
*
|
|
86
|
-
* * Example:
|
|
87
|
-
* ```
|
|
88
|
-
* // Unix
|
|
89
|
-
* console.log(import.meta.dirname); // /home/alice
|
|
90
|
-
*
|
|
91
|
-
* // Windows
|
|
92
|
-
* console.log(import.meta.dirname); // C:\alice
|
|
93
|
-
* ```
|
|
94
|
-
*/
|
|
95
|
-
dirname: string;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
type NodeRequest = ReturnType<typeof createRequire>;
|
|
99
|
-
type NodeModule = NonNullable<NodeRequest["main"]>;
|
|
100
|
-
interface ImportMetaPonyfillCommonjs {
|
|
101
|
-
(require: NodeRequest, module: NodeModule): ImportMeta;
|
|
102
|
-
}
|
|
103
|
-
interface ImportMetaPonyfillEsmodule {
|
|
104
|
-
(importMeta: ImportMeta): ImportMeta;
|
|
105
|
-
}
|
|
106
|
-
interface ImportMetaPonyfill extends ImportMetaPonyfillCommonjs, ImportMetaPonyfillEsmodule {
|
|
107
|
-
}
|
|
108
|
-
export declare let import_meta_ponyfill_commonjs: ImportMetaPonyfillCommonjs;
|
|
109
|
-
export declare let import_meta_ponyfill_esmodule: ImportMetaPonyfillEsmodule;
|
|
110
|
-
export declare let import_meta_ponyfill: ImportMetaPonyfill;
|