* feat(ai): job-shaped AI service with OpenAI-compatible backend, extraction-first; stop extracting every inbox document twice Sovereign plan WS1 PR1 (#1406 Tier 2, extraction-first, aligned with the AI surface audit). lib/ai grows a job-shaped service (generateText / generateStructured / extractFromDocument; no streaming members yet, see plan rule R3): - services/anthropic-family delegates to the existing createAiClient() and sends the exact request literals the inbox extractor sent before (request-shape tests deep-equal them), so hosted Bedrock stays byte-identical. - services/openai-compatible talks to any chat-completions endpoint (BYO Swedish provider) via Vercel AI SDK 6.x, exact-pinned and guarded: images as parts, PDFs rasterized with poppler (AI_PDF_MODE) or sent natively, AI_VISION / AI_STRICT_JSON declared, honest skips (ai_no_vision, pdf_rasterizer_missing) instead of fake failures. - config.ts: AI_PROVIDER/AI_BASE_URL/AI_API_KEY/AI_MODEL and per-tier AI_*_MODEL with the legacy BEDROCK_* names kept as the same overrides; getAiStatus() is the single source of truth for "is AI wired up". - provider.ts: openai-compatible in the auto-detect chain (after Bedrock and the direct API); createAiClient() refuses it loudly. Document extraction moves onto the service and gets the audit's fixes: - Inbox documents were extracted TWICE (pipeline A ran inside uploadDocument() before the inbox row existed, so its dedupe branch never fired; 3 707 + 1 666 calls / 30 d). The inbox now declares extractionOwner on the upload, the extension yields, and the inbox mirrors its single outcome onto document_attachments from every writer (sync, deferred, attach, retry, MCP). - Every "no extraction will ever happen" outcome is stamped (skipped:no_ai_entitlement / ai_unconfigured / system_generated / ...); the status route maps the quiet ones to 'disabled' on the first poll instead of a 30 s client timeout. Prod showed 309 of the 327 never-extracted uploads were the paywall working silently. - Self-generated documents (our own invoice PDFs, payout files) are no longer OCR'd. - Agent invoke answers 503 ai_unconfigured when the deployment has no assistant backend, distinct from the paywall. Guard: new direct-ai-client antipattern check (shrink-only allowlist of the pre-abstraction SDK callers) plus exact pins for @anthropic-ai/sdk, ai and @ai-sdk/openai-compatible. Verified: 15 958 unit tests green, guards, lint ratchet, typecheck, and a live smoke against hosted Bedrock through the new service (ping, streamed tool turn, thinking+cache, PDF extraction). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ai): make AI_API_KEY optional for OpenAI-compatible endpoints (keyless local model servers) A local model server (llama.cpp's server, Ollama /v1, LM Studio, vLLM) usually has no auth. Before, the OpenAI-compatible backend required both AI_BASE_URL and AI_API_KEY to count as configured, so running Accounted on a local model meant setting a meaningless placeholder key. - resolveAiProvider / hasAiCredentials: a base URL alone is now enough. - services/openai-compatible: only send Authorization: Bearer when AI_API_KEY is set, so a keyless server is never handed an empty bearer; a hosted provider that needs a key still sets it. - Docs (SELF-HOSTING Option 3: local-model example, key marked optional), DECISIONS. Verified: with no AI_API_KEY, just AI_BASE_URL + AI_MODEL, getAiStatus() reports configured=true / provider=openai-compatible (live). lib/ai suite 71 green; tsc, guards, lint clean. Bedrock/Anthropic logic unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
182 lines
6.3 KiB
TypeScript
182 lines
6.3 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { makeDocumentAttachment } from '@/tests/helpers'
|
|
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
|
import { MCP_TOOL_CAPABILITY_MAP } from '@/lib/entitlements/keys'
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
createPendingDocumentUpload: vi.fn(),
|
|
completePendingDocumentUpload: vi.fn(),
|
|
extractInvoiceFields: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('@/lib/core/documents/document-service', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('@/lib/core/documents/document-service')>()
|
|
return {
|
|
...actual,
|
|
createPendingDocumentUpload: mocks.createPendingDocumentUpload,
|
|
completePendingDocumentUpload: mocks.completePendingDocumentUpload,
|
|
}
|
|
})
|
|
|
|
vi.mock('@/extensions/general/invoice-inbox/lib/extract-invoice-fields', async (importOriginal) => {
|
|
const actual = await importOriginal<
|
|
typeof import('@/extensions/general/invoice-inbox/lib/extract-invoice-fields')
|
|
>()
|
|
return { ...actual, extractInvoiceFields: mocks.extractInvoiceFields }
|
|
})
|
|
|
|
import { tools } from '../server'
|
|
|
|
const companyId = '11111111-1111-4111-8111-111111111111'
|
|
const userId = '22222222-2222-4222-8222-222222222222'
|
|
const uploadId = '33333333-3333-4333-8333-333333333333'
|
|
|
|
function findTool(name: string) {
|
|
const tool = tools.find((candidate) => candidate.name === name)
|
|
if (!tool) throw new Error(`Tool not found: ${name}`)
|
|
return tool
|
|
}
|
|
|
|
function makeQueryBuilder(result: { data: unknown; error: unknown }) {
|
|
const builder: Record<string, unknown> = {}
|
|
// ilike/not/order/range serve the shared supplier matcher
|
|
// (lib/suppliers/match-supplier.ts): name lookup and the vat_number scan.
|
|
for (const method of ['select', 'eq', 'limit', 'insert', 'ilike', 'not', 'order']) {
|
|
builder[method] = vi.fn().mockReturnValue(builder)
|
|
}
|
|
builder.maybeSingle = vi.fn().mockResolvedValue(result)
|
|
builder.single = vi.fn().mockResolvedValue(result)
|
|
builder.range = vi.fn().mockResolvedValue({ data: [], error: null })
|
|
return builder
|
|
}
|
|
|
|
describe('MCP model-free document upload tools', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mocks.createPendingDocumentUpload.mockResolvedValue({
|
|
uploadId,
|
|
signedUrl: 'https://storage.example/upload?token=signed',
|
|
expiresAt: '2026-08-03T12:00:00.000Z',
|
|
})
|
|
mocks.completePendingDocumentUpload.mockResolvedValue({
|
|
document: makeDocumentAttachment({
|
|
id: uploadId,
|
|
user_id: userId,
|
|
company_id: companyId,
|
|
file_name: 'invoice.pdf',
|
|
mime_type: 'application/pdf',
|
|
}),
|
|
buffer: new TextEncoder().encode('%PDF-1.4\n%%EOF\n').buffer,
|
|
})
|
|
mocks.extractInvoiceFields.mockResolvedValue({
|
|
data: {
|
|
supplier: { name: 'Synthetic Supplier AB', orgNumber: null },
|
|
invoice: { number: 'INV-1' },
|
|
},
|
|
})
|
|
})
|
|
|
|
it('returns an unauthenticated PUT URL without accepting file bytes', async () => {
|
|
const tool = findTool('gnubok_create_document_upload')
|
|
const result = await tool.execute(
|
|
{ file_name: 'invoice.pdf' },
|
|
companyId,
|
|
userId,
|
|
{} as never,
|
|
)
|
|
|
|
expect(mocks.createPendingDocumentUpload).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
companyId,
|
|
userId,
|
|
expect.stringMatching(/^[0-9a-f-]{36}$/),
|
|
'invoice.pdf',
|
|
)
|
|
expect(result).toEqual({
|
|
upload_id: uploadId,
|
|
upload_url: 'https://storage.example/upload?token=signed',
|
|
expires_at: '2026-08-03T12:00:00.000Z',
|
|
})
|
|
const schema = tool.inputSchema as { properties: Record<string, unknown> }
|
|
expect(schema.properties).not.toHaveProperty('file_content_base64')
|
|
})
|
|
|
|
it('completes the reserved upload and uses the upload UUID for both records', async () => {
|
|
const inboxInsert = makeQueryBuilder({ data: { id: uploadId, status: 'received' }, error: null })
|
|
const invoiceLookups = [
|
|
makeQueryBuilder({ data: null, error: null }),
|
|
makeQueryBuilder({ data: null, error: null }),
|
|
inboxInsert,
|
|
]
|
|
const supplier = makeQueryBuilder({ data: null, error: null })
|
|
const from = vi.fn((table: string) => {
|
|
if (table === 'invoice_inbox_items') return invoiceLookups.shift()
|
|
if (table === 'suppliers') return supplier
|
|
throw new Error(`Unexpected table: ${table}`)
|
|
})
|
|
|
|
const result = await findTool('gnubok_complete_document_upload').execute(
|
|
{ upload_id: uploadId, file_name: 'invoice.pdf', mime_type: 'application/pdf' },
|
|
companyId,
|
|
userId,
|
|
{ from } as never,
|
|
)
|
|
|
|
expect(mocks.completePendingDocumentUpload).toHaveBeenCalledWith(
|
|
expect.anything(),
|
|
companyId,
|
|
userId,
|
|
uploadId,
|
|
'invoice.pdf',
|
|
'application/pdf',
|
|
undefined,
|
|
// The inbox item created right after owns extraction; the
|
|
// document-extraction extension must yield on the uploaded event.
|
|
{ extractionOwner: 'invoice-inbox' },
|
|
)
|
|
expect(inboxInsert.insert).toHaveBeenCalledWith(
|
|
expect.objectContaining({ id: uploadId, document_id: uploadId }),
|
|
)
|
|
expect(result).toMatchObject({
|
|
document_id: uploadId,
|
|
inbox_item_id: uploadId,
|
|
status: 'received',
|
|
})
|
|
expect(mocks.extractInvoiceFields).toHaveBeenCalledOnce()
|
|
})
|
|
|
|
it('returns an already completed inbox item without downloading or extracting again', async () => {
|
|
const existing = makeQueryBuilder({
|
|
data: {
|
|
id: uploadId,
|
|
document_id: uploadId,
|
|
status: 'received',
|
|
extracted_data: { invoice: { number: 'INV-1' } },
|
|
matched_supplier_id: null,
|
|
},
|
|
error: null,
|
|
})
|
|
const result = await findTool('gnubok_complete_document_upload').execute(
|
|
{ upload_id: uploadId, file_name: 'invoice.pdf', mime_type: 'application/pdf' },
|
|
companyId,
|
|
userId,
|
|
{ from: vi.fn().mockReturnValue(existing) } as never,
|
|
)
|
|
|
|
expect(result).toMatchObject({ document_id: uploadId, inbox_item_id: uploadId })
|
|
expect(mocks.completePendingDocumentUpload).not.toHaveBeenCalled()
|
|
expect(mocks.extractInvoiceFields).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('keeps scope and AI capability gates aligned across all upload paths', () => {
|
|
for (const name of [
|
|
'gnubok_create_document_upload',
|
|
'gnubok_complete_document_upload',
|
|
'gnubok_upload_document',
|
|
]) {
|
|
expect(TOOL_SCOPE_MAP[name]).toBe('transactions:write')
|
|
expect(MCP_TOOL_CAPABILITY_MAP[name]).toBe('ai')
|
|
}
|
|
})
|
|
})
|