Compare commits

..

7 Commits

Author SHA1 Message Date
backryun
a8dfccf1c8 fix(changelog): reformat 9239/9490 feature fragments to bullet convention (base-red #9985) 2026-08-12 03:57:10 -03:00
backryun
1dc2e4fffd fix(ci): clear base-red typecheck + migration collisions on release/v3.8.50
Resolve 13 typecheck:core errors (deepai executor/import, responseSanitizer
cached_tokens typing, search.ts token headers, usageTracking duplicate props,
modelCapabilityOverrideKey max_token, executeWebSearch null) and remove the
stale duplicate 143_job_registry.sql (canonical is 146_job_registry per
RENAMED_MIGRATION_COMPATIBILITY), freeing the 147 KNOWN_GAPS entry.

Base-reds tracked by #9985.
2026-08-12 03:43:08 -03:00
backryun
297d404327 fix(quality): base-red round 3 — gateways dup chatanywhere + regolo close (unblock typecheck) 2026-08-12 02:34:26 -03:00
Diego Rodrigues de Sa e Souza
4e6f808b43 feat(plugins): add onStreamComplete built-in event exposing streaming usage and timing (#9571) (#9669)
* feat(plugins): add onStreamComplete built-in event exposing streaming usage and timing (#9571)

* fix(changelog): remove YAML frontmatter from 9571 fragment

The changelog fragment format requires the first non-empty line to be
a markdown bullet ("- "). YAML frontmatter was the first non-empty
line, causing the integrity check to fail.

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-12 02:15:57 -03:00
Diego Rodrigues de Sa e Souza
cc3c5b98c0 feat(a2a): inbound delegation to the OmniConductor fleet via POST /api/a2a/tasks (PRD RF5) (#8223)
* feat(a2a): conductor bridge core — event mapping with canceled->cancelled

* feat(a2a): incremental SSE parser for conductor bridge

* feat(a2a): conductor bridge connection loop with persisted cursor and backoff

* feat(a2a): start conductor bridge at boot behind CONDUCTOR_HUB_URL

* fix(a2a): conductor bridge parses the hub's real SSE wire format (id/type in frame, data={ts,payload})

* docs(reference): document CONDUCTOR_HUB_URL/TOKEN in ENVIRONMENT.md (env-doc-sync gate)

* feat(a2a): fleet skills derived from the Conductor hub for the agent card

* feat(a2a): agent card announces Conductor fleet skills

* feat(dashboard): server-side hub proxy for the Conductor panel (whitelisted shapes, fail-open)

* feat(dashboard): /api/conductor proxy routes (fleet, task detail, cancel) behind management auth

* feat(dashboard): Conductor panel — fleet live view, task detail and cancel over /api/conductor proxy

* feat(dashboard): /api/conductor/ask — server-side proxy to Faro (spokesperson) with whitelisted {text,pending}

* chore(env): CONDUCTOR_SPOKESPERSON_URL declared in schema, .env.example and ENVIRONMENT.md

* feat(dashboard): Faro chat with push-to-talk voice on the Conductor panel

* feat(a2a): inbound delegation to the Conductor fleet — POST /api/a2a/tasks translating to the hub

---------

Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-12 02:13:41 -03:00
Diego Rodrigues de Sa e Souza
3638adeeae feat(dashboard): Faro chat with push-to-talk voice on the Conductor panel (PRD RF4) (#8222)
* feat(a2a): conductor bridge core — event mapping with canceled->cancelled

* feat(a2a): incremental SSE parser for conductor bridge

* feat(a2a): conductor bridge connection loop with persisted cursor and backoff

* feat(a2a): start conductor bridge at boot behind CONDUCTOR_HUB_URL

* fix(a2a): conductor bridge parses the hub's real SSE wire format (id/type in frame, data={ts,payload})

* docs(reference): document CONDUCTOR_HUB_URL/TOKEN in ENVIRONMENT.md (env-doc-sync gate)

* feat(a2a): fleet skills derived from the Conductor hub for the agent card

* feat(a2a): agent card announces Conductor fleet skills

* feat(dashboard): server-side hub proxy for the Conductor panel (whitelisted shapes, fail-open)

* feat(dashboard): /api/conductor proxy routes (fleet, task detail, cancel) behind management auth

* feat(dashboard): Conductor panel — fleet live view, task detail and cancel over /api/conductor proxy

* feat(dashboard): /api/conductor/ask — server-side proxy to Faro (spokesperson) with whitelisted {text,pending}

* chore(env): CONDUCTOR_SPOKESPERSON_URL declared in schema, .env.example and ENVIRONMENT.md

* feat(dashboard): Faro chat with push-to-talk voice on the Conductor panel

---------

Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-12 02:00:20 -03:00
Diego Rodrigues de Sa e Souza
3db785dc41 feat(dashboard): Conductor panel — fleet, tasks and cancel over server-side proxy (PRD RF3) (#8221)
* feat(a2a): conductor bridge core — event mapping with canceled->cancelled

* feat(a2a): incremental SSE parser for conductor bridge

* feat(a2a): conductor bridge connection loop with persisted cursor and backoff

* feat(a2a): start conductor bridge at boot behind CONDUCTOR_HUB_URL

* fix(a2a): conductor bridge parses the hub's real SSE wire format (id/type in frame, data={ts,payload})

* docs(reference): document CONDUCTOR_HUB_URL/TOKEN in ENVIRONMENT.md (env-doc-sync gate)

* feat(a2a): fleet skills derived from the Conductor hub for the agent card

* feat(a2a): agent card announces Conductor fleet skills

* feat(dashboard): server-side hub proxy for the Conductor panel (whitelisted shapes, fail-open)

* feat(dashboard): /api/conductor proxy routes (fleet, task detail, cancel) behind management auth

* feat(dashboard): Conductor panel — fleet live view, task detail and cancel over /api/conductor proxy

---------

Co-authored-by: backryun <bakryun0718@proton.me>
2026-08-12 01:53:14 -03:00
33 changed files with 3138 additions and 2072 deletions

View File

@@ -1,7 +1,3 @@
feat(images): execute full combo strategy + fallback in /v1/images/generations (#9239)
- feat(images): execute full combo strategy + fallback in /v1/images/generations (#9239)
Add open-sse/services/imageCombo.ts that expands combo targets, filters
to images-capable, executes priority strategy with handleImageGeneration
per target, and returns first success or last failure. Route patches
detect combo names before model resolution and divert to the new
execution path.
Adds open-sse/services/imageCombo.ts that expands combo targets, filters to images-capable, executes the priority strategy with handleImageGeneration per target, and returns the first success or last failure. Route patches detect combo names before model resolution and divert to the new execution path.

View File

@@ -1,5 +1,3 @@
---
feature: 9490
---
- feat(opencode-plugin): warm catalog startup from disk snapshot + parallel refresh (#9490)
**Warm catalog startup from disk snapshot + parallel refresh** (opencode-plugin): The config-shim hook now reads the last disk snapshot *before* fetching, so the provider registers immediately with the last-known-good catalog (~1-2s vs ~30s on a warm gateway). All six fetchers run concurrently via `Promise.allSettled` instead of sequentially. A failed refresh keeps the snapshot (no overwrite). An in-flight guard prevents concurrent refreshes for the same cache key. The `features.diskCache: false` opt-out disables the warm read entirely.
The config-shim hook now reads the last disk snapshot before fetching, so the provider registers immediately with the last-known-good catalog (~1-2s vs ~30s on a warm gateway). All six fetchers run concurrently via Promise.allSettled instead of sequentially. A failed refresh keeps the snapshot (no overwrite). An in-flight guard prevents concurrent refreshes for the same cache key. The features.diskCache: false opt-out disables the warm read entirely.

View File

@@ -0,0 +1,11 @@
- **feat(plugins):** add onStreamComplete built-in event exposing streaming usage and timing (#9571)
Adds a new `onStreamComplete` plugin event that fires after an SSE stream is fully
consumed, carrying usage token counts and timing metrics (latency, TTFT). Built-in
events now include `onStreamComplete` as a fire-and-forget lifecycle hook.
Payload: `status`, `usage` (prompt_tokens, completion_tokens, reasoning_tokens,
cache_read_input_tokens, cache_creation_input_tokens), `timing` (latencyMs, ttft),
`model`, `provider`, `errorCode`.
Non-breaking — existing `onResponse` hooks with `{ streamed: true }` remain unchanged.

View File

@@ -0,0 +1 @@
- feat(a2a): inbound delegation to the OmniConductor fleet — `POST /api/a2a/tasks` translates an external A2A task into the hub's `POST /v1/tasks` (fleet skills only, repo required, `CONDUCTOR_ORCHESTRATOR_TOKEN` with hub-token fallback); states flow back through the SSE→A2A mirror

View File

@@ -0,0 +1 @@
- feat(dashboard): Faro chat with voice on the Conductor panel — text via `/api/conductor/ask` (server-side proxy to the spokesperson; hub credential never reaches the browser; `pending` → Sim/Não confirmation buttons) and a guaranteed push-to-talk voice cycle (MediaRecorder → `/api/v1/audio/transcriptions` → ask → `/api/v1/audio/speech` playback), with operator-configurable STT/TTS models

View File

@@ -178,6 +178,9 @@ The JSON-RPC endpoint `/a2a` is the canonical A2A entry point. The REST endpoint
| `/api/a2a/tasks/[id]` | GET | Get task by ID | management |
| `/api/a2a/tasks/[id]/cancel` | POST | Cancel running task | management |
| `/.well-known/agent.json` | GET | Agent Card (A2A discovery) | (public, cached 3600s) |
| `/api/a2a/tasks` | POST | Inbound delegation to the OmniConductor fleet (Conductor PRD RF5) | Bearer vs `OMNIROUTE_API_KEY` + `a2aEnabled` |
**Inbound Conductor delegation (`POST /api/a2a/tasks`):** external A2A agents delegate coding work to the OmniConductor fleet through OmniRoute. Body: `{ skill: "conductor" | "conductor-cli-<profile>", messages: [{role, content}], metadata: { conductor: { repo: { url, base_ref? }, mode?, cli?, model? } } }` — only Conductor fleet skills (the ones announced on the Agent Card) are delegable; `metadata.conductor.repo.url` is required (the fleet works on git repos). The route translates to the hub's `POST /v1/tasks` using the server-side `CONDUCTOR_ORCHESTRATOR_TOKEN` (fallback `CONDUCTOR_HUB_TOKEN`) and returns `201 { conductor_task_id, state: "submitted" }`; task states flow back through the SSE→A2A mirror (RF1) and are visible via `GET /api/a2a/tasks?skill=conductor`.
---

View File

@@ -1,5 +1,5 @@
import type { RegistryEntry } from "../../shared.ts";
import { CONOL_FALLBACK_MODELS } from "../../../services/conolModels.ts";
import { CONOL_FALLBACK_MODELS } from "../../../../services/conolModels.ts";
export const conol_webProvider: RegistryEntry = {
id: "conol-web",

View File

@@ -1,4 +1,4 @@
import type { RegistryEntry } from "../shared";
import type { RegistryEntry } from "../../shared";
export const deepaiProvider: RegistryEntry = {
id: "deepai",
@@ -7,6 +7,7 @@ export const deepaiProvider: RegistryEntry = {
baseUrl: "https://api.deepai.org",
authType: "apikey",
authHeader: "api-key",
executor: "default",
models: [
{ id: "text2img", name: "Text to Image" },
],

View File

@@ -251,7 +251,10 @@ import { recordCompressionCacheStats } from "./chatCore/compressionCacheStats.ts
import { writeCavemanOutputAnalytics } from "./chatCore/cavemanOutputAnalytics.ts";
import { scheduleQuotaShareConsumption } from "./chatCore/quotaShareConsumption.ts";
import { emitRequestGamificationEvent } from "./chatCore/gamificationEvent.ts";
import { runPluginOnResponseHook } from "./chatCore/pluginOnResponse.ts";
import {
runPluginOnResponseHook,
runPluginOnStreamCompleteHook,
} from "./chatCore/pluginOnResponse.ts";
import { scheduleStreamingQuotaShareConsumption } from "./chatCore/streamingQuotaShare.ts";
import { recordStreamingUsageStats } from "./chatCore/streamingUsageStats.ts";
import { recordStreamingCost } from "./chatCore/streamingCost.ts";
@@ -4934,6 +4937,17 @@ export async function handleChatCore({
streamUsage,
log,
});
// Plugin onStreamComplete hook — fire-and-forget, fail-open (#9571)
runPluginOnStreamCompleteHook({
status: normalizedStreamStatus,
usage: streamUsage as Record<string, unknown> | undefined,
ttft,
model,
provider,
errorCode: streamErrorCode,
startTime,
});
};
const streamFailureFinalizers = streamFailure.createStreamFailureFinalizers({

View File

@@ -45,3 +45,57 @@ export async function runPluginOnResponseHook(args: {
/* plugin onResponse optional */
}
}
/**
* Payload passed to plugin onStreamComplete hooks after a streaming response is consumed.
* Carries usage token counts, timing metrics (latency, TTFT), model, provider, and error code.
*/
export type PluginOnStreamCompletePayload = {
status: number;
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
reasoning_tokens?: number;
cache_read_input_tokens?: number;
cache_creation_input_tokens?: number;
};
timing?: {
latencyMs: number;
ttft?: number;
};
model?: string;
provider?: string;
errorCode?: string;
};
/**
* Run plugin onStreamComplete hooks — fire-and-forget and fail-open.
* Called inside the onStreamComplete callback (chatCore.ts) where usage and timing data
* converge after an SSE stream is fully consumed.
*/
export async function runPluginOnStreamCompleteHook(args: {
status: number;
usage?: Record<string, unknown>;
ttft?: number;
model: string | null | undefined;
provider: string | null | undefined;
errorCode?: string | null | undefined;
startTime: number;
}): Promise<void> {
try {
const { runOnStreamComplete } = await import("@/lib/plugins/hooks");
runOnStreamComplete({
status: args.status,
usage: args.usage as PluginOnStreamCompletePayload["usage"],
timing: {
latencyMs: Date.now() - args.startTime,
ttft: args.ttft,
},
model: args.model ?? undefined,
provider: args.provider ?? undefined,
errorCode: args.errorCode ?? undefined,
}).catch(() => {});
} catch (_) {
/* plugin onStreamComplete optional */
}
}

View File

@@ -537,7 +537,7 @@ function sanitizeResponsesUsage(usage: unknown): unknown {
// DeepSeek native API: map flat prompt_cache_hit_tokens into input_tokens_details
if (
normalized.prompt_cache_hit_tokens !== undefined &&
!normalized.input_tokens_details?.cached_tokens
!(toRecord(normalized.input_tokens_details) ?? {}).cached_tokens
) {
normalized.input_tokens_details = {
...(normalized.input_tokens_details as Record<string, unknown> || {}),
@@ -549,7 +549,7 @@ function sanitizeResponsesUsage(usage: unknown): unknown {
if (
normalized.cache_read_input_tokens !== undefined &&
normalized.cache_read_input_tokens !== 0 &&
!normalized.input_tokens_details?.cached_tokens
!(toRecord(normalized.input_tokens_details) ?? {}).cached_tokens
) {
normalized.input_tokens_details = {
...(normalized.input_tokens_details as Record<string, unknown> || {}),

View File

@@ -304,7 +304,7 @@ function buildSerperRequest(
url: `${config.baseUrl}${endpoint}`,
init: {
method: "POST",
headers: { "Content-Type": "application/json", "X-API-Key": params.token },
headers: { "Content-Type": "application/json", ...(params.token ? { "X-API-Key": params.token } : {}) },
body: JSON.stringify(body),
},
};
@@ -322,7 +322,7 @@ function buildBraveRequest(
url: `${config.baseUrl}${endpoint}?${qp}`,
init: {
method: "GET",
headers: { Accept: "application/json", "X-Subscription-Token": params.token },
headers: { Accept: "application/json", ...(params.token ? { "X-Subscription-Token": params.token } : {}) },
},
};
}
@@ -348,7 +348,7 @@ function buildExaRequest(
url: config.baseUrl,
init: {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": params.token },
headers: { "Content-Type": "application/json", ...(params.token ? { "x-api-key": params.token } : {}) },
body: JSON.stringify(body),
},
};

View File

@@ -665,8 +665,6 @@ export function extractUsage(chunk) {
chunk.usage.reasoning_tokens,
// xAI's exact provider-reported cost (port of decolua/9router#2453, capability A).
cost_in_usd_ticks: chunk.usage.cost_in_usd_ticks,
cache_read_input_tokens: chunk.usage.cache_read_input_tokens,
cache_creation_input_tokens: chunk.usage.cache_creation_input_tokens,
});
}

View File

@@ -51,7 +51,7 @@ export const KNOWN_DUPLICATE_VERSIONS = new Set([
// O stale-enforcement exige que cada reserva seja removida quando os arquivos
// correspondentes aterrissarem na release.
// ---------------------------------------------------------------------------
export const KNOWN_GAPS = new Set(["026", "055", "121", "144", "145", "147", "148", "149"]); // 121: número queimado no ciclo v3.8.47 — 122 (#6909) mergeou antes e 121 nunca aterrissou (validação e2e 2026-07-12)
export const KNOWN_GAPS = new Set(["026", "055", "121", "144", "145", "148", "149"]); // 121: número queimado no ciclo v3.8.47 — 122 (#6909) mergeou antes e 121 nunca aterrissou (validação e2e 2026-07-12)
function pad3(n) {
return String(n).padStart(3, "0");

View File

@@ -11,6 +11,8 @@ import { useTranslations } from "next-intl";
import { Badge, Card, ConfirmModal, DataTable, EmptyState, Modal } from "@/shared/components";
import FaroChat from "./FaroChat";
interface FleetRunner {
id: string;
name: string;
@@ -174,6 +176,8 @@ export default function ConductorPageClient() {
</>
)}
<FaroChat />
<Modal isOpen={detail !== null} onClose={() => setDetail(null)} title={t("detailTitle")} size="lg">
{detail && (
<div className="space-y-4 text-sm">

View File

@@ -0,0 +1,272 @@
"use client";
/**
* Faro chat with voice (Conductor PRD RF4). Text: input → /api/conductor/ask
* (server-side proxy — the hub credential never reaches the browser). When the
* answer carries `pending`, Faro is asking for confirmation: the Sim/Não
* buttons just send "sim"/"não" — the safety gate lives in Faro's engine.
*
* Voice (guaranteed cycle, PRD RF4): push-to-talk → MediaRecorder →
* POST /api/v1/audio/transcriptions (multipart) → text → /ask → response →
* POST /api/v1/audio/speech → play the returned audio blob. STT/TTS models are
* operator-configurable (provider/model of THIS OmniRoute install), persisted
* in localStorage.
*/
import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { Badge, Card } from "@/shared/components";
interface ChatMessage {
role: "user" | "faro";
text: string;
}
type VoiceState = "idle" | "listening" | "thinking" | "speaking";
const STT_KEY = "conductor.sttModel";
const TTS_KEY = "conductor.ttsModel";
function safeGet(key: string, fallback: string): string {
try {
return localStorage.getItem(key) || fallback;
} catch {
return fallback;
}
}
async function errorMessageOf(res: Response, fallback: string): Promise<string> {
try {
const data = await res.json();
return data?.error?.message ?? fallback;
} catch {
return fallback;
}
}
export default function FaroChat() {
const t = useTranslations("conductor");
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState("");
const [pending, setPending] = useState(false);
const [busy, setBusy] = useState(false);
const [voice, setVoice] = useState<VoiceState>("idle");
const [speak, setSpeak] = useState(false);
const [sttModel, setSttModel] = useState("openai/whisper-1");
const [ttsModel, setTtsModel] = useState("openai/tts-1");
const [err, setErr] = useState("");
const recorderRef = useRef<MediaRecorder | null>(null);
const logRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setSttModel(safeGet(STT_KEY, "openai/whisper-1"));
setTtsModel(safeGet(TTS_KEY, "openai/tts-1"));
}, []);
useEffect(() => {
logRef.current?.scrollTo({ top: logRef.current.scrollHeight });
}, [messages]);
const persistModels = (stt: string, tts: string) => {
setSttModel(stt);
setTtsModel(tts);
try {
localStorage.setItem(STT_KEY, stt);
localStorage.setItem(TTS_KEY, tts);
} catch {
// modo privado: segue só em memória
}
};
const playAnswer = async (text: string) => {
setVoice("speaking");
try {
const res = await fetch("/api/v1/audio/speech", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: ttsModel, input: text }),
});
if (!res.ok) {
setErr(await errorMessageOf(res, t("ttsFailed")));
return;
}
const url = URL.createObjectURL(await res.blob());
const audio = new Audio(url);
await audio.play().catch(() => undefined);
audio.onended = () => URL.revokeObjectURL(url);
} finally {
setVoice("idle");
}
};
const send = async (message: string, viaVoice = false) => {
const clean = message.trim();
if (!clean || busy) return;
setErr("");
setBusy(true);
setVoice("thinking");
setMessages((m) => [...m, { role: "user", text: clean }]);
setInput("");
try {
const res = await fetch("/api/conductor/ask", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: clean }),
});
if (!res.ok) {
setErr(await errorMessageOf(res, t("faroOffline")));
return;
}
const data = await res.json();
setMessages((m) => [...m, { role: "faro", text: data.text }]);
setPending(Boolean(data.pending));
if (viaVoice && speak && data.text) await playAnswer(data.text);
} catch {
setErr(t("faroOffline"));
} finally {
setBusy(false);
setVoice((v) => (v === "thinking" ? "idle" : v));
}
};
const startRecording = async () => {
setErr("");
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(stream);
const chunks: Blob[] = [];
recorder.ondataavailable = (e) => e.data.size > 0 && chunks.push(e.data);
recorder.onstop = async () => {
stream.getTracks().forEach((track) => track.stop());
setVoice("thinking");
const blob = new Blob(chunks, { type: recorder.mimeType || "audio/webm" });
const form = new FormData();
form.append("model", sttModel);
form.append("file", new File([blob], "faro-ptt.webm", { type: blob.type }));
try {
// multipart: sem header manual — o browser define o boundary
const res = await fetch("/api/v1/audio/transcriptions", { method: "POST", body: form });
if (!res.ok) {
setErr(await errorMessageOf(res, t("sttFailed")));
setVoice("idle");
return;
}
const data = await res.json();
if (data.text) await send(data.text, true);
else setVoice("idle");
} catch {
setErr(t("sttFailed"));
setVoice("idle");
}
};
recorderRef.current = recorder;
recorder.start();
setVoice("listening");
} catch {
setErr(t("micDenied"));
}
};
const stopRecording = () => {
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
recorderRef.current = null;
};
const voiceLabel: Record<VoiceState, string> = {
idle: t("voiceIdle"),
listening: t("voiceListening"),
thinking: t("voiceThinking"),
speaking: t("voiceSpeaking"),
};
return (
<Card title={t("faroTitle")} subtitle={t("faroSubtitle")}>
<div className="space-y-3">
<div ref={logRef} className="max-h-72 overflow-y-auto space-y-2 text-sm">
{messages.length === 0 && <p className="text-text-muted text-xs">{t("faroEmpty")}</p>}
{messages.map((m, i) => (
<div key={i} className={m.role === "user" ? "text-right" : "text-left"}>
<span
className={
m.role === "user"
? "inline-block rounded px-2 py-1 bg-primary/10"
: "inline-block rounded px-2 py-1 bg-black/5 dark:bg-white/10 whitespace-pre-wrap"
}
>
{m.text}
</span>
</div>
))}
</div>
{err && <Badge variant="error">{err}</Badge>}
{pending && (
<div className="flex items-center gap-2">
<Badge variant="warning" dot>{t("faroPending")}</Badge>
<button type="button" className="text-sm underline" onClick={() => void send("sim")}>
{t("yes")}
</button>
<button type="button" className="text-sm underline" onClick={() => void send("não")}>
{t("no")}
</button>
</div>
)}
<div className="flex items-center gap-2">
<input
className="flex-1 rounded border border-black/10 dark:border-white/10 bg-transparent px-2 py-1 text-sm"
placeholder={t("faroPlaceholder")}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void send(input);
}}
disabled={busy}
/>
<button type="button" className="text-sm underline" onClick={() => void send(input)} disabled={busy}>
{t("faroSend")}
</button>
<button
type="button"
className={`text-sm px-2 py-1 rounded ${voice === "listening" ? "bg-red-500/20" : "bg-black/5 dark:bg-white/10"}`}
title={t("pushToTalk")}
aria-pressed={voice === "listening"}
onMouseDown={() => void startRecording()}
onMouseUp={stopRecording}
onMouseLeave={stopRecording}
onTouchStart={() => void startRecording()}
onTouchEnd={stopRecording}
>
🎙 {voiceLabel[voice]}
</button>
<label className="flex items-center gap-1 text-xs text-text-muted">
<input type="checkbox" checked={speak} onChange={(e) => setSpeak(e.target.checked)} />
{t("speakAnswers")}
</label>
</div>
<details className="text-xs text-text-muted">
<summary>{t("voiceModels")}</summary>
<div className="flex gap-2 pt-2">
<label className="flex-1">
STT
<input
className="w-full rounded border border-black/10 dark:border-white/10 bg-transparent px-2 py-1"
value={sttModel}
onChange={(e) => persistModels(e.target.value, ttsModel)}
/>
</label>
<label className="flex-1">
TTS
<input
className="w-full rounded border border-black/10 dark:border-white/10 bg-transparent px-2 py-1"
value={ttsModel}
onChange={(e) => persistModels(sttModel, e.target.value)}
/>
</label>
</div>
</details>
</div>
</Card>
);
}

View File

@@ -1,5 +1,9 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getTaskManager, type TaskState } from "@/lib/a2a/taskManager";
import { createConductorTask } from "@/lib/conductor/hubProxy";
import { getSettings } from "@/lib/db/settings";
const VALID_TASK_STATES = new Set<TaskState>([
"submitted",
@@ -44,3 +48,97 @@ export async function GET(request: Request) {
return NextResponse.json({ error: message }, { status: 500 });
}
}
// ============ POST — delegação de entrada à frota do Conductor (PRD Conductor RF5) ============
const delegationSchema = z.object({
skill: z.string().default("conductor"),
messages: z.array(z.object({ role: z.string(), content: z.string() })).min(1),
metadata: z
.object({
conductor: z
.object({
repo: z.object({ url: z.string().min(1), base_ref: z.string().optional() }).optional(),
mode: z.string().optional(),
cli: z.string().optional(),
model: z.string().optional(),
})
.optional(),
})
.optional(),
});
/** Mesma semântica de auth do JSON-RPC A2A (src/app/a2a/route.ts): Bearer vs OMNIROUTE_API_KEY; aberto se não configurada. */
function authenticateA2A(request: Request): boolean {
const configuredKey = process.env.OMNIROUTE_API_KEY;
if (!configuredKey) return true;
const token = (request.headers.get("authorization") || "").replace(/^Bearer\s+/i, "");
return token === configuredKey;
}
/**
* Traduz uma task A2A externa em `POST /v1/tasks` do hub do OmniConductor.
* Só skills da frota (`conductor` / `conductor-cli-<profile>` — as anunciadas no
* Agent Card) são delegáveis; os estados voltam pelo espelho SSE→A2A (RF1).
*/
export async function POST(request: Request) {
if (!authenticateA2A(request)) {
return NextResponse.json({ error: "Unauthorized: missing or invalid API key" }, { status: 401 });
}
const settings = await getSettings();
if (settings.a2aEnabled !== true) {
return NextResponse.json(
{ error: "A2A endpoint is disabled. Enable it from the Endpoints page." },
{ status: 503 }
);
}
let raw: unknown;
try {
raw = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const parsed = delegationSchema.safeParse(raw);
if (!parsed.success) {
return NextResponse.json({ error: "Invalid A2A task: provide messages[] (and metadata.conductor)" }, { status: 400 });
}
const { skill, messages, metadata } = parsed.data;
if (skill !== "conductor" && !skill.startsWith("conductor-cli-")) {
return NextResponse.json(
{ error: "Only Conductor fleet skills are delegable here (conductor / conductor-cli-<profile>)" },
{ status: 400 }
);
}
const conductor = metadata?.conductor;
if (!conductor?.repo?.url) {
return NextResponse.json(
{ error: "Delegation requires metadata.conductor.repo.url (the fleet works on git repos)" },
{ status: 400 }
);
}
const prompt = [...messages].reverse().find((m) => m.role === "user")?.content ?? messages[messages.length - 1].content;
const created = await createConductorTask({
repoUrl: conductor.repo.url,
baseRef: conductor.repo.base_ref,
prompt,
mode: conductor.mode,
cli: skill.startsWith("conductor-cli-") ? skill.slice("conductor-cli-".length) : conductor.cli,
model: conductor.model,
});
if (!created.ok) {
return NextResponse.json(
{ error: `Conductor hub refused the delegation (HTTP ${created.status})` },
{ status: created.status }
);
}
return NextResponse.json(
{
conductor_task_id: created.task_id,
state: "submitted",
note: "States flow back through the SSE→A2A mirror (GET /api/a2a/tasks, skill=conductor).",
},
{ status: 201 }
);
}

View File

@@ -0,0 +1,37 @@
/**
* POST /api/conductor/ask — proxy para o Faro (spokesperson do OmniConductor).
* O /ask do Faro exige credencial do hub (server-side); o browser fala só com
* esta rota. Resposta whitelisted {text, pending} — quando `pending` vier, a UI
* oferece Sim/Não (a trava de confirmação é do motor do Faro; nunca contornada).
*/
import { NextResponse } from "next/server";
import { z } from "zod";
import { createErrorResponse } from "@/lib/api/errorResponse";
import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { askFaro } from "@/lib/conductor/faroProxy";
const askSchema = z.object({ message: z.string().min(1).max(4000) });
export async function POST(request: Request) {
const authError = await requireManagementAuth(request);
if (authError) return authError;
let raw: unknown;
try {
raw = await request.json();
} catch {
return createErrorResponse({ status: 400, message: "Invalid JSON body" });
}
const parsed = askSchema.safeParse(raw);
if (!parsed.success) {
return createErrorResponse({ status: 400, message: "Body must be { message: string (1-4000 chars) }" });
}
const answer = await askFaro(parsed.data.message);
if (!answer.ok) {
return createErrorResponse({ status: 503, message: "Faro (spokesperson) is offline or refused the request" });
}
return NextResponse.json({ text: answer.text, pending: answer.pending });
}

View File

@@ -1277,11 +1277,11 @@
"discoverySubtitle": "Scan providers for free access",
"conductor": "Conductor",
"conductorSubtitle": "CLI-agent fleet",
"resilienceConnections": "Connection Resilience",
"resilienceConnectionsSubtitle": "Cooldown, breaker, lockout state",
"settingsModalityBridge": "Modality Bridge",
"settingsModalityBridgeSubtitle": "Image/audio → text fallback for text-only models",
"commandPalette": {
"resilienceConnections": "Connection Resilience",
"resilienceConnectionsSubtitle": "Cooldown, breaker, lockout state",
"settingsModalityBridge": "Modality Bridge",
"settingsModalityBridgeSubtitle": "Image/audio → text fallback for text-only models",
"commandPalette": {
"title": "Command palette",
"searchPlaceholder": "Search pages, settings, tools...",
"clearSearch": "Clear search",
@@ -6193,12 +6193,13 @@
"cline": "Connect Cline with the existing OAuth flow.",
"cursor": "Connect Cursor IDE with the existing OAuth flow.",
"github": "Connect GitHub Copilot with the existing OAuth flow.",
"gitlab-duo": "GitLab Duo OAuth is not configured. Register an OAuth application at https://gitlab.com/-/profile/applications with redirect URI http://localhost:20128/callback and scopes \"ai_features read_user\", then set GITLAB_DUO_OAUTH_CLIENT_ID (and optionally GITLAB_DUO_OAUTH_CLIENT_SECRET) and restart.",
"gitlab-duo": "OAuth application with ai_features + read_user scopes. Configure GITLAB_DUO_OAUTH_CLIENT_ID and optionally GITLAB_DUO_OAUTH_CLIENT_SECRET on this OmniRoute instance.",
"kilocode": "Connect Kilo Code with the existing OAuth flow.",
"kimi-coding": "Connect Kimi Coding with the existing OAuth flow.",
"kiro": "Free tier: 50 credits/month (~25K100K tokens). ⚠️ Kiro ToS prohibits third-party proxy/harness use.",
"codex": "Connect OpenAI Codex with the existing OAuth flow.",
"qwen": "Connect Qwen Code with the existing OAuth flow."
"qwen": "Connect Qwen Code with the existing OAuth flow.",
"github-models": "Create a GitHub PAT with 'models: read' scope at github.com/settings/tokens"
},
"passthroughModelsDescription": "{provider} accepts provider-native model IDs. Import from /models or add custom IDs for routing.",
"bedrockModelsDescription": "Amazon Bedrock models are scoped by AWS region. Import from /models or add Bedrock model IDs enabled in the selected region.",
@@ -6248,86 +6249,87 @@
"apiProtocolHint": "Some providers publish the same models over more than one protocol. Leave the default unless you need the alternative.",
"bulkAddFormatHintCloudflare": "One key per line. Format: name|accountId|apiKey (Cloudflare account ID + API token).",
"lmarenaWebCookieHint": "Open arena.ai, sign in, then copy the full Cookie header from a Network request. Include arena-auth-prod-v1.0 and arena-auth-prod-v1.1 (and further chunks if present), preferably with cf_clearance. Do not paste only the empty arena-auth-prod-v1 cookie. Optional: providerSpecificData.recaptchaV3Token if create-evaluation still returns 403.",
"kimiOfficialSupporterBadge": "Founding Friend",
"kimiOfficialSupporterTooltip": "Kimi (Moonshot AI) is OmniRoute's founding Open Source Friend",
"kimiOfficialSupporterBadge": "Official Supporter",
"kimiOfficialSupporterTooltip": "Kimi (Moonshot AI) is an official OmniRoute launch partner",
"cheaperInferenceSupporterBadge": "Open Source Friend",
"cheaperInferenceSupporterTooltip": "Cheaper Inference backs OmniRoute as an Open Source Friend",
"kimiPartnerLinkNote": "Partner link — supports OmniRoute at no extra cost to you",
"anonymousFallbackTitle": "Anonymous fallback",
"anonymousFallbackDesc": "When all configured connections are exhausted (quota, credits, or expiry), temporarily use this provider's keyless tier. Turn off to skip this provider instead of sending anonymous requests — recommended when the keyless tier rejects them (401).",
"anonymousFallbackEnabled": "Anonymous fallback enabled for {provider}",
"anonymousFallbackDisabled": "Anonymous fallback disabled for {provider} — exhausted connections will skip this provider",
"anonymousFallbackUpdateFailed": "Failed to update anonymous fallback setting",
"batchDeleteFailed": "Batch delete failed",
"batchDeleteNetworkError": "Network error during batch delete",
"batchUpdateFailed": "Batch update failed",
"batchUpdateNetworkError": "Network error during batch update",
"categoryAudio": "Audio",
"categoryCloudAgent": "Cloud Agent",
"categoryIde": "IDE",
"categoryLocal": "Local",
"categorySearch": "Search",
"categoryWebCookie": "Web Cookie",
"claudeExtraUsageBlockingDisabled": "Claude extra-usage blocking disabled (extra usage is allowed)",
"claudeExtraUsageBlockingEnabled": "Claude extra-usage blocking enabled (extra usage will be blocked)",
"claudeRoutingPreferenceDisabled": "Unprefixed Claude models no longer prefer Claude Code",
"claudeRoutingPreferenceEnabled": "Unprefixed Claude models now prefer Claude Code",
"clearMediaFilter": "Clear",
"cliproxyRoutingDisabled": "Requests now use native OmniRoute (direct)",
"cliproxyRoutingEnabled": "Requests now route through CLIProxyAPI (deeper emulation)",
"codexLimitPolicyUpdated": "Codex limit policy updated",
"codexServiceModeUpdated": "Codex service mode updated",
"codexServiceTierActive": "Codex {tier} service tier is active",
"codexTierFastLabel": "Fast",
"codexTierFlexLabel": "Flex",
"commandCodeApplyFailed": "Failed to apply Command Code auth",
"commandCodeApplyingApproval": "Browser approved, applying…",
"commandCodeApplyingKey": "Applying browser-approved key…",
"commandCodeApprovalInstructions": "Open the auth URL, approve access, then paste the returned key/JSON/URL below…",
"commandCodeAuthExpired": "Command Code auth expired",
"commandCodeConnected": "Command Code connected",
"commandCodeConnectionAdded": "Command Code connection added",
"commandCodeLinkExpired": "Command Code link expired",
"commandCodeOpeningStudio": "Opening Command Code Studio…",
"commandCodePopupBlocked": "Popup blocked. Please allow popups and try Command Code Connect again.",
"commandCodeStartFailed": "Failed to start Command Code auth",
"connectionDeleted": "Connection deleted",
"connectionFallback": "connection",
"coolingConnectionsDescription": "These connections returned a 429 (rate-limit) on their last request. OmniRoute will skip them until the timer expires — no manual disable required.",
"coolingConnectionsTitle": "Currently cooling ({count})",
"failedDeleteAlias": "Failed to delete alias",
"failedDeleteConnection": "Failed to delete connection",
"failedDistributeProxies": "Failed to distribute proxies.",
"failedSaveModelEndpointSettings": "Failed to save model endpoint settings",
"failedUpdateClaudeExtraUsagePolicy": "Failed to update Claude extra-usage policy",
"failedUpdateClaudeRoutingPreference": "Failed to update Claude Code routing preference",
"failedUpdateCliproxyRouting": "Failed to update CLIProxyAPI routing",
"failedUpdateCodexLimitPolicy": "Failed to update Codex limit policy",
"failedUpdateCodexServiceMode": "Failed to update Codex service mode",
"filterByMedia": "Media",
"freeBadge": "Free",
"kimiCodeApiKeyLabel": "Kimi Code API Key",
"modelTestFailed": "Model test failed",
"modelTestNetworkError": "Network error testing model",
"networkError": "Network error",
"networkErrorDeletingAlias": "Network error deleting alias",
"networkErrorSettingAlias": "Network error setting alias",
"noProvidersMatch": "No providers match your search.",
"noSavedProxies": "No saved proxies found. Add proxies in Settings → Proxy first.",
"pageLoadErrorDescription": "We could not load provider data right now. Check your connection and try again.",
"pageLoadErrorId": "Error ID: {id}",
"pageLoadErrorRetry": "Try Again",
"pageLoadErrorTitle": "Failed to load providers",
"playgroundTitle": "Playground",
"providerDetailConnectionFlexActive": "Codex flex service tier is active for this connection",
"providerDetailConnectionPriorityActive": "Codex priority service tier is active for this connection",
"providerDetailGlobalFlexActive": "Global Codex flex service tier is active",
"providerDetailGlobalPriorityActive": "Global Codex priority service tier is active",
"proxiesDistributed": "Distributed {assigned} proxy assignment(s) across {tagLabel}{total} connection(s).",
"rerankEndpoint": "Rerank",
"savedModelEndpointSettings": "Saved model endpoint settings",
"searchByModelAria": "Search by model",
"selectSupportedEndpoint": "Select at least one supported endpoint"
"anonymousFallbackTitle": "Anonymous fallback",
"anonymousFallbackDesc": "When all configured connections are exhausted (quota, credits, or expiry), temporarily use this provider's keyless tier. Turn off to skip this provider instead of sending anonymous requests — recommended when the keyless tier rejects them (401).",
"anonymousFallbackEnabled": "Anonymous fallback enabled for {provider}",
"anonymousFallbackDisabled": "Anonymous fallback disabled for {provider} — exhausted connections will skip this provider",
"anonymousFallbackUpdateFailed": "Failed to update anonymous fallback setting",
"batchDeleteFailed": "Batch delete failed",
"batchDeleteNetworkError": "Network error during batch delete",
"batchUpdateFailed": "Batch update failed",
"batchUpdateNetworkError": "Network error during batch update",
"categoryAudio": "Audio",
"categoryCloudAgent": "Cloud Agent",
"categoryIde": "IDE",
"categoryLocal": "Local",
"categorySearch": "Search",
"categoryWebCookie": "Web Cookie",
"claudeExtraUsageBlockingDisabled": "Claude extra-usage blocking disabled (extra usage is allowed)",
"claudeExtraUsageBlockingEnabled": "Claude extra-usage blocking enabled (extra usage will be blocked)",
"claudeRoutingPreferenceDisabled": "Unprefixed Claude models no longer prefer Claude Code",
"claudeRoutingPreferenceEnabled": "Unprefixed Claude models now prefer Claude Code",
"clearMediaFilter": "Clear",
"cliproxyRoutingDisabled": "Requests now use native OmniRoute (direct)",
"cliproxyRoutingEnabled": "Requests now route through CLIProxyAPI (deeper emulation)",
"codexLimitPolicyUpdated": "Codex limit policy updated",
"codexServiceModeUpdated": "Codex service mode updated",
"codexServiceTierActive": "Codex {tier} service tier is active",
"codexTierFastLabel": "Fast",
"codexTierFlexLabel": "Flex",
"commandCodeApplyFailed": "Failed to apply Command Code auth",
"commandCodeApplyingApproval": "Browser approved, applying…",
"commandCodeApplyingKey": "Applying browser-approved key…",
"commandCodeApprovalInstructions": "Open the auth URL, approve access, then paste the returned key/JSON/URL below…",
"commandCodeAuthExpired": "Command Code auth expired",
"commandCodeConnected": "Command Code connected",
"commandCodeConnectionAdded": "Command Code connection added",
"commandCodeLinkExpired": "Command Code link expired",
"commandCodeOpeningStudio": "Opening Command Code Studio…",
"commandCodePopupBlocked": "Popup blocked. Please allow popups and try Command Code Connect again.",
"commandCodeStartFailed": "Failed to start Command Code auth",
"connectionDeleted": "Connection deleted",
"connectionFallback": "connection",
"coolingConnectionsDescription": "These connections returned a 429 (rate-limit) on their last request. OmniRoute will skip them until the timer expires — no manual disable required.",
"coolingConnectionsTitle": "Currently cooling ({count})",
"failedDeleteAlias": "Failed to delete alias",
"failedDeleteConnection": "Failed to delete connection",
"failedDistributeProxies": "Failed to distribute proxies.",
"failedSaveModelEndpointSettings": "Failed to save model endpoint settings",
"failedUpdateClaudeExtraUsagePolicy": "Failed to update Claude extra-usage policy",
"failedUpdateClaudeRoutingPreference": "Failed to update Claude Code routing preference",
"failedUpdateCliproxyRouting": "Failed to update CLIProxyAPI routing",
"failedUpdateCodexLimitPolicy": "Failed to update Codex limit policy",
"failedUpdateCodexServiceMode": "Failed to update Codex service mode",
"filterByMedia": "Media",
"freeBadge": "Free",
"kimiCodeApiKeyLabel": "Kimi Code API Key",
"modelTestFailed": "Model test failed",
"modelTestNetworkError": "Network error testing model",
"networkError": "Network error",
"networkErrorDeletingAlias": "Network error deleting alias",
"networkErrorSettingAlias": "Network error setting alias",
"noProvidersMatch": "No providers match your search.",
"noSavedProxies": "No saved proxies found. Add proxies in Settings → Proxy first.",
"pageLoadErrorDescription": "We could not load provider data right now. Check your connection and try again.",
"pageLoadErrorId": "Error ID: {id}",
"pageLoadErrorRetry": "Try Again",
"pageLoadErrorTitle": "Failed to load providers",
"playgroundTitle": "Playground",
"providerDetailConnectionFlexActive": "Codex flex service tier is active for this connection",
"providerDetailConnectionPriorityActive": "Codex priority service tier is active for this connection",
"providerDetailGlobalFlexActive": "Global Codex flex service tier is active",
"providerDetailGlobalPriorityActive": "Global Codex priority service tier is active",
"proxiesDistributed": "Distributed {assigned} proxy assignment(s) across {tagLabel}{total} connection(s).",
"rerankEndpoint": "Rerank",
"savedModelEndpointSettings": "Saved model endpoint settings",
"searchByModelAria": "Search by model",
"selectSupportedEndpoint": "Select at least one supported endpoint",
"antigravityClientProfileHarness": "Harness / CLI"
},
"settings": {
"title": "Settings",
@@ -6657,78 +6659,78 @@
"NEEDS_CORE_NOT_CONFIGURED": "This subscription has nodes that need a local proxy core (SS/VMess/Trojan/VLESS); they are not routed until you configure the local-core SOCKS5 endpoint.",
"NO_USABLE_NODES": "Subscription yielded no usable nodes (http/https/socks5 or nodes with a local core endpoint)."
},
"description": "Paste your proxy subscription link. Once enabled, traffic is routed through the proxy pool in global or rule (specified Provider) mode. Subscription nodes are automatically synced into the proxy pool and reuse existing polling, health-check, and anti-leak mechanisms.",
"addSubscription": "Add Subscription",
"newSubscription": "Add Subscription",
"editSubscription": "Edit Subscription",
"name": "Name",
"namePlaceholder": "e.g. My Subscription A",
"url": "Subscription URL",
"urlPlaceholder": "https://.../subscribe?token=...",
"mode": "Mode",
"globalMode": "Global Mode",
"ruleMode": "Rule Mode",
"globalModeDesc": "All Provider traffic goes through this subscription's proxy pool.",
"ruleModeDesc": "Only selected Providers' traffic goes through the proxy; the rest connect directly.",
"localCoreEndpoint": "Local Core SOCKS5/HTTP Endpoint (Optional)",
"localCoreEndpointPlaceholder": "socks5://127.0.0.1:1080",
"localCoreEndpointDesc": "Only accepts 127.0.0.1 / localhost (SS/VMess/Trojan/VLESS require a local sing-box/clash core).",
"routeByProvider": "Route by Provider (multi-select)",
"loadingProviders": "Loading Provider list…",
"autoRefreshInterval": "Auto Refresh Interval (minutes)",
"enableAfterCreate": "Enable on creation (sync and take effect immediately)",
"saving": "Saving…",
"saveChanges": "Save Changes",
"createSubscription": "Create Subscription",
"loading": "Loading…",
"noSubscriptions": "No subscriptions yet. Click \"Add Subscription\" to get started.",
"statusOk": "OK",
"statusError": "Error",
"statusEmpty": "Empty",
"global": "Global",
"rule": "Rule",
"enabled": "Enabled",
"disabled": "Disabled",
"nodeCount": "Nodes: {count}",
"needsCoreCount": "{count} need local core",
"lastSynced": "Last synced: {time}",
"consecutiveFailures": "{count} consecutive failures",
"lastError": "Last error: {time}",
"coreHintTitle": "This subscription has {count} nodes that require a local proxy core (SS / VMess / Trojan / VLESS, etc.) and are currently not routed.",
"coreHintDesc": "These protocols cannot be forwarded directly by OmniRoute. Please start a sing-box or clash (Clash.Meta) core on your machine, expose it as a SOCKS5/HTTP endpoint, and fill it in via Edit (only 127.0.0.1 / localhost is accepted).",
"copy": "Copy",
"goConfigure": "Configure",
"disable": "Disable",
"enable": "Enable",
"refreshNodes": "Refresh Nodes",
"edit": "Edit",
"delete": "Delete",
"confirmDelete": "Are you sure you want to delete subscription \"{name}\"? Associated proxy nodes will also be removed.",
"nameRequired": "Please enter a name",
"urlRequired": "Please enter a subscription URL",
"ruleModeProviderRequired": "Please select at least one Provider in rule mode",
"saveFailed": "Save failed",
"loadFailed": "Failed to load subscription list",
"toggleFailed": "Failed to toggle switch",
"refreshFailed": "Failed to refresh",
"deleteFailed": "Failed to delete",
"add": "Add",
"cancel": "Cancel",
"configure": "Configure",
"copyEndpoint": "Copy Endpoint",
"coreEndpointHint": "Core Endpoint Hint",
"coreNodesHint": "Core Nodes Hint",
"create": "Create",
"deleteConfirm": "Delete Confirm",
"empty": "Empty",
"globalModeDescription": "Global Mode Description",
"localCoreHint": "Local Core Hint",
"nodeSummary": "Node Summary",
"providerRequired": "Provider Required",
"providerRouting": "Provider Routing",
"refresh": "Refresh",
"refreshInterval": "Refresh Interval",
"ruleModeDescription": "Rule Mode Description"
"description": "Paste your proxy subscription link. Once enabled, traffic is routed through the proxy pool in global or rule (specified Provider) mode. Subscription nodes are automatically synced into the proxy pool and reuse existing polling, health-check, and anti-leak mechanisms.",
"addSubscription": "Add Subscription",
"newSubscription": "Add Subscription",
"editSubscription": "Edit Subscription",
"name": "Name",
"namePlaceholder": "e.g. My Subscription A",
"url": "Subscription URL",
"urlPlaceholder": "https://.../subscribe?token=...",
"mode": "Mode",
"globalMode": "Global Mode",
"ruleMode": "Rule Mode",
"globalModeDesc": "All Provider traffic goes through this subscription's proxy pool.",
"ruleModeDesc": "Only selected Providers' traffic goes through the proxy; the rest connect directly.",
"localCoreEndpoint": "Local Core SOCKS5/HTTP Endpoint (Optional)",
"localCoreEndpointPlaceholder": "socks5://127.0.0.1:1080",
"localCoreEndpointDesc": "Only accepts 127.0.0.1 / localhost (SS/VMess/Trojan/VLESS require a local sing-box/clash core).",
"routeByProvider": "Route by Provider (multi-select)",
"loadingProviders": "Loading Provider list…",
"autoRefreshInterval": "Auto Refresh Interval (minutes)",
"enableAfterCreate": "Enable on creation (sync and take effect immediately)",
"saving": "Saving…",
"saveChanges": "Save Changes",
"createSubscription": "Create Subscription",
"loading": "Loading…",
"noSubscriptions": "No subscriptions yet. Click \"Add Subscription\" to get started.",
"statusOk": "OK",
"statusError": "Error",
"statusEmpty": "Empty",
"global": "Global",
"rule": "Rule",
"enabled": "Enabled",
"disabled": "Disabled",
"nodeCount": "Nodes: {count}",
"needsCoreCount": "{count} need local core",
"lastSynced": "Last synced: {time}",
"consecutiveFailures": "{count} consecutive failures",
"lastError": "Last error: {time}",
"coreHintTitle": "This subscription has {count} nodes that require a local proxy core (SS / VMess / Trojan / VLESS, etc.) and are currently not routed.",
"coreHintDesc": "These protocols cannot be forwarded directly by OmniRoute. Please start a sing-box or clash (Clash.Meta) core on your machine, expose it as a SOCKS5/HTTP endpoint, and fill it in via Edit (only 127.0.0.1 / localhost is accepted).",
"copy": "Copy",
"goConfigure": "Configure",
"disable": "Disable",
"enable": "Enable",
"refreshNodes": "Refresh Nodes",
"edit": "Edit",
"delete": "Delete",
"confirmDelete": "Are you sure you want to delete subscription \"{name}\"? Associated proxy nodes will also be removed.",
"nameRequired": "Please enter a name",
"urlRequired": "Please enter a subscription URL",
"ruleModeProviderRequired": "Please select at least one Provider in rule mode",
"saveFailed": "Save failed",
"loadFailed": "Failed to load subscription list",
"toggleFailed": "Failed to toggle switch",
"refreshFailed": "Failed to refresh",
"deleteFailed": "Failed to delete",
"add": "Add",
"cancel": "Cancel",
"configure": "Configure",
"copyEndpoint": "Copy Endpoint",
"coreEndpointHint": "Core Endpoint Hint",
"coreNodesHint": "Core Nodes Hint",
"create": "Create",
"deleteConfirm": "Delete Confirm",
"empty": "Empty",
"globalModeDescription": "Global Mode Description",
"localCoreHint": "Local Core Hint",
"nodeSummary": "Node Summary",
"providerRequired": "Provider Required",
"providerRouting": "Provider Routing",
"refresh": "Refresh",
"refreshInterval": "Refresh Interval",
"ruleModeDescription": "Rule Mode Description"
},
"bulkHealthcheck": "Bulk Healthcheck",
"bulkHealthcheckDesc": "Test all configured proxies against a target URL to find which ones work.",
@@ -6764,7 +6766,7 @@
"denoRelayOrgDomainRequired": "Organization domain is required",
"denoRelayDeployFailed": "Deno Deploy failed",
"denoRelayTokenHint": "Organization token (prefix ddo_) from console.deno.com → Organization → Settings → Organization Tokens. Used once for deploy and never stored.",
"denoRelayOrgDomainHint": "Your Deno Deploy organization's default domain (e.g. acme.deno.net). The relay will be reachable at https://&lt;app-name&gt;.&lt;org-slug&gt;.deno.net.",
"denoRelayOrgDomainHint": "Your Deno Deploy organization's default domain (e.g. acme.deno.net). The relay will be reachable at https://<app-name>.<org-slug>.deno.net.",
"proxyFreePoolFilterProtocol": "Filter by protocol",
"proxyFreePoolProtocol": "Protocol",
"proxyFreePoolCountryPlaceholder": "Country (e.g. US)",
@@ -7903,9 +7905,9 @@
"resilienceEnableServerWaitDesc": "When enabled, OmniRoute waits for the first cooldown to expire and retries automatically.",
"resilienceMaxAttempts": "Maximum attempts",
"resilienceMaxWaitPerAttempt": "Maximum wait per attempt",
"resilienceComboCooldownWaitTitle": "Combo cooldown wait",
"resilienceComboCooldownWaitDesc": "For all combo strategies: wait out a short transient cooldown and re-dispatch instead of returning a 429 immediately. Never waits on quota_exhausted.",
"resilienceComboCooldownWaitToggleDesc": "All combo strategies; never waits on quota_exhausted.",
"resilienceComboCooldownWaitTitle": "Quota-share combo cooldown wait",
"resilienceComboCooldownWaitDesc": "For quota-share combos only: wait out a short transient cooldown and re-dispatch instead of returning a 429 immediately. Never waits on quota_exhausted.",
"resilienceComboCooldownWaitToggleDesc": "Quota-share combos only; never waits on quota_exhausted.",
"resilienceComboCooldownMaxWaitMs": "Maximum wait per attempt",
"resilienceComboCooldownBudgetMs": "Total wait budget",
"resilienceQuotaShareConcurrencyTitle": "Quota-share per-connection concurrency",
@@ -8001,138 +8003,138 @@
"enableCredentialRedactionDesc": "Scrubs API keys, tokens, private keys, and JWTs from messages, tool calls, and responses.",
"pricingAutoSyncDisabled": "Automatic Sync Disabled",
"pricingAutoSyncEnabled": "Automatic Sync Enabled",
"modalityBridgeIntro": "Bridge multimodal content to text before it reaches text-only models. Vision is live; Audio arrives with the AudioBridge; Video is on the roadmap.",
"modalityBridgeVisionTab": "Vision",
"modalityBridgeAudioTab": "Audio",
"modalityBridgeVideoTab": "Video",
"modalityBridgeSubTabsAria": "Modality Bridge sections",
"modalityBridgeVisionTitle": "Vision Bridge",
"modalityBridgeVisionDesc": "Describe images with a vision model and continue with the user's chosen text model.",
"modalityBridgeMode": "Mode",
"modalityBridgeModeAuto": "Auto (recommended)",
"modalityBridgeModeAutoHint": "Legacy heuristic: reroute individual models without credentials; describe otherwise.",
"modalityBridgeModeDescribe": "Always describe",
"modalityBridgeModeDescribeHint": "The model you chose always answers; images are replaced by text descriptions.",
"modalityBridgeModeReroute": "Always reroute",
"modalityBridgeModeRerouteHint": "Send the whole request to the best vision-capable model (falls back to describe when none is usable).",
"modalityBridgeVisionModel": "Vision model",
"modalityBridgeVisionModelAuto": "Auto (best available)",
"modalityBridgeTaskAware": "Task-aware description",
"modalityBridgeTaskAwareDesc": "Include the user's question as focus so the vision model describes what matters and transcribes visible text.",
"modalityBridgePrompt": "Description prompt",
"modalityBridgeAdvanced": "Advanced",
"modalityBridgeTimeoutMs": "Timeout (ms)",
"modalityBridgeMaxImages": "Max images per request",
"modalityBridgeCacheEnabled": "Cache descriptions",
"modalityBridgeCacheEnabledDesc": "Reuse descriptions for identical images (SHA-256 keyed, in-memory).",
"modalityBridgeCacheTtlMinutes": "Cache TTL (minutes)",
"modalityBridgeCacheMaxEntries": "Cache max entries",
"modalityBridgeStatsBridged": "bridged",
"modalityBridgeStatsCacheHits": "cache hits",
"modalityBridgeStatsFailures": "failures",
"modalityBridgeStatsLastUsed": "last used",
"modalityBridgeStatsNever": "never",
"modalityBridgeTestButton": "Test with sample image",
"modalityBridgeTestRunning": "Testing…",
"modalityBridgeTestOk": "Bridge OK — {count} image(s) described by {model}",
"modalityBridgeTestReroute": "Bridge rerouted the request to {model}",
"modalityBridgeTestNoop": "Bridge did not activate (model may support vision natively or bridge is disabled)",
"modalityBridgeTestError": "Test failed: {message}",
"modalityBridgeAudioComingSoon": "The Audio bridge (speech → text via /v1/audio/transcriptions) ships in the next release. Its settings keys are already reserved.",
"modalityBridgeVideoComingSoon": "Video bridging (frame sampling + captioning) is on the backlog — see issue #9760.",
"modalityBridgeMovedTitle": "Vision Bridge moved",
"modalityBridgeMovedBody": "Vision Bridge settings now live in the dedicated Modality Bridge page.",
"modalityBridgeMovedCta": "Open Modality Bridge settings",
"modalityBridgeAudioTitle": "Audio Bridge",
"modalityBridgeAudioDesc": "Transcribe audio with a speech-to-text model before continuing with the chosen text model.",
"modalityBridgeAudioEnabled": "Enable Audio Bridge",
"modalityBridgeAudioEnabledDesc": "Replace audio parts with transcripts when the target model cannot process audio.",
"modalityBridgeAudioModel": "Speech-to-text model",
"modalityBridgeAudioModelAuto": "Auto (first connected STT provider)",
"modalityBridgeAudioMaxClips": "Max audio clips per request",
"modalityBridgeAudioTestButton": "Test with sample audio",
"modalityBridgeAudioTestRunning": "Testing audio…",
"modalityBridgeAudioTestOk": "Audio Bridge OK — {count} clip(s) transcribed by {model}",
"modalityBridgeAudioTestNoop": "Audio Bridge did not activate (the target may support audio, no STT provider is connected, or the bridge is disabled)",
"modalityBridgeAudioTestError": "Audio test failed: {message}",
"modelRoutingDescriptionPlaceholder": "Route Opus models to frontier combo",
"cliproxyapiFallbackCodes": "Cliproxyapi Fallback Codes",
"cliproxyapiFallbackDescription": "Cliproxyapi Fallback Description",
"cliproxyapiHealthLabel": "Cliproxyapi Health Label",
"cliproxyapiImportFailed": "Cliproxyapi Import Failed",
"cliproxyapiImportResult": "Cliproxyapi Import Result",
"cliproxyapiInvalidUrl": "Cliproxyapi Invalid URL",
"cliproxyapiLifecycleNoticeAfter": "Cliproxyapi Lifecycle Notice After",
"cliproxyapiLifecycleNoticeBefore": "Cliproxyapi Lifecycle Notice Before",
"cliproxyapiLifecycleNoticeLink": "Cliproxyapi Lifecycle Notice Link",
"cliproxyapiPortLabel": "Cliproxyapi Port Label",
"cliproxyapiStatusLabel": "Cliproxyapi Status Label",
"cliproxyapiVersionLabel": "Cliproxyapi Version Label",
"collection": "Collection",
"errorPage": {
"modalityBridgeIntro": "Bridge multimodal content to text before it reaches text-only models. Vision is live; Audio arrives with the AudioBridge; Video is on the roadmap.",
"modalityBridgeVisionTab": "Vision",
"modalityBridgeAudioTab": "Audio",
"modalityBridgeVideoTab": "Video",
"modalityBridgeSubTabsAria": "Modality Bridge sections",
"modalityBridgeVisionTitle": "Vision Bridge",
"modalityBridgeVisionDesc": "Describe images with a vision model and continue with the user's chosen text model.",
"modalityBridgeMode": "Mode",
"modalityBridgeModeAuto": "Auto (recommended)",
"modalityBridgeModeAutoHint": "Legacy heuristic: reroute individual models without credentials; describe otherwise.",
"modalityBridgeModeDescribe": "Always describe",
"modalityBridgeModeDescribeHint": "The model you chose always answers; images are replaced by text descriptions.",
"modalityBridgeModeReroute": "Always reroute",
"modalityBridgeModeRerouteHint": "Send the whole request to the best vision-capable model (falls back to describe when none is usable).",
"modalityBridgeVisionModel": "Vision model",
"modalityBridgeVisionModelAuto": "Auto (best available)",
"modalityBridgeTaskAware": "Task-aware description",
"modalityBridgeTaskAwareDesc": "Include the user's question as focus so the vision model describes what matters and transcribes visible text.",
"modalityBridgePrompt": "Description prompt",
"modalityBridgeAdvanced": "Advanced",
"modalityBridgeTimeoutMs": "Timeout (ms)",
"modalityBridgeMaxImages": "Max images per request",
"modalityBridgeCacheEnabled": "Cache descriptions",
"modalityBridgeCacheEnabledDesc": "Reuse descriptions for identical images (SHA-256 keyed, in-memory).",
"modalityBridgeCacheTtlMinutes": "Cache TTL (minutes)",
"modalityBridgeCacheMaxEntries": "Cache max entries",
"modalityBridgeStatsBridged": "bridged",
"modalityBridgeStatsCacheHits": "cache hits",
"modalityBridgeStatsFailures": "failures",
"modalityBridgeStatsLastUsed": "last used",
"modalityBridgeStatsNever": "never",
"modalityBridgeTestButton": "Test with sample image",
"modalityBridgeTestRunning": "Testing…",
"modalityBridgeTestOk": "Bridge OK — {count} image(s) described by {model}",
"modalityBridgeTestReroute": "Bridge rerouted the request to {model}",
"modalityBridgeTestNoop": "Bridge did not activate (model may support vision natively or bridge is disabled)",
"modalityBridgeTestError": "Test failed: {message}",
"modalityBridgeAudioComingSoon": "The Audio bridge (speech → text via /v1/audio/transcriptions) ships in the next release. Its settings keys are already reserved.",
"modalityBridgeVideoComingSoon": "Video bridging (frame sampling + captioning) is on the backlog — see issue #9760.",
"modalityBridgeMovedTitle": "Vision Bridge moved",
"modalityBridgeMovedBody": "Vision Bridge settings now live in the dedicated Modality Bridge page.",
"modalityBridgeMovedCta": "Open Modality Bridge settings",
"modalityBridgeAudioTitle": "Audio Bridge",
"modalityBridgeAudioDesc": "Transcribe audio with a speech-to-text model before continuing with the chosen text model.",
"modalityBridgeAudioEnabled": "Enable Audio Bridge",
"modalityBridgeAudioEnabledDesc": "Replace audio parts with transcripts when the target model cannot process audio.",
"modalityBridgeAudioModel": "Speech-to-text model",
"modalityBridgeAudioModelAuto": "Auto (first connected STT provider)",
"modalityBridgeAudioMaxClips": "Max audio clips per request",
"modalityBridgeAudioTestButton": "Test with sample audio",
"modalityBridgeAudioTestRunning": "Testing audio…",
"modalityBridgeAudioTestOk": "Audio Bridge OK — {count} clip(s) transcribed by {model}",
"modalityBridgeAudioTestNoop": "Audio Bridge did not activate (the target may support audio, no STT provider is connected, or the bridge is disabled)",
"modalityBridgeAudioTestError": "Audio test failed: {message}",
"modelRoutingDescriptionPlaceholder": "Route Opus models to frontier combo",
"cliproxyapiFallbackCodes": "Cliproxyapi Fallback Codes",
"cliproxyapiFallbackDescription": "Cliproxyapi Fallback Description",
"cliproxyapiHealthLabel": "Cliproxyapi Health Label",
"cliproxyapiImportFailed": "Cliproxyapi Import Failed",
"cliproxyapiImportResult": "Cliproxyapi Import Result",
"cliproxyapiInvalidUrl": "Cliproxyapi Invalid URL",
"cliproxyapiLifecycleNoticeAfter": "Cliproxyapi Lifecycle Notice After",
"cliproxyapiLifecycleNoticeBefore": "Cliproxyapi Lifecycle Notice Before",
"cliproxyapiLifecycleNoticeLink": "Cliproxyapi Lifecycle Notice Link",
"cliproxyapiPortLabel": "Cliproxyapi Port Label",
"cliproxyapiStatusLabel": "Cliproxyapi Status Label",
"cliproxyapiVersionLabel": "Cliproxyapi Version Label",
"collection": "Collection",
"errorPage": {
"description": "We could not load settings right now. Please retry in a few seconds.",
"errorId": "Error ID: {id}",
"retry": "Try Again",
"title": "Failed to load settings"
},
"host": "Host",
"notInstalled": "Not installed",
"oneproxyActions": "Oneproxy Actions",
"oneproxyActive": "Oneproxy Active",
"oneproxyAnonymity": "Oneproxy Anonymity",
"oneproxyCountry": "Oneproxy Country",
"oneproxyDelete": "Oneproxy Delete",
"oneproxyEmpty": "Oneproxy Empty",
"oneproxyHost": "Oneproxy Host",
"oneproxyLatency": "Oneproxy Latency",
"oneproxyProtocol": "Oneproxy Protocol",
"oneproxyQuality": "Oneproxy Quality",
"oneproxySyncFailed": "Sync failed: {error}",
"oneproxySyncSuccess": "Synced {total} proxies ({added} new, {updated} updated)",
"proxyDocumentationSocks5DescAfter": "Proxy Documentation Socks5 Desc After",
"proxyFreePoolAddProxy": "Proxy Free Pool Add Proxy",
"proxyFreePoolAdding": "Proxy Free Pool Adding",
"proxyFreePoolSelectProxy": "Proxy Free Pool Select Proxy",
"proxyStatusActive": "Proxy Status Active",
"proxyStatusInactive": "Proxy Status Inactive",
"routingAddEntry": "Add entry",
"settingSaveFailed": "Setting Save Failed",
"settingSaved": "Setting Saved",
"skillsmpApiKeyHintAfter": ". Rate limit: {limit} requests/day.",
"skillsmpApiKeyHintBefore": "Get your API key from",
"syncFailed": "Sync failed",
"unhealthy": "Unhealthy",
"oneproxyDescription": "Fetch and rotate free validated proxies from the 1proxy community platform",
"oneproxySyncing": "Syncing...",
"oneproxySyncNow": "Sync Now",
"oneproxyClearAll": "Clear All",
"oneproxyGoogle": "Google",
"oneproxyClearAllConfirm": "Clear all 1proxy proxies?",
"memorySkillsSkillsmpDescription": "Connect to SkillsMP to discover and install skills from the marketplace.",
"memorySkillsActiveProviderDescription": "Choose which provider the Skills page uses for search and install.",
"memorySkillsSkillsmpProviderTitle": "SkillsMP Marketplace",
"memorySkillsSkillsmpProviderDescription": "Authenticated marketplace (uses your SkillsMP API key).",
"memorySkillsSkillsshProviderTitle": "skills.sh Directory",
"memorySkillsSkillsshProviderDescription": "Public directory provider (no API key required).",
"routingCcBridgeCatalogName": "Anthropic-compatible CC bridge",
"routingClaudeProviderName": "Claude (OAuth)",
"routingClaudeProviderDescription": "Native Claude provider with OAuth-issued tokens.",
"routingCcBridgeName": "Claude-Code Bridge",
"routingCcBridgeDescription": "Relay endpoints using API keys (anthropic-compatible-cc-*).",
"routingCustomProviderDescription": "Custom provider.",
"routingUnknownOpKind": "Unknown op kind: {kind}",
"routingInvalidJson": "Invalid JSON: {error}",
"routingConfigMustBeObject": "Config must be a JSON object",
"routingEnabledMustBeBoolean": "`enabled` must be true or false",
"routingPipelineMustBeArray": "`pipeline` must be an array of ops",
"routingPipelineTooLong": "Pipeline cannot exceed 50 ops",
"routingOpMissingKind": "Op #{index}: missing or invalid `kind`",
"routingOpUnknownKind": "Op #{index}: unknown kind \"{kind}\"",
"routingJsonEditorHide": "Hide JSON editor",
"routingJsonEditorImportExport": "Import / export JSON",
"routingJsonEditorLabel": "JSON (edit and apply, or paste to import)",
"routingApplyJson": "Apply JSON",
"routingTransformsFootnote": "All transform ops are idempotent on re-run. Changes take effect immediately on the next request."
"host": "Host",
"notInstalled": "Not installed",
"oneproxyActions": "Oneproxy Actions",
"oneproxyActive": "Oneproxy Active",
"oneproxyAnonymity": "Oneproxy Anonymity",
"oneproxyCountry": "Oneproxy Country",
"oneproxyDelete": "Oneproxy Delete",
"oneproxyEmpty": "Oneproxy Empty",
"oneproxyHost": "Oneproxy Host",
"oneproxyLatency": "Oneproxy Latency",
"oneproxyProtocol": "Oneproxy Protocol",
"oneproxyQuality": "Oneproxy Quality",
"oneproxySyncFailed": "Sync failed: {error}",
"oneproxySyncSuccess": "Synced {total} proxies ({added} new, {updated} updated)",
"proxyDocumentationSocks5DescAfter": "Proxy Documentation Socks5 Desc After",
"proxyFreePoolAddProxy": "Proxy Free Pool Add Proxy",
"proxyFreePoolAdding": "Proxy Free Pool Adding",
"proxyFreePoolSelectProxy": "Proxy Free Pool Select Proxy",
"proxyStatusActive": "Proxy Status Active",
"proxyStatusInactive": "Proxy Status Inactive",
"routingAddEntry": "Add entry",
"settingSaveFailed": "Setting Save Failed",
"settingSaved": "Setting Saved",
"skillsmpApiKeyHintAfter": ". Rate limit: {limit} requests/day.",
"skillsmpApiKeyHintBefore": "Get your API key from",
"syncFailed": "Sync failed",
"unhealthy": "Unhealthy",
"oneproxyDescription": "Fetch and rotate free validated proxies from the 1proxy community platform",
"oneproxySyncing": "Syncing...",
"oneproxySyncNow": "Sync Now",
"oneproxyClearAll": "Clear All",
"oneproxyGoogle": "Google",
"oneproxyClearAllConfirm": "Clear all 1proxy proxies?",
"memorySkillsSkillsmpDescription": "Connect to SkillsMP to discover and install skills from the marketplace.",
"memorySkillsActiveProviderDescription": "Choose which provider the Skills page uses for search and install.",
"memorySkillsSkillsmpProviderTitle": "SkillsMP Marketplace",
"memorySkillsSkillsmpProviderDescription": "Authenticated marketplace (uses your SkillsMP API key).",
"memorySkillsSkillsshProviderTitle": "skills.sh Directory",
"memorySkillsSkillsshProviderDescription": "Public directory provider (no API key required).",
"routingCcBridgeCatalogName": "Anthropic-compatible CC bridge",
"routingClaudeProviderName": "Claude (OAuth)",
"routingClaudeProviderDescription": "Native Claude provider with OAuth-issued tokens.",
"routingCcBridgeName": "Claude-Code Bridge",
"routingCcBridgeDescription": "Relay endpoints using API keys (anthropic-compatible-cc-*).",
"routingCustomProviderDescription": "Custom provider.",
"routingUnknownOpKind": "Unknown op kind: {kind}",
"routingInvalidJson": "Invalid JSON: {error}",
"routingConfigMustBeObject": "Config must be a JSON object",
"routingEnabledMustBeBoolean": "`enabled` must be true or false",
"routingPipelineMustBeArray": "`pipeline` must be an array of ops",
"routingPipelineTooLong": "Pipeline cannot exceed 50 ops",
"routingOpMissingKind": "Op #{index}: missing or invalid `kind`",
"routingOpUnknownKind": "Op #{index}: unknown kind \"{kind}\"",
"routingJsonEditorHide": "Hide JSON editor",
"routingJsonEditorImportExport": "Import / export JSON",
"routingJsonEditorLabel": "JSON (edit and apply, or paste to import)",
"routingApplyJson": "Apply JSON",
"routingTransformsFootnote": "All transform ops are idempotent on re-run. Changes take effect immediately on the next request."
},
"contextRtk": {
"title": "RTK Engine",
@@ -10482,7 +10484,8 @@
"gitlabDuoSetupTitle": "GitLab Duo OAuth setup",
"gitlabDuoSetupMessage": "GitLab Duo OAuth is not configured. Register an OAuth application at {applicationsUrl} with redirect URI {redirectUri} and scopes \"{scopes}\", then set {clientIdEnv} (and optionally {clientSecretEnv}) and restart.",
"gitlabDuoSetupDescription": "After the application is registered and the env vars are set on this OmniRoute instance, click Continue to start the OAuth login.",
"continue": "Continue"
"continue": "Continue",
"googleOAuthWarning": "Remote access + Google OAuth: bundled credentials only accept loopback redirects like <code>127.0.0.1</code>. The browser that approves Google must be able to reach OmniRoute on that local port, usually by opening OmniRoute locally or using an SSH/local-forward tunnel. Recommended for remote installs: on your own computer run <code>npx omniroute login antigravity</code> and paste the credential blob it prints into the field below. For fully remote use without this local callback, <a>configure your own OAuth credentials</a>."
},
"cursorAuthModal": {
"title": "Connect Cursor IDE",
@@ -12320,13 +12323,13 @@
"updateProviderFailed": "Failed to update provider",
"providerEnabled": "{provider} enabled",
"providerDisabled": "{provider} disabled",
"providerAdded": "{provider} added",
"add": "Add",
"manualApiKey": "Use a manual API key",
"createDahlTokenFailed": "Failed to create Dahl token",
"providerProxy": "Proxy",
"providerProxyConfigureHint": "Configure proxy",
"providerProxyTitleConfigured": "Proxy configured: {host}"
"providerAdded": "{provider} added",
"add": "Add",
"manualApiKey": "Use a manual API key",
"createDahlTokenFailed": "Failed to create Dahl token",
"providerProxy": "Proxy",
"providerProxyConfigureHint": "Configure proxy",
"providerProxyTitleConfigured": "Proxy configured: {host}"
},
"gamification": {
"leaderboardScopes": {
@@ -13020,14 +13023,14 @@
"testFailed": "Test failed"
},
"kimiSponsorBanner": {
"title": "Kimi (Moonshot AI) is OmniRoute's founding Open Source Friend",
"title": "Kimi (Moonshot AI) is now an official sponsor of OmniRoute",
"description": "Kimi K3 brings a 1M-token context window and frontier coding performance to OmniRoute at a fraction of the cost.",
"cta": "Get Kimi Code",
"partnerLinkNote": "Partner link",
"dismissAriaLabel": "Dismiss"
},
"featureFlagExposeFunctionalGatewayMirrorsDescription": "Advertise <gateway-alias>/<model> mirror ids on /v1/models for models whose canonical owner has no active credential but a passthrough gateway with an active credential routes them. Warning: adds catalog entries for all clients when enabled globally.",
"radarPage": {
"radarPage": {
"title": "Radar Catalog",
"subtitle": "Free model catalog enriched with community intelligence",
"loading": "Loading catalog...",
@@ -13083,7 +13086,7 @@
"campaignsUpsellCommunity": "Limited-time campaigns are a supporter extra. Everything on this page's fixed links stays free for everyone.",
"campaignsValidUntil": "Valid until {date}"
},
"radarSetupPage": {
"radarSetupPage": {
"title": "Provider Setup",
"setupTitle": "Setup: {provider}",
"setupSubtitle": "Follow the steps below to configure this provider",
@@ -13108,7 +13111,7 @@
"addConnectionDescription": "Don't have a connection yet? Add one in the providers dashboard.",
"addConnectionLink": "Go to providers →"
},
"resilienceConnections": {
"resilienceConnections": {
"title": "Connection Resilience",
"table": {
"status": "Status",
@@ -13202,12 +13205,12 @@
"degraded.source.modelLockouts": "Model Lockouts",
"degraded.source.count": "Connection Count"
},
"featureFlagCapabilityFilterEnabledDescription": "Reject requests before dispatch when the target model lacks required capabilities (vision, tools, structured output, context window). Protects direct single-provider requests that bypass the combo-layer compatibility filter.",
"capabilityFilter.visionMismatch": "Provider does not support vision for this image request",
"capabilityFilter.toolsMismatch": "Provider does not support tool calling",
"capabilityFilter.structuredOutputMismatch": "Provider does not support structured output",
"capabilityFilter.contextWindowMismatch": "Request exceeds provider context window",
"publicSystem": {
"featureFlagCapabilityFilterEnabledDescription": "Reject requests before dispatch when the target model lacks required capabilities (vision, tools, structured output, context window). Protects direct single-provider requests that bypass the combo-layer compatibility filter.",
"capabilityFilter.visionMismatch": "Provider does not support vision for this image request",
"capabilityFilter.toolsMismatch": "Provider does not support tool calling",
"capabilityFilter.structuredOutputMismatch": "Provider does not support structured output",
"capabilityFilter.contextWindowMismatch": "Request exceeds provider context window",
"publicSystem": {
"notFound": {
"title": "Page not found",
"description": "The page you're looking for doesn't exist or has been moved.",
@@ -13344,7 +13347,7 @@
}
}
},
"kiroAuthModal": {
"kiroAuthModal": {
"title": "Connect {providerLabel}",
"chooseMethod": "Choose your authentication method:",
"builderId": "AWS Builder ID",
@@ -13386,7 +13389,7 @@
"errorApiKeyImportFailed": "API key import failed",
"errorIdcStartUrlRequired": "Please enter your IDC start URL"
},
"kiroSocialOAuthModal": {
"kiroSocialOAuthModal": {
"title": "Connect {providerLabel} via {providerName}",
"errorStartAuthorization": "Failed to start authorization",
"errorAuthorizationExpired": "Authorization expired. Start the login flow again.",
@@ -13405,7 +13408,7 @@
"errorTitle": "Connection Failed",
"close": "Close"
},
"traeAuthModal": {
"traeAuthModal": {
"errorAuthorizationFailed": "Authorization failed",
"errorPopupBlocked": "Popup blocked — allow popups for this site, or paste the token manually below.",
"errorPopupClosed": "Authorization window was closed before completing.",
@@ -13431,14 +13434,14 @@
"importToken": "Import Token",
"cancel": "Cancel"
},
"sharedComponents": {
"sharedComponents": {
"distributeProxies": {
"distributing": "Distributing...",
"complete": "Complete",
"defaultLabel": "Distribute Proxies"
}
},
"providerTest": {
"providerTest": {
"dialogLabel": "Test {provider}",
"deprecated": "deprecated",
"risk": "risk",
@@ -13473,7 +13476,7 @@
"tokens": "Tokens"
}
},
"proxyLog": {
"proxyLog": {
"detailAriaLabel": "Proxy log detail",
"event": "Proxy Event",
"close": "Close proxy detail modal",
@@ -13491,7 +13494,7 @@
"error": "Error",
"configuration": "Proxy Configuration"
},
"requestTimeline": {
"requestTimeline": {
"title": "Request Timeline",
"modes": {
"follow": "Follow",
@@ -13516,7 +13519,7 @@
"unknownModel": "unknown",
"pending": "pending"
},
"metadata": {
"metadata": {
"compressionTitle": "Compression",
"compressionDescription": "Configure context compression settings to reduce token usage and costs.",
"relayTitle": "OmniRoute — Relay Proxies",
@@ -13553,6 +13556,25 @@
"cancelConfirmMessage": "The hub will abort the execution on the runner. This cannot be undone.",
"cancelFailed": "The hub refused the cancellation",
"close": "Close",
"error": "Error"
"error": "Error",
"faroTitle": "Faro — fleet spokesperson",
"faroSubtitle": "Chat and voice, anchored in real fleet events. Destructive commands always ask for confirmation.",
"faroEmpty": "Ask about the fleet — e.g. \"how is the fleet?\"",
"faroPending": "Faro is asking for confirmation",
"faroPlaceholder": "talk to Faro…",
"faroSend": "send",
"faroOffline": "Faro (spokesperson) is offline",
"yes": "Yes",
"no": "No",
"pushToTalk": "Hold to talk",
"speakAnswers": "speak answers",
"voiceModels": "Voice models (provider/model of this OmniRoute)",
"voiceIdle": "talk",
"voiceListening": "listening…",
"voiceThinking": "thinking…",
"voiceSpeaking": "speaking…",
"sttFailed": "Transcription failed (check the STT model/provider)",
"ttsFailed": "Speech synthesis failed (check the TTS model/provider)",
"micDenied": "Microphone unavailable or permission denied"
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
/**
* Server-side proxy to Faro, the OmniConductor spokesperson (Conductor PRD RF4).
*
* Faro's `/ask` requires a valid hub credential (Bearer) — that token lives only
* in server env, so the browser talks to our /api/conductor/ask route, never to
* Faro directly. The response is whitelisted to {text, pending}: `pending` set
* means Faro is asking for confirmation (the UI offers Sim/Não); the safety gate
* itself lives in Faro's engine and is never bypassed here.
*/
import { z } from "zod";
const faroResponseSchema = z.object({
text: z.string(),
pending: z.unknown().nullish(),
});
export interface FaroAnswer {
ok: boolean;
text: string;
pending: unknown;
}
export interface FaroProxyOptions {
fetchImpl?: typeof fetch;
}
const DEFAULT_FARO_URL = "http://127.0.0.1:7920";
export async function askFaro(message: string, opts: FaroProxyOptions = {}): Promise<FaroAnswer> {
const base = process.env.CONDUCTOR_SPOKESPERSON_URL?.trim() || DEFAULT_FARO_URL;
const token = process.env.CONDUCTOR_HUB_TOKEN?.trim() ?? "";
try {
const doFetch = opts.fetchImpl ?? fetch;
const res = await doFetch(`${base}/ask`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify({ message }),
});
if (!res.ok) return { ok: false, text: "", pending: null };
const parsed = faroResponseSchema.parse(await res.json());
return { ok: true, text: parsed.text, pending: parsed.pending ?? null };
} catch {
return { ok: false, text: "", pending: null };
}
}

View File

@@ -155,6 +155,51 @@ export async function getConductorTaskDetail(
return null;
}
}
export interface DelegationInput {
repoUrl: string;
prompt: string;
baseRef?: string;
mode?: string;
cli?: string;
model?: string;
}
/**
* Delegates work to the fleet: translates an external A2A task into the hub's
* `POST /v1/tasks` (Conductor PRD RF5). Uses the orchestrator credential when
* set (CONDUCTOR_ORCHESTRATOR_TOKEN), falling back to the hub token. States
* flow back through the RF1 mirror — this call only creates.
*/
export async function createConductorTask(
input: DelegationInput,
opts: HubProxyOptions = {}
): Promise<{ ok: boolean; status: number; task_id?: string }> {
const cfg = hubConfig();
if (!cfg) return { ok: false, status: 503 };
const token = process.env.CONDUCTOR_ORCHESTRATOR_TOKEN?.trim() || cfg.token;
const body: Record<string, unknown> = {
repo: { url: input.repoUrl, base_ref: input.baseRef?.trim() || "main" },
spec: { prompt: input.prompt },
mode: input.mode?.trim() || "solo",
};
const requirements: Record<string, string> = {};
if (input.cli?.trim()) requirements.cli = input.cli.trim();
if (input.model?.trim()) requirements.model = input.model.trim();
if (Object.keys(requirements).length) body.requirements = requirements;
try {
const doFetch = opts.fetchImpl ?? fetch;
const res = await doFetch(`${cfg.url}/v1/tasks`, {
method: "POST",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) return { ok: false, status: res.status };
const created = z.object({ id: z.string() }).parse(await res.json());
return { ok: true, status: res.status, task_id: created.id };
} catch {
return { ok: false, status: 503 };
}
}
/** Cancels a task on the hub. Returns the hub's verdict without leaking its body on error. */
export async function cancelConductorTask(

View File

@@ -1,48 +0,0 @@
-- Migration 139: generic job registry (jobs + job_runs tables)
-- Job registry (#8848): centralized periodic-job scheduling + run history.
--
-- jobs: one row per registered job (interval or cron), with env-flag gating
-- job_runs: one row per execution (running/success/failure), pruned by count + age
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
type TEXT NOT NULL DEFAULT 'interval' CHECK(type IN ('interval', 'cron')),
cron TEXT, -- cron expression (type='cron'); NULL for interval jobs
interval_ms INTEGER, -- interval in ms (type='interval'); NULL for cron jobs
enabled INTEGER NOT NULL DEFAULT 1, -- 0=disabled, 1=enabled
env_flag TEXT, -- env var name (boolean gate), e.g. 'OMNIROUTE_WARMUP_ENABLED'; NULL = no gate
config TEXT NOT NULL DEFAULT '{}', -- JSON config (concurrency, timezone, envDefault, ...)
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS job_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
job_id TEXT NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
started_at TEXT NOT NULL, -- ISO-8601, written explicitly by recordRun (no DB default)
finished_at TEXT, -- ISO-8601; NULL while running
status TEXT NOT NULL DEFAULT 'running', -- 'running' | 'success' | 'failure'
error_message TEXT, -- sanitized error message (no stack trace)
records_affected INTEGER DEFAULT 0, -- job-specific meaning (see below)
duration_ms INTEGER, -- execution duration in ms
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_jr_job_id ON job_runs(job_id, started_at DESC);
CREATE INDEX IF NOT EXISTS idx_jr_started_at ON job_runs(started_at);
-- Built-in job registration (idempotent - INSERT OR IGNORE).
-- env_flag = NULL means "no registry-level boolean gate"; per-job disable semantics
-- live inside the handler itself (see token_health_check wrapper).
-- 'warmup' is seeded disabled because its handler is not part of this change.
-- startAll() filters on enabled before it looks for a handler, so a disabled row
-- stays quiet instead of warning on every boot; the change that brings the warmup
-- handler flips it on.
INSERT OR IGNORE INTO jobs (id, type, cron, interval_ms, enabled, env_flag, config) VALUES
('budget_reset', 'interval', NULL, 600000, 1, NULL, '{}'),
('warmup', 'cron', '0 7 * * *', NULL, 0, 'OMNIROUTE_WARMUP_ENABLED', '{"timezone":"America/Los_Angeles","envDefault":false}'),
('token_health_check', 'interval', NULL, 60000, 1, NULL, '{}');
-- records_affected semantics:
-- budget_reset = number of budget records reset (UPDATE ... SET budget_used=0 row count)
-- warmup = number of connections attempted for warmup
-- token_health_check = number of connections swept by the health check

View File

@@ -1,7 +1,7 @@
import { getDbInstance } from "./core";
import { invalidateDbCache } from "./readCache";
export type ModelCapabilityOverrideKey = "max_input_tokens" | "max_output_tokens";
export type ModelCapabilityOverrideKey = "max_input_tokens" | "max_output_tokens" | "max_token";
export interface ModelCapabilityOverride {
provider: string;
@@ -21,7 +21,7 @@ interface OverrideRow {
}
function isSupportedKey(value: unknown): value is ModelCapabilityOverrideKey {
return value === "max_input_tokens" || value === "max_output_tokens";
return value === "max_input_tokens" || value === "max_output_tokens" || value === "max_token";
}
function isPositiveInteger(value: unknown): value is number {

View File

@@ -70,6 +70,9 @@ export const webRuntimeEnvSchema = z.object({
BASE_URL: optionalHttpUrl,
NEXT_PUBLIC_BASE_URL: optionalHttpUrl,
CONDUCTOR_HUB_URL: optionalHttpUrl,
CONDUCTOR_SPOKESPERSON_URL: optionalHttpUrl,
CONDUCTOR_ORCHESTRATOR_TOKEN: optionalTrimmedString,
CONDUCTOR_HUB_TOKEN: optionalTrimmedString,
OMNIROUTE_PORT: optionalPortEnv,
API_PORT: optionalPortEnv,

View File

@@ -222,7 +222,7 @@ export async function executeWebSearch(
.filter((provider) => supportsSearchType(provider, searchType))
.sort((a, b) => a.costPerQuery - b.costPerQuery)
.map((provider) => provider.id)
.filter((providerId) => providerId !== providerConfig.id);
.filter((providerId) => providerId !== providerConfig!.id);
for (const providerId of otherIds) {
const creds = await resolveSearchCredentials(providerId);

View File

@@ -1179,6 +1179,7 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
authHint: "Get your Regolo API key from regolo.ai, then paste it here as a Bearer token.",
apiHint:
"OpenAI-compatible endpoint at https://api.regolo.ai/v1 with dynamic model discovery (19 models).",
},
"naga-ac": {
id: "naga-ac",
alias: "naga",
@@ -1195,19 +1196,4 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
authHint:
"Get API key at naga.ac — Google/GitHub/Discord signup available.",
},
chatanywhere: {
id: "chatanywhere",
alias: "chtany",
name: "ChatAnywhere",
icon: "chat",
color: "#10B981",
textIcon: "CA",
website: "https://api.chatanywhere.tech",
hasFree: true,
freeNote:
"Free tier: 5 req/day for GPT-5/4o/4.1, 30/day DeepSeek, 200/day gpt-4o-mini. Personal non-commercial use only — see chatanywhere/GPT_API_free. Requires GitHub-account-gated API key.",
passthroughModels: true,
authHint:
"Get free API key at api.chatanywhere.tech — requires GitHub account signup.",
},
};

View File

@@ -6,9 +6,7 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
const { registerHook, unregisterHook } = await import("../../src/lib/plugins/hooks.ts");
const { runPluginOnResponseHook } =
await import("../../open-sse/handlers/chatCore/pluginOnResponse.ts");
const { registerHook, unregisterHook } = await import("../../src/lib/plugins/hooks.ts");const { runPluginOnResponseHook, runPluginOnStreamCompleteHook } = await import("../../open-sse/handlers/chatCore/pluginOnResponse.ts");
async function waitFor(pred: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = Date.now() + timeoutMs;
@@ -19,6 +17,7 @@ async function waitFor(pred: () => boolean, timeoutMs = 2000): Promise<void> {
after(() => {
unregisterHook("onResponse", "test-onresponse-plugin");
unregisterHook("onStreamComplete", "test-onstreamcomplete-plugin");
});
test("no registered hooks → resolves without throwing (no-op)", async () => {
@@ -143,3 +142,140 @@ test("a throwing hook never rejects the caller (fail-open)", async () => {
);
await new Promise((r) => setTimeout(r, 30));
});
// ── onStreamComplete hook tests (#9571) ──
test("onStreamComplete: no registered hooks resolves without throwing (no-op)", async () => {
const start = Date.now();
await assert.doesNotReject(
runPluginOnStreamCompleteHook({
status: 200,
usage: { prompt_tokens: 10, completion_tokens: 20 },
ttft: 150,
model: "gpt-4",
provider: "openai",
errorCode: undefined,
startTime: start - 500,
})
);
});
test("onStreamComplete: registered hook receives usage + timing payload", async () => {
let captured: Record<string, unknown> | undefined;
registerHook(
"onStreamComplete",
"test-onstreamcomplete-plugin",
async (payload: Record<string, unknown>) => {
captured = payload;
}
);
const startTime = Date.now() - 500;
await runPluginOnStreamCompleteHook({
status: 200,
usage: { prompt_tokens: 42, completion_tokens: 100, reasoning_tokens: 5 },
ttft: 200,
model: "claude-3-opus",
provider: "anthropic",
errorCode: undefined,
startTime,
});
await waitFor(() => captured !== undefined);
assert.ok(captured, "expected onStreamComplete hook to be invoked");
// payload shape: status, usage, timing, model, provider
assert.equal(captured!.status, 200);
assert.ok(captured!.usage, "usage should be present");
assert.equal((captured!.usage as Record<string, number>).prompt_tokens, 42);
assert.equal((captured!.usage as Record<string, number>).completion_tokens, 100);
assert.equal((captured!.usage as Record<string, number>).reasoning_tokens, 5);
assert.ok(captured!.timing, "timing should be present");
const timing = captured!.timing as Record<string, number>;
assert.equal(timing.ttft, 200);
assert.ok(timing.latencyMs > 450, "latencyMs should be near 500");
assert.equal(captured!.model, "claude-3-opus");
assert.equal(captured!.provider, "anthropic");
assert.equal(captured!.errorCode, undefined);
});
test("onStreamComplete: payload includes cache token fields when present", async () => {
let captured: Record<string, unknown> | undefined;
registerHook(
"onStreamComplete",
"test-onstreamcomplete-plugin",
async (payload: Record<string, unknown>) => {
captured = payload;
}
);
await runPluginOnStreamCompleteHook({
status: 200,
usage: {
prompt_tokens: 50,
completion_tokens: 30,
cache_read_input_tokens: 20,
cache_creation_input_tokens: 10,
},
ttft: 100,
model: "gpt-4",
provider: "openai",
errorCode: undefined,
startTime: Date.now(),
});
await waitFor(() => captured !== undefined);
assert.ok(captured);
const usage = captured!.usage as Record<string, number>;
assert.equal(usage.cache_read_input_tokens, 20);
assert.equal(usage.cache_creation_input_tokens, 10);
});
test("onStreamComplete: throwing hook never rejects the caller (fail-open)", async () => {
registerHook("onStreamComplete", "test-onstreamcomplete-plugin", async () => {
throw new Error("stream-complete-boom");
});
await assert.doesNotReject(
runPluginOnStreamCompleteHook({
status: 500,
usage: undefined,
ttft: undefined,
model: "gpt-4",
provider: "openai",
errorCode: "upstream_error",
startTime: Date.now(),
})
);
await new Promise((r) => setTimeout(r, 30));
});
test("onStreamComplete: errorCode is passed through when provided", async () => {
let captured: Record<string, unknown> | undefined;
registerHook(
"onStreamComplete",
"test-onstreamcomplete-plugin",
async (payload: Record<string, unknown>) => {
captured = payload;
}
);
await runPluginOnStreamCompleteHook({
status: 502,
usage: undefined,
ttft: undefined,
model: "grok-3",
provider: "xai",
errorCode: "upstream_timeout",
startTime: Date.now(),
});
await waitFor(() => captured !== undefined);
assert.ok(captured);
assert.equal(captured!.status, 502);
assert.equal(captured!.errorCode, "upstream_timeout");
assert.equal(captured!.model, "grok-3");
assert.equal(captured!.provider, "xai");
});

View File

@@ -0,0 +1,112 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createServer, type Server } from "node:http";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-conductor-a2a-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const settings = await import("../../src/lib/db/settings.ts");
const tasksRoute = await import("../../src/app/api/a2a/tasks/route.ts");
const servers: Server[] = [];
async function enableA2A() {
await settings.updateSettings({ a2aEnabled: true });
}
function delegationRequest(body: unknown, bearer?: string) {
return new Request("http://localhost/api/a2a/tasks", {
method: "POST",
headers: {
"content-type": "application/json",
...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
},
body: JSON.stringify(body),
});
}
const VALID_BODY = {
skill: "conductor-cli-claude",
messages: [{ role: "user", content: "adicione um README com a seção Sobre" }],
metadata: { conductor: { repo: { url: "https://git.x/repo", base_ref: "dev" }, mode: "solo", model: "cc/claude-sonnet-5" } },
};
test.beforeEach(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
delete process.env.CONDUCTOR_HUB_URL;
delete process.env.OMNIROUTE_API_KEY;
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
delete process.env.CONDUCTOR_HUB_URL;
delete process.env.OMNIROUTE_API_KEY;
while (servers.length > 0) {
const s = servers.pop();
await new Promise((resolve) => s?.close(resolve));
}
});
test("A2A desabilitado → 503 (mesmo gate do JSON-RPC)", async () => {
const res = await tasksRoute.POST(delegationRequest(VALID_BODY));
assert.equal(res.status, 503);
});
test("com OMNIROUTE_API_KEY configurada, bearer errado → 401 e bearer certo passa", async () => {
await enableA2A();
process.env.OMNIROUTE_API_KEY = "chave-certa";
const denied = await tasksRoute.POST(delegationRequest(VALID_BODY, "chave-errada"));
assert.equal(denied.status, 401);
});
test("delegação válida → 201 com o task_id do hub; requirements derivados da skill do card", async () => {
await enableA2A();
const bodies: unknown[] = [];
await new Promise<void>((resolve) => {
const server = createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
bodies.push(JSON.parse(raw));
res.writeHead(201, { "content-type": "application/json" });
res.end(JSON.stringify({ id: "t_delegada", status: "submitted" }));
});
});
servers.push(server);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
process.env.CONDUCTOR_HUB_URL = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;
resolve();
});
});
const res = await tasksRoute.POST(delegationRequest(VALID_BODY));
assert.equal(res.status, 201);
const out = await res.json();
assert.equal(out.conductor_task_id, "t_delegada");
assert.equal(out.state, "submitted");
const sent = bodies[0] as { repo: { url: string; base_ref: string }; spec: { prompt: string }; requirements: { cli: string; model: string } };
assert.equal(sent.repo.url, "https://git.x/repo");
assert.equal(sent.repo.base_ref, "dev");
assert.equal(sent.spec.prompt, "adicione um README com a seção Sobre");
assert.equal(sent.requirements.cli, "claude", "skill conductor-cli-claude vira requirements.cli");
assert.equal(sent.requirements.model, "cc/claude-sonnet-5");
});
test("sem repo na metadata → 400 (delegação exige repo); skill não-conductor → 400", async () => {
await enableA2A();
const noRepo = await tasksRoute.POST(
delegationRequest({ skill: "conductor", messages: [{ role: "user", content: "p" }] })
);
assert.equal(noRepo.status, 400);
const wrongSkill = await tasksRoute.POST(
delegationRequest({ ...VALID_BODY, skill: "smart-routing" })
);
assert.equal(wrongSkill.status, 400);
});

View File

@@ -0,0 +1,85 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createServer, type Server } from "node:http";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-conductor-ask-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const askRoute = await import("../../src/app/api/conductor/ask/route.ts");
const servers: Server[] = [];
test.beforeEach(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
delete process.env.CONDUCTOR_SPOKESPERSON_URL;
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
delete process.env.CONDUCTOR_SPOKESPERSON_URL;
while (servers.length > 0) {
const s = servers.pop();
await new Promise((resolve) => s?.close(resolve));
}
});
test("fonte: auth antes do proxy; token nunca manuseado na rota", () => {
const src = fs.readFileSync(path.join(process.cwd(), "src/app/api/conductor/ask/route.ts"), "utf8");
const authAt = src.indexOf("requireManagementAuth(");
assert.ok(authAt > 0);
assert.match(src, /if \(authError\) return authError;/);
assert.ok(src.indexOf("askFaro(") > authAt, "askFaro só depois do gate");
assert.ok(!src.includes("CONDUCTOR_HUB_TOKEN"), "token vive no faroProxy, não na rota");
});
test("POST valida o body (Zod) e repassa text+pending do Faro", async () => {
await new Promise<void>((resolve) => {
const server = createServer((req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ text: "frota vazia", pending: null }));
});
servers.push(server);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
process.env.CONDUCTOR_SPOKESPERSON_URL = `http://127.0.0.1:${typeof addr === "object" && addr ? addr.port : 0}`;
resolve();
});
});
const ok = await askRoute.POST(
new Request("http://localhost/api/conductor/ask", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: "como está a frota?" }),
})
);
assert.equal(ok.status, 200);
assert.deepEqual(await ok.json(), { text: "frota vazia", pending: null });
const bad = await askRoute.POST(
new Request("http://localhost/api/conductor/ask", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: "" }),
})
);
assert.equal(bad.status, 400, "mensagem vazia é rejeitada pelo Zod");
});
test("Faro fora do ar → 503 sanitizado", async () => {
process.env.CONDUCTOR_SPOKESPERSON_URL = "http://127.0.0.1:1";
const res = await askRoute.POST(
new Request("http://localhost/api/conductor/ask", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: "oi" }),
})
);
assert.equal(res.status, 503);
});

View File

@@ -0,0 +1,71 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createConductorTask } from "../../src/lib/conductor/hubProxy.ts";
function fakeHub(body: unknown, status = 201) {
const calls: { url: string; method: string; auth: string | null; body: unknown }[] = [];
const impl = (async (url: string | URL | Request, init?: RequestInit) => {
calls.push({
url: String(url),
method: init?.method ?? "GET",
auth: (init?.headers as Record<string, string> | undefined)?.authorization ?? null,
body: JSON.parse(String(init?.body ?? "{}")),
});
return new Response(JSON.stringify(body), { status });
}) as typeof fetch;
return { impl, calls };
}
test.beforeEach(() => {
process.env.CONDUCTOR_HUB_URL = "http://hub.test:7910";
process.env.CONDUCTOR_HUB_TOKEN = "tok-hub";
delete process.env.CONDUCTOR_ORCHESTRATOR_TOKEN;
});
test.after(() => {
delete process.env.CONDUCTOR_HUB_URL;
delete process.env.CONDUCTOR_HUB_TOKEN;
delete process.env.CONDUCTOR_ORCHESTRATOR_TOKEN;
});
test("traduz a delegação A2A no POST /v1/tasks do hub (shape exato do contrato)", async () => {
const { impl, calls } = fakeHub({ id: "t_novo", status: "submitted" });
const r = await createConductorTask(
{ repoUrl: "https://git.x/repo", baseRef: "dev", prompt: "adicione um README", mode: "council-3", cli: "claude", model: "cc/claude-sonnet-5" },
{ fetchImpl: impl }
);
assert.deepEqual(r, { ok: true, status: 201, task_id: "t_novo" });
assert.equal(calls[0].url, "http://hub.test:7910/v1/tasks");
assert.equal(calls[0].method, "POST");
assert.deepEqual(calls[0].body, {
repo: { url: "https://git.x/repo", base_ref: "dev" },
spec: { prompt: "adicione um README" },
mode: "council-3",
requirements: { cli: "claude", model: "cc/claude-sonnet-5" },
});
});
test("defaults: base_ref main, mode solo, sem requirements quando cli/model ausentes", async () => {
const { impl, calls } = fakeHub({ id: "t_d", status: "submitted" });
await createConductorTask({ repoUrl: "https://git.x/r", prompt: "p" }, { fetchImpl: impl });
assert.deepEqual(calls[0].body, { repo: { url: "https://git.x/r", base_ref: "main" }, spec: { prompt: "p" }, mode: "solo" });
});
test("credencial: prefere CONDUCTOR_ORCHESTRATOR_TOKEN; fallback é o token do hub", async () => {
const a = fakeHub({ id: "t_1" });
await createConductorTask({ repoUrl: "https://x/r", prompt: "p" }, { fetchImpl: a.impl });
assert.equal(a.calls[0].auth, "Bearer tok-hub");
process.env.CONDUCTOR_ORCHESTRATOR_TOKEN = "tok-orch";
const b = fakeHub({ id: "t_2" });
await createConductorTask({ repoUrl: "https://x/r", prompt: "p" }, { fetchImpl: b.impl });
assert.equal(b.calls[0].auth, "Bearer tok-orch");
});
test("recusa do hub → {ok:false, status} sem lançar nem vazar corpo; env ausente → 503", async () => {
const { impl } = fakeHub({ error: "segredo do hub" }, 422);
const r = await createConductorTask({ repoUrl: "https://x/r", prompt: "p" }, { fetchImpl: impl });
assert.deepEqual(r, { ok: false, status: 422 });
delete process.env.CONDUCTOR_HUB_URL;
assert.deepEqual(await createConductorTask({ repoUrl: "https://x/r", prompt: "p" }, {}), { ok: false, status: 503 });
});

View File

@@ -0,0 +1,39 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
// Invariantes de segurança/UX do chat com voz (componentes React: vitest-ui advisory + dashboard-typecheck).
const CHAT = "src/app/(dashboard)/dashboard/conductor/FaroChat.tsx";
function src(): string {
return fs.readFileSync(path.join(process.cwd(), CHAT), "utf8");
}
test("client fala SÓ com o OmniRoute: /api/conductor/ask + /api/v1/audio/* (nunca Faro/hub direto)", () => {
const s = src();
assert.match(s, /"use client"/);
assert.match(s, /\/api\/conductor\/ask/);
assert.match(s, /\/api\/v1\/audio\/transcriptions/);
assert.match(s, /\/api\/v1\/audio\/speech/);
assert.ok(!s.includes(":7920"), "endereço do Faro nunca no client");
assert.ok(!s.includes("CONDUCTOR_"), "nenhuma env do Conductor no client");
});
test("pending do Faro → botões Sim/Não que enviam 'sim'/'não' (trava de confirmação é do motor do Faro)", () => {
const s = src();
assert.match(s, /pending/);
assert.match(s, /"sim"/);
assert.match(s, /"não"/);
});
test("voz: push-to-talk com MediaRecorder/getUserMedia; STT multipart sem Content-Type manual; TTS via Blob com revoke", () => {
const s = src();
assert.match(s, /navigator\.mediaDevices\.getUserMedia/);
assert.match(s, /MediaRecorder/);
assert.match(s, /FormData\(\)/);
assert.ok(!/audio\/transcriptions[\s\S]{0,300}content-type/i.test(s), "multipart deixa o browser definir o boundary");
assert.match(s, /URL\.createObjectURL/);
assert.match(s, /URL\.revokeObjectURL/);
assert.match(s, /useTranslations\("conductor"\)/);
});

View File

@@ -0,0 +1,61 @@
import test from "node:test";
import assert from "node:assert/strict";
import { askFaro } from "../../src/lib/conductor/faroProxy.ts";
function fakeFaro(body: unknown, status = 200) {
const calls: { url: string; auth: string | null; body: unknown }[] = [];
const impl = (async (url: string | URL | Request, init?: RequestInit) => {
calls.push({
url: String(url),
auth: (init?.headers as Record<string, string> | undefined)?.authorization ?? null,
body: JSON.parse(String(init?.body ?? "{}")),
});
return new Response(JSON.stringify(body), { status });
}) as typeof fetch;
return { impl, calls };
}
test.beforeEach(() => {
process.env.CONDUCTOR_SPOKESPERSON_URL = "http://faro.test:7920";
process.env.CONDUCTOR_HUB_TOKEN = "tok-hub";
});
test.after(() => {
delete process.env.CONDUCTOR_SPOKESPERSON_URL;
delete process.env.CONDUCTOR_HUB_TOKEN;
});
test("repassa a mensagem ao /ask com o token server-side e devolve text+pending", async () => {
const { impl, calls } = fakeFaro({ text: "frota ok", pending: { kind: "cancel_task" }, extra: "NÃO passa" });
const r = await askFaro("como está a frota?", { fetchImpl: impl });
assert.deepEqual(r, { ok: true, text: "frota ok", pending: { kind: "cancel_task" } });
assert.equal(calls[0].url, "http://faro.test:7920/ask");
assert.equal(calls[0].auth, "Bearer tok-hub");
assert.deepEqual(calls[0].body, { message: "como está a frota?" });
});
test("pending null passa como null (sem confirmação pendente)", async () => {
const { impl } = fakeFaro({ text: "oi", pending: null });
const r = await askFaro("oi", { fetchImpl: impl });
assert.deepEqual(r, { ok: true, text: "oi", pending: null });
});
test("Faro fora do ar / erro HTTP → degradado {ok:false} sem lançar nem vazar corpo", async () => {
const failing = (async () => {
throw new Error("ECONNREFUSED");
}) as unknown as typeof fetch;
const down = await askFaro("oi", { fetchImpl: failing });
assert.equal(down.ok, false);
const { impl } = fakeFaro({ error: "segredo interno" }, 401);
const denied = await askFaro("oi", { fetchImpl: impl });
assert.equal(denied.ok, false);
assert.ok(!JSON.stringify(denied).includes("segredo interno"));
});
test("URL default do Faro é loopback :7920 quando a env não está setada", async () => {
delete process.env.CONDUCTOR_SPOKESPERSON_URL;
const { impl, calls } = fakeFaro({ text: "x", pending: null });
await askFaro("oi", { fetchImpl: impl });
assert.equal(calls[0].url, "http://127.0.0.1:7920/ask");
});