File size: 10,593 Bytes
c78c312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/**
 * OpenRouter API Integration
 * Routes requests to multiple AI models via OpenRouter
 */

const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions'

interface Message {
  role: 'system' | 'user' | 'assistant'
  content: string
}

interface SendMessageOptions {
  messages: Message[]
  model: string
  apiKey: string
  noLog?: boolean
  signal?: AbortSignal
  temperature?: number
  maxTokens?: number
  top_p?: number
  top_k?: number
  frequency_penalty?: number
  presence_penalty?: number
  repetition_penalty?: number
}

interface OpenRouterResponse {
  id: string
  model: string
  choices: {
    message: {
      role: string
      content: string
    }
    finish_reason: string
  }[]
  usage?: {
    prompt_tokens: number
    completion_tokens: number
    total_tokens: number
  }
}

/**
 * Send a message to the AI model via OpenRouter
 */
export async function sendMessage({
  messages,
  model,
  apiKey,
  noLog = false,
  signal,
  temperature = 0.7,
  maxTokens = 4096,
  top_p,
  top_k,
  frequency_penalty,
  presence_penalty,
  repetition_penalty
}: SendMessageOptions): Promise<string> {
  if (!apiKey) {
    throw new Error('API key is required')
  }

  // Prepare request body
  const body: Record<string, unknown> = {
    model,
    messages,
    temperature,
    max_tokens: maxTokens
  }

  // Add optional sampling parameters (only if explicitly set)
  if (top_p !== undefined) body.top_p = top_p
  if (top_k !== undefined) body.top_k = top_k
  if (frequency_penalty !== undefined) body.frequency_penalty = frequency_penalty
  if (presence_penalty !== undefined) body.presence_penalty = presence_penalty
  if (repetition_penalty !== undefined) body.repetition_penalty = repetition_penalty

  // Add provider-specific options if needed
  const providerOptions: Record<string, unknown> = {}

  // Handle no-log mode for supported providers
  if (noLog) {
    // OpenRouter passes through provider preferences
    providerOptions['allow_fallbacks'] = false
  }

  if (Object.keys(providerOptions).length > 0) {
    body.provider = providerOptions
  }

  const response = await fetch(OPENROUTER_API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      'HTTP-Referer': typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000',
      'X-Title': 'G0DM0D3'
    },
    body: JSON.stringify(body),
    signal
  })

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    const errorMessage = errorData.error?.message || `API error: ${response.status}`
    throw new Error(errorMessage)
  }

  const data: OpenRouterResponse = await response.json()

  if (!data.choices || data.choices.length === 0) {
    throw new Error('No response from model')
  }

  return data.choices[0].message.content
}

/**
 * Stream a message response from the AI model
 * (For future implementation)
 */
export async function* streamMessage({
  messages,
  model,
  apiKey,
  noLog = false,
  signal,
  temperature = 0.7,
  maxTokens = 4096,
  top_p,
  top_k,
  frequency_penalty,
  presence_penalty,
  repetition_penalty
}: SendMessageOptions): AsyncGenerator<string, void, unknown> {
  if (!apiKey) {
    throw new Error('API key is required')
  }

  const streamBody: Record<string, unknown> = {
    model,
    messages,
    temperature,
    max_tokens: maxTokens,
    stream: true
  }

  if (top_p !== undefined) streamBody.top_p = top_p
  if (top_k !== undefined) streamBody.top_k = top_k
  if (frequency_penalty !== undefined) streamBody.frequency_penalty = frequency_penalty
  if (presence_penalty !== undefined) streamBody.presence_penalty = presence_penalty
  if (repetition_penalty !== undefined) streamBody.repetition_penalty = repetition_penalty

  const response = await fetch(OPENROUTER_API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      'HTTP-Referer': typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000',
      'X-Title': 'G0DM0D3'
    },
    body: JSON.stringify(streamBody),
    signal
  })

  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}))
    throw new Error(errorData.error?.message || `API error: ${response.status}`)
  }

  const reader = response.body?.getReader()
  if (!reader) {
    throw new Error('No response body')
  }

  const decoder = new TextDecoder()
  let buffer = ''

  try {
    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        const trimmed = line.trim()
        if (!trimmed || trimmed === 'data: [DONE]') continue
        if (!trimmed.startsWith('data: ')) continue

        try {
          const json = JSON.parse(trimmed.slice(6))
          const content = json.choices?.[0]?.delta?.content
          if (content) {
            yield content
          }
        } catch {
          // Skip invalid JSON
        }
      }
    }
  } finally {
    reader.releaseLock()
  }
}

/**
 * Get available models from OpenRouter
 */
export async function getModels(apiKey: string): Promise<string[]> {
  const response = await fetch('https://openrouter.ai/api/v1/models', {
    headers: {
      'Authorization': `Bearer ${apiKey}`
    }
  })

  if (!response.ok) {
    throw new Error('Failed to fetch models')
  }

  const data = await response.json()
  return data.data.map((model: { id: string }) => model.id)
}

/**
 * Validate an API key
 */
export async function validateApiKey(apiKey: string): Promise<boolean> {
  try {
    await getModels(apiKey)
    return true
  } catch {
    return false
  }
}

// ── ULTRAPLINIAN Streaming (Liquid Response) ──────────────────────────

export interface UltraplinianRaceModel {
  model: string
  score: number
  duration_ms: number
  success: boolean
  error?: string
  content_length: number
  models_responded: number
  models_total: number
}

export interface UltraplinianLeader {
  model: string
  score: number
  duration_ms: number
  content: string
}

export interface UltraplinianComplete {
  response: string
  winner: { model: string; score: number; duration_ms: number } | null
  race: {
    tier: string
    models_queried: number
    models_succeeded: number
    total_duration_ms: number
    rankings: Array<{
      model: string; score: number; duration_ms: number
      success: boolean; error?: string; content_length: number
    }>
  }
  params_used: Record<string, number | undefined>
  pipeline: {
    godmode: boolean
    autotune: { detected_context: string; confidence: number; reasoning: string; strategy: string } | null
    parseltongue: { triggers_found: string[]; technique_used: string; transformations_count: number } | null
    stm: { modules_applied: string[]; original_length: number; transformed_length: number } | null
  }
}

export interface UltraplinianCallbacks {
  onRaceStart?: (data: { tier: string; models_queried: number }) => void
  onModelResult?: (data: UltraplinianRaceModel) => void
  onLeaderChange?: (data: UltraplinianLeader) => void
  onComplete?: (data: UltraplinianComplete) => void
  onError?: (error: string) => void
}

export interface UltraplinianOptions {
  messages: Message[]
  openrouterApiKey: string
  apiBaseUrl: string
  godmodeApiKey: string
  tier?: 'fast' | 'standard' | 'full'
  godmode?: boolean
  autotune?: boolean
  strategy?: string
  parseltongue?: boolean
  parseltongue_technique?: string
  parseltongue_intensity?: string
  stm_modules?: string[]
  signal?: AbortSignal
}

/**
 * Stream an ULTRAPLINIAN race via SSE.
 *
 * Connects to the backend's streaming endpoint and fires callbacks
 * as models finish. The first good response arrives in ~3-5s,
 * with live upgrades as better responses come in.
 */
export async function streamUltraplinian(
  options: UltraplinianOptions,
  callbacks: UltraplinianCallbacks,
): Promise<void> {
  const {
    messages, openrouterApiKey, apiBaseUrl, godmodeApiKey,
    tier = 'fast', godmode = true, autotune = true, strategy = 'adaptive',
    parseltongue = true, parseltongue_technique = 'leetspeak',
    parseltongue_intensity = 'medium', stm_modules = ['hedge_reducer', 'direct_mode'],
    signal,
  } = options

  const response = await fetch(`${apiBaseUrl}/v1/ultraplinian/completions`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${godmodeApiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      messages, openrouter_api_key: openrouterApiKey, tier, godmode,
      autotune, strategy, parseltongue, parseltongue_technique,
      parseltongue_intensity, stm_modules, stream: true,
    }),
    signal,
  })

  if (!response.ok) {
    const err = await response.json().catch(() => ({}))
    throw new Error(err.error || `ULTRAPLINIAN API error: ${response.status}`)
  }

  const reader = response.body?.getReader()
  if (!reader) throw new Error('No response body from ULTRAPLINIAN stream')

  const decoder = new TextDecoder()
  let buffer = ''

  try {
    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      let currentEvent = ''
      for (const line of lines) {
        const trimmed = line.trim()
        if (!trimmed) {
          currentEvent = ''
          continue
        }
        if (trimmed.startsWith('event: ')) {
          currentEvent = trimmed.slice(7)
          continue
        }
        if (trimmed.startsWith('data: ')) {
          try {
            const data = JSON.parse(trimmed.slice(6))
            switch (currentEvent) {
              case 'race:start':
                callbacks.onRaceStart?.(data)
                break
              case 'race:model':
                callbacks.onModelResult?.(data)
                break
              case 'race:leader':
                callbacks.onLeaderChange?.(data)
                break
              case 'race:complete':
                callbacks.onComplete?.(data)
                break
              case 'race:error':
                callbacks.onError?.(data.error)
                break
            }
          } catch {}
          currentEvent = ''
        }
      }
    }
  } finally {
    reader.releaseLock()
  }
}