Files
accounted/extensions/general/document-extraction/index.ts
T
Mattsson 3829b6add3 fix(ai): complete plain-key self-hosting path (#1584)
* feat(ai): resolve the Claude backend from the environment

Tier 1 of #1406: a self-hosted deployment can now run every AI feature on a
plain ANTHROPIC_API_KEY, with no AWS account. Hosted behaviour is unchanged.

lib/ai/provider.ts resolves the backend once, from the environment:

  AI_PROVIDER              explicit override, bedrock|anthropic
  AWS static key pair      Bedrock
  ANTHROPIC_API_KEY        the direct Anthropic API
  nothing set              Bedrock, so the AWS credential provider chain
                           (instance profile, IRSA) still resolves

Bedrock deliberately wins when both credential sets are present. EU residency
in eu-north-1 is a BFL/GDPR posture rather than a default, so adding an
Anthropic key for an experiment must not silently move production inference
out of the region. AI_PROVIDER is the way to say you meant it.

Model ids are written bare in code and prefixed to eu.anthropic.* only for
Bedrock, which needs the cross-region inference profile for on-demand
throughput. An operator override that already carries a prefix passes through
untouched, so BEDROCK_MODEL_ID and friends keep working as written.

Converted call sites: the agent composer, invoice-inbox extraction, the
document-extraction model label, and both receipt-hunt clients. The last two
are not named in the issue, which predates receipt-hunt landing in main.

@anthropic-ai/sdk is declared at 0.95.0, the version @anthropic-ai/bedrock-sdk
0.29.1 already pulled in transitively, so the lockfile dedupes to one copy
with no new download.

scripts/smoke-bedrock.ts becomes scripts/smoke-ai.ts and grows two steps.
Unit tests can only prove which provider and model id get resolved; they
cannot prove the resulting request is one the backend accepts. The script now
sends real traffic over all three shapes the app uses: a plain create, a
streamed turn carrying adaptive thinking, an effort level, an hour-long cache
breakpoint and a tool, and document extraction end to end when given a file.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* docs(self-hosting): document the AI smoke test

The script added alongside the provider split is what closes the #1406
acceptance criterion ("document extraction and the assistant both work"), so
a self-hoster needs to know it exists. Covers both invocations and states
that it exits non-zero, which is what makes it usable as a post-deploy check.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* test(ai): split the smoke test's thinking probe from its tool probe

The combined probe could not falsify what it claimed to. It asked a question
that needs a tool call, so the tool was used and adaptive thinking correctly
declined to reason about it: the zero thinking-block count that came back was
uninformative rather than a signal.

2a keeps the tool and drops thinking. 2b asks a question with several
dependent steps (reverse charge, then a partial deduction, then the affected
boxes) so that a model honouring the parameter must reason, and reports the
thinking text length as well as the block count, since display:"summarized"
can yield blocks with empty text.

The cached system prompt is also padded past the 1024-token minimum cacheable
prefix. Below that the API caches nothing and reports no error, so the old
probe's cache counters read zero whether or not caching worked.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* fix(document-extraction): stop requiring AWS_REGION in the manifest

The extension now needs one of two credential sets, AWS static keys or
ANTHROPIC_API_KEY, and the manifest schema cannot express "one of". Since
requiredEnvVars only drives a build-time warning and never gates anything,
listing AWS_REGION told every self-hoster running the direct API to set a
variable that has no effect for them.

The description was also still promising Sonnet 4.6 via Bedrock specifically,
which is no longer what the extension does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* fix(ai): read documentKind defensively in the smoke test

The field arrived with the receipt-aware extraction work, so referencing it
directly stops the script compiling against any checkout from before that
landed. tsconfig includes **/*.ts and next.config does not disable type
checking, so on such a checkout this failed the production build rather than
just the script: caught while preparing a test branch for a self-hosted
instance that had not synced yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* fix(deps): restore the nested @swc/helpers entry in the lockfile

Declaring @anthropic-ai/sdk with `npm install --package-lock-only` also pruned
node_modules/next-intl/node_modules/@swc/helpers@0.5.23, an optional peer entry
the local npm 11 considers redundant and the image's npm 10.9.8 does not. The
result passed every local check and failed `npm ci` inside the Docker build,
which is the only place the lockfile is actually enforced.

The lockfile is now the previous one plus the single root dependency line,
verified with `npm ci --dry-run`. @anthropic-ai/sdk needed nothing else: it was
already in the tree as a transitive dependency of @anthropic-ai/bedrock-sdk.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>

* Update DECISIONS.md

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update Docker documentation for AI provider credentials

Clarify the role of credentials in AI provider selection and document extraction requirements.

* Update SELF-HOSTING.md with smoke-ai script details

Clarify usage of smoke-ai script for credential checks and document extraction.

* Improve error handling and logging in smoke-ai script

* fix(ai): complete plain-key self-hosting path

Signed-off-by: Emil <emilmattsson14@gmail.com>

---------

Signed-off-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>
Signed-off-by: Emil <emilmattsson14@gmail.com>
Co-authored-by: Bjorn Bergenheim <29535152+bjornbergenheim@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-08-13 15:45:24 +02:00

205 lines
7.2 KiB
TypeScript

import type { Extension } from '@/lib/extensions/types'
import type { SupabaseClient } from '@supabase/supabase-js'
import { extractInvoiceFields } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
import { toProviderModelId } from '@/lib/ai/provider'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { createLogger } from '@/lib/logger'
import { createServiceClient } from '@/lib/supabase/server'
import type { DocumentAttachment } from '@/types'
const log = createLogger('document-extraction')
// Mime types we know Claude can read directly via Bedrock. Anything else
// (HEIC, ZIP, TXT, …) is skipped: extracted_at still gets stamped so the
// row is marked as "attempted, not eligible".
const SUPPORTED_MIME_TYPES = new Set([
'application/pdf',
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
])
// AI-extraction extension: paid AI tier only.
//
// Subscribes to the existing document.uploaded event bus topic and runs
// Sonnet 4.6 (via Bedrock, reusing invoice-inbox's extractInvoiceFields) on
// every uploaded receipt or invoice. Writes the result to
// document_attachments.extracted_data so the agent intent capture can use
// it without re-asking the user.
//
// Idempotency: skips when extracted_at is already set on the row. Also
// dedupes against invoice_inbox_items.extracted_data: when the inbox
// extension already extracted the same file, we copy its result instead
// of paying for a second Sonnet call.
//
// Free tier: disable this extension in extensions.config.json. Uploads
// still work; the agent intent will see null extracted_data and either
// ask the user or call gnubok_get_document_content at chat-time.
//
// See dev_docs/specialized-agent-plan.md (§ paid/free tier note): to be
// authored.
export const documentExtractionExtension: Extension = {
id: 'document-extraction',
name: 'AI document extraction',
version: '1.0.0',
eventHandlers: [
{
eventType: 'document.uploaded',
handler: async (payload) => {
const { document, companyId } = payload as {
document: DocumentAttachment
userId: string
companyId: string
}
await extractAndPersist(document, companyId)
},
},
],
}
async function extractAndPersist(
document: DocumentAttachment,
companyId: string,
): Promise<void> {
// Service-role client: the handler runs out-of-band of the request that
// emitted the event, so we don't have user cookies. RLS doesn't fit:
// events have no user context.
const supabase: SupabaseClient = createServiceClient()
// Idempotency guard: never re-extract a row that already has extracted_at.
// Note: the column may be null OR the row may not yet have the new
// schema (legacy supabase types). Fail closed on missing schema.
const { data: existing, error: existingErr } = await supabase
.from('document_attachments')
.select('id, mime_type, storage_path, extracted_at')
.eq('id', document.id)
.single()
if (existingErr || !existing) {
log.warn('document not found, skipping extraction', {
doc: document.id,
err: existingErr?.message,
})
return
}
if (existing.extracted_at) {
return
}
// Dedup against inbox: if invoice-inbox already extracted this exact file
// (same document_id), copy its result to avoid a second AI call. If the
// inbox row marked the upload as skip_extraction=true, the inbox row's
// extracted_data is an empty skeleton: we must stamp the doc with a
// 'skipped:*' model so the client-side useDocumentExtraction hook reports
// 'unsupported' rather than 'succeeded' (otherwise the UI would claim AI
// finished reading a doc it never opened).
const { data: inboxRow } = await supabase
.from('invoice_inbox_items')
.select('extracted_data, extraction_skipped')
.eq('document_id', document.id)
.maybeSingle()
if (inboxRow?.extraction_skipped) {
await supabase
.from('document_attachments')
.update({
extracted_at: new Date().toISOString(),
extraction_model: 'skipped:invoice_inbox_gate',
})
.eq('id', document.id)
return
}
let extractedData: Record<string, unknown> | null = null
let model: string = 'copied-from-invoice-inbox'
if (inboxRow?.extracted_data) {
extractedData = inboxRow.extracted_data as Record<string, unknown>
} else {
const mimeType = existing.mime_type as string | null
if (!mimeType || !SUPPORTED_MIME_TYPES.has(mimeType)) {
// Stamp the attempt so we don't keep retrying unsupported types.
await supabase
.from('document_attachments')
.update({ extracted_at: new Date().toISOString(), extraction_model: 'skipped:unsupported_mime' })
.eq('id', document.id)
return
}
// Download the file from Supabase Storage. The bucket is private: the
// service-role client can read any path.
const storagePath = existing.storage_path as string | null
if (!storagePath) {
log.warn('document has no storage_path, skipping', { doc: document.id })
return
}
const { data: blob, error: dlErr } = await supabase.storage
.from('documents')
.download(storagePath)
if (dlErr || !blob) {
log.warn('storage download failed', { doc: document.id, err: dlErr?.message })
return
}
const buffer = Buffer.from(await blob.arrayBuffer())
if (!(await hasCapability(supabase, companyId, CAPABILITY.ai))) {
log.info('extraction skipped, ai capability not entitled', { doc: document.id, companyId })
return
}
try {
const { data, rawText } = await extractInvoiceFields({
buffer,
mimeType,
fileName: (document.file_name as string) || 'document',
})
// extractInvoiceFields returns an "empty" result on failure rather
// than throwing: distinguish by checking rawText. When rawText is
// null, the call was skipped (creds missing, unsupported type) or
// the JSON parse failed.
if (!rawText) {
await supabase
.from('document_attachments')
.update({
extracted_at: new Date().toISOString(),
extraction_model: 'failed:no_raw_text',
})
.eq('id', document.id)
return
}
extractedData = data as unknown as Record<string, unknown>
model = toProviderModelId(process.env.BEDROCK_MODEL_ID || 'claude-sonnet-5')
} catch (err) {
log.warn('extraction threw', {
doc: document.id,
err: err instanceof Error ? err.message : String(err),
})
await supabase
.from('document_attachments')
.update({
extracted_at: new Date().toISOString(),
extraction_model: 'failed:exception',
})
.eq('id', document.id)
return
}
}
const { error: updateErr } = await supabase
.from('document_attachments')
.update({
extracted_data: extractedData,
extracted_at: new Date().toISOString(),
extraction_model: model,
})
.eq('id', document.id)
if (updateErr) {
log.warn('persist failed', { doc: document.id, err: updateErr.message, companyId })
return
}
log.info('extraction persisted', { doc: document.id, model, companyId })
}