commit 7b59a16866ddd07fb9847b5aaaf50d2ee8e0986d Author: reform Date: Fri Oct 23 20:03:52 2026 +0300 recovered snapshot from suspended aaronjaworski710 (history unavailable) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4313a59 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.har +factory-session.json +factory-session.json.* +factory-conversations.json +factory-conversations.json.* +node_modules/ +*.tmp +*.log +factory-credentials.json +dashboard-credentials.har +factory-accounts.json +data/ +_work/ +*.local.json diff --git a/POST.md b/POST.md new file mode 100644 index 0000000..beff477 --- /dev/null +++ b/POST.md @@ -0,0 +1,34 @@ +# Пост для Telegram-канала (стиль @alstack) + +--- + +🔥 **GPT-5.6 Sol, бесплатный и прямо в твоём терминале** + +Пока все ищут, где взять топ-модель без подписок за $200 — один локальный прокси решает всё. + +Что случилось: у factory.8090.ai есть свой веб-чат с топовыми моделями. Я завернул его в **локальный OpenAI-совместимый шлюз** — и теперь любым CLI-агентом (Cline, Roo Code, OpenCode, Continue, OMP) можно работать через их моделей, как будто это твой обычный API. + +Что умеет коробка: + +▪️ Дашборд на `127.0.0.1:18090` — вставил креды, всё работает +▪️ 4 способа подачи кредов, включая **авто-сбор консольной командой** — один клик, заголовки сами падают в буфер +▪️ Chrome-расширение: перехватывает auth-заголовки твоей сессии и **само пушит их в прокси** — ноль ручного копирования +▪️ Кнопки «установить в Cline / Roo / OpenCode / Continue / OMP» — конфиги CLI обновляются в один клик, как в 9router +▪️ Playground прямо в дашборде: модель, reasoning_effort, стриминг +▪️ Токены протухают через час? Отправил боту ещё одно сообщение — расширение обновило креды само + +Как запустить (2 минуты): + +``` +git clone https://github.com/gbonnet65923/factory-8090-proxy +cd factory-8090-proxy +node server.mjs +``` + +Дальше: открываешь дашборд → «Способ 4» → вставляешь команду в консоль на factory.8090.ai → отправляешь боту любое сообщение → возвращаешься — модели уже на месте. + +Ноль зависимостей. Чистый Node 22, stdlib only. OpenAI `/v1/chat/completions`, стриминг, tool choice — всё как у больших. + +🔗 Репо: https://github.com/gbonnet65923/factory-8090-proxy + +Это тот случай, когда «просто попробовать» занимает меньше времени, чем прочитать этот пост. Кто заведёт — отпишитесь, как зашли 🫡 diff --git a/README.md b/README.md new file mode 100644 index 0000000..3af3c16 --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# Factory 8090 Proxy — бесплатный GPT-5.6/Opus через локальный OpenAI-шлюз + +Превращает веб-чат [factory.8090.ai](https://factory.8090.ai) в **локальный OpenAI-совместимый API**: вставил креды — получил endpoint для Roo Code, Cline, OMP, curl и всего, что умеет `/v1/chat/completions`. Zero-dependency: нужен только Node.js 20+. + +## Быстрый старт (2 минуты) + +1. **Запусти** `Start-Proxy.bat` (или `node server.mjs`). +2. Открой дашборд: **http://127.0.0.1:18090/** +3. Вставь креды — два способа на выбор: + - **HAR**: Chrome DevTools → Network → *Save all as HAR with sensitive data* → вставь JSON в форму дашборда (или просто скопируй `.har`-файл рядом с `server.mjs` — прокси подхватит его сам, без рестарта); + - **Headers**: скопируй заголовки любого запроса к `api.factory.8090.dev` (authorization, cognito, zed, org) + URL запроса. +4. Бейдж стал **live** — эндпоинт готов: + +``` +Base URL: http://127.0.0.1:18090/v1 +API key: local-trial +Models: gpt-5.6-sol, opus-5.5, … (каталог подтягивается с сервера) +``` + +Готовые сниппеты для curl / Roo Code / OMP — прямо на дашборде, с копированием в один клик. Там же **playground**: выбор модели, `reasoning_effort`, стриминг. + +## Фичи + +- **Дашборд из коробки** — статус, вставка кредов, playground, готовые конфиги. Никаких вторых серверов и портов. +- **Degraded-старт** — без кредов прокси не падает, а ждёт: `/health` → `waiting_for_har`, completions → 503 с подсказкой. Вставил креды — сразу live. +- **Hot-reload кредов** — дроп `.har`-файла в каталог = автоподхват без рестарта (fs.watch + debounce). Headers-вставка персистится в `factory-credentials.json` и переживает рестарты. +- **Reasoning** — OpenAI-поле `reasoning_effort` (`minimal|low|medium|high|none`) маппится в `thinking_level` Factory per-request. В OMP: `model:high` суффикс. +- **Инструменты** — полный tool-calling (function calling, `tool_choice`, параллельные вызовы, потоковая передача tool calls). +- **Sessions** — conversation-resume на стороне Factory: повторные запросы в рамках задачи продолжают тот же тред (перенос токенов ниже, ответы связаны контекстом). +- **Auto-refresh токена** — если в HAR есть Cognito-refresh-запрос, прокси обновляет авторизацию сам, пока жива refresh-сессия. +- **Ретраи** — сетевые сбои и 502/503/504/429 ретраятся автоматически. +- **`usage`** в каждом ответе (оценка симв./4). + +## Безопасность + +- Слушает только `127.0.0.1`; защита от DNS-rebinding (Host-header whitelist). +- Локальный API-ключ (`local-trial`, меняется через `PROXY_API_KEY`). +- `.har`-файлы, `factory-session.json`, `factory-conversations.json`, `factory-credentials.json` содержат данные сессии — **не публикуй и не отправляй их** (все в `.gitignore`). + +## Переменные окружения (все опциональны) + +| Переменная | По умолчанию | Что делает | +|---|---|---| +| `PROXY_PORT` | `18090` | порт | +| `PROXY_API_KEY` | `local-trial` | локальный ключ | +| `PROXY_HAR_WATCH` | вкл | `0` — выключить автоподхват `.har` | +| `PROXY_HAR_WATCH_DIR` | каталог скрипта | где искать `.har` | +| `FACTORY_HAR_PATH` | — | путь к HAR при запуске из env | +| `FACTORY_MODEL_KEY` | — | модель по умолчанию, если нет в HAR | + +## OMP / Claude-совместимые агенты + +```yaml +hermes-factory8090: + api: openai-completions + apiKey: local-trial + baseUrl: http://127.0.0.1:18090/v1 + models: + - id: gpt-5.6-sol + reasoning: true +``` + +## OpenCode + +`~/.config/opencode/opencode.json` (или `opencode.json` в проекте): + +```json +{ + "$schema": "https://opencode.ai/config.json", + "provider": { + "factory8090": { + "npm": "@ai-sdk/openai-compatible", + "name": "Factory 8090", + "options": { "baseURL": "http://127.0.0.1:18090/v1", "apiKey": "local-trial" }, + "models": { "gpt-5.6-sol": { "name": "GPT 5.6 Sol", "limit": { "context": 200000, "output": 32000 } } } + } + } +} +``` + +Выбор модели: `opencode run -m factory8090/gpt-5.6-sol "hi"`. + +## Cline (VS Code) + +Cline → Settings → API Provider: **OpenAI Compatible** → Base URL `http://127.0.0.1:18090/v1`, API Key `local-trial`, Model ID `gpt-5.6-sol`. + +## Continue + +`~/.continue/config.yaml`: + +```yaml +providers: + factory8090: + npm: "@continuedev/openai" + apiBase: http://127.0.0.1:18090/v1 + apiKey: local-trial + +models: + - name: GPT 5.6 Sol + provider: factory8090 + model: gpt-5.6-sol + roles: [chat, edit, apply] +``` + +## Тесты + +``` +npm test +``` + +33 теста, без сети: reasoning-маппинг, degraded-режим, hot-reload через дашборд (HAR и headers), tool-calls, стриминг, сессии. + +--- +Креды Factory — твои, трафик идёт напрямую с твоей машины в factory.8090.ai. Проект для личного использования. diff --git a/Start-From-Har.ps1 b/Start-From-Har.ps1 new file mode 100644 index 0000000..6b707ef --- /dev/null +++ b/Start-From-Har.ps1 @@ -0,0 +1,77 @@ +$harDirectory = $PSScriptRoot +$credentialHar = $null +$templateHar = $null +$modelsHar = $null +$authHar = $null +$credentialHeaders = $null +foreach ($candidate in (Get-ChildItem -LiteralPath $harDirectory -Filter '*.har' -File | + Sort-Object LastWriteTime -Descending)) { + try { + $har = Get-Content -LiteralPath $candidate.FullName -Raw | ConvertFrom-Json + if (-not $authHar) { + $authEntry = $har.log.entries | Where-Object { + $_.request.url -like 'https://cognito-idp.*.amazonaws.com/*' -and + $_.response.content.text -match '"RefreshToken"' + } | Select-Object -Last 1 + if ($authEntry) { $authHar = $candidate.FullName } + } + if (-not $credentialHar) { + $credentialRequest = $har.log.entries | Where-Object { + $_.request.url -like 'https://api.factory.8090.dev/*' -and + (@($_.request.headers | Where-Object { $_.name -ieq 'authorization' })).Count -gt 0 -and + (@($_.request.headers | Where-Object { $_.name -ieq 'x-sofa-cognito-id-token' })).Count -gt 0 -and + (@($_.request.headers | Where-Object { $_.name -ieq 'x-zed-token' })).Count -gt 0 + } | Select-Object -Last 1 + if ($credentialRequest) { + $credentialHar = $candidate.FullName + $credentialHeaders = $credentialRequest.request.headers + } + } + $inputRequest = $har.log.entries | Where-Object { $_.request.method -eq 'POST' -and + $_.request.url -match '/agents/chat-agent/input$' } | Select-Object -Last 1 + if ($inputRequest -and -not $templateHar) { $templateHar = $candidate.FullName } + $modelsRequest = $har.log.entries | Where-Object { $_.request.method -eq 'GET' -and + $_.request.url -match '/agents/models$' -and $_.response.status -eq 200 -and + $_.response.content.text } | Select-Object -Last 1 + if ($modelsRequest -and -not $modelsHar) { $modelsHar = $candidate.FullName } + if ($credentialHar -and $templateHar -and $modelsHar -and $authHar) { break } + } + catch { continue } +} +if (-not $credentialHar) { throw "No Factory HAR with authentication headers was found beside Start-Proxy.bat: $harDirectory" } +if (-not $templateHar) { $templateHar = $modelsHar } +if (-not $templateHar) { throw "No Factory HAR with a chat input or models request was found beside Start-Proxy.bat: $harDirectory" } +$getHeader = { param($name) ($credentialHeaders | Where-Object { $_.name -ieq $name } | Select-Object -First 1).value } +$env:FACTORY_HAR_PATH = $templateHar +if ($authHar) { + $env:FACTORY_AUTH_HAR_PATH = $authHar + $env:FACTORY_SESSION_PATH = Join-Path $PSScriptRoot 'factory-session.json' +} +$env:PROXY_CONVERSATIONS_PATH = Join-Path $PSScriptRoot 'factory-conversations.json' +if ($modelsHar) { $env:FACTORY_MODELS_HAR_PATH = $modelsHar } +$env:FACTORY_BEARER_TOKEN = (& $getHeader 'authorization') -replace '^Bearer\s+', '' +$env:FACTORY_COGNITO_TOKEN = & $getHeader 'x-sofa-cognito-id-token' +$env:FACTORY_ZED_TOKEN = & $getHeader 'x-zed-token' +$env:FACTORY_ORG_ID = & $getHeader 'x-sofa-active-org-id' +$env:FACTORY_WEB_CLIENT_VERSION = & $getHeader 'x-web-client-version' +$env:PROXY_API_KEY = 'local-trial' +try { + Write-Host "Using credentials from $([IO.Path]::GetFileName($credentialHar)) and chat template from $([IO.Path]::GetFileName($templateHar))" + if ($modelsHar) { Write-Host "Using model catalog from $([IO.Path]::GetFileName($modelsHar))" } + if ($authHar) { Write-Host "Automatic token refresh enabled from $([IO.Path]::GetFileName($authHar))" } + Push-Location -LiteralPath $PSScriptRoot + try { & node .\server.mjs } finally { Pop-Location } +} +finally { + Remove-Item Env:\FACTORY_HAR_PATH -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_MODELS_HAR_PATH -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_AUTH_HAR_PATH -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_SESSION_PATH -ErrorAction SilentlyContinue + Remove-Item Env:\PROXY_CONVERSATIONS_PATH -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_BEARER_TOKEN -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_COGNITO_TOKEN -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_ZED_TOKEN -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_ORG_ID -ErrorAction SilentlyContinue + Remove-Item Env:\FACTORY_WEB_CLIENT_VERSION -ErrorAction SilentlyContinue + Remove-Item Env:\PROXY_API_KEY -ErrorAction SilentlyContinue +} diff --git a/Start-Proxy.bat b/Start-Proxy.bat new file mode 100644 index 0000000..f07af76 --- /dev/null +++ b/Start-Proxy.bat @@ -0,0 +1,7 @@ +@echo off +rem Starts the Factory 8090 proxy with the built-in dashboard. +rem Drop a .har file next to this script or paste credentials at +rem http://127.0.0.1:18090/ once it is running. +cd /d "%~dp0" +node server.mjs +pause diff --git a/conversations.mjs b/conversations.mjs new file mode 100644 index 0000000..121f283 --- /dev/null +++ b/conversations.mjs @@ -0,0 +1,404 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { readFileSync, writeFileSync, renameSync, unlinkSync, chmodSync } from 'node:fs'; + +const MAX_SESSIONS = 500; +const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; + +function digest(value) { + return createHash('sha256').update(JSON.stringify(value)).digest('hex'); +} + +function messageHashes(messages) { + return messages.map(digest); +} + +export function normalizeTool(tool) { + return { + name: tool.name, + description: tool.description || '', + parameters: tool.parameters || {}, + }; +} + +export function normalizeTools(tools) { + if (!Array.isArray(tools) || !tools.length) return []; + return tools.map(normalizeTool).sort((a, b) => a.name.localeCompare(b.name)); +} + +export function normalizeToolChoice(choice) { + if (!choice) return 'auto'; + if (typeof choice === 'string') return choice.toLowerCase(); + if (typeof choice === 'object' && choice?.type === 'function') { + return { type: 'function', name: choice.function?.name || '' }; + } + return choice; +} + +export function computeOperationKey(options) { + const { + model, + hashes, + tools = [], + toolChoice = 'auto', + parallelToolCalls = true, + taskId = null, + requestId = null, + } = options; + + return digest({ + model, + hashes, + tools: normalizeTools(tools), + toolChoice: normalizeToolChoice(toolChoice), + parallelToolCalls: parallelToolCalls !== false, + taskId: taskId || null, + requestId: requestId || null, + }); +} + +function turnIdsOf(item) { + if (Array.isArray(item?.turnToolCallIds)) return item.turnToolCallIds.filter(id => typeof id === 'string' && id); + const lineage = new Set(Array.isArray(item?.lineageToolCallIds) ? item.lineageToolCallIds : []); + return (Array.isArray(item?.issuedToolCallIds) ? item.issuedToolCallIds : []) + .filter(id => typeof id === 'string' && id && !lineage.has(id)); +} + +function boundaryToolIds(messages, start) { + const ids = new Set(); + const assistant = messages[start]; + if (!assistant || assistant.role !== 'assistant') return ids; + for (const call of assistant.tool_calls || []) { + if (typeof call?.id === 'string' && call.id) ids.add(call.id); + } + for (let index = start + 1; index < messages.length; index++) { + const message = messages[index]; + if (message?.role !== 'tool') break; + if (typeof message.tool_call_id === 'string' && message.tool_call_id) ids.add(message.tool_call_id); + } + return ids; +} + +function readSaved(path) { + if (!path) return []; + try { + const parsed = JSON.parse(readFileSync(path, 'utf8')); + return parsed.version === 1 && Array.isArray(parsed.sessions) ? parsed.sessions : []; + } catch { + return []; + } +} + +export function createConversationStore(path, now = Date.now) { + // On startup, any session loaded from disk that had status === 'pending' + // was interrupted by process termination. Mark it uncertain so it cannot + // be confused with an in-flight or completed turn. + let sessions = readSaved(path).map(item => { + if (!item) return item; + const base = { + ...item, + issuedToolCallIds: Array.isArray(item.issuedToolCallIds) ? item.issuedToolCallIds : [], + lineageToolCallIds: Array.isArray(item.lineageToolCallIds) ? item.lineageToolCallIds : [], + turnToolCallIds: turnIdsOf(item), + }; + if (base.status === 'pending') { + return { ...base, status: 'uncertain' }; + } + return base; + }).filter(item => + item && typeof item.id === 'string' && typeof item.conversationId === 'string' && + Array.isArray(item.expected) && now() - item.updatedAt < MAX_AGE_MS + ).slice(-MAX_SESSIONS); + + const inFlightRequests = new Map(); // requestHash -> Promise + const conversationLocks = new Map(); // conversationId -> Promise + + function pruneSessions() { + const cutoff = now() - MAX_AGE_MS; + sessions = sessions.filter(s => s && s.updatedAt >= cutoff); + if (sessions.length > MAX_SESSIONS) { + // Prioritize preserving active done uncontinued sessions so parent tasks are not evicted + const uncontinued = sessions.filter(s => !s.continuedBy && s.status === 'done'); + const others = sessions.filter(s => s.continuedBy || s.status !== 'done'); + const keptOthers = others.slice(-Math.max(0, MAX_SESSIONS - uncontinued.length)); + sessions = [...keptOthers, ...uncontinued].sort((a, b) => a.updatedAt - b.updatedAt); + } + } + + function save() { + if (!path) return; + const temp = `${path}.${randomUUID()}.tmp`; + try { + writeFileSync(temp, JSON.stringify({ version: 1, sessions }), { mode: 0o600 }); + renameSync(temp, path); + try { chmodSync(path, 0o600); } catch { /* Windows compatibility */ } + } catch (err) { + try { unlinkSync(temp); } catch { /* ignore */ } + throw new Error(`Failed to persist conversation store to ${path}: ${err.message}`); + } + } + + function exactPrefix(hashes, prefix) { + return prefix.length <= hashes.length && prefix.every((part, index) => part === hashes[index]); + } + + function select(model, messages, options = {}) { + const taskId = options.taskId || null; + const requestId = options.requestId || null; + const tools = options.tools || []; + const toolChoice = options.toolChoice || 'auto'; + const parallelToolCalls = options.parallelToolCalls !== false; + const hashes = messageHashes(messages); + const requestHash = computeOperationKey({ + model, + hashes, + tools, + toolChoice, + parallelToolCalls, + taskId, + requestId, + }); + // A byte-identical body is not an identity. Cache and in-flight merging are + // enabled only when the client supplied a task id or an idempotency key. + // Without either, a retry and a new identical task cannot be told apart, + // so the safe choice is a fresh Factory conversation. + const canDedupe = Boolean(taskId || requestId); + const finish = fields => ({ + session: null, + hashes, + requestHash, + taskId, + requestId, + canDedupe, + ...fields, + }); + + if (canDedupe && inFlightRequests.has(requestHash)) { + const activePromise = inFlightRequests.get(requestHash); + if (options.ignoreInFlightPromise !== activePromise && options.ignoreInFlightHash !== requestHash) { + return finish({ + mode: 'in_flight', + inFlightPromise: activePromise, + }); + } + } + + if (canDedupe) { + const exact = sessions.findLast(s => + s.model === model && + (taskId ? s.taskId === taskId : !s.taskId) && + s.requestHash === requestHash + ); + if (exact) { + if (exact.status === 'done') { + if (exact.completion) { + // A turn already extended by a later request is not an active replay. + if (exact.continuedBy) return finish({ mode: 'new' }); + return finish({ session: exact, mode: 'cached', completion: exact.completion }); + } + // Parse error on a completed upstream turn: retry inside the same conversation. + return finish({ session: exact, mode: 'continue' }); + } + if (exact.status === 'pending') { + const activePromise = inFlightRequests.get(requestHash); + if (activePromise && options.ignoreInFlightPromise !== activePromise && options.ignoreInFlightHash !== requestHash) { + return finish({ + session: exact, + mode: 'in_flight', + inFlightPromise: activePromise, + }); + } + } + // uncertain, or a pending turn whose in-flight promise is gone: + // do not send the same turn into that Factory conversation again. + return finish({ mode: 'new' }); + } + } + + // Roo rewrites the assistant message before the next request: content "" + // instead of null, and JSON.stringify of the parsed tool arguments. That + // changes the message hash at the boundary even when the tool call ids are + // the same. Match the client prefix exactly, then accept the boundary + // assistant message only when it carries ids this turn issued. + const aligned = sessions.filter(session => { + if (session.model !== model || session.status !== 'done' || session.continuedBy) return false; + if (taskId ? session.taskId !== taskId : session.taskId) return false; + if (!Array.isArray(session.request) || !(session.request.length < hashes.length)) return false; + return exactPrefix(hashes, session.request); + }).sort((a, b) => b.request.length - a.request.length || b.updatedAt - a.updatedAt); + + const links = session => { + const start = session.request.length; + const turnIds = Array.isArray(session.turnToolCallIds) ? session.turnToolCallIds : []; + if (!turnIds.length) { + if (!taskId) return false; + return session.expected.length === start + 1 && hashes[start] === session.expected[start]; + } + const present = boundaryToolIds(messages, start); + return turnIds.some(id => present.has(id)); + }; + const longest = aligned[0]?.request.length ?? -1; + const frontier = aligned.filter(session => session.request.length === longest); + const linked = frontier.filter(links); + const describe = (session, reason) => { + const start = session?.request?.length ?? 0; + return { + reason, + prefix: start, + incomingLength: hashes.length, + boundaryRole: messages[start]?.role || null, + storedHash: typeof session?.expected?.[start] === 'string' ? session.expected[start].slice(0, 12) : null, + incomingHash: typeof hashes[start] === 'string' ? hashes[start].slice(0, 12) : null, + turnToolCalls: session?.turnToolCallIds?.length || 0, + }; + }; + + if (!linked.length) { + const candidate = aligned[0]; + let reason = 'new-no-prefix'; + if (candidate) { + const start = candidate.request.length; + const turnIds = Array.isArray(candidate.turnToolCallIds) ? candidate.turnToolCallIds : []; + const hashMatches = candidate.expected.length === start + 1 && hashes[start] === candidate.expected[start]; + reason = !turnIds.length && !taskId && hashMatches ? 'new-anonymous-text' : 'new-assistant-mismatch'; + } + return finish({ mode: 'new', decision: describe(candidate, reason) }); + } + if (linked.length > 1 && linked[0].request.length === linked[1].request.length) { + return finish({ mode: 'new', decision: describe(linked[0], 'new-ambiguous') }); + } + const parent = linked[0]; + return finish({ + session: parent, + mode: 'continue', + resumeAt: parent.request.length + 1, + decision: describe(parent, parent.turnToolCallIds?.length ? 'continue-tool-boundary' : 'continue-text'), + }); + } + + function begin(selection, model, options = {}) { + if (selection.session) selection.session.continuedBy = true; + const parent = selection.session || null; + const session = { + id: randomUUID(), + parentSession: parent, + conversationId: parent?.conversationId || randomUUID(), + clientMessageId: randomUUID(), + model, + taskId: options.taskId || selection.taskId || parent?.taskId || null, + requestHash: selection.requestHash, + request: selection.hashes, + expected: [], + issuedToolCallIds: [], + turnToolCallIds: [], + lineageToolCallIds: [ + ...(parent?.lineageToolCallIds || []), + ...(parent?.issuedToolCallIds || []), + ], + status: 'pending', + updatedAt: now(), + }; + sessions.push(session); + pruneSessions(); + try { + save(); + } catch (err) { + const idx = sessions.indexOf(session); + if (idx !== -1) sessions.splice(idx, 1); + if (selection.session) selection.session.continuedBy = false; + throw err; + } + return session; + } + + function commit(session, responseMessage, completion) { + session.expected = [...session.request, digest(responseMessage)]; + session.completion = completion; + session.status = 'done'; + session.updatedAt = now(); + + const toolCalls = completion?.choices?.[0]?.message?.tool_calls || responseMessage?.tool_calls; + const newlyIssued = Array.isArray(toolCalls) + ? toolCalls.map(c => c.id).filter(Boolean) + : []; + session.turnToolCallIds = newlyIssued; + session.issuedToolCallIds = [ + ...new Set([...(session.lineageToolCallIds || []), ...newlyIssued]), + ]; + + try { + save(); + } catch (err) { + session.status = 'uncertain'; + throw err; + } + } + + function commitParseError(session, rawAssistantText) { + session.expected = [...session.request]; + session.rawResponse = rawAssistantText; + session.completion = null; + session.status = 'done'; + session.updatedAt = now(); + session.issuedToolCallIds = [...(session.lineageToolCallIds || [])]; + try { + save(); + } catch (err) { + session.status = 'uncertain'; + throw err; + } + } + + function fail(session, options = {}) { + if (options.revertParent && session.parentSession) { + session.parentSession.continuedBy = false; + } + // An accepted Factory input may have completed despite a lost stream. + // Mark uncertain so it cannot be reused, and retries will start a clean new conversation. + session.status = 'uncertain'; + session.updatedAt = now(); + try { + save(); + } catch (err) { + console.error(`Warning: failed to persist session failure state: ${err.message}`); + } + } + + function setInFlight(requestHash, promise) { + inFlightRequests.set(requestHash, promise); + } + + function clearInFlight(requestHash) { + inFlightRequests.delete(requestHash); + } + + async function runExclusive(conversationId, fn) { + if (!conversationId) return fn(); + const prev = conversationLocks.get(conversationId) || Promise.resolve(); + let release; + const next = new Promise(resolve => { release = resolve; }); + const chained = prev.then(() => next, () => next); + conversationLocks.set(conversationId, chained); + try { + await prev; + return await fn(); + } finally { + release(); + if (conversationLocks.get(conversationId) === chained) { + conversationLocks.delete(conversationId); + } + } + } + + return { + select, + begin, + commit, + commitParseError, + fail, + setInFlight, + clearInFlight, + runExclusive, + activeLocksCount: () => conversationLocks.size, + getSessions: () => [...sessions], + }; +} diff --git a/dashboard.mjs b/dashboard.mjs new file mode 100644 index 0000000..795f78b --- /dev/null +++ b/dashboard.mjs @@ -0,0 +1,444 @@ +// Dashboard: paste credentials, watch status, test the endpoint. +// Pure helpers — no server, no fs. server.mjs owns routes and state. +function parseHeaderBlock(text) { + const headers = {}; + for (const line of text.split(/\r?\n/)) { + if (line.startsWith('http')) continue; // URL line pasted together with headers + const match = line.match(/^([A-Za-z0-9-]+)\s*:\s*(.*)$/); + if (!match) continue; + const name = match[1].toLowerCase(); + headers[name] = match[2].trim(); + } + return headers; +} + +function projectIdFromUrl(raw) { + try { + const path = new URL(raw).pathname; + return path.match(/^\/v2\/project\/([^/]+)\/agents/)?.[1] + || path.match(/^\/project\/([^/]+)$/)?.[1]; + } + catch { return undefined; } +} + +// Auto-detects what the user pasted: a HAR JSON document, a cookie-export +// JSON array (Cookie-Editor / EditThisCookie extension format), a URL, or a +// copied request-header block. Returns a parse result for envOverlayFromParsed. +function cookieFromExport(json) { + const arr = Array.isArray(json) ? json : [json]; + const pairs = arr + .filter(item => item && typeof item === 'object' && typeof item.name === 'string' && item.value != null) + .map(item => `${item.name}=${item.value}`); + return pairs.length ? pairs.join('; ') : null; +} + +export function parseCredentialPaste(text, urlHint = '') { + const trimmed = String(text || '').trim(); + if (!trimmed) throw new Error('Вставь HAR-файл, заголовки запроса или экспорт кук — инструкции выше'); + + if (trimmed.startsWith('{') || trimmed.startsWith('[')) { + let json; + try { json = JSON.parse(trimmed); } + catch { throw new Error('Текст похож на JSON, но JSON невалиден — скопируй файл/заголовки целиком'); } + if (json?.log?.entries) return { kind: 'har', har: json }; + const cookie = cookieFromExport(json); + if (cookie) { + // Cookie-Editor export: no auth tokens in it — keep parsing as headers, + // envOverlayFromParsed will ask for authorization if it is missing. + const urlMatch = urlHint || ''; + const projectId = projectIdFromUrl(urlMatch); + const originMatch = urlMatch.match(/^https?:\/\/[^/]+/)?.[0]; + const result = { kind: 'headers', headers: { cookie } }; + if (projectId) result.projectId = projectId; + if (originMatch) result.apiBase = originMatch; + return result; + } + throw new Error('JSON — не HAR (нет log.entries) и не экспорт кук (нет name/value)'); + } + + const headers = parseHeaderBlock(trimmed); + if (!headers.authorization && !headers['x-sofa-cognito-id-token'] && !headers.cookie) { + throw new Error('В заголовках нет authorization / x-sofa-cognito-id-token / cookie — скопируй секцию Request Headers из DevTools целиком'); + } + const urlMatch = urlHint || trimmed.match(/https?:\/\/[^\s]+\/v2\/project\/[^\s]+\/agents[^\s]*/)?.[0] || ''; + const projectId = projectIdFromUrl(urlMatch); + const originMatch = urlMatch.match(/^https?:\/\/[^/]+/)?.[0]; + const result = { kind: 'headers', headers }; + if (projectId) result.projectId = projectId; + if (originMatch) result.apiBase = originMatch; + return result; +} + +export function envOverlayFromParsed(parsed) { + const h = parsed.headers || {}; + const bearer = h.authorization?.replace(/^Bearer\s+/i, ''); + if (!bearer && !h['x-sofa-cognito-id-token']) { + throw new Error( + 'Кук недостаточно: factory.8090.ai авторизуется заголовками authorization: Bearer … и x-sofa-cognito-id-token: … ' + + '(куки из расширения, включая posthog, — аналитические и токенов не содержат). ' + + 'Скопируй Request Headers из DevTools (F12 → Network → POST …/input → Headers) или вставь HAR с sensitive data' + ); + } + if (!parsed.projectId) throw new Error('Header credentials need the request URL (contains the project id) — paste it in the URL field'); + const cognito = h['x-sofa-cognito-id-token'] || ''; + return { + FACTORY_API_BASE_URL: parsed.apiBase || 'https://api.factory.8090.dev', + FACTORY_PROJECT_ID: parsed.projectId, + FACTORY_ORG_ID: h['x-sofa-active-org-id'] || '', + FACTORY_BEARER_TOKEN: bearer || cognito || '', + FACTORY_COGNITO_TOKEN: cognito || bearer || '', + FACTORY_ZED_TOKEN: h['x-zed-token'] || '', + FACTORY_COOKIE: h.cookie || '', + FACTORY_WEB_CLIENT_VERSION: h['x-web-client-version'] || '0.53.7', + FACTORY_MODEL_KEY: 'gpt-5.6-sol', + }; +} + + +const CSS = ` +:root { color-scheme: dark; --bg:#0a0c10; --panel:#10141b; --panel2:#161c26; --line:#232b37; --fg:#e6edf3; --dim:#93a1b0; --ok:#3fb950; --warn:#d29922; --err:#f85149; --acc:#58a6ff; --grad:linear-gradient(135deg,#58a6ff,#bc8cff); } +* { box-sizing: border-box; margin: 0; } +body { background: var(--bg); background-image: radial-gradient(1100px 480px at 75% -12%, rgba(88,166,255,.10), transparent 60%), radial-gradient(800px 380px at 8% -4%, rgba(188,140,255,.07), transparent 60%); color: var(--fg); font: 15px/1.55 -apple-system, "Segoe UI", Inter, Roboto, sans-serif; padding: 32px 24px 72px; max-width: 1040px; margin: 0 auto; -webkit-font-smoothing: antialiased; } +header { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; margin-bottom: 28px; } +.logo { width: 46px; height: 46px; border-radius: 13px; background: var(--grad); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 15px; color: #fff; letter-spacing: -0.5px; flex: none; box-shadow: 0 6px 18px rgba(88,166,255,.35); } +h1 { font-size: 24px; letter-spacing: -0.3px; font-weight: 700; } +h1 span { background: var(--grad); -webkit-background-clip: text; background-clip: text; color: transparent; } +.sub { color: var(--dim); font-size: 13px; } +p.sub { margin-bottom: 14px; } +.card { background: linear-gradient(180deg, var(--panel2), var(--panel)); border: 1px solid var(--line); border-radius: 14px; padding: 20px; margin-bottom: 18px; box-shadow: inset 0 1px 0 rgba(255,255,255,.03), 0 10px 30px rgba(0,0,0,.35); } +.card h2 { font-size: 11px; letter-spacing: 0.09em; text-transform: uppercase; color: var(--dim); font-weight: 600; margin-bottom: 14px; } +.badge { display: inline-block; padding: 3px 12px; border-radius: 999px; font-size: 12px; font-weight: 600; vertical-align: middle; } +.badge.ok { background: rgba(63,185,80,.14); color: var(--ok); box-shadow: inset 0 0 0 1px rgba(63,185,80,.35); } +.badge.warn { background: rgba(210,153,34,.14); color: var(--warn); box-shadow: inset 0 0 0 1px rgba(210,153,34,.35); } +.row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 14px; } +.stat { background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; color: var(--dim); font-size: 12px; } +.stat b { color: var(--fg); font-size: 18px; display: block; font-variant-numeric: tabular-nums; } +.models { display: flex; flex-wrap: wrap; gap: 6px; } +.models code { background: var(--bg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 9px; font-size: 12px; color: var(--acc); font-family: ui-monospace, Consolas, monospace; } +textarea, input, select { width: 100%; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; font: 13px/1.5 ui-monospace, Consolas, monospace; transition: border-color .15s; } +textarea:focus, input:focus, select:focus { outline: none; border-color: var(--acc); box-shadow: 0 0 0 3px rgba(88,166,255,.12); } +textarea { min-height: 140px; resize: vertical; } +label { display: block; color: var(--dim); font-size: 12px; font-weight: 500; margin: 12px 0 5px; } +button { background: linear-gradient(180deg, #2ea043, #238636); color: #fff; border: 1px solid rgba(240,246,252,.12); border-radius: 10px; padding: 9px 18px; font-weight: 600; font-size: 14px; cursor: pointer; box-shadow: 0 4px 14px rgba(46,160,67,.25); } +button:hover { filter: brightness(1.12); } +button:active { transform: translateY(1px); } +button.ghost { background: transparent; border: 1px solid var(--line); color: var(--fg); font-weight: 500; padding: 5px 12px; font-size: 12px; box-shadow: none; } +pre { position: relative; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 12px; overflow-x: auto; font: 12px/1.55 ui-monospace, Consolas, monospace; white-space: pre-wrap; word-break: break-all; cursor: copy; transition: border-color .15s; } +pre:hover { border-color: var(--acc); } +pre:hover::after { content: "копировать"; position: absolute; top: 6px; right: 8px; font-size: 10px; color: var(--dim); background: var(--panel2); border: 1px solid var(--line); padding: 2px 7px; border-radius: 5px; font-family: -apple-system, "Segoe UI", sans-serif; } +details { border: 1px solid var(--line); border-radius: 10px; background: var(--bg); margin-bottom: 10px; overflow: hidden; } +details summary { cursor: pointer; padding: 11px 14px; color: var(--fg); font-weight: 600; font-size: 13px; list-style: none; display: flex; align-items: center; gap: 9px; user-select: none; } +details summary::-webkit-details-marker { display: none; } +details summary::before { content: "▸"; color: var(--dim); transition: transform .15s; flex: none; } +details[open] summary::before { transform: rotate(90deg); } +details[open] summary { border-bottom: 1px solid var(--line); background: rgba(88,166,255,.05); } +details > ol, details > p, details > pre, details > div { margin: 0 14px; padding-top: 12px; } +details > :last-child { padding-bottom: 14px; } +ol.sub { list-style: none; padding: 0; } +ol.sub li { position: relative; padding-left: 34px; margin-bottom: 9px; color: var(--dim); font-size: 13.5px; } +ol.sub li::before { content: counter(list-item); position: absolute; left: 0; top: 1px; width: 22px; height: 22px; border-radius: 7px; background: rgba(88,166,255,.12); color: var(--acc); font-size: 11px; font-weight: 700; display: flex; align-items: center; justify-content: center; border: 1px solid rgba(88,166,255,.25); } +ol.sub li b { color: var(--fg); } +.reco { font-size: 10px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; background: rgba(63,185,80,.14); color: var(--ok); padding: 2px 8px; border-radius: 999px; margin-left: auto; flex: none; } +.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.msg { margin-top: 12px; font-size: 13px; font-family: ui-monospace, Consolas, monospace; } +.msg.ok { color: var(--ok); } .msg.err { color: var(--err); } +#playout { white-space: pre-wrap; min-height: 44px; margin-top: 12px; } +.hidden { display: none; } +@media (max-width: 720px) { .grid { grid-template-columns: 1fr; } .row { gap: 8px; } .card { padding: 16px; } } +`; + +const JS = ` +const $ = id => document.getElementById(id); +async function refresh() { + try { + const s = await (await fetch('/v1/status')).json(); + $('badge').textContent = s.ready ? 'live' : 'waiting for credentials'; + $('badge').className = 'badge ' + (s.ready ? 'ok' : 'warn'); + $('mcount').textContent = s.models ? s.models.length : 0; + $('acount').textContent = s.accounts ?? 0; + $('sessions').textContent = s.sessions; + $('models').innerHTML = (s.models || []).map(m => '' + m + '').join(''); + const needCreds = !s.ready; + $('credcard').classList.remove('hidden'); + $('readycard').classList.toggle('hidden', needCreds); + const sel = $('pmodel'); + const current = sel.value; + sel.innerHTML = (s.models || []).map(m => '' + m + ''); + } catch { $('badge').textContent = 'unreachable'; $('badge').className = 'badge warn'; } +} +async function applyCreds() { + $('credmsg').textContent = 'Applying…'; $('credmsg').className = 'msg'; + try { + const res = await fetch('/dashboard/credentials', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ text: $('credtext').value, url: $('credurl').value }), + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error?.message || res.statusText); + $('credmsg').textContent = 'Credentials applied — proxy is live.' + (data.accounts ? ' Аккаунтов в пуле: ' + data.accounts + '.' : ''); $('credmsg').className = 'msg ok'; + refresh(); + } catch (e) { $('credmsg').textContent = e.message; $('credmsg').className = 'msg err'; } +} +function copy(id) { + const text = $(id).textContent; + navigator.clipboard.writeText(text).then(() => { $(id).dataset.hint = 'copied!'; }); +} +async function install(target) { + const msg = $('instmsg'); + msg.textContent = 'Устанавливаю в ' + target + '…'; msg.className = 'msg'; + try { + const res = await fetch('/dashboard/install', { + method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + KEY }, + body: JSON.stringify({ target }), + }); + const data = await res.json(); + if (!res.ok || data.ok === false) throw new Error(data.message || data.error?.message || res.statusText); + msg.textContent = '✔ ' + (data.message || 'готово'); msg.className = 'msg ok'; + } catch (e) { msg.textContent = '✖ ' + e.message; msg.className = 'msg err'; } +} +async function play() { + $('playout').textContent = '…'; + const body = { model: $('pmodel').value, messages: [{ role: 'user', content: $('pmsg').value }], max_tokens: 200 }; + if ($('peffort').value) body.reasoning_effort = $('peffort').value; + if ($('pstream').checked) { await playStream(body); return; } + try { + const res = await fetch('/v1/chat/completions', { + method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + KEY }, + body: JSON.stringify(body), + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error?.message || res.statusText); + $('playout').textContent = data.choices[0].message.content + '\\n\\n[usage: ' + JSON.stringify(data.usage) + ']'; + } catch (e) { $('playout').textContent = e.message; } +} +async function playStream(body) { + body.stream = true; + const res = await fetch('/v1/chat/completions', { + method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer ' + KEY }, + body: JSON.stringify(body), + }); + if (!res.ok) { $('playout').textContent = (await res.json()).error?.message; return; } + const reader = res.body.getReader(); + const dec = new TextDecoder(); + let buf = '', out = ''; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + buf += dec.decode(value, { stream: true }); + let idx; + while ((idx = buf.indexOf('\\n\\n')) !== -1) { + const frame = buf.slice(0, idx); buf = buf.slice(idx + 2); + const line = frame.split('\\n').find(l => l.startsWith('data: ')); + if (!line) continue; + const payload = line.slice(6); + if (payload === '[DONE]') continue; + try { out += (JSON.parse(payload).choices[0].delta.content || ''); } catch { } + } + } + $('playout').textContent = out; +} +refresh(); setInterval(refresh, 5000); +`; + +// DevTools console one-liner: hooks fetch/XHR on factory.8090.ai, captures the +// auth headers of the next chat-agent/input request and copies them (with the +// URL as the first line) so the whole thing can be pasted into one field. +const CONSOLE_SNIPPET = [ + '(() => {', + ' const emit = (url, h) => {', + ' const lines = Object.keys(h).map(k => k + ": " + h[k]);', + ' const text = url + "\\n" + lines.join("\\n");', + ' window.__FACTORY_CREDENTIALS__ = text;', + ' try { navigator.clipboard.writeText(text);', + ' console.log("%c\\u2714 \\u0413\\u043e\\u0442\\u043e\\u0432\\u043e \\u2014 \\u043a\\u0440\\u0435\\u0434\\u044b \\u0432 \\u0431\\u0443\\u0444\\u0435\\u0440\\u0435. \\u0412\\u0441\\u0442\\u0430\\u0432\\u044c \\u0432\\u0441\\u0451 \\u0432 \\u043e\\u0434\\u043d\\u043e \\u043f\\u043e\\u043b\\u0435 \\u043d\\u0430 \\u0434\\u0430\\u0448\\u0431\\u043e\\u0440\\u0434\\u0435.", "color:#3fb950;font-size:14px"); }', + ' catch (e) { console.log("\\u0421\\u043a\\u043e\\u043f\\u0438\\u0440\\u0443\\u0439 \\u0432\\u0440\\u0443\\u0447\\u043d\\u0443\\u044e \\u0438\\u0437 \\u043b\\u043e\\u0433\\u0430 \\u043d\\u0438\\u0436\\u0435:"); }', + ' console.log(text);', + ' };', + ' const of = window.fetch;', + ' window.fetch = function(input, init) {', + ' try {', + ' init = init || {};', + ' const url = typeof input === "string" ? input : (input && input.url) || "";', + ' if (/chat-agent\\/input/.test(url)) {', + ' const h = {};', + ' if (init.headers && typeof init.headers.forEach === "function") init.headers.forEach(function(v, k) { h[k] = v; });', + ' else if (init.headers) Object.assign(h, init.headers);', + ' emit(url, h);', + ' }', + ' } catch (e) {}', + ' return of.apply(this, arguments);', + ' };', + ' const oo = XMLHttpRequest.prototype.open, os = XMLHttpRequest.prototype.setRequestHeader, osd = XMLHttpRequest.prototype.send;', + ' XMLHttpRequest.prototype.open = function(m, u) { this.__furl = u; return oo.apply(this, arguments); };', + ' XMLHttpRequest.prototype.setRequestHeader = function(k, v) {', + ' if (this.__furl && /chat-agent\\/input/.test(this.__furl)) (this.__fh = this.__fh || {})[k] = v;', + ' return os.apply(this, arguments);', + ' };', + ' XMLHttpRequest.prototype.send = function() {', + ' if (this.__furl && this.__fh) emit(this.__furl, this.__fh);', + ' return osd.apply(this, arguments);', + ' };', + ' const found = [];', + ' for (let i = 0; i < localStorage.length; i++) {', + ' const k = localStorage.key(i), v = localStorage.getItem(k);', + ' if (/^eyJ/.test(v) || /token/i.test(k)) found.push(k);', + ' }', + ' if (found.length) console.log("\\u041a\\u043b\\u044e\\u0447\\u0438 localStorage \\u0441 \\u0442\\u043e\\u043a\\u0435\\u043d\\u0430\\u043c\\u0438: " + found.join(", "));', + ' console.log("%c\\u{1F3A4} \\u0425\\u0443\\u043a \\u0443\\u0441\\u0442\\u0430\\u043d\\u043e\\u0432\\u043b\\u0435\\u043d. \\u0422\\u0435\\u043f\\u0435\\u0440\\u044c \\u043e\\u0442\\u043f\\u0440\\u0430\\u0432\\u044c \\u0431\\u043e\\u0442\\u0443 \\u043b\\u044e\\u0431\\u043e\\u0435 \\u0441\\u043e\\u043e\\u0431\\u0449\\u0435\\u043d\\u0438\\u0435 \\u2014 \\u043a\\u0440\\u0435\\u0434\\u044b \\u0441\\u043e\\u0431\\u0435\\u0440\\u0443\\u0442\\u0441\\u044f \\u0441\\u0430\\u043c\\u0438.", "color:#58a6ff;font-size:14px");', + '})();', +].join('\n'); + +export function renderDashboardPage({ port, apiKey, models = [] }) { + const base = `http://127.0.0.1:${port}/v1`; + const curl = `curl ${base}/chat/completions \\\n -H "Authorization: Bearer ${apiKey}" \\\n -H "Content-Type: application/json" \\\n -d '{"model":"${models[0] || 'gpt-5.6-sol'}","messages":[{"role":"user","content":"Say OK"}]}'`; + const roo = JSON.stringify({ + apiProvider: 'openai-compatible', + baseUrl: base, + apiKey, + defaultModel: models[0] || 'gpt-5.6-sol', + }, null, 2); + const omp = ` hermes-factory8090:\n api: openai-completions\n apiKey: ${apiKey}\n baseUrl: ${base}\n compat:\n supportsStreaming: true\n supportsToolChoice: true\n models:\n - id: ${models[0] || 'gpt-5.6-sol'}\n reasoning: true`; + const modelList = (models.length ? models : ['gpt-5.6-sol']); + const opencode = JSON.stringify({ + $schema: 'https://opencode.ai/config.json', + provider: { + factory8090: { + npm: '@ai-sdk/openai-compatible', + name: 'Factory 8090', + options: { baseURL: base, apiKey }, + models: Object.fromEntries(modelList.map(m => [m, { name: m, limit: { context: 200000, output: 32000 } }])), + }, + }, + }, null, 2); + const cline = JSON.stringify({ + apiProvider: 'openai-compatible', + openAiBaseUrl: base, + openAiApiKey: apiKey, + openAiModelId: modelList[0], + }, null, 2); + const continueSnippet = `models:\n${modelList.map(m => ` - name: ${m}\n provider: factory8090\n roles: [chat, edit, apply]\n model: ${m}\n apiKey: ${apiKey}`).join('\n')}\n\nproviders:\n factory8090:\n npm: '@continuedev/openai'\n apiBase: ${base}\n apiKey: ${apiKey}`; + return ` + +Factory 8090 Proxy + + + +
+ +
+

Factory 8090 Proxy

+
Локальный OpenAI-совместимый шлюз для factory.8090.ai  ·  …
+
+
+ +
+

Статус

+
+
0моделей
+
0аккаунтов
+
0активных сессий
+
—токен истекает
+
+
+
+ +
+

Креды

+

Прокси стартует без кредов и ждёт их здесь. Вставь — подхватит на лету, без рестарта.

+ +
+ Способ 1 — HAR-файл (рекомендуется, куки и токены внутри) +
    +
  1. Открой factory.8090.ai в Chrome и войди в аккаунт.
  2. +
  3. F12 → вкладка Network (Сеть). Отправь боту любое сообщение.
  4. +
  5. Клик правой кнопкой по любому запросу в списке → «Save all as HAR with sensitive data» (Сохранить всё как HAR с конфиденциальными данными).
    Важно: нужен именно вариант with sensitive data — обычный HAR не содержит токенов.
  6. +
  7. Открой сохранённый .har файл блокнотом → Ctrl+A, Ctrl+C.
  8. +
  9. Вставь всё в поле ниже → Применить. URL не нужен.
  10. +
+
+ +
+ Способ 2 — Заголовки запроса + куки (вручную) +
    +
  1. Открой factory.8090.ai в Chrome и войди в аккаунт.
  2. +
  3. F12 → вкладка Network → отправь боту любое сообщение.
  4. +
  5. Найди запрос POST …/agents/chat-agent/input → клик по нему → вкладка Headers (Заголовки).
  6. +
  7. В секции Request Headers скопируй все строки — включая строку cookie: … (куки идут сюда же, отдельного поля не нужно).
    Проще всего: правый клик по списку заголовков → «Copy value»/выделить всё и скопировать.
  8. +
  9. Вставь в поле ниже. Обязательно нужны строки authorization: Bearer … или x-sofa-cognito-id-token: ….
  10. +
  11. В поле URL запроса скопируй адрес из шапки того же запроса (там есть project id) → Применить.
  12. +
+
+ +
+ Способ 3 — Куки из расширения (формат Cookie-Editor / EditThisCookie JSON) +
    +
  1. Поставь в Chrome расширение Cookie-Editor, открой factory.8090.ai (войдя в аккаунт).
  2. +
  3. Клик по иконке расширения → Export (JSON) → вставь массив кук в поле ниже.
  4. +
  5. Вставь также URL страницы в поле URL.
  6. +
+

⚠ Одних кук недостаточно: авторизация у factory идёт заголовками authorization: Bearer … и x-sofa-cognito-id-token: …, а куки вида posthog_* — только аналитика. Способ 3 годится как дополнение к способу 2 (вставь куки + заголовки в одно поле), сам по себе — нет.

+
+
+ Способ 4 — Команда в консоль (авто-сбор, без ручного копирования)проще всего +
    +
  1. Открой factory.8090.ai (войдя в аккаунт) и нажми F12 → вкладка Console.
  2. +
  3. Скопируй команду (клик по блоку ниже) и вставь её в консоль → Enter.
  4. +
  5. Отправь боту любое сообщение — команда перехватит запрос к API и сама скопирует URL и все auth-заголовки в буфер обмена.
  6. +
  7. Вернись сюда и вставь всё одним куском в поле ниже (URL будет первой строкой, отдельное поле URL не нужно).
  8. +
+
${CONSOLE_SNIPPET.replace(/
+    

Клик по блоку — копирование. Команда безвредна: она только читает исходящий запрос, ничего не отправляет и не меняет.

+

💾 Пул аккаунтов: каждая вставка — это аккаунт. Повторная вставка с тем же логином обновляет его токены; вставка с другого логина добавляет новый аккаунт в пул. При 401 (токен истёк) прокси сам переключается на следующий аккаунт. Токены живут ~1 час — при 401 просто вставь свежий блок.

+
+ + + + + +
+
+
+ +
+

Эндпоинт

+
+
${base}
+
${apiKey}
+
+ +
+ + + + + +
+
+
curl
${curl.replace(/
+
Roo Code / Cline settings
${roo.replace(/
+
OMP models.yml
${omp.replace(/
+
OpenCode — opencode.json
${opencode.replace(/
+
Cline — VS Code settings
${cline.replace(/
+
Continue — config.yaml
${continueSnippet.replace(/
+
+ +
+

Playground

+

Модели и выбор появятся, как только вставишь креды выше (сейчас прокси ждёт авторизацию).

+
+
+
+
+
+ + +
+ + +
+

+
+ + +`; +} diff --git a/factory-accounts.example.json b/factory-accounts.example.json new file mode 100644 index 0000000..a7f05d6 --- /dev/null +++ b/factory-accounts.example.json @@ -0,0 +1,9 @@ +[ + { + "id": "", + "headers": { + "authorization": "Bearer " + }, + "note": "Replace with your own factory.8090.ai session. Real file is gitignored." + } +] \ No newline at end of file diff --git a/factory-accounts.json b/factory-accounts.json new file mode 100644 index 0000000..a7f05d6 --- /dev/null +++ b/factory-accounts.json @@ -0,0 +1,9 @@ +[ + { + "id": "", + "headers": { + "authorization": "Bearer " + }, + "note": "Replace with your own factory.8090.ai session. Real file is gitignored." + } +] \ No newline at end of file diff --git a/factory-auth.mjs b/factory-auth.mjs new file mode 100644 index 0000000..9300f34 --- /dev/null +++ b/factory-auth.mjs @@ -0,0 +1,111 @@ +import { readFileSync, writeFileSync, renameSync, unlinkSync, chmodSync } from 'node:fs'; +import { randomUUID } from 'node:crypto'; + +function jwtExpiry(token) { + try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url')).exp * 1000; } + catch { return 0; } +} + +function readJson(path) { + try { return JSON.parse(readFileSync(path, 'utf8')); } + catch { return null; } +} + +export function authFromHar(path) { + const har = readJson(path); + if (!har?.log?.entries) throw new Error('FACTORY_AUTH_HAR_PATH is not a readable HAR'); + let configEntry; + let cognito; + for (const e of har.log.entries) { + try { + if (new URL(e.request.url).pathname === '/config.json') { + configEntry = e; + cognito = JSON.parse(configEntry.response?.content?.text || '{}').cognito; + } + } catch { /* ignore malformed HAR entries */ } + } + const entry = har.log.entries.findLast(e => { + try { + if (!cognito?.region || new URL(e.request.url).hostname !== `cognito-idp.${cognito.region}.amazonaws.com`) return false; + return Boolean(JSON.parse(e.response.content.text).AuthenticationResult?.RefreshToken); + } catch { return false; } + }); + if (!entry || !cognito?.userPoolClientId || !cognito?.region) { + throw new Error('HAR has no Cognito refresh token or public client configuration'); + } + let result; + try { + result = JSON.parse(entry.response.content.text).AuthenticationResult; + } catch { + throw new Error('HAR contains unreadable Cognito AuthenticationResult'); + } + return { + clientId: cognito.userPoolClientId, region: cognito.region, + accessToken: result.AccessToken, idToken: result.IdToken, + refreshToken: result.RefreshToken, expiresAt: jwtExpiry(result.AccessToken), + }; +} + +export function createFactoryAuth(initial, sessionPath, fetchImpl = fetch, now = Date.now) { + const saved = sessionPath && readJson(sessionPath); + // A saved session can contain a rotated refresh token that the HAR no longer has. + let state = saved?.clientId === initial.clientId && saved?.region === initial.region && + saved?.refreshToken && saved?.accessToken && saved?.idToken && + jwtExpiry(saved.accessToken) >= initial.expiresAt ? saved : initial; + let pending; + let persistenceError = null; + + function persistState() { + if (!sessionPath) return; + const temp = `${sessionPath}.${randomUUID()}.tmp`; + try { + writeFileSync(temp, JSON.stringify(state), { mode: 0o600 }); + renameSync(temp, sessionPath); + try { chmodSync(sessionPath, 0o600); } catch { /* Windows compatibility */ } + persistenceError = null; + } catch (err) { + try { unlinkSync(temp); } catch { /* ignore */ } + persistenceError = new Error(`Could not save the refreshed Factory session to ${sessionPath}: ${err.message}`); + throw persistenceError; + } + } + + async function refresh() { + const response = await fetchImpl(`https://cognito-idp.${state.region}.amazonaws.com/`, { + method: 'POST', + headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSCognitoIdentityProviderService.GetTokensFromRefreshToken' }, + body: JSON.stringify({ ClientId: state.clientId, RefreshToken: state.refreshToken }), + signal: AbortSignal.timeout(30_000), + }); + if (!response.ok) throw new Error(`Cognito token refresh failed (HTTP ${response.status})`); + let result; + try { + result = (await response.json()).AuthenticationResult; + } catch { + throw new Error('Cognito token refresh returned invalid JSON'); + } + if (!result?.AccessToken || !result?.IdToken) throw new Error('Cognito token refresh returned no access or ID token'); + const next = { + ...state, accessToken: result.AccessToken, idToken: result.IdToken, + refreshToken: result.RefreshToken || state.refreshToken, + expiresAt: jwtExpiry(result.AccessToken), + }; + state = next; + persistState(); + return state; + } + + return { + async current() { + if (persistenceError) { + persistState(); + } + if (state.expiresAt > now() + 5 * 60_000) return state; + if (!pending) pending = refresh().finally(() => { pending = null; }); + return pending; + }, + getState() { + return state; + }, + }; +} diff --git a/factory-conversations.json b/factory-conversations.json new file mode 100644 index 0000000..aafed72 --- /dev/null +++ b/factory-conversations.json @@ -0,0 +1 @@ +{"version":1,"sessions":[{"id":"2039af70-065b-4ea8-9a02-97d97c866094","parentSession":null,"conversationId":"f9af48c1-9fbd-45e3-a6d3-598d26c733e9","clientMessageId":"bedc4565-8a8f-4d4d-a1a3-44561d35310b","model":"gpt-5.6-sol","taskId":null,"requestHash":"ea0b4a09cd4a68f29d6739893de9738eeff5d1b2ebf5f84bfeceb4e8b81ca88b","request":["9cc7e36e7aefcef148ea0990bdefbd41f7887e990892dadb425998cc01c8fb47"],"expected":[],"issuedToolCallIds":[],"turnToolCallIds":[],"lineageToolCallIds":[],"status":"uncertain","updatedAt":1790445522479}]} \ No newline at end of file diff --git a/factory-credentials.example.json b/factory-credentials.example.json new file mode 100644 index 0000000..d0467fe --- /dev/null +++ b/factory-credentials.example.json @@ -0,0 +1,6 @@ +{ + "headers": { + "authorization": "Bearer " + }, + "note": "Replace with your own factory.8090.ai credentials. Real file is gitignored." +} \ No newline at end of file diff --git a/factory-credentials.json b/factory-credentials.json new file mode 100644 index 0000000..d0467fe --- /dev/null +++ b/factory-credentials.json @@ -0,0 +1,6 @@ +{ + "headers": { + "authorization": "Bearer " + }, + "note": "Replace with your own factory.8090.ai credentials. Real file is gitignored." +} \ No newline at end of file diff --git a/factory_ext/README.md b/factory_ext/README.md new file mode 100644 index 0000000..462751d --- /dev/null +++ b/factory_ext/README.md @@ -0,0 +1,23 @@ +# Factory 8090 Credential Collector (Chrome MV3) + +Расширение автоматически ловит auth-заголовки (authorization, x-sofa-cognito-id-token, x-zed-token, …) запросов твоей сессии на factory.8090.ai и **само** отправляет их в прокси `127.0.0.1:18090`. Никакого ручного копирования. + +## Установка + +1. Chrome → `chrome://extensions` +2. Включи **Developer mode** (справа сверху) +3. **Load unpacked** → выбери папку `factory_ext` +4. Убедись, что прокси запущен: `node C:/Users/User/tmp/factory_proxy/server.mjs` (порт 18090) + +## Как работает + +1. Открой factory.8090.ai, войди в аккаунт +2. Отправь боту любое сообщение +3. Расширение перехватит POST `api.factory.8090.dev/v2/project//agents/chat-agent/input`, соберёт заголовки и запушит их на `POST /dashboard/credentials` прокси +4. На дашборде `http://127.0.0.1:18090/` статус станет `ready`, появятся модели + +Расширение только читает исходящие заголовки — ничего не блокирует и не меняет. Креды уходят только на `127.0.0.1` (твой локальный прокси). + +Данные последнего перехвата: `chrome://extensions` → Factory 8090 Credential Collector → service worker → Storage (lastText / lastUrl). + +Токены Cognito живут ~час — просто отправь боту ещё одно сообщение, расширение обновит креды само. diff --git a/factory_ext/background.js b/factory_ext/background.js new file mode 100644 index 0000000..0b45ae8 --- /dev/null +++ b/factory_ext/background.js @@ -0,0 +1,41 @@ +// Factory 8090 Credential Collector — MV3 service worker. +// Watches outgoing requests to api.factory.8090.dev; when it sees a +// chat-agent/input request with an authorization header, it formats the +// headers and POSTs them to the local proxy dashboard endpoint. +// Read-only: never modifies or blocks requests. + +const PROXY_ENDPOINT = 'http://127.0.0.1:18090/dashboard/credentials'; +const TARGET = /api\.factory\.8090\.dev\/v2\/project\/[0-9a-f-]+\/agents\/chat-agent\/input/i; + +chrome.webRequest.onBeforeSendHeaders.addListener( + (details) => { + try { + if (details.method !== 'POST' || !TARGET.test(details.url)) return; + const headers = {}; + for (const h of details.requestHeaders || []) { + headers[h.name.toLowerCase()] = h.value || ''; + } + if (!headers.authorization) return; + const text = Object.keys(headers) + .map((k) => k + ': ' + headers[k]) + .join('\n'); + chrome.storage.local.get({ lastSent: 0 }, ({ lastSent }) => { + // Debounce: the site sends several requests per message. + if (Date.now() - lastSent < 2000) return; + chrome.storage.local.set({ lastSent: Date.now(), lastText: text, lastUrl: details.url }); + fetch(PROXY_ENDPOINT, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ text, url: details.url }), + }) + .then((r) => r.text()) + .then((t) => console.log('[factory-collector] proxy response:', t)) + .catch((e) => console.warn('[factory-collector] proxy unreachable:', e.message)); + }); + } catch (e) { + console.warn('[factory-collector] error:', e); + } + }, + { urls: ['https://api.factory.8090.dev/*'] }, + ['requestHeaders'] +); diff --git a/factory_ext/manifest.json b/factory_ext/manifest.json new file mode 100644 index 0000000..3dd2917 --- /dev/null +++ b/factory_ext/manifest.json @@ -0,0 +1,13 @@ +{ + "manifest_version": 3, + "name": "Factory 8090 Credential Collector", + "version": "1.0.0", + "description": "Перехватывает auth-заголовки запросов factory.8090.ai и автоматически отправляет их в локальный прокси (127.0.0.1:18090)", + "permissions": ["webRequest"], + "host_permissions": [ + "https://api.factory.8090.dev/*", + "https://factory.8090.ai/*", + "http://127.0.0.1:18090/*" + ], + "background": { "service_worker": "background.js" } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..9d15872 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "name": "factory-8090-local-proxy", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "start": "node server.mjs", + "test": "node --test" + }, + "engines": { + "node": ">=20" + } +} diff --git a/server.mjs b/server.mjs new file mode 100644 index 0000000..f0787d9 --- /dev/null +++ b/server.mjs @@ -0,0 +1,1641 @@ +import http from 'node:http'; +import { randomUUID, timingSafeEqual } from 'node:crypto'; +import { readFileSync, writeFileSync, readdirSync, statSync, watch, existsSync, copyFileSync, mkdirSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { basename, dirname, join } from 'node:path'; +import { authFromHar, createFactoryAuth } from './factory-auth.mjs'; +import { parseCredentialPaste, envOverlayFromParsed, renderDashboardPage } from './dashboard.mjs'; +import { createConversationStore } from './conversations.mjs'; + +const MAX_REQUEST_BYTES = 8 * 1024 * 1024; +const MAX_SSE_FRAME_BYTES = 32 * 1024 * 1024; +const MAX_FACTORY_PROMPT_CHARS = 240_000; + +class ProxyError extends Error { + constructor(status, message, type = 'invalid_request_error') { + super(message); + this.status = status; + this.type = type; + } +} + +function required(env, name) { + const value = env[name]?.trim(); + if (!value) throw new Error(`${name} is required`); + return value; +} + +function settingsFromHar(path) { + let har; + try { har = JSON.parse(readFileSync(path, 'utf8')); } + catch { throw new Error('FACTORY_HAR_PATH does not point to a readable HAR JSON file'); } + const inputEntry = har.log?.entries?.findLast(item => + item.request?.method === 'POST' && /\/agents\/chat-agent\/input$/.test(item.request.url || '')); + const entry = inputEntry || har.log?.entries?.findLast(item => + item.request?.method === 'GET' && /\/agents\/models$/.test(item.request.url || '')); + if (!entry) throw new Error('The HAR has no Factory Agent chat input or models request'); + const header = name => entry.request.headers?.find(item => item.name?.toLowerCase() === name)?.value; + const requestUrl = new URL(entry.request.url); + const projectId = requestUrl.pathname.match(/^\/v2\/project\/([^/]+)\/agents\//)?.[1]; + let payload = {}; + if (inputEntry) { + try { payload = JSON.parse(inputEntry.request.postData.text); } + catch { throw new Error('The Factory input request in the HAR has no readable JSON body'); } + } + const selectionEntry = har.log?.entries?.findLast(item => + item.request?.method === 'GET' && /\/agents\/user-preferences\/model-selection/.test(item.request.url || '')); + let selectedModel; + try { selectedModel = JSON.parse(selectionEntry?.response?.content?.text || '{}').effective_model_key; } + catch { /* A missing selection can fall back to the catalog recommendation. */ } + let recommendedModel; + try { recommendedModel = JSON.parse(entry.response?.content?.text || '{}').recommended_model; } + catch { /* The chat input response is not a model catalog. */ } + const cognitoToken = header('x-sofa-cognito-id-token'); + return { + FACTORY_API_BASE_URL: requestUrl.origin, + FACTORY_PROJECT_ID: projectId, + FACTORY_ORG_ID: header('x-sofa-active-org-id'), + // Chrome's sanitized HAR drops Authorization. Supply it separately unless + // the HAR was exported with sensitive data. + FACTORY_BEARER_TOKEN: header('authorization')?.replace(/^Bearer\s+/i, ''), + FACTORY_COGNITO_TOKEN: cognitoToken, + FACTORY_ZED_TOKEN: header('x-zed-token'), + FACTORY_WEB_CLIENT_VERSION: header('x-web-client-version'), + FACTORY_MODEL_KEY: payload.model?.model_key || selectedModel || recommendedModel, + FACTORY_THINKING_LEVEL: payload.model?.configuration?.thinking_level, + FACTORY_CONTEXT_WINDOW: payload.model?.configuration?.context_window, + FACTORY_GENERATION_MODE: payload.model?.configuration?.generation_mode, + FACTORY_SERVING_SOURCE: payload.model?.configuration?.serving_source, + }; +} + +function modelCatalogFromHar(path) { + let har; + try { har = JSON.parse(readFileSync(path, 'utf8')); } + catch { throw new Error('FACTORY_MODELS_HAR_PATH does not point to a readable HAR JSON file'); } + const entry = har.log?.entries?.findLast(item => + item.request?.method === 'GET' && /\/agents\/models$/.test(new URL(item.request.url || 'http://invalid').pathname)); + if (!entry) throw new Error('The model HAR has no Factory agents/models response'); + let catalog; + try { catalog = JSON.parse(entry.response.content.text); } + catch { throw new Error('The Factory model catalog in the HAR is not readable JSON'); } + if (!Array.isArray(catalog.models) || !catalog.models.length) { + throw new Error('The Factory model catalog in the HAR is empty'); + } + return catalog.models.filter(model => typeof model.key === 'string' && model.key.length > 0); +} + +export function loadConfig(env = process.env) { + const values = env.FACTORY_HAR_PATH ? { ...settingsFromHar(env.FACTORY_HAR_PATH), ...env } : env; + const authInitial = values.FACTORY_AUTH_HAR_PATH ? authFromHar(values.FACTORY_AUTH_HAR_PATH) : null; + const apiBase = new URL(values.FACTORY_API_BASE_URL || 'https://api.factory.8090.dev'); + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(apiBase.hostname); + if (apiBase.protocol !== 'https:' && !(apiBase.protocol === 'http:' && loopback)) { + throw new Error('FACTORY_API_BASE_URL must use HTTPS (HTTP is allowed only for loopback tests)'); + } + const port = Number(values.PROXY_PORT || 18090); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('PROXY_PORT is invalid'); + const catalog = values.FACTORY_MODELS_HAR_PATH ? modelCatalogFromHar(values.FACTORY_MODELS_HAR_PATH) : []; + const modelKey = values.FACTORY_MODEL_KEY || + (catalog.some(model => model.key === 'gpt-5.6-sol') ? 'gpt-5.6-sol' : catalog[0]?.key); + if (!modelKey) throw new Error('FACTORY_MODEL_KEY is required when the HAR has no model catalog'); + const modelKeys = [...new Set([modelKey, ...catalog.map(model => model.key), + ...(values.PROXY_MODEL_IDS || '').split(',').map(value => value.trim()).filter(Boolean)])]; + const modelSettings = Object.fromEntries(catalog.map(model => [model.key, { + thinkingLevel: model.capabilities?.thinking?.choices?.default || model.capabilities?.thinking?.default || model.default_thinking_level || 'medium', + }])); + const bearerToken = values.FACTORY_BEARER_TOKEN?.trim() || authInitial?.accessToken; + if (!bearerToken) throw new Error('FACTORY_BEARER_TOKEN is required (or provide FACTORY_AUTH_HAR_PATH)'); + const cognitoToken = values.FACTORY_COGNITO_TOKEN?.trim() || authInitial?.idToken; + if (!cognitoToken) throw new Error('FACTORY_COGNITO_TOKEN is required (or provide FACTORY_AUTH_HAR_PATH)'); + const defaultConversationPath = env === process.env && process.env.NODE_ENV !== 'test' + ? 'factory-conversations.json' + : null; + return { + apiBase: apiBase.origin, + projectId: required(values, 'FACTORY_PROJECT_ID'), + orgId: required(values, 'FACTORY_ORG_ID'), + bearerToken, + cognitoToken, + cookie: values.FACTORY_COOKIE?.trim() || null, + authInitial, + authSessionPath: values.FACTORY_SESSION_PATH, + conversationPath: values.PROXY_CONVERSATIONS_PATH || defaultConversationPath, + blockDuplicateTools: values.PROXY_BLOCK_DUPLICATE_TOOLS === '1', + zedToken: required(values, 'FACTORY_ZED_TOKEN'), + modelKey, + modelKeys, + modelSettings, + thinkingLevelOverride: env.FACTORY_THINKING_LEVEL || null, + localApiKey: required(values, 'PROXY_API_KEY'), + webClientVersion: values.FACTORY_WEB_CLIENT_VERSION || '0.53.7', + thinkingLevel: values.FACTORY_THINKING_LEVEL || 'medium', + contextWindow: values.FACTORY_CONTEXT_WINDOW || 'default', + generationMode: values.FACTORY_GENERATION_MODE || 'standard', + servingSource: values.FACTORY_SERVING_SOURCE || 'platform', + ready: true, + clientSessionId: randomUUID(), + port, + }; +} + +function sendJson(res, status, value) { + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); + res.end(JSON.stringify(value)); +} + +function sendError(res, error) { + if (res.headersSent) { + res.write(`data: ${JSON.stringify({ error: { message: error.message, type: error.type || 'upstream_error' } })}\n\n`); + res.end(); + return; + } + sendJson(res, error.status || 502, { + error: { message: error.message, type: error.type || 'upstream_error' }, + }); +} + +function authorized(req, key) { + const supplied = req.headers.authorization; + if (typeof supplied !== 'string' || !supplied.startsWith('Bearer ')) return false; + const a = Buffer.from(supplied.slice(7)); + const b = Buffer.from(key); + return a.length === b.length && timingSafeEqual(a, b); +} + +async function readJson(req) { + const chunks = []; + let size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > MAX_REQUEST_BYTES) throw new ProxyError(413, 'Request body is too large'); + chunks.push(chunk); + } + try { + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } catch { + throw new ProxyError(400, 'Invalid JSON request body'); + } +} + +function textContent(content) { + if (typeof content === 'string') return content; + if (content === null || content === undefined) return ''; + if (Array.isArray(content) && content.every(part => part?.type === 'text' && (typeof part.text === 'string' || typeof part.content === 'string'))) { + return content.map(part => part.text ?? part.content ?? '').join('\n'); + } + throw new ProxyError(400, 'Only text message content is supported'); +} + +function normalizeMessages(messages) { + const normalized = messages.map(message => { + if (!['system', 'developer', 'user', 'assistant', 'tool'].includes(message?.role)) { + throw new ProxyError(400, 'Unsupported message role'); + } + const result = { role: message.role }; + if ((message.content === null || message.content === undefined || message.content === '') && message.role === 'assistant' && Array.isArray(message.tool_calls)) { + result.content = null; + } else { + result.content = textContent(message.content); + } + if (message.role === 'assistant' && Array.isArray(message.tool_calls)) { + result.tool_calls = message.tool_calls.map(call => ({ + id: call.id, name: call.function?.name, arguments: call.function?.arguments, + })); + } + if (message.role === 'tool') { + if (typeof message.tool_call_id !== 'string') throw new ProxyError(400, 'Tool result needs tool_call_id'); + result.tool_call_id = message.tool_call_id; + } + return result; + }); + if (!['user', 'tool'].includes(normalized.at(-1)?.role)) { + throw new ProxyError(400, 'The last message must have role user or tool'); + } + return normalized; +} + +export function factoryPrompt(messages, tools, toolChoice, parallelToolCalls) { + if (!tools.length && messages.length === 1) return messages[0].content; + if (tools.length) { + const choice = typeof toolChoice === 'object' + ? `Call only ${toolChoice.function?.name || 'the selected function'}.` + : toolChoice === 'required' ? 'You must call at least one function.' + : 'Call a function only when needed; otherwise answer normally.'; + const prefix = [ + 'You are supplying the next response in an OpenAI Chat Completions conversation.', + 'Return exactly one JSON object, with no Markdown or surrounding text.', + 'To request client-side function execution, return:', + '{"kind":"tool_calls","tool_calls":[{"name":"function_name","arguments":{}}]}', + 'To answer the user, return: {"kind":"message","content":"your answer"}', + 'Use only a listed function name and arguments matching its JSON schema.', + 'Do not execute, simulate, or claim to have executed client-side functions. The client will run them and send results in a later request.', + choice, + parallelToolCalls === false ? 'Return at most one tool call.' : '', + `TOOLS_JSON:\n${JSON.stringify(tools)}`, + ].filter(Boolean).join('\n\n'); + for (const budget of [120_000, 90_000, 60_000, 30_000]) { + const prompt = `${prefix}\n\nMESSAGES_JSON:\n${JSON.stringify(compactToolHistory(messages, budget))}\n\n` + + 'Tool results appear only in MESSAGES_JSON. Reuse available results; if a result was shortened, request only the missing range instead of rereading the same range.'; + if (prompt.length <= MAX_FACTORY_PROMPT_CHARS) return prompt; + } + throw new ProxyError(413, 'Conversation history is too large for the Factory text bridge; start a new Roo task'); + } + for (const budget of [120_000, 90_000, 60_000, 30_000]) { + const prompt = 'Continue this conversation. Messages are JSON with explicit roles. Reply with only the next assistant message.\n\n' + + JSON.stringify(compactToolHistory(messages, budget)); + if (prompt.length <= MAX_FACTORY_PROMPT_CHARS) return prompt; + } + throw new ProxyError(413, 'Conversation history is too large for the Factory text bridge; start a new Roo task'); +} + +function shortenedResult(content, limit) { + if (content.length <= limit) return content; + const marker = `\n[Tool result shortened: ${content.length} characters total; request only a missing range if needed.]\n`; + const available = Math.max(0, limit - marker.length); + const front = Math.ceil(available * 2 / 3); + return content.slice(0, front) + marker + content.slice(-Math.floor(available / 3)); +} + +function compactToolHistory(messages, budget) { + const seen = new Set(); + let remaining = budget; + let largeKept = 0; + return messages.toReversed().map(message => { + if (message.role !== 'tool') return message; + if (seen.has(message.content)) { + return { ...message, content: '[Repeated tool result omitted; identical content appears in a later tool result in MESSAGES_JSON.]' }; + } + if (message.content.length > 4096 && largeKept++ >= 4) { + return { ...message, content: '[Older large tool result omitted to keep context bounded; request a specific range if needed.]' }; + } + const limit = Math.min(message.content.length, 48_000, remaining); + if (remaining < 100) { + return { ...message, content: '[Tool result omitted because context budget is exhausted.]' }; + } + remaining -= limit; + seen.add(message.content); + return { ...message, content: shortenedResult(message.content, limit) }; + }).reverse(); +} + +function canonicalJson(value) { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (value && typeof value === 'object') { + return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`; + } + return JSON.stringify(value); +} + +function toolSignature(name, argumentsValue) { + try { + const args = typeof argumentsValue === 'string' ? JSON.parse(argumentsValue) : argumentsValue; + return `${name}\0${canonicalJson(args)}`; + } catch { return null; } +} + +function completedToolCalls(messages) { + const calls = new Map(); + const completed = []; + for (const message of messages) { + if (message.role === 'assistant') { + for (const call of message.tool_calls || []) calls.set(call.id, call); + } else if (message.role === 'tool') { + const call = calls.get(message.tool_call_id); + if (!call) continue; + const signature = toolSignature(call.name, call.arguments); + if (signature) completed.push({ name: call.name, arguments: call.arguments, + content: message.content, signature }); + } + } + return completed; +} + +const WRITE_TOOLS = new Set([ + 'write_file', 'write_to_file', 'apply_diff', 'apply_patch', 'edit_file', 'search_replace', 'insert_content', +]); + +function callName(call) { + return call?.function?.name || call?.name || ''; +} + +function callArguments(call) { + return call?.function?.arguments ?? call?.arguments; +} + +function argumentPath(argumentsValue) { + let args; + try { args = typeof argumentsValue === 'string' ? JSON.parse(argumentsValue) : argumentsValue; } + catch { return null; } + if (!args || typeof args !== 'object' || Array.isArray(args)) return null; + if (typeof args.path === 'string' && args.path) return args.path; + if (typeof args.file_path === 'string' && args.file_path) return args.file_path; + return null; +} + +function readFileRange(argumentsValue) { + let args; + try { args = typeof argumentsValue === 'string' ? JSON.parse(argumentsValue) : argumentsValue; } + catch { return null; } + const path = argumentPath(args); + if (!path || !Number.isInteger(args?.offset) || !Number.isInteger(args?.limit) || args.limit < 1) return null; + return { path, start: args.offset, end: args.offset + args.limit - 1 }; +} + +function fileEditState(messages) { + const pending = new Map(); + const reads = []; + const writes = []; + messages.forEach((message, index) => { + if (message.role === 'assistant') { + for (const call of message.tool_calls || []) pending.set(call.id, call); + return; + } + if (message.role !== 'tool') return; + const call = pending.get(message.tool_call_id); + if (!call) return; + const name = callName(call); + const args = callArguments(call); + const path = argumentPath(args); + if (WRITE_TOOLS.has(name) && path) writes.push({ path, index }); + if (name === 'read_file' && path) { + reads.push({ + path, + signature: toolSignature(name, args), + range: readFileRange(args), + index, + }); + } + }); + return { reads, writes }; +} + +function readWasEditedAfter(state, path, index) { + return state.writes.some(write => write.path === path && write.index > index); +} + +function isUselessRead(call, state) { + if (callName(call) !== 'read_file') return false; + const args = callArguments(call); + const path = argumentPath(args); + const signature = toolSignature('read_file', args); + const range = readFileRange(args); + if (!path) return false; + return state.reads.some(prior => { + if (prior.path !== path || readWasEditedAfter(state, path, prior.index)) return false; + if (signature && prior.signature === signature) return true; + return Boolean(range && prior.range && prior.range.start <= range.start && prior.range.end >= range.end); + }); +} + +function isBlockedRepeat(call, messages, blockOtherTools) { + const state = fileEditState(messages); + if (isUselessRead(call, state)) return true; + if (!blockOtherTools || callName(call) === 'read_file') return false; + const signature = toolSignature(callName(call), callArguments(call)); + if (!signature) return false; + return completedToolCalls(messages).some(item => item.signature === signature); +} + +function validateCompletion(body, config) { + if (!body || typeof body !== 'object' || Array.isArray(body)) throw new ProxyError(400, 'A JSON object is required'); + if (!config.modelKeys.includes(body.model)) throw new ProxyError(400, `Unknown model: ${body.model}`); + if (!Array.isArray(body.messages) || body.messages.length === 0) throw new ProxyError(400, 'messages must be a nonempty array'); + if (body.stream !== undefined && typeof body.stream !== 'boolean') throw new ProxyError(400, 'stream must be a boolean'); + if (body.functions?.length || body.function_call) throw new ProxyError(400, 'Legacy functions are not supported'); + if (body.tools !== undefined && !Array.isArray(body.tools)) throw new ProxyError(400, 'tools must be an array'); + const tools = (body.tools || []).map(tool => { + const fn = tool?.function; + if (tool?.type !== 'function' || typeof fn?.name !== 'string' || !fn.name || + !fn.parameters || typeof fn.parameters !== 'object') { + throw new ProxyError(400, 'Only named function tools with JSON parameters are supported'); + } + return { name: fn.name, description: fn.description || '', parameters: fn.parameters }; + }); + const choice = body.tool_choice ?? 'auto'; + if (!['auto', 'none', 'required'].includes(choice) && + !(choice?.type === 'function' && typeof choice.function?.name === 'string')) { + throw new ProxyError(400, 'Unsupported tool_choice'); + } + if (choice === 'required' && !tools.length) throw new ProxyError(400, 'tool_choice required needs tools'); + if (typeof choice === 'object' && !tools.some(tool => tool.name === choice.function.name)) { + throw new ProxyError(400, 'tool_choice names an unavailable tool'); + } + if (body.response_format || body.modalities || body.audio || body.stop || (body.n !== undefined && body.n !== 1)) { + throw new ProxyError(400, 'Requested output format or options are not supported by this proxy'); + } + const effort = body.reasoning_effort; + if (effort !== undefined && !['minimal', 'low', 'medium', 'high', 'none'].includes(effort)) { + throw new ProxyError(400, 'reasoning_effort must be one of minimal, low, medium, high, none'); + } + const messages = normalizeMessages(body.messages); + const activeTools = choice === 'none' ? [] : tools; + return { + model: body.model, + messages, + stream: body.stream === true, + tools: activeTools, + toolChoice: choice, + parallelToolCalls: body.parallel_tool_calls !== false, + thinkingLevel: effort === undefined || effort === null || effort === 'none' + ? null + : ({ minimal: 'low', low: 'low', medium: 'medium', high: 'high' })[effort] || 'medium', + }; +} +function invalidToolCall(reason) { + const messages = { + 'malformed tool call JSON': 'Factory returned malformed tool call JSON', + 'truncated tool call': 'Factory response was truncated due to length before the tool call JSON completed', + 'empty tool call list': 'Factory returned no tool calls', + 'parallel tool calls disabled': 'Factory returned parallel tool calls when disabled', + 'unknown tool': 'Factory selected an unknown tool', + 'invalid arguments': 'Factory returned invalid tool arguments', + 'tool call list failed validation': 'Factory returned a tool call list that failed validation', + }; + const error = new ProxyError(502, messages[reason] || 'Factory returned an invalid tool call', 'upstream_error'); + error.repairable = true; + error.reason = reason; + return error; +} + +function toolReplyCandidate(text) { + const trimmed = String(text ?? '').trim().replace(/^\uFEFF/, ''); + const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); + if (fenced) return fenced[1].trim(); + const opened = trimmed.match(/^```(?:json)?\s*([\s\S]*)$/i); + if (opened) return opened[1].trim(); + return trimmed; +} + +// A reply is a tool-call attempt only when the reply itself starts as that JSON +// document. A later example inside ordinary prose does not qualify. +function looksLikeToolCallAttempt(text) { + const candidate = toolReplyCandidate(text); + return /^\{\s*"kind"\s*:\s*"tool_calls"/.test(candidate) + || /^\{\s*"tool_calls"\s*:/.test(candidate); +} + +function jsonTypeName(value) { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + return typeof value; +} + +function matchesDeclaredType(value, type) { + if (type === 'integer') return typeof value === 'number' && Number.isInteger(value); + if (type === 'number') return typeof value === 'number' && Number.isFinite(value); + return jsonTypeName(value) === type; +} + +function argumentsMatchSchema(args, schema) { + if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return true; + const required = Array.isArray(schema.required) ? schema.required : []; + for (const key of required) { + if (typeof key !== 'string' || !Object.hasOwn(args, key)) return false; + } + const properties = schema.properties && typeof schema.properties === 'object' && !Array.isArray(schema.properties) + ? schema.properties : null; + if (schema.additionalProperties === false && properties) { + for (const key of Object.keys(args)) { + if (!Object.hasOwn(properties, key)) return false; + } + } + if (!properties) return true; + for (const [key, spec] of Object.entries(properties)) { + if (!Object.hasOwn(args, key) || !spec || typeof spec !== 'object' || Array.isArray(spec)) continue; + const value = args[key]; + if (typeof spec.type === 'string') { + if (!matchesDeclaredType(value, spec.type)) return false; + } else if (Array.isArray(spec.type) && spec.type.length && + !spec.type.some(type => typeof type === 'string' && matchesDeclaredType(value, type))) { + return false; + } + } + return true; +} + +function extractBalancedJsonObject(text) { + const trimmed = text.trim(); + const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i); + const candidate = fenced ? fenced[1].trim() : trimmed; + try { + const direct = JSON.parse(candidate); + if (direct && typeof direct === 'object' && !Array.isArray(direct)) { + if (direct.kind === 'tool_calls' || direct.kind === 'message' || Array.isArray(direct.tool_calls)) { + return direct; + } + } + } catch { /* try balanced scan below */ } + + for (let i = 0; i < text.length; i++) { + if (text[i] === '{') { + let depth = 0; + let inString = false; + let escaped = false; + for (let j = i; j < text.length; j++) { + const char = text[j]; + if (inString) { + if (escaped) escaped = false; + else if (char === '\\') escaped = true; + else if (char === '"') inString = false; + } else { + if (char === '"') inString = true; + else if (char === '{') depth++; + else if (char === '}') { + depth--; + if (depth === 0) { + const slice = text.slice(i, j + 1); + try { + const parsed = JSON.parse(slice); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + if (parsed.kind === 'tool_calls' || parsed.kind === 'message' || Array.isArray(parsed.tool_calls)) { + return parsed; + } + } + } catch { /* ignore and continue scan */ } + break; + } + } + } + } + } + } + return null; +} + +function parseToolCalls(reply, tools, toolChoice, parallelToolCalls) { + const requested = reply.tool_calls; + if (!Array.isArray(requested) || !requested.length) { + throw invalidToolCall('empty tool call list'); + } + if (!parallelToolCalls && requested.length > 1) { + throw invalidToolCall('parallel tool calls disabled'); + } + const allowed = new Map(tools.map(tool => [tool.name, tool])); + const validated = []; + let sawUnknown = false; + let sawInvalidArgs = false; + for (const call of requested) { + const name = call?.name; + const tool = typeof name === 'string' ? allowed.get(name) : undefined; + if (!tool || (typeof toolChoice === 'object' && name !== toolChoice.function.name)) { + sawUnknown = true; + continue; + } + let args = call.arguments; + if (typeof args === 'string') { + try { args = JSON.parse(args); } + catch { sawInvalidArgs = true; continue; } + } + if (!args || typeof args !== 'object' || Array.isArray(args) || !argumentsMatchSchema(args, tool.parameters)) { + sawInvalidArgs = true; + continue; + } + validated.push({ name, args }); + } + if (sawUnknown || sawInvalidArgs || validated.length !== requested.length) { + const reason = sawUnknown && sawInvalidArgs ? 'tool call list failed validation' + : sawUnknown ? 'unknown tool' + : sawInvalidArgs ? 'invalid arguments' + : 'tool call list failed validation'; + throw invalidToolCall(reason); + } + const calls = validated.map(call => ({ + id: `call_${randomUUID().replaceAll('-', '')}`, + type: 'function', + function: { name: call.name, arguments: JSON.stringify(call.args) }, + })); + return { content: null, toolCalls: calls, finishReason: 'tool_calls' }; +} + +function decodeToolReply(text, tools, toolChoice, parallelToolCalls, finishReason = 'stop') { + // A document that starts as tool_calls must parse as a whole. Do not recover + // a smaller object from broken quotes and do not return that text as a message. + if (looksLikeToolCallAttempt(text)) { + let parsed = null; + try { parsed = JSON.parse(toolReplyCandidate(text)); } + catch { parsed = null; } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || + !(parsed.kind === 'tool_calls' || Array.isArray(parsed.tool_calls))) { + throw invalidToolCall(finishReason === 'length' ? 'truncated tool call' : 'malformed tool call JSON'); + } + return parseToolCalls(parsed, tools, toolChoice, parallelToolCalls); + } + + if (finishReason === 'length') { + const reply = extractBalancedJsonObject(text); + if (reply && (reply.kind === 'tool_calls' || Array.isArray(reply.tool_calls))) { + return parseToolCalls(reply, tools, toolChoice, parallelToolCalls); + } + if (toolChoice === 'required' || typeof toolChoice === 'object') { + throw new ProxyError(502, 'Factory response was truncated due to length before tool call completed', 'upstream_error'); + } + return { content: text, toolCalls: [], finishReason: 'length' }; + } + + const reply = extractBalancedJsonObject(text); + if (!reply) { + if (toolChoice === 'required' || typeof toolChoice === 'object') { + throw new ProxyError(502, 'Factory did not return the required tool call', 'upstream_error'); + } + return { content: text, toolCalls: [], finishReason: 'stop' }; + } + + if (reply.kind === 'tool_calls' || Array.isArray(reply.tool_calls)) { + return parseToolCalls(reply, tools, toolChoice, parallelToolCalls); + } + if (toolChoice === 'required' || typeof toolChoice === 'object') { + throw new ProxyError(502, 'Factory did not return the required tool call', 'upstream_error'); + } + if (typeof reply.content === 'string') return { content: reply.content, toolCalls: [], finishReason: 'stop' }; + return { content: text, toolCalls: [], finishReason: 'stop' }; +} + +function invalidToolCallRepairPrompt(tools, toolChoice, parallelToolCalls) { + const choice = typeof toolChoice === 'object' + ? `Call only ${toolChoice.function?.name || 'the selected function'}.` + : toolChoice === 'required' + ? 'You must call at least one listed function.' + : 'Call a function only when one is needed; otherwise return a message.'; + const names = tools.map(tool => tool.name).filter(name => typeof name === 'string' && name); + return [ + 'RETRY_AFTER_INVALID_TOOL_CALL: The previous assistant reply was not accepted.', + 'It looked like a tool call, but it was not strictly valid JSON, or a tool name or its arguments failed validation.', + 'The previous reply is already in this conversation. Use that context only to decide the next valid response.', + 'Do not execute, simulate, repair, or repeat the invalid command. Do not quote or reconstruct its text.', + 'Return exactly one JSON object and no other text.', + 'To call tools: {"kind":"tool_calls","tool_calls":[{"name":"function_name","arguments":{}}]}', + 'To answer without tools: {"kind":"message","content":"your answer"}', + 'Every element of tool_calls must be valid. Do not return a partial list.', + names.length ? `Allowed functions: ${names.join(', ')}.` : '', + 'Arguments must match the function JSON schema.', + choice, + parallelToolCalls === false ? 'Return at most one tool call.' : '', + ].filter(Boolean).join('\n\n'); +} + +function factoryHeaders(config, auth) { + const headers = { + accept: '*/*', + 'content-type': 'application/json', + authorization: `Bearer ${auth?.accessToken || config.bearerToken}`, + origin: 'https://factory.8090.ai', + 'x-sofa-active-org-id': config.orgId, + 'x-sofa-client-session-id': config.clientSessionId, + 'x-sofa-cognito-id-token': auth?.idToken || config.cognitoToken, + 'x-zed-token': config.zedToken, + 'x-web-client-version': config.webClientVersion, + }; + if (config.cookie) headers.cookie = config.cookie; + return headers; +} + +async function postFactory(config, endpoint, payload, signal, fetchImpl, retried401 = false) { + let auth; + if (config.authSession) { + try { auth = await config.authSession.current(); } + catch (error) { throw new ProxyError(502, error.message, 'authentication_error'); } + } + let response; + try { + response = await fetchImpl( + `${config.apiBase}/v2/project/${encodeURIComponent(config.projectId)}/agents/chat-agent/${endpoint}`, + { method: 'POST', headers: factoryHeaders(config, auth), body: JSON.stringify(payload), signal }, + ); + } catch (error) { + if (signal.aborted && signal.reason === 'timeout') { + throw new ProxyError(504, 'Factory request timed out', 'upstream_error'); + } + if (signal.aborted) throw new ProxyError(499, 'Client disconnected', 'client_cancelled'); + const wrapped = new ProxyError(502, `Factory ${endpoint} request failed: ${error.cause?.code || error.name}`, 'upstream_error'); + wrapped.cause = error; + throw wrapped; + } + if (!response.ok) { + await response.body?.cancel(); + if (response.status === 401 && !retried401 && config.accounts?.length > 1 && rotateAccount(config, fetchImpl)) { + return postFactory(config, endpoint, payload, signal, fetchImpl, true); + } + const hint = response.status === 401 ? ' — токен истёк, вставь свежие креды на дашборде (они обновят аккаунт в пуле)' : ''; + throw new ProxyError(502, `Factory ${endpoint} returned HTTP ${response.status}${hint}`, 'upstream_error'); + } + return response; +} + +const TRANSIENT_NETWORK_CODES = new Set([ + 'ENOTFOUND', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', +]); + +function isTransientFactoryError(error) { + if (error?.status === 502 || error?.status === 503 || error?.status === 504 || error?.status === 429) return true; + const cause = error?.cause; + if (cause instanceof TypeError) return true; + return typeof cause?.code === 'string' && TRANSIENT_NETWORK_CODES.has(cause.code); +} + +// Retry once after 2s when the input POST failed before the message was +// accepted. Never retry 'stream', and never retry an aborted request. +async function postFactoryInput(config, payload, signal, fetchImpl) { + const attempt = () => postFactory(config, 'input', payload, signal, fetchImpl); + try { + return await attempt(); + } catch (error) { + if (signal.aborted || !isTransientFactoryError(error)) throw error; + await new Promise(resolve => setTimeout(resolve, 2000)); + if (signal.aborted) throw error; + return attempt(); + } +} + +async function* sseEvents(body) { + const decoder = new TextDecoder(); + let buffer = ''; + let data = []; + let frameBytes = 0; + for await (const chunk of body) { + buffer += decoder.decode(chunk, { stream: true }); + let newline; + while ((newline = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newline).replace(/\r$/, ''); + buffer = buffer.slice(newline + 1); + if (line === '') { + if (data.length) yield data.join('\n'); + data = []; + frameBytes = 0; + } else if (line.startsWith('data:')) { + frameBytes += Buffer.byteLength(line); + if (frameBytes > MAX_SSE_FRAME_BYTES) throw new ProxyError(502, 'Factory SSE frame is too large', 'upstream_error'); + data.push(line.slice(5).replace(/^ /, '')); + } + } + // A network chunk can contain many complete SSE frames. Limit only the + // unfinished frame, not the whole chunk before its lines are consumed. + if (frameBytes + Buffer.byteLength(buffer) > MAX_SSE_FRAME_BYTES) { + throw new ProxyError(502, 'Factory SSE frame is too large', 'upstream_error'); + } + } + if (buffer.startsWith('data:')) data.push(buffer.slice(5).replace(/^ /, '')); + if (data.length) yield data.join('\n'); +} + +async function* factoryTextEvents(body) { + for await (const raw of sseEvents(body)) { + let event; + try { event = JSON.parse(raw); } catch { continue; } + if (event.type === 'content' && typeof event.delta === 'string') { + yield { type: 'delta', text: event.delta }; + } else if (event.type === 'done') { + yield { type: 'done', finishReason: event.finish_reason === 'length' ? 'length' : 'stop' }; + return; + } else if (event.type === 'error' || event.type === 'turn_error') { + throw new ProxyError(502, 'Factory agent reported an error', 'upstream_error'); + } + } + throw new ProxyError(502, 'Factory stream ended before a done event', 'upstream_error'); +} + +function startStreamKeepAlive(res) { + const timer = setInterval(() => { + if (!res.writableEnded) { + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(': keepalive\n\n'); + } + }, 15_000); + timer.unref(); + return timer; +} + +function chunk(id, created, model, delta, finishReason = null) { + return { + id, object: 'chat.completion.chunk', created, model, + choices: [{ index: 0, delta, finish_reason: finishReason }], + }; +} + +function estimateUsage(promptText, completionText) { + const promptTokens = Math.max(0, Math.ceil(promptText.length / 4)); + const completionTokens = Math.max(0, Math.ceil((completionText || '').length / 4)); + return { + prompt_tokens: promptTokens, + completion_tokens: completionTokens, + total_tokens: promptTokens + completionTokens, + }; +} + +async function openFactoryEvents(config, model, prompt, signal, fetchImpl, conversationId = randomUUID(), clientMessageId = randomUUID(), onInputAccepted = null, requestThinkingLevel = null) { + const input = await postFactoryInput(config, { + action: 'send_message', + conversation_id: conversationId, + content: [{ type: 'text', content: prompt }], + client_state: { + kind: 'platform', current_view: { kind: 'platform', view: 'settings' }, + focused_context: '', attached_artifact_ids: [], timezone: 'UTC', + }, + model: { + type: 'specific', model_key: model, + configuration: { + thinking_level: requestThinkingLevel || config.thinkingLevelOverride || config.modelSettings[model]?.thinkingLevel || config.thinkingLevel, + context_window: config.contextWindow, + generation_mode: config.generationMode, + serving_source: config.servingSource, + }, + }, + client_message_id: clientMessageId, + }, signal, fetchImpl); + let accepted; + try { accepted = await input.json(); } catch { throw new ProxyError(502, 'Factory input returned invalid JSON', 'upstream_error'); } + if (accepted.accepted !== true) throw new ProxyError(502, 'Factory did not accept the message', 'upstream_error'); + if (typeof onInputAccepted === 'function') onInputAccepted(); + + const upstream = await postFactory(config, 'stream', { + conversation_id: conversationId, tail_user_messages: 10, + }, signal, fetchImpl); + if (!upstream.headers.get('content-type')?.toLowerCase().includes('text/event-stream') || !upstream.body) { + await upstream.body?.cancel(); + throw new ProxyError(502, 'Factory did not return an SSE stream', 'upstream_error'); + } + + return factoryTextEvents(upstream.body); +} + +export function extractTaskId(req, body = {}) { + const header = req?.headers; + const taskId = header?.['x-roo-task-id'] || + header?.['x-task-id'] || + header?.['x-session-id'] || + header?.['x-conversation-id'] || + body?.user || + body?.task_id || + body?.metadata?.task_id || + body?.metadata?.sessionId || + null; + return typeof taskId === 'string' && taskId.trim() ? taskId.trim() : null; +} + +export function extractRequestId(req, body = {}) { + const header = req?.headers; + const reqId = header?.['idempotency-key'] || + header?.['x-request-id'] || + header?.['x-client-request-id'] || + header?.['x-retry-id'] || + body?.request_id || + null; + return typeof reqId === 'string' && reqId.trim() ? reqId.trim() : null; +} + +async function handleCompletion(req, res, config, fetchImpl, conversations) { + const body = await readJson(req); + if (config.ready === false) { + throw new ProxyError(503, `Proxy is waiting for Factory credentials. Open http://127.0.0.1:${config.port}/ and paste a HAR or request headers.`, 'not_ready_error'); + } + const { model, messages, stream, tools, toolChoice, parallelToolCalls, thinkingLevel } = validateCompletion(body, config); + const taskId = extractTaskId(req, body); + const requestId = extractRequestId(req, body); + const selection = conversations.select(model, messages, { + taskId, + requestId, + tools, + toolChoice, + parallelToolCalls, + }); + if (selection.decision?.reason === 'new-assistant-mismatch') { + const decision = selection.decision; + console.info(`conversation new-assistant-mismatch prefix=${decision.prefix} incoming=${decision.incomingLength} role=${decision.boundaryRole || '-'} stored=${decision.storedHash || '-'} incomingHash=${decision.incomingHash || '-'} turnToolCalls=${decision.turnToolCalls}`); + } + if (selection.mode === 'in_flight') { + const completion = await selection.inFlightPromise; + sendCompletion(res, completion, stream); + return; + } + if (selection.mode === 'cached') { + sendCompletion(res, selection.session.completion, stream); + return; + } + + let resolveInFlight; + let rejectInFlight; + const inFlightPromise = new Promise((resolve, reject) => { + resolveInFlight = resolve; + rejectInFlight = reject; + }); + inFlightPromise.catch(() => {}); + if (selection.canDedupe) conversations.setInFlight(selection.requestHash, inFlightPromise); + + let session; + let factoryInputAccepted = false; + let isParseError = false; + let lastFactoryText = ''; + let activeAborter = null; + try { + const targetConversationId = selection.session?.conversationId; + await conversations.runExclusive(targetConversationId, async () => { + // Recheck inside the lock ignoring our own in-flight hash/promise + let activeSelection = conversations.select(model, messages, { + taskId, + requestId, + tools, + toolChoice, + parallelToolCalls, + ignoreInFlightPromise: inFlightPromise, + }); + if (activeSelection.mode === 'cached') { + resolveInFlight(activeSelection.completion); + sendCompletion(res, activeSelection.completion, stream); + return; + } + + session = conversations.begin(activeSelection, model, { taskId }); + const incremental = activeSelection.mode === 'continue' + ? (() => { + const cut = Number.isInteger(activeSelection.resumeAt) + ? activeSelection.resumeAt + : activeSelection.session.expected.length; + const newMessages = messages.slice(cut); + if (!newMessages.length) { + return 'Your previous response did not return a valid tool call or JSON object as requested. Return exactly one strictly valid JSON object now. Do not execute, repair, or repeat an invalid command from the previous reply.'; + } + return `Continue the existing Factory conversation. The previous assistant answer is already in this conversation. Only these NEW client messages follow; do not replay previous tool calls or results.\n\n${factoryPrompt(newMessages, tools, toolChoice, parallelToolCalls)}`; + })() + : factoryPrompt(messages, tools, toolChoice, parallelToolCalls); + + const aborter = new AbortController(); + activeAborter = aborter; + const timeout = setTimeout(() => aborter.abort('timeout'), 10 * 60 * 1000); + timeout.unref(); + res.on('close', () => { + if (!res.writableEnded) aborter.abort('client'); + clearTimeout(timeout); + }); + + const id = `chatcmpl-${randomUUID().replaceAll('-', '')}`; + const created = Math.floor(Date.now() / 1000); + + const events = await openFactoryEvents( + config, model, incremental, aborter.signal, fetchImpl, + session.conversationId, session.clientMessageId, + () => { factoryInputAccepted = true; }, + thinkingLevel + ); + + if (tools.length) { + let keepAliveTimer = null; + if (stream) { + keepAliveTimer = setInterval(() => { + if (!res.writableEnded) { + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(': keepalive\n\n'); + } + }, 15_000); + keepAliveTimer.unref(); + } + + let factoryText = ''; + let finishReason = 'stop'; + try { + for await (const event of events) { + if (event.type === 'delta') factoryText += event.text; + if (event.type === 'done') finishReason = event.finishReason; + } + } finally { + if (keepAliveTimer) clearInterval(keepAliveTimer); + } + + let reply; + try { + reply = decodeToolReply(factoryText, tools, toolChoice, parallelToolCalls, finishReason); + } catch (error) { + if (!error.repairable) { + isParseError = true; + lastFactoryText = factoryText; + throw error; + } + let repairKeepAlive = null; + if (stream) repairKeepAlive = startStreamKeepAlive(res); + let retryText = ''; + let retryFinishReason = 'stop'; + try { + const retryEvents = await openFactoryEvents( + config, model, + invalidToolCallRepairPrompt(tools, toolChoice, parallelToolCalls), + aborter.signal, fetchImpl, session.conversationId, + ); + for await (const event of retryEvents) { + if (event.type === 'delta') retryText += event.text; + if (event.type === 'done') retryFinishReason = event.finishReason; + } + } finally { + if (repairKeepAlive) clearInterval(repairKeepAlive); + } + try { + reply = decodeToolReply(retryText, tools, toolChoice, parallelToolCalls, retryFinishReason); + } catch (retryError) { + isParseError = true; + lastFactoryText = retryText; + const reason = retryError.reason || error.reason || 'invalid tool call'; + throw new ProxyError(502, + `Factory tool call was invalid (${reason}) and the correction was also invalid. No tool was executed. Retry the request to ask for a valid tool call.`, + 'upstream_error'); + } + } + + const repeated = call => isBlockedRepeat(call, messages, config.blockDuplicateTools); + const stale = reply.toolCalls.filter(repeated); + const fresh = reply.toolCalls.filter(call => !repeated(call)); + if (stale.length && fresh.length) { + reply = { ...reply, content: null, toolCalls: fresh, finishReason: 'tool_calls' }; + } else if (stale.length) { + const mustCall = toolChoice === 'required' || typeof toolChoice === 'object'; + const nextStep = mustCall + ? 'A tool call is required. Choose an allowed tool call with new arguments that advances the task; do not return a text answer.' + : 'Use the existing result to answer the user, or choose a different tool call that advances the task.'; + const retryPrompt = `RETRY_AFTER_DUPLICATE_TOOL_CALL: You requested a read or function call whose result is already in the client history. Do not read the same file range again unless a later edit changed that file. A different range is allowed. ${nextStep}`; + + if (stream) { + keepAliveTimer = setInterval(() => { + if (!res.writableEnded) { + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(': keepalive\n\n'); + } + }, 15_000); + keepAliveTimer.unref(); + } + + let retryText = ''; + let retryFinishReason = 'stop'; + try { + const retryEvents = await openFactoryEvents( + config, model, retryPrompt, aborter.signal, fetchImpl, + session.conversationId + ); + for await (const event of retryEvents) { + if (event.type === 'delta') retryText += event.text; + if (event.type === 'done') retryFinishReason = event.finishReason; + } + } finally { + if (keepAliveTimer) clearInterval(keepAliveTimer); + } + + try { + reply = decodeToolReply(retryText, tools, toolChoice, parallelToolCalls, retryFinishReason); + } catch (err) { + isParseError = true; + lastFactoryText = retryText; + throw err; + } + + if (reply.toolCalls.some(repeated)) { + throw new ProxyError(502, + 'Factory repeated a completed tool call after retry; no new tool result was produced', + 'upstream_error'); + } + } + + const completionFinishReason = reply.finishReason || (reply.toolCalls.length ? 'tool_calls' : 'stop'); + const responseMessage = reply.toolCalls.length + ? { role: 'assistant', content: null, tool_calls: reply.toolCalls } + : { role: 'assistant', content: reply.content }; + const completion = { + id, object: 'chat.completion', created, model, + choices: [{ index: 0, message: responseMessage, finish_reason: completionFinishReason }], + usage: estimateUsage(incremental, reply.toolCalls.length ? JSON.stringify(reply.toolCalls) : reply.content || ''), + }; + conversations.commit(session, normalizeMessages([responseMessage, { role: 'user', content: '' }])[0], completion); + resolveInFlight(completion); + sendCompletion(res, completion, stream); + return; + } + + if (stream) { + let text = ''; + let finishReason = 'stop'; + let headersSent = false; + const keepAliveTimer = startStreamKeepAlive(res); + try { + for await (const event of events) { + if (event.type === 'delta') { + if (!headersSent) { + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(`data: ${JSON.stringify(chunk(id, created, model, { role: 'assistant', content: '' }))}\n\n`); + headersSent = true; + clearInterval(keepAliveTimer); + } + text += event.text; + res.write(`data: ${JSON.stringify(chunk(id, created, model, { content: event.text }))}\n\n`); + } + if (event.type === 'done') finishReason = event.finishReason; + } + } finally { + clearInterval(keepAliveTimer); + } + const completion = { + id, object: 'chat.completion', created, model, + choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: finishReason }], + usage: estimateUsage(incremental, text), + }; + conversations.commit(session, { role: 'assistant', content: text }, completion); + if (!headersSent) { + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(`data: ${JSON.stringify(chunk(id, created, model, { role: 'assistant', content: '' }))}\n\n`); + headersSent = true; + } + res.write(`data: ${JSON.stringify(chunk(id, created, model, {}, finishReason))}\n\n`); + res.end('data: [DONE]\n\n'); + resolveInFlight(completion); + return; + } + + let text = ''; + let finishReason = 'stop'; + for await (const event of events) { + if (event.type === 'delta') text += event.text; + if (event.type === 'done') finishReason = event.finishReason; + } + const completion = { + id, object: 'chat.completion', created, model, + choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: finishReason }], + usage: estimateUsage(incremental, text), + }; + conversations.commit(session, { role: 'assistant', content: text }, completion); + resolveInFlight(completion); + sendJson(res, 200, completion); + }); + } catch (error) { + if (activeAborter?.signal?.aborted) { + if (activeAborter.signal.reason === 'timeout') { + error = new ProxyError(504, 'Factory request timed out', 'upstream_error'); + } else { + error = new ProxyError(499, 'Client disconnected', 'client_cancelled'); + } + } + if (session) { + if (isParseError) { + conversations.commitParseError(session, lastFactoryText); + } else { + conversations.fail(session, { revertParent: !factoryInputAccepted }); + } + } + rejectInFlight(error); + throw error; + } finally { + if (selection.canDedupe) conversations.clearInFlight(selection.requestHash); + } +} + +function sendCompletion(res, completion, stream) { + if (!stream) { sendJson(res, 200, completion); return; } + const { id, created, model } = completion; + const choice = completion.choices[0]; + if (!res.headersSent) { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + } + res.write(`data: ${JSON.stringify(chunk(id, created, model, { role: 'assistant', content: '' }))}\n\n`); + if (choice.message.tool_calls?.length) { + choice.message.tool_calls.forEach((call, index) => { + res.write(`data: ${JSON.stringify(chunk(id, created, model, { tool_calls: [{ index, ...call }] }))}\n\n`); + }); + } else if (choice.message.content) { + res.write(`data: ${JSON.stringify(chunk(id, created, model, { content: choice.message.content }))}\n\n`); + } + res.write(`data: ${JSON.stringify(chunk(id, created, model, {}, choice.finish_reason))}\n\n`); + res.end('data: [DONE]\n\n'); +} + +function isValidHost(hostHeader, expectedPort) { + if (typeof hostHeader !== 'string') return false; + const host = hostHeader.toLowerCase().trim(); + const allowed = [ + `127.0.0.1:${expectedPort}`, + `localhost:${expectedPort}`, + `[::1]:${expectedPort}`, + '127.0.0.1', + 'localhost', + '[::1]', + ]; + return allowed.includes(host); +} + +// Best-effort live model catalog refresh. Never throws: any failure keeps the +// HAR/env catalog and logs one info line. Called fire-and-forget at startup. +async function refreshModelCatalog(config, fetchImpl) { + try { + const auth = config.authInitial ? await config.authSession?.current() : null; + const response = await fetchImpl( + `${config.apiBase}/v2/project/${encodeURIComponent(config.projectId)}/agents/models`, + { method: 'GET', headers: factoryHeaders(config, auth) }, + ); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const body = await response.json(); + if (!Array.isArray(body?.models) || !body.models.length) throw new Error('no models in response'); + const models = body.models.filter(model => typeof model.key === 'string' && model.key.length > 0); + if (!models.length) throw new Error('no named models in response'); + config.modelKeys = [...new Set([config.modelKey, ...models.map(model => model.key), ...config.modelKeys])]; + config.modelSettings = { + ...config.modelSettings, + ...Object.fromEntries(models.map(model => [model.key, { + thinkingLevel: model.capabilities?.thinking?.choices?.default || model.capabilities?.thinking?.default || model.default_thinking_level || 'medium', + }])), + }; + console.info(`Factory model catalog refreshed: ${models.map(model => model.key).join(', ')}`); + } catch (error) { + console.info(`Factory model catalog refresh failed, keeping existing catalog: ${error?.message || error}`); + } +} + +// --- Live credential reload (HAR drop, dashboard paste, saved file) -------- + +const CREDENTIALS_FILE = 'factory-credentials.json'; + +function envOverlayFromHar(harPath, sessionPath) { + const overlay = { ...settingsFromHar(harPath), FACTORY_HAR_PATH: harPath }; + try { + authFromHar(harPath); // only set when this HAR carries a Cognito refresh token + overlay.FACTORY_AUTH_HAR_PATH = harPath; + overlay.FACTORY_SESSION_PATH = sessionPath; + } catch { /* headers-only HAR: bearer from headers stays valid until it expires */ } + return overlay; +} + +const ACCOUNTS_FILE = 'factory-accounts.json'; + +function accountIdFromParsed(parsed) { + const h = parsed.headers || {}; + const token = h.authorization?.replace(/^Bearer\s+/i, '') || h['x-sofa-cognito-id-token'] || ''; + return token.slice(0, 32) || `acct-${Date.now()}`; +} + +function persistAccounts(config) { + try { + writeFileSync(join(config.watchDir || process.cwd(), ACCOUNTS_FILE), JSON.stringify(config.accounts, null, 2)); + } catch { /* persistence optional */ } +} + +function activateAccount(config, account, fetchImpl) { + config.activeAccountId = account.id; + loadFreshConfig(config, envOverlayFromParsed(account), fetchImpl); +} + +function upsertAccount(config, parsed, fetchImpl) { + config.accounts = config.accounts || []; + const account = { + id: accountIdFromParsed(parsed), + headers: parsed.headers, + projectId: parsed.projectId, + apiBase: parsed.apiBase, + savedAt: Date.now(), + }; + const existing = config.accounts.find(a => a.id === account.id); + if (existing) Object.assign(existing, account); else config.accounts.push(account); + activateAccount(config, existing || account, fetchImpl); + persistAccounts(config); + return config.accounts.length; +} + +function rotateAccount(config, fetchImpl) { + if (!config.accounts?.length) return null; + const idx = config.accounts.findIndex(a => a.id === config.activeAccountId); + const next = config.accounts[(idx + 1) % config.accounts.length]; + if (next.id === config.activeAccountId) return null; + activateAccount(config, next, fetchImpl); + return next; +} + +function applyRuntimeConfig(target, fresh, fetchImpl) { + for (const key of Object.keys(fresh)) { + if (key === 'authSession' || key === 'modelCatalogRefresh' || key === 'conversationPath' || key === 'port') continue; + target[key] = fresh[key]; + } + target.authSession = fresh.authInitial + ? createFactoryAuth(fresh.authInitial, fresh.authSessionPath, fetchImpl) + : null; + target.ready = true; +} + +function loadFreshConfig(config, overlay, fetchImpl) { + const base = config.watchEnv || process.env; + const env = { ...base, ...overlay, + PROXY_CONVERSATIONS_PATH: config.conversationPath, + PROXY_API_KEY: base.PROXY_API_KEY || config.localApiKey }; + const fresh = loadConfig(env); + applyRuntimeConfig(config, fresh, fetchImpl); + config.modelCatalogRefresh = refreshModelCatalog(config, fetchImpl); +} + +function probeHarFiles(config, fetchImpl) { + const files = readdirSync(config.watchDir) + .filter(name => name.endsWith('.har')) + .map(name => join(config.watchDir, name)) + .filter(file => { try { return statSync(file).isFile(); } catch { return false; } }) + .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs); + const sessionPath = config.conversationPath + ? join(dirname(config.conversationPath), 'factory-session.json') + : join(config.watchDir, 'factory-session.json'); + for (const file of files) { + try { + loadFreshConfig(config, envOverlayFromHar(file, sessionPath), fetchImpl); + console.log(`Factory credentials loaded from ${basename(file)}; proxy is live`); + return true; + } catch (error) { + console.info(`Ignoring ${basename(file)}: ${error.message}`); + } + } + return false; +} + +function startHarWatcher(config, server, fetchImpl) { + let timer = null; + const trigger = () => { + clearTimeout(timer); + timer = setTimeout(() => { try { probeHarFiles(config, fetchImpl); } catch { /* keep old config */ } }, 500); + }; + try { + const watcher = watch(config.watchDir, { persistent: false }, (event, filename) => { + if (typeof filename === 'string' && !filename.toLowerCase().endsWith('.har')) return; + trigger(); + }); + watcher.unref?.(); + server.on('close', () => { clearTimeout(timer); watcher.close(); }); + } catch { /* watching unavailable: manual dashboard paste still works */ } +} + +function readSavedCredentials(path) { + try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } +} + +// Writes the proxy provider into local CLI/IDE config files (one click from +// the dashboard). Always backs up the file first; JSON targets are merged, +// YAML targets only created or verified (no risky text surgery). +function installCliTarget(target, { base, apiKey, models }) { + const stamp = '.bak-factory8090'; + const mergeJsonFile = (filePath, mutate) => { + let data = {}; + if (existsSync(filePath)) { + try { data = JSON.parse(readFileSync(filePath, 'utf8')); } + catch (error) { + return { ok: false, message: filePath + ' не парсится как JSON (' + error.message + ') — файл не тронут, вставь блок из карточки «Эндпоинт» вручную' }; + } + copyFileSync(filePath, filePath + stamp); + } else { + mkdirSync(dirname(filePath), { recursive: true }); + } + const note = mutate(data) || 'ok'; + writeFileSync(filePath, JSON.stringify(data, null, 2)); + return { ok: true, message: filePath + ' обновлён' + (existsSync(filePath + stamp) ? ' (бэкап: ' + filePath + stamp + ')' : '') + '. ' + note }; + }; + const vsSettings = join(homedir(), 'AppData', 'Roaming', 'Code', 'User', 'settings.json'); + switch (target) { + case 'opencode': + return mergeJsonFile(join(homedir(), '.config', 'opencode', 'opencode.json'), (data) => { + data.provider = data.provider || {}; + data.provider.factory8090 = { + npm: '@ai-sdk/openai-compatible', + name: 'Factory 8090', + options: { baseURL: base, apiKey }, + models: Object.fromEntries(models.map(m => [m, { name: m, limit: { context: 200000, output: 32000 } }])), + }; + return 'провайдер factory8090 записан; выбери его в OpenCode (Models → Factory 8090)'; + }); + case 'cline': + return mergeJsonFile(vsSettings, (data) => { + data['cline.apiProvider'] = 'openai-compatible'; + data['cline.openAiBaseUrl'] = base; + data['cline.openAiApiKey'] = apiKey; + data['cline.openAiModelId'] = models[0]; + return 'ключи cline.* записаны в settings.json VS Code; перезапусти окно VS Code'; + }); + case 'roo': + return mergeJsonFile(vsSettings, (data) => { + data['roo-cline.apiProvider'] = 'openai-compatible'; + data['roo-cline.openAiBaseUrl'] = base; + data['roo-cline.openAiApiKey'] = apiKey; + data['roo-cline.openAiModelId'] = models[0]; + return 'ключи roo-cline.* записаны в settings.json VS Code; перезапусти окно VS Code'; + }); + case 'continue': { + const filePath = join(homedir(), '.continue', 'config.yaml'); + const providerBlock = '\nproviders:\n factory8090:\n npm: \'@continuedev/openai\'\n apiBase: ' + base + '\n apiKey: ' + apiKey + '\n'; + if (existsSync(filePath)) { + const raw = readFileSync(filePath, 'utf8'); + if (raw.includes('factory8090')) return { ok: true, message: filePath + ' уже содержит провайдер factory8090 — ничего не менял' }; + if (/^providers:/m.test(raw) || /^models:/m.test(raw)) { + copyFileSync(filePath, filePath + stamp); + writeFileSync(filePath, raw + '\n # factory8090 — см. блок в дашборде, вставь в существующую секцию providers/models\n'); + return { ok: false, message: filePath + ' уже имеет секции providers/models — допиши блок из карточки «Эндпоинт» вручную (бэкап сделан)' }; + } + copyFileSync(filePath, filePath + stamp); + writeFileSync(filePath, raw + '\nmodels:\n' + models.map(m => ' - name: ' + m + '\n provider: factory8090\n roles: [chat, edit, apply]\n model: ' + m + '\n apiKey: ' + apiKey + '\n').join('') + providerBlock); + return { ok: true, message: filePath + ' дополнен (бэкап: ' + filePath + stamp + ')' }; + } + mkdirSync(dirname(filePath), { recursive: true }); + writeFileSync(filePath, 'name: Factory 8090 Proxy\nversion: 1.0.0\nschema: v1\nmodels:\n' + models.map(m => ' - name: ' + m + '\n provider: factory8090\n roles: [chat, edit, apply]\n model: ' + m + '\n apiKey: ' + apiKey + '\n').join('') + providerBlock + '\n'); + return { ok: true, message: filePath + ' создан с нуля' }; + } + case 'omp': { + const filePath = join(homedir(), '.omp', 'agent', 'models.yml'); + if (!existsSync(filePath)) return { ok: false, message: filePath + ' не найден — OMP не установлен?' }; + const raw = readFileSync(filePath, 'utf8'); + return raw.includes('hermes-factory8090') + ? { ok: true, message: 'OMP уже подключён (hermes-factory8090 в models.yml); проверь enabledModels в config.yml' } + : { ok: false, message: 'hermes-factory8090 не найден в models.yml — вставь блок из карточки «Эндпоинт» (секция OMP models.yml)' }; + } + default: + throw new Error('Неизвестный target: ' + target); + } +} + +export function createProxyServer(config, fetchImpl = fetch) { + const conversations = createConversationStore(config.conversationPath); + if (config.authInitial && !config.authSession) { + config.authSession = createFactoryAuth(config.authInitial, config.authSessionPath, fetchImpl); + } + if (config.ready !== false) config.modelCatalogRefresh = refreshModelCatalog(config, fetchImpl); + const server = http.createServer(async (req, res) => { + const serverPort = req.socket?.localPort || config.port; + if (!isValidHost(req.headers.host, serverPort)) { + sendJson(res, 403, { error: { message: 'Invalid Host header', type: 'access_denied' } }); + return; + } + const pathname = new URL(req.url || '/', 'http://localhost').pathname; + if (req.method === 'GET' && pathname === '/health') { + sendJson(res, 200, { status: config.ready === false ? 'waiting_for_har' : 'ok' }); + return; + } + if (req.method === 'GET' && (pathname === '/' || pathname === '/index.html')) { + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + res.end(renderDashboardPage({ port: serverPort, apiKey: config.localApiKey, models: config.modelKeys })); + return; + } + if (req.method === 'POST' && pathname === '/dashboard/credentials') { + try { + const body = await readJson(req); + const parsed = parseCredentialPaste(body.text, body.url); + if (parsed.kind === 'har') { + const harPath = join(config.watchDir || process.cwd(), 'dashboard-credentials.har'); + writeFileSync(harPath, JSON.stringify(parsed.har)); + probeHarFiles(config, fetchImpl); + } else { + upsertAccount(config, parsed, fetchImpl); + try { + writeFileSync(join(config.watchDir || process.cwd(), CREDENTIALS_FILE), + JSON.stringify({ headers: parsed.headers, projectId: parsed.projectId, apiBase: parsed.apiBase }, null, 2)); + } catch { /* persistence optional */ } + } + sendJson(res, 200, { + ready: config.ready !== false, + models: config.modelKeys, + accounts: config.accounts?.length || 0, + }); + } catch (error) { + sendJson(res, 400, { error: { message: error.message, type: 'invalid_request_error' } }); + } + return; + } + if (req.method === 'GET' && pathname === '/v1/status') { + const authState = config.authSession?.getState?.(); + sendJson(res, 200, { + ready: config.ready !== false, + models: config.modelKeys, + sessions: conversations.activeLocksCount(), + accounts: config.accounts?.length || (config.ready ? 1 : 0), + activeAccount: config.activeAccountId ? config.activeAccountId.slice(0, 8) : null, + auth: authState?.expiresAt ? { expiresAt: authState.expiresAt } : null, + }); + return; + } + if (!authorized(req, config.localApiKey)) { + sendJson(res, 401, { error: { message: 'Invalid local API key', type: 'authentication_error' } }); + return; + } + + if (req.method === 'POST' && pathname === '/dashboard/install') { + try { + const body = await readJson(req); + const result = installCliTarget(body.target, { + base: `http://127.0.0.1:${serverPort}/v1`, + apiKey: config.localApiKey, + models: (config.modelKeys?.length ? config.modelKeys : ['gpt-5.6-sol']), + }); + sendJson(res, 200, result); + } catch (error) { + sendJson(res, 400, { ok: false, message: error.message }); + } + return; + } + if (req.method === 'GET' && pathname === '/v1/models') { + if (config.ready === false) { sendJson(res, 200, { object: 'list', data: [] }); return; } + sendJson(res, 200, { object: 'list', data: config.modelKeys.map(id => ({ id, object: 'model', created: 0, owned_by: 'factory-8090' })) }); + return; + } + if (req.method === 'POST' && pathname === '/v1/chat/completions') { + try { await handleCompletion(req, res, config, fetchImpl, conversations); } + catch (error) { if (!res.destroyed) sendError(res, error); } + return; + } + sendJson(res, 404, { error: { message: 'Endpoint not found', type: 'invalid_request_error' } }); + }); + if (config.authSession) { + const timer = setInterval(() => { + config.authSession.current().catch(error => console.error(`Factory auth refresh: ${error.message}`)); + }, 60_000); + timer.unref(); + server.on('close', () => clearInterval(timer)); + } + if (config.watchDir) startHarWatcher(config, server, fetchImpl); + return server; +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const scriptDir = dirname(fileURLToPath(import.meta.url)); + const watchDir = process.env.PROXY_HAR_WATCH_DIR || scriptDir; + const watchEnabled = process.env.PROXY_HAR_WATCH !== '0'; + let config = null; + try { + config = loadConfig(); + console.log(`Factory proxy configured from ${config.harPath ? basename(config.harPath) : 'environment'}`); + } catch (error) { + config = { + port: Number(process.env.PROXY_PORT || 18090), + localApiKey: process.env.PROXY_API_KEY || 'local-trial', + conversationPath: process.env.PROXY_CONVERSATIONS_PATH || join(scriptDir, 'factory-conversations.json'), + modelKey: null, + modelKeys: [], + modelSettings: {}, + thinkingLevel: 'medium', + contextWindow: 'default', + generationMode: 'standard', + servingSource: 'platform', + clientSessionId: randomUUID(), + ready: false, + watchEnv: process.env, + watchDir: watchEnabled ? watchDir : null, + }; + console.log(`Factory proxy starting without credentials: ${error.message}`); + } + if (watchEnabled && !config.watchDir) { config.watchEnv = config.watchEnv || process.env; config.watchDir = watchDir; } + const server = createProxyServer(config); + if (!config.ready) { + let accounts = null; + try { accounts = JSON.parse(readFileSync(join(scriptDir, ACCOUNTS_FILE), 'utf8')); } catch { /* no pool file */ } + if (!Array.isArray(accounts) || !accounts.length) { + const saved = readSavedCredentials(join(scriptDir, CREDENTIALS_FILE)); + if (saved?.projectId && saved?.headers) accounts = [saved]; + } + config.accounts = []; + for (const account of (accounts || []).filter(a => a?.projectId && a?.headers)) { + config.accounts.push({ + id: account.id || accountIdFromParsed(account), + headers: account.headers, + projectId: account.projectId, + apiBase: account.apiBase, + savedAt: account.savedAt || Date.now(), + }); + } + if (config.accounts.length) { + try { + activateAccount(config, config.accounts[config.accounts.length - 1], fetch); + persistAccounts(config); + console.log(`Factory credentials restored: ${config.accounts.length} account(s) in pool`); + } catch (error) { console.info(`Saved credentials rejected: ${error.message}`); } + } + if (!config.ready && config.watchDir) probeHarFiles(config, fetch); + } + server.listen(config.port, '127.0.0.1', () => { + const state = config.ready ? 'live' : 'waiting for credentials'; + console.log(`Factory proxy ${state} on http://127.0.0.1:${config.port}/ — dashboard`); + console.log(`OpenAI endpoint: http://127.0.0.1:${config.port}/v1 (API key: ${config.localApiKey})`); + if (!config.ready) console.log('Open the dashboard and paste a HAR export or request headers from factory.8090.ai'); + }); +} diff --git a/server.test.mjs b/server.test.mjs new file mode 100644 index 0000000..0d3c7e5 --- /dev/null +++ b/server.test.mjs @@ -0,0 +1,875 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import os from 'node:os'; +import path from "node:path"; +import { join } from "node:path"; +import { randomUUID } from 'node:crypto'; +import { unlinkSync, mkdtempSync, rmSync, readFileSync } from 'node:fs'; +import { + createProxyServer, + loadConfig, + factoryPrompt, + extractTaskId, + extractRequestId, +} from './server.mjs'; +import { createConversationStore } from './conversations.mjs'; + +const baseEnv = { + FACTORY_API_BASE_URL: 'http://127.0.0.1:9', + FACTORY_PROJECT_ID: 'project-test', + FACTORY_ORG_ID: 'org-test', + FACTORY_BEARER_TOKEN: 'bearer-test', + FACTORY_COGNITO_TOKEN: 'cognito-test', + FACTORY_ZED_TOKEN: 'zed-test', + PROXY_API_KEY: 'local-key-test', + FACTORY_MODEL_KEY: 'test-model', +}; + +// --------------------------------------------------------------------------- +// factoryPrompt +// --------------------------------------------------------------------------- + +test('factoryPrompt returns content for a single message without tools', () => { + assert.equal(factoryPrompt([{ role: 'user', content: 'hi there' }], []), 'hi there'); +}); + +test('factoryPrompt embeds TOOLS_JSON and required tool_choice phrasing', () => { + const prompt = factoryPrompt( + [{ role: 'user', content: 'read foo' }], + [{ type: 'function', function: { name: 'read_file', description: '', parameters: { type: 'object' } } }], + 'required', + true, + ); + assert.match(prompt, /TOOLS_JSON/); + assert.match(prompt, /"name":"read_file"/); + assert.match(prompt, /You must call at least one function/); +}); + +test('factoryPrompt honours a named tool_choice and parallel=false', () => { + const prompt = factoryPrompt( + [{ role: 'user', content: 'read foo' }], + [{ type: 'function', function: { name: 'read_file', description: '', parameters: { type: 'object' } } }], + { type: 'function', function: { name: 'read_file' } }, + false, + ); + assert.match(prompt, /Call only read_file/); + assert.match(prompt, /Return at most one tool call/); +}); + +test('factoryPrompt throws 413 for oversized histories', () => { + assert.throws( + () => factoryPrompt([{ role: 'user', content: 'a' }, { role: 'user', content: 'x'.repeat(300_000) }], []), + error => error?.status === 413 && /too large/.test(error.message), + ); +}); + +// --------------------------------------------------------------------------- +// extractTaskId / extractRequestId +// --------------------------------------------------------------------------- + +test('extractTaskId prefers headers and trims', () => { + assert.equal(extractTaskId({ headers: { 'x-roo-task-id': 't1', 'x-task-id': 't2' } }), 't1'); + assert.equal(extractTaskId({ headers: { 'x-task-id': ' t2 ' } }), 't2'); + assert.equal(extractTaskId({ headers: { 'x-session-id': 's' } }), 's'); + assert.equal(extractTaskId({ headers: { 'x-conversation-id': 'c' } }), 'c'); +}); + +test('extractTaskId falls back to body fields and null', () => { + assert.equal(extractTaskId({}, { user: 'u1' }), 'u1'); + assert.equal(extractTaskId({}, { task_id: 't' }), 't'); + assert.equal(extractTaskId({}, { metadata: { task_id: 'mt' } }), 'mt'); + assert.equal(extractTaskId({}, { metadata: { sessionId: 'ms' } }), 'ms'); + assert.equal(extractTaskId({ headers: {} }, { user: 'u1', task_id: 't' }), 'u1'); + assert.equal(extractTaskId({ headers: {} }, {}), null); + assert.equal(extractTaskId({}, {}), null); +}); + +test('extractRequestId prefers headers and falls back to body', () => { + assert.equal(extractRequestId({ headers: { 'idempotency-key': 'i1', 'x-request-id': 'r1' } }), 'i1'); + assert.equal(extractRequestId({ headers: { 'x-request-id': 'r1', 'x-client-request-id': 'c1' } }), 'r1'); + assert.equal(extractRequestId({ headers: { 'x-retry-id': ' ry ' } }), 'ry'); + assert.equal(extractRequestId({}, { request_id: 'br' }), 'br'); + assert.equal(extractRequestId({ headers: {} }, {}), null); +}); + +// --------------------------------------------------------------------------- +// loadConfig +// --------------------------------------------------------------------------- + +test('loadConfig applies defaults and does not fabricate models', () => { + const config = loadConfig({ ...baseEnv, PROXY_MODEL_IDS: 'extra-1, extra-2' }); + assert.equal(config.apiBase, 'http://127.0.0.1:9'); + assert.equal(config.projectId, 'project-test'); + assert.equal(config.port, 18090); + assert.equal(config.thinkingLevel, 'medium'); + assert.equal(config.webClientVersion, '0.53.7'); + assert.equal(config.conversationPath, null); + assert.equal(config.authInitial, null); + assert.deepEqual(config.modelKeys, ['test-model', 'extra-1', 'extra-2']); + assert.deepEqual(config.modelSettings, {}); +}); + +test('loadConfig rejects invalid PROXY_PORT', () => { + for (const bad of ['0', '-1', '70000', 'abc', '12.5']) { + assert.throws(() => loadConfig({ ...baseEnv, PROXY_PORT: bad }), /PROXY_PORT is invalid/); + } +}); + +test('loadConfig enforces HTTPS except for loopback', () => { + assert.throws(() => loadConfig({ ...baseEnv, FACTORY_API_BASE_URL: 'http://example.com' }), /HTTPS/); + const loopback = loadConfig({ ...baseEnv, FACTORY_API_BASE_URL: 'http://localhost:9' }); + assert.equal(loopback.apiBase, 'http://localhost:9'); + const https = loadConfig({ ...baseEnv, FACTORY_API_BASE_URL: 'https://api.factory.8090.dev' }); + assert.equal(https.apiBase, 'https://api.factory.8090.dev'); + const noUrl = { ...baseEnv }; + delete noUrl.FACTORY_API_BASE_URL; + assert.equal(loadConfig(noUrl).apiBase, 'https://api.factory.8090.dev'); +}); + +test('loadConfig requires FACTORY_MODEL_KEY without a catalog', () => { + const env = { ...baseEnv, PROXY_MODEL_IDS: 'extra-1' }; + delete env.FACTORY_MODEL_KEY; + assert.throws(() => loadConfig(env), /FACTORY_MODEL_KEY is required/); +}); + +test('loadConfig requires the local API key', () => { + const env = { ...baseEnv }; + delete env.PROXY_API_KEY; + assert.throws(() => loadConfig(env), /PROXY_API_KEY is required/); +}); + +// --------------------------------------------------------------------------- +// Integration helpers +// --------------------------------------------------------------------------- + +const doneFrame = 'data: {"type":"done","finish_reason":"stop"}\n\n'; + +function deltaFrame(text) { + return `data: {"type":"content","delta":${JSON.stringify(text)}}\n\n`; +} + +// Fake Factory backend. Startup live-catalog probe gets 500 so the env +// catalog is kept; input is accepted; each stream call consumes one batch of +// SSE frames (strings or functions resolving to strings), FIFO. +function fakeFetch(frameBatches) { + const batches = Array.isArray(frameBatches[0]) ? frameBatches : [frameBatches]; + let batchIndex = 0; + const inputs = []; + const fn = async (url, options) => { + if (url.includes('/agents/models')) { + return new Response(JSON.stringify({ models: [] }), { status: 500 }); + } + if (url.includes('/agents/chat-agent/input')) { + if (options?.body) { try { inputs.push(JSON.parse(options.body)); } catch { inputs.push(options.body); } } + return new Response(JSON.stringify({ accepted: true }), { status: 200, headers: { 'content-type': 'application/json' } }); + } + if (url.includes('/agents/chat-agent/stream')) { + const frames = batches[batchIndex++]; + if (!frames) throw new Error('fakeFetch: no more stream batches'); + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + for (const frame of frames) { + controller.enqueue(encoder.encode(typeof frame === 'function' ? await frame() : frame)); + } + controller.close(); + }, + }); + return new Response(stream, { status: 200, headers: { 'content-type': 'text/event-stream' } }); + } + throw new Error(`fakeFetch: unexpected URL ${url}`); + }; + fn.inputs = inputs; + return fn; +} + +function tempFilePath() { + return path.join(os.tmpdir(), `factory-proxy-test-${randomUUID()}.json`); +} + +function requestRaw(port, method, pathname, { host, auth, extra = {}, body } = {}) { + return new Promise((resolve, reject) => { + const headers = {}; + headers.host = host || `127.0.0.1:${port}`; + if (auth) headers.authorization = `Bearer ${auth}`; + Object.assign(headers, extra); + if (body !== undefined) headers['content-type'] = 'application/json'; + const req = http.request({ host: '127.0.0.1', port, method, path: pathname, headers }, res => { + const chunks = []; + res.on('data', chunk => chunks.push(chunk)); + res.on('end', () => { + const text = Buffer.concat(chunks).toString('utf8'); + let json = null; + try { json = JSON.parse(text); } catch { /* body may be SSE */ } + resolve({ status: res.statusCode, headers: res.headers, text, json }); + }); + }); + req.on('error', reject); + if (body !== undefined) req.write(JSON.stringify(body)); + req.end(); + }); +} + +async function withServer(frames, fn, env = {}) { + const fetchImpl = fakeFetch(frames); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath(), ...env }); + const server = createProxyServer(config, fetchImpl); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }); + const port = server.address().port; + try { + return await fn(config, port, fetchImpl); + } finally { + await new Promise((resolve, reject) => { + server.close(error => (error ? reject(error) : resolve())); + }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +} + +function completionBody(overrides = {}) { + return { + model: 'test-model', + messages: [{ role: 'user', content: 'Hello' }], + ...overrides, + }; +} + +// --------------------------------------------------------------------------- +// Integration: chat completions +// --------------------------------------------------------------------------- + +test('non-stream completion returns content, finish_reason and usage', async () => { + const frames = [deltaFrame('Hello world'), doneFrame]; + await withServer(frames, async (config, port) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody(), + }); + assert.equal(res.status, 200); + assert.equal(res.json.choices[0].message.content, 'Hello world'); + assert.equal(res.json.choices[0].finish_reason, 'stop'); + assert.ok(res.json.usage, 'completion must include usage'); + assert.ok(Number.isInteger(res.json.usage.prompt_tokens) && res.json.usage.prompt_tokens >= 0); + assert.ok(Number.isInteger(res.json.usage.completion_tokens) && res.json.usage.completion_tokens >= 0); + assert.equal(res.json.usage.total_tokens, res.json.usage.prompt_tokens + res.json.usage.completion_tokens); + assert.ok(res.json.usage.total_tokens > 0); + }); +}); + +test('streaming completion emits role, content and done chunks', async () => { + const frames = [deltaFrame('Hello '), deltaFrame('world'), doneFrame]; + await withServer(frames, async (config, port) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ stream: true }), + }); + assert.equal(res.status, 200); + assert.match(res.headers['content-type'] || '', /text\/event-stream/); + const dataFrames = res.text + .split('\n\n') + .map(line => line.trim()) + .filter(line => line.startsWith('data: ')) + .map(line => line.slice(6)); + assert.equal(dataFrames.at(-1), '[DONE]'); + const chunks = dataFrames.slice(0, -1).map(frame => JSON.parse(frame)); + assert.equal(chunks[0].choices[0].delta.role, 'assistant'); + const content = chunks.map(chunk => chunk.choices[0].delta.content || '').join(''); + assert.equal(content, 'Hello world'); + assert.equal(chunks.at(-1).choices[0].finish_reason, 'stop'); + }); +}); + +test('tool call flow surfaces tool_calls, finish_reason and usage', async () => { + const toolDoc = '{"kind":"tool_calls","tool_calls":[{"name":"read_file","arguments":{"path":"foo.txt"}}]}'; + const half = Math.ceil(toolDoc.length / 2); + const frames = [ + deltaFrame(toolDoc.slice(0, half)), + deltaFrame(toolDoc.slice(half)), + doneFrame, + ]; + await withServer(frames, async (config, port) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ + messages: [{ role: 'user', content: 'read foo' }], + tools: [{ + type: 'function', + function: { + name: 'read_file', + description: '', + parameters: { type: 'object', properties: { path: { type: 'string' } }, required: ['path'] }, + }, + }], + }), + }); + assert.equal(res.status, 200); + const choice = res.json.choices[0]; + assert.equal(choice.finish_reason, 'tool_calls'); + assert.equal(choice.message.tool_calls[0].function.name, 'read_file'); + assert.equal(JSON.parse(choice.message.tool_calls[0].function.arguments).path, 'foo.txt'); + assert.ok(res.json.usage && res.json.usage.total_tokens > 0); + }); +}); + +// --------------------------------------------------------------------------- +// Integration: admin endpoints and auth +// --------------------------------------------------------------------------- + +test('GET /v1/models lists the configured models', async () => { + await withServer([], async (config, port) => { + const res = await requestRaw(port, 'GET', '/v1/models', { auth: config.localApiKey }); + assert.equal(res.status, 200); + assert.deepEqual(res.json.data.map(item => item.id), config.modelKeys); + }); +}); + +test('GET /v1/status reports models, active sessions and auth state', async () => { + const delayedDone = () => new Promise(resolve => setTimeout(() => resolve(doneFrame), 800)); + await withServer([], async (config, port) => { + const before = await requestRaw(port, 'GET', '/v1/status', { auth: config.localApiKey }); + assert.equal(before.status, 200); + assert.deepEqual(before.json.models, config.modelKeys); + assert.equal(before.json.sessions, 0); + assert.equal(before.json.auth, null); + }); + // A continuation of a finished turn holds the conversation lock while the + // upstream stream is open, so sessions must count it as active. + await withServer([[deltaFrame('ok'), doneFrame], [deltaFrame('x'), delayedDone]], async (config, port) => { + const first = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + extra: { 'x-roo-task-id': 'test-task' }, + body: completionBody(), + }); + assert.equal(first.status, 200); + const pending = requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + extra: { 'x-roo-task-id': 'test-task' }, + body: completionBody({ + messages: [ + { role: 'user', content: 'Hello' }, + { role: 'assistant', content: 'ok' }, + { role: 'user', content: 'more' }, + ], + }), + }); + await new Promise(resolve => setTimeout(resolve, 150)); + const during = await requestRaw(port, 'GET', '/v1/status', { auth: config.localApiKey }); + assert.equal(during.json.sessions, 1); + await pending; + const after = await requestRaw(port, 'GET', '/v1/status', { auth: config.localApiKey }); + assert.equal(after.json.sessions, 0); + }); +}); + +test('wrong or missing API key is rejected with 401', async () => { + await withServer([], async (config, port) => { + const chat = await requestRaw(port, 'POST', '/v1/chat/completions', { auth: 'wrong-key', body: completionBody() }); + assert.equal(chat.status, 401); + const models = await requestRaw(port, 'GET', '/v1/models', { auth: 'wrong-key' }); + assert.equal(models.status, 401); + const noKey = await requestRaw(port, 'GET', '/v1/models', {}); + assert.equal(noKey.status, 401); + }); +}); + +test('/health is open and invalid Host headers are rejected', async () => { + await withServer([], async (config, port) => { + const health = await requestRaw(port, 'GET', '/health', {}); + assert.equal(health.status, 200); + assert.deepEqual(health.json, { status: 'ok' }); + const spoofed = await requestRaw(port, 'GET', '/health', { host: 'evil.example.com' }); + assert.equal(spoofed.status, 403); + const spoofedChat = await requestRaw(port, 'POST', '/v1/chat/completions', { + host: 'evil.example.com', + auth: config.localApiKey, + body: completionBody(), + }); + assert.equal(spoofedChat.status, 403); + }); +}); + +// --------------------------------------------------------------------------- +// createConversationStore +// --------------------------------------------------------------------------- + +test('select returns mode new for an unknown request', () => { + const store = createConversationStore(null); + const sel = store.select('test-model', [{ role: 'user', content: 'hi' }], { taskId: 'task-1' }); + assert.equal(sel.mode, 'new'); + assert.equal(sel.session, null); +}); + +test('begin + commit then extended messages continue with resumeAt', () => { + const store = createConversationStore(null); + const messages = [{ role: 'user', content: 'hi' }]; + const first = store.select('test-model', messages, { taskId: 'task-1' }); + const session = store.begin(first, 'test-model', { taskId: 'task-1' }); + const response = { role: 'assistant', content: 'hello there' }; + store.commit(session, response, { + id: 'x', object: 'chat.completion', created: 0, model: 'test-model', + choices: [{ index: 0, message: response, finish_reason: 'stop' }], + }); + const second = store.select('test-model', [...messages, response, { role: 'user', content: 'more' }], { taskId: 'task-1' }); + assert.equal(second.mode, 'continue'); + assert.equal(second.resumeAt, messages.length + 1); +}); + +test('continued when the boundary carries an appended tool result', () => { + const store = createConversationStore(null); + const call = { id: 'call_1', type: 'function', function: { name: 'read_file', arguments: '{"path":"a.txt"}' } }; + const messages = [{ role: 'user', content: 'read a.txt' }]; + const first = store.select('test-model', messages, { taskId: 'task-1' }); + const session = store.begin(first, 'test-model', { taskId: 'task-1' }); + const assistant = { role: 'assistant', content: null, tool_calls: [call] }; + store.commit(session, assistant, { + id: 'x', object: 'chat.completion', created: 0, model: 'test-model', + choices: [{ index: 0, message: assistant, finish_reason: 'tool_calls' }], + }); + const extended = [ + ...messages, + assistant, + { role: 'tool', tool_call_id: 'call_1', content: 'file body' }, + { role: 'user', content: 'thanks' }, + ]; + const second = store.select('test-model', extended, { taskId: 'task-1' }); + assert.equal(second.mode, 'continue'); + assert.equal(second.resumeAt, messages.length + 1); +}); + +test('byte-identical request after commit replays the cached completion', () => { + const store = createConversationStore(null); + const messages = [{ role: 'user', content: 'hi' }]; + const first = store.select('test-model', messages, { taskId: 'task-1' }); + const session = store.begin(first, 'test-model', { taskId: 'task-1' }); + const response = { role: 'assistant', content: 'hello' }; + const completion = { + id: 'x', object: 'chat.completion', created: 0, model: 'test-model', + choices: [{ index: 0, message: response, finish_reason: 'stop' }], + }; + store.commit(session, response, completion); + const replay = store.select('test-model', messages, { taskId: 'task-1' }); + assert.equal(replay.mode, 'cached'); + assert.equal(replay.completion.id, 'x'); +}); + +test('commitParseError makes a same-body retry continue', () => { + const store = createConversationStore(null); + const messages = [{ role: 'user', content: 'hi' }]; + const first = store.select('test-model', messages, { taskId: 'task-1' }); + const session = store.begin(first, 'test-model', { taskId: 'task-1' }); + store.commitParseError(session, 'broken json'); + const retry = store.select('test-model', messages, { taskId: 'task-1' }); + assert.equal(retry.mode, 'continue'); + assert.equal(retry.session.id, session.id); +}); + +test('sessions persist and resume after reload from disk', () => { + const filePath = tempFilePath(); + try { + const messages = [{ role: 'user', content: 'hello disk' }]; + const storeA = createConversationStore(filePath); + const first = storeA.select('test-model', messages, { taskId: 'task-1' }); + const session = storeA.begin(first, 'test-model', { taskId: 'task-1' }); + const response = { role: 'assistant', content: 'persisted' }; + storeA.commit(session, response, { + id: 'x', object: 'chat.completion', created: 0, model: 'test-model', + choices: [{ index: 0, message: response, finish_reason: 'stop' }], + }); + const storeB = createConversationStore(filePath); + assert.equal(storeB.getSessions().length, 1); + const second = storeB.select('test-model', [...messages, response, { role: 'user', content: 'again' }], { taskId: 'task-1' }); + assert.equal(second.mode, 'continue'); + } finally { + try { unlinkSync(filePath); } catch { /* ignore */ } + } +}); + +// --------------------------------------------------------------------------- +// reasoning_effort passthrough +// --------------------------------------------------------------------------- + +test('reasoning_effort high reaches Factory as thinking_level high', async () => { + await withServer([deltaFrame('ok'), doneFrame], async (config, port, fetchImpl) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ reasoning_effort: 'high' }), + }); + assert.equal(res.status, 200); + const input = fetchImpl.inputs.at(-1); + assert.equal(input?.model?.configuration?.thinking_level, 'high'); + }); +}); + +test('reasoning_effort minimal maps to thinking_level low', async () => { + await withServer([deltaFrame('ok'), doneFrame], async (config, port, fetchImpl) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ reasoning_effort: 'minimal' }), + }); + assert.equal(res.status, 200); + assert.equal(fetchImpl.inputs.at(-1)?.model?.configuration?.thinking_level, 'low'); + }); +}); + +test('invalid reasoning_effort is rejected with 400', async () => { + await withServer([deltaFrame('ok'), doneFrame], async (config, port) => { + const res = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ reasoning_effort: 'extreme' }), + }); + assert.equal(res.status, 400); + assert.match(res.json.error.message, /reasoning_effort/); + }); +}); + +// --------------------------------------------------------------------------- +// degraded mode (waiting for credentials) +// --------------------------------------------------------------------------- + +test('degraded server reports waiting_for_har and 503s completions', async () => { + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + const server = createProxyServer(config, fakeFetch([])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const health = await requestRaw(port, 'GET', '/health'); + assert.equal(health.status, 200); + assert.equal(health.json.status, 'waiting_for_har'); + const models = await requestRaw(port, 'GET', '/v1/models', { auth: config.localApiKey }); + assert.deepEqual(models.json.data, []); + const status = await requestRaw(port, 'GET', '/v1/status'); + assert.equal(status.json.ready, false); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody(), + }); + assert.equal(completion.status, 503); + assert.match(completion.json.error.message, /waiting for Factory credentials/); + } finally { + await new Promise(resolve => server.close(resolve)); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +// --------------------------------------------------------------------------- +// dashboard credential paste (hot-reload path) +// --------------------------------------------------------------------------- + +const harFixture = () => ({ + log: { entries: [{ + request: { + method: 'POST', + url: 'http://127.0.0.1:9/v2/project/project-test/agents/chat-agent/input', + headers: [ + { name: 'authorization', value: 'Bearer bearer-har' }, + { name: 'x-sofa-cognito-id-token', value: 'cognito-har' }, + { name: 'x-zed-token', value: 'zed-har' }, + { name: 'x-sofa-active-org-id', value: 'org-har' }, + ], + postData: { text: '{"model":{"model_key":"test-model"}}' }, + }, + response: { content: { text: '' } }, + }] }, +}); + +test('dashboard HAR paste activates the proxy live', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-har-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([deltaFrame('live'), doneFrame])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { text: JSON.stringify(harFixture()) }, + }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + const health = await requestRaw(port, 'GET', '/health'); + assert.equal(health.json.status, 'ok'); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody(), + }); + assert.equal(completion.status, 200); + assert.equal(completion.json.choices[0].message.content, 'live'); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('dashboard header paste activates the proxy live', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-cred-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([deltaFrame('live'), doneFrame])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { + text: 'authorization: Bearer bearer-har\nx-sofa-cognito-id-token: cognito-har\nx-zed-token: zed-har\nx-sofa-active-org-id: org-har', + url: 'http://127.0.0.1:9/v2/project/project-test/agents/chat-agent/input', + }, + }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ model: 'gpt-5.6-sol' }), + }); + assert.equal(completion.status, 200); + assert.equal(completion.json.choices[0].message.content, 'live'); + const saved = readFileSync(join(watchDir, 'factory-credentials.json'), 'utf8'); + assert.equal(JSON.parse(saved).projectId, 'project-test'); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('dashboard paste with URL as first line and headers in one blob activates the proxy', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-urlblob-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([deltaFrame('live'), doneFrame])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { + text: 'http://127.0.0.1:9/v2/project/project-urlblob/agents/chat-agent/input\nauthorization: Bearer bearer-har\nx-sofa-cognito-id-token: cognito-har\nx-zed-token: zed-har\nx-sofa-active-org-id: org-har', + }, + }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ model: 'gpt-5.6-sol' }), + }); + assert.equal(completion.status, 200); + assert.equal(completion.json.choices[0].message.content, 'live'); + const saved = readFileSync(join(watchDir, 'factory-credentials.json'), 'utf8'); + const parsed = JSON.parse(saved); + assert.equal(parsed.projectId, 'project-urlblob'); + assert.ok(parsed.headers.authorization === 'Bearer bearer-har'); + assert.ok(!('https' in parsed.headers), 'URL line must not become a junk header'); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('cognito-only paste activates the proxy without PROXY_API_KEY in watchEnv', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-cognitoonly-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + const { PROXY_API_KEY: _omit, ...bareEnv } = { ...baseEnv }; + config.watchEnv = bareEnv; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([deltaFrame('live'), doneFrame])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { + text: 'http://127.0.0.1:9/v2/project/project-cognito/agents/chat-agent/input\nx-sofa-cognito-id-token: cognito-har\nx-zed-token: zed-har\nx-sofa-active-org-id: org-har', + }, + }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + assert.equal(config.bearerToken, 'cognito-har'); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ model: 'gpt-5.6-sol' }), + }); + assert.equal(completion.status, 200); + assert.equal(completion.json.choices[0].message.content, 'live'); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('re-pasting the same account updates it instead of duplicating', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-dedupe-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([deltaFrame('live'), doneFrame])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + const text = 'http://127.0.0.1:9/v2/project/project-pool/agents/chat-agent/input\nauthorization: Bearer ' + 'a'.repeat(40) + '\nx-sofa-cognito-id-token: cognito-pool\nx-zed-token: zed-pool\nx-sofa-active-org-id: org-pool'; + try { + for (let i = 0; i < 2; i++) { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { body: { text } }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + } + const status = await requestRaw(port, 'GET', '/v1/status'); + assert.equal(status.json.accounts, 1); + const pool = JSON.parse(readFileSync(join(watchDir, 'factory-accounts.json'), 'utf8')); + assert.equal(pool.length, 1); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('401 from Factory rotates to the next pooled account and succeeds', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-rotate-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const base = fakeFetch([deltaFrame('rotated'), doneFrame]); + const seenAuth = []; + let inputCalls = 0; + const fetchImpl = async (url, options) => { + if (url.includes('/agents/chat-agent/input')) { + inputCalls += 1; + seenAuth.push(options.headers.authorization); + if (inputCalls === 1) { + return new Response(JSON.stringify({ error: 'unauthorized' }), { status: 401 }); + } + } + return base(url, options); + }; + const server = createProxyServer(config, fetchImpl); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + const headers = token => 'x-sofa-cognito-id-token: cognito-' + token + '\nx-zed-token: zed-pool\nx-sofa-active-org-id: org-pool'; + try { + await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { text: 'http://127.0.0.1:9/v2/project/project-pool/agents/chat-agent/input\nauthorization: Bearer ' + 'a'.repeat(40) + '\n' + headers('aaa') }, + }); + await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { text: 'http://127.0.0.1:9/v2/project/project-pool/agents/chat-agent/input\nauthorization: Bearer ' + 'b'.repeat(40) + '\n' + headers('bbb') }, + }); + const status = await requestRaw(port, 'GET', '/v1/status'); + assert.equal(status.json.accounts, 2); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ model: 'gpt-5.6-sol' }), + }); + assert.equal(completion.status, 200); + assert.equal(completion.json.choices[0].message.content, 'rotated'); + assert.equal(seenAuth.length, 2); + assert.equal(seenAuth[0], 'Bearer ' + 'b'.repeat(40)); + assert.equal(seenAuth[1], 'Bearer ' + 'a'.repeat(40)); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('dashboard paste with garbage returns 400', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-bad-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { text: 'not json or headers' }, + }); + assert.equal(res.status, 400); + assert.ok(res.json.error.message.length > 0); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('cookie-export paste without auth tokens returns a clear 400', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-cookie-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const server = createProxyServer(config, fakeFetch([])); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { + text: JSON.stringify([{ domain: '.8090.ai', name: 'ph_phc_x_posthog', value: '%7B%22distinct_id%22%3A%22abc%22%7D' }]), + url: 'https://factory.8090.ai/project/c35c2c08-af19-465a-863e-c969e36e5543', + }, + }); + assert.equal(res.status, 400); + assert.match(res.json.error.message, /authorization/); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('header paste with cookie line forwards cookie to Factory', async () => { + const watchDir = mkdtempSync(join(os.tmpdir(), 'factory-proxy-cookie-h-')); + const config = loadConfig({ ...baseEnv, PROXY_CONVERSATIONS_PATH: tempFilePath() }); + config.ready = false; + config.watchEnv = { ...baseEnv }; + config.watchDir = watchDir; + const seenHeaders = []; + const base = fakeFetch([deltaFrame('live'), doneFrame]); + const fetchImpl = (url, init) => { seenHeaders.push(init?.headers || {}); return base(url, init); }; + const server = createProxyServer(config, fetchImpl); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + try { + const res = await requestRaw(port, 'POST', '/dashboard/credentials', { + body: { + text: 'authorization: Bearer tok-1\nx-sofa-cognito-id-token: cog-1\nx-zed-token: zed-1\nx-sofa-active-org-id: org-1\ncookie: ph=analytics; session=xyz', + url: `http://127.0.0.1:9/v2/project/${baseEnv.FACTORY_PROJECT_ID}/agents/chat-agent/input`, + }, + }); + assert.equal(res.status, 200); + assert.equal(res.json.ready, true); + const completion = await requestRaw(port, 'POST', '/v1/chat/completions', { + auth: config.localApiKey, + body: completionBody({ model: 'gpt-5.6-sol' }), + }); + assert.equal(completion.status, 200); + assert.ok(seenHeaders.some(h => h.cookie === 'ph=analytics; session=xyz'), + 'cookie header should be forwarded to Factory'); + } finally { + await new Promise(resolve => server.close(resolve)); + rmSync(watchDir, { recursive: true, force: true }); + try { unlinkSync(config.conversationPath); } catch { /* ignore */ } + } +}); + +test('dashboard page renders with endpoint snippets', async () => { + await withServer([], async (config, port) => { + const res = await requestRaw(port, 'GET', '/'); + assert.equal(res.status, 200); + assert.match(res.headers['content-type'], /text\/html/); + assert.match(res.text, /Factory 8090 Proxy/); + assert.match(res.text, /chat\/completions/); + }); +}); \ No newline at end of file diff --git a/skill/SKILL.md b/skill/SKILL.md new file mode 100644 index 0000000..5c28bbf --- /dev/null +++ b/skill/SKILL.md @@ -0,0 +1,49 @@ +--- +name: factory-8090-proxy +description: Factory 8090 web2api proxy — запуск, дашборд 18090, вставка HAR/headers кредов, reasoning_effort, OMP integration. Триггеры: factory, 8090, factory proxy, factory.8090.ai, hermes-factory8090. +--- + +# Factory 8090 Proxy + +Локальный OpenAI-совместимый шлюз для factory.8090.ai. Каталог: `C:/Users/User/tmp/factory_proxy/` (репо: gbonnet65923/factory-8090-proxy). Zero-dep Node 22 ESM, stdlib only. + +## Запуск + +``` +cd C:/Users/User/tmp/factory_proxy && node server.mjs +``` + +Или `Start-Proxy.bat`. Порт **18090**, listen 127.0.0.1 только. + +## Креды + +Без кредов прокси стартует degraded (`/health` → `waiting_for_har`, completions → 503). Ждёт: + +1. **Дашборд** `http://127.0.0.1:18090/` — вставить HAR JSON (DevTools → Network → Save all as HAR **with sensitive data**) или headers запроса к `api.factory.8090.dev` (authorization/x-sofa-cognito-id-token/x-zed-token/x-sofa-active-org-id) + URL с project id. Headers-режим персистится в `factory-credentials.json`. +2. **Дроп `.har`-файла** в каталог скрипта — hot-reload, без рестарта (fs.watch, debounce 500ms). + +Логи: `Factory credentials loaded from X; proxy is live`. + +## Эндпоинты + +- `POST /v1/chat/completions` — Bearer `local-trial` (PROXY_API_KEY), stream + tools. +- `GET /v1/models`, `GET /v1/status` (ready/models/sessions/auth), `GET /health`. +- `GET /` — дашборд (playground, reasoning_effort select, сниппеты curl/Roo/OMP). + +## Reasoning + +`reasoning_effort` (minimal/low/medium/high/none) → `thinking_level` Factory per-request: minimal→low, none→null (дефолт), остальные напрямую. OMP: суффикс `:high` к имени модели. + +## OMP + +`~/.omp/agent/models.yml` → провайдер `hermes-factory8090` (baseUrl `http://127.0.0.1:18090/v1`, apiKey `local-trial`, модели `gpt-5.6-sol` + `opus-5.5`, reasoning: true). config.yml: enabledModels + modelProviderOrder. + +## Тесты + +`node --test` в каталоге (33 теста, без сети). Смоук: `/health` → `{"status":"ok"}` после вставки кредов. + +## Границы + +- Секреты (`.har`, `factory-session.json`, `factory-conversations.json`, `factory-credentials.json`) не в репо — в `.gitignore`. +- Пуш репо — через `C:/Users/User/tmp/ghprobe/apipush.mjs` (REST Contents API, git-remote-https отсутствует). +- catalog refresh при degraded-старте пропускается; после live-перехода подтягивается с сервера.