backup: working version 2026-04-20 (direct API + undici + acc3)

This commit is contained in:
aedes
2026-04-20 21:10:58 +03:00
parent c1e0940368
commit ec1a587c42
2 changed files with 425 additions and 0 deletions

View File

@@ -0,0 +1,315 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sechenov — Claude Chat</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #0f0f0f;
color: #e8e8e8;
height: 100vh;
display: flex;
flex-direction: column;
}
header {
padding: 12px 20px;
border-bottom: 1px solid #222;
display: flex;
align-items: center;
gap: 16px;
flex-shrink: 0;
}
header h1 { font-size: 16px; font-weight: 600; color: #fff; }
select {
background: #1e1e1e;
border: 1px solid #333;
color: #e8e8e8;
padding: 5px 10px;
border-radius: 6px;
font-size: 13px;
cursor: pointer;
}
select:focus { outline: none; border-color: #555; }
#status {
margin-left: auto;
font-size: 12px;
color: #666;
}
main {
flex: 1;
display: flex;
gap: 0;
overflow: hidden;
}
.pane {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
.pane + .pane { border-left: 1px solid #222; }
.pane-label {
padding: 8px 16px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #555;
border-bottom: 1px solid #1a1a1a;
flex-shrink: 0;
}
textarea {
flex: 1;
background: #0f0f0f;
color: #e8e8e8;
border: none;
padding: 16px;
font-size: 14px;
line-height: 1.6;
resize: none;
font-family: inherit;
}
textarea:focus { outline: none; }
textarea::placeholder { color: #444; }
#output {
flex: 1;
padding: 16px;
overflow-y: auto;
font-size: 14px;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
color: #d4d4d4;
}
#output.empty { color: #444; font-style: italic; }
footer {
padding: 12px 20px;
border-top: 1px solid #222;
display: flex;
gap: 10px;
align-items: center;
flex-shrink: 0;
}
button {
padding: 8px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s;
}
#sendBtn {
background: #2563eb;
color: #fff;
}
#sendBtn:hover { background: #1d4ed8; }
#sendBtn:disabled { background: #1e3a5f; color: #5a7fa8; cursor: not-allowed; }
#clearBtn {
background: #1e1e1e;
color: #999;
border: 1px solid #333;
}
#clearBtn:hover { background: #252525; }
.spinner {
display: none;
width: 14px; height: 14px;
border: 2px solid #333;
border-top-color: #2563eb;
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.loading .spinner { display: inline-block; }
/* Markdown-like rendering */
#output code {
background: #1a1a1a;
padding: 1px 5px;
border-radius: 3px;
font-family: 'Fira Code', 'Consolas', monospace;
font-size: 13px;
color: #ce9178;
}
#output pre {
background: #1a1a1a;
border: 1px solid #2a2a2a;
border-radius: 6px;
padding: 12px;
overflow-x: auto;
margin: 8px 0;
}
#output pre code {
background: none;
padding: 0;
color: #d4d4d4;
}
</style>
</head>
<body>
<header>
<h1>Claude Chat</h1>
<select id="modelSel">
<option value="sonnet">Sonnet 4.6</option>
<option value="haiku">Haiku 4.5</option>
</select>
<span id="status"></span>
</header>
<main>
<div class="pane">
<div class="pane-label">Запрос</div>
<textarea id="input" placeholder="Вставьте текст сюда..."></textarea>
</div>
<div class="pane">
<div class="pane-label">Ответ</div>
<div id="output" class="empty">Ответ появится здесь...</div>
</div>
</main>
<footer>
<button id="sendBtn">Отправить</button>
<button id="clearBtn">Очистить</button>
<div class="spinner" id="spinner"></div>
<span id="timer" style="margin-left:4px;font-size:12px;color:#555;"></span>
</footer>
<script>
const inputEl = document.getElementById('input');
const outputEl = document.getElementById('output');
const sendBtn = document.getElementById('sendBtn');
const clearBtn = document.getElementById('clearBtn');
const modelSel = document.getElementById('modelSel');
const statusEl = document.getElementById('status');
const spinnerEl = document.getElementById('spinner');
const timerEl = document.getElementById('timer');
let timerInterval = null;
let startTime = null;
function setLoading(on) {
sendBtn.disabled = on;
spinnerEl.style.display = on ? 'inline-block' : 'none';
if (on) {
startTime = Date.now();
timerInterval = setInterval(() => {
timerEl.textContent = ((Date.now() - startTime) / 1000).toFixed(1) + 's';
}, 100);
} else {
clearInterval(timerInterval);
}
}
function renderMarkdown(text) {
// Simple: escape html, then apply basic markdown
let html = text
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// Code blocks
html = html.replace(/```[\w]*\n?([\s\S]*?)```/g, (_, code) =>
`<pre><code>${code.trim()}</code></pre>`);
// Inline code
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
// Bold
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
return html;
}
async function send() {
const text = inputEl.value.trim();
if (!text) return;
outputEl.className = '';
outputEl.innerHTML = '';
setLoading(true);
statusEl.textContent = 'Генерирую...';
let fullText = '';
try {
const resp = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, model: modelSel.value }),
});
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const parts = buf.split('\n\n');
buf = parts.pop();
for (const part of parts) {
if (!part.startsWith('data: ')) continue;
const raw = part.slice(6).trim();
if (raw === '[DONE]') continue;
try {
const obj = JSON.parse(raw);
if (obj.error) {
outputEl.innerHTML += `<span style="color:#f87171">${obj.error}</span>`;
} else if (obj.text) {
fullText += obj.text;
outputEl.innerHTML = renderMarkdown(fullText);
outputEl.scrollTop = outputEl.scrollHeight;
}
} catch (e) {}
}
}
} catch (e) {
outputEl.innerHTML = `<span style="color:#f87171">Ошибка: ${e.message}</span>`;
} finally {
setLoading(false);
statusEl.textContent = fullText ? `${fullText.length} символов` : '';
}
}
sendBtn.addEventListener('click', send);
inputEl.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'Enter') send();
});
clearBtn.addEventListener('click', () => {
inputEl.value = '';
outputEl.innerHTML = 'Ответ появится здесь...';
outputEl.className = 'empty';
statusEl.textContent = '';
timerEl.textContent = '';
});
</script>
</body>
</html>

View File

@@ -0,0 +1,110 @@
const express = require('express');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { ProxyAgent, setGlobalDispatcher } = require('undici');
const proxyUrl = process.env.HTTPS_PROXY || process.env.HTTP_PROXY;
if (proxyUrl) {
setGlobalDispatcher(new ProxyAgent(proxyUrl));
console.log(`✓ Using proxy: ${proxyUrl}`);
}
const app = express();
app.use(express.json({ limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'public')));
const MODELS = {
sonnet: 'claude-sonnet-4-6',
haiku: 'claude-haiku-4-5-20251001',
};
function getAccessToken() {
const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
const credsPath = path.join(configDir, '.credentials.json');
try {
const creds = JSON.parse(fs.readFileSync(credsPath, 'utf8'));
return creds?.claudeAiOauth?.accessToken || null;
} catch (e) {
return null;
}
}
app.post('/api/chat', async (req, res) => {
const { text, model = 'sonnet' } = req.body;
if (!text?.trim()) return res.status(400).json({ error: 'text required' });
const modelId = MODELS[model] || MODELS.sonnet;
const accessToken = getAccessToken();
if (!accessToken) {
return res.status(500).json({ error: 'No credentials in ' + (process.env.CLAUDE_CONFIG_DIR || '~/.claude') });
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
const heartbeat = setInterval(() => res.write(': ping\n\n'), 15000);
try {
const apiResp = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
'anthropic-version': '2023-06-01',
'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14',
'x-app': 'cli',
'User-Agent': 'claude-cli/2.1.114',
},
body: JSON.stringify({
model: modelId,
max_tokens: 8192,
stream: true,
system: "You are Claude Code, Anthropic's official CLI for Claude.",
messages: [{ role: 'user', content: text }],
}),
});
if (!apiResp.ok) {
const errText = await apiResp.text();
res.write(`data: ${JSON.stringify({ error: `${apiResp.status}: ${errText.substring(0, 500)}` })}\n\n`);
return;
}
const reader = apiResp.body.getReader();
const decoder = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const events = buf.split('\n\n');
buf = events.pop();
for (const ev of events) {
const dataLine = ev.split('\n').find(l => l.startsWith('data: '));
if (!dataLine) continue;
const payload = dataLine.slice(6);
if (payload === '[DONE]') continue;
try {
const obj = JSON.parse(payload);
if (obj.type === 'content_block_delta' && obj.delta?.type === 'text_delta') {
res.write(`data: ${JSON.stringify({ text: obj.delta.text })}\n\n`);
}
} catch (e) {}
}
}
} catch (err) {
console.error('[api error]', err.message);
res.write(`data: ${JSON.stringify({ error: err.message })}\n\n`);
} finally {
clearInterval(heartbeat);
res.write('data: [DONE]\n\n');
res.end();
}
});
app.listen(8108, () => console.log('sechenov :8108'));