CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 4s
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 5s
CI (SIAX Cloud) / security (push) Successful in 16s
Security Scan (SIAX Cloud) / security (push) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Successful in 15s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 19s
CI (SIAX Cloud) / integration (pull_request) Successful in 29s
CI (SIAX Cloud) / quality (push) Successful in 46s
CI (SIAX Cloud) / quality (pull_request) Successful in 48s
114 lines
6.7 KiB
TypeScript
114 lines
6.7 KiB
TypeScript
import { admitModelExecution, type ModelAdmissionRequest, type ModelBudgetReservation, type ModelExecutionPolicy } from './model-admission';
|
|
import { toPropagationHeaders, type SiaxRequestContext } from '../platform/siax-context';
|
|
|
|
/** A request that may have reached INF0 must be reconciled before retry or credit release. */
|
|
export class Inf0OutcomeUnknownError extends Error {
|
|
constructor() { super('INF0 outcome or usage could not be verified; reconciliation is required'); this.name = 'Inf0OutcomeUnknownError'; }
|
|
}
|
|
export interface Inf0GatewayReceipt {
|
|
status: 'model_stopped' | 'needs_review';
|
|
content: string;
|
|
modelExecuted: string;
|
|
providerKind: 'local' | 'external';
|
|
promptTokens: number;
|
|
completionTokens: number;
|
|
totalTokens: number;
|
|
/** Absent means the upstream did not report cost, never zero by assumption. */
|
|
costUsd?: number;
|
|
}
|
|
type Message = { role: 'system' | 'user' | 'assistant'; content: string };
|
|
|
|
/**
|
|
* Internal Wave-2 INF0 adapter, not mounted to a customer route. The caller
|
|
* must obtain context, the full-route egress policy, the active reservation,
|
|
* and input token count from trusted sources. Admission is not a durable
|
|
* reservation and cannot attest a deployed route table or project membership.
|
|
* This client neither retries nor settles/releases credits.
|
|
*/
|
|
export class Inf0GatewayClient {
|
|
private readonly baseUrl: string;
|
|
private readonly fetchImpl: typeof fetch;
|
|
constructor(private readonly options: { baseUrl: string; serviceToken: string; fetchImpl?: typeof fetch; timeoutMs?: number }) {
|
|
const url = new URL(options.baseUrl);
|
|
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !options.serviceToken.trim()) {
|
|
throw new Error('A trusted HTTPS INF0 endpoint and service credential are required');
|
|
}
|
|
if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1000 || options.timeoutMs > 300000)) {
|
|
throw new Error('Invalid INF0 timeout');
|
|
}
|
|
this.baseUrl = url.toString().replace(/\/+$/, '');
|
|
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
}
|
|
|
|
async complete(input: {
|
|
context: SiaxRequestContext;
|
|
admission: ModelAdmissionRequest;
|
|
policy: ModelExecutionPolicy;
|
|
reservation: ModelBudgetReservation | undefined;
|
|
/** Token count from a trusted tokenizer matching the configured route. */
|
|
inputTokens: number;
|
|
messages: readonly Message[];
|
|
}): Promise<Inf0GatewayReceipt> {
|
|
// Preserve the admitted scope, policy, reservation and messages until the
|
|
// response is checked; callers must not change those limits in flight.
|
|
const { context, admission, policy, reservation, messages, inputTokens } = structuredClone(input);
|
|
const decision = admitModelExecution(admission, policy, reservation);
|
|
if (!decision.allowed) throw new Error(`Model execution denied: ${decision.reason}`);
|
|
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 || messages.length > 32
|
|
|| messages.some((m) => !m || !['system', 'user', 'assistant'].includes(m.role) || typeof m.content !== 'string')
|
|
|| Buffer.byteLength(JSON.stringify(messages), 'utf8') > 256 * 1024) {
|
|
throw new Error('Invalid scoped model request');
|
|
}
|
|
let response: Response;
|
|
try {
|
|
response = await this.fetchImpl(`${this.baseUrl}/v1/inf0/gateway/complete`, {
|
|
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(this.options.timeoutMs ?? 120000),
|
|
headers: { ...toPropagationHeaders(context), authorization: `Bearer ${this.options.serviceToken}`, 'content-type': 'application/json' },
|
|
body: JSON.stringify({ tenant_id: context.tenantId, project_id: context.projectId, correlation_id: context.correlationId,
|
|
route: admission.modelId, messages, max_tokens: admission.maxOutputTokens, risk_level: 'L3', data_classification: admission.dataClass }),
|
|
});
|
|
} catch { throw new Inf0OutcomeUnknownError(); }
|
|
if (!response.ok || !response.body) throw new Inf0OutcomeUnknownError();
|
|
let decoded: unknown;
|
|
const reader = response.body.getReader();
|
|
try {
|
|
const chunks: Uint8Array[] = [];
|
|
let bytes = 0;
|
|
for (;;) {
|
|
const part = await reader.read();
|
|
if (part.done) break;
|
|
bytes += part.value.byteLength;
|
|
if (bytes > 512 * 1024) { await reader.cancel(); throw new Error('response too large'); }
|
|
chunks.push(part.value);
|
|
}
|
|
decoded = JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
|
|
} catch { throw new Inf0OutcomeUnknownError(); }
|
|
finally { reader.releaseLock(); }
|
|
const result = decoded as { content?: unknown; modelExecuted?: unknown; finishReason?: unknown;
|
|
routeDecision?: { route?: unknown; providerKind?: unknown }; cost?: { promptTokens?: unknown; completionTokens?: unknown; totalTokens?: unknown; costUsd?: unknown } } | null;
|
|
const cost = result?.cost;
|
|
const promptTokens = cost?.promptTokens;
|
|
const completionTokens = cost?.completionTokens;
|
|
const totalTokens = cost?.totalTokens;
|
|
if (!result || typeof result.content !== 'string' || typeof result.modelExecuted !== 'string' || !result.modelExecuted.trim()
|
|
|| result.routeDecision?.route !== admission.modelId || !['local', 'external'].includes(String(result.routeDecision?.providerKind))
|
|
|| (policy.destination === 'internal' && result.routeDecision?.providerKind !== 'local')
|
|
|| !Number.isSafeInteger(promptTokens) || !Number.isSafeInteger(completionTokens) || !Number.isSafeInteger(totalTokens)
|
|
|| (promptTokens as number) < 0 || (promptTokens as number) > admission.maxInputTokens || (completionTokens as number) < 0
|
|
|| (promptTokens as number) + (completionTokens as number) !== totalTokens
|
|
|| (completionTokens as number) > admission.maxOutputTokens
|
|
|| (cost?.costUsd !== undefined && (typeof cost.costUsd !== 'number' || !Number.isFinite(cost.costUsd) || cost.costUsd < 0))) {
|
|
throw new Inf0OutcomeUnknownError();
|
|
}
|
|
return {
|
|
status: result.finishReason === 'stop' && (completionTokens as number) > 0 && result.content.trim() ? 'model_stopped' : 'needs_review',
|
|
content: result.content, modelExecuted: result.modelExecuted, providerKind: result.routeDecision!.providerKind as 'local' | 'external',
|
|
promptTokens: promptTokens as number, completionTokens: completionTokens as number, totalTokens: totalTokens as number,
|
|
...(cost?.costUsd === undefined ? {} : { costUsd: cost.costUsd as number }),
|
|
};
|
|
}
|
|
}
|