File size: 7,220 Bytes
1dfeea6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//
// SPDX-FileCopyrightText: Hadad <hadad@linuxmail.org>
// SPDX-License-Identifier: Apache-2.0
//

import express from "express";
import http from "http";
import { WebSocketServer } from "ws";
import fetch from "node-fetch";
import cookieParser from "cookie-parser";
import path from "path";

const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ server });
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL || "";
const OPENAI_API_KEY = process.env.OPENAI_API_KEY || "";
const UMINT = process.env.UMINT || ``;

app.use(cookieParser());

// Root endpoint.
app.get("/", (_req, res) => res.send(UMINT));

// Search Engine Optimization (SEO).
// Robots Exclusion Protocol.
app.get("/robots.txt", (_req, res) => {
  res.sendFile(path.resolve("src/crawlers/robots.txt"));
});  // https://umint-ai.hf.space/robots.txt
// Sitemaps.
app.get("/sitemap.xml", (_req, res) => {
  res.sendFile(path.resolve("src/crawlers/sitemap.xml"));
});  // https://umint-ai.hf.space/sitemap.xml
// Google Search Console Tools.
app.get("/google15aba15fe250d693.html", (_req, res) => {
  res.sendFile(path.resolve("src/webmasters/google.html"));
});  // https://umint-ai.hf.space/google15aba15fe250d693.html
// Bing Webmaster Tools.
app.get("/BingSiteAuth.xml", (_req, res) => {
  res.sendFile(path.resolve("src/webmasters/bing.xml"));
});  // https://umint-ai.hf.space/BingSiteAuth.xml
// End of SEO.

// Favicon.
app.get("/assets/images/favicon.ico", (_req, res) => {
  res.sendFile(path.resolve("assets/images/favicon.ico"));
});

wss.on("connection", (ws) => {
  // Abort controller for the currently active streaming request.
  let currentAbortController = null;

  // Handle incoming messages from the WebSocket client.
  ws.on("message", async (msg) => {
    try {
      const data = JSON.parse(msg.toString());

      // Handle explicit stop request from client.
      if (data.type === "stop") {
        if (currentAbortController) {
          // Abort the active fetch request to stop streaming.
          currentAbortController.abort();
          currentAbortController = null;
        }
        // Notify client that streaming ended.
        ws.send(JSON.stringify({ type: "end" }));
        return;
      }

      // Extract user message and optional history for context.
      const message = data.message;
      const history = data.history || [];
      // Build messages array with history and the new user message.
      const setup_messages = [...history, { role: "user", content: message }];

      // Create a new AbortController to allow client to cancel the stream.
      currentAbortController = new AbortController();
      const signal = currentAbortController.signal;

      // Send request to the Endpoint.
      const request = await fetch(OPENAI_API_BASE_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${OPENAI_API_KEY}`,
        },
        body: JSON.stringify({
          model: "gpt-4.1-nano",
          messages: setup_messages,
          stream: true,
          private: true,
          isPrivate: true
        }),
        signal
      });

      // Handle non 2xx responses by returning an error to the client.
      if (!request.ok) {
        const errorData = await request.text();
        ws.send(JSON.stringify({ type: "error", error: `HTTP ${request.status}: ${request.statusText} - ${errorData}` }));
        if (currentAbortController) {
          currentAbortController.abort();
          currentAbortController = null;
        }
        return;
      }

      // Get the response body stream to read incremental chunks.
      const reader = request.body;
      if (!reader) {
        ws.send(JSON.stringify({ type: "error", error: "Response body is empty" }));
        if (currentAbortController) {
          currentAbortController.abort();
          currentAbortController = null;
        }
        return;
      }

      // Buffer partial data between streamed chunks.
      let buffer = "";
      try {
        // Iterate over stream chunks as they arrive.
        for await (const chunk of reader) {
          // If client requested abort, stop processing and inform the client.
          if (signal.aborted) {
            ws.send(JSON.stringify({ type: "end" }));
            if (currentAbortController) {
              currentAbortController.abort();
              currentAbortController = null;
            }
            return;
          }

          // Append raw chunk text to the buffer.
          buffer += chunk.toString();

          // Process full lines separated by newline characters.
          let idx;
          while ((idx = buffer.indexOf("\n")) !== -1) {
            const line = buffer.slice(0, idx).trim();
            buffer = buffer.slice(idx + 1);

            if (line.startsWith("data: ")) {
              const dataStr = line.substring(6).trim();
              // Skip empty events and the stream terminator.
              if (!dataStr || dataStr === "[DONE]") continue;
              try {
                // Parse JSON payload and extract incremental content.
                const parsed = JSON.parse(dataStr);
                const part = parsed?.choices?.[0]?.delta?.content;
                if (part) {
                  // Send incremental chunk to the client.
                  ws.send(JSON.stringify({ type: "chunk", chunk: part }));
                }
              } catch (parseError) {
                // Log parsing errors for debugging.
                console.error("Error parsing JSON:", parseError, "Data string:", dataStr);
              }
            }
          }
        }
      } catch (logs) {
        // If the fetch was aborted by the client, signal end.
        if (signal.aborted) {
          ws.send(JSON.stringify({ type: "end" }));
        } else {
          // For unexpected stream errors, log and notify client.
          console.error("Error:", logs);
          ws.send(JSON.stringify({ type: "error", error: "Error: " + (logs && logs.message ? logs.message : String(logs)) }));
        }
        if (currentAbortController) {
          currentAbortController.abort();
          currentAbortController = null;
        }
        return;
      }

      // Normal end of stream, notify client.
      ws.send(JSON.stringify({ type: "end" }));
      if (currentAbortController) {
        currentAbortController.abort();
        currentAbortController = null;
      }
    } catch (e) {
      // Catch JSON parse errors and other unexpected exceptions.
      console.error("General error:", e);
      ws.send(JSON.stringify({ type: "error", error: e.message || "An unknown error occurred" }));
      if (currentAbortController) {
        currentAbortController.abort();
        currentAbortController = null;
      }
    }
  });

  // Ensure any active fetch is aborted when the WebSocket closes.
  ws.on("close", () => {
    if (currentAbortController) {
      currentAbortController.abort();
      currentAbortController = null;
    }
  });
});

const PORT = process.env.PORT || 7860;
// Start the HTTP and WebSocket server.
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});