recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
+14
@@ -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
|
||||
@@ -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
|
||||
|
||||
Это тот случай, когда «просто попробовать» занимает меньше времени, чем прочитать этот пост. Кто заведёт — отпишитесь, как зашли 🫡
|
||||
@@ -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. Проект для личного использования.
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
@@ -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<completion>
|
||||
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],
|
||||
};
|
||||
}
|
||||
+444
@@ -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 => '<code>' + m + '</code>').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 => '<option' + (m === current ? ' selected' : '') + '>' + m + '</option>');
|
||||
} 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 `<!doctype html>
|
||||
<html lang="ru"><head><meta charset="utf-8">
|
||||
<title>Factory 8090 Proxy</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>${CSS}</style></head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="logo">F8</div>
|
||||
<div>
|
||||
<h1>Factory <span>8090</span> Proxy</h1>
|
||||
<div class="sub">Локальный OpenAI-совместимый шлюз для factory.8090.ai · <span id="badge" class="badge warn">…</span></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="card" id="readycard">
|
||||
<h2>Статус</h2>
|
||||
<div class="row">
|
||||
<div class="stat"><b id="mcount">0</b>моделей</div>
|
||||
<div class="stat"><b id="acount">0</b>аккаунтов</div>
|
||||
<div class="stat"><b id="sessions">0</b>активных сессий</div>
|
||||
<div class="stat"><b id="authexp">—</b>токен истекает</div>
|
||||
</div>
|
||||
<div class="models" id="models"></div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="credcard">
|
||||
<h2>Креды</h2>
|
||||
<p class="sub">Прокси стартует без кредов и ждёт их здесь. Вставь — подхватит на лету, без рестарта.</p>
|
||||
|
||||
<details>
|
||||
<summary><b>Способ 1 — HAR-файл</b> (рекомендуется, куки и токены внутри)</summary>
|
||||
<ol class="sub">
|
||||
<li>Открой <b>factory.8090.ai</b> в Chrome и войди в аккаунт.</li>
|
||||
<li>F12 → вкладка <b>Network</b> (Сеть). Отправь боту любое сообщение.</li>
|
||||
<li>Клик правой кнопкой по любому запросу в списке → <b>«Save all as HAR with sensitive data»</b> (Сохранить всё как HAR с конфиденциальными данными).<br>Важно: нужен именно вариант <i>with sensitive data</i> — обычный HAR не содержит токенов.</li>
|
||||
<li>Открой сохранённый .har файл блокнотом → Ctrl+A, Ctrl+C.</li>
|
||||
<li>Вставь всё в поле ниже → <b>Применить</b>. URL не нужен.</li>
|
||||
</ol>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Способ 2 — Заголовки запроса + куки</b> (вручную)</summary>
|
||||
<ol class="sub">
|
||||
<li>Открой <b>factory.8090.ai</b> в Chrome и войди в аккаунт.</li>
|
||||
<li>F12 → вкладка <b>Network</b> → отправь боту любое сообщение.</li>
|
||||
<li>Найди запрос <b>POST …/agents/chat-agent/input</b> → клик по нему → вкладка <b>Headers</b> (Заголовки).</li>
|
||||
<li>В секции <b>Request Headers</b> скопируй <b>все строки</b> — включая строку <b>cookie: …</b> (куки идут сюда же, отдельного поля не нужно).<br>Проще всего: правый клик по списку заголовков → «Copy value»/выделить всё и скопировать.</li>
|
||||
<li>Вставь в поле ниже. Обязательно нужны строки <b>authorization: Bearer …</b> или <b>x-sofa-cognito-id-token: …</b>.</li>
|
||||
<li>В поле <b>URL запроса</b> скопируй адрес из шапки того же запроса (там есть project id) → <b>Применить</b>.</li>
|
||||
</ol>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Способ 3 — Куки из расширения</b> (формат Cookie-Editor / EditThisCookie JSON)</summary>
|
||||
<ol class="sub">
|
||||
<li>Поставь в Chrome расширение <b>Cookie-Editor</b>, открой <b>factory.8090.ai</b> (войдя в аккаунт).</li>
|
||||
<li>Клик по иконке расширения → <b>Export</b> (JSON) → вставь массив кук в поле ниже.</li>
|
||||
<li>Вставь также <b>URL</b> страницы в поле URL.</li>
|
||||
</ol>
|
||||
<p class="sub" style="color: var(--warn)">⚠ Одних кук <b>недостаточно</b>: авторизация у factory идёт заголовками <b>authorization: Bearer …</b> и <b>x-sofa-cognito-id-token: …</b>, а куки вида posthog_* — только аналитика. Способ 3 годится как дополнение к способу 2 (вставь куки + заголовки в одно поле), сам по себе — нет.</p>
|
||||
</details>
|
||||
<details open>
|
||||
<summary><b>Способ 4 — Команда в консоль</b> (авто-сбор, без ручного копирования)<span class="reco">проще всего</span></summary>
|
||||
<ol class="sub">
|
||||
<li>Открой <b>factory.8090.ai</b> (войдя в аккаунт) и нажми <b>F12</b> → вкладка <b>Console</b>.</li>
|
||||
<li>Скопируй команду (клик по блоку ниже) и вставь её в консоль → <b>Enter</b>.</li>
|
||||
<li>Отправь боту <b>любое сообщение</b> — команда перехватит запрос к API и сама скопирует URL и все auth-заголовки в буфер обмена.</li>
|
||||
<li>Вернись сюда и вставь всё <b>одним куском</b> в поле ниже (URL будет первой строкой, отдельное поле URL не нужно).</li>
|
||||
</ol>
|
||||
<pre id="cssnippet" style="max-height:220px;overflow:auto;cursor:pointer;white-space:pre-wrap;word-break:break-all" onclick="copy('cssnippet')">${CONSOLE_SNIPPET.replace(/</g, '<')}</pre>
|
||||
<p class="sub">Клик по блоку — копирование. Команда безвредна: она только читает исходящий запрос, ничего не отправляет и не меняет.</p>
|
||||
<p class="sub">💾 <b>Пул аккаунтов:</b> каждая вставка — это аккаунт. Повторная вставка с тем же логином обновляет его токены; вставка с другого логина добавляет новый аккаунт в пул. При 401 (токен истёк) прокси сам переключается на следующий аккаунт. Токены живут ~1 час — при 401 просто вставь свежий блок.</p>
|
||||
</details>
|
||||
|
||||
<label for="credtext">HAR JSON, заголовки запроса или экспорт кук — всё в это поле (cookie строкой «cookie: …» или JSON-массивом)</label>
|
||||
<textarea id="credtext" placeholder='{"log":{"entries":[…]}} — HAR целиком либо заголовки: authorization: Bearer eyJ… x-sofa-cognito-id-token: eyJ… cookie: __Host-session=…; other=… x-sofa-active-org-id: … либо куки из расширения: [{"domain":".8090.ai","name":"…","value":"…"}]'></textarea>
|
||||
<label for="credurl">URL запроса — нужен для способов 2 и 3: https://api.factory.8090.dev/v2/project/<id>/agents/chat-agent/input (для способа 3 можно URL страницы: https://factory.8090.ai/project/<id>)</label>
|
||||
<input id="credurl" placeholder="https://api.factory.8090.dev/v2/project/.../agents/chat-agent/input">
|
||||
<div style="margin-top:10px"><button onclick="applyCreds()">Применить</button></div>
|
||||
<div class="msg" id="credmsg"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Эндпоинт</h2>
|
||||
<div class="grid">
|
||||
<div><label>Base URL</label><pre id="curlurl" onclick="copy('curlurl')">${base}</pre></div>
|
||||
<div><label>API-ключ</label><pre id="curlkey" onclick="copy('curlkey')">${apiKey}</pre></div>
|
||||
</div>
|
||||
<label style="margin-top:14px">Установить провайдер в CLI/IDE одним кликом (конфиг обновится сам, бэкап рядом)</label>
|
||||
<div style="display:flex; gap:8px; flex-wrap:wrap">
|
||||
<button class="ghost" onclick="install('opencode')">OpenCode</button>
|
||||
<button class="ghost" onclick="install('cline')">Cline</button>
|
||||
<button class="ghost" onclick="install('roo')">Roo Code</button>
|
||||
<button class="ghost" onclick="install('continue')">Continue</button>
|
||||
<button class="ghost" onclick="install('omp')">OMP</button>
|
||||
</div>
|
||||
<div class="msg" id="instmsg"></div>
|
||||
<details open><summary>curl</summary><pre id="curlsample" onclick="copy('curlsample')">${curl.replace(/</g, '<')}</pre></details>
|
||||
<details><summary>Roo Code / Cline settings</summary><pre id="roosample" onclick="copy('roosample')">${roo.replace(/</g, '<')}</pre></details>
|
||||
<details><summary>OMP models.yml</summary><pre id="ompsample" onclick="copy('ompsample')">${omp.replace(/</g, '<')}</pre></details>
|
||||
<details><summary>OpenCode — opencode.json</summary><pre id="ocsample" onclick="copy('ocsample')">${opencode.replace(/</g, '<')}</pre></details>
|
||||
<details><summary>Cline — VS Code settings</summary><pre id="clsample" onclick="copy('clsample')">${cline.replace(/</g, '<')}</pre></details>
|
||||
<details><summary>Continue — config.yaml</summary><pre id="ctsample" onclick="copy('ctsample')">${continueSnippet.replace(/</g, '<')}</pre></details>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Playground</h2>
|
||||
<p class="sub" style="margin-bottom:10px">Модели и выбор появятся, как только вставишь креды выше (сейчас прокси ждёт авторизацию).</p>
|
||||
<div class="grid">
|
||||
<div><label>Модель</label><select id="pmodel"></select></div>
|
||||
<div><label>reasoning_effort</label>
|
||||
<select id="peffort"><option value="">— по умолчанию —</option><option>minimal</option><option>low</option><option>medium</option><option>high</option></select></div>
|
||||
</div>
|
||||
<label>Сообщение</label>
|
||||
<textarea id="pmsg" style="min-height:70px">Say OK</textarea>
|
||||
<div style="margin-top:10px; display:flex; gap:12px; align-items:center">
|
||||
<button onclick="play()">Отправить</button>
|
||||
<label style="display:flex; gap:6px; margin:0; align-items:center"><input type="checkbox" id="pstream" style="width:auto"> stream</label>
|
||||
</div>
|
||||
<pre id="playout" class="msg"></pre>
|
||||
</div>
|
||||
|
||||
<script>const KEY = ${JSON.stringify(apiKey)};\n${JS}</script>
|
||||
</body></html>`;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"id": "<YOUR_ACCOUNT_ID>",
|
||||
"headers": {
|
||||
"authorization": "Bearer <YOUR_FACTORY_JWT>"
|
||||
},
|
||||
"note": "Replace with your own factory.8090.ai session. Real file is gitignored."
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{
|
||||
"id": "<YOUR_ACCOUNT_ID>",
|
||||
"headers": {
|
||||
"authorization": "Bearer <YOUR_FACTORY_JWT>"
|
||||
},
|
||||
"note": "Replace with your own factory.8090.ai session. Real file is gitignored."
|
||||
}
|
||||
]
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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}]}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"headers": {
|
||||
"authorization": "Bearer <YOUR_FACTORY_JWT>"
|
||||
},
|
||||
"note": "Replace with your own factory.8090.ai credentials. Real file is gitignored."
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"headers": {
|
||||
"authorization": "Bearer <YOUR_FACTORY_JWT>"
|
||||
},
|
||||
"note": "Replace with your own factory.8090.ai credentials. Real file is gitignored."
|
||||
}
|
||||
@@ -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/<id>/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 живут ~час — просто отправь боту ещё одно сообщение, расширение обновит креды само.
|
||||
@@ -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']
|
||||
);
|
||||
@@ -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" }
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
+1641
File diff suppressed because it is too large
Load Diff
+875
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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-перехода подтягивается с сервера.
|
||||
Reference in New Issue
Block a user