feat(workbench): use the decision server's local model while the AI API is on hold
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (pull_request) Successful in 3s
masterplan-lock / check (push) Successful in 5s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / security (pull_request) Successful in 22s
CI (SIAX Cloud) / security (push) Successful in 23s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / quality (push) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m18s
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (pull_request) Successful in 3s
masterplan-lock / check (push) Successful in 5s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / security (pull_request) Successful in 22s
CI (SIAX Cloud) / security (push) Successful in 23s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / quality (push) Successful in 45s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m18s
- DecisionOllamaGatewayClient calls the self-hosted Ollama on server-decision-01 (tailnet HTTP only for loopback/RFC1918/100.64-127), keeps the same local admission and reports providerKind=local. - createInf0Gateway prefers it over INF0/LiteLLM when configured. - Evidence is computed deterministically from values when a small model omits offsets; a value must occur exactly once in the source or the result goes to review. This makes a 9B local model usable without weakening verification. Tests: 4 new gateway cases + 2 evidence-derivation cases; full typecheck green.
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
import {
|
||||
admitModelExecution,
|
||||
type ModelAdmissionRequest,
|
||||
type ModelBudgetReservation,
|
||||
type ModelExecutionPolicy,
|
||||
} from './model-admission';
|
||||
import { Inf0OutcomeUnknownError, type Inf0GatewayReceipt } from './inf0-gateway-client';
|
||||
import type { SiaxRequestContext } from '../platform/siax-context';
|
||||
|
||||
type Message = { role: 'system' | 'user' | 'assistant'; content: string };
|
||||
|
||||
export interface GatewayCompleteInput {
|
||||
context: SiaxRequestContext;
|
||||
admission: ModelAdmissionRequest;
|
||||
policy: ModelExecutionPolicy;
|
||||
reservation: ModelBudgetReservation | undefined;
|
||||
inputTokens: number;
|
||||
messages: readonly Message[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Self-hosted Ollama on the SIAX decision server (server-decision-01).
|
||||
*
|
||||
* This is the interim AI path used while the external model API is on hold:
|
||||
* the same local model that serves the Jev/Laya plane, reached over the
|
||||
* tailnet. No provider key, no per-token cost and no customer document leaves
|
||||
* the fleet. Admission is enforced locally exactly like the INF0 paths.
|
||||
*
|
||||
* The endpoint must be an explicit, server-owned internal address: plain HTTP
|
||||
* is only accepted for loopback, RFC1918 or tailnet (100.64.0.0/10) hosts.
|
||||
*/
|
||||
function isInternalAddress(hostname: string): boolean {
|
||||
const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
|
||||
if (!ipv4) return hostname === 'localhost';
|
||||
const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
|
||||
if (ipv4.slice(1).some((part) => Number(part) > 255)) return false;
|
||||
if (a === 127) return true;
|
||||
if (a === 10) return true;
|
||||
if (a === 192 && b === 168) return true;
|
||||
if (a === 172 && b >= 16 && b <= 31) return true;
|
||||
if (a === 100 && b >= 64 && b <= 127) return true; // tailnet CGNAT range
|
||||
return false;
|
||||
}
|
||||
|
||||
export function assertTrustedDecisionOllamaUrl(value: string): URL {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new Error('Invalid decision Ollama URL');
|
||||
}
|
||||
const httpOk = url.protocol === 'http:' && isInternalAddress(url.hostname);
|
||||
const httpsOk = url.protocol === 'https:';
|
||||
if ((!httpOk && !httpsOk) || url.username || url.password || url.search || url.hash || !url.hostname) {
|
||||
throw new Error('Decision Ollama URL must be a trusted internal endpoint');
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export class DecisionOllamaGatewayClient {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
constructor(
|
||||
private readonly options: {
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
fetchImpl?: typeof fetch;
|
||||
timeoutMs?: number;
|
||||
},
|
||||
) {
|
||||
const url = assertTrustedDecisionOllamaUrl(options.baseUrl);
|
||||
if (!options.model.trim()) throw new Error('Decision Ollama model is required');
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async complete(input: GatewayCompleteInput): Promise<Inf0GatewayReceipt> {
|
||||
const { context, admission, policy, reservation, inputTokens, messages } = structuredClone(input);
|
||||
const decision = admitModelExecution(admission, policy, reservation);
|
||||
if (!decision.allowed) {
|
||||
throw new Error(`Model execution denied: ${decision.reason}`);
|
||||
}
|
||||
if (policy.destination !== 'internal') {
|
||||
throw new Error('Model execution denied: decision Ollama is an internal route');
|
||||
}
|
||||
if (
|
||||
context.tenantId !== admission.tenantId ||
|
||||
context.projectId !== admission.projectId ||
|
||||
!context.actorId?.trim() ||
|
||||
!context.correlationId?.trim() ||
|
||||
!Number.isSafeInteger(inputTokens) ||
|
||||
inputTokens <= 0 ||
|
||||
inputTokens > admission.maxInputTokens ||
|
||||
!Array.isArray(messages) ||
|
||||
messages.length === 0
|
||||
) {
|
||||
throw new Error('Invalid scoped model request');
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.baseUrl}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.options.timeoutMs ?? 120_000),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-tenant-id': context.tenantId,
|
||||
'x-actor-id': context.actorId,
|
||||
'x-siax-correlation-id': context.correlationId,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.options.model,
|
||||
messages,
|
||||
max_tokens: admission.maxOutputTokens,
|
||||
temperature: 0,
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
} catch {
|
||||
throw new Inf0OutcomeUnknownError();
|
||||
}
|
||||
if (!response.ok) throw new Inf0OutcomeUnknownError();
|
||||
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = await response.json();
|
||||
} catch {
|
||||
throw new Inf0OutcomeUnknownError();
|
||||
}
|
||||
const result = decoded as {
|
||||
model?: unknown;
|
||||
choices?: Array<{ message?: { content?: unknown }; finish_reason?: unknown }>;
|
||||
usage?: { prompt_tokens?: unknown; completion_tokens?: unknown; total_tokens?: unknown };
|
||||
} | null;
|
||||
const content = result?.choices?.[0]?.message?.content;
|
||||
const promptTokens = result?.usage?.prompt_tokens;
|
||||
const completionTokens = result?.usage?.completion_tokens;
|
||||
const totalTokens = result?.usage?.total_tokens;
|
||||
if (
|
||||
!result ||
|
||||
typeof content !== 'string' ||
|
||||
typeof result.model !== 'string' ||
|
||||
!result.model.trim() ||
|
||||
!Number.isSafeInteger(promptTokens) ||
|
||||
!Number.isSafeInteger(completionTokens) ||
|
||||
!Number.isSafeInteger(totalTokens) ||
|
||||
(promptTokens as number) < 0 ||
|
||||
(promptTokens as number) > admission.maxInputTokens ||
|
||||
(completionTokens as number) > admission.maxOutputTokens ||
|
||||
(promptTokens as number) + (completionTokens as number) !== totalTokens
|
||||
) {
|
||||
throw new Inf0OutcomeUnknownError();
|
||||
}
|
||||
|
||||
const finish = result.choices?.[0]?.finish_reason;
|
||||
return {
|
||||
status:
|
||||
finish === 'stop' && (completionTokens as number) > 0 && content.trim()
|
||||
? 'model_stopped'
|
||||
: 'needs_review',
|
||||
content,
|
||||
modelExecuted: result.model,
|
||||
providerKind: 'local',
|
||||
promptTokens: promptTokens as number,
|
||||
completionTokens: completionTokens as number,
|
||||
totalTokens: totalTokens as number,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,16 @@
|
||||
* Resolve the live INF0 inference path.
|
||||
*
|
||||
* Preference order:
|
||||
* 1. INF0_GATEWAY_LITELLM_KEY + INF0_GATEWAY_URL (live LiteLLM, used today)
|
||||
* 2. INF0_URL + INF0_API_TOKEN (native `/v1/inf0/*` surface, contract-only)
|
||||
* 1. DECISION_OLLAMA_URL + DECISION_OLLAMA_MODEL (self-hosted model on the
|
||||
* SIAX decision server; interim path while the external model API is on
|
||||
* hold — no provider key, no per-token cost, nothing leaves the fleet)
|
||||
* 2. INF0_GATEWAY_LITELLM_KEY + INF0_GATEWAY_URL (live LiteLLM)
|
||||
* 3. INF0_URL + INF0_API_TOKEN (native `/v1/inf0/*` surface, contract-only)
|
||||
*
|
||||
* Returns `undefined` when neither is configured, so the caller can fail
|
||||
* closed with an explicit "not configured" response.
|
||||
*/
|
||||
import { DecisionOllamaGatewayClient } from './decision-ollama-client';
|
||||
import { Inf0GatewayClient } from './inf0-gateway-client';
|
||||
import { LiteLlmGatewayClient } from './litellm-gateway-client';
|
||||
import { isTrustedHttpsUrl } from './runtime-config';
|
||||
@@ -17,6 +21,18 @@ export interface Inf0Gateway {
|
||||
}
|
||||
|
||||
export function createInf0Gateway(env: NodeJS.ProcessEnv = process.env): Inf0Gateway | undefined {
|
||||
const decisionUrl = env.DECISION_OLLAMA_URL?.trim();
|
||||
const decisionModel = env.DECISION_OLLAMA_MODEL?.trim();
|
||||
if (decisionUrl && decisionModel) {
|
||||
try {
|
||||
return new DecisionOllamaGatewayClient({
|
||||
baseUrl: decisionUrl,
|
||||
model: decisionModel,
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
const litellmKey = env.INF0_GATEWAY_LITELLM_KEY?.trim();
|
||||
const litellmUrl = env.INF0_GATEWAY_URL?.trim() || 'https://ai-gateway.siax.io/v1';
|
||||
if (litellmKey && isTrustedHttpsUrl(litellmUrl)) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user