docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,229 +0,0 @@
|
||||
/**
|
||||
* Product planning inventory, NOT an execution registry. Every entry needs
|
||||
* version pinning, licence/model review, installation and integration tests
|
||||
* before a separately authorized DocumentTool may be created for it.
|
||||
*/
|
||||
export type CandidateRole =
|
||||
| 'detection'
|
||||
| 'document'
|
||||
| 'ocr'
|
||||
| 'table'
|
||||
| 'quality'
|
||||
| 'mapping'
|
||||
| 'entity'
|
||||
| 'media'
|
||||
| 'chat'
|
||||
| 'workflow'
|
||||
| 'metering'
|
||||
| 'model'
|
||||
| 'integration'
|
||||
| 'agent'
|
||||
| 'decision'
|
||||
| 'evaluation'
|
||||
| 'observability'
|
||||
| 'browser';
|
||||
export interface ToolCandidate {
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
roles: readonly CandidateRole[];
|
||||
/** Planning only; no candidate is automatically allowed to execute. */
|
||||
status: 'qualification_required';
|
||||
review: 'standard' | 'additional_license_or_service_review';
|
||||
}
|
||||
|
||||
const candidate = (
|
||||
id: string,
|
||||
name: string,
|
||||
source: string,
|
||||
roles: readonly CandidateRole[],
|
||||
review: ToolCandidate['review'] = 'standard',
|
||||
): ToolCandidate => ({ id, name, source, roles, status: 'qualification_required', review });
|
||||
|
||||
export const TOOL_CANDIDATES: readonly ToolCandidate[] = [
|
||||
candidate('tika', 'Apache Tika', 'https://github.com/apache/tika', ['detection', 'document']),
|
||||
candidate('docling', 'Docling', 'https://github.com/docling-project/docling', [
|
||||
'detection',
|
||||
'document',
|
||||
'table',
|
||||
]),
|
||||
candidate('unstructured', 'Unstructured', 'https://github.com/Unstructured-IO/unstructured', [
|
||||
'document',
|
||||
'table',
|
||||
]),
|
||||
candidate('pdfplumber', 'pdfplumber', 'https://github.com/jsvine/pdfplumber', ['document', 'table']),
|
||||
candidate('tesseract', 'Tesseract', 'https://github.com/tesseract-ocr/tesseract', ['ocr']),
|
||||
candidate('paddleocr', 'PaddleOCR', 'https://github.com/PaddlePaddle/PaddleOCR', ['ocr', 'document']),
|
||||
candidate('ocrmypdf', 'OCRmyPDF', 'https://github.com/ocrmypdf/OCRmyPDF', ['ocr', 'document']),
|
||||
candidate('markitdown', 'MarkItDown', 'https://github.com/microsoft/markitdown', ['document']),
|
||||
candidate('duckdb', 'DuckDB', 'https://github.com/duckdb/duckdb', ['table', 'quality']),
|
||||
candidate('polars', 'Polars', 'https://github.com/pola-rs/polars', ['table', 'quality']),
|
||||
candidate('arrow', 'Apache Arrow and Parquet', 'https://github.com/apache/arrow', ['table']),
|
||||
candidate('frictionless', 'Frictionless', 'https://github.com/frictionlessdata/frictionless-py', [
|
||||
'table',
|
||||
'quality',
|
||||
]),
|
||||
candidate('pandera', 'Pandera', 'https://github.com/unionai-oss/pandera', ['table', 'quality']),
|
||||
candidate(
|
||||
'great-expectations',
|
||||
'Great Expectations',
|
||||
'https://github.com/great-expectations/great_expectations',
|
||||
['quality'],
|
||||
),
|
||||
candidate('openrefine', 'OpenRefine', 'https://github.com/OpenRefine/OpenRefine', [
|
||||
'table',
|
||||
'quality',
|
||||
'mapping',
|
||||
]),
|
||||
candidate('valentine', 'Valentine', 'https://github.com/delftdata/valentine', ['mapping']),
|
||||
candidate('rapidfuzz', 'RapidFuzz', 'https://github.com/rapidfuzz/RapidFuzz', ['entity', 'mapping']),
|
||||
candidate('splink', 'Splink', 'https://github.com/moj-analytical-services/splink', ['entity']),
|
||||
candidate('sqlglot', 'SQLGlot', 'https://github.com/tobymao/sqlglot', ['table', 'mapping']),
|
||||
candidate('assistant-ui', 'assistant-ui', 'https://github.com/assistant-ui/assistant-ui', ['chat']),
|
||||
candidate('temporal', 'Temporal', 'https://github.com/temporalio/temporal', ['workflow']),
|
||||
candidate('langgraph', 'LangGraph', 'https://github.com/langchain-ai/langgraph', ['workflow', 'agent']),
|
||||
candidate(
|
||||
'jev',
|
||||
'TypeSafe Jev',
|
||||
'https://docs.typesafe.ai/',
|
||||
['decision', 'model'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('pydantic-ai', 'PydanticAI', 'https://github.com/pydantic/pydantic-ai', ['agent']),
|
||||
candidate(
|
||||
'microsoft-agent-framework',
|
||||
'Microsoft Agent Framework',
|
||||
'https://github.com/microsoft/agent-framework',
|
||||
['agent', 'workflow'],
|
||||
),
|
||||
candidate('semantic-kernel', 'Semantic Kernel', 'https://github.com/microsoft/semantic-kernel', ['agent']),
|
||||
candidate(
|
||||
'autogen',
|
||||
'AutoGen',
|
||||
'https://github.com/microsoft/autogen',
|
||||
['agent'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('crewai', 'CrewAI', 'https://github.com/crewAIInc/crewAI', ['agent', 'workflow']),
|
||||
candidate('haystack', 'Haystack', 'https://github.com/deepset-ai/haystack', ['agent', 'workflow']),
|
||||
candidate(
|
||||
'llama-index',
|
||||
'LlamaIndex',
|
||||
'https://github.com/run-llama/llama_index',
|
||||
['agent', 'document'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('llama-agents', 'llama-agents', 'https://github.com/run-llama/llama-agents', [
|
||||
'agent',
|
||||
'workflow',
|
||||
]),
|
||||
candidate('google-adk', 'Google ADK', 'https://github.com/google/adk-python', ['agent', 'workflow']),
|
||||
candidate(
|
||||
'mastra',
|
||||
'Mastra',
|
||||
'https://github.com/mastra-ai/mastra',
|
||||
['agent', 'workflow'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('openai-agents-sdk', 'OpenAI Agents SDK', 'https://github.com/openai/openai-agents-python', [
|
||||
'agent',
|
||||
]),
|
||||
candidate('smolagents', 'smolagents', 'https://github.com/huggingface/smolagents', ['agent']),
|
||||
candidate('dspy', 'DSPy', 'https://github.com/stanfordnlp/dspy', ['agent', 'evaluation']),
|
||||
candidate(
|
||||
'flowise',
|
||||
'Flowise',
|
||||
'https://github.com/FlowiseAI/Flowise',
|
||||
['agent', 'workflow'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'browser-use',
|
||||
'browser-use',
|
||||
'https://github.com/browser-use/browser-use',
|
||||
['browser', 'agent'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('playwright-mcp', 'Playwright MCP', 'https://github.com/microsoft/playwright-mcp', ['browser']),
|
||||
candidate('promptfoo', 'Promptfoo', 'https://github.com/promptfoo/promptfoo', ['evaluation']),
|
||||
candidate('deepeval', 'DeepEval', 'https://github.com/confident-ai/deepeval', ['evaluation']),
|
||||
candidate('ragas', 'Ragas', 'https://github.com/vibrantlabsai/ragas', ['evaluation']),
|
||||
candidate(
|
||||
'langfuse',
|
||||
'Langfuse',
|
||||
'https://github.com/langfuse/langfuse',
|
||||
['evaluation', 'observability'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'arize-phoenix',
|
||||
'Arize Phoenix',
|
||||
'https://github.com/Arize-ai/phoenix',
|
||||
['evaluation', 'observability'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate('openmeter', 'OpenMeter', 'https://github.com/openmeterio/openmeter', ['metering']),
|
||||
candidate('whisper', 'Whisper', 'https://github.com/openai/whisper', ['media']),
|
||||
candidate('faster-whisper', 'faster-whisper', 'https://github.com/SYSTRAN/faster-whisper', ['media']),
|
||||
candidate('ffmpeg', 'FFmpeg', 'https://ffmpeg.org/', ['media'], 'additional_license_or_service_review'),
|
||||
candidate(
|
||||
'pymupdf',
|
||||
'PyMuPDF',
|
||||
'https://github.com/pymupdf/PyMuPDF',
|
||||
['document'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'marker',
|
||||
'Marker',
|
||||
'https://github.com/datalab-to/marker',
|
||||
['document', 'ocr'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'mineru',
|
||||
'MinerU',
|
||||
'https://github.com/opendatalab/MinerU',
|
||||
['document', 'ocr'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'airbyte',
|
||||
'Airbyte',
|
||||
'https://github.com/airbytehq/airbyte',
|
||||
['integration'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'dify',
|
||||
'Dify',
|
||||
'https://github.com/langgenius/dify',
|
||||
['workflow', 'chat'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'n8n',
|
||||
'n8n',
|
||||
'https://github.com/n8n-io/n8n',
|
||||
['workflow', 'integration'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'open-webui',
|
||||
'Open WebUI',
|
||||
'https://github.com/open-webui/open-webui',
|
||||
['chat'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
candidate(
|
||||
'openrouter',
|
||||
'OpenRouter',
|
||||
'https://openrouter.ai/',
|
||||
['model'],
|
||||
'additional_license_or_service_review',
|
||||
),
|
||||
];
|
||||
|
||||
export function candidatesForRole(role: CandidateRole): readonly ToolCandidate[] {
|
||||
return TOOL_CANDIDATES.filter((entry) => entry.roles.includes(role));
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
import type { RepositorySql } from '../repositories/db';
|
||||
import { withCreditTenant } from './credit-tenant-scope';
|
||||
|
||||
export type CreditOperation = 'verified_payment' | 'grant' | 'reserve' | 'settle' | 'release';
|
||||
export interface CreditCommand {
|
||||
tenantId: string;
|
||||
idempotencyKey: string;
|
||||
kind: CreditOperation;
|
||||
/** Verified globally unique provider payment reference, or reservation ID. */
|
||||
reference: string;
|
||||
amount: number;
|
||||
}
|
||||
export interface CreditBalance {
|
||||
available: number;
|
||||
reserved: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal transaction primitive. verified_payment must only be invoked after
|
||||
* an independently verified and matched payment; this class does not verify
|
||||
* a payment, authorize a caller, price a job, or implement refunds/chargebacks.
|
||||
* No routes expose it. Account row locks serialize all changes per tenant.
|
||||
*/
|
||||
export class PostgresCreditLedger {
|
||||
constructor(private readonly sql: RepositorySql) {}
|
||||
|
||||
/** Read-only balance for the authenticated tenant. Never creates a row. */
|
||||
async balance(tenantId: string): Promise<CreditBalance> {
|
||||
if (typeof tenantId !== 'string' || !tenantId.trim() || tenantId.length > 256) {
|
||||
throw new Error('Invalid credit tenant');
|
||||
}
|
||||
return withCreditTenant(this.sql, tenantId, async (tx) => {
|
||||
const rows = await tx<{ available: string; reserved: string }[]>`
|
||||
SELECT available, reserved FROM opt_credit_accounts WHERE tenant_id = ${tenantId}`;
|
||||
const row = rows[0];
|
||||
return row
|
||||
? { available: Number(row.available), reserved: Number(row.reserved) }
|
||||
: { available: 0, reserved: 0 };
|
||||
});
|
||||
}
|
||||
|
||||
async apply(command: CreditCommand): Promise<{ replay: boolean; balance: CreditBalance }> {
|
||||
const { tenantId, idempotencyKey, kind, reference, amount } = command;
|
||||
if (
|
||||
![tenantId, idempotencyKey, reference].every(
|
||||
(value) => typeof value === 'string' && value.trim().length > 0,
|
||||
) ||
|
||||
!['verified_payment', 'grant', 'reserve', 'settle', 'release'].includes(kind) ||
|
||||
!Number.isSafeInteger(amount) ||
|
||||
amount < 0 ||
|
||||
((kind === 'verified_payment' || kind === 'grant' || kind === 'reserve') && amount === 0) ||
|
||||
(kind === 'release' && amount !== 0)
|
||||
)
|
||||
throw new Error('Invalid credit command');
|
||||
|
||||
return withCreditTenant(this.sql, tenantId, async (tx) => {
|
||||
await tx`INSERT INTO opt_credit_accounts (tenant_id) VALUES (${tenantId}) ON CONFLICT DO NOTHING`;
|
||||
const accounts = await tx<{ available: string; reserved: string }[]>`
|
||||
SELECT available, reserved FROM opt_credit_accounts WHERE tenant_id = ${tenantId} FOR UPDATE`;
|
||||
const account = accounts[0]!;
|
||||
let available = Number(account.available);
|
||||
let reserved = Number(account.reserved);
|
||||
const previous = await tx<{ kind: string; reference: string; amount: string }[]>`
|
||||
SELECT kind, reference, amount FROM opt_credit_events WHERE tenant_id = ${tenantId} AND idempotency_key = ${idempotencyKey}`;
|
||||
if (previous[0]) {
|
||||
if (
|
||||
previous[0].kind !== kind ||
|
||||
previous[0].reference !== reference ||
|
||||
Number(previous[0].amount) !== amount
|
||||
) {
|
||||
throw new Error('Idempotency key reused for a different credit command');
|
||||
}
|
||||
return { replay: true, balance: { available, reserved } };
|
||||
}
|
||||
|
||||
if (kind === 'verified_payment' || kind === 'grant') {
|
||||
available += amount;
|
||||
} else if (kind === 'reserve') {
|
||||
if (available < amount) throw new Error('Insufficient available credits');
|
||||
await tx`INSERT INTO opt_credit_reservations (tenant_id, reservation_id, amount, status)
|
||||
VALUES (${tenantId}, ${reference}, ${amount}, 'reserved')`;
|
||||
available -= amount;
|
||||
reserved += amount;
|
||||
} else {
|
||||
const reservations = await tx<{ amount: string; status: string }[]>`
|
||||
SELECT amount, status FROM opt_credit_reservations WHERE tenant_id = ${tenantId} AND reservation_id = ${reference} FOR UPDATE`;
|
||||
const reservation = reservations[0];
|
||||
if (!reservation || reservation.status !== 'reserved')
|
||||
throw new Error('Active credit reservation not found');
|
||||
const held = Number(reservation.amount);
|
||||
if (kind === 'settle' && amount > held) throw new Error('Settlement exceeds reserved credits');
|
||||
const spent = kind === 'settle' ? amount : 0;
|
||||
reserved -= held;
|
||||
available += held - spent;
|
||||
await tx`UPDATE opt_credit_reservations SET status = ${kind === 'settle' ? 'settled' : 'released'},
|
||||
settled_amount = ${spent} WHERE tenant_id = ${tenantId} AND reservation_id = ${reference}`;
|
||||
}
|
||||
if (
|
||||
!Number.isSafeInteger(available) ||
|
||||
!Number.isSafeInteger(reserved) ||
|
||||
available < 0 ||
|
||||
reserved < 0
|
||||
) {
|
||||
throw new Error('Credit balance outside supported range');
|
||||
}
|
||||
await tx`UPDATE opt_credit_accounts SET available = ${available}, reserved = ${reserved} WHERE tenant_id = ${tenantId}`;
|
||||
await tx`INSERT INTO opt_credit_events (tenant_id, idempotency_key, kind, amount, reference)
|
||||
VALUES (${tenantId}, ${idempotencyKey}, ${kind}, ${amount}, ${reference})`;
|
||||
return { replay: false, balance: { available, reserved } };
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { RepositorySql } from '../repositories/db';
|
||||
import type { CreditPurchaseSnapshot } from './pay0-credit-verification';
|
||||
import { withCreditTenant } from './credit-tenant-scope';
|
||||
|
||||
interface PurchaseRow {
|
||||
tenant_id: string;
|
||||
purchase_id: string;
|
||||
checkout_session_id: string;
|
||||
amount_minor: string;
|
||||
currency: string;
|
||||
credits: string;
|
||||
}
|
||||
function fromRow(row: PurchaseRow): CreditPurchaseSnapshot {
|
||||
return {
|
||||
tenantId: row.tenant_id,
|
||||
purchaseId: row.purchase_id,
|
||||
checkoutSessionId: row.checkout_session_id,
|
||||
amountMinor: Number(row.amount_minor),
|
||||
currency: row.currency,
|
||||
credits: Number(row.credits),
|
||||
};
|
||||
}
|
||||
|
||||
/** Server-internal snapshot storage. Callers must authenticate and price orders before create. */
|
||||
export class PostgresCreditPurchaseStore {
|
||||
constructor(private readonly sql: RepositorySql) {}
|
||||
|
||||
async create(snapshot: CreditPurchaseSnapshot): Promise<CreditPurchaseSnapshot> {
|
||||
if (
|
||||
![snapshot.tenantId, snapshot.purchaseId, snapshot.checkoutSessionId].every(
|
||||
(s) => typeof s === 'string' && s.trim(),
|
||||
) ||
|
||||
!Number.isSafeInteger(snapshot.amountMinor) ||
|
||||
snapshot.amountMinor <= 0 ||
|
||||
!Number.isSafeInteger(snapshot.credits) ||
|
||||
snapshot.credits <= 0 ||
|
||||
!/^[A-Z]{3}$/.test(snapshot.currency)
|
||||
) {
|
||||
throw new Error('Invalid credit purchase snapshot');
|
||||
}
|
||||
return withCreditTenant(this.sql, snapshot.tenantId, async (tx) => {
|
||||
const rows = await tx<PurchaseRow[]>`
|
||||
INSERT INTO opt_credit_purchases (tenant_id, purchase_id, checkout_session_id, amount_minor, currency, credits)
|
||||
VALUES (${snapshot.tenantId}, ${snapshot.purchaseId}, ${snapshot.checkoutSessionId}, ${snapshot.amountMinor}, ${snapshot.currency}, ${snapshot.credits})
|
||||
ON CONFLICT (tenant_id, purchase_id) DO NOTHING RETURNING *`;
|
||||
if (rows[0]) return fromRow(rows[0]);
|
||||
const existingRows = await tx<PurchaseRow[]>`
|
||||
SELECT * FROM opt_credit_purchases WHERE tenant_id = ${snapshot.tenantId} AND purchase_id = ${snapshot.purchaseId}`;
|
||||
const existing = existingRows[0] ? fromRow(existingRows[0]) : undefined;
|
||||
if (!existing || existing.checkoutSessionId !== snapshot.checkoutSessionId || existing.amountMinor !== snapshot.amountMinor
|
||||
|| existing.currency !== snapshot.currency || existing.credits !== snapshot.credits) {
|
||||
throw new Error('Purchase id reused for a different price snapshot');
|
||||
}
|
||||
return existing;
|
||||
});
|
||||
}
|
||||
|
||||
async get(tenantId: string, purchaseId: string): Promise<CreditPurchaseSnapshot | undefined> {
|
||||
if (typeof purchaseId !== 'string' || !purchaseId.trim()) throw new Error('Invalid credit purchase id');
|
||||
return withCreditTenant(this.sql, tenantId, async (tx) => {
|
||||
const rows = await tx<PurchaseRow[]>`SELECT * FROM opt_credit_purchases WHERE tenant_id = ${tenantId} AND purchase_id = ${purchaseId}`;
|
||||
return rows[0] ? fromRow(rows[0]) : undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* Exact credit estimates from a caller-supplied, versioned price book.
|
||||
* This is a calculator only: it is not a wallet, reservation or payment proof.
|
||||
*/
|
||||
export interface CreditPriceLine {
|
||||
metric: string;
|
||||
/** Maximum chargeable units for this job, established by the server. */
|
||||
maxUnits: number;
|
||||
/** Integer credits per billing block. */
|
||||
creditsPerBlock: number;
|
||||
unitsPerBlock: number;
|
||||
}
|
||||
|
||||
export interface CreditQuote {
|
||||
priceBookVersion: string;
|
||||
maximumCredits: number;
|
||||
lines: Array<{ metric: string; maxUnits: number; maximumCredits: number }>;
|
||||
}
|
||||
|
||||
/** Round each metered component up to its configured billing block. */
|
||||
export function quoteMaximumCredits(
|
||||
priceBookVersion: string,
|
||||
lines: readonly CreditPriceLine[],
|
||||
): CreditQuote {
|
||||
if (!priceBookVersion.trim() || lines.length === 0)
|
||||
throw new Error('A versioned price book and at least one line are required');
|
||||
const names = new Set<string>();
|
||||
let total = BigInt(0);
|
||||
const output = lines.map((line) => {
|
||||
if (!line.metric.trim() || names.has(line.metric))
|
||||
throw new Error('Metric names must be nonempty and unique');
|
||||
names.add(line.metric);
|
||||
if (
|
||||
!Number.isSafeInteger(line.maxUnits) ||
|
||||
line.maxUnits < 0 ||
|
||||
!Number.isSafeInteger(line.creditsPerBlock) ||
|
||||
line.creditsPerBlock < 0 ||
|
||||
!Number.isSafeInteger(line.unitsPerBlock) ||
|
||||
line.unitsPerBlock <= 0
|
||||
) {
|
||||
throw new Error('Credit quantities must be nonnegative safe integers and block size must be positive');
|
||||
}
|
||||
const units = BigInt(line.maxUnits);
|
||||
const size = BigInt(line.unitsPerBlock);
|
||||
const value = ((units + size - BigInt(1)) / size) * BigInt(line.creditsPerBlock);
|
||||
total += value;
|
||||
if (value > BigInt(Number.MAX_SAFE_INTEGER) || total > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
throw new Error('Credit quote exceeds the supported integer range');
|
||||
return { metric: line.metric, maxUnits: line.maxUnits, maximumCredits: Number(value) };
|
||||
});
|
||||
return { priceBookVersion, maximumCredits: Number(total), lines: output };
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import type postgres from 'postgres';
|
||||
import type { RepositorySql } from '../repositories/db';
|
||||
|
||||
/** A scoped transaction is not a user authorization or payment verification. */
|
||||
export async function withCreditTenant<T>(
|
||||
sql: RepositorySql,
|
||||
tenantId: string,
|
||||
action: (tx: postgres.TransactionSql) => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (typeof tenantId !== 'string' || !tenantId.trim() || tenantId.length > 256) throw new Error('Invalid credit tenant');
|
||||
return sql.begin(async (tx) => {
|
||||
const roles = await tx<{ rolsuper: boolean; rolbypassrls: boolean }[]>`
|
||||
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`;
|
||||
if (!roles[0] || roles[0].rolsuper || roles[0].rolbypassrls) throw new Error('Credits require an RLS-enforced database role');
|
||||
// Do not silently run against pre-migration credit tables. Policy bodies
|
||||
// themselves remain a trusted migration/database-administrator boundary.
|
||||
const gates = await tx<{ enabled: boolean }[]>`
|
||||
SELECT COUNT(*) = 4 AS enabled
|
||||
FROM (VALUES
|
||||
('opt_credit_accounts', 'opt_credit_accounts_tenant'),
|
||||
('opt_credit_reservations', 'opt_credit_reservations_tenant'),
|
||||
('opt_credit_events', 'opt_credit_events_tenant'),
|
||||
('opt_credit_purchases', 'opt_credit_purchases_tenant')
|
||||
) AS expected(table_name, policy_name)
|
||||
JOIN pg_class AS c ON c.oid = to_regclass(expected.table_name)
|
||||
WHERE c.relrowsecurity AND c.relforcerowsecurity
|
||||
AND (SELECT COUNT(*) FROM pg_policy AS p WHERE p.polrelid = c.oid) = 1
|
||||
AND EXISTS (SELECT 1 FROM pg_policy AS p WHERE p.polrelid = c.oid AND p.polname = expected.policy_name)`;
|
||||
if (gates[0]?.enabled !== true) throw new Error('Credit tenant isolation migration is not active');
|
||||
await tx`SELECT set_config('app.opt_credit_tenant_id', ${tenantId}, true)`;
|
||||
return action(tx);
|
||||
}) as Promise<T>;
|
||||
}
|
||||
@@ -1,183 +0,0 @@
|
||||
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}/api/chat`, {
|
||||
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,
|
||||
stream: false,
|
||||
// Structured extraction: JSON mode, no chain-of-thought output, and a
|
||||
// hard output budget. A thinking model otherwise spends the whole
|
||||
// budget on reasoning and returns model_incomplete.
|
||||
format: 'json',
|
||||
think: false,
|
||||
options: {
|
||||
temperature: 0,
|
||||
num_predict: admission.maxOutputTokens,
|
||||
num_ctx: Math.max(
|
||||
4096,
|
||||
Math.min(131072, admission.maxInputTokens + admission.maxOutputTokens + 1024),
|
||||
),
|
||||
},
|
||||
}),
|
||||
});
|
||||
} 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;
|
||||
message?: { content?: unknown };
|
||||
done?: unknown;
|
||||
done_reason?: unknown;
|
||||
prompt_eval_count?: unknown;
|
||||
eval_count?: unknown;
|
||||
} | null;
|
||||
const content = result?.message?.content;
|
||||
const promptTokens = result?.prompt_eval_count;
|
||||
const completionTokens = result?.eval_count;
|
||||
if (
|
||||
!result ||
|
||||
typeof content !== 'string' ||
|
||||
typeof result.model !== 'string' ||
|
||||
!result.model.trim() ||
|
||||
!Number.isSafeInteger(promptTokens) ||
|
||||
!Number.isSafeInteger(completionTokens) ||
|
||||
(promptTokens as number) < 0 ||
|
||||
(promptTokens as number) > admission.maxInputTokens ||
|
||||
(completionTokens as number) > admission.maxOutputTokens
|
||||
) {
|
||||
throw new Inf0OutcomeUnknownError();
|
||||
}
|
||||
const totalTokens = (promptTokens as number) + (completionTokens as number);
|
||||
|
||||
const finish = result.done_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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { Doc0UploadReceipt } from './doc0-upload-client';
|
||||
import type { TextSource } from './structured-output-validation';
|
||||
|
||||
export class Doc0SourceUnavailableError extends Error {
|
||||
constructor() { super('DOC0 extracted source could not be verified; review or reconciliation is required'); this.name = 'Doc0SourceUnavailableError'; }
|
||||
}
|
||||
|
||||
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
const MAX_SEGMENTS = 100;
|
||||
const MAX_SOURCE_BYTES = 192 * 1024;
|
||||
|
||||
async function boundedJson(response: Response): Promise<unknown> {
|
||||
if (!response.ok || !response.body) throw new Error('source unavailable');
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
size += part.value.byteLength;
|
||||
if (size > MAX_RESPONSE_BYTES) { void reader.cancel().catch(() => undefined); throw new Error('source too large'); }
|
||||
chunks.push(part.value);
|
||||
}
|
||||
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))) as unknown;
|
||||
} finally { reader.releaseLock(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a bounded DOC0 index for a verified upload receipt. The caller must
|
||||
* independently authenticate and authorize the tenant/project/actor, and
|
||||
* DOC0 must enforce the same project policy. The segment index is not proof
|
||||
* of OCR accuracy, semantic correctness, or complete source extraction.
|
||||
*/
|
||||
export class Doc0SourceClient {
|
||||
private readonly baseUrl: string;
|
||||
private readonly token: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: { baseUrl: string; serviceToken: string; fetchImpl?: typeof fetch; timeoutMs?: number }) {
|
||||
let url: URL;
|
||||
try { url = new URL(options.baseUrl); } catch { throw new Error('Invalid DOC0 source configuration'); }
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || !options.serviceToken.trim()
|
||||
|| (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 1000 || options.timeoutMs > 300000))) {
|
||||
throw new Error('Invalid DOC0 source configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.token = options.serviceToken;
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.timeoutMs = options.timeoutMs ?? 120000;
|
||||
}
|
||||
|
||||
async read(input: {
|
||||
tenantId: string; projectId: string; actorId: string; requestId: string; receipt: Doc0UploadReceipt;
|
||||
}): Promise<{ sources: TextSource[]; reportedTextSha256: string }> {
|
||||
const snapshot = structuredClone(input);
|
||||
const { tenantId, projectId, actorId, requestId, receipt } = snapshot;
|
||||
if (![tenantId, projectId, actorId, requestId, receipt?.documentId, receipt?.versionId]
|
||||
.every((value) => typeof value === 'string' && /^[\x21-\x7e]{1,256}$/.test(value))
|
||||
|| !/^[0-9a-f]{64}$/.test(receipt?.checksumSha256 ?? '') || receipt?.pipelineStage !== 'parsed') {
|
||||
throw new Doc0SourceUnavailableError();
|
||||
}
|
||||
let value: unknown;
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/v1/doc0/documents/${encodeURIComponent(receipt.documentId)}/versions/${encodeURIComponent(receipt.versionId)}/segments?limit=${MAX_SEGMENTS}&offset=0`, {
|
||||
method: 'GET', redirect: 'error', cache: 'no-store', signal: AbortSignal.timeout(this.timeoutMs),
|
||||
headers: { authorization: `Bearer ${this.token}`, 'x-tenant-id': tenantId, 'x-actor-id': actorId, 'x-request-id': requestId },
|
||||
});
|
||||
value = await boundedJson(response);
|
||||
} catch { throw new Doc0SourceUnavailableError(); }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Doc0SourceUnavailableError();
|
||||
const page = value as { texts?: unknown; segments?: unknown; offset?: unknown };
|
||||
if (page.offset !== 0 || !Array.isArray(page.texts) || page.texts.length !== 1 || !Array.isArray(page.segments)) {
|
||||
throw new Doc0SourceUnavailableError();
|
||||
}
|
||||
const meta = page.texts[0] as Record<string, unknown> | null;
|
||||
if (!meta || meta.tenantId !== tenantId || meta.documentId !== receipt.documentId || meta.versionId !== receipt.versionId
|
||||
|| typeof meta.documentTextId !== 'string' || !meta.documentTextId || typeof meta.parserRunId !== 'string' || !meta.parserRunId
|
||||
|| meta.segmentsTruncated !== false || !Number.isSafeInteger(meta.segmentCount) || (meta.segmentCount as number) < 1
|
||||
|| (meta.segmentCount as number) > MAX_SEGMENTS || meta.segmentCount !== page.segments.length
|
||||
|| !Number.isSafeInteger(meta.charCount) || (meta.charCount as number) < 1
|
||||
|| typeof meta.textSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(meta.textSha256)) {
|
||||
throw new Doc0SourceUnavailableError();
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
const sources: TextSource[] = [];
|
||||
let priorEnd = 0;
|
||||
for (const [index, value] of page.segments.entries()) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Doc0SourceUnavailableError();
|
||||
const segment = value as Record<string, unknown>;
|
||||
if (segment.tenantId !== tenantId || segment.documentId !== receipt.documentId || segment.versionId !== receipt.versionId
|
||||
|| segment.documentTextId !== meta.documentTextId || segment.parserRunId !== meta.parserRunId
|
||||
|| segment.sourceVersionSha256 !== receipt.checksumSha256 || segment.sequence !== index
|
||||
|| typeof segment.segmentId !== 'string' || !segment.segmentId || ids.has(segment.segmentId)
|
||||
|| typeof segment.text !== 'string' || !segment.text || !Number.isSafeInteger(segment.charStart)
|
||||
|| !Number.isSafeInteger(segment.charEnd) || (segment.charStart as number) < priorEnd
|
||||
|| (segment.charEnd as number) - (segment.charStart as number) !== segment.text.length
|
||||
|| (segment.charEnd as number) > (meta.charCount as number)
|
||||
|| segment.segmentSha256 !== createHash('sha256').update(segment.text, 'utf8').digest('hex')) {
|
||||
throw new Doc0SourceUnavailableError();
|
||||
}
|
||||
ids.add(segment.segmentId);
|
||||
priorEnd = segment.charEnd as number;
|
||||
sources.push({ id: segment.segmentId, text: segment.text });
|
||||
}
|
||||
if (Buffer.byteLength(JSON.stringify(sources), 'utf8') > MAX_SOURCE_BYTES) throw new Doc0SourceUnavailableError();
|
||||
return { sources, reportedTextSha256: meta.textSha256 };
|
||||
}
|
||||
}
|
||||
@@ -1,393 +0,0 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
export type DocumentClassification =
|
||||
'public' | 'internal' | 'confidential' | 'restricted' | 'personal-data' | 'financial' | 'legal';
|
||||
export interface Doc0UploadInput {
|
||||
/** Must be verified and authorized by the caller, never sourced from unchecked headers. */
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
requestId: string;
|
||||
idempotencyKey: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
classification: DocumentClassification;
|
||||
bytes: Uint8Array;
|
||||
}
|
||||
export interface Doc0UploadReceipt {
|
||||
documentId: string;
|
||||
versionId: string;
|
||||
checksumSha256: string;
|
||||
pipelineStage: string;
|
||||
}
|
||||
|
||||
/** The POST may have committed even if its response could not be verified. */
|
||||
export class Doc0UploadOutcomeUnknownError extends Error {
|
||||
constructor() {
|
||||
super(
|
||||
'DOC0 upload outcome or receipt could not be verified; reconcile using the original idempotency key',
|
||||
);
|
||||
this.name = 'Doc0UploadOutcomeUnknownError';
|
||||
}
|
||||
}
|
||||
|
||||
export class Doc0InspectionUnavailableError extends Error {
|
||||
constructor() {
|
||||
super('DOC0 upload inspection could not be verified');
|
||||
this.name = 'Doc0InspectionUnavailableError';
|
||||
}
|
||||
}
|
||||
|
||||
export interface Doc0InspectionInput {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
requestId: string;
|
||||
idempotencyKey: string;
|
||||
sourceSha256: string;
|
||||
sourceSizeBytes: number;
|
||||
/** Original server-compatible fingerprint from a trusted, durable attempt manifest. */
|
||||
requestFingerprint: string;
|
||||
}
|
||||
export type Doc0Inspection =
|
||||
| { status: 'not_found' | 'in_progress' | 'reconciliation_required' }
|
||||
| { status: 'completed_recorded'; documentId: string; versionId: string };
|
||||
|
||||
/**
|
||||
* DOC0 fingerprints the multipart parser's filename and MIME, not the values
|
||||
* supplied to FormData. Use an ASCII wire name and a restricted, normalized
|
||||
* MIME so their parser interpretation is deterministic. The original name is
|
||||
* preserved separately as DOC0's displayName.
|
||||
*
|
||||
* Internal contract only: callers must retain this identity before dispatch,
|
||||
* authorize its scope, and keep the same input bytes/metadata until dispatch.
|
||||
*/
|
||||
/**
|
||||
* One upload identity per operation — not per file.
|
||||
*
|
||||
* "Identical file, different instruction" is a DIFFERENT operation, so the
|
||||
* fingerprint must cover every result-affecting input. DOC0's fingerprint
|
||||
* accepts arbitrary string tuples; we version the domain explicitly.
|
||||
*
|
||||
* Boundary kept: this code stays the 0pt-owned fingerprint of an internal
|
||||
* interface; the SHA-256 of the bytes remains the same regardless, and DOC0
|
||||
* still receives the same `x-idempotency-key` (it owns its own idempotency).
|
||||
*/
|
||||
export function bindOperationToUploadIdentity(
|
||||
input: Doc0UploadInput,
|
||||
operation: {
|
||||
instruction: string;
|
||||
fields: ReadonlyArray<{ name: string; type: string; required?: boolean }>;
|
||||
modelId: string;
|
||||
dataClass: string;
|
||||
format: 'json' | 'csv';
|
||||
},
|
||||
): Doc0UploadInput {
|
||||
const payloadVersion = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify([
|
||||
'0pt-structure-operation-v1',
|
||||
operation.instruction.length,
|
||||
operation.instruction,
|
||||
operation.fields.map((f) => [f.name, f.type, f.required === true]),
|
||||
operation.modelId,
|
||||
operation.dataClass,
|
||||
operation.format,
|
||||
]),
|
||||
)
|
||||
.digest('hex')
|
||||
.slice(0, 16);
|
||||
return { ...input, filename: `${input.filename}#${payloadVersion}` };
|
||||
}
|
||||
|
||||
export function prepareDoc0UploadIdentity(input: Doc0UploadInput): {
|
||||
sourceSha256: string;
|
||||
sourceSizeBytes: number;
|
||||
requestFingerprint: string;
|
||||
wireFilename: string;
|
||||
wireMimeType: string;
|
||||
} {
|
||||
if (
|
||||
![
|
||||
input.tenantId,
|
||||
input.projectId,
|
||||
input.actorId,
|
||||
input.requestId,
|
||||
input.idempotencyKey,
|
||||
input.filename,
|
||||
input.mimeType,
|
||||
].every((value) => typeof value === 'string' && value.trim()) ||
|
||||
![input.tenantId, input.actorId, input.requestId, input.idempotencyKey].every((value) =>
|
||||
/^[\x21-\x7e]{1,256}$/.test(value),
|
||||
) ||
|
||||
!['public', 'internal', 'confidential', 'restricted', 'personal-data', 'financial', 'legal'].includes(
|
||||
input.classification,
|
||||
) ||
|
||||
!(input.bytes instanceof Uint8Array) ||
|
||||
input.bytes.byteLength === 0
|
||||
)
|
||||
throw new Error('Invalid DOC0 upload input');
|
||||
const wireMimeType = input.mimeType.toLowerCase();
|
||||
if (!/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(wireMimeType)) {
|
||||
throw new Error('Invalid DOC0 upload MIME type');
|
||||
}
|
||||
const extension = /\.([a-z0-9]{1,16})$/i.exec(input.filename)?.[1]?.toLowerCase() ?? 'bin';
|
||||
const wireFilename = `source.${extension}`;
|
||||
const sourceSha256 = createHash('sha256').update(input.bytes).digest('hex');
|
||||
const sourceSizeBytes = input.bytes.byteLength;
|
||||
const requestFingerprint = createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify([
|
||||
'doc0-upload-v1',
|
||||
input.tenantId,
|
||||
input.projectId,
|
||||
input.actorId,
|
||||
sourceSha256,
|
||||
sourceSizeBytes,
|
||||
wireFilename,
|
||||
wireMimeType,
|
||||
input.filename,
|
||||
'unknown',
|
||||
input.classification,
|
||||
[],
|
||||
null,
|
||||
]),
|
||||
)
|
||||
.digest('hex');
|
||||
return { sourceSha256, sourceSizeBytes, requestFingerprint, wireFilename, wireMimeType };
|
||||
}
|
||||
|
||||
const MAX_RECEIPT_BYTES = 128 * 1024;
|
||||
|
||||
async function readBoundedJson(response: Response): Promise<unknown> {
|
||||
if (!response.ok || !response.body) throw new Error('response unavailable');
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const parts: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
for (;;) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
length += chunk.value.byteLength;
|
||||
if (length > MAX_RECEIPT_BYTES) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
throw new Error('response too large');
|
||||
}
|
||||
parts.push(chunk.value);
|
||||
}
|
||||
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts))) as unknown;
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal client only. The caller must enforce verified tenant/project/actor
|
||||
* permissions and data handling policy. The coordinated DOC0/N0D/ST0RE
|
||||
* sensitivity handling must be deployed and verified end to end before this
|
||||
* is wired to customer uploads.
|
||||
*/
|
||||
export class Doc0UploadClient {
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly baseUrl: string;
|
||||
constructor(
|
||||
private readonly options: {
|
||||
baseUrl: string;
|
||||
serviceToken: string;
|
||||
maxBytes: number;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
},
|
||||
) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(options.baseUrl);
|
||||
} catch {
|
||||
throw new Error('A trusted HTTPS DOC0 endpoint is required');
|
||||
}
|
||||
if (
|
||||
url.protocol !== 'https:' ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
!options.serviceToken.trim() ||
|
||||
!Number.isSafeInteger(options.maxBytes) ||
|
||||
options.maxBytes <= 0 ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) ||
|
||||
options.timeoutMs < 1_000 ||
|
||||
options.timeoutMs > 300_000))
|
||||
) {
|
||||
throw new Error(
|
||||
'A trusted HTTPS DOC0 endpoint, service credential and valid upload limits are required',
|
||||
);
|
||||
}
|
||||
// Keep the validated values even if the caller later changes its options object.
|
||||
this.options = { ...options };
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
}
|
||||
|
||||
async upload(input: Doc0UploadInput): Promise<Doc0UploadReceipt> {
|
||||
if (!(input.bytes instanceof Uint8Array) || input.bytes.byteLength > this.options.maxBytes) {
|
||||
throw new Error('Invalid DOC0 upload input');
|
||||
}
|
||||
// Bind the outbound request and receipt to the same immutable-by-caller input.
|
||||
input = { ...input, bytes: new Uint8Array(input.bytes) };
|
||||
const identity = prepareDoc0UploadIdentity(input);
|
||||
if (identity.sourceSizeBytes > this.options.maxBytes) throw new Error('Invalid DOC0 upload input');
|
||||
const expectedHash = identity.sourceSha256;
|
||||
const body = new FormData();
|
||||
body.set(
|
||||
'input',
|
||||
JSON.stringify({
|
||||
projectId: input.projectId,
|
||||
displayName: input.filename,
|
||||
documentType: 'unknown',
|
||||
classification: input.classification,
|
||||
}),
|
||||
);
|
||||
body.set(
|
||||
'file',
|
||||
new Blob([new Uint8Array(input.bytes)], { type: identity.wireMimeType }),
|
||||
identity.wireFilename,
|
||||
);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetchImpl(`${this.baseUrl}/v1/doc0/documents`, {
|
||||
method: 'POST',
|
||||
redirect: 'error',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.options.serviceToken}`,
|
||||
'x-tenant-id': input.tenantId,
|
||||
'x-actor-id': input.actorId,
|
||||
'x-request-id': input.requestId,
|
||||
'x-idempotency-key': input.idempotencyKey,
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(this.options.timeoutMs ?? 120_000),
|
||||
});
|
||||
} catch {
|
||||
throw new Doc0UploadOutcomeUnknownError();
|
||||
}
|
||||
// Even a non-2xx response does not prove the write did not commit.
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = await readBoundedJson(response);
|
||||
} catch {
|
||||
throw new Doc0UploadOutcomeUnknownError();
|
||||
}
|
||||
const data = decoded as {
|
||||
document?: {
|
||||
documentId?: unknown;
|
||||
tenantId?: unknown;
|
||||
projectId?: unknown;
|
||||
currentVersionId?: unknown;
|
||||
};
|
||||
currentVersion?: {
|
||||
versionId?: unknown;
|
||||
tenantId?: unknown;
|
||||
documentId?: unknown;
|
||||
checksumSha256?: unknown;
|
||||
sizeBytes?: unknown;
|
||||
pipelineStage?: unknown;
|
||||
};
|
||||
};
|
||||
const doc = data?.document;
|
||||
const version = data?.currentVersion;
|
||||
if (
|
||||
!doc ||
|
||||
!version ||
|
||||
typeof doc.documentId !== 'string' ||
|
||||
!doc.documentId ||
|
||||
typeof version.versionId !== 'string' ||
|
||||
!version.versionId ||
|
||||
doc.tenantId !== input.tenantId ||
|
||||
version.tenantId !== input.tenantId ||
|
||||
doc.projectId !== input.projectId ||
|
||||
version.documentId !== doc.documentId ||
|
||||
doc.currentVersionId !== version.versionId ||
|
||||
version.checksumSha256 !== expectedHash ||
|
||||
version.sizeBytes !== input.bytes.byteLength ||
|
||||
typeof version.pipelineStage !== 'string' ||
|
||||
!version.pipelineStage
|
||||
) {
|
||||
throw new Doc0UploadOutcomeUnknownError();
|
||||
}
|
||||
return {
|
||||
documentId: doc.documentId,
|
||||
versionId: version.versionId,
|
||||
checksumSha256: expectedHash,
|
||||
pipelineStage: version.pipelineStage,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe only: neither `not_found` nor `completed_recorded` proves that
|
||||
* an external write is absent, that storage is intact, or that extraction
|
||||
* is complete. No automatic retry, settlement or customer route is wired.
|
||||
*/
|
||||
async inspect(input: Doc0InspectionInput): Promise<Doc0Inspection> {
|
||||
if (
|
||||
![input.tenantId, input.projectId, input.actorId, input.requestId, input.idempotencyKey].every(
|
||||
(value) => typeof value === 'string' && value.trim(),
|
||||
) ||
|
||||
input.projectId.length > 256 ||
|
||||
input.idempotencyKey.length > 256 ||
|
||||
!/^[0-9a-f]{64}$/.test(input.sourceSha256) ||
|
||||
!/^[0-9a-f]{64}$/.test(input.requestFingerprint) ||
|
||||
!Number.isSafeInteger(input.sourceSizeBytes) ||
|
||||
input.sourceSizeBytes <= 0
|
||||
) {
|
||||
throw new Error('Invalid DOC0 inspection input');
|
||||
}
|
||||
let result: unknown;
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/v1/doc0/upload-intents/inspect`, {
|
||||
method: 'POST',
|
||||
redirect: 'error',
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(this.options.timeoutMs ?? 120_000),
|
||||
headers: {
|
||||
authorization: `Bearer ${this.options.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
'x-tenant-id': input.tenantId,
|
||||
'x-actor-id': input.actorId,
|
||||
'x-request-id': input.requestId,
|
||||
'x-idempotency-key': input.idempotencyKey,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
projectId: input.projectId,
|
||||
sourceSha256: input.sourceSha256,
|
||||
sourceSizeBytes: input.sourceSizeBytes,
|
||||
requestFingerprint: input.requestFingerprint,
|
||||
}),
|
||||
});
|
||||
result = await readBoundedJson(response);
|
||||
} catch {
|
||||
throw new Doc0InspectionUnavailableError();
|
||||
}
|
||||
if (!result || typeof result !== 'object' || Array.isArray(result))
|
||||
throw new Doc0InspectionUnavailableError();
|
||||
const record = result as Record<string, unknown>;
|
||||
if (
|
||||
typeof record.status === 'string' &&
|
||||
['not_found', 'in_progress', 'reconciliation_required'].includes(record.status) &&
|
||||
Object.keys(record).length === 1
|
||||
) {
|
||||
return { status: record.status as 'not_found' | 'in_progress' | 'reconciliation_required' };
|
||||
}
|
||||
if (
|
||||
record.status === 'completed_recorded' &&
|
||||
Object.keys(record).length === 3 &&
|
||||
typeof record.documentId === 'string' &&
|
||||
record.documentId.trim() &&
|
||||
typeof record.versionId === 'string' &&
|
||||
record.versionId.trim()
|
||||
) {
|
||||
return { status: 'completed_recorded', documentId: record.documentId, versionId: record.versionId };
|
||||
}
|
||||
throw new Doc0InspectionUnavailableError();
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { validateStructuredOutput, type FieldEvidence, type OutputFieldContract, type TextSource, type ValidationIssue } from './structured-output-validation';
|
||||
|
||||
export type ValidatedExport =
|
||||
| { status: 'ready'; mediaType: 'application/json' | 'text/csv'; content: string }
|
||||
| { status: 'needs_review'; issues: ValidationIssue[] };
|
||||
|
||||
/**
|
||||
* Serialize a single, flat record after rechecking its evidence against the
|
||||
* supplied source text. This is an internal serializer, not an authorization,
|
||||
* completeness, semantic-correctness or source-authenticity check.
|
||||
* CSV rejects formula-like text rather than silently changing customer data;
|
||||
* JSON preserves it exactly. CSV also rejects absent optional fields so that
|
||||
* absence is never silently converted into an empty string.
|
||||
*/
|
||||
export function exportValidatedOutput(input: {
|
||||
format: 'json' | 'csv';
|
||||
fields: readonly OutputFieldContract[];
|
||||
value: unknown;
|
||||
sources: readonly TextSource[];
|
||||
evidence: readonly FieldEvidence[];
|
||||
}): ValidatedExport {
|
||||
if (input.format !== 'json' && input.format !== 'csv') {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'unsupported_export_format' }] };
|
||||
}
|
||||
const validation = validateStructuredOutput(input);
|
||||
if (validation.status !== 'mechanically_validated') return validation;
|
||||
|
||||
const value = input.value as Record<string, string | number | boolean>;
|
||||
const ordered: Record<string, string | number | boolean> = Object.create(null) as Record<string, string | number | boolean>;
|
||||
for (const field of input.fields) {
|
||||
if (Object.prototype.hasOwnProperty.call(value, field.name)) ordered[field.name] = value[field.name]!;
|
||||
else if (input.format === 'csv') {
|
||||
return { status: 'needs_review', issues: [{ field: field.name, code: 'csv_missing_value' }] };
|
||||
}
|
||||
}
|
||||
if (input.format === 'json') {
|
||||
return { status: 'ready', mediaType: 'application/json', content: `${JSON.stringify(ordered, null, 2)}\n` };
|
||||
}
|
||||
|
||||
// Spreadsheet applications may interpret these prefixes as formulas even
|
||||
// in quoted CSV cells. Treat leading control characters as unsafe as well.
|
||||
const unsafe = (cell: string): boolean => /^[\t\r\n]/u.test(cell) || /^\s*[=+@-]/u.test(cell);
|
||||
for (const field of input.fields) {
|
||||
if (unsafe(field.name) || (field.type === 'string' && unsafe(ordered[field.name] as string))) {
|
||||
return { status: 'needs_review', issues: [{ field: field.name, code: 'csv_unsafe_cell' }] };
|
||||
}
|
||||
}
|
||||
const quote = (cell: string): string => `"${cell.replaceAll('"', '""')}"`;
|
||||
const header = input.fields.map((field) => quote(field.name)).join(',');
|
||||
const row = input.fields.map((field) => quote(String(ordered[field.name]))).join(',');
|
||||
return { status: 'ready', mediaType: 'text/csv', content: `${header}\r\n${row}\r\n` };
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
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 }),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
/**
|
||||
* Resolve the live INF0 inference path.
|
||||
*
|
||||
* Preference order:
|
||||
* 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';
|
||||
|
||||
export interface Inf0Gateway {
|
||||
complete(input: Parameters<Inf0GatewayClient['complete']>[0]): ReturnType<Inf0GatewayClient['complete']>;
|
||||
}
|
||||
|
||||
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)) {
|
||||
try {
|
||||
return new LiteLlmGatewayClient({
|
||||
baseUrl: litellmUrl,
|
||||
apiKey: litellmKey,
|
||||
providerKind: env.INF0_GATEWAY_PROVIDER_KIND === 'local' ? 'local' : 'external',
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
const baseUrl = env.INF0_URL ?? env.INF0_API_URL;
|
||||
const token = env.INF0_API_TOKEN ?? env.INF0_SERVICE_TOKEN;
|
||||
if (isTrustedHttpsUrl(baseUrl) && token?.trim()) {
|
||||
try {
|
||||
return new Inf0GatewayClient({ baseUrl, serviceToken: token.trim() });
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
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[];
|
||||
}
|
||||
|
||||
/**
|
||||
* INF0's live inference anchor today is the LiteLLM gateway (OpenAI-compatible,
|
||||
* `ai-gateway.siax.io/v1`). The `/v1/inf0/*` SIAX surface is contract-only, so
|
||||
* this adapter calls the live route while keeping the exact same admission
|
||||
* semantics as the future native client: scope, allow-list, data class,
|
||||
* external-transfer policy and token limits are all enforced locally before
|
||||
* the request leaves the process.
|
||||
*
|
||||
* No provider key is placed in this repo: the caller passes a per-tenant
|
||||
* LiteLLM virtual key resolved from the environment at runtime.
|
||||
*/
|
||||
export class LiteLlmGatewayClient {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
constructor(
|
||||
private readonly options: {
|
||||
baseUrl: string;
|
||||
apiKey: string;
|
||||
providerKind?: 'local' | 'external';
|
||||
fetchImpl?: typeof fetch;
|
||||
timeoutMs?: number;
|
||||
},
|
||||
) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(options.baseUrl);
|
||||
} catch {
|
||||
throw new Error('Invalid INF0 gateway URL');
|
||||
}
|
||||
if (
|
||||
url.protocol !== 'https:' ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
!options.apiKey.trim()
|
||||
) {
|
||||
throw new Error('A trusted HTTPS INF0 gateway and key are required');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.options = { ...options };
|
||||
}
|
||||
|
||||
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 (
|
||||
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}/chat/completions`, {
|
||||
method: 'POST',
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.options.timeoutMs ?? 120_000),
|
||||
headers: {
|
||||
authorization: `Bearer ${this.options.apiKey}`,
|
||||
'content-type': 'application/json',
|
||||
'x-tenant-id': context.tenantId,
|
||||
'x-siax-project-id': context.projectId ?? '',
|
||||
'x-actor-id': context.actorId,
|
||||
'x-siax-correlation-id': context.correlationId,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: admission.modelId,
|
||||
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 providerKind = this.options.providerKind ?? 'external';
|
||||
if (policy.destination === 'internal' && providerKind !== 'local') {
|
||||
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,
|
||||
promptTokens: promptTokens as number,
|
||||
completionTokens: completionTokens as number,
|
||||
totalTokens: totalTokens as number,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/**
|
||||
* Admission decision only. All policy, context and reservation values must be
|
||||
* obtained from trusted server-side stores; this function does not verify a
|
||||
* user identity, reserve credits, or call INF0 or a model provider.
|
||||
*/
|
||||
export interface ModelAdmissionRequest {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
jobId: string;
|
||||
modelId: string;
|
||||
dataClass: string;
|
||||
maxInputTokens: number;
|
||||
maxOutputTokens: number;
|
||||
maximumCredits: number;
|
||||
}
|
||||
export interface ModelExecutionPolicy {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
allowedModelIds: readonly string[];
|
||||
allowedDataClasses: readonly string[];
|
||||
/** Destination is determined from the operator's verified model registry. */
|
||||
destination: 'internal' | 'external';
|
||||
externalTransferAllowed: boolean;
|
||||
maxInputTokens: number;
|
||||
maxOutputTokens: number;
|
||||
}
|
||||
export interface ModelBudgetReservation {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
jobId: string;
|
||||
status: 'reserved' | 'settled' | 'released';
|
||||
credits: number;
|
||||
}
|
||||
export type ModelAdmission = { allowed: true } | {
|
||||
allowed: false;
|
||||
reason: 'invalid_request' | 'scope_mismatch' | 'model_not_allowed' | 'data_class_not_allowed'
|
||||
| 'external_transfer_denied' | 'token_limit_exceeded' | 'reservation_required';
|
||||
};
|
||||
|
||||
export function admitModelExecution(
|
||||
request: ModelAdmissionRequest,
|
||||
policy: ModelExecutionPolicy,
|
||||
reservation: ModelBudgetReservation | undefined,
|
||||
): ModelAdmission {
|
||||
const names = [request.tenantId, request.projectId, request.jobId, request.modelId, request.dataClass, policy.tenantId, policy.projectId];
|
||||
if (!names.every((s) => typeof s === 'string' && s.trim())
|
||||
|| !Array.isArray(policy.allowedModelIds) || !Array.isArray(policy.allowedDataClasses)
|
||||
|| !['none', 'low', 'medium', 'high', 'restricted'].includes(request.dataClass)
|
||||
|| !['internal', 'external'].includes(policy.destination) || typeof policy.externalTransferAllowed !== 'boolean'
|
||||
|| ![request.maxInputTokens, request.maxOutputTokens, policy.maxInputTokens, policy.maxOutputTokens]
|
||||
.every((n) => Number.isSafeInteger(n) && n > 0)
|
||||
|| !Number.isSafeInteger(request.maximumCredits) || request.maximumCredits < 0) {
|
||||
return { allowed: false, reason: 'invalid_request' };
|
||||
}
|
||||
if (request.tenantId !== policy.tenantId || request.projectId !== policy.projectId) return { allowed: false, reason: 'scope_mismatch' };
|
||||
if (!policy.allowedModelIds.includes(request.modelId)) return { allowed: false, reason: 'model_not_allowed' };
|
||||
if (!policy.allowedDataClasses.includes(request.dataClass)) return { allowed: false, reason: 'data_class_not_allowed' };
|
||||
if (policy.destination === 'external' && (!policy.externalTransferAllowed || ['high', 'restricted'].includes(request.dataClass))) {
|
||||
return { allowed: false, reason: 'external_transfer_denied' };
|
||||
}
|
||||
if (request.maxInputTokens > policy.maxInputTokens || request.maxOutputTokens > policy.maxOutputTokens) {
|
||||
return { allowed: false, reason: 'token_limit_exceeded' };
|
||||
}
|
||||
// maximumCredits === 0 means the operator runs this route without a wallet
|
||||
// (explicit pilot mode), so no reservation is required. Any positive amount
|
||||
// still requires an active, matching reservation.
|
||||
if (request.maximumCredits > 0 && (
|
||||
!reservation || reservation.tenantId !== request.tenantId || reservation.projectId !== request.projectId
|
||||
|| reservation.jobId !== request.jobId || reservation.status !== 'reserved'
|
||||
|| !Number.isSafeInteger(reservation.credits) || reservation.credits < request.maximumCredits)) {
|
||||
return { allowed: false, reason: 'reservation_required' };
|
||||
}
|
||||
return { allowed: true };
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import { SiaxHttp } from '../clients/http';
|
||||
import type { SiaxRequestContext } from '../platform/siax-context';
|
||||
import type { CreditCommand } from './credit-ledger';
|
||||
|
||||
/** This snapshot must come from an immutable server-owned order, never from a browser or webhook payload. */
|
||||
export interface CreditPurchaseSnapshot {
|
||||
tenantId: string;
|
||||
purchaseId: string;
|
||||
checkoutSessionId: string;
|
||||
amountMinor: number;
|
||||
currency: string;
|
||||
credits: number;
|
||||
}
|
||||
|
||||
interface Checkout {
|
||||
id: string;
|
||||
tenant_id: string;
|
||||
payment_intent_id: string;
|
||||
payable_type: string;
|
||||
payable_ref: string;
|
||||
amount_snapshot: number;
|
||||
currency: string;
|
||||
status: string;
|
||||
provider?: string;
|
||||
provider_reference?: string;
|
||||
}
|
||||
interface Intent {
|
||||
id: string;
|
||||
tenant_id: string;
|
||||
payable_type: string;
|
||||
payable_ref: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
canonical_status: string;
|
||||
captured_amount: number;
|
||||
refunded_amount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read PAY0's canonical session and intent before deriving a grant command.
|
||||
* This does not create an order, authenticate a caller, write to the ledger,
|
||||
* or handle a later refund/chargeback. No customer-facing route uses it yet.
|
||||
*/
|
||||
export class Pay0CreditVerifier {
|
||||
private readonly http: SiaxHttp;
|
||||
constructor(baseUrl: string, serviceToken: string) {
|
||||
if (!baseUrl.trim() || !serviceToken.trim())
|
||||
throw new Error('PAY0 URL and service credential are required');
|
||||
this.http = new SiaxHttp({ dependency: 'pay0', baseUrl, token: serviceToken });
|
||||
}
|
||||
|
||||
async verify(snapshot: CreditPurchaseSnapshot, context: SiaxRequestContext): Promise<CreditCommand> {
|
||||
if (
|
||||
!snapshot.tenantId ||
|
||||
!snapshot.purchaseId ||
|
||||
!snapshot.checkoutSessionId ||
|
||||
!Number.isSafeInteger(snapshot.amountMinor) ||
|
||||
snapshot.amountMinor <= 0 ||
|
||||
!Number.isSafeInteger(snapshot.credits) ||
|
||||
snapshot.credits <= 0 ||
|
||||
!/^[A-Z]{3}$/.test(snapshot.currency) ||
|
||||
context.tenantId !== snapshot.tenantId
|
||||
)
|
||||
throw new Error('Invalid or mismatched credit purchase');
|
||||
const checkoutResponse = await this.http.request({
|
||||
method: 'GET',
|
||||
path: `/v1/pay0/checkout-sessions/${encodeURIComponent(snapshot.checkoutSessionId)}`,
|
||||
context,
|
||||
});
|
||||
const checkout = (checkoutResponse.json as { data?: Checkout } | undefined)?.data;
|
||||
if (
|
||||
!checkout ||
|
||||
checkout.id !== snapshot.checkoutSessionId ||
|
||||
checkout.tenant_id !== snapshot.tenantId ||
|
||||
checkout.payable_type !== '0pt_credit_purchase' ||
|
||||
checkout.payable_ref !== snapshot.purchaseId ||
|
||||
checkout.amount_snapshot !== snapshot.amountMinor ||
|
||||
checkout.currency !== snapshot.currency ||
|
||||
checkout.status !== 'completed' ||
|
||||
!checkout.payment_intent_id ||
|
||||
!checkout.provider ||
|
||||
!checkout.provider_reference
|
||||
) {
|
||||
throw new Error('PAY0 checkout does not match a completed credit purchase');
|
||||
}
|
||||
const intentResponse = await this.http.request({
|
||||
method: 'GET',
|
||||
path: `/v1/pay0/payment-intents/${encodeURIComponent(checkout.payment_intent_id)}`,
|
||||
context,
|
||||
});
|
||||
const intent = (intentResponse.json as { data?: Intent } | undefined)?.data;
|
||||
if (
|
||||
!intent ||
|
||||
intent.id !== checkout.payment_intent_id ||
|
||||
intent.tenant_id !== snapshot.tenantId ||
|
||||
intent.payable_type !== '0pt_credit_purchase' ||
|
||||
intent.payable_ref !== snapshot.purchaseId ||
|
||||
intent.amount !== snapshot.amountMinor ||
|
||||
intent.currency !== snapshot.currency ||
|
||||
intent.canonical_status !== 'captured' ||
|
||||
intent.captured_amount !== snapshot.amountMinor ||
|
||||
intent.refunded_amount !== 0
|
||||
) {
|
||||
throw new Error('PAY0 payment intent does not match an unrefunded captured purchase');
|
||||
}
|
||||
return {
|
||||
tenantId: snapshot.tenantId,
|
||||
idempotencyKey: `pay0:credit-purchase:${snapshot.purchaseId}`,
|
||||
kind: 'verified_payment',
|
||||
reference: `pay0:intent:${intent.id}`,
|
||||
amount: snapshot.credits,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
/**
|
||||
* Server-owned, versioned credit price book.
|
||||
*
|
||||
* Prices are a business decision, not a code default: this module never
|
||||
* invents a price. It parses an explicit `OPT_CREDIT_PRICE_BOOK` JSON document
|
||||
* and fails closed when it is missing or invalid, so the checkout route can
|
||||
* answer "price book not configured" instead of charging an arbitrary amount.
|
||||
*
|
||||
* Expected shape (all money in minor units, all quantities safe integers):
|
||||
*
|
||||
* {
|
||||
* "version": "2026-11-01",
|
||||
* "currency": "SEK",
|
||||
* "packs": [{ "id": "starter", "credits": 100, "amountMinor": 9900 }],
|
||||
* "metering": {
|
||||
* "pagesPerCredit": 5,
|
||||
* "inputTokensPerCredit": 20000,
|
||||
* "outputTokensPerCredit": 4000
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
export interface CreditPack {
|
||||
id: string;
|
||||
credits: number;
|
||||
amountMinor: number;
|
||||
}
|
||||
|
||||
export interface CreditMetering {
|
||||
pagesPerCredit: number;
|
||||
inputTokensPerCredit: number;
|
||||
outputTokensPerCredit: number;
|
||||
}
|
||||
|
||||
export interface CreditPriceBook {
|
||||
version: string;
|
||||
currency: string;
|
||||
packs: readonly CreditPack[];
|
||||
metering: CreditMetering;
|
||||
}
|
||||
|
||||
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
|
||||
|
||||
function safePositive(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 && value <= MAX_SAFE;
|
||||
}
|
||||
|
||||
function safePositiveOrZero(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= MAX_SAFE;
|
||||
}
|
||||
|
||||
function parsePack(raw: unknown, currency: string): CreditPack {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new Error('Each credit pack must be an object');
|
||||
}
|
||||
const pack = raw as Record<string, unknown>;
|
||||
if (
|
||||
typeof pack.id !== 'string' ||
|
||||
!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(pack.id) ||
|
||||
!safePositive(pack.credits) ||
|
||||
!safePositive(pack.amountMinor) ||
|
||||
(pack.currency !== undefined && pack.currency !== currency)
|
||||
) {
|
||||
throw new Error('Invalid credit pack');
|
||||
}
|
||||
return { id: pack.id, credits: pack.credits, amountMinor: pack.amountMinor };
|
||||
}
|
||||
|
||||
export function parseCreditPriceBook(raw: unknown): CreditPriceBook {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new Error('Price book must be an object');
|
||||
}
|
||||
const doc = raw as Record<string, unknown>;
|
||||
const version = doc.version;
|
||||
const currency = doc.currency;
|
||||
if (
|
||||
typeof version !== 'string' ||
|
||||
!/^\d{4}-\d{2}-\d{2}(?:\.\d+)?$/.test(version) ||
|
||||
typeof currency !== 'string' ||
|
||||
!/^[A-Z]{3}$/.test(currency) ||
|
||||
!Array.isArray(doc.packs) ||
|
||||
doc.packs.length === 0 ||
|
||||
doc.packs.length > 100
|
||||
) {
|
||||
throw new Error('Invalid price book header or packs');
|
||||
}
|
||||
const packs = doc.packs.map((pack) => parsePack(pack, currency));
|
||||
const ids = new Set(packs.map((pack) => pack.id));
|
||||
if (ids.size !== packs.length) throw new Error('Duplicate credit pack id');
|
||||
if (!doc.metering || typeof doc.metering !== 'object' || Array.isArray(doc.metering)) {
|
||||
throw new Error('Price book metering is required');
|
||||
}
|
||||
const metering = doc.metering as Record<string, unknown>;
|
||||
if (
|
||||
!safePositive(metering.pagesPerCredit) ||
|
||||
!safePositive(metering.inputTokensPerCredit) ||
|
||||
!safePositive(metering.outputTokensPerCredit)
|
||||
) {
|
||||
throw new Error('Invalid metering rates');
|
||||
}
|
||||
return {
|
||||
version,
|
||||
currency,
|
||||
packs,
|
||||
metering: {
|
||||
pagesPerCredit: metering.pagesPerCredit,
|
||||
inputTokensPerCredit: metering.inputTokensPerCredit,
|
||||
outputTokensPerCredit: metering.outputTokensPerCredit,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns `undefined` (fail closed) when the price book is absent or invalid. */
|
||||
export function readCreditPriceBook(env: NodeJS.ProcessEnv = process.env): CreditPriceBook | undefined {
|
||||
const raw = env.OPT_CREDIT_PRICE_BOOK;
|
||||
if (!raw || !raw.trim()) return undefined;
|
||||
try {
|
||||
return parseCreditPriceBook(JSON.parse(raw));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function findPack(book: CreditPriceBook, packId: string): CreditPack | undefined {
|
||||
return book.packs.find((pack) => pack.id === packId);
|
||||
}
|
||||
|
||||
/** Round each metered unit up to its billing block, exactly like credit-quote. */
|
||||
export function creditsForUsage(
|
||||
book: CreditPriceBook,
|
||||
units: { pages: number; inputTokens: number; outputTokens: number },
|
||||
): number {
|
||||
if (
|
||||
!safePositiveOrZero(units.pages) ||
|
||||
!safePositiveOrZero(units.inputTokens) ||
|
||||
!safePositiveOrZero(units.outputTokens)
|
||||
) {
|
||||
throw new Error('Usage units must be nonnegative safe integers');
|
||||
}
|
||||
const blocks =
|
||||
Math.ceil(units.pages / book.metering.pagesPerCredit) +
|
||||
Math.ceil(units.inputTokens / book.metering.inputTokensPerCredit) +
|
||||
Math.ceil(units.outputTokens / book.metering.outputTokensPerCredit);
|
||||
if (!Number.isSafeInteger(blocks) || blocks < 0) {
|
||||
throw new Error('Credit estimate outside supported range');
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* 0pt project authorization for the document workbench.
|
||||
*
|
||||
* Two sources, in order:
|
||||
*
|
||||
* 1. OpenFGA via the universal `@siax/access` primitive (the same one DOC0
|
||||
* uses) when `OPENFGA_API_URL/STORE_ID/MODEL_ID/AUTH_TOKEN` are set.
|
||||
* 2. An explicit, server-owned grant list (`OPT_PROJECT_GRANTS`), a
|
||||
* transitional source for environments where the central relationship
|
||||
* store is not deployed yet.
|
||||
*
|
||||
* FAIL CLOSED: when neither source is configured, or the source is
|
||||
* unavailable, the answer is "no". A grant is never derived from a request
|
||||
* header or body.
|
||||
*
|
||||
* `OPT_PROJECT_GRANTS` shape (JSON array):
|
||||
* [{"tenantId":"379976258701823235","projectId":"prj_alpha","actorId":"*"}]
|
||||
* `actorId: "*"` grants every verified actor in the tenant; otherwise the exact
|
||||
* actor must match.
|
||||
*/
|
||||
import { OpenFgaRelationships, isProjectAccessAllowed } from '@siax/access';
|
||||
import { readDocumentWorkbenchRuntime } from './runtime-config';
|
||||
|
||||
export interface ProjectScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
export type ProjectAuthorizer = (scope: ProjectScope) => Promise<boolean>;
|
||||
|
||||
interface ProjectGrant {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const scopeId = /^[\x21-\x7e]{1,256}$/;
|
||||
|
||||
export function parseProjectGrants(raw: string | undefined): ProjectGrant[] | undefined {
|
||||
if (!raw || !raw.trim()) return undefined;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > 1000) {
|
||||
return undefined;
|
||||
}
|
||||
const grants: ProjectGrant[] = [];
|
||||
for (const entry of parsed) {
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return undefined;
|
||||
const grant = entry as Record<string, unknown>;
|
||||
if (
|
||||
typeof grant.tenantId !== 'string' ||
|
||||
!scopeId.test(grant.tenantId) ||
|
||||
typeof grant.projectId !== 'string' ||
|
||||
!scopeId.test(grant.projectId) ||
|
||||
typeof grant.actorId !== 'string' ||
|
||||
(grant.actorId !== '*' && !scopeId.test(grant.actorId))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
grants.push({
|
||||
tenantId: grant.tenantId,
|
||||
projectId: grant.projectId,
|
||||
actorId: grant.actorId,
|
||||
});
|
||||
}
|
||||
return grants;
|
||||
}
|
||||
|
||||
export function createProjectAuthorizer(env: NodeJS.ProcessEnv = process.env): ProjectAuthorizer {
|
||||
const runtime = readDocumentWorkbenchRuntime(env);
|
||||
let relationships: OpenFgaRelationships | undefined;
|
||||
if (runtime.openfga) {
|
||||
try {
|
||||
relationships = new OpenFgaRelationships(runtime.openfga);
|
||||
} catch {
|
||||
relationships = undefined;
|
||||
}
|
||||
}
|
||||
const grants = parseProjectGrants(env.OPT_PROJECT_GRANTS);
|
||||
|
||||
return async (scope) => {
|
||||
if (!scopeId.test(scope.tenantId) || !scopeId.test(scope.projectId) || !scopeId.test(scope.actorId)) {
|
||||
return false;
|
||||
}
|
||||
if (relationships) {
|
||||
return isProjectAccessAllowed(scope, { relationships });
|
||||
}
|
||||
if (!grants) return false;
|
||||
return grants.some(
|
||||
(grant) =>
|
||||
grant.tenantId === scope.tenantId &&
|
||||
grant.projectId === scope.projectId &&
|
||||
(grant.actorId === '*' || grant.actorId === scope.actorId),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/** True when the server has enough configuration to authorize at all. */
|
||||
export function projectAuthorizationConfigured(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
if (readDocumentWorkbenchRuntime(env).openfga) return true;
|
||||
return Boolean(parseProjectGrants(env.OPT_PROJECT_GRANTS));
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { SiaxRequestContext } from '../platform/siax-context';
|
||||
import type { PostgresCreditLedger } from './credit-ledger';
|
||||
import type { PostgresCreditPurchaseStore } from './credit-purchase-store';
|
||||
import type { Pay0CreditVerifier } from './pay0-credit-verification';
|
||||
|
||||
/** Internal reconciliation only; caller is responsible for authentication and scheduling. */
|
||||
export async function reconcileCreditPurchase(
|
||||
deps: { purchases: PostgresCreditPurchaseStore; pay0: Pay0CreditVerifier; ledger: PostgresCreditLedger },
|
||||
tenantId: string,
|
||||
purchaseId: string,
|
||||
context: SiaxRequestContext,
|
||||
) {
|
||||
if (!tenantId || !purchaseId || context.tenantId !== tenantId) throw new Error('Invalid purchase scope');
|
||||
const snapshot = await deps.purchases.get(tenantId, purchaseId);
|
||||
if (!snapshot) throw new Error('Credit purchase not found');
|
||||
const command = await deps.pay0.verify(snapshot, context);
|
||||
return deps.ledger.apply(command);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/**
|
||||
* Server-side runtime configuration for the document workbench.
|
||||
*
|
||||
* Every integration is optional to BOOT and mandatory to USE: a route that
|
||||
* needs DOC0/INF0/PAY0 returns a typed "not configured" error instead of
|
||||
* fabricating success. URLs must be trusted HTTPS endpoints; tokens are never
|
||||
* logged or returned.
|
||||
*
|
||||
* This module is deliberately framework-neutral and free of product imports so
|
||||
* it can be lifted into a shared package without change.
|
||||
*/
|
||||
|
||||
export interface HttpsEndpoint {
|
||||
baseUrl: string;
|
||||
serviceToken: string;
|
||||
}
|
||||
|
||||
export interface DocumentWorkbenchRuntime {
|
||||
doc0?: HttpsEndpoint & { maxUploadBytes: number; actorId?: string };
|
||||
inf0?: HttpsEndpoint;
|
||||
pay0?: HttpsEndpoint;
|
||||
n0d?: HttpsEndpoint;
|
||||
st0re?: HttpsEndpoint;
|
||||
openfga?: {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
};
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
function first(...values: Array<string | undefined>): string | undefined {
|
||||
for (const value of values) {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Only absolute HTTPS endpoints with no credentials/query/hash are trusted. */
|
||||
export function isTrustedHttpsUrl(value: string | undefined): value is string {
|
||||
if (!value) return false;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function endpoint(
|
||||
env: NodeJS.ProcessEnv,
|
||||
urlNames: readonly string[],
|
||||
tokenNames: readonly string[],
|
||||
): HttpsEndpoint | undefined {
|
||||
const baseUrl = first(...urlNames.map((name) => env[name]));
|
||||
const serviceToken = first(...tokenNames.map((name) => env[name]));
|
||||
if (!isTrustedHttpsUrl(baseUrl) || !serviceToken) return undefined;
|
||||
return { baseUrl: baseUrl.replace(/\/+$/, ''), serviceToken };
|
||||
}
|
||||
|
||||
function positiveInt(value: string | undefined, fallback: number): number {
|
||||
if (!value) return fallback;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
export function readDocumentWorkbenchRuntime(env: NodeJS.ProcessEnv = process.env): DocumentWorkbenchRuntime {
|
||||
const doc0 = endpoint(env, ['DOC0_URL', 'DOC0_API_URL'], ['DOC0_SERVICE_TOKEN', 'DOC0_SVC_PAT']);
|
||||
const inf0 = endpoint(env, ['INF0_URL', 'INF0_API_URL'], ['INF0_API_TOKEN', 'INF0_SERVICE_TOKEN']);
|
||||
const pay0 = endpoint(env, ['PAY0_URL', 'PAY0_API_URL'], ['PAY0_API_TOKEN', 'PAY0_SERVICE_TOKEN']);
|
||||
const n0d = endpoint(env, ['N0D_URL', 'N0D_API_URL'], ['N0D_API_TOKEN', 'N0D_SERVICE_TOKEN']);
|
||||
const st0re = endpoint(env, ['ST0RE_URL', 'ST0RE_API_URL'], ['ST0RE_API_TOKEN', 'ST0RE_SERVICE_TOKEN']);
|
||||
|
||||
const openfgaBase = first(env.OPENFGA_API_URL);
|
||||
const openfgaStore = first(env.OPENFGA_STORE_ID);
|
||||
const openfgaModel = first(env.OPENFGA_MODEL_ID);
|
||||
const openfgaToken = first(env.OPENFGA_AUTH_TOKEN, env.OPENFGA_AUTH_KEY);
|
||||
|
||||
return {
|
||||
...(doc0
|
||||
? {
|
||||
doc0: {
|
||||
...doc0,
|
||||
maxUploadBytes: positiveInt(env.OPT_MAX_UPLOAD_BYTES, DEFAULT_MAX_UPLOAD_BYTES),
|
||||
...(env.DOC0_SERVICE_ACTOR_ID ? { actorId: env.DOC0_SERVICE_ACTOR_ID.trim() } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(inf0 ? { inf0 } : {}),
|
||||
...(pay0 ? { pay0 } : {}),
|
||||
...(n0d ? { n0d } : {}),
|
||||
...(st0re ? { st0re } : {}),
|
||||
...(isTrustedHttpsUrl(openfgaBase) && openfgaStore && openfgaModel && openfgaToken
|
||||
? {
|
||||
openfga: {
|
||||
baseUrl: openfgaBase.replace(/\/+$/, ''),
|
||||
storeId: openfgaStore,
|
||||
modelId: openfgaModel,
|
||||
serviceToken: openfgaToken,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/**
|
||||
* Deterministic, locale-aware value parsing used for evidence checks.
|
||||
*
|
||||
* The model sees text; code decides whether a source span really supports a
|
||||
* value. These helpers never guess when a format is ambiguous: a span that can
|
||||
* be read two ways yields no match, and the field goes to review.
|
||||
*/
|
||||
|
||||
function isCalendarDate(year: number, month: number, day: number): boolean {
|
||||
if (year < 1 || month < 1 || month > 12 || day < 1) return false;
|
||||
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return day <= days[month - 1]!;
|
||||
}
|
||||
|
||||
const pad = (n: number): string => String(n).padStart(2, '0');
|
||||
|
||||
/** Returns every unambiguous ISO rendering of the span (empty when ambiguous). */
|
||||
export function dateCandidates(text: string): string[] {
|
||||
const t = text.trim();
|
||||
const iso = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(t);
|
||||
if (iso) {
|
||||
const [y, m, d] = [Number(iso[1]), Number(iso[2]), Number(iso[3])];
|
||||
return isCalendarDate(y, m, d) ? [`${y}-${pad(m)}-${pad(d)}`] : [];
|
||||
}
|
||||
const compact = /^(\d{4})(\d{2})(\d{2})$/.exec(t);
|
||||
if (compact) {
|
||||
const [y, m, d] = [Number(compact[1]), Number(compact[2]), Number(compact[3])];
|
||||
return isCalendarDate(y, m, d) ? [`${y}-${pad(m)}-${pad(d)}`] : [];
|
||||
}
|
||||
const numeric = /^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/.exec(t);
|
||||
if (numeric) {
|
||||
const a = Number(numeric[1]);
|
||||
const b = Number(numeric[2]);
|
||||
const y = Number(numeric[3]);
|
||||
// Both day-first and month-first are possible for <=12/<=12: no match.
|
||||
if (a <= 12 && b <= 12) return [];
|
||||
const [day, month] = a > 12 ? [a, b] : [b, a];
|
||||
return isCalendarDate(y, month, day) ? [`${y}-${pad(month)}-${pad(day)}`] : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Returns every unambiguous decimal rendering of the span. */
|
||||
export function decimalCandidates(text: string): string[] {
|
||||
const t = text.trim().replace(/[\s\u00a0\u202f]/g, '');
|
||||
if (!/^[+-]?[\d.,]+$/.test(t) || !/\d/.test(t)) return [];
|
||||
const sign = t.startsWith('-') ? '-' : '';
|
||||
const body = t.replace(/^[+-]/, '');
|
||||
const hasComma = body.includes(',');
|
||||
const hasDot = body.includes('.');
|
||||
const out = new Set<string>();
|
||||
const add = (value: string) => {
|
||||
if (/^(0|[1-9]\d*)(\.\d+)?$/.test(value)) out.add(`${sign}${value}`);
|
||||
};
|
||||
if (hasComma && hasDot) {
|
||||
const lastComma = body.lastIndexOf(',');
|
||||
const lastDot = body.lastIndexOf('.');
|
||||
if (lastComma > lastDot) add(body.replace(/\./g, '').replace(',', '.'));
|
||||
else add(body.replace(/,/g, ''));
|
||||
} else if (hasComma) {
|
||||
const parts = body.split(',');
|
||||
if (parts.length === 2 && parts[1]!.length <= 2) add(`${parts[0]}.${parts[1]}`);
|
||||
add(body.replace(/,/g, ''));
|
||||
} else if (hasDot) {
|
||||
const parts = body.split('.');
|
||||
if (parts.length === 2 && parts[1]!.length <= 2) add(body);
|
||||
add(body.replace(/\./g, ''));
|
||||
} else {
|
||||
add(body);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical decimal string: no exponent, no leading '+', no trailing zeros in
|
||||
* the fraction. Used only for equality checks; the delivered value keeps its
|
||||
* original precision.
|
||||
*/
|
||||
export function canonicalDecimal(value: string): string | undefined {
|
||||
const match = /^([+-]?)(0|[1-9]\d*)(?:\.(\d+))?$/.exec(value.trim());
|
||||
if (!match) return undefined;
|
||||
const sign = match[1] === '-' ? '-' : '';
|
||||
const fraction = (match[3] ?? '').replace(/0+$/, '');
|
||||
return `${sign}${match[2]}${fraction ? `.${fraction}` : ''}`;
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
import type Stripe from 'stripe';
|
||||
import type { CreditCommand } from './credit-ledger';
|
||||
import type { CreditPurchaseSnapshot } from './pay0-credit-verification';
|
||||
|
||||
/**
|
||||
* Stripe-backed credit verification.
|
||||
*
|
||||
* The webhook is only a trigger: this class re-reads the checkout session and
|
||||
* its payment intent from Stripe and derives the grant from that authoritative
|
||||
* response. Nothing in the webhook body is trusted for price, credits or
|
||||
* tenant. The resulting command is idempotent per (tenant, purchase).
|
||||
*
|
||||
* This does not implement refunds, chargebacks or partial captures beyond
|
||||
* refusing to grant when Stripe reports anything other than a fully paid,
|
||||
* unrefunded session.
|
||||
*/
|
||||
export interface StripeCheckoutReader {
|
||||
checkout: {
|
||||
sessions: {
|
||||
retrieve(id: string, options: { expand: string[] }): Promise<Stripe.Checkout.Session>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export class StripeCreditVerificationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly reason: 'not_found' | 'mismatch' | 'not_paid' | 'refunded' | 'unsupported',
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'StripeCreditVerificationError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function verifyStripeCreditPurchase(
|
||||
stripe: StripeCheckoutReader,
|
||||
snapshot: CreditPurchaseSnapshot,
|
||||
context: { tenantId: string },
|
||||
): Promise<CreditCommand> {
|
||||
if (
|
||||
context.tenantId !== snapshot.tenantId ||
|
||||
!snapshot.checkoutSessionId.trim() ||
|
||||
!Number.isSafeInteger(snapshot.credits) ||
|
||||
snapshot.credits <= 0
|
||||
) {
|
||||
throw new StripeCreditVerificationError('Invalid or mismatched credit purchase', 'mismatch');
|
||||
}
|
||||
|
||||
const session = await stripe.checkout.sessions.retrieve(snapshot.checkoutSessionId, {
|
||||
expand: ['payment_intent'],
|
||||
});
|
||||
|
||||
if (session.id !== snapshot.checkoutSessionId) {
|
||||
throw new StripeCreditVerificationError('Session id mismatch', 'mismatch');
|
||||
}
|
||||
if (
|
||||
session.metadata?.kind !== '0pt_credit_purchase' ||
|
||||
session.metadata?.tenant_id !== snapshot.tenantId ||
|
||||
session.metadata?.purchase_id !== snapshot.purchaseId
|
||||
) {
|
||||
throw new StripeCreditVerificationError('Session metadata does not belong to this purchase', 'mismatch');
|
||||
}
|
||||
if (
|
||||
session.amount_total !== snapshot.amountMinor ||
|
||||
session.currency?.toUpperCase() !== snapshot.currency
|
||||
) {
|
||||
throw new StripeCreditVerificationError(
|
||||
'Session amount or currency does not match the server price snapshot',
|
||||
'mismatch',
|
||||
);
|
||||
}
|
||||
if (session.payment_status !== 'paid') {
|
||||
throw new StripeCreditVerificationError('Session is not paid', 'not_paid');
|
||||
}
|
||||
|
||||
const intent = session.payment_intent;
|
||||
if (!intent || typeof intent === 'string') {
|
||||
throw new StripeCreditVerificationError('Payment intent was not expanded', 'unsupported');
|
||||
}
|
||||
if (
|
||||
intent.status !== 'succeeded' ||
|
||||
intent.currency?.toUpperCase() !== snapshot.currency ||
|
||||
(typeof intent.amount_received === 'number' && intent.amount_received < snapshot.amountMinor)
|
||||
) {
|
||||
throw new StripeCreditVerificationError(
|
||||
'Payment intent is not a completed capture of the snapshot amount',
|
||||
'not_paid',
|
||||
);
|
||||
}
|
||||
return {
|
||||
tenantId: snapshot.tenantId,
|
||||
idempotencyKey: `credit_purchase:${snapshot.tenantId}:${snapshot.purchaseId}`,
|
||||
kind: 'verified_payment',
|
||||
reference: intent.id,
|
||||
amount: snapshot.credits,
|
||||
};
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,68 +0,0 @@
|
||||
import { validateStructuredOutput, type FieldEvidence, type OutputFieldContract, type TextSource, type ValidationIssue } from './structured-output-validation';
|
||||
import { exportValidatedOutput } from './export-validated-output';
|
||||
|
||||
/** Each row is independently supported by spans in the original source texts. */
|
||||
export interface EvidencedRecord { value: Record<string, unknown>; evidence: FieldEvidence[] }
|
||||
export interface BatchIssue extends ValidationIssue { row?: number }
|
||||
export type BatchValidation =
|
||||
| { status: 'mechanically_validated'; records: EvidencedRecord[] }
|
||||
| { status: 'needs_review'; issues: BatchIssue[] };
|
||||
|
||||
const MAX_RECORDS = 200;
|
||||
|
||||
/** This gate cannot establish that the model found every source record. */
|
||||
export function validateStructuredBatch(input: {
|
||||
fields: readonly OutputFieldContract[];
|
||||
sources: readonly TextSource[];
|
||||
records: unknown;
|
||||
}): BatchValidation {
|
||||
if (!Array.isArray(input.records) || input.records.length === 0 || input.records.length > MAX_RECORDS) {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'invalid_record_count' }] };
|
||||
}
|
||||
const issues: BatchIssue[] = [];
|
||||
const records: EvidencedRecord[] = [];
|
||||
for (const [row, candidate] of input.records.entries()) {
|
||||
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)
|
||||
|| ![Object.prototype, null].includes(Object.getPrototypeOf(candidate))
|
||||
|| Object.keys(candidate).some((key) => key !== 'value' && key !== 'evidence')) {
|
||||
issues.push({ row, field: '', code: 'invalid_record' });
|
||||
continue;
|
||||
}
|
||||
const record = candidate as { value?: unknown; evidence?: unknown };
|
||||
if (!Array.isArray(record.evidence)) {
|
||||
issues.push({ row, field: '', code: 'invalid_evidence' });
|
||||
continue;
|
||||
}
|
||||
const validation = validateStructuredOutput({ fields: input.fields, sources: input.sources, value: record.value, evidence: record.evidence });
|
||||
if (validation.status === 'needs_review') issues.push(...validation.issues.map((issue) => ({ row, ...issue })));
|
||||
else records.push({ value: record.value as Record<string, unknown>, evidence: record.evidence as FieldEvidence[] });
|
||||
}
|
||||
return issues.length ? { status: 'needs_review', issues } : { status: 'mechanically_validated', records };
|
||||
}
|
||||
|
||||
/** Revalidate every row immediately before export; never return partial output. */
|
||||
export function exportValidatedBatch(input: {
|
||||
format: 'json' | 'csv'; fields: readonly OutputFieldContract[];
|
||||
sources: readonly TextSource[]; records: unknown;
|
||||
}):
|
||||
| { status: 'ready'; mediaType: 'application/json' | 'text/csv'; content: string }
|
||||
| { status: 'needs_review'; issues: BatchIssue[] } {
|
||||
if (input.format !== 'json' && input.format !== 'csv') {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'unsupported_export_format' }] };
|
||||
}
|
||||
const validation = validateStructuredBatch(input);
|
||||
if (validation.status !== 'mechanically_validated') return validation;
|
||||
const serialized: string[] = [];
|
||||
for (const [row, record] of validation.records.entries()) {
|
||||
const result = exportValidatedOutput({ ...input, ...record });
|
||||
if (result.status !== 'ready') return { status: 'needs_review', issues: result.issues.map((issue) => ({ row, ...issue })) };
|
||||
serialized.push(result.content);
|
||||
}
|
||||
if (input.format === 'json') {
|
||||
return { status: 'ready', mediaType: 'application/json', content: `[\n${serialized.map((s) => s.trim()).join(',\n')}\n]\n` };
|
||||
}
|
||||
const quote = (cell: string) => `"${cell.replaceAll('"', '""')}"`;
|
||||
const header = input.fields.map((field) => quote(field.name)).join(',');
|
||||
const rows = validation.records.map((record) => input.fields.map((field) => quote(String(record.value[field.name]))).join(','));
|
||||
return { status: 'ready', mediaType: 'text/csv', content: `${header}\r\n${rows.join('\r\n')}\r\n` };
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/**
|
||||
* Narrow, deterministic first-version output gate. Source offsets are UTF-16
|
||||
* indices into the exact, versioned extracted text supplied by the caller.
|
||||
* This validates mechanical support, not whether the selected source is true,
|
||||
* complete, correctly OCR'd, or semantically represents the requested field.
|
||||
*/
|
||||
import { dateCandidates, decimalCandidates } from './source-values';
|
||||
|
||||
export type OutputFieldType = 'string' | 'integer' | 'boolean' | 'decimal' | 'date';
|
||||
export interface OutputFieldContract {
|
||||
name: string;
|
||||
type: OutputFieldType;
|
||||
required: boolean;
|
||||
}
|
||||
export interface TextSource {
|
||||
id: string;
|
||||
text: string;
|
||||
}
|
||||
export interface FieldEvidence {
|
||||
field: string;
|
||||
sourceId: string;
|
||||
start: number;
|
||||
end: number;
|
||||
transform: 'exact' | 'trim' | 'integer' | 'boolean' | 'decimal' | 'date';
|
||||
}
|
||||
export interface ValidationIssue {
|
||||
field: string;
|
||||
code: string;
|
||||
}
|
||||
export type OutputValidation =
|
||||
{ status: 'mechanically_validated'; issues: [] } | { status: 'needs_review'; issues: ValidationIssue[] };
|
||||
|
||||
/** ISO dates are validated as calendar dates without timezone conversion. */
|
||||
function isIsoDate(value: string): boolean {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||
if (!match) return false;
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (year < 1 || month < 1 || month > 12) return false;
|
||||
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return day >= 1 && day <= days[month - 1]!;
|
||||
}
|
||||
|
||||
/** Fail closed for malformed contracts, extra fields, missing evidence and mismatches. */
|
||||
export function validateStructuredOutput(input: {
|
||||
fields: readonly OutputFieldContract[];
|
||||
value: unknown;
|
||||
sources: readonly TextSource[];
|
||||
evidence: readonly FieldEvidence[];
|
||||
}): OutputValidation {
|
||||
const issues: ValidationIssue[] = [];
|
||||
const add = (field: string, code: string) => issues.push({ field, code });
|
||||
if (
|
||||
!Array.isArray(input.fields) ||
|
||||
input.fields.length === 0 ||
|
||||
!Array.isArray(input.sources) ||
|
||||
!Array.isArray(input.evidence)
|
||||
) {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'invalid_contract' }] };
|
||||
}
|
||||
const fields = new Map<string, OutputFieldContract>();
|
||||
for (const field of input.fields) {
|
||||
if (
|
||||
!field ||
|
||||
typeof field.name !== 'string' ||
|
||||
!field.name.trim() ||
|
||||
fields.has(field.name) ||
|
||||
!['string', 'integer', 'boolean', 'decimal', 'date'].includes(field.type) ||
|
||||
typeof field.required !== 'boolean'
|
||||
) {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'invalid_contract' }] };
|
||||
}
|
||||
fields.set(field.name, field);
|
||||
}
|
||||
const sources = new Map<string, string>();
|
||||
for (const source of input.sources) {
|
||||
if (
|
||||
!source ||
|
||||
typeof source.id !== 'string' ||
|
||||
!source.id.trim() ||
|
||||
typeof source.text !== 'string' ||
|
||||
sources.has(source.id)
|
||||
) {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'invalid_source' }] };
|
||||
}
|
||||
sources.set(source.id, source.text);
|
||||
}
|
||||
if (
|
||||
!input.value ||
|
||||
typeof input.value !== 'object' ||
|
||||
Array.isArray(input.value) ||
|
||||
![Object.prototype, null].includes(Object.getPrototypeOf(input.value))
|
||||
) {
|
||||
return { status: 'needs_review', issues: [{ field: '', code: 'invalid_output' }] };
|
||||
}
|
||||
const output = input.value as Record<string, unknown>;
|
||||
for (const key of Object.keys(output)) if (!fields.has(key)) add(key, 'unexpected_field');
|
||||
for (const evidence of input.evidence) {
|
||||
if (
|
||||
!evidence ||
|
||||
typeof evidence.field !== 'string' ||
|
||||
!fields.has(evidence.field) ||
|
||||
!Object.prototype.hasOwnProperty.call(output, evidence.field)
|
||||
)
|
||||
add(evidence?.field ?? '', 'unexpected_evidence');
|
||||
}
|
||||
for (const [name, field] of fields) {
|
||||
const present = Object.prototype.hasOwnProperty.call(output, name);
|
||||
if (!present) {
|
||||
if (field.required) add(name, 'missing_required');
|
||||
continue;
|
||||
}
|
||||
const value = output[name];
|
||||
if (
|
||||
(['string', 'decimal', 'date'].includes(field.type) && typeof value !== 'string') ||
|
||||
(field.type === 'boolean' && typeof value !== 'boolean') ||
|
||||
(field.type === 'integer' && (typeof value !== 'number' || !Number.isSafeInteger(value)))
|
||||
) {
|
||||
add(name, 'invalid_type');
|
||||
continue;
|
||||
}
|
||||
const evidence = input.evidence.filter((entry) => entry?.field === name);
|
||||
if (evidence.length !== 1) {
|
||||
add(name, 'evidence_required');
|
||||
continue;
|
||||
}
|
||||
const ref = evidence[0]!;
|
||||
const text = sources.get(ref.sourceId);
|
||||
if (
|
||||
typeof text !== 'string' ||
|
||||
!Number.isSafeInteger(ref.start) ||
|
||||
!Number.isSafeInteger(ref.end) ||
|
||||
ref.start < 0 ||
|
||||
ref.end <= ref.start ||
|
||||
ref.end > text.length
|
||||
) {
|
||||
add(name, 'invalid_source_range');
|
||||
continue;
|
||||
}
|
||||
const excerpt = text.slice(ref.start, ref.end);
|
||||
let matched = false;
|
||||
if (field.type === 'string' && ref.transform === 'exact') matched = excerpt === value;
|
||||
else if (field.type === 'string' && ref.transform === 'trim') matched = excerpt.trim() === value;
|
||||
else if (
|
||||
field.type === 'integer' &&
|
||||
ref.transform === 'integer' &&
|
||||
/^-?(0|[1-9][0-9]*)$/.test(excerpt.trim())
|
||||
) {
|
||||
const number = Number(excerpt.trim());
|
||||
matched = Number.isSafeInteger(number) && number === value;
|
||||
} else if (
|
||||
field.type === 'boolean' &&
|
||||
ref.transform === 'boolean' &&
|
||||
['true', 'false'].includes(excerpt.trim())
|
||||
) {
|
||||
matched = (excerpt.trim() === 'true') === value;
|
||||
} else if (field.type === 'decimal' && ref.transform === 'decimal' && typeof value === 'string') {
|
||||
// Keep the exact decimal string: floating point would lose money precision.
|
||||
// The span may be locale-formatted ("12 500,00"); only unambiguous
|
||||
// renderings count, so "1,234" cannot silently become either 1.234 or 1234.
|
||||
matched = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value) && decimalCandidates(excerpt).includes(value);
|
||||
} else if (field.type === 'date' && ref.transform === 'date' && typeof value === 'string') {
|
||||
matched = isIsoDate(value) && dateCandidates(excerpt).includes(value);
|
||||
}
|
||||
if (!matched) add(name, 'evidence_mismatch');
|
||||
}
|
||||
return issues.length
|
||||
? { status: 'needs_review', issues }
|
||||
: { status: 'mechanically_validated', issues: [] };
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* Deterministic admission boundary for a document agent's tool proposal.
|
||||
* This module selects from an operator-supplied registry; it never executes a
|
||||
* tool, authenticates a user, or grants access to customer data by itself.
|
||||
*/
|
||||
|
||||
export interface DocumentTool {
|
||||
id: string;
|
||||
version: string;
|
||||
installed: boolean;
|
||||
licenseApproved: boolean;
|
||||
supportedMimeTypes: readonly string[];
|
||||
supportedDataClasses: readonly string[];
|
||||
/** True whenever execution sends content outside the approved environment. */
|
||||
externalTransfer: boolean;
|
||||
}
|
||||
|
||||
export interface DocumentToolPolicy {
|
||||
allowedToolIds: readonly string[];
|
||||
allowedExternalToolIds: readonly string[];
|
||||
dataClass: string;
|
||||
}
|
||||
|
||||
export type ToolSelection =
|
||||
| { allowed: true; tool: DocumentTool }
|
||||
| {
|
||||
allowed: false;
|
||||
reason:
|
||||
| 'invalid_input'
|
||||
| 'unknown_tool'
|
||||
| 'ambiguous_registry'
|
||||
| 'not_authorized'
|
||||
| 'not_ready'
|
||||
| 'unsupported_format'
|
||||
| 'unsupported_data_class'
|
||||
| 'external_transfer_denied';
|
||||
};
|
||||
|
||||
/** The MIME type must be established by the content-inspection stage, not the agent. */
|
||||
export function selectDocumentTool(input: {
|
||||
proposedToolId: unknown;
|
||||
detectedMimeType: string;
|
||||
registry: readonly DocumentTool[];
|
||||
policy: DocumentToolPolicy;
|
||||
}): ToolSelection {
|
||||
const { proposedToolId, detectedMimeType, registry, policy } = input;
|
||||
if (
|
||||
typeof proposedToolId !== 'string' ||
|
||||
!proposedToolId.trim() ||
|
||||
!detectedMimeType.trim() ||
|
||||
!policy.dataClass.trim()
|
||||
) {
|
||||
return { allowed: false, reason: 'invalid_input' };
|
||||
}
|
||||
const matches = registry.filter((entry) => entry.id === proposedToolId);
|
||||
if (matches.length === 0) return { allowed: false, reason: 'unknown_tool' };
|
||||
if (matches.length !== 1) return { allowed: false, reason: 'ambiguous_registry' };
|
||||
const tool = matches[0]!;
|
||||
if (!policy.allowedToolIds.includes(tool.id)) return { allowed: false, reason: 'not_authorized' };
|
||||
if (
|
||||
tool.installed !== true ||
|
||||
tool.licenseApproved !== true ||
|
||||
typeof tool.version !== 'string' ||
|
||||
!tool.version.trim() ||
|
||||
(tool.externalTransfer !== true && tool.externalTransfer !== false)
|
||||
)
|
||||
return { allowed: false, reason: 'not_ready' };
|
||||
if (!tool.supportedMimeTypes.includes(detectedMimeType))
|
||||
return { allowed: false, reason: 'unsupported_format' };
|
||||
if (!tool.supportedDataClasses.includes(policy.dataClass))
|
||||
return { allowed: false, reason: 'unsupported_data_class' };
|
||||
if (tool.externalTransfer && !policy.allowedExternalToolIds.includes(tool.id)) {
|
||||
return { allowed: false, reason: 'external_transfer_denied' };
|
||||
}
|
||||
return { allowed: true, tool };
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/**
|
||||
* One-time trial credits.
|
||||
*
|
||||
* A new tenant can be granted a fixed, server-owned amount so the credit
|
||||
* ledger (reserve → settle) works in production without a card charge. It is
|
||||
* idempotent per tenant: the ledger's unique (tenant, idempotency_key) makes
|
||||
* every repeat a replay, never a second grant. The amount is never read from a
|
||||
* client; `OPT_TRIAL_CREDITS=0` (default) disables it entirely.
|
||||
*/
|
||||
export interface CreditCommandSink {
|
||||
apply(command: {
|
||||
tenantId: string;
|
||||
idempotencyKey: string;
|
||||
kind: 'grant';
|
||||
reference: string;
|
||||
amount: number;
|
||||
}): Promise<unknown>;
|
||||
}
|
||||
|
||||
export function readTrialCredits(env: NodeJS.ProcessEnv = process.env): number {
|
||||
const parsed = Number(env.OPT_TRIAL_CREDITS ?? '0');
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 0 || parsed > 1_000_000) return 0;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function ensureTrialCredits(
|
||||
ledger: CreditCommandSink,
|
||||
tenantId: string,
|
||||
amount: number,
|
||||
): Promise<void> {
|
||||
if (!Number.isSafeInteger(amount) || amount <= 0) return;
|
||||
if (typeof tenantId !== 'string' || !tenantId.trim()) return;
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `trial:${tenantId}`,
|
||||
kind: 'grant',
|
||||
reference: `trial:${tenantId}`,
|
||||
amount,
|
||||
});
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
import type { RepositorySql } from '../repositories/db';
|
||||
import type postgres from 'postgres';
|
||||
|
||||
/** All scope values must come from authenticated and project-authorized context. */
|
||||
export interface UploadAttemptIdentity {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
/** Also used as the original DOC0 idempotency key by the future caller. */
|
||||
attemptId: string;
|
||||
sourceSha256: string;
|
||||
sourceSizeBytes: number;
|
||||
requestFingerprint: string;
|
||||
}
|
||||
export type UploadAttemptState = 'prepared' | 'dispatch_started';
|
||||
export interface StoredUploadReceipt {
|
||||
documentId: string;
|
||||
versionId: string;
|
||||
checksumSha256: string;
|
||||
pipelineStage: string;
|
||||
}
|
||||
interface Row {
|
||||
source_sha256: string;
|
||||
source_size_bytes: string;
|
||||
request_fingerprint: string;
|
||||
state: UploadAttemptState;
|
||||
}
|
||||
|
||||
function validate(input: UploadAttemptIdentity): void {
|
||||
if (
|
||||
![input.tenantId, input.projectId, input.actorId, input.attemptId].every(
|
||||
(value) => typeof value === 'string' && value.trim().length > 0 && value.length <= 256,
|
||||
) ||
|
||||
!/^[0-9a-f]{64}$/.test(input.sourceSha256) ||
|
||||
!/^[0-9a-f]{64}$/.test(input.requestFingerprint) ||
|
||||
!Number.isSafeInteger(input.sourceSizeBytes) ||
|
||||
input.sourceSizeBytes <= 0
|
||||
) {
|
||||
throw new Error('Invalid document upload attempt');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal, one-way coordination primitive; not an authentication, project
|
||||
* authorization or content-integrity check. Callers must persist the exact
|
||||
* DOC0-compatible fingerprint and verify actual uploaded bytes themselves.
|
||||
* RLS session settings are set only inside each transaction; the database
|
||||
* role must not be superuser or BYPASSRLS. A started dispatch is never
|
||||
* automatically retried or declared absent. No customer route is wired.
|
||||
*/
|
||||
export class PostgresUploadAttemptStore {
|
||||
constructor(private readonly sql: RepositorySql) {}
|
||||
|
||||
private async scoped<T>(
|
||||
input: UploadAttemptIdentity,
|
||||
action: (tx: postgres.TransactionSql) => Promise<T>,
|
||||
): Promise<T> {
|
||||
validate(input);
|
||||
return this.sql.begin(async (tx) => {
|
||||
const roles = await tx<{ rolsuper: boolean; rolbypassrls: boolean }[]>`
|
||||
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`;
|
||||
if (!roles[0] || roles[0].rolsuper || roles[0].rolbypassrls)
|
||||
throw new Error('Upload attempts require an RLS-enforced database role');
|
||||
await tx`SELECT set_config('app.opt_tenant_id', ${input.tenantId}, true), set_config('app.opt_project_id', ${input.projectId}, true), set_config('app.opt_actor_id', ${input.actorId}, true)`;
|
||||
return action(tx);
|
||||
}) as Promise<T>;
|
||||
}
|
||||
|
||||
async prepare(input: UploadAttemptIdentity): Promise<{ state: UploadAttemptState; replay: boolean }> {
|
||||
return this.scoped(input, async (tx) => {
|
||||
const inserted = await tx<Row[]>`
|
||||
INSERT INTO opt_document_upload_attempts (tenant_id,project_id,actor_id,attempt_id,source_sha256,source_size_bytes,request_fingerprint,state)
|
||||
VALUES (${input.tenantId},${input.projectId},${input.actorId},${input.attemptId},${input.sourceSha256},${input.sourceSizeBytes},${input.requestFingerprint},'prepared')
|
||||
ON CONFLICT (tenant_id,attempt_id) DO NOTHING RETURNING source_sha256,source_size_bytes,request_fingerprint,state`;
|
||||
const rows = inserted.length
|
||||
? inserted
|
||||
: await tx<Row[]>`
|
||||
SELECT source_sha256,source_size_bytes,request_fingerprint,state FROM opt_document_upload_attempts
|
||||
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId} AND attempt_id=${input.attemptId}`;
|
||||
const row = rows[0];
|
||||
if (
|
||||
!row ||
|
||||
row.source_sha256 !== input.sourceSha256 ||
|
||||
row.source_size_bytes !== String(input.sourceSizeBytes) ||
|
||||
row.request_fingerprint !== input.requestFingerprint
|
||||
) {
|
||||
throw new Error('Document upload attempt cannot be reused');
|
||||
}
|
||||
return { state: row.state, replay: inserted.length === 0 };
|
||||
});
|
||||
}
|
||||
|
||||
/** Exactly one claimant may start dispatch. Persist this before any network write. */
|
||||
async startDispatch(input: UploadAttemptIdentity): Promise<boolean> {
|
||||
return this.scoped(input, async (tx) => {
|
||||
const rows = await tx<{ attempt_id: string }[]>`
|
||||
UPDATE opt_document_upload_attempts SET state='dispatch_started', updated_at=clock_timestamp()
|
||||
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
||||
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
||||
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}
|
||||
AND state='prepared' RETURNING attempt_id`;
|
||||
return rows.length === 1;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the verified DOC0 receipt so a retry with the same idempotency key
|
||||
* returns the SAME 201 receipt instead of "outcome unknown". Only the fields
|
||||
* DOC0 itself returned are stored; storage/extraction are not re-proven here.
|
||||
*/
|
||||
async recordReceipt(input: UploadAttemptIdentity, receipt: StoredUploadReceipt): Promise<void> {
|
||||
if (
|
||||
![receipt.documentId, receipt.versionId, receipt.pipelineStage].every(
|
||||
(value) => typeof value === 'string' && value.trim().length > 0 && value.length <= 256,
|
||||
) ||
|
||||
!/^[0-9a-f]{64}$/.test(receipt.checksumSha256)
|
||||
) {
|
||||
throw new Error('Invalid upload receipt');
|
||||
}
|
||||
await this.scoped(input, async (tx) => {
|
||||
const rows = await tx<{ attempt_id: string }[]>`
|
||||
UPDATE opt_document_upload_attempts
|
||||
SET document_id=${receipt.documentId}, version_id=${receipt.versionId},
|
||||
receipt_checksum=${receipt.checksumSha256}, pipeline_stage=${receipt.pipelineStage},
|
||||
verified_at=clock_timestamp(), updated_at=clock_timestamp()
|
||||
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
||||
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
||||
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}
|
||||
RETURNING attempt_id`;
|
||||
if (rows.length !== 1) throw new Error('Upload attempt receipt could not be recorded');
|
||||
});
|
||||
}
|
||||
|
||||
async getReceipt(input: UploadAttemptIdentity): Promise<StoredUploadReceipt | undefined> {
|
||||
return this.scoped(input, async (tx) => {
|
||||
const rows = await tx<
|
||||
{
|
||||
document_id: string | null;
|
||||
version_id: string | null;
|
||||
receipt_checksum: string | null;
|
||||
pipeline_stage: string | null;
|
||||
}[]
|
||||
>`
|
||||
SELECT document_id, version_id, receipt_checksum, pipeline_stage
|
||||
FROM opt_document_upload_attempts
|
||||
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
||||
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
||||
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}`;
|
||||
const row = rows[0];
|
||||
if (!row?.document_id || !row.version_id || !row.receipt_checksum || !row.pipeline_stage)
|
||||
return undefined;
|
||||
return {
|
||||
documentId: row.document_id,
|
||||
versionId: row.version_id,
|
||||
checksumSha256: row.receipt_checksum,
|
||||
pipelineStage: row.pipeline_stage,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
import {
|
||||
Doc0UploadOutcomeUnknownError,
|
||||
prepareDoc0UploadIdentity,
|
||||
type Doc0Inspection,
|
||||
type Doc0InspectionInput,
|
||||
type Doc0UploadInput,
|
||||
type Doc0UploadReceipt,
|
||||
} from './doc0-upload-client';
|
||||
import type { StoredUploadReceipt, UploadAttemptIdentity, UploadAttemptState } from './upload-attempt-store';
|
||||
|
||||
type Scope = Pick<Doc0UploadInput, 'tenantId' | 'projectId' | 'actorId'>;
|
||||
type Attempts = {
|
||||
prepare(input: UploadAttemptIdentity): Promise<{ state: UploadAttemptState; replay: boolean }>;
|
||||
startDispatch(input: UploadAttemptIdentity): Promise<boolean>;
|
||||
/** Optional so lightweight tests/implementations keep working. */
|
||||
recordReceipt?(input: UploadAttemptIdentity, receipt: StoredUploadReceipt): Promise<void>;
|
||||
getReceipt?(input: UploadAttemptIdentity): Promise<StoredUploadReceipt | undefined>;
|
||||
};
|
||||
type Doc0 = {
|
||||
upload(input: Doc0UploadInput): Promise<Doc0UploadReceipt>;
|
||||
inspect(input: Doc0InspectionInput): Promise<Doc0Inspection>;
|
||||
};
|
||||
export type CoordinatedUpload =
|
||||
| { status: 'receipt_verified'; receipt: Doc0UploadReceipt }
|
||||
| { status: 'outcome_unknown'; observation?: Doc0Inspection };
|
||||
|
||||
/**
|
||||
* Internal only: no customer routes are wired. Scope must be derived from an
|
||||
* authenticated principal and independently authorized by the injected policy.
|
||||
* The DOC0 journal, RLS database role, storage and project authorization must
|
||||
* be deployed and verified before this coordinator can serve customer data.
|
||||
*/
|
||||
export class DocumentUploadCoordinator {
|
||||
constructor(
|
||||
private readonly deps: {
|
||||
attempts: Attempts;
|
||||
doc0: Doc0;
|
||||
authorize: (scope: Scope) => Promise<boolean>;
|
||||
maxBytes: number;
|
||||
},
|
||||
) {
|
||||
if (!Number.isSafeInteger(deps.maxBytes) || deps.maxBytes <= 0) throw new Error('Invalid upload limit');
|
||||
}
|
||||
|
||||
async execute(input: Doc0UploadInput): Promise<CoordinatedUpload> {
|
||||
if (!(input.bytes instanceof Uint8Array) || input.bytes.byteLength > this.deps.maxBytes) {
|
||||
throw new Error('Invalid upload input');
|
||||
}
|
||||
// Snapshot both metadata and bytes before the first await: a caller cannot
|
||||
// mutate the request between the durable fingerprint and the actual POST.
|
||||
const snapshot: Doc0UploadInput = { ...input, bytes: new Uint8Array(input.bytes) };
|
||||
const details = prepareDoc0UploadIdentity(snapshot);
|
||||
const scope = { tenantId: snapshot.tenantId, projectId: snapshot.projectId, actorId: snapshot.actorId };
|
||||
if ((await this.deps.authorize(scope)) !== true) throw new Error('Document upload not authorized');
|
||||
const attempt: UploadAttemptIdentity = {
|
||||
...scope,
|
||||
attemptId: snapshot.idempotencyKey,
|
||||
sourceSha256: details.sourceSha256,
|
||||
sourceSizeBytes: details.sourceSizeBytes,
|
||||
requestFingerprint: details.requestFingerprint,
|
||||
};
|
||||
await this.deps.attempts.prepare(attempt);
|
||||
// A database error here also stops the operation: the update might have
|
||||
// committed and must never be followed by an unrecorded network write.
|
||||
if ((await this.deps.attempts.startDispatch(attempt)) === true) {
|
||||
try {
|
||||
const receipt = await this.deps.doc0.upload(snapshot);
|
||||
// Persist the verified receipt so retrying with the same idempotency
|
||||
// key returns this exact 201 instead of "outcome unknown". A journal
|
||||
// write failure must not turn a real upload into an error response.
|
||||
try {
|
||||
await this.deps.attempts.recordReceipt?.(attempt, receipt);
|
||||
} catch {
|
||||
/* receipt stays unpersisted; a retry falls back to observation */
|
||||
}
|
||||
return { status: 'receipt_verified', receipt };
|
||||
} catch (error) {
|
||||
// The client marks every potentially committed POST as unknown. Any
|
||||
// other error propagates, while the one-way dispatch remains recorded.
|
||||
if (!(error instanceof Doc0UploadOutcomeUnknownError)) throw error;
|
||||
}
|
||||
}
|
||||
// A retry of an already-dispatched attempt: if the first dispatch returned
|
||||
// a verified receipt, return it again (same document, same checksum).
|
||||
try {
|
||||
const stored = await this.deps.attempts.getReceipt?.(attempt);
|
||||
if (stored) return { status: 'receipt_verified', receipt: stored };
|
||||
} catch {
|
||||
/* fall through to observation */
|
||||
}
|
||||
// Observation only. Even not_found does not prove that a write cannot
|
||||
// still arrive; completed_recorded does not prove storage or extraction.
|
||||
try {
|
||||
const observation = await this.deps.doc0.inspect({
|
||||
...scope,
|
||||
requestId: snapshot.requestId,
|
||||
idempotencyKey: snapshot.idempotencyKey,
|
||||
sourceSha256: details.sourceSha256,
|
||||
sourceSizeBytes: details.sourceSizeBytes,
|
||||
requestFingerprint: details.requestFingerprint,
|
||||
});
|
||||
return { status: 'outcome_unknown', observation };
|
||||
} catch {
|
||||
return { status: 'outcome_unknown' };
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user