# Infrastructure layer: configuration, PostgreSQL access (psql inside the container) and the # embedding provider (Ollama). Nothing here is exported; agents use the Public commands. function Get-FkeConfig { # Read at call time so environment overrides (and the test suite's scratch database) take effect. $ollama = if ($env:FOUNDRY_OLLAMA_URL) { $env:FOUNDRY_OLLAMA_URL } else { 'http://localhost:11434' } [pscustomobject]@{ Container = if ($env:FOUNDRY_PG_CONTAINER) { $env:FOUNDRY_PG_CONTAINER } else { 'foundry-postgres' } User = if ($env:FOUNDRY_PG_USER) { $env:FOUNDRY_PG_USER } else { 'foundry' } Database = if ($env:FOUNDRY_PG_DATABASE) { $env:FOUNDRY_PG_DATABASE } else { 'foundry' } OllamaUrl = $ollama.TrimEnd('/') EmbeddingModel = if ($env:FOUNDRY_EMBEDDING_MODEL) { $env:FOUNDRY_EMBEDDING_MODEL } else { 'nomic-embed-text' } EmbeddingDimension = 768 # must match VECTOR(768) in migrations/001-initial-schema.sql } } function Invoke-FkeSql { <# Runs SQL through psql inside the container, on stdin. Caller-supplied values never get concatenated into SQL: they travel as one JSON payload inside a randomly tagged dollar-quoted literal, read back in SQL with current_setting('fke.p')::jsonb. Returns the parsed JSON of the single output value (queries should SELECT one jsonb value), or the raw text with -Text. #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Sql, $Payload, [string]$Database, [switch]$Text ) $cfg = Get-FkeConfig if (-not $Database) { $Database = $cfg.Database } $header = '' if ($null -ne $Payload) { $json = $Payload | ConvertTo-Json -Depth 20 -Compress do { $tag = 'fke' + [Guid]::NewGuid().ToString('N') } while ($json.Contains($tag)) $q = '$' + $tag + '$' $header = "SELECT set_config('fke.p', ${q}${json}${q}, false) AS ok \gset`n" } $script = $header + $Sql + "`n" $savedConsole = [Console]::OutputEncoding $savedOut = $OutputEncoding [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) $OutputEncoding = [Text.UTF8Encoding]::new($false) try { $out = $script | & docker exec -i $cfg.Container psql -U $cfg.User -d $Database -X -q -t -A -v ON_ERROR_STOP=1 2>&1 $code = $LASTEXITCODE } finally { [Console]::OutputEncoding = $savedConsole $OutputEncoding = $savedOut } $lines = @($out | ForEach-Object { "$_" }) if ($code -ne 0) { throw "Knowledge database error (exit $code): $($lines -join ' ')" } $joined = ($lines -join "`n").Trim() if ($Text) { return $joined } if (-not $joined) { return $null } $joined | ConvertFrom-Json -Depth 50 } function Get-FkeEmbedding { # Returns [double[]] with the configured dimension, or throws. Callers decide how to degrade. param([Parameter(Mandatory)][string]$Text) $cfg = Get-FkeConfig $body = @{ model = $cfg.EmbeddingModel; input = $Text } | ConvertTo-Json -Compress $r = Invoke-RestMethod -Uri "$($cfg.OllamaUrl)/api/embed" -Method Post -ContentType 'application/json; charset=utf-8' ` -Body ([Text.Encoding]::UTF8.GetBytes($body)) -TimeoutSec 60 if (-not $r.embeddings -or -not $r.embeddings[0]) { throw "Ollama returned no embedding for model '$($cfg.EmbeddingModel)'." } $vec = [double[]]@($r.embeddings[0]) if ($vec.Count -ne $cfg.EmbeddingDimension) { throw "Embedding model '$($cfg.EmbeddingModel)' returned $($vec.Count) dimensions; the schema stores $($cfg.EmbeddingDimension)." } , $vec } function Get-FkeTokenEstimate { # Rough heuristic (about 4 characters per token); not a tokenizer. Used only for budgeting. param([Parameter(Mandatory)][string]$Text) [int][math]::Ceiling($Text.Length / 4.0) }