Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1143a8aba3 | ||
|
|
baf33b6844 | ||
|
|
776749277c | ||
|
|
41b1b89fcb | ||
|
|
4d4e994562 |
@@ -1,92 +0,0 @@
|
||||
name: Sync Portal Docs
|
||||
|
||||
# Regenerates the portal Developer Docs manifest from the Stirling docs repo and
|
||||
# opens a PR when it changes. Runs weekly, on manual dispatch, or when the docs
|
||||
# repo fires a `docs-updated` repository_dispatch.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 6 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
description: "Docs repo ref (branch or tag) to sync from"
|
||||
required: false
|
||||
default: "main"
|
||||
repository_dispatch:
|
||||
types: [docs-updated]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
name: Sync docs manifest
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@ab7a9404c0f3da075243ca237b5fac12c98deaa5 # v2.19.3
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup GitHub App Bot
|
||||
id: setup-bot
|
||||
uses: ./.github/actions/setup-bot
|
||||
with:
|
||||
app-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "npm"
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
env:
|
||||
NPM_CONFIG_IGNORE_SCRIPTS: "true"
|
||||
run: npm ci --ignore-scripts --audit=false --fund=false
|
||||
|
||||
- name: Regenerate docs manifest
|
||||
working-directory: frontend
|
||||
env:
|
||||
DOCS_REF: ${{ github.event.inputs.ref || github.event.client_payload.ref || 'main' }}
|
||||
GITHUB_TOKEN: ${{ steps.setup-bot.outputs.token }}
|
||||
run: npm run docs:sync
|
||||
|
||||
- name: Create Pull Request
|
||||
id: cpr
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
||||
with:
|
||||
token: ${{ steps.setup-bot.outputs.token }}
|
||||
commit-message: "Sync portal docs from docs repo"
|
||||
committer: ${{ steps.setup-bot.outputs.committer }}
|
||||
author: ${{ steps.setup-bot.outputs.committer }}
|
||||
signoff: true
|
||||
branch: sync-portal-docs
|
||||
base: main
|
||||
title: "Sync portal docs from docs repo"
|
||||
body: |
|
||||
Auto-generated by ${{ steps.setup-bot.outputs.app-slug }}[bot].
|
||||
|
||||
Regenerates `frontend/editor/src/portal/generated/docsManifest.json`
|
||||
from the Stirling docs repo via `npm run docs:sync`.
|
||||
labels: documentation,github-actions,frontend
|
||||
add-paths: frontend/editor/src/portal/generated/docsManifest.json
|
||||
delete-branch: true
|
||||
sign-commits: true
|
||||
@@ -308,6 +308,106 @@ public class ApplicationProperties {
|
||||
* explicitly requests it via {@code AiEngineClient.postWithTimeout}.
|
||||
*/
|
||||
private int longRunningTimeoutSeconds = 600;
|
||||
|
||||
/** Timeout (seconds) for the SSE stream held open by long-running orchestrator runs. */
|
||||
private int streamTimeoutSeconds = 1800;
|
||||
|
||||
/**
|
||||
* Whether the processor pushes admin/settings-derived AI config (models, keys, RAG, limits)
|
||||
* to the engine's {@code POST /api/v1/config} on startup and after a save. True lets a
|
||||
* self-hosted admin drive the engine from the UI. Environment-driven deployments pin this
|
||||
* false (SaaS does in application-saas.properties) so the engine stays entirely
|
||||
* env-controlled and the processor never overrides its config.
|
||||
*/
|
||||
private boolean pushConfigToEngine = true;
|
||||
|
||||
/** Model + provider selection, forwarded to the engine per-request. */
|
||||
private Models models = new Models();
|
||||
|
||||
/** Retrieval-augmented-generation (RAG) knobs, forwarded to the engine per-request. */
|
||||
private Rag rag = new Rag();
|
||||
|
||||
/** Request size / cost guardrails. */
|
||||
private Limits limits = new Limits();
|
||||
|
||||
/** Per-capability on/off switches so an admin can disable individual AI tools. */
|
||||
private Features features = new Features();
|
||||
|
||||
@Data
|
||||
public static class Models {
|
||||
/** Provider driving the model strings: 'anthropic', 'openai', 'ollama', or 'custom'. */
|
||||
private String provider = "anthropic";
|
||||
|
||||
/** High-quality tier model name (without provider prefix), e.g. 'claude-haiku-4-5'. */
|
||||
private String smartModel = "claude-haiku-4-5";
|
||||
|
||||
/** Cheap/fast tier model name (without provider prefix). */
|
||||
private String fastModel = "claude-haiku-4-5";
|
||||
|
||||
private int smartMaxTokens = 8192;
|
||||
private int fastMaxTokens = 2048;
|
||||
|
||||
/**
|
||||
* API key for the selected provider. Secret - masked in the admin API and overridable
|
||||
* by the engine's own provider env var (e.g. ANTHROPIC_API_KEY) in environment-driven
|
||||
* deployments. Empty means the engine falls back to its native env credentials.
|
||||
*/
|
||||
private String apiKey = "";
|
||||
|
||||
/**
|
||||
* OpenAI-compatible base URL for 'ollama' / 'custom' providers (e.g.
|
||||
* http://ollama:11434/v1). Ignored for anthropic/openai. SSRF-sensitive - admin only.
|
||||
*/
|
||||
private String baseUrl = "";
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Rag {
|
||||
/**
|
||||
* Embedding provider: 'voyageai', 'openai', 'ollama', or 'custom' (OpenAI-compatible).
|
||||
*/
|
||||
private String embeddingProvider = "voyageai";
|
||||
|
||||
/** Embedding model name (without provider prefix), e.g. 'voyage-4'. */
|
||||
private String embeddingModel = "voyage-4";
|
||||
|
||||
/**
|
||||
* Secret API key for the embedding provider; masked + env-overridable like
|
||||
* models.apiKey.
|
||||
*/
|
||||
private String embeddingApiKey = "";
|
||||
|
||||
/**
|
||||
* OpenAI-compatible base URL for 'ollama' / 'custom' embedding providers (e.g.
|
||||
* http://ollama:11434/v1). Ignored for voyageai/openai. SSRF-sensitive - admin only.
|
||||
*/
|
||||
private String embeddingBaseUrl = "";
|
||||
|
||||
/** How many chunks retrieval returns per search. */
|
||||
private int topK = 20;
|
||||
|
||||
/** Per-run cap on knowledge-search tool calls before the agent must answer. */
|
||||
private int maxSearches = 5;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Limits {
|
||||
private int maxPages = 200;
|
||||
private int maxCharacters = 200000;
|
||||
|
||||
/** Process-wide cap on concurrent model API calls (engine restart to apply). */
|
||||
private int modelMaxConcurrency = 32;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Features {
|
||||
private boolean chat = true;
|
||||
private boolean documentQuestions = true;
|
||||
private boolean createPdf = true;
|
||||
private boolean mathAuditor = true;
|
||||
private boolean pdfComment = true;
|
||||
private boolean classify = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+13
-1
@@ -336,7 +336,19 @@ public class ConfigController {
|
||||
configData.put("premiumEnabled", applicationProperties.getPremium().isEnabled());
|
||||
|
||||
// AI Engine settings
|
||||
configData.put("aiEngineEnabled", applicationProperties.getAiEngine().isEnabled());
|
||||
ApplicationProperties.AiEngine aiEngineConfig = applicationProperties.getAiEngine();
|
||||
configData.put("aiEngineEnabled", aiEngineConfig.isEnabled());
|
||||
// Per-capability flags let the UI hide individual AI tools an admin has turned off.
|
||||
ApplicationProperties.AiEngine.Features aiFeatures = aiEngineConfig.getFeatures();
|
||||
configData.put(
|
||||
"aiFeatures",
|
||||
Map.ofEntries(
|
||||
Map.entry("chat", aiFeatures.isChat()),
|
||||
Map.entry("documentQuestions", aiFeatures.isDocumentQuestions()),
|
||||
Map.entry("createPdf", aiFeatures.isCreatePdf()),
|
||||
Map.entry("mathAuditor", aiFeatures.isMathAuditor()),
|
||||
Map.entry("pdfComment", aiFeatures.isPdfComment()),
|
||||
Map.entry("classify", aiFeatures.isClassify())));
|
||||
|
||||
// Timestamp TSA settings — single source of truth for presets + admin URLs
|
||||
ApplicationProperties.Security.Timestamp tsConfig =
|
||||
|
||||
@@ -366,6 +366,35 @@ aiEngine:
|
||||
enabled: false # Set to 'true' to enable the AI engine integration
|
||||
url: http://localhost:5001 # URL of the Python AI engine
|
||||
timeoutSeconds: 120 # Timeout in seconds for AI engine requests
|
||||
longRunningTimeoutSeconds: 600 # Timeout (seconds) for heavy operations like RAG ingestion of large documents
|
||||
streamTimeoutSeconds: 1800 # SSE stream timeout (seconds) for long-running orchestrator runs
|
||||
pushConfigToEngine: true # Push admin/settings AI config (models, keys, RAG, limits) to the engine on startup + save. Set false to leave the engine fully env-controlled
|
||||
models:
|
||||
provider: anthropic # Model provider: 'anthropic', 'openai', 'ollama', or 'custom' (OpenAI-compatible)
|
||||
smartModel: claude-haiku-4-5 # High-quality tier model name (no provider prefix)
|
||||
fastModel: claude-haiku-4-5 # Cheap/fast tier model name (no provider prefix)
|
||||
smartMaxTokens: 8192 # Max output tokens for the smart tier
|
||||
fastMaxTokens: 2048 # Max output tokens for the fast tier
|
||||
apiKey: "" # API key for the selected provider (secret). Empty = engine uses its native env credentials (e.g. ANTHROPIC_API_KEY)
|
||||
baseUrl: "" # OpenAI-compatible base URL for 'ollama'/'custom' providers (e.g. http://ollama:11434/v1). Ignored for anthropic/openai
|
||||
rag:
|
||||
embeddingProvider: voyageai # Embedding provider: 'voyageai', 'openai', 'ollama', or 'custom' (OpenAI-compatible)
|
||||
embeddingModel: voyage-4 # Embedding model name (no provider prefix)
|
||||
embeddingApiKey: "" # Secret API key for the embedding provider. Empty = engine uses its native env credentials (e.g. VOYAGE_API_KEY)
|
||||
embeddingBaseUrl: "" # OpenAI-compatible base URL for 'ollama'/'custom' embedding providers (e.g. http://ollama:11434/v1). Ignored for voyageai/openai
|
||||
topK: 20 # Number of chunks retrieval returns per search
|
||||
maxSearches: 5 # Per-run cap on knowledge-search tool calls before the agent must answer
|
||||
limits:
|
||||
maxPages: 200 # Upper bound on PDF pages the engine will process per request
|
||||
maxCharacters: 200000 # Upper bound on characters of extracted text per request
|
||||
modelMaxConcurrency: 32 # Process-wide cap on concurrent model API calls (engine restart to apply)
|
||||
features: # Per-capability switches; turn an individual AI tool off without disabling the whole engine
|
||||
chat: true # Assistant chat
|
||||
documentQuestions: true # Ask-questions-about-a-PDF
|
||||
createPdf: true # Generate a PDF from a natural-language spec
|
||||
mathAuditor: true # Numerical/formula contradiction auditing
|
||||
pdfComment: true # AI-authored PDF comments/annotations
|
||||
classify: true # Automatic document classification/labelling
|
||||
|
||||
policies:
|
||||
# Folder automations can read from and write to the directories you allow here, so treat this as a
|
||||
@@ -385,6 +414,8 @@ policies:
|
||||
mcp:
|
||||
enabled: false # Master switch. 'false' (default) means no /mcp endpoint, no metadata, no beans wired.
|
||||
scopesEnabled: true # Enforce mcp.tools.read / mcp.tools.write scopes derived from operation category
|
||||
maxRequestBytes: 10485760 # Max size (bytes) of an incoming MCP tool request payload (default 10 MB)
|
||||
maxInlineResponseBytes: 10485760 # Max size (bytes) of an MCP tool response returned inline before it is rejected (default 10 MB)
|
||||
allowedOperations: [] # Tool allow-list (operation ids, e.g. ['compress-pdf']). Empty = all. When set, ONLY these are exposed over MCP.
|
||||
blockedOperations: [] # Tool deny-list (operation ids). Always removed from MCP even if otherwise allowed.
|
||||
auth:
|
||||
|
||||
+7
-5
@@ -7,7 +7,6 @@ import java.util.concurrent.Executor;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -28,6 +27,7 @@ import jakarta.validation.Valid;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.job.ResultFile;
|
||||
import stirling.software.common.service.JobOwnershipService;
|
||||
import stirling.software.common.service.TaskManager;
|
||||
@@ -63,12 +63,11 @@ public class AiEngineController {
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
/**
|
||||
* SSE emitter timeout. Long enough to accommodate multi-gigabyte PDF workflows (OCR on a
|
||||
* SSE emitter timeout in ms. Long enough to accommodate multi-gigabyte PDF workflows (OCR on a
|
||||
* 1000-page scan, splitting a huge PDF, etc.) without the emitter completing out from under the
|
||||
* executor. Configurable via {@code stirling.ai.streamTimeoutMs}.
|
||||
* executor. Derived from {@code aiEngine.streamTimeoutSeconds}.
|
||||
*/
|
||||
@Value("${stirling.ai.streamTimeoutMs:1800000}")
|
||||
private long streamTimeoutMs;
|
||||
private final long streamTimeoutMs;
|
||||
|
||||
public AiEngineController(
|
||||
AiEngineClient aiEngineClient,
|
||||
@@ -78,6 +77,7 @@ public class AiEngineController {
|
||||
TaskManager taskManager,
|
||||
JobOwnershipService jobOwnershipService,
|
||||
AiEngineEndpointResolver endpointResolver,
|
||||
ApplicationProperties applicationProperties,
|
||||
@Autowired(required = false) UserServiceInterface userService) {
|
||||
this.aiEngineClient = aiEngineClient;
|
||||
this.aiWorkflowService = aiWorkflowService;
|
||||
@@ -87,6 +87,8 @@ public class AiEngineController {
|
||||
this.jobOwnershipService = jobOwnershipService;
|
||||
this.endpointResolver = endpointResolver;
|
||||
this.userService = userService;
|
||||
this.streamTimeoutMs =
|
||||
applicationProperties.getAiEngine().getStreamTimeoutSeconds() * 1000L;
|
||||
}
|
||||
|
||||
private String currentUserId() {
|
||||
|
||||
+5
@@ -36,6 +36,7 @@ import stirling.software.proprietary.classification.store.ClassificationLabelSto
|
||||
import stirling.software.proprietary.model.api.ai.AiPageText;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.AiFeatureGate;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
@@ -68,6 +69,7 @@ public class ClassifyLabelController {
|
||||
private final PdfContentExtractor pdfContentExtractor;
|
||||
private final PdfMetadataService pdfMetadataService;
|
||||
private final AiEngineClient aiEngineClient;
|
||||
private final AiFeatureGate aiFeatureGate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final UserServiceInterface userService;
|
||||
|
||||
@@ -86,6 +88,7 @@ public class ClassifyLabelController {
|
||||
PdfContentExtractor pdfContentExtractor,
|
||||
PdfMetadataService pdfMetadataService,
|
||||
AiEngineClient aiEngineClient,
|
||||
AiFeatureGate aiFeatureGate,
|
||||
ObjectMapper objectMapper,
|
||||
@Autowired(required = false) UserServiceInterface userService,
|
||||
@Autowired(required = false) ClassificationLabelStore labelStore,
|
||||
@@ -95,6 +98,7 @@ public class ClassifyLabelController {
|
||||
this.pdfContentExtractor = pdfContentExtractor;
|
||||
this.pdfMetadataService = pdfMetadataService;
|
||||
this.aiEngineClient = aiEngineClient;
|
||||
this.aiFeatureGate = aiFeatureGate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.userService = userService;
|
||||
this.labelStore = labelStore;
|
||||
@@ -111,6 +115,7 @@ public class ClassifyLabelController {
|
||||
+ " intended for direct client use.")
|
||||
public ResponseEntity<Resource> classifyAndLabel(
|
||||
@RequestParam("fileInput") MultipartFile fileInput) throws IOException {
|
||||
aiFeatureGate.requireClassify();
|
||||
try (PDDocument document = pdfDocumentFactory.load(fileInput, true)) {
|
||||
String fileName = safeFileName(fileInput.getOriginalFilename());
|
||||
|
||||
|
||||
+53
-2
@@ -8,6 +8,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -45,6 +46,7 @@ import stirling.software.common.util.RegexPatternUtils;
|
||||
import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;
|
||||
import stirling.software.proprietary.service.AiEngineConfigSync;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
@@ -58,6 +60,7 @@ public class AdminSettingsController {
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ApplicationContext applicationContext;
|
||||
private final AiEngineConfigSync aiEngineConfigSync;
|
||||
|
||||
// Track settings that have been modified but not yet applied (require restart)
|
||||
private static final ConcurrentHashMap<String, Object> pendingChanges =
|
||||
@@ -172,6 +175,28 @@ public class AdminSettingsController {
|
||||
.body(Map.of("error", "No settings provided to update"));
|
||||
}
|
||||
|
||||
// Work on a mutable copy so the removal below works even if the caller passed an
|
||||
// immutable map, then drop masked sensitive values so a UI round-trip never overwrites
|
||||
// a real secret (e.g. an API key) with the "********" placeholder from the GET
|
||||
// response.
|
||||
settings = new LinkedHashMap<>(settings);
|
||||
settings.entrySet()
|
||||
.removeIf(
|
||||
e -> {
|
||||
if (!"********".equals(e.getValue())) {
|
||||
return false;
|
||||
}
|
||||
String key = e.getKey();
|
||||
String leaf =
|
||||
key.contains(".")
|
||||
? key.substring(key.lastIndexOf('.') + 1)
|
||||
: key;
|
||||
return isSensitiveFieldWithPath(leaf, key);
|
||||
});
|
||||
if (settings.isEmpty()) {
|
||||
return ResponseEntity.ok(Map.of("message", "No changed settings to update."));
|
||||
}
|
||||
|
||||
// Validate all settings first before applying any changes
|
||||
for (Map.Entry<String, Object> entry : settings.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
@@ -206,6 +231,10 @@ public class AdminSettingsController {
|
||||
pendingChanges.put(key, value != null ? value : "");
|
||||
}
|
||||
|
||||
// If AI settings changed, push them to the engine live so model/RAG/limit changes
|
||||
// apply without waiting for a processor restart.
|
||||
maybePushAiEngineLive();
|
||||
|
||||
return ResponseEntity.ok(
|
||||
Map.of(
|
||||
"message",
|
||||
@@ -600,6 +629,23 @@ public class AdminSettingsController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward any pending {@code aiEngine.*} changes to the AI engine immediately. The running bean
|
||||
* overlaid with these pending values is the current settings.yml state; {@link
|
||||
* AiEngineConfigSync} no-ops unless AI is enabled and an engine-relevant key changed.
|
||||
*/
|
||||
private void maybePushAiEngineLive() {
|
||||
Map<String, Object> aiEnginePending = new HashMap<>();
|
||||
for (Map.Entry<String, Object> entry : pendingChanges.entrySet()) {
|
||||
if (entry.getKey().startsWith("aiEngine.")) {
|
||||
aiEnginePending.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
if (!aiEnginePending.isEmpty()) {
|
||||
aiEngineConfigSync.pushLiveAfterSave(aiEnginePending);
|
||||
}
|
||||
}
|
||||
|
||||
private Object getSectionData(String sectionName) {
|
||||
if (sectionName == null || sectionName.trim().isEmpty()) {
|
||||
return null;
|
||||
@@ -843,8 +889,13 @@ public class AdminSettingsController {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for fields containing 'password' or 'secret'
|
||||
return lowerField.contains("password") || lowerField.contains("secret");
|
||||
// Substring match for secret-bearing field names. Covers provider credentials such as
|
||||
// aiEngine.models.apiKey and aiEngine.rag.embeddingApiKey (which the exact-name set would
|
||||
// miss) so keys are never returned to the client in cleartext.
|
||||
return lowerField.contains("password")
|
||||
|| lowerField.contains("secret")
|
||||
|| lowerField.contains("apikey")
|
||||
|| lowerField.contains("token");
|
||||
}
|
||||
|
||||
/** Create a masked representation for sensitive fields */
|
||||
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
/**
|
||||
* Pushes the admin-configured AI settings (model provider/name, per-provider API key, RAG choices,
|
||||
* limits) to the Python engine so a self-hosted deployment can drive the engine's model and API key
|
||||
* from the Stirling settings UI. Pushed on processor startup and again live whenever AI settings
|
||||
* are saved (so model/RAG/limit changes apply without a restart). The engine applies it live
|
||||
* (rebuilds its models) and caches it, so it self-restores on its own reboot. Empty
|
||||
* key/baseUrl/model fields mean "keep the engine's own environment credential".
|
||||
*
|
||||
* <p>Gated by {@code aiEngine.pushConfigToEngine} (default true). Environment-driven deployments
|
||||
* pin it false (SaaS does so in application-saas.properties) so the engine stays entirely
|
||||
* env-controlled and the processor never pushes settings-derived config to it. Best-effort and
|
||||
* non-blocking: a slow or unreachable engine never delays or fails Stirling startup.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AiEngineConfigSync {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
private static final long RETRY_DELAY_MS = 3000L;
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final AiEngineClient aiEngineClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void pushConfigOnStartup() {
|
||||
AiEngine cfg = applicationProperties.getAiEngine();
|
||||
if (!cfg.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (!cfg.isPushConfigToEngine()) {
|
||||
log.debug(
|
||||
"Skipping AI engine config push: aiEngine.pushConfigToEngine is disabled"
|
||||
+ " (the engine is configured from its own environment)");
|
||||
return;
|
||||
}
|
||||
// Engine may still be booting; push on a virtual thread with a few retries so we never
|
||||
// block or crash Stirling startup when the engine is slow or briefly unreachable.
|
||||
Thread.ofVirtual().name("ai-engine-config-sync").start(() -> pushWithRetries(cfg));
|
||||
}
|
||||
|
||||
/**
|
||||
* Push AI settings to the engine immediately after an admin save so model/RAG/limit changes
|
||||
* reach the engine without waiting for a processor restart. {@code pendingAiEngine} are the
|
||||
* pending {@code aiEngine.*} dot-notation changes; the running bean overlaid with these is the
|
||||
* current settings.yml state. No-op unless AI is enabled and an engine-relevant key changed.
|
||||
*/
|
||||
public void pushLiveAfterSave(Map<String, Object> pendingAiEngine) {
|
||||
// Gate on the RUNNING bean: AiEngineClient refuses calls while the bean is disabled, so
|
||||
// pushing on a pending-but-not-restarted enable would always fail. The post-restart
|
||||
// startup push covers first-time enablement.
|
||||
AiEngine cfg = applicationProperties.getAiEngine();
|
||||
if (pendingAiEngine == null
|
||||
|| pendingAiEngine.isEmpty()
|
||||
|| !cfg.isPushConfigToEngine()
|
||||
|| !cfg.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
boolean engineRelevant =
|
||||
pendingAiEngine.keySet().stream().anyMatch(AiEngineConfigSync::isEngineRelevantKey);
|
||||
if (!engineRelevant) {
|
||||
return;
|
||||
}
|
||||
ObjectNode node = buildConfigNode(cfg);
|
||||
pendingAiEngine.forEach((k, v) -> overlayIfEngineRelevant(node, k, v));
|
||||
String body = node.toString();
|
||||
Thread.ofVirtual().name("ai-engine-config-live-push").start(() -> pushOnce(body));
|
||||
}
|
||||
|
||||
private void pushOnce(String body) {
|
||||
try {
|
||||
aiEngineClient.post("/api/v1/config", body, null);
|
||||
log.info("Pushed AI engine configuration after settings change");
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"Live AI engine config push failed: {} (will re-sync on next restart)",
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Only models/rag/limits are forwarded to the engine; enabled/url/timeouts/features are
|
||||
// processor-side and don't need a live engine push.
|
||||
private static boolean isEngineRelevantKey(String key) {
|
||||
return key.startsWith("aiEngine.models.")
|
||||
|| key.startsWith("aiEngine.rag.")
|
||||
|| key.startsWith("aiEngine.limits.");
|
||||
}
|
||||
|
||||
private void overlayIfEngineRelevant(ObjectNode node, String key, Object value) {
|
||||
if (!isEngineRelevantKey(key)) {
|
||||
return;
|
||||
}
|
||||
String[] parts = key.substring("aiEngine.".length()).split("\\.");
|
||||
ObjectNode parent = node;
|
||||
for (int i = 0; i < parts.length - 1; i++) {
|
||||
JsonNode child = parent.get(parts[i]);
|
||||
parent = (child instanceof ObjectNode on) ? on : parent.putObject(parts[i]);
|
||||
}
|
||||
parent.set(parts[parts.length - 1], objectMapper.valueToTree(value));
|
||||
}
|
||||
|
||||
private void pushWithRetries(AiEngine cfg) {
|
||||
String body = buildConfigNode(cfg).toString();
|
||||
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
aiEngineClient.post("/api/v1/config", body, null);
|
||||
log.info("Pushed AI engine configuration on startup (attempt {})", attempt);
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
log.warn(
|
||||
"AI engine config push failed (attempt {}/{}): {}",
|
||||
attempt,
|
||||
MAX_ATTEMPTS,
|
||||
e.getMessage());
|
||||
if (attempt < MAX_ATTEMPTS) {
|
||||
try {
|
||||
Thread.sleep(RETRY_DELAY_MS);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
log.warn(
|
||||
"Giving up pushing AI engine configuration after {} attempts; the engine will use"
|
||||
+ " its own environment configuration until the next restart.",
|
||||
MAX_ATTEMPTS);
|
||||
}
|
||||
|
||||
private ObjectNode buildConfigNode(AiEngine cfg) {
|
||||
AiEngine.Models m = cfg.getModels();
|
||||
AiEngine.Rag r = cfg.getRag();
|
||||
AiEngine.Limits l = cfg.getLimits();
|
||||
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode models = root.putObject("models");
|
||||
models.put("provider", m.getProvider());
|
||||
models.put("smartModel", m.getSmartModel());
|
||||
models.put("fastModel", m.getFastModel());
|
||||
models.put("smartMaxTokens", m.getSmartMaxTokens());
|
||||
models.put("fastMaxTokens", m.getFastMaxTokens());
|
||||
models.put("apiKey", m.getApiKey());
|
||||
models.put("baseUrl", m.getBaseUrl());
|
||||
|
||||
ObjectNode rag = root.putObject("rag");
|
||||
rag.put("embeddingProvider", r.getEmbeddingProvider());
|
||||
rag.put("embeddingModel", r.getEmbeddingModel());
|
||||
rag.put("embeddingApiKey", r.getEmbeddingApiKey());
|
||||
rag.put("embeddingBaseUrl", r.getEmbeddingBaseUrl());
|
||||
rag.put("topK", r.getTopK());
|
||||
rag.put("maxSearches", r.getMaxSearches());
|
||||
|
||||
ObjectNode limits = root.putObject("limits");
|
||||
limits.put("maxPages", l.getMaxPages());
|
||||
limits.put("maxCharacters", l.getMaxCharacters());
|
||||
limits.put("modelMaxConcurrency", l.getModelMaxConcurrency());
|
||||
|
||||
return root;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine.Features;
|
||||
|
||||
/**
|
||||
* Central gate for the per-capability AI feature switches ({@code aiEngine.features.*}). Each AI
|
||||
* capability entry point calls the matching {@code require*} method so an admin who turns a feature
|
||||
* off in the settings UI gets a clean 503 instead of the request silently reaching the engine. All
|
||||
* checks also fail closed when the AI engine itself is disabled.
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AiFeatureGate {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
private Features features() {
|
||||
return applicationProperties.getAiEngine().getFeatures();
|
||||
}
|
||||
|
||||
private void require(boolean featureEnabled, String feature) {
|
||||
if (!applicationProperties.getAiEngine().isEnabled() || !featureEnabled) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.SERVICE_UNAVAILABLE, "AI feature '" + feature + "' is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
public void requireChat() {
|
||||
require(features().isChat(), "chat");
|
||||
}
|
||||
|
||||
public void requireDocumentQuestions() {
|
||||
require(features().isDocumentQuestions(), "documentQuestions");
|
||||
}
|
||||
|
||||
public void requireCreatePdf() {
|
||||
require(features().isCreatePdf(), "createPdf");
|
||||
}
|
||||
|
||||
public void requireMathAuditor() {
|
||||
require(features().isMathAuditor(), "mathAuditor");
|
||||
}
|
||||
|
||||
public void requirePdfComment() {
|
||||
require(features().isPdfComment(), "pdfComment");
|
||||
}
|
||||
|
||||
public void requireClassify() {
|
||||
require(features().isClassify(), "classify");
|
||||
}
|
||||
}
|
||||
+3
@@ -32,6 +32,7 @@ import stirling.software.proprietary.classification.model.ClassificationLabels;
|
||||
import stirling.software.proprietary.classification.store.InProcessClassificationLabelStore;
|
||||
import stirling.software.proprietary.policy.config.PolicyManagementAuthority;
|
||||
import stirling.software.proprietary.service.AiEngineClient;
|
||||
import stirling.software.proprietary.service.AiFeatureGate;
|
||||
import stirling.software.proprietary.service.PdfContentExtractor;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
@@ -49,6 +50,7 @@ class ClassifyLabelControllerTest {
|
||||
@Mock private PdfContentExtractor pdfContentExtractor;
|
||||
@Mock private PdfMetadataService pdfMetadataService;
|
||||
@Mock private AiEngineClient aiEngineClient;
|
||||
@Mock private AiFeatureGate aiFeatureGate;
|
||||
@Mock private PolicyManagementAuthority policyManagementAuthority;
|
||||
|
||||
private final ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
@@ -65,6 +67,7 @@ class ClassifyLabelControllerTest {
|
||||
pdfContentExtractor,
|
||||
pdfMetadataService,
|
||||
aiEngineClient,
|
||||
aiFeatureGate,
|
||||
objectMapper,
|
||||
null,
|
||||
labelStore,
|
||||
|
||||
+55
-1
@@ -1,10 +1,13 @@
|
||||
package stirling.software.proprietary.security.controller.api;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -26,6 +29,7 @@ import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.proprietary.security.model.api.admin.SettingValueResponse;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingValueRequest;
|
||||
import stirling.software.proprietary.security.model.api.admin.UpdateSettingsRequest;
|
||||
import stirling.software.proprietary.service.AiEngineConfigSync;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
@@ -37,6 +41,7 @@ class AdminSettingsControllerTest {
|
||||
private ApplicationProperties applicationProperties;
|
||||
private ObjectMapper objectMapper;
|
||||
private ApplicationContext applicationContext;
|
||||
private AiEngineConfigSync aiEngineConfigSync;
|
||||
|
||||
private AdminSettingsController controller;
|
||||
|
||||
@@ -45,9 +50,13 @@ class AdminSettingsControllerTest {
|
||||
applicationProperties = new ApplicationProperties();
|
||||
objectMapper = JsonMapper.builder().build();
|
||||
applicationContext = org.mockito.Mockito.mock(ApplicationContext.class);
|
||||
aiEngineConfigSync = org.mockito.Mockito.mock(AiEngineConfigSync.class);
|
||||
controller =
|
||||
new AdminSettingsController(
|
||||
applicationProperties, objectMapper, applicationContext);
|
||||
applicationProperties,
|
||||
objectMapper,
|
||||
applicationContext,
|
||||
aiEngineConfigSync);
|
||||
clearPendingChanges();
|
||||
}
|
||||
|
||||
@@ -277,6 +286,51 @@ class AdminSettingsControllerTest {
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("drops a masked ******** secret so a UI round-trip can't overwrite a real key")
|
||||
void dropsMaskedSecretValue() {
|
||||
UpdateSettingsRequest request = new UpdateSettingsRequest();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("aiEngine.models.apiKey", "********");
|
||||
settings.put("ui.appName", "My App");
|
||||
request.setSettings(settings);
|
||||
|
||||
try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {
|
||||
ResponseEntity<Map<String, Object>> response = controller.updateSettings(request);
|
||||
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
// The masked secret is stripped; only the real change is persisted.
|
||||
mocked.verify(
|
||||
() ->
|
||||
GeneralUtils.updateSettingsTransactional(
|
||||
argThat(
|
||||
(Map<String, Object> m) ->
|
||||
!m.containsKey("aiEngine.models.apiKey")
|
||||
&& m.containsKey("ui.appName"))));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("forwards only aiEngine.* pending keys to the engine live-push")
|
||||
void forwardsOnlyAiEngineKeysToLivePush() {
|
||||
UpdateSettingsRequest request = new UpdateSettingsRequest();
|
||||
Map<String, Object> settings = new HashMap<>();
|
||||
settings.put("aiEngine.models.provider", "ollama");
|
||||
settings.put("ui.appName", "My App");
|
||||
request.setSettings(settings);
|
||||
|
||||
try (MockedStatic<GeneralUtils> mocked = mockStatic(GeneralUtils.class)) {
|
||||
controller.updateSettings(request);
|
||||
|
||||
verify(aiEngineConfigSync)
|
||||
.pushLiveAfterSave(
|
||||
argThat(
|
||||
(Map<String, Object> m) ->
|
||||
m.containsKey("aiEngine.models.provider")
|
||||
&& !m.containsKey("ui.appName")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.AiEngine;
|
||||
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* The config-push bridge is a self-hosted-only feature: it lets the admin UI drive the engine's
|
||||
* model/key/RAG/limit config. Environment-driven deployments pin {@code
|
||||
* aiEngine.pushConfigToEngine} false (SaaS does so in application-saas.properties) so the engine
|
||||
* stays entirely env-controlled - these tests lock in that the processor stays silent then while
|
||||
* still pushing when it is enabled.
|
||||
*/
|
||||
class AiEngineConfigSyncTest {
|
||||
|
||||
private ApplicationProperties applicationProperties;
|
||||
private AiEngineClient aiEngineClient;
|
||||
private AiEngineConfigSync sync;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
applicationProperties = new ApplicationProperties();
|
||||
applicationProperties.getAiEngine().setEnabled(true);
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(true);
|
||||
aiEngineClient = mock(AiEngineClient.class);
|
||||
ObjectMapper objectMapper = JsonMapper.builder().build();
|
||||
sync = new AiEngineConfigSync(applicationProperties, aiEngineClient, objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSkippedWhenPushDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(false);
|
||||
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
// Returns synchronously before spawning the push thread, so no interaction ever happens.
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSkippedWhenDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setEnabled(false);
|
||||
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSentWhenEnabledAndPushOn() throws Exception {
|
||||
sync.pushConfigOnStartup();
|
||||
|
||||
// Push runs on a virtual thread; wait for the single POST to /api/v1/config.
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSkippedWhenPushDisabled() throws Exception {
|
||||
applicationProperties.getAiEngine().setPushConfigToEngine(false);
|
||||
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.models.provider", "ollama"));
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSentForEngineRelevantChangeWhenPushOn() throws Exception {
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.models.provider", "ollama"));
|
||||
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), anyString(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startupPushSerialisesTheEngineWireContract() throws Exception {
|
||||
// Distinct values so a dropped/renamed field is detectable. Mirrors
|
||||
// engine/tests/fixtures/processor_config_push.json - keep the two in sync; the engine's
|
||||
// test_config_contract.py validates that same shape on the receiving side.
|
||||
AiEngine ai = applicationProperties.getAiEngine();
|
||||
ai.getModels().setProvider("ollama");
|
||||
ai.getModels().setSmartModel("smart-model-x");
|
||||
ai.getModels().setFastModel("fast-model-x");
|
||||
ai.getModels().setSmartMaxTokens(1111);
|
||||
ai.getModels().setFastMaxTokens(2222);
|
||||
ai.getModels().setApiKey("provider-key-abc");
|
||||
ai.getModels().setBaseUrl("http://engine.example/v1");
|
||||
ai.getRag().setEmbeddingProvider("custom");
|
||||
ai.getRag().setEmbeddingModel("embed-model-x");
|
||||
ai.getRag().setEmbeddingApiKey("embed-key-abc");
|
||||
ai.getRag().setEmbeddingBaseUrl("http://embed.example/v1");
|
||||
ai.getRag().setTopK(33);
|
||||
ai.getRag().setMaxSearches(7);
|
||||
ai.getLimits().setMaxPages(111);
|
||||
ai.getLimits().setMaxCharacters(222222);
|
||||
ai.getLimits().setModelMaxConcurrency(9);
|
||||
|
||||
ArgumentCaptor<String> body = ArgumentCaptor.forClass(String.class);
|
||||
sync.pushConfigOnStartup();
|
||||
verify(aiEngineClient, timeout(3000)).post(eq("/api/v1/config"), body.capture(), isNull());
|
||||
|
||||
JsonNode root = JsonMapper.builder().build().readTree(body.getValue());
|
||||
|
||||
JsonNode models = root.get("models");
|
||||
assertEquals("ollama", models.get("provider").asText());
|
||||
assertEquals("smart-model-x", models.get("smartModel").asText());
|
||||
assertEquals("fast-model-x", models.get("fastModel").asText());
|
||||
assertEquals(1111, models.get("smartMaxTokens").asInt());
|
||||
assertEquals(2222, models.get("fastMaxTokens").asInt());
|
||||
assertEquals("provider-key-abc", models.get("apiKey").asText());
|
||||
assertEquals("http://engine.example/v1", models.get("baseUrl").asText());
|
||||
|
||||
JsonNode rag = root.get("rag");
|
||||
assertEquals("custom", rag.get("embeddingProvider").asText());
|
||||
assertEquals("embed-model-x", rag.get("embeddingModel").asText());
|
||||
assertEquals("embed-key-abc", rag.get("embeddingApiKey").asText());
|
||||
assertEquals("http://embed.example/v1", rag.get("embeddingBaseUrl").asText());
|
||||
assertEquals(33, rag.get("topK").asInt());
|
||||
assertEquals(7, rag.get("maxSearches").asInt());
|
||||
|
||||
JsonNode limits = root.get("limits");
|
||||
assertEquals(111, limits.get("maxPages").asInt());
|
||||
assertEquals(222222, limits.get("maxCharacters").asInt());
|
||||
assertEquals(9, limits.get("modelMaxConcurrency").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void livePushSkippedForNonEngineRelevantChange() throws Exception {
|
||||
// features.* is processor-side only; no engine push is warranted.
|
||||
sync.pushLiveAfterSave(Map.of("aiEngine.features.chat", false));
|
||||
|
||||
verify(aiEngineClient, never()).post(anyString(), anyString(), isNull());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
|
||||
/**
|
||||
* Every AI capability entry point calls the matching {@code require*} before reaching the engine.
|
||||
* These lock in fail-closed behaviour: a 503 when the engine is disabled OR the individual feature
|
||||
* flag is off, and a clean pass only when both are on.
|
||||
*/
|
||||
class AiFeatureGateTest {
|
||||
|
||||
private ApplicationProperties props;
|
||||
private AiFeatureGate gate;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
props = new ApplicationProperties();
|
||||
props.getAiEngine().setEnabled(true); // features default all-on
|
||||
gate = new AiFeatureGate(props);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesWhenEngineEnabledAndFeatureOn() {
|
||||
assertDoesNotThrow(() -> gate.requireClassify());
|
||||
assertDoesNotThrow(() -> gate.requireChat());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throws503WhenFeatureFlagOff() {
|
||||
props.getAiEngine().getFeatures().setClassify(false);
|
||||
|
||||
ResponseStatusException ex =
|
||||
assertThrows(ResponseStatusException.class, () -> gate.requireClassify());
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, ex.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void throws503WhenEngineDisabledEvenIfFeatureOn() {
|
||||
props.getAiEngine().setEnabled(false); // feature flag still true
|
||||
|
||||
ResponseStatusException ex =
|
||||
assertThrows(ResponseStatusException.class, () -> gate.requireChat());
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, ex.getStatusCode());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
# Stirling-PDF SaaS profile. Pure multi-tenant cloud.
|
||||
# Activated when the :saas module is on the classpath.
|
||||
|
||||
# ---------- AI engine ----------
|
||||
# The SaaS AI backend is env-driven and reached through the saas AiProxyController, so the
|
||||
# processor must never push settings-derived config to it. Pin the config-push off; the engine
|
||||
# stays entirely environment-controlled.
|
||||
aiEngine.pushConfigToEngine=false
|
||||
|
||||
# ---------- Datasource ----------
|
||||
system.datasource.enableCustomDatabase=true
|
||||
system.datasource.customDatabaseUrl=${SAAS_DB_URL:}
|
||||
|
||||
@@ -88,3 +88,8 @@ STIRLING_LOG_FILE=
|
||||
# Use when diagnosing worker stalls: a hung call shows a "Request" line with
|
||||
# no matching "Response" line. Noisy; leave off in normal use.
|
||||
STIRLING_HTTP_DEBUG=false
|
||||
|
||||
# Allow the Java processor to push admin-configured AI settings (model,
|
||||
# credentials, limits) to POST /api/v1/config at startup. Set false in
|
||||
# environment-driven deployments so the environment is the single source of truth.
|
||||
#STIRLING_ALLOW_CONFIG_PUSH=true
|
||||
|
||||
@@ -4,6 +4,7 @@ version = "0.1.0"
|
||||
description = "AI Document Engine"
|
||||
requires-python = ">=3.13"
|
||||
dependencies = [
|
||||
"cryptography>=44.0.0",
|
||||
"fastapi>=0.116.0",
|
||||
"jinja2>=3.1.0",
|
||||
"pgvector>=0.3.6",
|
||||
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents.output_mode import output_retries
|
||||
from stirling.contracts import (
|
||||
MathAuditorToolReportArtifact,
|
||||
OrchestratorRequest,
|
||||
@@ -68,6 +69,10 @@ class MathIntentClassifier:
|
||||
self._agent: Agent[None, _MathIntentDecision] = Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=_MathIntentDecision,
|
||||
# Local models emit valid structured output only intermittently (they
|
||||
# sometimes wrap the JSON in prose); a few extra retries make this
|
||||
# hot-path classifier reliable. No-op for real providers.
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
system_prompt=_MATH_INTENT_SYSTEM_PROMPT,
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
|
||||
@@ -2,12 +2,14 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import assert_never
|
||||
from typing import Literal, assert_never
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.output import NativeOutput, ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.agents.output_mode import output_retries, uses_tool_output
|
||||
from stirling.agents.pdf_create import PdfCreateAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.agents.pdf_questions import PdfQuestionAgent
|
||||
@@ -27,6 +29,7 @@ from stirling.contracts import (
|
||||
format_file_names,
|
||||
)
|
||||
from stirling.contracts.pdf_create import PdfCreateOrchestrateResponse
|
||||
from stirling.models import ApiModel
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -38,6 +41,38 @@ class OrchestratorDeps:
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
# Enum-style routing used for Ollama/custom (OpenAI-compatible local) models. The
|
||||
# function-ToolOutput delegates below take no arguments (they read everything from
|
||||
# ctx), but local models reliably try to pass the user's message as tool args, which
|
||||
# the zero-arg delegate schemas reject. Having the model pick a capability by name and
|
||||
# dispatching in Python (via the same _run_* methods used on resume) sidesteps that.
|
||||
_RouteCapability = Literal["pdf_edit", "pdf_question", "user_spec", "pdf_review", "pdf_create", "unsupported"]
|
||||
|
||||
|
||||
class _RouteDecision(ApiModel):
|
||||
# Local models routinely add stray tool args (the filename, the question echoed back)
|
||||
# and send null for optional fields; tolerate both so routing never fails on cosmetics.
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
capability: _RouteCapability
|
||||
message: str | None = Field(
|
||||
default=None,
|
||||
description="Only for capability='unsupported': a short, helpful message to show the user.",
|
||||
)
|
||||
|
||||
|
||||
_ROUTER_SYSTEM_PROMPT = (
|
||||
"You are the top-level router. Choose exactly one capability that best handles the request:\n"
|
||||
"- pdf_edit: modify or convert one or more attached PDFs.\n"
|
||||
"- pdf_question: answer questions about the contents of the attached PDFs.\n"
|
||||
"- user_spec: create or define an agent spec.\n"
|
||||
"- pdf_review: return the PDF with review comments/annotations attached.\n"
|
||||
"- pdf_create: generate a NEW document from scratch (invoice, report, letter) - no input file.\n"
|
||||
"- unsupported: none of the above fit, or the user asks about the assistant itself; put a "
|
||||
"helpful message in 'message'.\n"
|
||||
"Respond with the capability and (only for unsupported) a message."
|
||||
)
|
||||
|
||||
|
||||
class OrchestratorAgent:
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
@@ -86,6 +121,9 @@ class OrchestratorAgent:
|
||||
description="Return this when none of the delegate outputs fit the request.",
|
||||
),
|
||||
],
|
||||
# Local models (Ollama/custom) pick a delegate less reliably; give the
|
||||
# routing a few extra validation retries. No-op for real providers.
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
deps_type=OrchestratorDeps,
|
||||
system_prompt=(
|
||||
"You are the top-level orchestrator. "
|
||||
@@ -103,6 +141,24 @@ class OrchestratorAgent:
|
||||
),
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
# Local models can't drive the zero-arg function-delegate routing above, so
|
||||
# route them by capability name and dispatch in Python instead.
|
||||
self._route_via_enum = uses_tool_output(runtime.settings.chat_provider)
|
||||
# The router has no tools of its own, so NativeOutput (a direct structured
|
||||
# response) works on Ollama here - unlike tool-using agents, which need
|
||||
# ToolOutput. A single output tool would tempt a local model to answer in
|
||||
# plain text and never call it ("include your response in a tool call").
|
||||
self._router = (
|
||||
Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=NativeOutput([_RouteDecision]),
|
||||
retries=output_retries(runtime.settings.chat_provider),
|
||||
system_prompt=_ROUTER_SYSTEM_PROMPT,
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
if self._route_via_enum
|
||||
else None
|
||||
)
|
||||
|
||||
async def handle(self, request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
logger.info(
|
||||
@@ -114,6 +170,8 @@ class OrchestratorAgent:
|
||||
)
|
||||
if request.resume_with is not None:
|
||||
return await self._resume(request, request.resume_with)
|
||||
if self._router is not None:
|
||||
return await self._route_and_dispatch(request)
|
||||
result = await self.agent.run(
|
||||
self._build_prompt(request),
|
||||
deps=OrchestratorDeps(runtime=self.runtime, request=request),
|
||||
@@ -121,6 +179,31 @@ class OrchestratorAgent:
|
||||
logger.info("[orchestrator] routed -> %s", type(result.output).__name__)
|
||||
return result.output
|
||||
|
||||
async def _route_and_dispatch(self, request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
"""Local-model routing: pick a capability by name, then dispatch in Python."""
|
||||
assert self._router is not None
|
||||
result = await self._router.run(self._build_prompt(request))
|
||||
decision = result.output
|
||||
logger.info("[orchestrator] enum-routed -> %s", decision.capability)
|
||||
match decision.capability:
|
||||
case "pdf_edit":
|
||||
return await self._run_pdf_edit(request)
|
||||
case "pdf_question":
|
||||
return await self._run_pdf_question(request)
|
||||
case "user_spec":
|
||||
return await self._run_agent_draft(request)
|
||||
case "pdf_review":
|
||||
return await self._run_pdf_review(request)
|
||||
case "pdf_create":
|
||||
return await self._run_pdf_create(request)
|
||||
case "unsupported":
|
||||
return UnsupportedCapabilityResponse(
|
||||
capability="orchestrate",
|
||||
message=decision.message or "I can't help with that request.",
|
||||
)
|
||||
case _ as unreachable:
|
||||
assert_never(unreachable)
|
||||
|
||||
async def _resume(self, request: OrchestratorRequest, capability: SupportedCapability) -> OrchestratorResponse:
|
||||
"""Fast-path to get back to the correct endpoint without having to call AI.
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Provider-aware structured-output strategy.
|
||||
|
||||
OpenAI-compatible local models (Ollama, and 'custom' OpenAI-compatible endpoints)
|
||||
block tool-calling whenever a native json-schema ``response_format`` is set: the
|
||||
API constrains every completion to the output schema, so the model can never emit
|
||||
a tool-call turn. Agents that combine structured output with tools (RAG search,
|
||||
whole-document read, etc.) therefore get an ungrounded answer - the model fills the
|
||||
schema directly instead of calling a retrieval tool.
|
||||
|
||||
Delivering the structured result via a tool call (:class:`ToolOutput`) sidesteps
|
||||
this: it's all tool-calling, which these endpoints handle, so the model can call a
|
||||
retrieval tool and then the output tool. Real providers (Anthropic, OpenAI) keep
|
||||
:class:`NativeOutput`, which is unaffected and preferred there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from pydantic_ai.output import NativeOutput, ToolOutput
|
||||
|
||||
# Providers whose OpenAI-compatible endpoint needs tool-delivered structured output.
|
||||
_TOOL_OUTPUT_PROVIDERS = frozenset({"ollama", "custom"})
|
||||
|
||||
|
||||
def uses_tool_output(chat_provider: str) -> bool:
|
||||
return chat_provider in _TOOL_OUTPUT_PROVIDERS
|
||||
|
||||
|
||||
def structured_output(output_types: Sequence[Any], *, chat_provider: str) -> Any:
|
||||
"""Pick a structured-output spec compatible with the active chat provider.
|
||||
|
||||
Ollama/custom deliver each output variant via a :class:`ToolOutput`; every other
|
||||
provider uses a single :class:`NativeOutput` over the variants.
|
||||
"""
|
||||
types = list(output_types)
|
||||
if uses_tool_output(chat_provider):
|
||||
return [ToolOutput(t) for t in types]
|
||||
return NativeOutput(types)
|
||||
|
||||
|
||||
def output_retries(chat_provider: str, *, native: int = 1, tool: int = 6) -> int:
|
||||
"""Local models delivering via ToolOutput need more output-validation retries -
|
||||
small models produce valid complex/nested structured output only intermittently."""
|
||||
return tool if uses_tool_output(chat_provider) else native
|
||||
@@ -3,10 +3,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents.contradiction import ContradictionCapability, ContradictionDetector
|
||||
from stirling.agents.math_presentation import MathIntentClassifier, extract_math_verdict
|
||||
from stirling.agents.output_mode import output_retries, structured_output
|
||||
from stirling.agents.shared import ChunkedReasoner, WholeDocReaderCapability
|
||||
from stirling.contracts import (
|
||||
AiFile,
|
||||
@@ -196,9 +196,17 @@ class PdfQuestionAgent:
|
||||
files=request.files,
|
||||
principals=principals,
|
||||
)
|
||||
# Ollama/custom (OpenAI-compatible local) models block tool-calling under a
|
||||
# native json-schema response format, so deliver the structured result via a
|
||||
# tool call instead - otherwise the model never calls the retrieval tools and
|
||||
# answers ungrounded. Real providers keep NativeOutput. See agents.output_mode.
|
||||
provider = self.runtime.settings.chat_provider
|
||||
agent = Agent(
|
||||
model=self.runtime.smart_model,
|
||||
output_type=NativeOutput([PdfQuestionAnswerResponse, PdfQuestionNotFoundResponse]),
|
||||
output_type=structured_output(
|
||||
[PdfQuestionAnswerResponse, PdfQuestionNotFoundResponse], chat_provider=provider
|
||||
),
|
||||
retries=output_retries(provider),
|
||||
system_prompt=PDF_QUESTION_SYSTEM_PROMPT,
|
||||
# pydantic-ai accepts a list of (string-or-callable) instruction sources;
|
||||
# it resolves each at run time and concatenates them for the model.
|
||||
|
||||
@@ -3,28 +3,20 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.models import Model
|
||||
from pydantic_ai.models.instrumented import InstrumentationSettings
|
||||
|
||||
from stirling.agents import (
|
||||
DocumentClassifierAgent,
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
UserSpecAgent,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
from stirling.api.bootstrap import apply_app_state, build_app_state
|
||||
from stirling.api.dependencies import enforce_required_user_id
|
||||
from stirling.api.engine_auth import EngineSharedSecretMiddleware
|
||||
from stirling.api.middleware import UserIdMiddleware
|
||||
from stirling.api.routes import (
|
||||
agent_capabilities_router,
|
||||
agent_draft_router,
|
||||
config_router,
|
||||
document_classifier_router,
|
||||
document_router,
|
||||
execution_router,
|
||||
@@ -34,10 +26,12 @@ from stirling.api.routes import (
|
||||
pdf_edit_router,
|
||||
pdf_question_router,
|
||||
)
|
||||
from stirling.api.routes.config import CONFIG_APPLY_ERRORS, resolve_and_apply
|
||||
from stirling.config import AppSettings, load_settings
|
||||
from stirling.config.config_cache import load_config
|
||||
from stirling.contracts import HealthResponse
|
||||
from stirling.documents import DocumentService
|
||||
from stirling.services import build_runtime, setup_posthog_tracking
|
||||
from stirling.documents import DocumentService, EmbeddingService
|
||||
from stirling.services import setup_posthog_tracking
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -83,22 +77,52 @@ def _load_startup_settings(fast_api: FastAPI) -> AppSettings:
|
||||
return load_settings()
|
||||
|
||||
|
||||
def _restore_cached_config(
|
||||
settings: AppSettings,
|
||||
) -> tuple[AppSettings, Model | None, Model | None, EmbeddingService | None]:
|
||||
"""Restore the last-applied pushed config from the encrypted on-disk cache.
|
||||
|
||||
Returns the effective settings plus the pre-built smart/fast models and
|
||||
embedder to inject into the initial app state. Falls back to the env settings
|
||||
(all-None) when config push is disabled, no cache exists, or the cached config
|
||||
can't be applied (bad/unavailable model) - the cache never crashes boot.
|
||||
"""
|
||||
if not settings.allow_config_push:
|
||||
return settings, None, None, None
|
||||
cached = load_config()
|
||||
if cached is None:
|
||||
return settings, None, None, None
|
||||
try:
|
||||
effective, smart_model, fast_model, embedder, notes = resolve_and_apply(settings, cached)
|
||||
except CONFIG_APPLY_ERRORS:
|
||||
logger.warning("Cached AI config could not be applied; falling back to env settings", exc_info=True)
|
||||
return settings, None, None, None
|
||||
logger.info(
|
||||
"Restored cached AI config: smart_model=%s fast_model=%s%s",
|
||||
effective.smart_model_name,
|
||||
effective.fast_model_name,
|
||||
f"; {'; '.join(notes)}" if notes else "",
|
||||
)
|
||||
return effective, smart_model, fast_model, embedder
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(fast_api: FastAPI):
|
||||
# Load env vars on startup so we can immediately crash if required env vars aren't set
|
||||
settings = _load_startup_settings(fast_api)
|
||||
runtime = build_runtime(settings)
|
||||
fast_api.state.settings = settings
|
||||
fast_api.state.runtime = runtime
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime)
|
||||
fast_api.state.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
fast_api.state.pdf_question_agent = PdfQuestionAgent(runtime)
|
||||
fast_api.state.user_spec_agent = UserSpecAgent(runtime)
|
||||
fast_api.state.execution_planning_agent = ExecutionPlanningAgent(runtime)
|
||||
fast_api.state.math_auditor_agent = MathAuditorAgent(runtime)
|
||||
fast_api.state.pdf_comment_agent = PdfCommentAgent(runtime)
|
||||
fast_api.state.document_classifier_agent = DocumentClassifierAgent(runtime)
|
||||
tracer_provider = setup_posthog_tracking(settings)
|
||||
# Precedence: env < persisted cache < live push. Restore the last-applied pushed
|
||||
# config unless config push is disabled (then env is the single source of truth).
|
||||
effective, smart_model, fast_model, embedder = _restore_cached_config(settings)
|
||||
app_state = build_app_state(
|
||||
effective,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
embedder=embedder,
|
||||
)
|
||||
fast_api.state.settings = effective
|
||||
apply_app_state(fast_api.state, app_state)
|
||||
runtime = app_state.runtime
|
||||
tracer_provider = setup_posthog_tracking(effective)
|
||||
if tracer_provider:
|
||||
Agent.instrument_all(InstrumentationSettings(tracer_provider=tracer_provider))
|
||||
reaper_task = asyncio.create_task(
|
||||
@@ -135,10 +159,18 @@ app.include_router(ledger_router, dependencies=_user_gate)
|
||||
app.include_router(pdf_comments_router, dependencies=_user_gate)
|
||||
app.include_router(agent_capabilities_router, dependencies=_user_gate)
|
||||
app.include_router(document_classifier_router, dependencies=_user_gate)
|
||||
# Config push is a system/admin sync from the Java processor with no X-User-Id, so
|
||||
# it is guarded by the X-Engine-Auth shared secret (global middleware) and the
|
||||
# allow_config_push flag only, deliberately NOT the per-user identity gate.
|
||||
app.include_router(config_router)
|
||||
|
||||
|
||||
@app.get("/health", response_model=HealthResponse)
|
||||
async def healthcheck(settings: Annotated[AppSettings, Depends(load_settings)]) -> HealthResponse:
|
||||
async def healthcheck(http_request: Request) -> HealthResponse:
|
||||
# Report the LIVE config (env < cache < push) held on app.state, not the
|
||||
# boot-time env cache, so an admin "Test connection" check shows the model
|
||||
# actually in use after a config push. Falls back to env if state isn't up yet.
|
||||
settings: AppSettings = getattr(http_request.app.state, "settings", None) or load_settings()
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
smart_model=settings.smart_model_name,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Assemble the runtime + every agent into a single swappable bundle.
|
||||
|
||||
Both the lifespan startup and the config-push endpoint build the same object
|
||||
graph: one :class:`AppRuntime` plus one agent instance per flow, each of which
|
||||
captures ``runtime.smart_model``/``runtime.fast_model`` at construction. To change
|
||||
models at runtime the whole bundle has to be rebuilt and swapped into
|
||||
``app.state`` atomically, which is what :func:`build_app_state` /
|
||||
:func:`apply_app_state` exist for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any
|
||||
|
||||
from pydantic_ai.models import Model
|
||||
|
||||
from stirling.agents import (
|
||||
DocumentClassifierAgent,
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
UserSpecAgent,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
from stirling.config import AppSettings
|
||||
from stirling.documents import DocumentService, EmbeddingService
|
||||
from stirling.services import AppRuntime, build_runtime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AppState:
|
||||
"""Every object the lifespan assigns onto ``fast_api.state``."""
|
||||
|
||||
runtime: AppRuntime
|
||||
orchestrator_agent: OrchestratorAgent
|
||||
pdf_edit_agent: PdfEditAgent
|
||||
pdf_question_agent: PdfQuestionAgent
|
||||
user_spec_agent: UserSpecAgent
|
||||
execution_planning_agent: ExecutionPlanningAgent
|
||||
math_auditor_agent: MathAuditorAgent
|
||||
pdf_comment_agent: PdfCommentAgent
|
||||
document_classifier_agent: DocumentClassifierAgent
|
||||
|
||||
|
||||
def build_app_state(
|
||||
settings: AppSettings,
|
||||
*,
|
||||
documents: DocumentService | None = None,
|
||||
fast_model: Model | None = None,
|
||||
smart_model: Model | None = None,
|
||||
embedder: EmbeddingService | None = None,
|
||||
) -> AppState:
|
||||
"""Build the runtime and every agent from ``settings``.
|
||||
|
||||
The keyword arguments are threaded straight to :func:`build_runtime` so a
|
||||
config-push rebuild can reuse the live document store and inject already
|
||||
validated models (and, on a cache-restore boot, a pre-built embedder); all
|
||||
None reproduces the original startup path.
|
||||
"""
|
||||
runtime = build_runtime(
|
||||
settings,
|
||||
documents=documents,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
embedder=embedder,
|
||||
)
|
||||
return AppState(
|
||||
runtime=runtime,
|
||||
orchestrator_agent=OrchestratorAgent(runtime),
|
||||
pdf_edit_agent=PdfEditAgent(runtime),
|
||||
pdf_question_agent=PdfQuestionAgent(runtime),
|
||||
user_spec_agent=UserSpecAgent(runtime),
|
||||
execution_planning_agent=ExecutionPlanningAgent(runtime),
|
||||
math_auditor_agent=MathAuditorAgent(runtime),
|
||||
pdf_comment_agent=PdfCommentAgent(runtime),
|
||||
document_classifier_agent=DocumentClassifierAgent(runtime),
|
||||
)
|
||||
|
||||
|
||||
def apply_app_state(state: Any, app_state: AppState) -> None:
|
||||
"""Copy every field of ``app_state`` onto a Starlette ``app.state`` object."""
|
||||
for field in fields(app_state):
|
||||
setattr(state, field.name, getattr(app_state, field.name))
|
||||
@@ -1,5 +1,6 @@
|
||||
from .agent_capabilities import router as agent_capabilities_router
|
||||
from .agent_drafts import router as agent_draft_router
|
||||
from .config import router as config_router
|
||||
from .document_classifier import router as document_classifier_router
|
||||
from .documents import router as document_router
|
||||
from .execution import router as execution_router
|
||||
@@ -12,6 +13,7 @@ from .pdf_questions import router as pdf_question_router
|
||||
__all__ = [
|
||||
"agent_capabilities_router",
|
||||
"agent_draft_router",
|
||||
"config_router",
|
||||
"document_classifier_router",
|
||||
"document_router",
|
||||
"execution_router",
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, status
|
||||
from openai import OpenAIError
|
||||
from pydantic_ai.exceptions import UserError
|
||||
from pydantic_ai.models import Model
|
||||
|
||||
from stirling.api.bootstrap import apply_app_state, build_app_state
|
||||
from stirling.config import AppSettings
|
||||
from stirling.config.config_cache import save_config
|
||||
from stirling.contracts import ConfigApplyResponse, ConfigPushRequest
|
||||
from stirling.documents import EmbeddingService
|
||||
from stirling.services import AppRuntime
|
||||
from stirling.services.runtime import _build_model, validate_structured_output_support
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/config", tags=["config"])
|
||||
|
||||
# Model/provider construction + validation failures. The HTTP route maps these to a
|
||||
# 400 (no swap); boot catches them to fall back to env when a cached config is bad.
|
||||
CONFIG_APPLY_ERRORS = (ValueError, UserError, OpenAIError)
|
||||
|
||||
_REINDEX_NOTE = (
|
||||
"Embedding model changed; existing indexed documents were embedded with the previous model and "
|
||||
"must be re-indexed. If the embedding dimensionality changed, re-ingest before searching."
|
||||
)
|
||||
|
||||
|
||||
def _strip_provider_prefix(model_name: str) -> str:
|
||||
"""Drop a leading ``provider:`` from an env model string ("anthropic:x" -> "x").
|
||||
|
||||
Only used when falling back to the env-configured name under an explicit
|
||||
pushed provider; a bare pushed name (which may itself contain ``:`` such as
|
||||
"llama3:8b") is used verbatim and never passed through here.
|
||||
"""
|
||||
_, sep, rest = model_name.partition(":")
|
||||
return rest if sep else model_name
|
||||
|
||||
|
||||
def _compose_embedding_model(provider: str, model: str) -> str:
|
||||
"""Compose the engine's ``provider:model`` embedding string from pushed parts."""
|
||||
provider = provider.strip()
|
||||
return f"{provider}:{model}" if provider else model
|
||||
|
||||
|
||||
def _split_embedding_ref(ref: str) -> tuple[str, str]:
|
||||
"""Split an env embedding string ("voyageai:voyage-4") into (provider, model)."""
|
||||
provider, sep, model = ref.partition(":")
|
||||
return (provider, model) if sep else ("", ref)
|
||||
|
||||
|
||||
def _keep(pushed: int | None, current: int) -> int:
|
||||
"""Return the pushed value, or the current one when the push omitted it."""
|
||||
return pushed if pushed is not None else current
|
||||
|
||||
|
||||
def _is_loopback_client(request: Request) -> bool:
|
||||
"""True when the request originates from the local host (127.0.0.0/8, ::1)."""
|
||||
client = request.client
|
||||
if client is None:
|
||||
return False
|
||||
try:
|
||||
return ipaddress.ip_address(client.host).is_loopback
|
||||
except ValueError:
|
||||
return client.host == "localhost"
|
||||
|
||||
|
||||
def resolve_and_apply(
|
||||
current: AppSettings,
|
||||
request: ConfigPushRequest,
|
||||
) -> tuple[AppSettings, Model, Model, EmbeddingService | None, list[str]]:
|
||||
"""Resolve a pushed config against the running settings.
|
||||
|
||||
Builds and validates the smart/fast models, resolves the scalar overrides,
|
||||
and builds a new embedder when the embedding config changed. Empty/None pushed
|
||||
fields keep the current value. Returns the effective settings, the two built
|
||||
models, an optional new embedder (None when the embedding config is unchanged),
|
||||
and human-readable notes.
|
||||
|
||||
Raises one of :data:`CONFIG_APPLY_ERRORS` if a chosen model/embedder fails to
|
||||
build or validate; callers decide whether that becomes a 400 (HTTP route) or an
|
||||
env fallback (boot). It never swaps any live state - the caller owns that.
|
||||
"""
|
||||
models = request.models
|
||||
rag = request.rag
|
||||
limits = request.limits
|
||||
notes: list[str] = []
|
||||
|
||||
provider = models.provider.strip()
|
||||
api_key = models.api_key
|
||||
base_url = models.base_url
|
||||
use_explicit_provider = bool(provider or api_key or base_url)
|
||||
|
||||
if use_explicit_provider:
|
||||
smart_name = models.smart_model or _strip_provider_prefix(current.smart_model_name)
|
||||
fast_name = models.fast_model or _strip_provider_prefix(current.fast_model_name)
|
||||
else:
|
||||
# No provider/credentials pushed: keep the fully env-driven model strings.
|
||||
smart_name = models.smart_model or current.smart_model_name
|
||||
fast_name = models.fast_model or current.fast_model_name
|
||||
|
||||
def _build(bare: str) -> Model:
|
||||
if use_explicit_provider:
|
||||
return _build_model(bare, provider=provider or None, api_key=api_key or None, base_url=base_url or None)
|
||||
return _build_model(bare)
|
||||
|
||||
smart_model = _build(smart_name)
|
||||
fast_model = _build(fast_name)
|
||||
validate_structured_output_support(smart_model, smart_name)
|
||||
validate_structured_output_support(fast_model, fast_name)
|
||||
|
||||
# Scalars: None / empty keep the current value.
|
||||
smart_max_tokens = _keep(models.smart_max_tokens, current.smart_model_max_tokens)
|
||||
fast_max_tokens = _keep(models.fast_max_tokens, current.fast_model_max_tokens)
|
||||
top_k = _keep(rag.top_k, current.rag_default_top_k)
|
||||
max_searches = _keep(rag.max_searches, current.rag_max_searches)
|
||||
max_pages = _keep(limits.max_pages, current.max_pages)
|
||||
max_characters = _keep(limits.max_characters, current.max_characters)
|
||||
model_max_concurrency = _keep(limits.model_max_concurrency, current.model_max_concurrency)
|
||||
|
||||
# Embedding: any non-empty embedding field triggers a rebuild; empty fields fall
|
||||
# back to the running provider/model/creds so a partial push never clobbers env.
|
||||
embedding_changed = bool(
|
||||
rag.embedding_provider.strip() or rag.embedding_model.strip() or rag.embedding_api_key or rag.embedding_base_url
|
||||
)
|
||||
rag_embedding_model = current.rag_embedding_model
|
||||
new_embedder: EmbeddingService | None = None
|
||||
if embedding_changed:
|
||||
current_provider, current_model = _split_embedding_ref(current.rag_embedding_model)
|
||||
embed_provider = rag.embedding_provider.strip() or current_provider
|
||||
embed_model = rag.embedding_model.strip() or current_model
|
||||
rag_embedding_model = _compose_embedding_model(embed_provider, embed_model)
|
||||
new_embedder = EmbeddingService(
|
||||
model_name=embed_model,
|
||||
chunk_size=current.rag_chunk_size,
|
||||
chunk_overlap=current.rag_chunk_overlap,
|
||||
provider=embed_provider or None,
|
||||
api_key=rag.embedding_api_key or None,
|
||||
base_url=rag.embedding_base_url or None,
|
||||
)
|
||||
notes.append(_REINDEX_NOTE)
|
||||
|
||||
effective = current.model_copy(
|
||||
update={
|
||||
"chat_provider": provider,
|
||||
"smart_model_name": smart_name,
|
||||
"fast_model_name": fast_name,
|
||||
"smart_model_max_tokens": smart_max_tokens,
|
||||
"fast_model_max_tokens": fast_max_tokens,
|
||||
"rag_embedding_model": rag_embedding_model,
|
||||
"rag_default_top_k": top_k,
|
||||
"rag_max_searches": max_searches,
|
||||
"max_pages": max_pages,
|
||||
"max_characters": max_characters,
|
||||
"model_max_concurrency": model_max_concurrency,
|
||||
}
|
||||
)
|
||||
return effective, smart_model, fast_model, new_embedder, notes
|
||||
|
||||
|
||||
@router.post("", response_model=ConfigApplyResponse)
|
||||
async def apply_config(request: ConfigPushRequest, http_request: Request) -> ConfigApplyResponse:
|
||||
"""Apply admin-pushed AI settings by rebuilding the runtime + agents in place.
|
||||
|
||||
Gated by the X-Engine-Auth shared secret (global middleware) plus the
|
||||
``allow_config_push`` flag. Empty credential/model fields keep the engine's
|
||||
env-configured values. Returns 403 when config push is disabled, 400 (without
|
||||
swapping state) when a chosen model fails to build/validate. On success the
|
||||
config is also persisted (encrypted) so it survives an engine restart.
|
||||
"""
|
||||
app = http_request.app
|
||||
current: AppSettings = app.state.settings
|
||||
if not current.allow_config_push:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Config push is disabled on this deployment (STIRLING_ALLOW_CONFIG_PUSH is false).",
|
||||
)
|
||||
# Secure-by-default for this sensitive endpoint. When a shared secret is set the
|
||||
# global middleware has already authenticated the caller (only the processor has the
|
||||
# secret). When NO secret is set, only trust a loopback caller - a remote party must
|
||||
# never be able to push a config unauthenticated, since a pushed base_url/model could
|
||||
# repoint the engine to exfiltrate document content.
|
||||
if not current.engine_shared_secret and not _is_loopback_client(http_request):
|
||||
client_host = http_request.client.host if http_request.client else "unknown"
|
||||
logger.warning("Rejected config push from non-local caller %s with no shared secret set", client_host)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=(
|
||||
"Config push from a non-local caller requires STIRLING_ENGINE_SHARED_SECRET"
|
||||
" to be set on both the engine and the processor."
|
||||
),
|
||||
)
|
||||
|
||||
runtime: AppRuntime = app.state.runtime
|
||||
try:
|
||||
effective, smart_model, fast_model, new_embedder, notes = resolve_and_apply(current, request)
|
||||
except CONFIG_APPLY_ERRORS as exc:
|
||||
# Reject without touching the running config.
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
|
||||
|
||||
# Rebuild runtime + every agent, reusing the existing document store, then
|
||||
# swap the whole bundle onto app.state so in-flight lookups see one config.
|
||||
new_state = build_app_state(
|
||||
effective,
|
||||
documents=runtime.documents,
|
||||
fast_model=fast_model,
|
||||
smart_model=smart_model,
|
||||
)
|
||||
app.state.settings = effective
|
||||
apply_app_state(app.state, new_state)
|
||||
# Retune retrieval breadth on the reused store without rebuilding it.
|
||||
runtime.documents.default_top_k = effective.rag_default_top_k
|
||||
if new_embedder is not None:
|
||||
# Swap the embedder onto the reused DocumentService so we never tear down
|
||||
# the live vector store / connection pool.
|
||||
runtime.documents.embedder = new_embedder
|
||||
|
||||
# Persist the applied config (encrypted) so it is restored on the next boot.
|
||||
try:
|
||||
save_config(request)
|
||||
except OSError:
|
||||
logger.warning("Applied AI config but failed to persist the encrypted cache", exc_info=True)
|
||||
notes.append("Config applied but could not be persisted; it will not survive an engine restart.")
|
||||
|
||||
logger.info(
|
||||
"Applied pushed AI config: provider=%s smart_model=%s fast_model=%s top_k=%s",
|
||||
request.models.provider.strip() or "<env>",
|
||||
effective.smart_model_name,
|
||||
effective.fast_model_name,
|
||||
effective.rag_default_top_k,
|
||||
)
|
||||
|
||||
return ConfigApplyResponse(
|
||||
status="applied",
|
||||
provider=request.models.provider.strip(),
|
||||
smart_model=effective.smart_model_name,
|
||||
fast_model=effective.fast_model_name,
|
||||
smart_max_tokens=effective.smart_model_max_tokens,
|
||||
fast_max_tokens=effective.fast_model_max_tokens,
|
||||
rag_embedding_model=effective.rag_embedding_model,
|
||||
rag_top_k=effective.rag_default_top_k,
|
||||
rag_max_searches=effective.rag_max_searches,
|
||||
max_pages=effective.max_pages,
|
||||
max_characters=effective.max_characters,
|
||||
model_max_concurrency=effective.model_max_concurrency,
|
||||
notes=notes,
|
||||
)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Persistent, encrypted cache of the last-applied config-push.
|
||||
|
||||
The engine otherwise holds pushed config in RAM only, so a restart reverts to the
|
||||
env values until the processor pushes again. We persist the last-applied
|
||||
:class:`ConfigPushRequest` to ``<engine data dir>/ai_config_cache.enc`` (Fernet
|
||||
encrypted) and reload it on boot so the effective config survives restarts.
|
||||
|
||||
Key derivation: when ``STIRLING_ENGINE_SHARED_SECRET`` is set, the Fernet key is
|
||||
HKDF-SHA256 over that secret (constant salt/info) so no key material touches disk.
|
||||
Otherwise a random Fernet key is generated once and stored in a sibling
|
||||
``ai_config_cache.key`` (0600, best-effort) with a one-time warning.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
from stirling.config.settings import ENGINE_ROOT, load_settings
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CACHE_FILENAME = "ai_config_cache.enc"
|
||||
_KEY_FILENAME = "ai_config_cache.key"
|
||||
# Constant salt/info so the same shared secret always derives the same Fernet key.
|
||||
_HKDF_SALT = b"stirling-ai-config-cache/v1/salt"
|
||||
_HKDF_INFO = b"stirling-ai-config-cache/v1/fernet-key"
|
||||
|
||||
_keyfile_warned = False
|
||||
|
||||
|
||||
def _default_data_dir() -> Path:
|
||||
"""The engine data dir (where the sqlite store lives by default)."""
|
||||
return ENGINE_ROOT / "data"
|
||||
|
||||
|
||||
def _shared_secret() -> str:
|
||||
return load_settings().engine_shared_secret
|
||||
|
||||
|
||||
def _derive_key_from_secret(secret: str) -> bytes:
|
||||
hkdf = HKDF(algorithm=hashes.SHA256(), length=32, salt=_HKDF_SALT, info=_HKDF_INFO)
|
||||
return base64.urlsafe_b64encode(hkdf.derive(secret.encode("utf-8")))
|
||||
|
||||
|
||||
def _chmod_600(path: Path) -> None:
|
||||
# Best-effort owner-only perms; silently ignored where unsupported (e.g. Windows).
|
||||
try:
|
||||
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _load_or_create_keyfile(data_dir: Path) -> bytes:
|
||||
global _keyfile_warned
|
||||
key_path = data_dir / _KEY_FILENAME
|
||||
if key_path.exists():
|
||||
return key_path.read_bytes().strip()
|
||||
key = Fernet.generate_key()
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
key_path.write_bytes(key)
|
||||
_chmod_600(key_path)
|
||||
if not _keyfile_warned:
|
||||
logger.warning(
|
||||
"STIRLING_ENGINE_SHARED_SECRET is not set; encrypting the AI config cache with a local"
|
||||
" keyfile at %s (0600, best-effort). This is modest protection only - set a shared secret"
|
||||
" for HKDF key derivation in any deployment where the cache must be strongly protected.",
|
||||
key_path,
|
||||
)
|
||||
_keyfile_warned = True
|
||||
return key
|
||||
|
||||
|
||||
def _fernet(data_dir: Path) -> Fernet:
|
||||
secret = _shared_secret()
|
||||
if secret:
|
||||
return Fernet(_derive_key_from_secret(secret))
|
||||
return Fernet(_load_or_create_keyfile(data_dir))
|
||||
|
||||
|
||||
def save_config(request: ConfigPushRequest, *, data_dir: Path | None = None) -> None:
|
||||
"""Encrypt and persist the last-applied pushed config, overwriting any prior file."""
|
||||
data_dir = data_dir or _default_data_dir()
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
payload = request.model_dump_json(by_alias=True).encode("utf-8")
|
||||
token = _fernet(data_dir).encrypt(payload)
|
||||
(data_dir / _CACHE_FILENAME).write_bytes(token)
|
||||
|
||||
|
||||
def load_config(*, data_dir: Path | None = None) -> ConfigPushRequest | None:
|
||||
"""Load + decrypt the persisted pushed config.
|
||||
|
||||
Returns None (never raises) when the cache is absent, corrupt, or was written
|
||||
under a different key, so a bad cache can never crash boot.
|
||||
"""
|
||||
data_dir = data_dir or _default_data_dir()
|
||||
cache_path = data_dir / _CACHE_FILENAME
|
||||
if not cache_path.exists():
|
||||
return None
|
||||
try:
|
||||
token = cache_path.read_bytes()
|
||||
payload = _fernet(data_dir).decrypt(token)
|
||||
return ConfigPushRequest.model_validate_json(payload)
|
||||
except (InvalidToken, ValueError, OSError) as exc:
|
||||
logger.warning("Ignoring unreadable AI config cache at %s: %s", cache_path, exc)
|
||||
return None
|
||||
@@ -25,6 +25,12 @@ class AppSettings(BaseSettings):
|
||||
|
||||
smart_model_name: str = Field(validation_alias="STIRLING_SMART_MODEL")
|
||||
fast_model_name: str = Field(validation_alias="STIRLING_FAST_MODEL")
|
||||
# Provider backing the active chat models. Empty for env/native providers; set to
|
||||
# 'ollama'/'custom' by a config push. Agents that combine structured output with
|
||||
# tools read this to pick a tool-compatible output strategy, because OpenAI-compatible
|
||||
# local models (Ollama) block tool calls when a native json-schema response format is
|
||||
# set, so their structured result must be delivered via a tool call instead.
|
||||
chat_provider: str = Field(default="")
|
||||
smart_model_max_tokens: int = Field(validation_alias="STIRLING_SMART_MODEL_MAX_TOKENS")
|
||||
fast_model_max_tokens: int = Field(validation_alias="STIRLING_FAST_MODEL_MAX_TOKENS")
|
||||
# Process-wide ceiling on concurrent model API calls, shared by both model
|
||||
@@ -123,6 +129,11 @@ class AppSettings(BaseSettings):
|
||||
engine_shared_secret: str = Field(default="", validation_alias="STIRLING_ENGINE_SHARED_SECRET")
|
||||
engine_require_auth: bool = Field(default=False, validation_alias="STIRLING_ENGINE_REQUIRE_AUTH")
|
||||
|
||||
# When true, the Java processor may push admin-configured AI settings (model,
|
||||
# credentials, limits) to POST /api/v1/config at startup. Turn this off in
|
||||
# environment-driven deployments so the environment is the single source of truth.
|
||||
allow_config_push: bool = Field(default=True, validation_alias="STIRLING_ALLOW_CONFIG_PUSH")
|
||||
|
||||
|
||||
def _configure_logging(level_name: str, log_file: str, http_debug: bool) -> None:
|
||||
"""Configure the ``stirling`` logger hierarchy."""
|
||||
|
||||
@@ -29,6 +29,13 @@ from .common import (
|
||||
format_conversation_history,
|
||||
format_file_names,
|
||||
)
|
||||
from .config import (
|
||||
ConfigApplyResponse,
|
||||
ConfigLimitsSection,
|
||||
ConfigModelsSection,
|
||||
ConfigPushRequest,
|
||||
ConfigRagSection,
|
||||
)
|
||||
from .contradiction import (
|
||||
Claim,
|
||||
Contradiction,
|
||||
@@ -139,6 +146,11 @@ __all__ = [
|
||||
"Claim",
|
||||
"CommentSpec",
|
||||
"CompletedExecutionAction",
|
||||
"ConfigApplyResponse",
|
||||
"ConfigLimitsSection",
|
||||
"ConfigModelsSection",
|
||||
"ConfigPushRequest",
|
||||
"ConfigRagSection",
|
||||
"Contradiction",
|
||||
"ContradictionReport",
|
||||
"ContradictionSeverity",
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import ConfigDict, Field
|
||||
|
||||
from stirling.models import ApiModel
|
||||
|
||||
# Tolerate unknown fields so a newer processor pushing a field this engine version
|
||||
# doesn't know is ignored rather than rejecting the whole push. Overrides only the
|
||||
# ``extra`` policy from ApiModel; the camelCase alias generator is inherited.
|
||||
_TOLERANT = ConfigDict(extra="ignore")
|
||||
|
||||
|
||||
class ConfigModelsSection(ApiModel):
|
||||
"""Model provider + credentials pushed by the Java processor.
|
||||
|
||||
Field names on the wire are camelCase (``smartModel`` etc.) via the
|
||||
:class:`ApiModel` alias generator. Empty ``provider``/``apiKey``/``baseUrl``
|
||||
or empty model names mean "keep the engine's env-configured value".
|
||||
"""
|
||||
|
||||
model_config = _TOLERANT
|
||||
|
||||
provider: str = ""
|
||||
smart_model: str = ""
|
||||
fast_model: str = ""
|
||||
smart_max_tokens: int | None = None
|
||||
fast_max_tokens: int | None = None
|
||||
api_key: str = ""
|
||||
base_url: str = ""
|
||||
|
||||
|
||||
class ConfigRagSection(ApiModel):
|
||||
model_config = _TOLERANT
|
||||
|
||||
embedding_provider: str = ""
|
||||
embedding_model: str = ""
|
||||
embedding_api_key: str = ""
|
||||
# OpenAI-compatible endpoint URL for ollama/custom embedding providers.
|
||||
# Empty keeps the engine's env value, same convention as the other fields.
|
||||
embedding_base_url: str = ""
|
||||
top_k: int | None = None
|
||||
max_searches: int | None = None
|
||||
|
||||
|
||||
class ConfigLimitsSection(ApiModel):
|
||||
model_config = _TOLERANT
|
||||
|
||||
max_pages: int | None = None
|
||||
max_characters: int | None = None
|
||||
model_max_concurrency: int | None = None
|
||||
|
||||
|
||||
class ConfigPushRequest(ApiModel):
|
||||
"""Admin-configured AI settings pushed at processor startup."""
|
||||
|
||||
model_config = _TOLERANT
|
||||
|
||||
models: ConfigModelsSection = Field(default_factory=ConfigModelsSection)
|
||||
rag: ConfigRagSection = Field(default_factory=ConfigRagSection)
|
||||
limits: ConfigLimitsSection = Field(default_factory=ConfigLimitsSection)
|
||||
|
||||
|
||||
class ConfigApplyResponse(ApiModel):
|
||||
"""Summary of the effective config after a push. Never echoes credentials."""
|
||||
|
||||
status: str
|
||||
provider: str
|
||||
smart_model: str
|
||||
fast_model: str
|
||||
smart_max_tokens: int
|
||||
fast_max_tokens: int
|
||||
rag_embedding_model: str
|
||||
rag_top_k: int
|
||||
rag_max_searches: int
|
||||
max_pages: int
|
||||
max_characters: int
|
||||
model_max_concurrency: int
|
||||
notes: list[str] = Field(default_factory=list)
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic_ai import Embedder
|
||||
from pydantic_ai.embeddings.openai import OpenAIEmbeddingModel
|
||||
from pydantic_ai.providers.openai import OpenAIProvider
|
||||
|
||||
from stirling.documents.chunker import chunk_text
|
||||
from stirling.documents.store import Document
|
||||
@@ -12,6 +14,37 @@ from stirling.documents.store import Document
|
||||
DEFAULT_EMBED_BATCH_SIZE = 256
|
||||
|
||||
|
||||
def _build_embedder(
|
||||
model_name: str,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> Embedder:
|
||||
"""Construct an :class:`Embedder` for ``model_name``.
|
||||
|
||||
With no explicit ``provider``/``api_key``/``base_url`` this keeps the original
|
||||
behaviour: ``model_name`` is the ``provider:model`` string form (e.g.
|
||||
"voyageai:voyage-4") and credentials come from the provider's native env var.
|
||||
|
||||
With an explicit provider (config-push path) ``model_name`` is the bare model
|
||||
without a prefix. ``voyageai``/``openai`` compose the same string form; the
|
||||
OpenAI-compatible ``ollama``/``custom`` build an OpenAI embedding model against
|
||||
``base_url`` (Ollama ignores the key but the SDK still needs a non-empty one).
|
||||
"""
|
||||
if not provider and not api_key and not base_url:
|
||||
return Embedder(model_name)
|
||||
|
||||
provider_name = (provider or "").lower()
|
||||
key = api_key or None
|
||||
if provider_name in ("voyageai", "openai"):
|
||||
return Embedder(f"{provider_name}:{model_name}")
|
||||
if provider_name in ("ollama", "custom"):
|
||||
openai_provider = OpenAIProvider(base_url=base_url or None, api_key=key or "ollama")
|
||||
return Embedder(OpenAIEmbeddingModel(model_name, provider=openai_provider))
|
||||
raise ValueError(f"Unsupported embedding provider {provider!r}.")
|
||||
|
||||
|
||||
class EmbeddingService:
|
||||
"""Wraps Pydantic AI's Embedder to provide document chunking and embedding."""
|
||||
|
||||
@@ -21,8 +54,12 @@ class EmbeddingService:
|
||||
chunk_size: int = 512,
|
||||
chunk_overlap: int = 64,
|
||||
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> None:
|
||||
self._embedder = Embedder(model_name)
|
||||
self._embedder = _build_embedder(model_name, provider=provider, api_key=api_key, base_url=base_url)
|
||||
self._chunk_size = chunk_size
|
||||
self._chunk_overlap = chunk_overlap
|
||||
self._embed_batch_size = embed_batch_size
|
||||
|
||||
@@ -43,6 +43,25 @@ class DocumentService:
|
||||
self._store = store
|
||||
self._default_top_k = default_top_k
|
||||
|
||||
@property
|
||||
def default_top_k(self) -> int:
|
||||
return self._default_top_k
|
||||
|
||||
@default_top_k.setter
|
||||
def default_top_k(self, value: int) -> None:
|
||||
# Lets a config-push retune retrieval breadth without rebuilding the store.
|
||||
self._default_top_k = value
|
||||
|
||||
@property
|
||||
def embedder(self) -> EmbeddingService:
|
||||
return self._embedder
|
||||
|
||||
@embedder.setter
|
||||
def embedder(self, value: EmbeddingService) -> None:
|
||||
# Lets a config-push swap the embedding model while keeping the live store
|
||||
# (and its connection pool). Existing vectors need re-indexing afterwards.
|
||||
self._embedder = value
|
||||
|
||||
async def ingest(
|
||||
self,
|
||||
collection: FileId,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass
|
||||
@@ -12,8 +14,10 @@ from pydantic_ai import RunContext
|
||||
from pydantic_ai.messages import ModelMessage, ModelResponse
|
||||
from pydantic_ai.models import Model, ModelRequestParameters, StreamedResponse, infer_model
|
||||
from pydantic_ai.models.anthropic import AnthropicModel
|
||||
from pydantic_ai.models.openai import OpenAIChatModel
|
||||
from pydantic_ai.models.wrapper import WrapperModel
|
||||
from pydantic_ai.providers.anthropic import AnthropicProvider
|
||||
from pydantic_ai.providers.openai import OpenAIProvider
|
||||
from pydantic_ai.settings import ModelSettings
|
||||
|
||||
from stirling.config import ENGINE_ROOT, AppSettings, DocumentsBackend
|
||||
@@ -49,6 +53,79 @@ def _build_anthropic_http_client() -> httpx.AsyncClient:
|
||||
)
|
||||
|
||||
|
||||
# Placeholder used when no Anthropic key is configured; lets the engine boot so a
|
||||
# deployment that only uses another provider (e.g. Ollama via the admin UI / config
|
||||
# push) isn't blocked. Anthropic calls then fail with a clear 401 instead.
|
||||
_UNCONFIGURED_ANTHROPIC_KEY = "unconfigured"
|
||||
_warned_missing_anthropic_key = False
|
||||
|
||||
|
||||
def _anthropic_provider(explicit_key: str | None = None) -> AnthropicProvider:
|
||||
"""Build the Anthropic provider, tolerating a missing key at startup.
|
||||
|
||||
pydantic-ai's ``AnthropicProvider`` raises at construction when no key is
|
||||
available, which would crash the whole engine at boot even for deployments
|
||||
that never call Anthropic (Ollama/OpenAI-configured, or awaiting a config
|
||||
push that supplies credentials). We fall back to a placeholder key and warn
|
||||
once so startup succeeds; the placeholder only surfaces as a clear
|
||||
provider-side auth error if an Anthropic call is actually made.
|
||||
"""
|
||||
http_client = _build_anthropic_http_client()
|
||||
key = explicit_key or os.environ.get("ANTHROPIC_API_KEY")
|
||||
if key:
|
||||
return AnthropicProvider(api_key=key, http_client=http_client)
|
||||
global _warned_missing_anthropic_key
|
||||
if not _warned_missing_anthropic_key:
|
||||
_warned_missing_anthropic_key = True
|
||||
logger.warning(
|
||||
"ANTHROPIC_API_KEY is not set - the engine will start, but Anthropic model "
|
||||
"calls will fail until a key is provided or a different provider is configured "
|
||||
"(admin AI settings / config push)."
|
||||
)
|
||||
return AnthropicProvider(api_key=_UNCONFIGURED_ANTHROPIC_KEY, http_client=http_client)
|
||||
|
||||
|
||||
class _NullContentCoercingTransport(httpx.AsyncHTTPTransport):
|
||||
"""Coerce assistant ``content: null`` to ``""`` in outgoing OpenAI chat requests.
|
||||
|
||||
OpenAI's schema uses ``content: null`` for assistant messages that carry only
|
||||
tool calls, but Ollama's OpenAI-compatible endpoint rejects it ("invalid message
|
||||
content type: <nil>"), which intermittently breaks multi-turn tool conversations
|
||||
(RAG search + tool-delivered output). Rewriting null -> "" makes them acceptable
|
||||
without changing semantics. Scoped to the ollama/custom clients only.
|
||||
"""
|
||||
|
||||
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
||||
if request.headers.get("content-type", "").startswith("application/json") and request.content:
|
||||
try:
|
||||
body = json.loads(request.content)
|
||||
except ValueError:
|
||||
return await super().handle_async_request(request)
|
||||
messages = body.get("messages")
|
||||
if isinstance(messages, list):
|
||||
changed = False
|
||||
for message in messages:
|
||||
if isinstance(message, dict) and message.get("content", "") is None:
|
||||
message["content"] = ""
|
||||
changed = True
|
||||
if changed:
|
||||
new_body = json.dumps(body).encode("utf-8")
|
||||
headers = [(k, v) for k, v in request.headers.raw if k.lower() != b"content-length"]
|
||||
request = httpx.Request(
|
||||
method=request.method,
|
||||
url=request.url,
|
||||
headers=headers,
|
||||
content=new_body,
|
||||
extensions=request.extensions,
|
||||
)
|
||||
return await super().handle_async_request(request)
|
||||
|
||||
|
||||
def _openai_compat_http_client() -> httpx.AsyncClient:
|
||||
"""httpx client for Ollama/custom OpenAI-compatible endpoints (null-content fix)."""
|
||||
return httpx.AsyncClient(transport=_NullContentCoercingTransport())
|
||||
|
||||
|
||||
class ConcurrencyLimitedModel(WrapperModel):
|
||||
"""Caps in-flight model API calls with a semaphore shared across the process."""
|
||||
|
||||
@@ -131,45 +208,97 @@ def _build_document_store(settings: AppSettings) -> DocumentStore:
|
||||
assert_never(settings.documents_backend)
|
||||
|
||||
|
||||
def _build_documents(settings: AppSettings) -> DocumentService:
|
||||
"""Build the document service used by per-request RAG capabilities."""
|
||||
logger.info("Documents: embedding_model=%s", settings.rag_embedding_model)
|
||||
embedder = EmbeddingService(
|
||||
model_name=settings.rag_embedding_model,
|
||||
chunk_size=settings.rag_chunk_size,
|
||||
chunk_overlap=settings.rag_chunk_overlap,
|
||||
)
|
||||
def _build_documents(settings: AppSettings, embedder: EmbeddingService | None = None) -> DocumentService:
|
||||
"""Build the document service used by per-request RAG capabilities.
|
||||
|
||||
``embedder`` lets a cache-restore boot inject an already-built embedder (e.g.
|
||||
an OpenAI-compatible ollama/custom one whose base_url the plain
|
||||
``settings.rag_embedding_model`` string can't encode); None builds from settings.
|
||||
"""
|
||||
if embedder is None:
|
||||
logger.info("Documents: embedding_model=%s", settings.rag_embedding_model)
|
||||
embedder = EmbeddingService(
|
||||
model_name=settings.rag_embedding_model,
|
||||
chunk_size=settings.rag_chunk_size,
|
||||
chunk_overlap=settings.rag_chunk_overlap,
|
||||
)
|
||||
store = _build_document_store(settings)
|
||||
return DocumentService(embedder=embedder, store=store, default_top_k=settings.rag_default_top_k)
|
||||
|
||||
|
||||
def build_runtime(settings: AppSettings) -> AppRuntime:
|
||||
fast_model = _build_model(settings.fast_model_name)
|
||||
smart_model = _build_model(settings.smart_model_name)
|
||||
validate_structured_output_support(fast_model, settings.fast_model_name)
|
||||
validate_structured_output_support(smart_model, settings.smart_model_name)
|
||||
def build_runtime(
|
||||
settings: AppSettings,
|
||||
*,
|
||||
documents: DocumentService | None = None,
|
||||
fast_model: Model | None = None,
|
||||
smart_model: Model | None = None,
|
||||
embedder: EmbeddingService | None = None,
|
||||
) -> AppRuntime:
|
||||
"""Assemble the shared runtime.
|
||||
|
||||
``documents``/``fast_model``/``smart_model`` let a config-push rebuild reuse
|
||||
the live vector-store connection pool and inject already-built (and already
|
||||
validated) models instead of reconstructing them from the model-name strings.
|
||||
``embedder`` injects a pre-built embedder when building a fresh document store
|
||||
(cache-restore boot); it is ignored when ``documents`` is supplied. All None
|
||||
(the lifespan path) preserves the original startup behaviour.
|
||||
"""
|
||||
fast = fast_model if fast_model is not None else _build_model(settings.fast_model_name)
|
||||
smart = smart_model if smart_model is not None else _build_model(settings.smart_model_name)
|
||||
validate_structured_output_support(fast, settings.fast_model_name)
|
||||
validate_structured_output_support(smart, settings.smart_model_name)
|
||||
|
||||
# One semaphore across both tiers: the cap protects the provider account
|
||||
# and process resources, which the tiers share.
|
||||
model_semaphore = asyncio.Semaphore(settings.model_max_concurrency)
|
||||
return AppRuntime(
|
||||
settings=settings,
|
||||
fast_model=ConcurrencyLimitedModel(fast_model, model_semaphore),
|
||||
smart_model=ConcurrencyLimitedModel(smart_model, model_semaphore),
|
||||
documents=_build_documents(settings),
|
||||
fast_model=ConcurrencyLimitedModel(fast, model_semaphore),
|
||||
smart_model=ConcurrencyLimitedModel(smart, model_semaphore),
|
||||
documents=documents if documents is not None else _build_documents(settings, embedder),
|
||||
)
|
||||
|
||||
|
||||
def _build_model(model_name: str) -> Model:
|
||||
"""Construct a model, injecting our keepalive-free httpx client for
|
||||
Anthropic models so workers don't pick up stale pooled connections.
|
||||
def _build_model(
|
||||
model_name: str,
|
||||
*,
|
||||
provider: str | None = None,
|
||||
api_key: str | None = None,
|
||||
base_url: str | None = None,
|
||||
) -> Model:
|
||||
"""Construct a model for ``model_name``.
|
||||
|
||||
Other providers fall back to ``infer_model`` defaults; the stale-pool
|
||||
issue is specific to the Cloudflare-fronted Anthropic API in our
|
||||
observations and the fix doesn't necessarily apply elsewhere.
|
||||
With no explicit ``provider``/``api_key``/``base_url`` this keeps the original
|
||||
env-driven behaviour: Anthropic-prefixed names get our keepalive-free httpx
|
||||
client (so workers don't pick up stale pooled connections) and everything
|
||||
else falls back to ``infer_model``.
|
||||
|
||||
When the caller passes an explicit provider (config-push path), ``model_name``
|
||||
is the bare model without a ``provider:`` prefix and credentials come from the
|
||||
call. An empty ``api_key``/``base_url`` is treated as unset so the provider
|
||||
reads its native environment variable (e.g. ANTHROPIC_API_KEY / OPENAI_API_KEY).
|
||||
"""
|
||||
if model_name.startswith("anthropic:"):
|
||||
bare_name = model_name.removeprefix("anthropic:")
|
||||
provider = AnthropicProvider(http_client=_build_anthropic_http_client())
|
||||
return AnthropicModel(bare_name, provider=provider)
|
||||
return infer_model(model_name)
|
||||
if not provider and not api_key and not base_url:
|
||||
if model_name.startswith("anthropic:"):
|
||||
bare_name = model_name.removeprefix("anthropic:")
|
||||
return AnthropicModel(bare_name, provider=_anthropic_provider())
|
||||
return infer_model(model_name)
|
||||
|
||||
provider_name = (provider or "").lower()
|
||||
key = api_key or None
|
||||
if provider_name == "anthropic":
|
||||
return AnthropicModel(model_name, provider=_anthropic_provider(key))
|
||||
if provider_name == "openai":
|
||||
openai_provider = OpenAIProvider(api_key=key) if key else OpenAIProvider()
|
||||
return OpenAIChatModel(model_name, provider=openai_provider)
|
||||
if provider_name in ("ollama", "custom"):
|
||||
# OpenAI-compatible endpoint. Ollama ignores the key but the SDK still
|
||||
# requires a non-empty one, so default to a harmless placeholder. The custom
|
||||
# http client coerces null assistant content so multi-turn tool calls work.
|
||||
openai_provider = OpenAIProvider(
|
||||
base_url=base_url or None,
|
||||
api_key=key or "ollama",
|
||||
http_client=_openai_compat_http_client(),
|
||||
)
|
||||
return OpenAIChatModel(model_name, provider=openai_provider)
|
||||
raise ValueError(f"Unsupported model provider {provider!r}.")
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"models": {
|
||||
"provider": "ollama",
|
||||
"smartModel": "smart-model-x",
|
||||
"fastModel": "fast-model-x",
|
||||
"smartMaxTokens": 1111,
|
||||
"fastMaxTokens": 2222,
|
||||
"apiKey": "provider-key-abc",
|
||||
"baseUrl": "http://engine.example/v1"
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "custom",
|
||||
"embeddingModel": "embed-model-x",
|
||||
"embeddingApiKey": "embed-key-abc",
|
||||
"embeddingBaseUrl": "http://embed.example/v1",
|
||||
"topK": 33,
|
||||
"maxSearches": 7
|
||||
},
|
||||
"limits": {
|
||||
"maxPages": 111,
|
||||
"maxCharacters": 222222,
|
||||
"modelMaxConcurrency": 9
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Tests for the encrypted config cache (stirling.config.config_cache)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from stirling.config import config_cache
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
|
||||
def _sample() -> ConfigPushRequest:
|
||||
return ConfigPushRequest.model_validate(
|
||||
{
|
||||
"models": {
|
||||
"provider": "anthropic",
|
||||
"smartModel": "claude-haiku-4-5",
|
||||
"fastModel": "claude-haiku-4-5",
|
||||
"smartMaxTokens": 8192,
|
||||
"fastMaxTokens": 2048,
|
||||
"apiKey": "secret-key-value",
|
||||
"baseUrl": "",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "voyageai",
|
||||
"embeddingModel": "voyage-4",
|
||||
"embeddingApiKey": "embed-secret",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": 20,
|
||||
"maxSearches": 5,
|
||||
},
|
||||
"limits": {"maxPages": 200, "maxCharacters": 200000, "modelMaxConcurrency": 32},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_roundtrip_with_shared_secret(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "the-shared-secret")
|
||||
req = _sample()
|
||||
config_cache.save_config(req, data_dir=tmp_path)
|
||||
# HKDF-from-secret path: no keyfile is written.
|
||||
assert not (tmp_path / "ai_config_cache.key").exists()
|
||||
assert config_cache.load_config(data_dir=tmp_path) == req
|
||||
# Secrets are encrypted at rest.
|
||||
assert b"secret-key-value" not in (tmp_path / "ai_config_cache.enc").read_bytes()
|
||||
|
||||
|
||||
def test_roundtrip_with_keyfile_when_no_secret(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "")
|
||||
req = _sample()
|
||||
config_cache.save_config(req, data_dir=tmp_path)
|
||||
# No shared secret: a random keyfile is generated and reused for decrypt.
|
||||
assert (tmp_path / "ai_config_cache.key").exists()
|
||||
assert config_cache.load_config(data_dir=tmp_path) == req
|
||||
|
||||
|
||||
def test_load_missing_returns_none(tmp_path: Path) -> None:
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
|
||||
|
||||
def test_load_corrupt_returns_none(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "a-secret")
|
||||
(tmp_path / "ai_config_cache.enc").write_bytes(b"not-a-valid-fernet-token")
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
|
||||
|
||||
def test_wrong_key_returns_none(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "secret-a")
|
||||
config_cache.save_config(_sample(), data_dir=tmp_path)
|
||||
# A different secret derives a different key -> decrypt fails, returns None.
|
||||
monkeypatch.setattr(config_cache, "_shared_secret", lambda: "secret-b")
|
||||
assert config_cache.load_config(data_dir=tmp_path) is None
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Wire-contract test for the processor -> engine config push.
|
||||
|
||||
The Java processor (AiEngineConfigSync.buildConfigNode) serialises the admin AI settings as
|
||||
camelCase JSON and POSTs them to /api/v1/config. Because ConfigPushRequest uses extra="ignore"
|
||||
(so version skew never 422s), a field the engine can no longer map is silently dropped to its
|
||||
default instead of erroring. This test pins the exact camelCase contract: every field in the
|
||||
shared fixture must round-trip onto the model, so a rename on either side fails loudly.
|
||||
|
||||
The same fixture (tests/fixtures/processor_config_push.json) is the contract the Java
|
||||
AiEngineConfigSyncTest asserts its serialiser produces - keep the two in sync.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
FIXTURE = Path(__file__).parent / "fixtures" / "processor_config_push.json"
|
||||
|
||||
|
||||
def _load() -> dict:
|
||||
return json.loads(FIXTURE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_processor_contract_round_trips_every_field() -> None:
|
||||
payload = _load()
|
||||
req = ConfigPushRequest.model_validate(payload)
|
||||
|
||||
m = payload["models"]
|
||||
assert req.models.provider == m["provider"]
|
||||
assert req.models.smart_model == m["smartModel"]
|
||||
assert req.models.fast_model == m["fastModel"]
|
||||
assert req.models.smart_max_tokens == m["smartMaxTokens"]
|
||||
assert req.models.fast_max_tokens == m["fastMaxTokens"]
|
||||
assert req.models.api_key == m["apiKey"]
|
||||
assert req.models.base_url == m["baseUrl"]
|
||||
|
||||
r = payload["rag"]
|
||||
assert req.rag.embedding_provider == r["embeddingProvider"]
|
||||
assert req.rag.embedding_model == r["embeddingModel"]
|
||||
assert req.rag.embedding_api_key == r["embeddingApiKey"]
|
||||
assert req.rag.embedding_base_url == r["embeddingBaseUrl"]
|
||||
assert req.rag.top_k == r["topK"]
|
||||
assert req.rag.max_searches == r["maxSearches"]
|
||||
|
||||
limits = payload["limits"]
|
||||
assert req.limits.max_pages == limits["maxPages"]
|
||||
assert req.limits.max_characters == limits["maxCharacters"]
|
||||
assert req.limits.model_max_concurrency == limits["modelMaxConcurrency"]
|
||||
|
||||
|
||||
def test_processor_contract_has_no_unmapped_keys() -> None:
|
||||
"""Guard the fixture itself: every wire key must map to a model field (none silently
|
||||
absorbed by extra="ignore"). If the processor adds a field, extend the contract here."""
|
||||
payload = _load()
|
||||
expected = {
|
||||
"models": {
|
||||
"provider",
|
||||
"smartModel",
|
||||
"fastModel",
|
||||
"smartMaxTokens",
|
||||
"fastMaxTokens",
|
||||
"apiKey",
|
||||
"baseUrl",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider",
|
||||
"embeddingModel",
|
||||
"embeddingApiKey",
|
||||
"embeddingBaseUrl",
|
||||
"topK",
|
||||
"maxSearches",
|
||||
},
|
||||
"limits": {"maxPages", "maxCharacters", "modelMaxConcurrency"},
|
||||
}
|
||||
assert set(payload) == set(expected)
|
||||
for section, keys in expected.items():
|
||||
assert set(payload[section]) == keys
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Tests for the config-push endpoint (POST /api/v1/config).
|
||||
|
||||
These drive the real lifespan (via ``with TestClient(app)``) so ``app.state`` is
|
||||
populated, then exercise the gate + model-swap behaviour against the in-memory
|
||||
"test" runtime built by :func:`build_app_settings`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from conftest import build_app_settings
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from stirling.api import app
|
||||
from stirling.config import AppSettings, config_cache, load_settings
|
||||
from stirling.contracts import ConfigPushRequest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_config_cache(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
"""Point the encrypted config cache at a per-test tmp dir so persistence never
|
||||
touches the real engine/data dir or leaks between tests."""
|
||||
monkeypatch.setattr(config_cache, "_default_data_dir", lambda: tmp_path)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _client(
|
||||
settings_factory: Callable[[], AppSettings],
|
||||
*,
|
||||
client_addr: tuple[str, int] = ("127.0.0.1", 12345),
|
||||
) -> Iterator[TestClient]:
|
||||
"""Enter a TestClient whose lifespan builds app.state from ``settings_factory``.
|
||||
|
||||
Defaults to a loopback client address so the config endpoint's local-caller gate
|
||||
(which blocks remote unauthenticated pushes) allows the request through.
|
||||
"""
|
||||
previous = app.dependency_overrides.get(load_settings)
|
||||
app.dependency_overrides[load_settings] = settings_factory
|
||||
try:
|
||||
with TestClient(app, client=client_addr) as client:
|
||||
yield client
|
||||
finally:
|
||||
if previous is None:
|
||||
app.dependency_overrides.pop(load_settings, None)
|
||||
else:
|
||||
app.dependency_overrides[load_settings] = previous
|
||||
|
||||
|
||||
def _anthropic_push() -> dict[str, object]:
|
||||
return {
|
||||
"models": {
|
||||
"provider": "anthropic",
|
||||
"smartModel": "claude-haiku-4-5",
|
||||
"fastModel": "claude-haiku-4-5",
|
||||
"smartMaxTokens": 4096,
|
||||
"fastMaxTokens": 1024,
|
||||
"apiKey": "test-key-not-a-real-secret",
|
||||
"baseUrl": "",
|
||||
},
|
||||
"rag": {
|
||||
"embeddingProvider": "",
|
||||
"embeddingModel": "",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": 7,
|
||||
"maxSearches": 3,
|
||||
},
|
||||
"limits": {"maxPages": 50, "maxCharacters": 12345, "modelMaxConcurrency": 8},
|
||||
}
|
||||
|
||||
|
||||
def test_config_push_forbidden_when_disabled() -> None:
|
||||
def factory() -> AppSettings:
|
||||
return build_app_settings().model_copy(update={"allow_config_push": False})
|
||||
|
||||
with _client(factory) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_config_push_from_non_local_caller_without_secret_returns_403() -> None:
|
||||
"""Secure-by-default: with no shared secret, a remote caller cannot push a config."""
|
||||
with _client(build_app_settings, client_addr=("203.0.113.9", 4444)) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 403
|
||||
assert "STIRLING_ENGINE_SHARED_SECRET" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_config_push_applies_model_and_limits() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
# Wire summary is camelCase and never echoes the api key.
|
||||
assert body["smartModel"] == "claude-haiku-4-5"
|
||||
assert body["fastModel"] == "claude-haiku-4-5"
|
||||
assert body["smartMaxTokens"] == 4096
|
||||
assert body["ragTopK"] == 7
|
||||
assert body["maxPages"] == 50
|
||||
assert body["modelMaxConcurrency"] == 8
|
||||
assert "test-key-not-a-real-secret" not in response.text
|
||||
# State was swapped: the running settings now reflect the push.
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
assert app.state.runtime.documents.default_top_k == 7
|
||||
|
||||
|
||||
def test_config_push_unsupported_provider_returns_400_without_swap() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
before = app.state.runtime
|
||||
payload = _anthropic_push()
|
||||
payload["models"]["provider"] = "nonsense-provider" # type: ignore[index]
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 400
|
||||
# Running runtime is untouched when the push is rejected.
|
||||
assert app.state.runtime is before
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
|
||||
|
||||
def test_config_push_unsupported_model_returns_400() -> None:
|
||||
"""A model that fails structured-output validation is rejected with 400."""
|
||||
with _client(build_app_settings) as client:
|
||||
before = app.state.runtime
|
||||
with patch(
|
||||
"stirling.api.routes.config.validate_structured_output_support",
|
||||
side_effect=ValueError("Unsupported model foo. This model does not support structured outputs."),
|
||||
):
|
||||
response = client.post("/api/v1/config", json=_anthropic_push())
|
||||
assert response.status_code == 400
|
||||
assert "does not support structured outputs" in response.json()["detail"]
|
||||
assert app.state.runtime is before
|
||||
|
||||
|
||||
def test_config_push_ollama_embedding_rebuilds_embedder() -> None:
|
||||
"""A pushed ollama/custom embedding provider builds an OpenAI-compatible
|
||||
embedder and swaps it onto the reused DocumentService without tearing down
|
||||
the store; the response carries a re-index note."""
|
||||
with _client(build_app_settings) as client:
|
||||
store_before = app.state.runtime.documents
|
||||
embedder_before = app.state.runtime.documents.embedder
|
||||
payload = _anthropic_push()
|
||||
payload["rag"] = {
|
||||
"embeddingProvider": "ollama",
|
||||
"embeddingModel": "nomic-embed-text",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "http://localhost:11434/v1",
|
||||
"topK": 9,
|
||||
"maxSearches": 4,
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["ragEmbeddingModel"] == "ollama:nomic-embed-text"
|
||||
assert any("re-index" in note for note in body["notes"])
|
||||
docs = app.state.runtime.documents
|
||||
# Same store object reused (connection pool intact), embedder swapped.
|
||||
assert docs is store_before
|
||||
assert docs.embedder is not embedder_before
|
||||
assert docs.default_top_k == 9
|
||||
|
||||
|
||||
def test_config_push_unsupported_embedding_provider_returns_400() -> None:
|
||||
with _client(build_app_settings) as client:
|
||||
embedder_before = app.state.runtime.documents.embedder
|
||||
payload = _anthropic_push()
|
||||
payload["rag"] = {
|
||||
"embeddingProvider": "totally-bogus",
|
||||
"embeddingModel": "x",
|
||||
"embeddingApiKey": "",
|
||||
"embeddingBaseUrl": "",
|
||||
"topK": None,
|
||||
"maxSearches": None,
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 400
|
||||
# Embedder untouched when the push is rejected.
|
||||
assert app.state.runtime.documents.embedder is embedder_before
|
||||
|
||||
|
||||
def test_config_push_empty_models_keep_env_value() -> None:
|
||||
"""An empty models block keeps the engine's current (env) models but still
|
||||
applies pushed limits."""
|
||||
with _client(build_app_settings) as client:
|
||||
payload = _anthropic_push()
|
||||
payload["models"] = {
|
||||
"provider": "",
|
||||
"smartModel": "",
|
||||
"fastModel": "",
|
||||
"smartMaxTokens": None,
|
||||
"fastMaxTokens": None,
|
||||
"apiKey": "",
|
||||
"baseUrl": "",
|
||||
}
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
# Env "test" model preserved for both tiers; limits still applied.
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.fast_model_name == "test"
|
||||
assert app.state.settings.max_pages == 50
|
||||
|
||||
|
||||
def test_config_push_ignores_unknown_fields() -> None:
|
||||
"""A newer processor pushing fields this engine doesn't know must not 422;
|
||||
unknown fields are ignored and the rest of the push still applies."""
|
||||
with _client(build_app_settings) as client:
|
||||
payload = _anthropic_push()
|
||||
payload["futureTopLevelField"] = {"anything": 1}
|
||||
payload["models"]["experimentalFlag"] = True # type: ignore[index]
|
||||
response = client.post("/api/v1/config", json=payload)
|
||||
assert response.status_code == 200
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
|
||||
|
||||
def test_boot_restores_cached_config() -> None:
|
||||
"""A persisted config is decrypted and applied on boot, overriding env."""
|
||||
config_cache.save_config(ConfigPushRequest.model_validate(_anthropic_push()))
|
||||
with _client(build_app_settings):
|
||||
# Env model is "test"; the cache pushed claude-haiku-4-5 + limits.
|
||||
assert app.state.settings.smart_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.fast_model_name == "claude-haiku-4-5"
|
||||
assert app.state.settings.max_pages == 50
|
||||
assert app.state.settings.smart_model_max_tokens == 4096
|
||||
assert app.state.runtime.documents.default_top_k == 7
|
||||
|
||||
|
||||
def test_boot_ignores_cache_when_push_disabled() -> None:
|
||||
"""With allow_config_push false, env wins and the cache is ignored."""
|
||||
config_cache.save_config(ConfigPushRequest.model_validate(_anthropic_push()))
|
||||
|
||||
def factory() -> AppSettings:
|
||||
return build_app_settings().model_copy(update={"allow_config_push": False})
|
||||
|
||||
with _client(factory):
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.max_pages == 200
|
||||
|
||||
|
||||
def test_boot_proceeds_on_corrupt_cache(tmp_path: Path) -> None:
|
||||
"""A corrupt cache file is ignored and boot falls back to env, never crashing."""
|
||||
(tmp_path / "ai_config_cache.enc").write_bytes(b"not-a-valid-fernet-token")
|
||||
with _client(build_app_settings):
|
||||
assert app.state.settings.smart_model_name == "test"
|
||||
assert app.state.settings.max_pages == 200
|
||||
Generated
+2
@@ -603,6 +603,7 @@ name = "engine"
|
||||
version = "0.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "jinja2" },
|
||||
{ name = "opentelemetry-sdk" },
|
||||
@@ -630,6 +631,7 @@ dev = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "cryptography", specifier = ">=44.0.0" },
|
||||
{ name = "fastapi", specifier = ">=0.116.0" },
|
||||
{ name = "jinja2", specifier = ">=3.1.0" },
|
||||
{ name = "opentelemetry-sdk", specifier = ">=1.39.0" },
|
||||
|
||||
@@ -12,8 +12,6 @@ editor/public/mockServiceWorker.js
|
||||
# Auto-generated OG/social-preview metadata (scripts/generate-og-metadata.mjs); regenerated verbatim.
|
||||
editor/public/og-metadata.json
|
||||
editor/src/core/data/ogImageMap.json
|
||||
# Auto-generated portal docs manifest (scripts/sync-portal-docs.mts); regenerated verbatim.
|
||||
editor/src/portal/generated/docsManifest.json
|
||||
editor/public/pdfjs*/
|
||||
editor/public/js/thirdParty/
|
||||
editor/public/css/cookieconsent.css
|
||||
|
||||
@@ -6603,10 +6603,6 @@ title = "No components available"
|
||||
description = "GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."
|
||||
title = "Some components need a paid plan"
|
||||
|
||||
[portal.docs]
|
||||
browse = "Browse docs"
|
||||
viewSource = "View source on GitHub"
|
||||
|
||||
[portal.docs.authentication]
|
||||
codeCaption = "every request"
|
||||
eyebrow = "GETTING STARTED"
|
||||
@@ -6692,19 +6688,11 @@ title = "Official SDKs"
|
||||
beta = "Beta"
|
||||
deprecated = "Deprecated"
|
||||
|
||||
[portal.docs.search]
|
||||
empty = "No matching docs"
|
||||
placeholder = "Search docs"
|
||||
results = "{{count}} results"
|
||||
|
||||
[portal.docs.skills]
|
||||
eyebrow = "SKILLS"
|
||||
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
|
||||
title = "Agent skills"
|
||||
|
||||
[portal.docs.toc]
|
||||
title = "On this page"
|
||||
|
||||
[portal.docs.webhooks]
|
||||
codeCaption = "document.processed"
|
||||
eyebrow = "API REFERENCE"
|
||||
@@ -7258,7 +7246,7 @@ storage = "Storage"
|
||||
[portal.nav]
|
||||
agent-builder = "Agent Builder"
|
||||
components = "Components"
|
||||
docs = "Documentation"
|
||||
docs = "Developer Docs"
|
||||
documents = "Documents"
|
||||
editor = "Editor"
|
||||
home = "Home"
|
||||
|
||||
@@ -692,6 +692,160 @@ manualLinks = "Manual downloads: click the links and place the files into the te
|
||||
noLanguages = "No tessdata languages found in the configured directory."
|
||||
permissionNotice = "The tessdata path is not writable. Downloads will be opened in the browser; please save the .traineddata files manually into the tessdata folder."
|
||||
|
||||
# AI engine admin settings (AI nav group)
|
||||
[admin.settings.ai.documents]
|
||||
description = "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved."
|
||||
title = "Documents & RAG"
|
||||
|
||||
[admin.settings.ai.documents.embeddingApiKey]
|
||||
description = "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments."
|
||||
generic = "Embedding API key"
|
||||
openai = "OpenAI API key"
|
||||
voyageai = "VoyageAI API key"
|
||||
|
||||
[admin.settings.ai.documents.embeddingBaseUrl]
|
||||
description = "Base URL of the OpenAI-compatible / Ollama embeddings endpoint, e.g. http://ollama:11434/v1. Must point at a trusted internal endpoint (SSRF-sensitive)."
|
||||
label = "Embedding base URL"
|
||||
|
||||
[admin.settings.ai.documents.embeddingModel]
|
||||
description = "Embedding model name. Free text; suggestions are hints only."
|
||||
label = "Embedding model"
|
||||
|
||||
[admin.settings.ai.documents.embeddingProvider]
|
||||
description = "Provider used to turn document text into vector embeddings."
|
||||
label = "Embedding provider"
|
||||
|
||||
[admin.settings.ai.documents.maxSearches]
|
||||
description = "Maximum number of retrieval searches the agent may run per request."
|
||||
label = "Max searches"
|
||||
|
||||
[admin.settings.ai.documents.reindexNote]
|
||||
body = "Changing the embedding model invalidates previously-embedded documents. A full engine restart and re-index of existing documents is required for search to work correctly."
|
||||
title = "Re-index required"
|
||||
|
||||
[admin.settings.ai.documents.topK]
|
||||
description = "Number of most-relevant chunks retrieved per search."
|
||||
label = "Top K"
|
||||
|
||||
[admin.settings.ai.general]
|
||||
description = "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart."
|
||||
title = "AI Engine"
|
||||
|
||||
[admin.settings.ai.general.capabilities]
|
||||
description = "Turn individual AI features on or off. Disabled features are hidden in the app."
|
||||
title = "Capabilities"
|
||||
|
||||
[admin.settings.ai.general.enabled]
|
||||
description = "Master switch. When off, no AI tools, agents, or engine calls are available."
|
||||
label = "Enable AI"
|
||||
|
||||
[admin.settings.ai.general.features.chat]
|
||||
description = "Conversational assistant for working with PDFs."
|
||||
label = "Chat assistant"
|
||||
|
||||
[admin.settings.ai.general.features.classify]
|
||||
description = "Automatically categorise documents by type or content."
|
||||
label = "Document classification"
|
||||
|
||||
[admin.settings.ai.general.features.createPdf]
|
||||
description = "Generate a new PDF (e.g. from HTML) via an AI agent."
|
||||
label = "Create PDF from prompt"
|
||||
|
||||
[admin.settings.ai.general.features.documentQuestions]
|
||||
description = "Ask questions and get answers grounded in an uploaded document."
|
||||
label = "Document questions"
|
||||
|
||||
[admin.settings.ai.general.features.mathAuditor]
|
||||
description = "Review documents for mathematical and numerical errors."
|
||||
label = "Math auditor"
|
||||
|
||||
[admin.settings.ai.general.features.pdfComment]
|
||||
description = "Add AI-authored review comments and annotations to a PDF."
|
||||
label = "PDF comment agent"
|
||||
|
||||
[admin.settings.ai.general.longRunningTimeoutSeconds]
|
||||
description = "Timeout for heavier agent operations such as document generation."
|
||||
label = "Long-running timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.note]
|
||||
body = "The AI engine runs as a separate service. Its shared secret"
|
||||
body2 = "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved."
|
||||
title = "About the AI engine"
|
||||
|
||||
[admin.settings.ai.general.streamTimeoutSeconds]
|
||||
description = "Timeout for streamed (token-by-token) chat responses."
|
||||
label = "Stream timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.test]
|
||||
button = "Test connection"
|
||||
failBody = "The AI engine did not respond. Check the URL, that the engine container is running, and that AI is enabled (a restart is needed after enabling)."
|
||||
failTitle = "AI engine unreachable"
|
||||
okBody = "The AI engine responded to a health check."
|
||||
okTitle = "AI engine reachable"
|
||||
|
||||
[admin.settings.ai.general.timeoutSeconds]
|
||||
description = "Timeout for standard AI requests to the engine."
|
||||
label = "Request timeout (seconds)"
|
||||
|
||||
[admin.settings.ai.general.url]
|
||||
description = "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001."
|
||||
label = "AI engine URL"
|
||||
|
||||
[admin.settings.ai.limits]
|
||||
description = "Guardrails for how much work AI requests may do and how many run concurrently. Applied to the AI engine when saved."
|
||||
title = "Limits & Performance"
|
||||
|
||||
[admin.settings.ai.limits.maxCharacters]
|
||||
description = "Guardrail: reject AI requests whose extracted text exceeds this length."
|
||||
label = "Max characters per request"
|
||||
|
||||
[admin.settings.ai.limits.maxPages]
|
||||
description = "Guardrail: reject AI requests over this many PDF pages."
|
||||
label = "Max pages per request"
|
||||
|
||||
[admin.settings.ai.limits.modelMaxConcurrency]
|
||||
description = "Maximum simultaneous in-flight model calls across the whole engine."
|
||||
label = "Model max concurrency"
|
||||
|
||||
[admin.settings.ai.models]
|
||||
description = "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved."
|
||||
title = "Models & Providers"
|
||||
|
||||
[admin.settings.ai.models.apiKey]
|
||||
anthropic = "Anthropic API key"
|
||||
description = "Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments."
|
||||
generic = "API key"
|
||||
openai = "OpenAI API key"
|
||||
|
||||
[admin.settings.ai.models.baseUrl]
|
||||
description = "Base URL of the OpenAI-compatible / Ollama endpoint, e.g. http://ollama:11434/v1."
|
||||
label = "Provider base URL"
|
||||
warning = "The base URL must point at a trusted internal endpoint. The engine will make server-side requests to it, so an untrusted value is SSRF-sensitive."
|
||||
|
||||
[admin.settings.ai.models.fastMaxTokens]
|
||||
description = "Maximum output tokens for the fast model."
|
||||
label = "Fast model max tokens"
|
||||
|
||||
[admin.settings.ai.models.fastModel]
|
||||
description = "Cheaper, faster model for lightweight tasks. Free text; suggestions are hints only."
|
||||
label = "Fast model"
|
||||
|
||||
[admin.settings.ai.models.provider]
|
||||
description = "Which LLM provider the engine talks to."
|
||||
label = "Provider"
|
||||
|
||||
[admin.settings.ai.models.smartMaxTokens]
|
||||
description = "Maximum output tokens for the smart model."
|
||||
label = "Smart model max tokens"
|
||||
|
||||
[admin.settings.ai.models.smartModel]
|
||||
description = "High-capability model for complex reasoning. Free text; suggestions are hints only."
|
||||
label = "Smart model"
|
||||
|
||||
[admin.settings.ai.saved]
|
||||
body = "Changes are pushed to the AI engine automatically."
|
||||
title = "AI settings saved"
|
||||
|
||||
[admin.settings.badge]
|
||||
clickToUpgrade = "Click to view plan details"
|
||||
|
||||
@@ -6563,10 +6717,6 @@ bucket = "Bucket"
|
||||
name = "Name"
|
||||
region = "Region"
|
||||
|
||||
[portal.docs]
|
||||
browse = "Browse docs"
|
||||
viewSource = "View source on GitHub"
|
||||
|
||||
[portal.docs.authentication]
|
||||
codeCaption = "every request"
|
||||
eyebrow = "GETTING STARTED"
|
||||
@@ -6652,19 +6802,11 @@ title = "Official SDKs"
|
||||
beta = "Beta"
|
||||
deprecated = "Deprecated"
|
||||
|
||||
[portal.docs.search]
|
||||
empty = "No matching docs"
|
||||
placeholder = "Search docs"
|
||||
results = "{{count}} results"
|
||||
|
||||
[portal.docs.skills]
|
||||
eyebrow = "SKILLS"
|
||||
lead = "Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."
|
||||
title = "Agent skills"
|
||||
|
||||
[portal.docs.toc]
|
||||
title = "On this page"
|
||||
|
||||
[portal.docs.webhooks]
|
||||
codeCaption = "document.processed"
|
||||
eyebrow = "API REFERENCE"
|
||||
@@ -7329,7 +7471,7 @@ storage = "Storage"
|
||||
[portal.nav]
|
||||
agent-builder = "Agent Builder"
|
||||
components = "Components"
|
||||
docs = "Documentation"
|
||||
docs = "Developer Docs"
|
||||
documents = "Documents"
|
||||
editor = "Editor"
|
||||
home = "Home"
|
||||
@@ -8964,6 +9106,13 @@ title = "Signature Order"
|
||||
[settings]
|
||||
close = "Close"
|
||||
|
||||
[settings.ai]
|
||||
documents = "Documents & RAG"
|
||||
general = "General"
|
||||
limits = "Limits & Performance"
|
||||
models = "Models & Providers"
|
||||
title = "AI"
|
||||
|
||||
[settings.configuration]
|
||||
advanced = "Advanced"
|
||||
database = "Database"
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* Sync the portal Developer Docs from the Stirling docs repo.
|
||||
*
|
||||
* Fetches the docs repo tarball, extracts `docs/**` in-process (no external tar
|
||||
* binary, no per-file GitHub rate limits), shapes it with the pure transforms in
|
||||
* src/portal/docs/manifest/transform.ts, and writes the committed manifest that
|
||||
* the portal docs view renders. Re-run with `npm run docs:sync`.
|
||||
*
|
||||
* Env: DOCS_REPO, DOCS_REF, DOCS_ROOT override the defaults below.
|
||||
*/
|
||||
import { gunzipSync } from "node:zlib";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
// tsx/node16 can't resolve the @portal alias here, so import by relative .ts path.
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import {
|
||||
buildManifest,
|
||||
type CategoryMap,
|
||||
type RawDoc,
|
||||
} from "../src/portal/docs/manifest/transform.ts";
|
||||
|
||||
const REPO = process.env.DOCS_REPO ?? "Stirling-Tools/Stirling-Tools.github.io";
|
||||
const REF = process.env.DOCS_REF ?? "main";
|
||||
const ROOT = process.env.DOCS_ROOT ?? "docs";
|
||||
const SITE = "https://docs.stirlingpdf.com";
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const OUT = resolve(HERE, "../src/portal/generated/docsManifest.json");
|
||||
|
||||
/* ── Minimal tar reader (ustar + pax/GNU long names) ─────────────────────── */
|
||||
|
||||
interface TarEntry {
|
||||
name: string;
|
||||
type: string;
|
||||
data: Buffer;
|
||||
}
|
||||
|
||||
function readTar(buf: Buffer): TarEntry[] {
|
||||
const entries: TarEntry[] = [];
|
||||
let offset = 0;
|
||||
let longName: string | null = null;
|
||||
let paxPath: string | null = null;
|
||||
|
||||
const str = (start: number, len: number) => {
|
||||
const slice = buf.subarray(start, start + len);
|
||||
const end = slice.indexOf(0);
|
||||
return slice.toString("utf8", 0, end === -1 ? len : end);
|
||||
};
|
||||
|
||||
while (offset + 512 <= buf.length) {
|
||||
const header = buf.subarray(offset, offset + 512);
|
||||
// Two consecutive zero blocks mark the end of the archive.
|
||||
if (header.every((b) => b === 0)) break;
|
||||
|
||||
const name = str(offset, 100);
|
||||
const prefix = str(offset + 345, 155);
|
||||
const sizeStr = str(offset + 124, 12).trim();
|
||||
const size = parseInt(sizeStr, 8) || 0;
|
||||
const type = String.fromCharCode(header[156]);
|
||||
const dataStart = offset + 512;
|
||||
const data = buf.subarray(dataStart, dataStart + size);
|
||||
|
||||
let fullName = prefix ? `${prefix}/${name}` : name;
|
||||
if (longName) {
|
||||
fullName = longName;
|
||||
longName = null;
|
||||
}
|
||||
if (paxPath) {
|
||||
fullName = paxPath;
|
||||
paxPath = null;
|
||||
}
|
||||
|
||||
if (type === "L") {
|
||||
// GNU long name: the payload is the real name of the next entry.
|
||||
longName = data.toString("utf8").replace(/\0+$/, "");
|
||||
} else if (type === "x") {
|
||||
// pax extended header: pull a `path=` record for the next entry.
|
||||
const record = /(?:^|\n)\d+ path=([^\n]+)\n/.exec(data.toString("utf8"));
|
||||
if (record) paxPath = record[1];
|
||||
} else if (type === "0" || type === "\0" || type === "") {
|
||||
entries.push({ name: fullName, type, data: Buffer.from(data) });
|
||||
}
|
||||
|
||||
offset = dataStart + Math.ceil(size / 512) * 512;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/* ── Fetch + shape ───────────────────────────────────────────────────────── */
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const url = `https://api.github.com/repos/${REPO}/tarball/${REF}`;
|
||||
console.log(`Fetching ${REPO}@${REF} …`);
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
Accept: "application/vnd.github+json",
|
||||
"User-Agent": "stirling-portal-docs-sync",
|
||||
...(process.env.GITHUB_TOKEN
|
||||
? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
`GitHub tarball fetch failed: ${res.status} ${res.statusText}`,
|
||||
);
|
||||
}
|
||||
const gz = Buffer.from(await res.arrayBuffer());
|
||||
const entries = readTar(gunzipSync(gz));
|
||||
|
||||
// Strip the "<repo>-<sha>/" wrapper dir and keep only files under docs root.
|
||||
const prefix = `${ROOT}/`;
|
||||
const rawDocs: RawDoc[] = [];
|
||||
const categories: CategoryMap = {};
|
||||
for (const entry of entries) {
|
||||
const rel = entry.name.replace(/^[^/]+\//, "");
|
||||
if (!rel.startsWith(prefix)) continue;
|
||||
const inner = rel.slice(prefix.length);
|
||||
if (!inner) continue;
|
||||
if (inner.endsWith("/_category_.json")) {
|
||||
const dir = inner.slice(0, -"/_category_.json".length);
|
||||
try {
|
||||
categories[dir] = JSON.parse(entry.data.toString("utf8"));
|
||||
} catch {
|
||||
console.warn(` skipping unparseable _category_.json in ${dir}`);
|
||||
}
|
||||
} else if (/\.mdx?$/i.test(inner)) {
|
||||
rawDocs.push({ relPath: inner, content: entry.data.toString("utf8") });
|
||||
}
|
||||
}
|
||||
|
||||
if (rawDocs.length === 0) {
|
||||
throw new Error(`No markdown found under ${ROOT}/ — wrong repo/ref/root?`);
|
||||
}
|
||||
|
||||
const manifest = buildManifest(rawDocs, categories, {
|
||||
repo: REPO,
|
||||
ref: REF,
|
||||
root: ROOT,
|
||||
siteBaseUrl: SITE,
|
||||
});
|
||||
|
||||
mkdirSync(dirname(OUT), { recursive: true });
|
||||
writeFileSync(OUT, JSON.stringify(manifest, null, 2) + "\n", "utf8");
|
||||
|
||||
const items = manifest.nav.reduce((n, s) => n + s.items.length, 0);
|
||||
console.log(
|
||||
`Wrote ${manifest.nav.length} sections, ${items} docs → ${OUT.replace(/.*[/\\]frontend[/\\]/, "frontend/")}`,
|
||||
);
|
||||
for (const s of manifest.nav) {
|
||||
console.log(` ${s.icon} ${s.label} (${s.items.length})`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(err instanceof Error ? err.message : err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -4,9 +4,7 @@
|
||||
"module": "node16",
|
||||
"moduleResolution": "node16",
|
||||
"types": ["node"],
|
||||
"noEmit": true,
|
||||
// sync-portal-docs.mts imports the shared transform by its .ts path (run via tsx).
|
||||
"allowImportingTsExtensions": true
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["./**/*.ts", "./**/*.mts"]
|
||||
}
|
||||
|
||||
@@ -32,6 +32,10 @@ export const VALID_NAV_KEYS = [
|
||||
"adminEndpoints",
|
||||
"adminStorageSharing",
|
||||
"adminMcp",
|
||||
"adminAiGeneral",
|
||||
"adminAiModels",
|
||||
"adminAiDocuments",
|
||||
"adminAiLimits",
|
||||
"help",
|
||||
"legal",
|
||||
"backendThirdPartyLicenses",
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
import {
|
||||
deserializeToolStep,
|
||||
getExecutableTools,
|
||||
serializeStepFromEndpoint,
|
||||
serializeToolStep,
|
||||
stepRequiresUpload,
|
||||
type WorkingToolStep,
|
||||
@@ -199,41 +198,6 @@ describe("serialize/deserialize round-trip", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("serializeStepFromEndpoint", () => {
|
||||
test("maps a wizard step's UI params to the backend contract, filling defaults", () => {
|
||||
// The shape the policy setup wizard holds: an endpoint plus UI-shaped params
|
||||
// (redact's `wordsToRedact`), with several fields left to their defaults.
|
||||
const api = serializeStepFromEndpoint(
|
||||
"/api/v1/security/auto-redact",
|
||||
{ mode: "automatic", useRegex: true, wordsToRedact: ["ssn", "card"] },
|
||||
dynamicRegistry,
|
||||
);
|
||||
|
||||
expect(api.operation).toBe("/api/v1/security/auto-redact");
|
||||
// wordsToRedact -> listOfText (the field the backend actually reads), and the
|
||||
// frontend-only `mode` is dropped.
|
||||
expect(api.parameters).toMatchObject({ listOfText: "ssn\ncard" });
|
||||
expect(api.parameters).not.toHaveProperty("wordsToRedact");
|
||||
expect(api.parameters).not.toHaveProperty("mode");
|
||||
// Fields the wizard never set still get their defaults so the body is complete.
|
||||
expect(api.parameters).toHaveProperty("wholeWordSearch");
|
||||
expect(api.parameters).toHaveProperty("customPadding");
|
||||
});
|
||||
|
||||
test("passes an unmapped endpoint's params through unchanged", () => {
|
||||
expect(
|
||||
serializeStepFromEndpoint(
|
||||
"/api/v1/unknown/thing",
|
||||
{ keep: true },
|
||||
dynamicRegistry,
|
||||
),
|
||||
).toEqual({
|
||||
operation: "/api/v1/unknown/thing",
|
||||
parameters: { keep: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("stepRequiresUpload", () => {
|
||||
const step = (params: Record<string, unknown>): WorkingToolStep => ({
|
||||
toolId: "compress" as ToolId,
|
||||
|
||||
@@ -197,31 +197,6 @@ export function serializeToolStep(
|
||||
return { operation, parameters };
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a step held as an endpoint path plus frontend-shaped params - the form the policy setup
|
||||
* wizard keeps, where params match the tool's UI shape (e.g. redact's `wordsToRedact`) rather than
|
||||
* the backend contract - into the backend step contract, mapping params through the tool's
|
||||
* `toApiParams` (merged over its defaults, so fields the wizard never set still get their defaults).
|
||||
* The endpoint maps to a tool by path, so this works for dynamic-endpoint tools whose config
|
||||
* endpoint is a function. Endpoints that map to no known tool pass through unchanged.
|
||||
*/
|
||||
export function serializeStepFromEndpoint(
|
||||
operation: string,
|
||||
params: ErasedToolParams,
|
||||
registry: Partial<ToolRegistry>,
|
||||
): ToolApiStep {
|
||||
const match = findToolByEndpoint({ operation, parameters: params }, registry);
|
||||
const config = match?.[1].operationConfig;
|
||||
if (!config) return { operation, parameters: params };
|
||||
const merged = { ...(config.defaultParameters ?? {}), ...params };
|
||||
return {
|
||||
operation: resolveEndpoint(config, merged) ?? operation,
|
||||
parameters: config.toApiParams
|
||||
? (config.toApiParams(merged) as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the registry tool for a stored step's endpoint: exact match for static endpoints, else
|
||||
* membership in a dynamic tool's declared `endpoints` set (replaying its function can't recover a
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describeToolOperation } from "@app/hooks/tools/shared/toolOperationDescriptor";
|
||||
|
||||
interface Params {
|
||||
a: number;
|
||||
}
|
||||
|
||||
// A minimal config that type-checks against the flatten endpoint's model.
|
||||
const CONFIG = {
|
||||
endpoint: "/api/v1/misc/flatten" as const,
|
||||
defaultParameters: { a: 1 } satisfies Params,
|
||||
toApiParams: (p: Params) => ({ renderDpi: p.a }),
|
||||
fromApiParams: (api: { renderDpi?: number }) => ({ a: api.renderDpi ?? 0 }),
|
||||
};
|
||||
|
||||
describe("describeToolOperation", () => {
|
||||
test("wraps the config's mappers and endpoint into a descriptor", () => {
|
||||
const d = describeToolOperation("/api/v1/misc/flatten", CONFIG);
|
||||
expect(d.endpoint).toBe("/api/v1/misc/flatten");
|
||||
expect(d.toApi({ a: 200 })).toEqual({ renderDpi: 200 });
|
||||
});
|
||||
|
||||
test("fromApi merges the mapped values over the defaults", () => {
|
||||
const d = describeToolOperation("/api/v1/misc/flatten", CONFIG);
|
||||
expect(d.fromApi({ renderDpi: 72 })).toEqual({ a: 72 });
|
||||
});
|
||||
|
||||
test("throws when the config lacks a mapper", () => {
|
||||
expect(() =>
|
||||
describeToolOperation("/api/v1/misc/flatten", {
|
||||
endpoint: "/api/v1/misc/flatten" as const,
|
||||
defaultParameters: { a: 1 },
|
||||
toApiParams: (p: Params) => ({ renderDpi: p.a }),
|
||||
}),
|
||||
).toThrow(/mappers/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Typed wrapper over a tool's `toApiParams`/`fromApiParams` mappers, binding one endpoint to safe
|
||||
* frontend<->backend parameter conversion.
|
||||
*/
|
||||
|
||||
import type { ToolApiParams, ToolEndpoint } from "@app/types/toolApiTypes";
|
||||
|
||||
export interface ToolOperationDescriptor<E extends ToolEndpoint, TParams> {
|
||||
readonly endpoint: E;
|
||||
readonly defaultParameters: TParams;
|
||||
toApi(params: TParams): ToolApiParams[E];
|
||||
/** Backend model -> full frontend params (defaults merged under the mapped values). */
|
||||
fromApi(api: ToolApiParams[E]): TParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural subset of a tool's config. `CE` is the config's declared endpoint type, inferred from
|
||||
* the `endpoint` field: the literal for static tools, or the whole `ToolEndpoint` union for
|
||||
* dynamic-endpoint tools (whose endpoint is a function typed against the union).
|
||||
*/
|
||||
export interface BidirectionalToolConfig<TParams, CE extends ToolEndpoint> {
|
||||
endpoint: CE | null | ((params: TParams) => CE | null);
|
||||
defaultParameters?: TParams;
|
||||
toApiParams?(params: TParams): ToolApiParams[CE];
|
||||
fromApiParams?(api: ToolApiParams[CE]): Partial<TParams>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pin a config to `endpoint` (passed explicitly, since dynamic-endpoint tools declare `endpoint` as
|
||||
* a function). `E extends CE` rejects pairing a static tool's config with the wrong endpoint, while
|
||||
* allowing a dynamic tool whose `CE` is the full union. Throws when mappers or defaults are missing.
|
||||
*/
|
||||
export function describeToolOperation<
|
||||
E extends CE,
|
||||
CE extends ToolEndpoint,
|
||||
TParams,
|
||||
>(
|
||||
endpoint: E,
|
||||
config: BidirectionalToolConfig<TParams, CE>,
|
||||
): ToolOperationDescriptor<E, TParams> {
|
||||
const { toApiParams, fromApiParams, defaultParameters } = config;
|
||||
if (!toApiParams || !fromApiParams || defaultParameters === undefined) {
|
||||
throw new Error(
|
||||
`describeToolOperation: "${endpoint}" is missing mappers or defaults`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
endpoint,
|
||||
defaultParameters,
|
||||
// A dynamic tool's mapper is typed against the union; narrow to this endpoint (sound - the
|
||||
// runtime mapper produces this endpoint's model).
|
||||
toApi: (params) => toApiParams(params) as ToolApiParams[E],
|
||||
fromApi: (api) =>
|
||||
({
|
||||
...defaultParameters,
|
||||
...fromApiParams(api as ToolApiParams[CE]),
|
||||
}) as TParams,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import { Navigate, Route, Routes } from "react-router-dom";
|
||||
import { Home } from "@portal/views/Home";
|
||||
import { Users } from "@portal/views/Users";
|
||||
@@ -13,16 +12,10 @@ import { Components } from "@portal/views/Components";
|
||||
import { EditorAdmin } from "@portal/views/EditorAdmin";
|
||||
import { Infrastructure } from "@portal/views/Infrastructure";
|
||||
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
|
||||
import { DeveloperDocs } from "@portal/views/DeveloperDocs";
|
||||
import { Procurement } from "@portal/views/Procurement";
|
||||
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
|
||||
|
||||
// Lazy so the generated docs manifest (bundled JSON) lands in its own chunk.
|
||||
const DeveloperDocs = lazy(() =>
|
||||
import("@portal/views/DeveloperDocs").then((m) => ({
|
||||
default: m.DeveloperDocs,
|
||||
})),
|
||||
);
|
||||
|
||||
// The portal mounts as a route-set under /processor/* in the editor app, so these
|
||||
// child routes are relative to that base: strip the leading slash from the
|
||||
// logical VIEW_PATHS, and home is the index route. Redirects use toPortalPath
|
||||
@@ -66,14 +59,7 @@ export function ViewRouter() {
|
||||
/>
|
||||
<Route path={rel(VIEW_PATHS.usage)} element={<PortalBillingGate />} />
|
||||
<Route path={rel(VIEW_PATHS.procurement)} element={<Procurement />} />
|
||||
<Route
|
||||
path={rel(VIEW_PATHS.docs)}
|
||||
element={
|
||||
<Suspense fallback={null}>
|
||||
<DeveloperDocs />
|
||||
</Suspense>
|
||||
}
|
||||
/>
|
||||
<Route path={rel(VIEW_PATHS.docs)} element={<DeveloperDocs />} />
|
||||
{/* Account-link is now a Settings panel; redirect legacy bookmarks home. */}
|
||||
<Route
|
||||
path="account-link"
|
||||
|
||||
@@ -13,6 +13,8 @@ import type { TFunction } from "i18next";
|
||||
import { apiClient } from "@portal/api/http";
|
||||
import { fromWirePolicy, toWirePolicy } from "@app/policies/codec";
|
||||
import { runsToActivity, runsToStats } from "@app/policies/runs";
|
||||
import { policyStep, type PolicyToolStep } from "@app/policies/operations";
|
||||
import type { ToolEndpoint } from "@app/types/toolApiTypes";
|
||||
import type {
|
||||
PolicyDecodedState,
|
||||
PolicyRunView,
|
||||
@@ -66,7 +68,7 @@ export interface PolicyConfigDef {
|
||||
rules: string[];
|
||||
scopeLabel: string;
|
||||
fields: PolicyField[];
|
||||
defaultOperations: WirePipelineStep[];
|
||||
defaultOperations: PolicyToolStep[];
|
||||
}
|
||||
|
||||
export interface PolicyState {
|
||||
@@ -128,20 +130,11 @@ export interface CatalogueEntry {
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Tool → endpoint registry */
|
||||
/* Endpoint display labels */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export const TOOL_ENDPOINTS: Record<string, string> = {
|
||||
redact: "/api/v1/security/auto-redact",
|
||||
sanitize: "/api/v1/security/sanitize-pdf",
|
||||
watermark: "/api/v1/security/add-watermark",
|
||||
ocr: "/api/v1/misc/ocr-pdf",
|
||||
flatten: "/api/v1/misc/flatten",
|
||||
compress: "/api/v1/misc/compress-pdf",
|
||||
};
|
||||
|
||||
/** Values are i18n keys — render with t(). */
|
||||
export const ENDPOINT_LABELS: Record<string, string> = {
|
||||
/** i18n keys keyed by {@link ToolEndpoint}; labels stored steps in the detail view. */
|
||||
export const ENDPOINT_LABELS: Partial<Record<ToolEndpoint, string>> = {
|
||||
"/api/v1/security/auto-redact": "portal.policies.endpoints.autoRedact",
|
||||
"/api/v1/security/sanitize-pdf": "portal.policies.endpoints.sanitizePdf",
|
||||
"/api/v1/security/add-watermark": "portal.policies.endpoints.addWatermark",
|
||||
@@ -154,7 +147,8 @@ export function humanizeEndpoint(
|
||||
path: string,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
if (ENDPOINT_LABELS[path]) return t(ENDPOINT_LABELS[path]);
|
||||
const label = ENDPOINT_LABELS[path as ToolEndpoint];
|
||||
if (label) return t(label);
|
||||
const last = path.split("/").filter(Boolean).pop() ?? path;
|
||||
return last
|
||||
.replace(/-/g, " ")
|
||||
@@ -230,10 +224,7 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
"portal.policies.config.ingestion.rules.3",
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [
|
||||
{ operation: TOOL_ENDPOINTS.ocr, parameters: {} },
|
||||
{ operation: TOOL_ENDPOINTS.flatten, parameters: {} },
|
||||
],
|
||||
defaultOperations: [policyStep("ocr"), policyStep("flatten")],
|
||||
fields: [
|
||||
{
|
||||
label: "portal.policies.config.ingestion.fields.minConfidence",
|
||||
@@ -260,32 +251,16 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [
|
||||
{
|
||||
operation: TOOL_ENDPOINTS.redact,
|
||||
parameters: {
|
||||
mode: "automatic",
|
||||
useRegex: true,
|
||||
convertPDFToImage: true,
|
||||
wordsToRedact: DEFAULT_PII_PATTERNS,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: TOOL_ENDPOINTS.sanitize,
|
||||
parameters: {
|
||||
removeJavaScript: true,
|
||||
removeEmbeddedFiles: false,
|
||||
removeMetadata: false,
|
||||
removeLinks: false,
|
||||
removeFonts: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: TOOL_ENDPOINTS.watermark,
|
||||
// convertPDFToImage bakes the watermark in so it can't be stripped
|
||||
parameters: {
|
||||
convertPDFToImage: true,
|
||||
},
|
||||
},
|
||||
// Flatten to image so redactions can't be lifted off.
|
||||
policyStep("redact", {
|
||||
useRegex: true,
|
||||
convertPDFToImage: true,
|
||||
wordsToRedact: DEFAULT_PII_PATTERNS,
|
||||
}),
|
||||
// JavaScript removal only; the tool enables removeEmbeddedFiles by default, so turn it off.
|
||||
policyStep("sanitize", { removeEmbeddedFiles: false }),
|
||||
// Bake in via image so it can't be stripped.
|
||||
policyStep("watermark", { convertPDFToImage: true }),
|
||||
],
|
||||
fields: [],
|
||||
},
|
||||
@@ -297,10 +272,7 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
"portal.policies.config.compliance.rules.2",
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [
|
||||
{ operation: TOOL_ENDPOINTS.sanitize, parameters: {} },
|
||||
{ operation: TOOL_ENDPOINTS.flatten, parameters: {} },
|
||||
],
|
||||
defaultOperations: [policyStep("sanitize"), policyStep("flatten")],
|
||||
fields: [
|
||||
{
|
||||
label: "portal.policies.config.compliance.fields.frameworks",
|
||||
@@ -343,7 +315,7 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
"portal.policies.config.routing.rules.2",
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [{ operation: TOOL_ENDPOINTS.compress, parameters: {} }],
|
||||
defaultOperations: [policyStep("compress")],
|
||||
fields: [
|
||||
{
|
||||
label: "portal.policies.config.routing.fields.destination",
|
||||
@@ -374,7 +346,7 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {
|
||||
"portal.policies.config.retention.rules.2",
|
||||
],
|
||||
scopeLabel: "portal.policies.config.scopeAll",
|
||||
defaultOperations: [{ operation: TOOL_ENDPOINTS.compress, parameters: {} }],
|
||||
defaultOperations: [policyStep("compress")],
|
||||
fields: [
|
||||
{
|
||||
label: "portal.policies.config.retention.fields.keepFor",
|
||||
|
||||
@@ -1,45 +1,8 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Button, Skeleton, StatusBadge } from "@app/ui";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { DocsNavSection } from "@portal/api/docs";
|
||||
|
||||
/**
|
||||
* Left-hand documentation nav: a hierarchical accordion. Section ids encode their
|
||||
* path ("functionality/security" is a child of "functionality"), so sub-sections
|
||||
* nest under their parent. The root "Overview" section is static (always open, no
|
||||
* toggle); every other section collapses, and only the branch leading to the
|
||||
* active doc opens by default. (Search lives in DocsSearch above this.)
|
||||
*/
|
||||
|
||||
// Matches the generator's ROOT_SECTION_ID: the intro section is never collapsible.
|
||||
const STATIC_SECTION_ID = "overview";
|
||||
|
||||
interface NavNode {
|
||||
section: DocsNavSection;
|
||||
children: NavNode[];
|
||||
}
|
||||
|
||||
/** Split "a/b/c" → "a/b"; null for a top-level id. */
|
||||
function parentId(id: string): string | null {
|
||||
const i = id.lastIndexOf("/");
|
||||
return i === -1 ? null : id.slice(0, i);
|
||||
}
|
||||
|
||||
/** Build the section tree from the flat, pre-sorted section list. */
|
||||
function buildTree(sections: DocsNavSection[]): NavNode[] {
|
||||
const byId = new Map<string, NavNode>(
|
||||
sections.map((s) => [s.id, { section: s, children: [] }]),
|
||||
);
|
||||
const roots: NavNode[] = [];
|
||||
for (const node of byId.values()) {
|
||||
const pid = parentId(node.section.id);
|
||||
const parent = pid ? byId.get(pid) : undefined;
|
||||
if (parent) parent.children.push(node);
|
||||
else roots.push(node);
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/** Left-hand documentation nav tree; each leaf selects an in-page section. */
|
||||
export function DocsNav({
|
||||
sections,
|
||||
active,
|
||||
@@ -50,125 +13,50 @@ export function DocsNav({
|
||||
onSelect: (id: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// Per-section manual open/close, overriding the "active branch only" default.
|
||||
const [toggled, setToggled] = useState<Record<string, boolean>>({});
|
||||
const activeRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const activeSectionId = useMemo(
|
||||
() => sections.find((s) => s.items.some((i) => i.id === active))?.id,
|
||||
[sections, active],
|
||||
);
|
||||
|
||||
const tree = useMemo(() => buildTree(sections), [sections]);
|
||||
|
||||
// Keep the active item in view when navigating (e.g. via a cross-link).
|
||||
useEffect(() => {
|
||||
activeRef.current?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [active]);
|
||||
|
||||
const isOpen = (id: string): boolean => {
|
||||
if (id === STATIC_SECTION_ID) return true;
|
||||
// Default-open the branch containing the active doc (self or ancestor).
|
||||
const onActivePath =
|
||||
!!activeSectionId &&
|
||||
(activeSectionId === id || activeSectionId.startsWith(id + "/"));
|
||||
return toggled[id] ?? onActivePath;
|
||||
};
|
||||
|
||||
const renderNode = (node: NavNode) => {
|
||||
const { section, children } = node;
|
||||
const isStatic = section.id === STATIC_SECTION_ID;
|
||||
const open = isOpen(section.id);
|
||||
return (
|
||||
<div key={section.id} className="portal-docs__nav-group">
|
||||
{isStatic ? (
|
||||
<div className="portal-docs__nav-head">{section.label}</div>
|
||||
) : (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
fullWidth
|
||||
justify="between"
|
||||
className="portal-docs__nav-head portal-docs__nav-head--button"
|
||||
aria-expanded={open}
|
||||
onClick={() =>
|
||||
setToggled((prev) => ({ ...prev, [section.id]: !open }))
|
||||
}
|
||||
rightSection={
|
||||
<span className="portal-docs__nav-count">
|
||||
{section.items.length}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="portal-docs__nav-head-main">
|
||||
<span
|
||||
className={
|
||||
"portal-docs__nav-chevron" + (open ? " is-open" : "")
|
||||
}
|
||||
aria-hidden
|
||||
>
|
||||
▸
|
||||
</span>
|
||||
<span className="portal-docs__nav-headlabel">
|
||||
{section.label}
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{open && (
|
||||
<>
|
||||
{section.items.length > 0 && (
|
||||
<ul className="portal-docs__nav-list">
|
||||
{section.items.map((item) => {
|
||||
const isActive = item.id === active;
|
||||
return (
|
||||
<li key={item.id}>
|
||||
<Button
|
||||
ref={isActive ? activeRef : undefined}
|
||||
variant="tertiary"
|
||||
justify="start"
|
||||
fullWidth
|
||||
className={
|
||||
"portal-docs__nav-link" +
|
||||
(isActive ? " is-active" : "")
|
||||
}
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
onClick={() => onSelect(item.id)}
|
||||
>
|
||||
<span className="portal-docs__nav-label">
|
||||
{item.label}
|
||||
</span>
|
||||
{item.badge && (
|
||||
<StatusBadge
|
||||
tone={item.badge === "New" ? "success" : "info"}
|
||||
size="sm"
|
||||
>
|
||||
{item.badge}
|
||||
</StatusBadge>
|
||||
)}
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
{children.length > 0 && (
|
||||
<div className="portal-docs__nav-children">
|
||||
{children.map(renderNode)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<nav
|
||||
className="portal-docs__nav"
|
||||
aria-label={t("portal.docs.nav.ariaLabel")}
|
||||
>
|
||||
{tree.map(renderNode)}
|
||||
{sections.map((section) => (
|
||||
<div key={section.id} className="portal-docs__nav-group">
|
||||
<div className="portal-docs__nav-head">
|
||||
<span className="portal-docs__nav-icon" aria-hidden>
|
||||
{section.icon}
|
||||
</span>
|
||||
{section.label}
|
||||
</div>
|
||||
<ul className="portal-docs__nav-list">
|
||||
{section.items.map((item) => {
|
||||
const isActive = item.id === active;
|
||||
return (
|
||||
<li key={item.id}>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
justify="start"
|
||||
fullWidth
|
||||
className={
|
||||
"portal-docs__nav-link" + (isActive ? " is-active" : "")
|
||||
}
|
||||
aria-current={isActive ? "page" : undefined}
|
||||
onClick={() => onSelect(item.id)}
|
||||
>
|
||||
<span className="portal-docs__nav-label">{item.label}</span>
|
||||
{item.badge && (
|
||||
<StatusBadge
|
||||
tone={item.badge === "New" ? "success" : "info"}
|
||||
size="sm"
|
||||
>
|
||||
{item.badge}
|
||||
</StatusBadge>
|
||||
)}
|
||||
</Button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -176,16 +64,14 @@ export function DocsNav({
|
||||
export function DocsNavSkeleton() {
|
||||
return (
|
||||
<nav className="portal-docs__nav" aria-hidden>
|
||||
{Array.from({ length: 5 }).map((_, gi) => (
|
||||
{Array.from({ length: 4 }).map((_, gi) => (
|
||||
<div key={gi} className="portal-docs__nav-group">
|
||||
<Skeleton width="7rem" height="0.75rem" />
|
||||
{gi === 0 && (
|
||||
<div className="portal-docs__nav-list">
|
||||
{Array.from({ length: 4 }).map((_, li) => (
|
||||
<Skeleton key={li} width="80%" height="0.875rem" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="portal-docs__nav-list">
|
||||
{Array.from({ length: 3 }).map((_, li) => (
|
||||
<Skeleton key={li} width="80%" height="0.875rem" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@app/ui";
|
||||
import type { SearchResult, Segment } from "@portal/docs/search";
|
||||
|
||||
/** Render highlighted segments, wrapping matched runs in <mark>. */
|
||||
function Highlighted({ segments }: { segments: Segment[] }) {
|
||||
return (
|
||||
<>
|
||||
{segments.map((s, i) =>
|
||||
s.hit ? (
|
||||
<mark key={i} className="portal-docs__hl">
|
||||
{s.text}
|
||||
</mark>
|
||||
) : (
|
||||
<span key={i}>{s.text}</span>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Docs search box + results. While a query is active it shows a ranked list of
|
||||
* matching docs — each with its section, a highlighted title, and a content
|
||||
* snippet — that navigates on click (or Enter). Arrow keys move the selection.
|
||||
*/
|
||||
export function DocsSearch({
|
||||
query,
|
||||
onQueryChange,
|
||||
results,
|
||||
onSelect,
|
||||
}: {
|
||||
query: string;
|
||||
onQueryChange: (q: string) => void;
|
||||
results: SearchResult[];
|
||||
onSelect: (docId: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// -1 = nothing pre-selected; arrow keys drive this, the mouse uses CSS :hover.
|
||||
const [activeIndex, setActiveIndex] = useState(-1);
|
||||
const listRef = useRef<HTMLUListElement>(null);
|
||||
const hasQuery = query.trim().length > 0;
|
||||
|
||||
useEffect(() => setActiveIndex(-1), [query]);
|
||||
|
||||
useEffect(() => {
|
||||
listRef.current
|
||||
?.querySelector<HTMLElement>('[data-active="true"]')
|
||||
?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [activeIndex]);
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Escape") {
|
||||
onQueryChange("");
|
||||
return;
|
||||
}
|
||||
if (!results.length) return;
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setActiveIndex((i) => Math.min(i + 1, results.length - 1));
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActiveIndex((i) => Math.max(i - 1, 0));
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const hit = results[activeIndex >= 0 ? activeIndex : 0];
|
||||
if (hit) onSelect(hit.id);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="portal-docs__search">
|
||||
<div className="portal-docs__search-box">
|
||||
<span className="portal-docs__search-icon" aria-hidden>
|
||||
⌕
|
||||
</span>
|
||||
<input
|
||||
type="search"
|
||||
className="portal-docs__search-input"
|
||||
placeholder={t("portal.docs.search.placeholder")}
|
||||
value={query}
|
||||
onChange={(e) => onQueryChange(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
aria-label={t("portal.docs.search.placeholder")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{hasQuery && (
|
||||
<div className="portal-docs__results">
|
||||
{results.length === 0 ? (
|
||||
<p className="portal-docs__nav-empty">
|
||||
{t("portal.docs.search.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="portal-docs__results-count">
|
||||
{t("portal.docs.search.results", { count: results.length })}
|
||||
</div>
|
||||
<ul ref={listRef} className="portal-docs__results-list">
|
||||
{results.map((r, i) => (
|
||||
<li key={r.id}>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
fullWidth
|
||||
justify="start"
|
||||
className={
|
||||
"portal-docs__result" +
|
||||
(i === activeIndex ? " is-active" : "")
|
||||
}
|
||||
data-active={i === activeIndex}
|
||||
onClick={() => onSelect(r.id)}
|
||||
>
|
||||
<span className="portal-docs__result-body">
|
||||
<span className="portal-docs__result-head">
|
||||
<span className="portal-docs__result-title">
|
||||
<Highlighted segments={r.titleSegments} />
|
||||
</span>
|
||||
<span className="portal-docs__result-section">
|
||||
{r.sectionLabel}
|
||||
</span>
|
||||
</span>
|
||||
<span className="portal-docs__result-snippet">
|
||||
<Highlighted segments={r.snippet} />
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { useEffect, useState, type RefObject } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { Heading } from "@portal/docs/headings";
|
||||
|
||||
/**
|
||||
* "On this page" table of contents. Lists the current doc's H2/H3 headings,
|
||||
* scrolls the reading pane to a heading on click, and highlights the section
|
||||
* currently in view (scroll-spy against the pane's scroll container).
|
||||
*/
|
||||
export function DocsToc({
|
||||
headings,
|
||||
scrollRef,
|
||||
}: {
|
||||
headings: Heading[];
|
||||
scrollRef: RefObject<HTMLElement | null>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [active, setActive] = useState<string>(headings[0]?.slug ?? "");
|
||||
|
||||
useEffect(() => {
|
||||
const root = scrollRef.current;
|
||||
if (!root || headings.length === 0) return;
|
||||
setActive(headings[0].slug);
|
||||
|
||||
const visible = new Set<string>();
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
for (const e of entries) {
|
||||
if (e.isIntersecting) visible.add(e.target.id);
|
||||
else visible.delete(e.target.id);
|
||||
}
|
||||
// The topmost heading currently within the active zone wins.
|
||||
const current = headings.find((h) => visible.has(h.slug));
|
||||
if (current) setActive(current.slug);
|
||||
},
|
||||
// Active zone = the top ~30% of the reading pane.
|
||||
{ root, rootMargin: "0px 0px -70% 0px", threshold: 0 },
|
||||
);
|
||||
|
||||
const els = headings
|
||||
.map((h) => root.querySelector(`[id="${h.slug}"]`))
|
||||
.filter((el): el is Element => el !== null);
|
||||
els.forEach((el) => observer.observe(el));
|
||||
return () => observer.disconnect();
|
||||
}, [headings, scrollRef]);
|
||||
|
||||
const onSelect = (slug: string) => {
|
||||
scrollRef.current
|
||||
?.querySelector(`[id="${slug}"]`)
|
||||
?.scrollIntoView({ block: "start", behavior: "smooth" });
|
||||
setActive(slug);
|
||||
};
|
||||
|
||||
return (
|
||||
<nav className="portal-docs__toc" aria-label={t("portal.docs.toc.title")}>
|
||||
<div className="portal-docs__toc-title">{t("portal.docs.toc.title")}</div>
|
||||
<ul className="portal-docs__toc-list">
|
||||
{headings.map((h) => (
|
||||
<li key={h.slug}>
|
||||
<a
|
||||
href={`#${h.slug}`}
|
||||
className={
|
||||
"portal-docs__toc-link" +
|
||||
(h.level === 3 ? " is-sub" : "") +
|
||||
(active === h.slug ? " is-active" : "")
|
||||
}
|
||||
aria-current={active === h.slug ? "location" : undefined}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onSelect(h.slug);
|
||||
}}
|
||||
>
|
||||
{h.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import { isValidElement, useState, type ReactNode } from "react";
|
||||
import ReactMarkdown, {
|
||||
defaultUrlTransform,
|
||||
type Components,
|
||||
} from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { Button } from "@app/ui";
|
||||
import { makeSlugger } from "@portal/docs/headings";
|
||||
|
||||
/** Flatten a heading's React children to plain text for its anchor id. */
|
||||
function childText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") return String(node);
|
||||
if (Array.isArray(node)) return node.map(childText).join("");
|
||||
if (isValidElement(node)) {
|
||||
return childText((node.props as { children?: ReactNode }).children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// Keep our internal `doc:` scheme; sanitize every other URL as react-markdown
|
||||
// would by default (it strips unknown protocols, which would kill doc: links).
|
||||
function urlTransform(url: string): string {
|
||||
return url.startsWith("doc:") ? url : defaultUrlTransform(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a doc's normalised markdown. Internal cross-doc links carry the
|
||||
* `doc:` scheme (see the sync transform) and are intercepted here so they
|
||||
* navigate within the portal instead of leaving the app.
|
||||
*/
|
||||
|
||||
function CopyButton({ text }: { text: string }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
return (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
size="sm"
|
||||
className="portal-docs__md-copy"
|
||||
onClick={() =>
|
||||
void navigator.clipboard.writeText(text).then(() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
})
|
||||
}
|
||||
>
|
||||
{copied ? "✓ Copied" : "Copy"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function buildComponents(
|
||||
onNavigate: (docId: string) => void,
|
||||
slug: (text: string) => string,
|
||||
): Components {
|
||||
return {
|
||||
h2: ({ children }) => <h2 id={slug(childText(children))}>{children}</h2>,
|
||||
h3: ({ children }) => <h3 id={slug(childText(children))}>{children}</h3>,
|
||||
a: ({ href, children }) => {
|
||||
if (href?.startsWith("doc:")) {
|
||||
const id = href.slice(4);
|
||||
return (
|
||||
<a
|
||||
href={`#${id}`}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
onNavigate(id);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
const external = /^https?:/i.test(href ?? "");
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target={external ? "_blank" : undefined}
|
||||
rel={external ? "noopener noreferrer" : undefined}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
},
|
||||
// Eager, not lazy: lazy-loading inside the docs' own scroll container isn't
|
||||
// reliably triggered, and docs pages have only a handful of images.
|
||||
img: ({ node: _node, ...props }) => (
|
||||
<img {...props} className="portal-docs__md-img" />
|
||||
),
|
||||
pre: ({ children }) => {
|
||||
const code = isValidElement(children)
|
||||
? String(
|
||||
(children.props as { children?: unknown }).children ?? "",
|
||||
).replace(/\n$/, "")
|
||||
: String(children ?? "");
|
||||
return (
|
||||
<div className="portal-docs__md-pre">
|
||||
<pre>{children}</pre>
|
||||
<CopyButton text={code} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
table: ({ children }) => (
|
||||
<div className="portal-docs__md-tablewrap">
|
||||
<table>{children}</table>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function MarkdownDoc({
|
||||
markdown,
|
||||
onNavigate,
|
||||
}: {
|
||||
markdown: string;
|
||||
onNavigate: (docId: string) => void;
|
||||
}) {
|
||||
// A fresh de-duping slugger per render; react-markdown invokes h2/h3 in
|
||||
// document order, so ids line up with the TOC's extractHeadings slugs.
|
||||
const slug = makeSlugger();
|
||||
return (
|
||||
<div className="portal-docs__md">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
urlTransform={urlTransform}
|
||||
components={buildComponents(onNavigate, slug)}
|
||||
>
|
||||
{markdown}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { Tooltip } from "@app/components/shared/Tooltip";
|
||||
import type { ToolRegistry } from "@app/data/toolsTaxonomy";
|
||||
import type { WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";
|
||||
import { PipelineStepSettings } from "@portal/components/pipelines/PipelineStepSettings";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, fallback?: string) => fallback ?? key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// A stand-in tool-settings UI that uses the shared editor Tooltip. The Tooltip
|
||||
// pulls in the Preferences + Sidebar contexts, which the portal does not mount
|
||||
// app-wide — so this reproduces the "usePreferences must be used within a
|
||||
// PreferencesProvider" crash unless PipelineStepSettings supplies them.
|
||||
function TooltipSettings() {
|
||||
return (
|
||||
<Tooltip content="help">
|
||||
<button type="button">field</button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
const step = {
|
||||
support: "editable",
|
||||
toolId: "compress",
|
||||
params: {},
|
||||
} as unknown as WorkingToolStep;
|
||||
|
||||
const registry = {
|
||||
compress: { automationSettings: TooltipSettings },
|
||||
} as unknown as Partial<ToolRegistry>;
|
||||
|
||||
describe("PipelineStepSettings", () => {
|
||||
it("renders reused editor tool settings (which use the shared Tooltip) without app-wide Preferences/Sidebar providers", () => {
|
||||
expect(() =>
|
||||
render(
|
||||
<MantineProvider>
|
||||
<PipelineStepSettings
|
||||
step={step}
|
||||
registry={registry}
|
||||
onChange={() => {}}
|
||||
/>
|
||||
</MantineProvider>,
|
||||
),
|
||||
).not.toThrow();
|
||||
expect(screen.getByText("field")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Suspense } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Banner } from "@app/ui";
|
||||
import { PreferencesProvider } from "@app/contexts/PreferencesContext";
|
||||
import { SidebarProvider } from "@app/contexts/SidebarContext";
|
||||
import { type ToolRegistry } from "@app/data/toolsTaxonomy";
|
||||
import { type ErasedToolParams } from "@app/hooks/tools/shared/toolOperationTypes";
|
||||
import { type WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";
|
||||
@@ -46,14 +48,18 @@ export function PipelineStepSettings({
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Settings
|
||||
parameters={step.params}
|
||||
onParameterChange={(key, value) =>
|
||||
onChange({ ...step.params, [key]: value })
|
||||
}
|
||||
disabled={false}
|
||||
/>
|
||||
</Suspense>
|
||||
<PreferencesProvider>
|
||||
<SidebarProvider>
|
||||
<Suspense fallback={null}>
|
||||
<Settings
|
||||
parameters={step.params}
|
||||
onParameterChange={(key, value) =>
|
||||
onChange({ ...step.params, [key]: value })
|
||||
}
|
||||
disabled={false}
|
||||
/>
|
||||
</Suspense>
|
||||
</SidebarProvider>
|
||||
</PreferencesProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
fireEvent,
|
||||
render as baseRender,
|
||||
screen,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
|
||||
import {
|
||||
POLICY_CATEGORIES,
|
||||
POLICY_CONFIG,
|
||||
type CatalogueEntry,
|
||||
type DecoratedPolicy,
|
||||
type PolicySetupResult,
|
||||
type PipelineStep,
|
||||
} from "@portal/api/policies";
|
||||
|
||||
const render = (ui: Parameters<typeof baseRender>[0]) =>
|
||||
baseRender(ui, { wrapper: MantineProvider });
|
||||
|
||||
// Deterministic i18n: return the fallback when given, else the key. initReactI18next is stubbed
|
||||
// because the import graph pulls core/i18n.ts, which registers it as a plugin.
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
// Second arg is a string fallback in some call sites and an interpolation object in others;
|
||||
// only treat a string as the fallback.
|
||||
t: (key: string, fallback?: unknown) =>
|
||||
typeof fallback === "string" ? fallback : key,
|
||||
i18n: { changeLanguage: vi.fn() },
|
||||
}),
|
||||
initReactI18next: { type: "3rdParty", init: vi.fn() },
|
||||
}));
|
||||
|
||||
const fetchSources = vi.fn();
|
||||
vi.mock("@portal/api/sources", () => ({
|
||||
fetchSources: () => fetchSources(),
|
||||
}));
|
||||
|
||||
const CONTINUE = "portal.policies.wizard.actions.continue";
|
||||
const SAVE_CHANGES = "portal.policies.wizard.actions.saveChanges";
|
||||
const ENABLE = "portal.policies.wizard.actions.enablePolicy";
|
||||
|
||||
const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
|
||||
const securityConfig = POLICY_CONFIG.security;
|
||||
|
||||
function editEntry(steps: PipelineStep[]): CatalogueEntry {
|
||||
const policy: DecoratedPolicy = {
|
||||
category: security,
|
||||
config: securityConfig,
|
||||
state: {
|
||||
configured: true,
|
||||
status: "active",
|
||||
sources: ["editor"],
|
||||
scopeTypes: [],
|
||||
reviewerEmail: "",
|
||||
fieldValues: {},
|
||||
runOn: "upload",
|
||||
outputMode: "new_version",
|
||||
outputName: "",
|
||||
outputNamePosition: "suffix",
|
||||
maxRetries: 0,
|
||||
retryDelayMinutes: 0,
|
||||
backendId: "pol-1",
|
||||
isDefault: true,
|
||||
},
|
||||
steps,
|
||||
stats: { enforced: 0, dataProcessed: "-", activeFor: "-" },
|
||||
activity: [],
|
||||
};
|
||||
return { category: security, config: securityConfig, policy };
|
||||
}
|
||||
|
||||
/** Advance the wizard from the workflow tab to the settings tab and submit. */
|
||||
async function submitWizard(saveLabel: string) {
|
||||
fireEvent.click(await screen.findByRole("button", { name: CONTINUE }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: saveLabel }));
|
||||
}
|
||||
|
||||
describe("PolicySetupWizard", () => {
|
||||
beforeEach(() => {
|
||||
fetchSources.mockResolvedValue({ sources: [] });
|
||||
});
|
||||
|
||||
it("round-trips a saved step's backend params on edit", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const entry = editEntry([
|
||||
{
|
||||
operation: "/api/v1/security/auto-redact",
|
||||
parameters: { listOfText: "foo\nbar", useRegex: true },
|
||||
},
|
||||
]);
|
||||
|
||||
render(
|
||||
<PolicySetupWizard entry={entry} onClose={vi.fn()} onSubmit={onSubmit} />,
|
||||
);
|
||||
await submitWizard(SAVE_CHANGES);
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
|
||||
const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
|
||||
// Only the saved tool is enabled on edit, and its patterns survive the wire -> UI -> wire trip.
|
||||
expect(result.steps).toEqual([
|
||||
expect.objectContaining({
|
||||
operation: "/api/v1/security/auto-redact",
|
||||
parameters: expect.objectContaining({ listOfText: "foo\nbar" }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("seeds the preset chain for a new policy (redact + sanitize on, watermark off)", async () => {
|
||||
const onSubmit = vi.fn().mockResolvedValue(undefined);
|
||||
const entry: CatalogueEntry = {
|
||||
category: security,
|
||||
config: securityConfig,
|
||||
policy: null,
|
||||
};
|
||||
|
||||
render(
|
||||
<PolicySetupWizard entry={entry} onClose={vi.fn()} onSubmit={onSubmit} />,
|
||||
);
|
||||
await submitWizard(ENABLE);
|
||||
|
||||
await waitFor(() => expect(onSubmit).toHaveBeenCalled());
|
||||
const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
|
||||
const endpoints = result.steps.map((s) => s.operation);
|
||||
expect(endpoints).toEqual([
|
||||
"/api/v1/security/auto-redact",
|
||||
"/api/v1/security/sanitize-pdf",
|
||||
]);
|
||||
// Redact carries the preset PII patterns as the backend's listOfText.
|
||||
const redact = result.steps[0].parameters as { listOfText?: string };
|
||||
expect(redact.listOfText).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -13,23 +13,24 @@ import {
|
||||
} from "@app/ui";
|
||||
import { SettingsRow } from "@app/ui/SettingsRow";
|
||||
import {
|
||||
TOOL_ENDPOINTS,
|
||||
humanizeEndpoint,
|
||||
type CatalogueEntry,
|
||||
type PipelineStep,
|
||||
type PolicySetupResult,
|
||||
} from "@portal/api/policies";
|
||||
import type { ToolRegistry, ToolRegistryEntry } from "@app/data/toolsTaxonomy";
|
||||
import {
|
||||
deserializeToolStep,
|
||||
serializeStepFromEndpoint,
|
||||
} from "@app/hooks/tools/shared/toolAutomation";
|
||||
policyEndpoint,
|
||||
policyStepFromWire,
|
||||
policyStepToWire,
|
||||
type PolicyParams,
|
||||
type PolicyToolId,
|
||||
type PolicyToolStep,
|
||||
} from "@app/policies/operations";
|
||||
import { fetchSources } from "@portal/api/sources";
|
||||
import { useAsync } from "@portal/hooks/useAsync";
|
||||
import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";
|
||||
import { policyIcon } from "@portal/components/policies/policyIcons";
|
||||
import { sourceTypeMeta } from "@portal/components/sources/sourceTypes";
|
||||
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
|
||||
import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
|
||||
import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
|
||||
import "@portal/views/Policies.css";
|
||||
@@ -47,12 +48,8 @@ interface PolicySetupWizardProps {
|
||||
|
||||
type Step = "workflow" | "settings";
|
||||
|
||||
/** A configurable tool in the workflow step: whether it runs + its params. */
|
||||
interface ToolState {
|
||||
operation: string;
|
||||
enabled: boolean;
|
||||
parameters: Record<string, unknown>;
|
||||
}
|
||||
/** A policy step plus whether it runs. */
|
||||
type ToolState = PolicyToolStep & { enabled: boolean };
|
||||
|
||||
/** Resolve each field's effective value: saved override, else definition default. */
|
||||
function resolveFieldValues(
|
||||
@@ -69,9 +66,8 @@ function resolveFieldValues(
|
||||
* round-trips); otherwise the category preset's default chain. Each preset step
|
||||
* starts enabled — the user toggles tools off in the workflow.
|
||||
*/
|
||||
// Temporary: tracks which tools start disabled until the tool registry lands in
|
||||
// the portal and can drive this via registry metadata or a defaultEnabled flag.
|
||||
const DISABLED_BY_DEFAULT = new Set(["/api/v1/security/add-watermark"]);
|
||||
// Temporary until the catalogue carries a defaultEnabled flag.
|
||||
const DISABLED_BY_DEFAULT = new Set<PolicyToolId>(["watermark"]);
|
||||
|
||||
/**
|
||||
* Policy-facing framing for each capability a policy can include. Labels and
|
||||
@@ -81,43 +77,43 @@ const DISABLED_BY_DEFAULT = new Set(["/api/v1/security/add-watermark"]);
|
||||
* the humanised endpoint name with no description.
|
||||
*/
|
||||
const CAPABILITY_META: Record<
|
||||
string,
|
||||
PolicyToolId,
|
||||
{ labelKey: string; labelEn: string; descKey: string; descEn: string }
|
||||
> = {
|
||||
[TOOL_ENDPOINTS.redact]: {
|
||||
redact: {
|
||||
labelKey: "portal.policies.wizard.capability.redact.label",
|
||||
labelEn: "Redact sensitive information",
|
||||
descKey: "portal.policies.wizard.capability.redact.desc",
|
||||
descEn:
|
||||
"Finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read.",
|
||||
},
|
||||
[TOOL_ENDPOINTS.sanitize]: {
|
||||
sanitize: {
|
||||
labelKey: "portal.policies.wizard.capability.sanitize.label",
|
||||
labelEn: "Strip active content",
|
||||
descKey: "portal.policies.wizard.capability.sanitize.desc",
|
||||
descEn:
|
||||
"Removes hidden JavaScript so nothing can run automatically when the document is opened.",
|
||||
},
|
||||
[TOOL_ENDPOINTS.watermark]: {
|
||||
watermark: {
|
||||
labelKey: "portal.policies.wizard.capability.watermark.label",
|
||||
labelEn: "Apply a watermark",
|
||||
descKey: "portal.policies.wizard.capability.watermark.desc",
|
||||
descEn: "Stamps a visible mark (e.g. “Confidential”) across every page.",
|
||||
},
|
||||
[TOOL_ENDPOINTS.ocr]: {
|
||||
ocr: {
|
||||
labelKey: "portal.policies.wizard.capability.ocr.label",
|
||||
labelEn: "Make text searchable",
|
||||
descKey: "portal.policies.wizard.capability.ocr.desc",
|
||||
descEn: "Runs OCR so scanned pages become selectable, searchable text.",
|
||||
},
|
||||
[TOOL_ENDPOINTS.flatten]: {
|
||||
flatten: {
|
||||
labelKey: "portal.policies.wizard.capability.flatten.label",
|
||||
labelEn: "Flatten the document",
|
||||
descKey: "portal.policies.wizard.capability.flatten.desc",
|
||||
descEn:
|
||||
"Merges form fields and annotations into the page so they can't be edited.",
|
||||
},
|
||||
[TOOL_ENDPOINTS.compress]: {
|
||||
compress: {
|
||||
labelKey: "portal.policies.wizard.capability.compress.label",
|
||||
labelEn: "Reduce file size",
|
||||
descKey: "portal.policies.wizard.capability.compress.desc",
|
||||
@@ -125,29 +121,24 @@ const CAPABILITY_META: Record<
|
||||
},
|
||||
};
|
||||
|
||||
function seedTools(
|
||||
entry: CatalogueEntry,
|
||||
registry: Partial<ToolRegistry>,
|
||||
): ToolState[] {
|
||||
function seedTools(entry: CatalogueEntry): ToolState[] {
|
||||
const savedSteps = entry.policy?.steps ?? [];
|
||||
const savedByOp = new Map(savedSteps.map((s) => [s.operation, s]));
|
||||
// Always use defaultOperations as the canonical list so tools added after a
|
||||
// policy was first saved still appear when editing.
|
||||
return entry.config.defaultOperations.map((s) => {
|
||||
const saved = savedByOp.get(s.operation);
|
||||
const savedByTool = new Map<PolicyToolId, PolicyToolStep>();
|
||||
for (const wire of savedSteps) {
|
||||
const step = policyStepFromWire(wire);
|
||||
if (step) savedByTool.set(step.toolId, step);
|
||||
}
|
||||
// defaultOperations is the canonical list (so tools added later still show on edit); a saved
|
||||
// step's params win over the preset.
|
||||
return entry.config.defaultOperations.map((preset) => {
|
||||
const saved = savedByTool.get(preset.toolId);
|
||||
return {
|
||||
operation: s.operation,
|
||||
...(saved ?? preset),
|
||||
enabled: saved
|
||||
? true
|
||||
: savedSteps.length > 0
|
||||
? false
|
||||
: !DISABLED_BY_DEFAULT.has(s.operation),
|
||||
// Saved steps are in the backend contract shape; map them back to the UI
|
||||
// shape the config controls edit (e.g. `listOfText` -> `wordsToRedact`).
|
||||
// Presets are already authored in the UI shape, so use them as-is.
|
||||
parameters: saved
|
||||
? deserializeToolStep(saved, registry).params
|
||||
: s.parameters,
|
||||
: !DISABLED_BY_DEFAULT.has(preset.toolId),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -185,26 +176,12 @@ function PolicySetupWizardBody({
|
||||
onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { allTools: toolRegistry } = useToolRegistry();
|
||||
|
||||
// Portal tool operations are endpoint paths (/api/v1/…), not short registry IDs.
|
||||
// Build a reverse map so we can look up icons and display names by endpoint.
|
||||
const registryByEndpoint = useMemo(() => {
|
||||
const map = new Map<string, ToolRegistryEntry>();
|
||||
for (const entry of Object.values(toolRegistry)) {
|
||||
const ep = (entry as ToolRegistryEntry).operationConfig?.endpoint;
|
||||
if (typeof ep === "string") map.set(ep, entry as ToolRegistryEntry);
|
||||
}
|
||||
return map;
|
||||
}, [toolRegistry]);
|
||||
|
||||
const { category, config, policy } = entry;
|
||||
const isEdit = policy != null;
|
||||
|
||||
const [step, setStep] = useState<Step>("workflow");
|
||||
const [tools, setTools] = useState<ToolState[]>(() =>
|
||||
seedTools(entry, toolRegistry),
|
||||
);
|
||||
const [tools, setTools] = useState<ToolState[]>(() => seedTools(entry));
|
||||
const [fieldValues, setFieldValues] = useState(() =>
|
||||
resolveFieldValues(entry),
|
||||
);
|
||||
@@ -213,22 +190,11 @@ function PolicySetupWizardBody({
|
||||
);
|
||||
|
||||
const sourcesAsync = useAsync(() => fetchSources(), []);
|
||||
const availableSources = useMemo(() => {
|
||||
const backendSources = (sourcesAsync.data?.sources ?? []).filter(
|
||||
(s) => s.status !== "disabled",
|
||||
);
|
||||
const editorSource = {
|
||||
id: "editor",
|
||||
name: t("portal.sources.types.editor.label"),
|
||||
type: "editor",
|
||||
status: "active" as const,
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [],
|
||||
docsTotal: null,
|
||||
};
|
||||
return [editorSource, ...backendSources];
|
||||
}, [sourcesAsync.data, t]);
|
||||
const availableSources = useMemo(
|
||||
() =>
|
||||
(sourcesAsync.data?.sources ?? []).filter((s) => s.status !== "disabled"),
|
||||
[sourcesAsync.data],
|
||||
);
|
||||
// Document-type scoping has no UI; preserve any saved scope on edit and
|
||||
// default new policies to all document types.
|
||||
const [scopeTypes] = useState<string[]>(policy?.state.scopeTypes ?? []);
|
||||
@@ -256,9 +222,20 @@ function PolicySetupWizardBody({
|
||||
|
||||
const enabledTools = useMemo(() => tools.filter((tl) => tl.enabled), [tools]);
|
||||
|
||||
function patchTool(operation: string, patch: Partial<ToolState>) {
|
||||
function setToolEnabled(toolId: PolicyToolId, enabled: boolean) {
|
||||
setTools((prev) =>
|
||||
prev.map((tl) => (tl.operation === operation ? { ...tl, ...patch } : tl)),
|
||||
prev.map((tl) => (tl.toolId === toolId ? { ...tl, enabled } : tl)),
|
||||
);
|
||||
}
|
||||
|
||||
function setToolParams<Id extends PolicyToolId>(
|
||||
toolId: Id,
|
||||
params: PolicyParams<Id>,
|
||||
) {
|
||||
setTools((prev) =>
|
||||
prev.map((tl) =>
|
||||
tl.toolId === toolId ? ({ ...tl, params } as ToolState) : tl,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -277,11 +254,8 @@ function PolicySetupWizardBody({
|
||||
}
|
||||
setError(null);
|
||||
setSubmitting(true);
|
||||
// Map each tool's UI-shaped params (e.g. redact's `wordsToRedact`) into the
|
||||
// backend step contract (e.g. `listOfText`) via its `toApiParams`; saving the
|
||||
// UI shape verbatim would drop those fields and the step would run with none.
|
||||
const steps: PipelineStep[] = enabledTools.map((tl) =>
|
||||
serializeStepFromEndpoint(tl.operation, tl.parameters, toolRegistry),
|
||||
policyStepToWire(tl),
|
||||
);
|
||||
try {
|
||||
await onSubmit(entry, {
|
||||
@@ -386,20 +360,16 @@ function PolicySetupWizardBody({
|
||||
<Card padding="none">
|
||||
<div className="portal-policies__capabilities">
|
||||
{tools.map((tl) => {
|
||||
const meta = CAPABILITY_META[tl.operation];
|
||||
const meta = CAPABILITY_META[tl.toolId];
|
||||
const label = meta
|
||||
? t(meta.labelKey, meta.labelEn)
|
||||
: (registryByEndpoint.get(tl.operation)?.name ??
|
||||
humanizeEndpoint(tl.operation, t));
|
||||
: humanizeEndpoint(policyEndpoint(tl.toolId), t);
|
||||
const description = meta
|
||||
? t(meta.descKey, meta.descEn)
|
||||
: undefined;
|
||||
const hasConfig =
|
||||
tl.operation === TOOL_ENDPOINTS.redact ||
|
||||
tl.operation === TOOL_ENDPOINTS.watermark;
|
||||
return (
|
||||
<div
|
||||
key={tl.operation}
|
||||
key={tl.toolId}
|
||||
className="portal-policies__capability"
|
||||
data-on={tl.enabled || undefined}
|
||||
>
|
||||
@@ -411,27 +381,27 @@ function PolicySetupWizardBody({
|
||||
size="sm"
|
||||
checked={tl.enabled}
|
||||
onChange={(checked) =>
|
||||
patchTool(tl.operation, { enabled: checked })
|
||||
setToolEnabled(tl.toolId, checked)
|
||||
}
|
||||
label=""
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{tl.enabled && hasConfig && (
|
||||
{tl.enabled && (
|
||||
<div className="portal-policies__capability-config">
|
||||
{tl.operation === TOOL_ENDPOINTS.redact && (
|
||||
{tl.toolId === "redact" && (
|
||||
<PolicyRedactConfig
|
||||
parameters={tl.parameters}
|
||||
onChange={(parameters) =>
|
||||
patchTool(tl.operation, { parameters })
|
||||
parameters={tl.params}
|
||||
onChange={(params) =>
|
||||
setToolParams("redact", params)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{tl.operation === TOOL_ENDPOINTS.watermark && (
|
||||
{tl.toolId === "watermark" && (
|
||||
<PolicyWatermarkConfig
|
||||
parameters={tl.parameters}
|
||||
onChange={(parameters) =>
|
||||
patchTool(tl.operation, { parameters })
|
||||
parameters={tl.params}
|
||||
onChange={(params) =>
|
||||
setToolParams("watermark", params)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
@@ -475,9 +445,8 @@ function PolicySetupWizardBody({
|
||||
{t("portal.policies.wizard.sources.loading")}
|
||||
</p>
|
||||
) : (
|
||||
// The editor is always an available source (unconditionally prepended
|
||||
// to availableSources), so the list is never empty — no "no sources"
|
||||
// state exists.
|
||||
// The backend always returns the editor as a virtual source, so the
|
||||
// loaded list is never empty - no "no sources" state exists.
|
||||
<div className="portal-policies__sources">
|
||||
{availableSources.map((src) => (
|
||||
// A selectable multi-line tile (icon + name + type + check).
|
||||
|
||||
@@ -20,6 +20,10 @@ export interface NavEntry {
|
||||
externalUrl?: string;
|
||||
}
|
||||
|
||||
// Developer docs has no built-in portal page yet, so the tab opens the hosted docs
|
||||
// site in a new tab rather than routing to an empty page.
|
||||
const DEVELOPER_DOCS_URL = "https://docs.stirlingpdf.com/";
|
||||
|
||||
// Sidebar nav groups. This is a flavor seam: the SaaS build shadows this file to
|
||||
// drop sections not yet shipped there (see src/portal-saas/components/sidebarGroups).
|
||||
export const GROUP_PRIMARY: NavEntry[] = [{ id: "home", icon: <HomeIcon /> }];
|
||||
@@ -36,5 +40,5 @@ export const GROUP_OPERATIONAL: NavEntry[] = [
|
||||
export const GROUP_PLATFORM: NavEntry[] = [
|
||||
{ id: "infrastructure", icon: <InfrastructureIcon /> },
|
||||
{ id: "usage", icon: <UsageIcon /> },
|
||||
{ id: "docs", icon: <DocsIcon /> },
|
||||
{ id: "docs", icon: <DocsIcon />, externalUrl: DEVELOPER_DOCS_URL },
|
||||
];
|
||||
|
||||
@@ -30,7 +30,7 @@ export const VIEW_LABELS: Record<ViewId, string> = {
|
||||
components: "Components",
|
||||
infrastructure: "Infrastructure",
|
||||
usage: "Usage & Billing",
|
||||
docs: "Documentation",
|
||||
docs: "Developer Docs",
|
||||
procurement: "Procurement",
|
||||
settings: "Settings",
|
||||
};
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { extractHeadings, slugify } from "@portal/docs/headings";
|
||||
|
||||
describe("slugify", () => {
|
||||
it("lowercases, hyphenates, and trims punctuation", () => {
|
||||
expect(slugify("How it Works!")).toBe("how-it-works");
|
||||
expect(slugify(" Trailing & spaces ")).toBe("trailing-spaces");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractHeadings", () => {
|
||||
it("extracts H2/H3 only, with slugs matching the rendered ids", () => {
|
||||
const md = [
|
||||
"# Page Title",
|
||||
"## How it Works",
|
||||
"text",
|
||||
"### Sub Section",
|
||||
"#### Too Deep",
|
||||
"## Operations",
|
||||
].join("\n");
|
||||
expect(extractHeadings(md)).toEqual([
|
||||
{ level: 2, text: "How it Works", slug: "how-it-works" },
|
||||
{ level: 3, text: "Sub Section", slug: "sub-section" },
|
||||
{ level: 2, text: "Operations", slug: "operations" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("de-duplicates repeated heading text into unique slugs", () => {
|
||||
const md = ["## What Changed", "### What Changed", "## What Changed"].join(
|
||||
"\n",
|
||||
);
|
||||
expect(extractHeadings(md).map((h) => h.slug)).toEqual([
|
||||
"what-changed",
|
||||
"what-changed-1",
|
||||
"what-changed-2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores headings inside fenced code and strips inline marks", () => {
|
||||
const md = ["```", "## not a heading", "```", "## `Code` and *em*"].join(
|
||||
"\n",
|
||||
);
|
||||
expect(extractHeadings(md)).toEqual([
|
||||
{ level: 2, text: "Code and em", slug: "code-and-em" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
/**
|
||||
* Heading extraction for the "On this page" table of contents. The same
|
||||
* `slugify` is used here and in MarkdownDoc's heading renderer, so the TOC links
|
||||
* and the rendered heading ids always match.
|
||||
*/
|
||||
|
||||
export interface Heading {
|
||||
/** 2 or 3 (H2/H3). */
|
||||
level: number;
|
||||
text: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
/** "How it Works!" → "how-it-works" (the base id, before de-duplication). */
|
||||
export function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* A stateful slugger that de-duplicates: repeated heading text gets `-1`, `-2`, …
|
||||
* The TOC extraction and MarkdownDoc's heading renderer each make one and feed it
|
||||
* headings in document order, so their slugs (and thus link ↔ id) always match.
|
||||
*/
|
||||
export function makeSlugger(): (text: string) => string {
|
||||
const seen = new Map<string, number>();
|
||||
return (text: string) => {
|
||||
const base = slugify(text) || "section";
|
||||
const n = seen.get(base) ?? 0;
|
||||
seen.set(base, n + 1);
|
||||
return n === 0 ? base : `${base}-${n}`;
|
||||
};
|
||||
}
|
||||
|
||||
/** Extract H2/H3 headings from a doc body, skipping fenced code blocks. */
|
||||
export function extractHeadings(markdown: string): Heading[] {
|
||||
const noCode = markdown.replace(/^(```|~~~)[\s\S]*?^\1[ \t]*$/gm, "");
|
||||
const slug = makeSlugger();
|
||||
const headings: Heading[] = [];
|
||||
for (const m of noCode.matchAll(/^ {0,3}(#{2,3})[ \t]+(.+?)[ \t]*#*$/gm)) {
|
||||
const text = m[2].replace(/[`*_]/g, "").trim();
|
||||
if (text) headings.push({ level: m[1].length, text, slug: slug(text) });
|
||||
}
|
||||
return headings;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
/**
|
||||
* Runtime accessors over the generated docs manifest. This is the only module
|
||||
* that imports the (large) JSON, so lazy-loading the docs view keeps it in its
|
||||
* own chunk. Regenerate the JSON with `npm run docs:sync`.
|
||||
*/
|
||||
// Imported as a raw string (not a JSON module) so tsc doesn't infer a ~half-MB
|
||||
// literal type; parsed once here into the typed manifest.
|
||||
import manifestRaw from "@portal/generated/docsManifest.json?raw";
|
||||
import type {
|
||||
DocEntry,
|
||||
DocsManifest,
|
||||
DocsNavSection,
|
||||
} from "@portal/docs/manifest/transform";
|
||||
|
||||
const manifest = JSON.parse(manifestRaw) as DocsManifest;
|
||||
|
||||
/** Provenance of the current manifest (repo + ref it was generated from). */
|
||||
export const docsSource = manifest.source;
|
||||
|
||||
/** The auto-sorted nav tree (sections → items). */
|
||||
export function loadDocsNav(): DocsNavSection[] {
|
||||
return manifest.nav;
|
||||
}
|
||||
|
||||
/** A single doc by id, or undefined if it isn't in the manifest. */
|
||||
export function loadDoc(id: string): DocEntry | undefined {
|
||||
return manifest.docs[id];
|
||||
}
|
||||
|
||||
/** Every doc, for building the search index. */
|
||||
export function allDocs(): DocEntry[] {
|
||||
return Object.values(manifest.docs);
|
||||
}
|
||||
|
||||
/** The first doc id (first item of the first section) — the default landing. */
|
||||
export function firstDocId(): string | undefined {
|
||||
return manifest.nav[0]?.items[0]?.id;
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildManifest,
|
||||
convertAdmonitions,
|
||||
demoteHeadings,
|
||||
docIdForPath,
|
||||
humanize,
|
||||
parseFrontmatter,
|
||||
resolveRelative,
|
||||
rewriteReferences,
|
||||
sectionIcon,
|
||||
stripJsxTags,
|
||||
stripMdxImports,
|
||||
stripRedundantH1,
|
||||
type CategoryMap,
|
||||
type RawDoc,
|
||||
} from "@portal/docs/manifest/transform";
|
||||
|
||||
const OPTS = {
|
||||
repo: "Owner/Repo",
|
||||
ref: "main",
|
||||
root: "docs",
|
||||
siteBaseUrl: "https://docs.example.com",
|
||||
};
|
||||
|
||||
describe("parseFrontmatter", () => {
|
||||
it("splits scalar YAML frontmatter from the body", () => {
|
||||
const { data, body } = parseFrontmatter(
|
||||
"---\ntitle: OCR\nsidebar_position: 7\n---\n# Heading\ntext",
|
||||
);
|
||||
expect(data.title).toBe("OCR");
|
||||
expect(data.sidebar_position).toBe(7);
|
||||
expect(body).toBe("# Heading\ntext");
|
||||
});
|
||||
|
||||
it("returns the whole content as body when there is no frontmatter", () => {
|
||||
const { data, body } = parseFrontmatter("# Just a doc\nbody");
|
||||
expect(data).toEqual({});
|
||||
expect(body).toBe("# Just a doc\nbody");
|
||||
});
|
||||
|
||||
it("normalises CRLF line endings", () => {
|
||||
const { data } = parseFrontmatter("---\r\nid: x\r\n---\r\nbody");
|
||||
expect(data.id).toBe("x");
|
||||
});
|
||||
});
|
||||
|
||||
describe("id + label helpers", () => {
|
||||
it("slugifies nested paths", () => {
|
||||
expect(docIdForPath("Configuration/OCR.md")).toBe("configuration/ocr");
|
||||
expect(docIdForPath("Getting Started.md")).toBe("getting-started");
|
||||
});
|
||||
|
||||
it("humanises file/dir names", () => {
|
||||
expect(humanize("Getting-Started.md")).toBe("Getting Started");
|
||||
});
|
||||
|
||||
it("picks a section icon from the label", () => {
|
||||
expect(sectionIcon("Configuration")).toBe("⚙");
|
||||
expect(sectionIcon("Totally Unknown")).toBe("◇");
|
||||
});
|
||||
});
|
||||
|
||||
describe("MDX normalisation", () => {
|
||||
it("converts admonitions to titled blockquotes", () => {
|
||||
const out = convertAdmonitions(":::tip Upgrading?\nread this\n:::");
|
||||
expect(out).toContain("> **💡 Tip: Upgrading?**");
|
||||
expect(out).toContain("> read this");
|
||||
});
|
||||
|
||||
it("strips import/export statements", () => {
|
||||
const out = stripMdxImports("import Tabs from '@theme/Tabs';\n# Keep");
|
||||
expect(out).toBe("# Keep");
|
||||
});
|
||||
|
||||
it("removes JSX component tags but keeps inner content", () => {
|
||||
expect(
|
||||
stripJsxTags("<Tabs>\n<TabItem value='a'>keep</TabItem>\n</Tabs>"),
|
||||
).toContain("keep");
|
||||
expect(stripJsxTags("<TabItem>x</TabItem>")).not.toMatch(/<TabItem/);
|
||||
});
|
||||
|
||||
it("demotes body H1 to H2 but leaves code comments alone", () => {
|
||||
const md = "# Title\n\n```bash\n# a shell comment\n```";
|
||||
const out = demoteHeadings(md);
|
||||
expect(out).toContain("## Title");
|
||||
expect(out).toContain("# a shell comment");
|
||||
});
|
||||
|
||||
it("strips a leading H1 that duplicates the page title", () => {
|
||||
expect(stripRedundantH1("# OCR\nbody", "OCR")).toBe("body");
|
||||
expect(stripRedundantH1("# Other\nbody", "OCR")).toBe("# Other\nbody");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveRelative", () => {
|
||||
it("collapses ./ and ../ against a base dir", () => {
|
||||
expect(resolveRelative("Configuration", "./OCR.md")).toBe(
|
||||
"Configuration/OCR.md",
|
||||
);
|
||||
expect(
|
||||
resolveRelative("Configuration", "../Functionality/Compare.md"),
|
||||
).toBe("Functionality/Compare.md");
|
||||
});
|
||||
});
|
||||
|
||||
describe("rewriteReferences", () => {
|
||||
const ctx = {
|
||||
dir: "Configuration",
|
||||
// Keys are lowercased file paths (spaces preserved), as buildManifest builds them.
|
||||
pathToId: new Map([
|
||||
[
|
||||
"configuration/system and security",
|
||||
"configuration/system-and-security",
|
||||
],
|
||||
]),
|
||||
rawBase: "https://raw.example.com/Owner/Repo/main",
|
||||
siteBaseUrl: "https://docs.example.com",
|
||||
};
|
||||
|
||||
it("rewrites resolvable internal links to the doc: scheme (decoded + case-insensitive)", () => {
|
||||
const out = rewriteReferences(
|
||||
"see [sec](./System%20and%20Security.md)",
|
||||
ctx,
|
||||
"docs",
|
||||
);
|
||||
expect(out).toBe("see [sec](doc:configuration/system-and-security)");
|
||||
});
|
||||
|
||||
it("falls back to the live docs site for unresolved internal links", () => {
|
||||
const out = rewriteReferences("[x](./Missing.md)", ctx, "docs");
|
||||
expect(out).toBe("[x](https://docs.example.com/Configuration/Missing)");
|
||||
});
|
||||
|
||||
it("leaves absolute and anchor links untouched", () => {
|
||||
const md = "[a](https://x.com) and [b](#top)";
|
||||
expect(rewriteReferences(md, ctx, "docs")).toBe(md);
|
||||
});
|
||||
|
||||
it("rewrites relative images to absolute raw URLs", () => {
|
||||
expect(rewriteReferences("", ctx, "docs")).toBe(
|
||||
"",
|
||||
);
|
||||
expect(rewriteReferences("", ctx, "docs")).toBe(
|
||||
"",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not rewrite inside fenced code blocks", () => {
|
||||
const md = "```\n[x](./y.md)\n```";
|
||||
expect(rewriteReferences(md, ctx, "docs")).toBe(md);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildManifest", () => {
|
||||
const rawDocs: RawDoc[] = [
|
||||
{
|
||||
relPath: "Getting Started.md",
|
||||
content: "---\nsidebar_position: 0\n---\nintro",
|
||||
},
|
||||
{
|
||||
relPath: "Configuration/OCR.md",
|
||||
content: "---\ntitle: OCR\nsidebar_position: 7\n---\n# OCR\nbody",
|
||||
},
|
||||
{
|
||||
relPath: "Configuration/DATABASE.md",
|
||||
content: "---\nsidebar_position: 1\n---\n# Database\nsee [ocr](./OCR.md)",
|
||||
},
|
||||
];
|
||||
const categories: CategoryMap = {
|
||||
Configuration: { label: "Configuration", position: 5 },
|
||||
};
|
||||
|
||||
it("auto-sorts sections (root Overview first, then by category position)", () => {
|
||||
const m = buildManifest(rawDocs, categories, OPTS);
|
||||
expect(m.nav.map((s) => s.id)).toEqual(["overview", "configuration"]);
|
||||
expect(m.nav[0].label).toBe("Overview");
|
||||
expect(m.nav[1].label).toBe("Configuration");
|
||||
});
|
||||
|
||||
it("orders nav items by sidebar_position", () => {
|
||||
const m = buildManifest(rawDocs, categories, OPTS);
|
||||
const config = m.nav.find((s) => s.id === "configuration")!;
|
||||
expect(config.items.map((i) => i.id)).toEqual([
|
||||
"configuration/database",
|
||||
"configuration/ocr",
|
||||
]);
|
||||
});
|
||||
|
||||
it("derives titles from frontmatter, heading, then filename", () => {
|
||||
const m = buildManifest(rawDocs, categories, OPTS);
|
||||
expect(m.docs["configuration/ocr"].title).toBe("OCR");
|
||||
expect(m.docs["getting-started"].title).toBe("Getting Started");
|
||||
});
|
||||
|
||||
it("resolves cross-doc links and records source/edit urls", () => {
|
||||
const m = buildManifest(rawDocs, categories, OPTS);
|
||||
expect(m.docs["configuration/database"].markdown).toContain(
|
||||
"[ocr](doc:configuration/ocr)",
|
||||
);
|
||||
expect(m.docs["configuration/ocr"].sourcePath).toBe(
|
||||
"docs/Configuration/OCR.md",
|
||||
);
|
||||
expect(m.docs["configuration/ocr"].editUrl).toBe(
|
||||
"https://github.com/Owner/Repo/blob/main/docs/Configuration/OCR.md",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,481 +0,0 @@
|
||||
/**
|
||||
* Pure transforms that turn the Docusaurus docs repo into the portal docs
|
||||
* manifest. No I/O and no external deps so `tsx` (the sync CLI) and vitest can
|
||||
* both use it. The sync CLI does the fetching; this module does the shaping.
|
||||
*
|
||||
* The auto-sort rules:
|
||||
* - every directory that directly holds markdown becomes a nav section,
|
||||
* labelled + ordered by its `_category_.json` (root files → "Overview"),
|
||||
* - each `.md`/`.mdx` file becomes a nav item, ordered by frontmatter
|
||||
* `sidebar_position` then title,
|
||||
* - Docusaurus MDX is normalised to plain GitHub-flavoured markdown that
|
||||
* react-markdown can render (admonitions, JSX, relative links, images).
|
||||
*/
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Manifest shape (mirrored structurally by @portal/api/docs) */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export interface DocsNavItem {
|
||||
id: string;
|
||||
label: string;
|
||||
badge?: string;
|
||||
}
|
||||
|
||||
export interface DocsNavSection {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: string;
|
||||
items: DocsNavItem[];
|
||||
}
|
||||
|
||||
export interface DocEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
section: string;
|
||||
markdown: string;
|
||||
sourcePath: string;
|
||||
editUrl: string;
|
||||
}
|
||||
|
||||
export interface DocsManifest {
|
||||
source: { repo: string; ref: string; root: string };
|
||||
nav: DocsNavSection[];
|
||||
docs: Record<string, DocEntry>;
|
||||
}
|
||||
|
||||
/** One markdown file read from the repo, before shaping. */
|
||||
export interface RawDoc {
|
||||
/** Posix path relative to the docs root, e.g. "Configuration/OCR.md". */
|
||||
relPath: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** `_category_.json` contents, keyed by posix dir path relative to docs root. */
|
||||
export type CategoryMap = Record<string, { label?: string; position?: number }>;
|
||||
|
||||
export interface BuildOptions {
|
||||
repo: string;
|
||||
ref: string;
|
||||
/** Docs root within the repo, e.g. "docs". */
|
||||
root: string;
|
||||
/** Live docs site base, used as the fallback for unresolved internal links. */
|
||||
siteBaseUrl: string;
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Small helpers */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
const SECTION_ICONS: Array<[RegExp, string]> = [
|
||||
[/overview|getting started|start/i, "▶"],
|
||||
[/config/i, "⚙"],
|
||||
[/function|tool|feature/i, "▤"],
|
||||
[/install|deploy/i, "⤓"],
|
||||
[/migrat|upgrade/i, "⇄"],
|
||||
[/security|sign|auth/i, "🛡"],
|
||||
[/convert/i, "⇋"],
|
||||
[/page/i, "▦"],
|
||||
[/api|develop/i, "{ }"],
|
||||
];
|
||||
|
||||
/** A single-glyph icon for a section, chosen from its label. */
|
||||
export function sectionIcon(label: string): string {
|
||||
for (const [re, glyph] of SECTION_ICONS) if (re.test(label)) return glyph;
|
||||
return "◇";
|
||||
}
|
||||
|
||||
/** "Getting-Started_Guide" → "Getting Started Guide". */
|
||||
export function humanize(name: string): string {
|
||||
return name
|
||||
.replace(/\.mdx?$/i, "")
|
||||
.replace(/[-_]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
/** Lowercase, hyphenated, url-safe id for a path segment. */
|
||||
export function slugifySegment(name: string): string {
|
||||
return name
|
||||
.replace(/\.mdx?$/i, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/** Docs-root-relative posix path → stable doc id, e.g. "configuration/ocr". */
|
||||
export function docIdForPath(relPath: string): string {
|
||||
return relPath.split("/").map(slugifySegment).filter(Boolean).join("/");
|
||||
}
|
||||
|
||||
/** Posix dirname ("" for a root-level file). */
|
||||
export function dirOf(relPath: string): string {
|
||||
const i = relPath.lastIndexOf("/");
|
||||
return i === -1 ? "" : relPath.slice(0, i);
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Frontmatter */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export interface Frontmatter {
|
||||
data: Record<string, string | number>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
/** Split leading `--- ... ---` YAML frontmatter (scalar keys only) from body. */
|
||||
export function parseFrontmatter(content: string): Frontmatter {
|
||||
const normalised = content.replace(/\r\n/g, "\n");
|
||||
if (!normalised.startsWith("---\n")) return { data: {}, body: normalised };
|
||||
const end = normalised.indexOf("\n---", 4);
|
||||
if (end === -1) return { data: {}, body: normalised };
|
||||
const raw = normalised.slice(4, end);
|
||||
const rest = normalised.slice(end + 4).replace(/^\n/, "");
|
||||
const data: Record<string, string | number> = {};
|
||||
for (const line of raw.split("\n")) {
|
||||
const m = /^([A-Za-z0-9_]+):\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
let value: string | number = m[2].trim().replace(/^["']|["']$/g, "");
|
||||
if (/^-?\d+(\.\d+)?$/.test(value)) value = Number(value);
|
||||
data[m[1]] = value;
|
||||
}
|
||||
return { data, body: rest };
|
||||
}
|
||||
|
||||
/** First `# H1` heading text in a body, if any. */
|
||||
export function firstHeading(body: string): string | undefined {
|
||||
const m = /^#\s+(.+?)\s*$/m.exec(stripCodeFences(body));
|
||||
return m ? m[1].trim() : undefined;
|
||||
}
|
||||
|
||||
/** Blank out fenced code blocks so heading/link scans ignore their contents. */
|
||||
function stripCodeFences(md: string): string {
|
||||
return md.replace(/^(```|~~~)[\s\S]*?^\1\s*$/gm, "");
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Body normalisation (MDX → plain markdown) */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/** Run `fn` over the non-fenced-code spans of `md`, leaving code blocks intact. */
|
||||
function mapOutsideCode(md: string, fn: (text: string) => string): string {
|
||||
const parts = md.split(/(^(?:```|~~~)[\s\S]*?^(?:```|~~~)\s*$)/gm);
|
||||
return parts.map((part, i) => (i % 2 === 0 ? fn(part) : part)).join("");
|
||||
}
|
||||
|
||||
const ADMONITION_META: Record<string, { icon: string; label: string }> = {
|
||||
tip: { icon: "💡", label: "Tip" },
|
||||
note: { icon: "📝", label: "Note" },
|
||||
info: { icon: "ℹ️", label: "Info" },
|
||||
warning: { icon: "⚠️", label: "Warning" },
|
||||
caution: { icon: "⚠️", label: "Caution" },
|
||||
danger: { icon: "🚫", label: "Danger" },
|
||||
};
|
||||
|
||||
/** `:::tip Title\n…\n:::` → a blockquote with a bold titled first line. */
|
||||
export function convertAdmonitions(md: string): string {
|
||||
const re = /^:::(\w+)[ \t]*(.*)\n([\s\S]*?)^:::[ \t]*$/gm;
|
||||
return md.replace(re, (_all, type: string, title: string, body: string) => {
|
||||
const meta = ADMONITION_META[type.toLowerCase()] ?? {
|
||||
icon: "•",
|
||||
label: humanize(type),
|
||||
};
|
||||
const heading = title.trim()
|
||||
? `${meta.label}: ${title.trim()}`
|
||||
: meta.label;
|
||||
const quoted = body
|
||||
.replace(/\s+$/, "")
|
||||
.split("\n")
|
||||
.map((l) => (l ? `> ${l}` : ">"))
|
||||
.join("\n");
|
||||
return `> **${meta.icon} ${heading}**\n>\n${quoted}\n`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Drop MDX `import`/`export` statement lines (outside code). */
|
||||
export function stripMdxImports(md: string): string {
|
||||
return md
|
||||
.split("\n")
|
||||
.filter((l) => !/^\s*(import|export)\s.+from\s.+;?\s*$/.test(l))
|
||||
.filter((l) => !/^\s*import\s+['"][^'"]+['"];?\s*$/.test(l))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** Remove JSX component tags (Capitalised), keeping any inner content. */
|
||||
export function stripJsxTags(md: string): string {
|
||||
return md.replace(/<\/?[A-Z][A-Za-z0-9.]*(?:\s[^>]*?)?\/?>/g, "");
|
||||
}
|
||||
|
||||
/** Resolve a relative posix path against a base dir, collapsing `.`/`..`. */
|
||||
export function resolveRelative(baseDir: string, target: string): string {
|
||||
const stack = baseDir ? baseDir.split("/") : [];
|
||||
for (const seg of target.split("/")) {
|
||||
if (seg === "" || seg === ".") continue;
|
||||
if (seg === "..") stack.pop();
|
||||
else stack.push(seg);
|
||||
}
|
||||
return stack.join("/");
|
||||
}
|
||||
|
||||
interface LinkContext {
|
||||
dir: string;
|
||||
pathToId: Map<string, string>;
|
||||
rawBase: string;
|
||||
siteBaseUrl: string;
|
||||
}
|
||||
|
||||
/** Split "path#anchor" → [path, "#anchor" | ""]. */
|
||||
function splitAnchor(target: string): [string, string] {
|
||||
const i = target.indexOf("#");
|
||||
return i === -1 ? [target, ""] : [target.slice(0, i), target.slice(i)];
|
||||
}
|
||||
|
||||
/** Percent-decode a link path, tolerating malformed escapes. */
|
||||
function decodePath(p: string): string {
|
||||
try {
|
||||
return decodeURIComponent(p);
|
||||
} catch {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the doc id for a relative link target. Keys in pathToId are lowercased
|
||||
* so links work whether they use the filename or a slug, in any case, and with
|
||||
* percent-encoded spaces (the repo links to "System%20and%20Security").
|
||||
*/
|
||||
function resolveDocId(ctx: LinkContext, rawPath: string): string | undefined {
|
||||
const resolved = resolveRelative(ctx.dir, decodePath(rawPath)).toLowerCase();
|
||||
const noExt = resolved.replace(/\.mdx?$/i, "");
|
||||
const candidates = [
|
||||
resolved,
|
||||
noExt,
|
||||
`${noExt.replace(/\/$/, "")}/index`,
|
||||
noExt.replace(/\/index$/i, ""),
|
||||
];
|
||||
for (const c of candidates) {
|
||||
const id = ctx.pathToId.get(c);
|
||||
if (id) return id;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Rewrite a single markdown link target to a portal-usable href. */
|
||||
function rewriteLinkTarget(ctx: LinkContext, target: string): string {
|
||||
const trimmed = target.trim();
|
||||
if (/^(https?:|mailto:|tel:|#|doc:)/i.test(trimmed)) return trimmed;
|
||||
const [path, anchor] = splitAnchor(trimmed);
|
||||
if (!path) return trimmed;
|
||||
const id = resolveDocId(ctx, path);
|
||||
if (id) return `doc:${id}`;
|
||||
// Unresolved internal link → fall back to the live docs site (encode spaces).
|
||||
const slug = resolveRelative(ctx.dir, decodePath(path)).replace(
|
||||
/\.mdx?$/i,
|
||||
"",
|
||||
);
|
||||
const encoded = slug.split("/").map(encodeURIComponent).join("/");
|
||||
return `${ctx.siteBaseUrl}/${encoded}${anchor}`;
|
||||
}
|
||||
|
||||
/** Rewrite a relative image src to an absolute raw-content URL. */
|
||||
function rewriteImageSrc(ctx: LinkContext, src: string, root: string): string {
|
||||
const trimmed = src.trim();
|
||||
if (/^(https?:|data:)/i.test(trimmed)) return trimmed;
|
||||
if (trimmed.startsWith("/")) return `${ctx.rawBase}/static${trimmed}`;
|
||||
const resolved = resolveRelative(`${root}/${ctx.dir}`, trimmed);
|
||||
return `${ctx.rawBase}/${resolved}`;
|
||||
}
|
||||
|
||||
/** Rewrite markdown links + images (outside code) to portal/absolute targets. */
|
||||
export function rewriteReferences(
|
||||
md: string,
|
||||
ctx: LinkContext,
|
||||
root: string,
|
||||
): string {
|
||||
return mapOutsideCode(md, (text) => {
|
||||
// Images first so their `!` prefix isn't eaten by the link pattern.
|
||||
let out = text.replace(
|
||||
/!\[([^\]]*)\]\(([^)\s]+)([^)]*)\)/g,
|
||||
(_m, alt: string, src: string, tail: string) =>
|
||||
`}${tail})`,
|
||||
);
|
||||
out = out.replace(
|
||||
/(^|[^!])\[([^\]]+)\]\(([^)\s]+)([^)]*)\)/g,
|
||||
(_m, pre: string, label: string, href: string, tail: string) =>
|
||||
`${pre}[${label}](${rewriteLinkTarget(ctx, href)}${tail})`,
|
||||
);
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
/** Drop a leading `# H1` whose text equals the page title (avoids a dup head). */
|
||||
export function stripRedundantH1(md: string, title: string): string {
|
||||
const m = /^\s*#\s+(.+?)\s*(\n|$)/.exec(md);
|
||||
if (m && m[1].trim().toLowerCase() === title.trim().toLowerCase()) {
|
||||
return md.slice(m[0].length).replace(/^\n+/, "");
|
||||
}
|
||||
return md;
|
||||
}
|
||||
|
||||
/** Demote body `# H1` headings to `## H2` so the page title is the sole H1. */
|
||||
export function demoteHeadings(md: string): string {
|
||||
return mapOutsideCode(md, (text) => text.replace(/^# (?=\S)/gm, "## "));
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Section ordering */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
const ROOT_SECTION_ID = "overview";
|
||||
|
||||
/** Composite order key: `_category_.json.position` down the dir path. */
|
||||
function sectionOrderKey(dir: string, categories: CategoryMap): number[] {
|
||||
if (dir === "") return [-1];
|
||||
const key: number[] = [];
|
||||
const segs = dir.split("/");
|
||||
for (let i = 0; i < segs.length; i++) {
|
||||
const sub = segs.slice(0, i + 1).join("/");
|
||||
key.push(categories[sub]?.position ?? 999);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function compareKeys(a: number[], b: number[]): number {
|
||||
const n = Math.max(a.length, b.length);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const d = (a[i] ?? 0) - (b[i] ?? 0);
|
||||
if (d !== 0) return d;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Build */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
interface ShapedDoc extends DocEntry {
|
||||
navLabel: string;
|
||||
sidebarPosition: number;
|
||||
orderKey: number[];
|
||||
sectionLabel: string;
|
||||
}
|
||||
|
||||
/** Turn raw docs + category metadata into the full portal docs manifest. */
|
||||
export function buildManifest(
|
||||
rawDocs: RawDoc[],
|
||||
categories: CategoryMap,
|
||||
opts: BuildOptions,
|
||||
): DocsManifest {
|
||||
const rawBase = `https://raw.githubusercontent.com/${opts.repo}/${opts.ref}`;
|
||||
const editBase = `https://github.com/${opts.repo}/blob/${opts.ref}`;
|
||||
|
||||
// First pass: assign stable ids so links between docs can resolve. Keys are
|
||||
// lowercased (case-insensitive link matching); both with and without ext.
|
||||
const pathToId = new Map<string, string>();
|
||||
for (const doc of rawDocs) {
|
||||
const id = docIdForPath(doc.relPath);
|
||||
const lower = doc.relPath.toLowerCase();
|
||||
pathToId.set(lower, id);
|
||||
pathToId.set(lower.replace(/\.mdx?$/i, ""), id);
|
||||
}
|
||||
|
||||
const shaped: ShapedDoc[] = rawDocs.map((doc) => {
|
||||
const dir = dirOf(doc.relPath);
|
||||
const { data, body } = parseFrontmatter(doc.content);
|
||||
const title =
|
||||
(typeof data.title === "string" && data.title) ||
|
||||
firstHeading(body) ||
|
||||
humanize(doc.relPath.split("/").pop() ?? doc.relPath);
|
||||
const navLabel =
|
||||
(typeof data.sidebar_label === "string" && data.sidebar_label) || title;
|
||||
const description =
|
||||
typeof data.description === "string" ? data.description : undefined;
|
||||
|
||||
const ctx: LinkContext = {
|
||||
dir,
|
||||
pathToId,
|
||||
rawBase,
|
||||
siteBaseUrl: opts.siteBaseUrl.replace(/\/$/, ""),
|
||||
};
|
||||
let markdown = body;
|
||||
markdown = stripMdxImports(markdown);
|
||||
markdown = convertAdmonitions(markdown);
|
||||
markdown = stripJsxTags(markdown);
|
||||
markdown = rewriteReferences(markdown, ctx, opts.root);
|
||||
markdown = stripRedundantH1(markdown, title);
|
||||
markdown = demoteHeadings(markdown).trim();
|
||||
|
||||
const sectionId = dir === "" ? ROOT_SECTION_ID : docIdForPath(dir);
|
||||
const sectionLabel =
|
||||
dir === ""
|
||||
? "Overview"
|
||||
: (categories[dir]?.label ?? humanize(dir.split("/").pop() ?? dir));
|
||||
|
||||
return {
|
||||
id: docIdForPath(doc.relPath),
|
||||
title,
|
||||
navLabel,
|
||||
description,
|
||||
section: sectionId,
|
||||
markdown,
|
||||
sourcePath: `${opts.root}/${doc.relPath}`,
|
||||
editUrl: `${editBase}/${opts.root}/${doc.relPath}`,
|
||||
sidebarPosition:
|
||||
typeof data.sidebar_position === "number" ? data.sidebar_position : 999,
|
||||
orderKey: sectionOrderKey(dir, categories),
|
||||
sectionLabel,
|
||||
};
|
||||
});
|
||||
|
||||
// Group into sections and order everything deterministically.
|
||||
const bySection = new Map<string, ShapedDoc[]>();
|
||||
for (const doc of shaped) {
|
||||
const list = bySection.get(doc.section) ?? [];
|
||||
list.push(doc);
|
||||
bySection.set(doc.section, list);
|
||||
}
|
||||
|
||||
const nav: DocsNavSection[] = [...bySection.entries()]
|
||||
.map(([id, docs]) => {
|
||||
const first = docs[0];
|
||||
const items = [...docs]
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.sidebarPosition - b.sidebarPosition ||
|
||||
a.navLabel.localeCompare(b.navLabel),
|
||||
)
|
||||
.map<DocsNavItem>((d) => ({ id: d.id, label: d.navLabel }));
|
||||
return {
|
||||
id,
|
||||
label: first.sectionLabel,
|
||||
icon: sectionIcon(first.sectionLabel),
|
||||
items,
|
||||
_key: first.orderKey,
|
||||
};
|
||||
})
|
||||
.sort(
|
||||
(a, b) => compareKeys(a._key, b._key) || a.label.localeCompare(b.label),
|
||||
)
|
||||
.map(({ _key, ...section }) => section);
|
||||
|
||||
const docs: Record<string, DocEntry> = {};
|
||||
for (const d of shaped) {
|
||||
docs[d.id] = {
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
description: d.description,
|
||||
section: d.section,
|
||||
markdown: d.markdown,
|
||||
sourcePath: d.sourcePath,
|
||||
editUrl: d.editUrl,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
source: { repo: opts.repo, ref: opts.ref, root: opts.root },
|
||||
nav,
|
||||
docs,
|
||||
};
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildSnippet,
|
||||
highlight,
|
||||
searchDocs,
|
||||
toPlainText,
|
||||
type SearchDoc,
|
||||
} from "@portal/docs/search";
|
||||
|
||||
const DOCS: SearchDoc[] = [
|
||||
{
|
||||
id: "ocr",
|
||||
title: "OCR Guide",
|
||||
sectionLabel: "Configuration",
|
||||
text: "Stirling PDF uses Tesseract for its text recognition and language packs.",
|
||||
},
|
||||
{
|
||||
id: "docker",
|
||||
title: "Docker Install",
|
||||
sectionLabel: "Installation",
|
||||
text: "Run Stirling with docker compose up to start the container.",
|
||||
},
|
||||
{
|
||||
id: "ranky",
|
||||
title: "Something else",
|
||||
sectionLabel: "Misc",
|
||||
text: "docker docker docker appears many times in the body here.",
|
||||
},
|
||||
];
|
||||
|
||||
describe("toPlainText", () => {
|
||||
it("strips headings, links, inline code, and code fences", () => {
|
||||
const md =
|
||||
"# Title\n\nSee [the guide](doc:x) and run `npm i`.\n\n```bash\nnpm run build\n```";
|
||||
const out = toPlainText(md);
|
||||
expect(out).toContain("Title");
|
||||
expect(out).toContain("the guide");
|
||||
expect(out).toContain("npm i");
|
||||
expect(out).toContain("npm run build"); // code text kept, fences dropped
|
||||
expect(out).not.toContain("#");
|
||||
expect(out).not.toContain("```");
|
||||
expect(out).not.toContain("](");
|
||||
});
|
||||
});
|
||||
|
||||
describe("highlight", () => {
|
||||
it("splits text into hit/non-hit segments", () => {
|
||||
expect(highlight("Hello world", ["world"])).toEqual([
|
||||
{ text: "Hello ", hit: false },
|
||||
{ text: "world", hit: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("is safe against regex metacharacters in terms", () => {
|
||||
expect(() => highlight("a (b) c", ["("])).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSnippet", () => {
|
||||
it("windows around the first match and marks it", () => {
|
||||
const text =
|
||||
"lorem ipsum ".repeat(20) + "the TARGET keyword " + "dolor ".repeat(20);
|
||||
const segs = buildSnippet(text, ["target"]);
|
||||
expect(segs.some((s) => s.hit && /target/i.test(s.text))).toBe(true);
|
||||
// Windowed, so it should be far shorter than the full text.
|
||||
expect(segs.map((s) => s.text).join("").length).toBeLessThan(text.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("searchDocs", () => {
|
||||
it("returns nothing for an empty query", () => {
|
||||
expect(searchDocs(DOCS, " ")).toEqual([]);
|
||||
});
|
||||
|
||||
it("matches body content, not just titles (with a snippet)", () => {
|
||||
const res = searchDocs(DOCS, "tesseract");
|
||||
expect(res.map((r) => r.id)).toEqual(["ocr"]);
|
||||
expect(res[0].snippet.some((s) => s.hit && /tesseract/i.test(s.text))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("ranks title matches above body matches", () => {
|
||||
const res = searchDocs(DOCS, "docker");
|
||||
// "Docker Install" (title hit) outranks "Something else" (body-only hits).
|
||||
expect(res[0].id).toBe("docker");
|
||||
expect(res.map((r) => r.id)).toContain("ranky");
|
||||
});
|
||||
|
||||
it("requires every term to match (AND)", () => {
|
||||
expect(searchDocs(DOCS, "docker compose").map((r) => r.id)).toEqual([
|
||||
"docker",
|
||||
]);
|
||||
expect(searchDocs(DOCS, "docker tesseract")).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not throw on regex-special-character queries", () => {
|
||||
expect(() => searchDocs(DOCS, "a(b")).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
/**
|
||||
* Full-text search over the docs manifest. Pure + dependency-free so it's unit
|
||||
* testable. Indexes each doc's title + plaintext body; ranks title matches above
|
||||
* body matches; returns highlighted title + a content snippet per hit.
|
||||
*/
|
||||
|
||||
export interface SearchDoc {
|
||||
id: string;
|
||||
title: string;
|
||||
sectionLabel: string;
|
||||
/** Plaintext body (markdown stripped), original case. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** A run of result text, flagged when it matches a query term (for <mark>). */
|
||||
export interface Segment {
|
||||
text: string;
|
||||
hit: boolean;
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
id: string;
|
||||
title: string;
|
||||
sectionLabel: string;
|
||||
titleSegments: Segment[];
|
||||
snippet: Segment[];
|
||||
score: number;
|
||||
}
|
||||
|
||||
/** Strip markdown/MDX down to readable plaintext for indexing + snippets. */
|
||||
export function toPlainText(md: string): string {
|
||||
return md
|
||||
.replace(/^(```|~~~).*$/gm, " ") // fence delimiters (keep the code text)
|
||||
.replace(/`([^`]+)`/g, "$1") // inline code
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ") // images
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") // links → their text
|
||||
.replace(/^\s{0,3}>\s?/gm, "") // blockquotes
|
||||
.replace(/^\s{0,3}#{1,6}\s+/gm, "") // headings
|
||||
.replace(/^\s*[-*+]\s+/gm, "") // list bullets
|
||||
.replace(/[*_~]/g, "") // emphasis marks
|
||||
.replace(/\|/g, " ") // table pipes
|
||||
.replace(/\s+/g, " ") // collapse whitespace
|
||||
.trim();
|
||||
}
|
||||
|
||||
function escapeRegExp(s: string): string {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function countOccurrences(haystack: string, needle: string): number {
|
||||
let count = 0;
|
||||
let i = haystack.indexOf(needle);
|
||||
while (i !== -1) {
|
||||
count++;
|
||||
i = haystack.indexOf(needle, i + needle.length);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Split `text` into segments, flagging any run that matches a query term. */
|
||||
export function highlight(text: string, terms: string[]): Segment[] {
|
||||
const cleaned = terms.map(escapeRegExp).filter(Boolean);
|
||||
if (!cleaned.length) return [{ text, hit: false }];
|
||||
const re = new RegExp(`(${cleaned.join("|")})`, "gi");
|
||||
const segments: Segment[] = [];
|
||||
let last = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (m.index > last) {
|
||||
segments.push({ text: text.slice(last, m.index), hit: false });
|
||||
}
|
||||
segments.push({ text: m[0], hit: true });
|
||||
last = m.index + m[0].length;
|
||||
if (m.index === re.lastIndex) re.lastIndex++; // guard against zero-width
|
||||
}
|
||||
if (last < text.length) segments.push({ text: text.slice(last), hit: false });
|
||||
return segments.length ? segments : [{ text, hit: false }];
|
||||
}
|
||||
|
||||
/** Build a ~context-window snippet around the earliest term match. */
|
||||
export function buildSnippet(
|
||||
text: string,
|
||||
terms: string[],
|
||||
radius = 90,
|
||||
): Segment[] {
|
||||
const lower = text.toLowerCase();
|
||||
let pos = -1;
|
||||
for (const term of terms) {
|
||||
const i = lower.indexOf(term);
|
||||
if (i !== -1 && (pos === -1 || i < pos)) pos = i;
|
||||
}
|
||||
if (pos === -1) {
|
||||
const head = text.slice(0, radius * 2);
|
||||
return highlight(head + (text.length > head.length ? "…" : ""), terms);
|
||||
}
|
||||
let start = Math.max(0, pos - radius);
|
||||
let end = Math.min(text.length, pos + radius);
|
||||
// Snap to word boundaries so we don't slice mid-word.
|
||||
if (start > 0) {
|
||||
const space = text.indexOf(" ", start);
|
||||
if (space !== -1 && space < pos) start = space + 1;
|
||||
}
|
||||
if (end < text.length) {
|
||||
const space = text.lastIndexOf(" ", end);
|
||||
if (space > pos) end = space;
|
||||
}
|
||||
let snippet = text.slice(start, end).trim();
|
||||
if (start > 0) snippet = "…" + snippet;
|
||||
if (end < text.length) snippet = snippet + "…";
|
||||
return highlight(snippet, terms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank docs against a query. A doc matches when every term appears in its title
|
||||
* or body; title hits score highest.
|
||||
*/
|
||||
export function searchDocs(
|
||||
docs: SearchDoc[],
|
||||
query: string,
|
||||
limit = 40,
|
||||
): SearchResult[] {
|
||||
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
if (!terms.length) return [];
|
||||
|
||||
const results: SearchResult[] = [];
|
||||
for (const doc of docs) {
|
||||
const titleLower = doc.title.toLowerCase();
|
||||
const textLower = doc.text.toLowerCase();
|
||||
const matchesAll = terms.every(
|
||||
(term) => titleLower.includes(term) || textLower.includes(term),
|
||||
);
|
||||
if (!matchesAll) continue;
|
||||
|
||||
let score = 0;
|
||||
for (const term of terms) {
|
||||
if (titleLower.includes(term)) score += 10;
|
||||
if (titleLower.startsWith(term)) score += 5;
|
||||
score += Math.min(countOccurrences(textLower, term), 5);
|
||||
}
|
||||
|
||||
results.push({
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
sectionLabel: doc.sectionLabel,
|
||||
titleSegments: highlight(doc.title, terms),
|
||||
snippet: buildSnippet(doc.text, terms),
|
||||
score,
|
||||
});
|
||||
}
|
||||
|
||||
results.sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
|
||||
return results.slice(0, limit);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -4,13 +4,33 @@
|
||||
* only builds seed data for the MSW handlers and tests.
|
||||
*/
|
||||
|
||||
import type { PolicyRunView, WirePolicy } from "@app/policies/types";
|
||||
import { POLICY_CONFIG } from "@portal/api/policies";
|
||||
import type {
|
||||
PolicyRunView,
|
||||
WirePipelineStep,
|
||||
WirePolicy,
|
||||
} from "@app/policies/types";
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Seed data — real backend wire format */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
// Literal wire steps (not derived from the catalogue) so this fixtures module stays independent of
|
||||
// @portal/api/policies and its heavy tool-operation import graph.
|
||||
const SECURITY_STEPS: WirePipelineStep[] = [
|
||||
{
|
||||
operation: "/api/v1/security/auto-redact",
|
||||
parameters: {
|
||||
listOfText: "",
|
||||
useRegex: true,
|
||||
convertPDFToImage: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "/api/v1/security/sanitize-pdf",
|
||||
parameters: { removeJavaScript: true },
|
||||
},
|
||||
];
|
||||
|
||||
export function seedPolicies(): WirePolicy[] {
|
||||
return [
|
||||
{
|
||||
@@ -19,7 +39,7 @@ export function seedPolicies(): WirePolicy[] {
|
||||
owner: "security@acme.com",
|
||||
enabled: true,
|
||||
trigger: null,
|
||||
steps: POLICY_CONFIG.security.defaultOperations,
|
||||
steps: SECURITY_STEPS,
|
||||
output: {
|
||||
type: "inline",
|
||||
options: {
|
||||
|
||||
@@ -1,254 +1,73 @@
|
||||
/* Full-height docs surface: the sidebar and reading pane each scroll on their
|
||||
own inside the portal shell's scroll container, so a 70+ item nav no longer
|
||||
drags the whole page around. */
|
||||
.portal-docs {
|
||||
display: grid;
|
||||
grid-template-columns: 16rem minmax(0, 1fr);
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
grid-template-columns: 15rem minmax(0, 1fr);
|
||||
gap: 2rem;
|
||||
padding: 1.5rem;
|
||||
max-width: 84rem;
|
||||
margin: 0 auto;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
/* With an "On this page" TOC, add a right-hand column. */
|
||||
.portal-docs--with-toc {
|
||||
grid-template-columns: 16rem minmax(0, 1fr) 15rem;
|
||||
}
|
||||
|
||||
/* Not enough room for three columns → drop the TOC. */
|
||||
@media (max-width: 72rem) {
|
||||
.portal-docs--with-toc {
|
||||
grid-template-columns: 16rem minmax(0, 1fr);
|
||||
}
|
||||
.portal-docs__toc-col {
|
||||
display: none;
|
||||
@media (max-width: 60rem) {
|
||||
.portal-docs {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
}
|
||||
|
||||
.portal-docs--empty {
|
||||
display: block;
|
||||
padding: 3rem 1.5rem;
|
||||
}
|
||||
|
||||
/* ── Left nav (own scroll column) ──────────────────────────────────────── */
|
||||
/* ── Left nav ──────────────────────────────────────────────────────────── */
|
||||
|
||||
.portal-docs__sidebar {
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid var(--color-border-light);
|
||||
padding: 1.25rem 0;
|
||||
position: sticky;
|
||||
top: 1.5rem;
|
||||
align-self: start;
|
||||
}
|
||||
|
||||
@media (max-width: 60rem) {
|
||||
.portal-docs__sidebar {
|
||||
position: static;
|
||||
}
|
||||
}
|
||||
|
||||
.portal-docs__nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
/* Search */
|
||||
.portal-docs__search {
|
||||
margin-bottom: 0.75rem;
|
||||
padding: 0 0.75rem;
|
||||
}
|
||||
|
||||
.portal-docs__search-box {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.portal-docs__search-icon {
|
||||
position: absolute;
|
||||
left: 0.625rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
font-size: 0.9375rem;
|
||||
color: var(--color-text-4);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.portal-docs__search-input {
|
||||
width: 100%;
|
||||
padding: 0.4rem 0.6rem 0.4rem 1.9rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-1);
|
||||
background: var(--color-bg-subtle);
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: var(--radius-md);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.portal-docs__search-input:focus {
|
||||
border-color: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-docs__nav-empty {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-4);
|
||||
padding: 0.5rem 0.75rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Search results ────────────────────────────────────────────────────── */
|
||||
|
||||
.portal-docs__results {
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.portal-docs__results-count {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-text-4);
|
||||
padding: 0 0.75rem 0.5rem;
|
||||
}
|
||||
|
||||
.portal-docs__results-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Hairline divider between results for clear, calm separation. */
|
||||
.portal-docs__results-list li + li {
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-docs__result {
|
||||
height: auto;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.portal-docs__result:hover,
|
||||
.portal-docs__result.is-active {
|
||||
background: var(--color-bg-hover);
|
||||
}
|
||||
|
||||
.portal-docs__result-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
/* Title + section share one line; the title truncates before the section. */
|
||||
.portal-docs__result-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-docs__result-title {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
line-height: 1.3;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.portal-docs__result-section {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
.portal-docs__result-snippet {
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.4;
|
||||
color: var(--color-text-4);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 1;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Subtle match emphasis — coloured text, not a filled block. */
|
||||
.portal-docs__hl {
|
||||
color: var(--color-blue);
|
||||
font-weight: 600;
|
||||
background: none;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.portal-docs__nav-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.0625rem;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
/* Section label: shared typography for the static Overview label and the
|
||||
collapsible accordion headers below. */
|
||||
.portal-docs__nav-head {
|
||||
padding: 0.4rem 0.75rem 0.2rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-4);
|
||||
padding: 0 0.5rem;
|
||||
}
|
||||
|
||||
/* Collapsible section header (Overview stays a static label). */
|
||||
.portal-docs__nav-head--button:hover {
|
||||
background: var(--color-bg-hover);
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
|
||||
.portal-docs__nav-head-main {
|
||||
display: flex;
|
||||
.portal-docs__nav-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-docs__nav-headlabel {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.portal-docs__nav-chevron {
|
||||
font-size: 0.625rem;
|
||||
color: var(--color-text-4);
|
||||
transition: transform var(--motion-fast);
|
||||
}
|
||||
|
||||
.portal-docs__nav-chevron.is-open {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.portal-docs__nav-count {
|
||||
font-size: 0.625rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-4);
|
||||
justify-content: center;
|
||||
width: 1.125rem;
|
||||
height: 1.125rem;
|
||||
font-size: 0.6875rem;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-bg-subtle);
|
||||
border-radius: var(--radius-pill);
|
||||
padding: 0.05rem 0.4rem;
|
||||
}
|
||||
|
||||
/* Space consecutive sections apart (not before the first). */
|
||||
.portal-docs__nav-group + .portal-docs__nav-group {
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
|
||||
/* Nested sub-sections: indented under their parent with a guide line. */
|
||||
.portal-docs__nav-children {
|
||||
margin: 0.125rem 0 0.25rem 0.85rem;
|
||||
padding-left: 0.4rem;
|
||||
border-left: 1px solid var(--color-border-light);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.0625rem;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.portal-docs__nav-list {
|
||||
list-style: none;
|
||||
margin: 0 0 0.375rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -261,10 +80,10 @@
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.35rem 0.75rem;
|
||||
padding: 0.375rem 0.5rem;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border-radius: var(--radius-md);
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-3);
|
||||
cursor: pointer;
|
||||
@@ -291,129 +110,10 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Mobile-only nav toggle (a drawer button); hidden on desktop. */
|
||||
.portal-docs__nav-toggle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* ── Reading pane (own scroll column) ──────────────────────────────────── */
|
||||
/* ── Content shell ─────────────────────────────────────────────────────── */
|
||||
|
||||
.portal-docs__content {
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: 1.5rem 2rem 4rem;
|
||||
}
|
||||
|
||||
.portal-docs__content-inner {
|
||||
max-width: 46rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* ── On this page (right rail) ─────────────────────────────────────────── */
|
||||
|
||||
.portal-docs__toc-col {
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
border-left: 1px solid var(--color-border-light);
|
||||
padding: 1.5rem 0.75rem;
|
||||
}
|
||||
|
||||
.portal-docs__toc {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.portal-docs__toc-title {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-4);
|
||||
padding: 0 0.5rem 0.5rem;
|
||||
}
|
||||
|
||||
.portal-docs__toc-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.0625rem;
|
||||
}
|
||||
|
||||
.portal-docs__toc-link {
|
||||
display: block;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-left: 2px solid transparent;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.35;
|
||||
color: var(--color-text-3);
|
||||
text-decoration: none;
|
||||
transition: color var(--motion-fast);
|
||||
}
|
||||
|
||||
.portal-docs__toc-link.is-sub {
|
||||
padding-left: 1.25rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.portal-docs__toc-link:hover {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-docs__toc-link.is-active {
|
||||
color: var(--color-blue);
|
||||
border-left-color: var(--color-blue);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Scroll-to-heading lands just below the pane top, not flush against it. */
|
||||
.portal-docs__md h2,
|
||||
.portal-docs__md h3 {
|
||||
scroll-margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* ── Small screens: nav collapses into a drawer above the content ──────── */
|
||||
|
||||
@media (max-width: 60rem) {
|
||||
.portal-docs {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: auto auto minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.portal-docs__nav-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin: 0.75rem 1rem 0;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
background: var(--color-bg-subtle);
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.portal-docs__sidebar {
|
||||
display: none;
|
||||
height: auto;
|
||||
max-height: 60vh;
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-docs__sidebar.is-open {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.portal-docs__content {
|
||||
padding: 1.25rem 1.25rem 3rem;
|
||||
}
|
||||
}
|
||||
|
||||
.portal-docs__section {
|
||||
@@ -823,160 +523,3 @@
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
/* ── Markdown content ──────────────────────────────────────────────────── */
|
||||
|
||||
.portal-docs__md {
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.65;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
|
||||
.portal-docs__md h1,
|
||||
.portal-docs__md h2,
|
||||
.portal-docs__md h3,
|
||||
.portal-docs__md h4 {
|
||||
color: var(--color-text-1);
|
||||
font-weight: 650;
|
||||
line-height: 1.25;
|
||||
margin: 1.75rem 0 0.75rem;
|
||||
}
|
||||
|
||||
.portal-docs__md h2 {
|
||||
font-size: 1.3125rem;
|
||||
padding-bottom: 0.3rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-docs__md h3 {
|
||||
font-size: 1.0625rem;
|
||||
}
|
||||
|
||||
.portal-docs__md h4 {
|
||||
font-size: 0.9375rem;
|
||||
}
|
||||
|
||||
.portal-docs__md > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.portal-docs__md p,
|
||||
.portal-docs__md ul,
|
||||
.portal-docs__md ol {
|
||||
margin: 0 0 0.875rem;
|
||||
}
|
||||
|
||||
.portal-docs__md li {
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
|
||||
.portal-docs__md a {
|
||||
color: var(--color-blue);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.portal-docs__md a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.portal-docs__md code {
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-size: 0.85em;
|
||||
background: var(--color-bg-subtle);
|
||||
padding: 0.1em 0.35em;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.portal-docs__md blockquote {
|
||||
margin: 0 0 0.875rem;
|
||||
padding: 0.125rem 0.875rem;
|
||||
border-left: 3px solid var(--color-blue);
|
||||
background: var(--color-bg-subtle);
|
||||
border-radius: 0 var(--radius-md) var(--radius-md) 0;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.portal-docs__md blockquote p {
|
||||
margin: 0.5rem 0;
|
||||
}
|
||||
|
||||
.portal-docs__md-img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-docs__md hr {
|
||||
border: none;
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
margin: 1.5rem 0;
|
||||
}
|
||||
|
||||
.portal-docs__md-pre {
|
||||
position: relative;
|
||||
margin: 0 0 0.875rem;
|
||||
}
|
||||
|
||||
.portal-docs__md-pre pre {
|
||||
margin: 0;
|
||||
padding: 0.875rem 4rem 0.875rem 0.875rem;
|
||||
background: var(--color-bg-subtle);
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: var(--radius-md);
|
||||
overflow-x: auto;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.portal-docs__md-pre pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.portal-docs__md-copy {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
}
|
||||
|
||||
.portal-docs__md-tablewrap {
|
||||
overflow-x: auto;
|
||||
margin: 0 0 0.875rem;
|
||||
}
|
||||
|
||||
.portal-docs__md-tablewrap table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.portal-docs__md-tablewrap th,
|
||||
.portal-docs__md-tablewrap td {
|
||||
border: 1px solid var(--color-border-light);
|
||||
padding: 0.4rem 0.625rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.portal-docs__md-tablewrap th {
|
||||
background: var(--color-bg-subtle);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.portal-docs__source {
|
||||
margin-top: 2rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.portal-docs__source a {
|
||||
color: var(--color-text-3);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.portal-docs__source a:hover {
|
||||
color: var(--color-blue);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { DeveloperDocs } from "@portal/views/DeveloperDocs";
|
||||
|
||||
// Renders the real docs manifest (generated by scripts/sync-portal-docs.mts), so
|
||||
// this story is a live view of the auto-built Documentation browser. The view
|
||||
// fills its container's height (independent sidebar/content scroll), so the
|
||||
// decorator gives it a viewport-height frame.
|
||||
const meta: Meta<typeof DeveloperDocs> = {
|
||||
title: "Portal/DeveloperDocs/View",
|
||||
component: DeveloperDocs,
|
||||
parameters: { layout: "fullscreen" },
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div style={{ height: "100vh" }}>
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
};
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof DeveloperDocs>;
|
||||
|
||||
export const Default: Story = {};
|
||||
@@ -1,80 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { ReactElement } from "react";
|
||||
|
||||
// Deterministic labels; the view + DocsNav + MarkdownDoc all use useTranslation.
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
// 2nd arg may be a default string or i18next interpolation options ({count}).
|
||||
t: (key: string, opts?: unknown) => (typeof opts === "string" ? opts : key),
|
||||
i18n: { changeLanguage: vi.fn() },
|
||||
}),
|
||||
}));
|
||||
|
||||
import { DeveloperDocs } from "@portal/views/DeveloperDocs";
|
||||
|
||||
const renderDocs = (ui: ReactElement) =>
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/processor/docs"]}>
|
||||
<MantineProvider>{ui}</MantineProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
describe("DeveloperDocs — markdown browser over the generated manifest", () => {
|
||||
it("keeps Overview static (open, no toggle) and other sections collapsed", () => {
|
||||
renderDocs(<DeveloperDocs />);
|
||||
expect(screen.getByRole("searchbox")).toBeInTheDocument();
|
||||
// Overview is static: its items show, and it has no toggle button.
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Production Deployment Guide" }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /^Overview/i }),
|
||||
).not.toBeInTheDocument();
|
||||
// Other sections collapse, so their items are hidden until expanded.
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Kubernetes Guide" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/locally hosted web application/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("expands a collapsible section when its header is clicked", () => {
|
||||
renderDocs(<DeveloperDocs />);
|
||||
fireEvent.click(screen.getByRole("button", { name: /Installation/i }));
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Kubernetes Guide" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("searches doc content (not just titles), shows a snippet, and navigates", async () => {
|
||||
renderDocs(<DeveloperDocs />);
|
||||
// "Tesseract" appears in the OCR doc body but in no doc title — a result
|
||||
// whose snippet contains it proves full-text (content) search.
|
||||
fireEvent.change(screen.getByRole("searchbox"), {
|
||||
target: { value: "Tesseract" },
|
||||
});
|
||||
const hits = await screen.findAllByRole("button", { name: /Tesseract/i });
|
||||
expect(hits.length).toBeGreaterThan(0);
|
||||
fireEvent.click(hits[0]);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByText(/locally hosted web application/i),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it("follows an internal doc: link inside the rendered markdown", async () => {
|
||||
renderDocs(<DeveloperDocs />);
|
||||
// The Getting Started body links to the Migration guide via the doc: scheme.
|
||||
fireEvent.click(screen.getByRole("link", { name: /Migration Guide/i }));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByText(/locally hosted web application/i),
|
||||
).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,140 +1,97 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocation, useNavigate } from "react-router-dom";
|
||||
import { Button, EmptyState } from "@app/ui";
|
||||
import { DocsNav } from "@portal/components/docs/DocsNav";
|
||||
import { DocsSearch } from "@portal/components/docs/DocsSearch";
|
||||
import { DocsSection } from "@portal/components/docs/DocsSection";
|
||||
import { DocsToc } from "@portal/components/docs/DocsToc";
|
||||
import { MarkdownDoc } from "@portal/components/docs/MarkdownDoc";
|
||||
import { extractHeadings } from "@portal/docs/headings";
|
||||
import { EmptyState } from "@app/ui";
|
||||
import { useTier } from "@portal/contexts/TierContext";
|
||||
import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";
|
||||
import {
|
||||
allDocs,
|
||||
firstDocId,
|
||||
loadDoc,
|
||||
loadDocsNav,
|
||||
} from "@portal/docs/manifest/registry";
|
||||
import { searchDocs, toPlainText, type SearchDoc } from "@portal/docs/search";
|
||||
fetchDocsContent,
|
||||
fetchDocsNav,
|
||||
type DocsContent,
|
||||
type DocsNavSection,
|
||||
} from "@portal/api/docs";
|
||||
import { DocsNav, DocsNavSkeleton } from "@portal/components/docs/DocsNav";
|
||||
import { GettingStartedSection } from "@portal/components/docs/GettingStartedSection";
|
||||
import { AuthenticationSection } from "@portal/components/docs/AuthenticationSection";
|
||||
import { RateLimitsSection } from "@portal/components/docs/RateLimitsSection";
|
||||
import { EndpointReferenceSection } from "@portal/components/docs/EndpointReferenceSection";
|
||||
import { ErrorsSection } from "@portal/components/docs/ErrorsSection";
|
||||
import { WebhooksSection } from "@portal/components/docs/WebhooksSection";
|
||||
import { SdksSection } from "@portal/components/docs/SdksSection";
|
||||
import { ComponentsSection } from "@portal/components/docs/ComponentsSection";
|
||||
import { PlaybooksSection } from "@portal/components/docs/PlaybooksSection";
|
||||
import { SkillsSection } from "@portal/components/docs/SkillsSection";
|
||||
import "@portal/views/DeveloperDocs.css";
|
||||
|
||||
/**
|
||||
* Developer Docs — a markdown browser over the docs manifest generated from the
|
||||
* Stirling docs repo (see scripts/sync-portal-docs.mts). The nav is auto-sorted
|
||||
* from the repo's folders + frontmatter; content is the repo markdown, and the
|
||||
* search box does full-text search across every doc.
|
||||
*/
|
||||
/** Renders the content pane for the active nav leaf against fetched content. */
|
||||
function DocsContentPane({
|
||||
active,
|
||||
content,
|
||||
}: {
|
||||
active: string;
|
||||
content: DocsContent;
|
||||
}) {
|
||||
switch (active) {
|
||||
case "authentication":
|
||||
return <AuthenticationSection />;
|
||||
case "rate-limits":
|
||||
return <RateLimitsSection rateLimit={content.rateLimit} />;
|
||||
case "endpoints":
|
||||
return <EndpointReferenceSection />;
|
||||
case "errors":
|
||||
return <ErrorsSection errors={content.errors} />;
|
||||
case "webhooks":
|
||||
return <WebhooksSection />;
|
||||
case "sdk-overview":
|
||||
return <SdksSection sdks={content.sdks} />;
|
||||
case "component-library":
|
||||
return <ComponentsSection components={content.components} />;
|
||||
case "recipes":
|
||||
return <PlaybooksSection playbooks={content.playbooks} />;
|
||||
case "skill-catalog":
|
||||
return <SkillsSection skills={content.skills} />;
|
||||
default:
|
||||
return (
|
||||
<GettingStartedSection
|
||||
samples={content.quickstartSamples}
|
||||
response={content.quickstartResponse}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function DeveloperDocs() {
|
||||
const { t } = useTranslation();
|
||||
const { hash } = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const contentRef = useRef<HTMLElement>(null);
|
||||
const [navOpen, setNavOpen] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const { tier } = useTier();
|
||||
const [active, setActive] = useState("quickstart");
|
||||
|
||||
const nav = useMemo(() => loadDocsNav(), []);
|
||||
const fallback = useMemo(() => firstDocId(), []);
|
||||
const navState = useAsync<DocsNavSection[]>(() => fetchDocsNav(), []);
|
||||
const { data: nav } = navState;
|
||||
const { isLoading, isEmpty } = useSectionFlags(navState);
|
||||
|
||||
// Full-text index over every doc's plaintext body (built once).
|
||||
const index = useMemo<SearchDoc[]>(() => {
|
||||
const labels = new Map(nav.map((s) => [s.id, s.label]));
|
||||
return allDocs().map((d) => ({
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
sectionLabel: labels.get(d.section) ?? "",
|
||||
text: toPlainText(d.markdown),
|
||||
}));
|
||||
}, [nav]);
|
||||
const results = useMemo(() => searchDocs(index, query), [index, query]);
|
||||
const searching = query.trim().length > 0;
|
||||
|
||||
// Deep-link support: the active doc id lives in the URL hash.
|
||||
const hashId = decodeURIComponent(hash.replace(/^#/, ""));
|
||||
const activeId = hashId && loadDoc(hashId) ? hashId : fallback;
|
||||
const doc = activeId ? loadDoc(activeId) : undefined;
|
||||
const section = useMemo(
|
||||
() => nav.find((s) => s.items.some((i) => i.id === activeId)),
|
||||
[nav, activeId],
|
||||
const { data: content } = useAsync<DocsContent>(
|
||||
() => fetchDocsContent(tier),
|
||||
[tier],
|
||||
);
|
||||
// "On this page" headings for the current doc.
|
||||
const headings = useMemo(
|
||||
() => (doc ? extractHeadings(doc.markdown) : []),
|
||||
[doc],
|
||||
);
|
||||
|
||||
// Navigating closes the mobile drawer, clears the search, and resets the pane.
|
||||
const onSelect = useCallback(
|
||||
(id: string) => {
|
||||
navigate({ hash: id });
|
||||
setNavOpen(false);
|
||||
setQuery("");
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
contentRef.current?.scrollTo?.({ top: 0 });
|
||||
}, [activeId]);
|
||||
|
||||
if (nav.length === 0 || !doc) {
|
||||
return (
|
||||
<div className="portal-docs portal-docs--empty">
|
||||
<EmptyState
|
||||
title={t("portal.docs.nav.empty.title")}
|
||||
description={t("portal.docs.nav.empty.description")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const hasToc = headings.length > 0;
|
||||
|
||||
return (
|
||||
<div className={"portal-docs" + (hasToc ? " portal-docs--with-toc" : "")}>
|
||||
<Button
|
||||
variant="tertiary"
|
||||
className="portal-docs__nav-toggle"
|
||||
aria-expanded={navOpen}
|
||||
onClick={() => setNavOpen((open) => !open)}
|
||||
leftSection={<span aria-hidden>☰</span>}
|
||||
>
|
||||
{t("portal.docs.browse")}
|
||||
</Button>
|
||||
|
||||
<aside className={"portal-docs__sidebar" + (navOpen ? " is-open" : "")}>
|
||||
<DocsSearch
|
||||
query={query}
|
||||
onQueryChange={setQuery}
|
||||
results={results}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
{!searching && (
|
||||
<DocsNav sections={nav} active={activeId ?? ""} onSelect={onSelect} />
|
||||
<div className="portal-docs">
|
||||
<aside className="portal-docs__sidebar">
|
||||
{isLoading && <DocsNavSkeleton />}
|
||||
{isEmpty && (
|
||||
<EmptyState
|
||||
size="compact"
|
||||
title={t("portal.docs.nav.empty.title")}
|
||||
description={t("portal.docs.nav.empty.description")}
|
||||
/>
|
||||
)}
|
||||
{nav && nav.length > 0 && (
|
||||
<DocsNav sections={nav} active={active} onSelect={setActive} />
|
||||
)}
|
||||
</aside>
|
||||
|
||||
<main className="portal-docs__content" ref={contentRef}>
|
||||
<div className="portal-docs__content-inner">
|
||||
<DocsSection
|
||||
id={doc.id}
|
||||
eyebrow={section?.label ?? ""}
|
||||
title={doc.title}
|
||||
lead={doc.description}
|
||||
>
|
||||
<MarkdownDoc markdown={doc.markdown} onNavigate={onSelect} />
|
||||
<div className="portal-docs__source">
|
||||
<a href={doc.editUrl} target="_blank" rel="noopener noreferrer">
|
||||
{t("portal.docs.viewSource")}
|
||||
</a>
|
||||
</div>
|
||||
</DocsSection>
|
||||
</div>
|
||||
<main className="portal-docs__content">
|
||||
{content && <DocsContentPane active={active} content={content} />}
|
||||
</main>
|
||||
|
||||
{hasToc && (
|
||||
<aside className="portal-docs__toc-col">
|
||||
<DocsToc headings={headings} scrollRef={contentRef} />
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MultiSelect } from "@app/ui/MultiSelect";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PII_PRESETS } from "@app/data/policyDefinitions";
|
||||
import type { RedactParameters } from "@app/hooks/tools/redact/useRedactParameters";
|
||||
|
||||
/** The set of preset regexes — used to separate preset words from custom ones. */
|
||||
export const PRESET_PATTERNS = new Set(PII_PRESETS.map((p) => p.pattern));
|
||||
@@ -8,8 +9,8 @@ const PATTERN_BY_VALUE = new Map(PII_PRESETS.map((p) => [p.value, p.pattern]));
|
||||
const VALUE_BY_PATTERN = new Map(PII_PRESETS.map((p) => [p.pattern, p.value]));
|
||||
|
||||
interface PolicyPiiFieldProps {
|
||||
parameters: Record<string, unknown>;
|
||||
onChange: (parameters: Record<string, unknown>) => void;
|
||||
parameters: RedactParameters;
|
||||
onChange: (parameters: RedactParameters) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -26,9 +27,7 @@ export function PolicyPiiField({
|
||||
disabled,
|
||||
}: PolicyPiiFieldProps) {
|
||||
const { t } = useTranslation();
|
||||
const words = Array.isArray(parameters.wordsToRedact)
|
||||
? (parameters.wordsToRedact as string[])
|
||||
: [];
|
||||
const words = parameters.wordsToRedact;
|
||||
const selected = words
|
||||
.map((w) => VALUE_BY_PATTERN.get(w))
|
||||
.filter((v): v is string => Boolean(v));
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useEffect } from "react";
|
||||
import { PolicyPiiField } from "@app/components/policies/PolicyPiiField";
|
||||
import type { RedactParameters } from "@app/hooks/tools/redact/useRedactParameters";
|
||||
|
||||
interface PolicyRedactConfigProps {
|
||||
parameters: Record<string, unknown>;
|
||||
onChange: (parameters: Record<string, unknown>) => void;
|
||||
parameters: RedactParameters;
|
||||
onChange: (parameters: RedactParameters) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import AddWatermarkSingleStepSettings from "@app/components/tools/addWatermark/A
|
||||
import type { AddWatermarkParameters } from "@app/hooks/tools/addWatermark/useAddWatermarkParameters";
|
||||
|
||||
interface PolicyWatermarkConfigProps {
|
||||
parameters: Record<string, unknown>;
|
||||
onChange: (parameters: Record<string, unknown>) => void;
|
||||
parameters: AddWatermarkParameters;
|
||||
onChange: (parameters: AddWatermarkParameters) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export function PolicyWatermarkConfig({
|
||||
disabled,
|
||||
}: PolicyWatermarkConfigProps) {
|
||||
useEffect(() => {
|
||||
const patch: Record<string, unknown> = {};
|
||||
const patch: Partial<AddWatermarkParameters> = {};
|
||||
if (parameters.convertPDFToImage !== true) patch.convertPDFToImage = true;
|
||||
// Policies only support text watermarks.
|
||||
if (parameters.watermarkType !== "text") patch.watermarkType = "text";
|
||||
@@ -29,7 +29,7 @@ export function PolicyWatermarkConfig({
|
||||
|
||||
return (
|
||||
<AddWatermarkSingleStepSettings
|
||||
parameters={parameters as unknown as AddWatermarkParameters}
|
||||
parameters={parameters}
|
||||
onParameterChange={(key, value) =>
|
||||
onChange({ ...parameters, [key]: value })
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@ import AdminPlanSection from "@app/components/shared/config/configSections/Admin
|
||||
import AdminFeaturesSection from "@app/components/shared/config/configSections/AdminFeaturesSection";
|
||||
import AdminEndpointsSection from "@app/components/shared/config/configSections/AdminEndpointsSection";
|
||||
import AdminMcpSection from "@app/components/shared/config/configSections/AdminMcpSection";
|
||||
import AdminAiGeneralSection from "@app/components/shared/config/configSections/AdminAiGeneralSection";
|
||||
import AdminAiModelsSection from "@app/components/shared/config/configSections/AdminAiModelsSection";
|
||||
import AdminAiDocumentsSection from "@app/components/shared/config/configSections/AdminAiDocumentsSection";
|
||||
import AdminAiLimitsSection from "@app/components/shared/config/configSections/AdminAiLimitsSection";
|
||||
import AdminAuditSection from "@app/components/shared/config/configSections/AdminAuditSection";
|
||||
import AdminUsageSection from "@app/components/shared/config/configSections/AdminUsageSection";
|
||||
import AdminStorageSharingSection from "@app/components/shared/config/configSections/AdminStorageSharingSection";
|
||||
@@ -163,6 +167,45 @@ export const useConfigNavSections = (
|
||||
],
|
||||
});
|
||||
|
||||
// AI
|
||||
sections.push({
|
||||
title: t("settings.ai.title", "AI"),
|
||||
items: [
|
||||
{
|
||||
key: "adminAiGeneral",
|
||||
label: t("settings.ai.general", "General"),
|
||||
icon: "smart-toy-rounded",
|
||||
component: <AdminAiGeneralSection />,
|
||||
disabled: requiresLogin,
|
||||
disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,
|
||||
},
|
||||
{
|
||||
key: "adminAiModels",
|
||||
label: t("settings.ai.models", "Models & Providers"),
|
||||
icon: "psychology-rounded",
|
||||
component: <AdminAiModelsSection />,
|
||||
disabled: requiresLogin,
|
||||
disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,
|
||||
},
|
||||
{
|
||||
key: "adminAiDocuments",
|
||||
label: t("settings.ai.documents", "Documents & RAG"),
|
||||
icon: "description-rounded",
|
||||
component: <AdminAiDocumentsSection />,
|
||||
disabled: requiresLogin,
|
||||
disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,
|
||||
},
|
||||
{
|
||||
key: "adminAiLimits",
|
||||
label: t("settings.ai.limits", "Limits & Performance"),
|
||||
icon: "speed-rounded",
|
||||
component: <AdminAiLimitsSection />,
|
||||
disabled: requiresLogin,
|
||||
disabledTooltip: requiresLogin ? enableLoginTooltip : undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Security & Authentication
|
||||
sections.push({
|
||||
title: t("settings.securityAuth.title", "Security & Authentication"),
|
||||
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
NumberInput,
|
||||
PasswordInput,
|
||||
Autocomplete,
|
||||
Select,
|
||||
TextInput,
|
||||
Stack,
|
||||
Paper,
|
||||
Text,
|
||||
Loader,
|
||||
Group,
|
||||
Alert,
|
||||
} from "@mantine/core";
|
||||
import { alert } from "@app/components/toast";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import { useAdminSettings } from "@app/hooks/useAdminSettings";
|
||||
import { useSettingsDirty } from "@app/hooks/useSettingsDirty";
|
||||
import PendingBadge from "@app/components/shared/config/PendingBadge";
|
||||
import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { useLoginRequired } from "@app/hooks/useLoginRequired";
|
||||
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
|
||||
import {
|
||||
AiEngineSettingsData,
|
||||
AiEngineRag,
|
||||
AiEngineApiResponse,
|
||||
EMBEDDING_MODEL_SUGGESTIONS,
|
||||
} from "@app/components/shared/config/configSections/aiEngineSettings";
|
||||
|
||||
export default function AdminAiDocumentsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { loginEnabled } = useLoginRequired();
|
||||
|
||||
// Track edits to the masked secret so we never send "********" back.
|
||||
const [embeddingApiKeyDirty, setEmbeddingApiKeyDirty] = useState(false);
|
||||
|
||||
const {
|
||||
settings,
|
||||
setSettings,
|
||||
loading,
|
||||
saving,
|
||||
fetchSettings,
|
||||
saveSettings,
|
||||
isFieldPending,
|
||||
} = useAdminSettings<AiEngineSettingsData>({
|
||||
sectionName: "aiEngine",
|
||||
fetchTransformer: async (): Promise<
|
||||
AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }
|
||||
> => {
|
||||
const response = await apiClient.get<AiEngineApiResponse>(
|
||||
"/api/v1/admin/settings/section/aiEngine",
|
||||
);
|
||||
return response.data || {};
|
||||
},
|
||||
// Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.
|
||||
saveTransformer: (s: AiEngineSettingsData) => {
|
||||
const deltaSettings: Record<string, unknown> = {
|
||||
"aiEngine.rag.embeddingProvider":
|
||||
s.rag?.embeddingProvider ?? "voyageai",
|
||||
"aiEngine.rag.embeddingModel": s.rag?.embeddingModel ?? "",
|
||||
"aiEngine.rag.embeddingBaseUrl": s.rag?.embeddingBaseUrl ?? "",
|
||||
"aiEngine.rag.topK": s.rag?.topK ?? 0,
|
||||
"aiEngine.rag.maxSearches": s.rag?.maxSearches ?? 0,
|
||||
};
|
||||
if (embeddingApiKeyDirty) {
|
||||
deltaSettings["aiEngine.rag.embeddingApiKey"] =
|
||||
s.rag?.embeddingApiKey ?? "";
|
||||
}
|
||||
return { sectionData: {}, deltaSettings };
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, []);
|
||||
|
||||
const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
|
||||
settings,
|
||||
loading,
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await saveSettings();
|
||||
setEmbeddingApiKeyDirty(false);
|
||||
markSaved();
|
||||
// Engine-facing values are pushed to the AI engine live on save; no restart needed.
|
||||
alert({
|
||||
alertType: "success",
|
||||
title: t("admin.settings.ai.saved.title", "AI settings saved"),
|
||||
body: t(
|
||||
"admin.settings.ai.saved.body",
|
||||
"Changes are pushed to the AI engine automatically.",
|
||||
),
|
||||
});
|
||||
} catch (_error) {
|
||||
alert({
|
||||
alertType: "error",
|
||||
title: t("admin.error", "Error"),
|
||||
body: t("admin.settings.saveError", "Failed to save settings"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDiscard = useCallback(() => {
|
||||
setEmbeddingApiKeyDirty(false);
|
||||
setSettings(resetToSnapshot());
|
||||
}, [resetToSnapshot, setSettings]);
|
||||
|
||||
const setRag = (patch: Partial<AiEngineRag>) =>
|
||||
setSettings({ ...settings, rag: { ...(settings.rag || {}), ...patch } });
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h={200}>
|
||||
<Loader size="lg" />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const embeddingProvider = settings.rag?.embeddingProvider || "voyageai";
|
||||
const embeddingSuggestions =
|
||||
EMBEDDING_MODEL_SUGGESTIONS[embeddingProvider] || [];
|
||||
const showEmbeddingBaseUrl =
|
||||
embeddingProvider === "ollama" || embeddingProvider === "custom";
|
||||
// Ollama's embeddings endpoint needs no API key, mirroring the Models page.
|
||||
const showEmbeddingApiKey = embeddingProvider !== "ollama";
|
||||
const embeddingApiKeyLabel =
|
||||
embeddingProvider === "voyageai"
|
||||
? t(
|
||||
"admin.settings.ai.documents.embeddingApiKey.voyageai",
|
||||
"VoyageAI API key",
|
||||
)
|
||||
: embeddingProvider === "openai"
|
||||
? t(
|
||||
"admin.settings.ai.documents.embeddingApiKey.openai",
|
||||
"OpenAI API key",
|
||||
)
|
||||
: t(
|
||||
"admin.settings.ai.documents.embeddingApiKey.generic",
|
||||
"Embedding API key",
|
||||
);
|
||||
const embeddingApiKeyPlaceholder =
|
||||
embeddingProvider === "voyageai"
|
||||
? "pa-..."
|
||||
: embeddingProvider === "openai"
|
||||
? "sk-..."
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="settings-section-container">
|
||||
<Stack gap="lg" className="settings-section-content">
|
||||
<div>
|
||||
<Text fw={600} size="lg">
|
||||
{t("admin.settings.ai.documents.title", "Documents & RAG")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"admin.settings.ai.documents.description",
|
||||
"Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.documents.embeddingProvider.label",
|
||||
"Embedding provider",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("rag.embeddingProvider")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.embeddingProvider.description",
|
||||
"Provider used to turn document text into vector embeddings.",
|
||||
)}
|
||||
data={[
|
||||
{ value: "voyageai", label: "VoyageAI" },
|
||||
{ value: "openai", label: "OpenAI" },
|
||||
{ value: "ollama", label: "Ollama" },
|
||||
{ value: "custom", label: "Custom (OpenAI-compatible)" },
|
||||
]}
|
||||
value={embeddingProvider}
|
||||
onChange={(v) => setRag({ embeddingProvider: v || "voyageai" })}
|
||||
allowDeselect={false}
|
||||
comboboxProps={{
|
||||
withinPortal: true,
|
||||
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
|
||||
}}
|
||||
/>
|
||||
|
||||
<Autocomplete
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.documents.embeddingModel.label",
|
||||
"Embedding model",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("rag.embeddingModel")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.embeddingModel.description",
|
||||
"Embedding model name. Free text; suggestions are hints only.",
|
||||
)}
|
||||
data={embeddingSuggestions}
|
||||
value={settings.rag?.embeddingModel || ""}
|
||||
onChange={(value) => setRag({ embeddingModel: value })}
|
||||
comboboxProps={{
|
||||
withinPortal: true,
|
||||
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
|
||||
}}
|
||||
/>
|
||||
|
||||
{showEmbeddingApiKey && (
|
||||
<PasswordInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>{embeddingApiKeyLabel}</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("rag.embeddingApiKey")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.embeddingApiKey.description",
|
||||
"Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",
|
||||
)}
|
||||
value={settings.rag?.embeddingApiKey || ""}
|
||||
onChange={(e) => {
|
||||
setEmbeddingApiKeyDirty(true);
|
||||
setRag({ embeddingApiKey: e.target.value });
|
||||
}}
|
||||
placeholder={embeddingApiKeyPlaceholder}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showEmbeddingBaseUrl && (
|
||||
<TextInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.documents.embeddingBaseUrl.label",
|
||||
"Embedding base URL",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("rag.embeddingBaseUrl")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.embeddingBaseUrl.description",
|
||||
"Base URL of the OpenAI-compatible / Ollama embeddings endpoint, e.g. http://ollama:11434/v1. Must point at a trusted internal endpoint (SSRF-sensitive).",
|
||||
)}
|
||||
value={settings.rag?.embeddingBaseUrl || ""}
|
||||
onChange={(e) => setRag({ embeddingBaseUrl: e.target.value })}
|
||||
placeholder="http://ollama:11434/v1"
|
||||
/>
|
||||
)}
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t("admin.settings.ai.documents.topK.label", "Top K")}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("rag.topK")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.topK.description",
|
||||
"Number of most-relevant chunks retrieved per search.",
|
||||
)}
|
||||
value={settings.rag?.topK ?? 0}
|
||||
onChange={(value) => setRag({ topK: Number(value) })}
|
||||
min={1}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.documents.maxSearches.label",
|
||||
"Max searches",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("rag.maxSearches")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.documents.maxSearches.description",
|
||||
"Maximum number of retrieval searches the agent may run per request.",
|
||||
)}
|
||||
value={settings.rag?.maxSearches ?? 0}
|
||||
onChange={(value) => setRag({ maxSearches: Number(value) })}
|
||||
min={0}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Alert
|
||||
variant="light"
|
||||
color="orange"
|
||||
title={t(
|
||||
"admin.settings.ai.documents.reindexNote.title",
|
||||
"Re-index required",
|
||||
)}
|
||||
icon={<LocalIcon icon="warning-rounded" width="1rem" height="1rem" />}
|
||||
>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
"admin.settings.ai.documents.reindexNote.body",
|
||||
"Changing the embedding model invalidates previously-embedded documents. A full engine restart and re-index of existing documents is required for search to work correctly.",
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
</Stack>
|
||||
|
||||
<SettingsStickyFooter
|
||||
isDirty={isDirty}
|
||||
saving={saving}
|
||||
loginEnabled={loginEnabled}
|
||||
onSave={handleSave}
|
||||
onDiscard={handleDiscard}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
TextInput,
|
||||
NumberInput,
|
||||
Switch,
|
||||
Stack,
|
||||
Paper,
|
||||
Text,
|
||||
Loader,
|
||||
Group,
|
||||
Alert,
|
||||
Code,
|
||||
} from "@mantine/core";
|
||||
import { alert } from "@app/components/toast";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";
|
||||
import { useRestartServer } from "@app/components/shared/config/useRestartServer";
|
||||
import { useAdminSettings } from "@app/hooks/useAdminSettings";
|
||||
import { useSettingsDirty } from "@app/hooks/useSettingsDirty";
|
||||
import PendingBadge from "@app/components/shared/config/PendingBadge";
|
||||
import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { useLoginRequired } from "@app/hooks/useLoginRequired";
|
||||
import { Button } from "@app/ui/Button";
|
||||
import {
|
||||
AiEngineSettingsData,
|
||||
AiEngineFeatures,
|
||||
AiEngineApiResponse,
|
||||
} from "@app/components/shared/config/configSections/aiEngineSettings";
|
||||
|
||||
export default function AdminAiGeneralSection() {
|
||||
const { t } = useTranslation();
|
||||
const { loginEnabled } = useLoginRequired();
|
||||
const {
|
||||
restartModalOpened,
|
||||
showRestartModal,
|
||||
closeRestartModal,
|
||||
restartServer,
|
||||
} = useRestartServer();
|
||||
|
||||
const {
|
||||
settings,
|
||||
setSettings,
|
||||
loading,
|
||||
saving,
|
||||
fetchSettings,
|
||||
saveSettings,
|
||||
isFieldPending,
|
||||
} = useAdminSettings<AiEngineSettingsData>({
|
||||
sectionName: "aiEngine",
|
||||
fetchTransformer: async (): Promise<
|
||||
AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }
|
||||
> => {
|
||||
const response = await apiClient.get<AiEngineApiResponse>(
|
||||
"/api/v1/admin/settings/section/aiEngine",
|
||||
);
|
||||
return response.data || {};
|
||||
},
|
||||
// Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.
|
||||
saveTransformer: (s: AiEngineSettingsData) => ({
|
||||
sectionData: {},
|
||||
deltaSettings: {
|
||||
"aiEngine.enabled": s.enabled ?? false,
|
||||
"aiEngine.url": s.url ?? "",
|
||||
"aiEngine.timeoutSeconds": s.timeoutSeconds ?? 0,
|
||||
"aiEngine.longRunningTimeoutSeconds": s.longRunningTimeoutSeconds ?? 0,
|
||||
"aiEngine.streamTimeoutSeconds": s.streamTimeoutSeconds ?? 0,
|
||||
"aiEngine.features.chat": s.features?.chat ?? false,
|
||||
"aiEngine.features.documentQuestions":
|
||||
s.features?.documentQuestions ?? false,
|
||||
"aiEngine.features.createPdf": s.features?.createPdf ?? false,
|
||||
"aiEngine.features.mathAuditor": s.features?.mathAuditor ?? false,
|
||||
"aiEngine.features.pdfComment": s.features?.pdfComment ?? false,
|
||||
"aiEngine.features.classify": s.features?.classify ?? false,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, []);
|
||||
|
||||
const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
|
||||
settings,
|
||||
loading,
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await saveSettings();
|
||||
markSaved();
|
||||
showRestartModal();
|
||||
} catch (_error) {
|
||||
alert({
|
||||
alertType: "error",
|
||||
title: t("admin.error", "Error"),
|
||||
body: t("admin.settings.saveError", "Failed to save settings"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDiscard = useCallback(() => {
|
||||
setSettings(resetToSnapshot());
|
||||
}, [resetToSnapshot, setSettings]);
|
||||
|
||||
const [testingConnection, setTestingConnection] = useState(false);
|
||||
|
||||
// Probe the RUNNING configuration (the Java bean), not unsaved form values -
|
||||
// after enabling AI or changing the URL, save + restart first, then test.
|
||||
const handleTestConnection = async () => {
|
||||
setTestingConnection(true);
|
||||
try {
|
||||
await apiClient.get("/api/v1/ai/health");
|
||||
alert({
|
||||
alertType: "success",
|
||||
title: t(
|
||||
"admin.settings.ai.general.test.okTitle",
|
||||
"AI engine reachable",
|
||||
),
|
||||
body: t(
|
||||
"admin.settings.ai.general.test.okBody",
|
||||
"The AI engine responded to a health check.",
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
const detail =
|
||||
(error as { response?: { data?: { message?: string } } })?.response
|
||||
?.data?.message ||
|
||||
t(
|
||||
"admin.settings.ai.general.test.failBody",
|
||||
"The AI engine did not respond. Check the URL, that the engine container is running, and that AI is enabled (a restart is needed after enabling).",
|
||||
);
|
||||
alert({
|
||||
alertType: "error",
|
||||
title: t(
|
||||
"admin.settings.ai.general.test.failTitle",
|
||||
"AI engine unreachable",
|
||||
),
|
||||
body: detail,
|
||||
});
|
||||
} finally {
|
||||
setTestingConnection(false);
|
||||
}
|
||||
};
|
||||
|
||||
const setFeatures = (patch: Partial<AiEngineFeatures>) =>
|
||||
setSettings({
|
||||
...settings,
|
||||
features: { ...(settings.features || {}), ...patch },
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h={200}>
|
||||
<Loader size="lg" />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const enabled = settings.enabled || false;
|
||||
|
||||
return (
|
||||
<div className="settings-section-container">
|
||||
<Stack gap="lg" className="settings-section-content">
|
||||
<div>
|
||||
<Text fw={600} size="lg">
|
||||
{t("admin.settings.ai.general.title", "AI Engine")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"admin.settings.ai.general.description",
|
||||
"Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<div>
|
||||
<Text fw={500} size="sm">
|
||||
{t("admin.settings.ai.general.enabled.label", "Enable AI")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{t(
|
||||
"admin.settings.ai.general.enabled.description",
|
||||
"Master switch. When off, no AI tools, agents, or engine calls are available.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap="xs">
|
||||
<Switch
|
||||
checked={enabled}
|
||||
onChange={(e) =>
|
||||
setSettings({ ...settings, enabled: e.target.checked })
|
||||
}
|
||||
/>
|
||||
<PendingBadge show={isFieldPending("enabled")} />
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<TextInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t("admin.settings.ai.general.url.label", "AI engine URL")}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("url")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.general.url.description",
|
||||
"Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001.",
|
||||
)}
|
||||
value={settings.url || ""}
|
||||
onChange={(e) =>
|
||||
setSettings({ ...settings, url: e.target.value })
|
||||
}
|
||||
placeholder="http://stirling-pdf-engine:5001"
|
||||
disabled={!enabled}
|
||||
/>
|
||||
|
||||
<Group justify="flex-end">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
loading={testingConnection}
|
||||
onClick={handleTestConnection}
|
||||
>
|
||||
{t("admin.settings.ai.general.test.button", "Test connection")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.general.timeoutSeconds.label",
|
||||
"Request timeout (seconds)",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("timeoutSeconds")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.general.timeoutSeconds.description",
|
||||
"Timeout for standard AI requests to the engine.",
|
||||
)}
|
||||
value={settings.timeoutSeconds ?? 0}
|
||||
onChange={(value) =>
|
||||
setSettings({ ...settings, timeoutSeconds: Number(value) })
|
||||
}
|
||||
min={1}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.general.longRunningTimeoutSeconds.label",
|
||||
"Long-running timeout (seconds)",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("longRunningTimeoutSeconds")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.general.longRunningTimeoutSeconds.description",
|
||||
"Timeout for heavier agent operations such as document generation.",
|
||||
)}
|
||||
value={settings.longRunningTimeoutSeconds ?? 0}
|
||||
onChange={(value) =>
|
||||
setSettings({
|
||||
...settings,
|
||||
longRunningTimeoutSeconds: Number(value),
|
||||
})
|
||||
}
|
||||
min={1}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.general.streamTimeoutSeconds.label",
|
||||
"Stream timeout (seconds)",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("streamTimeoutSeconds")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.general.streamTimeoutSeconds.description",
|
||||
"Timeout for streamed (token-by-token) chat responses.",
|
||||
)}
|
||||
value={settings.streamTimeoutSeconds ?? 0}
|
||||
onChange={(value) =>
|
||||
setSettings({
|
||||
...settings,
|
||||
streamTimeoutSeconds: Number(value),
|
||||
})
|
||||
}
|
||||
min={1}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<div>
|
||||
<Text fw={600} size="sm">
|
||||
{t(
|
||||
"admin.settings.ai.general.capabilities.title",
|
||||
"Capabilities",
|
||||
)}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{t(
|
||||
"admin.settings.ai.general.capabilities.description",
|
||||
"Turn individual AI features on or off. Disabled features are hidden in the app.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.chat.label",
|
||||
"Chat assistant",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.chat.description",
|
||||
"Conversational assistant for working with PDFs.",
|
||||
)}
|
||||
checked={settings.features?.chat ?? false}
|
||||
onChange={(checked) => setFeatures({ chat: checked })}
|
||||
pending={isFieldPending("features.chat")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.documentQuestions.label",
|
||||
"Document questions",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.documentQuestions.description",
|
||||
"Ask questions and get answers grounded in an uploaded document.",
|
||||
)}
|
||||
checked={settings.features?.documentQuestions ?? false}
|
||||
onChange={(checked) =>
|
||||
setFeatures({ documentQuestions: checked })
|
||||
}
|
||||
pending={isFieldPending("features.documentQuestions")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.createPdf.label",
|
||||
"Create PDF from prompt",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.createPdf.description",
|
||||
"Generate a new PDF (e.g. from HTML) via an AI agent.",
|
||||
)}
|
||||
checked={settings.features?.createPdf ?? false}
|
||||
onChange={(checked) => setFeatures({ createPdf: checked })}
|
||||
pending={isFieldPending("features.createPdf")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.mathAuditor.label",
|
||||
"Math auditor",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.mathAuditor.description",
|
||||
"Review documents for mathematical and numerical errors.",
|
||||
)}
|
||||
checked={settings.features?.mathAuditor ?? false}
|
||||
onChange={(checked) => setFeatures({ mathAuditor: checked })}
|
||||
pending={isFieldPending("features.mathAuditor")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.pdfComment.label",
|
||||
"PDF comment agent",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.pdfComment.description",
|
||||
"Add AI-authored review comments and annotations to a PDF.",
|
||||
)}
|
||||
checked={settings.features?.pdfComment ?? false}
|
||||
onChange={(checked) => setFeatures({ pdfComment: checked })}
|
||||
pending={isFieldPending("features.pdfComment")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
<FeatureSwitch
|
||||
label={t(
|
||||
"admin.settings.ai.general.features.classify.label",
|
||||
"Document classification",
|
||||
)}
|
||||
description={t(
|
||||
"admin.settings.ai.general.features.classify.description",
|
||||
"Automatically categorise documents by type or content.",
|
||||
)}
|
||||
checked={settings.features?.classify ?? false}
|
||||
onChange={(checked) => setFeatures({ classify: checked })}
|
||||
pending={isFieldPending("features.classify")}
|
||||
disabled={!enabled}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
|
||||
<Alert
|
||||
variant="light"
|
||||
color="blue"
|
||||
title={t(
|
||||
"admin.settings.ai.general.note.title",
|
||||
"About the AI engine",
|
||||
)}
|
||||
icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}
|
||||
>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
"admin.settings.ai.general.note.body",
|
||||
"The AI engine runs as a separate service. Its shared secret",
|
||||
)}{" "}
|
||||
<Code>STIRLING_ENGINE_SHARED_SECRET</Code>{" "}
|
||||
{t(
|
||||
"admin.settings.ai.general.note.body2",
|
||||
"is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved.",
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
</Stack>
|
||||
|
||||
<SettingsStickyFooter
|
||||
isDirty={isDirty}
|
||||
saving={saving}
|
||||
loginEnabled={loginEnabled}
|
||||
onSave={handleSave}
|
||||
onDiscard={handleDiscard}
|
||||
/>
|
||||
|
||||
<RestartConfirmationModal
|
||||
opened={restartModalOpened}
|
||||
onClose={closeRestartModal}
|
||||
onRestart={restartServer}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface FeatureSwitchProps {
|
||||
label: string;
|
||||
description: string;
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
pending: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
function FeatureSwitch({
|
||||
label,
|
||||
description,
|
||||
checked,
|
||||
onChange,
|
||||
pending,
|
||||
disabled,
|
||||
}: FeatureSwitchProps) {
|
||||
return (
|
||||
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
||||
<div>
|
||||
<Text fw={500} size="sm">
|
||||
{label}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{description}
|
||||
</Text>
|
||||
</div>
|
||||
<Group gap="xs">
|
||||
<Switch
|
||||
checked={checked}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<PendingBadge show={pending} />
|
||||
</Group>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { NumberInput, Stack, Paper, Text, Loader, Group } from "@mantine/core";
|
||||
import { alert } from "@app/components/toast";
|
||||
import { useAdminSettings } from "@app/hooks/useAdminSettings";
|
||||
import { useSettingsDirty } from "@app/hooks/useSettingsDirty";
|
||||
import PendingBadge from "@app/components/shared/config/PendingBadge";
|
||||
import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { useLoginRequired } from "@app/hooks/useLoginRequired";
|
||||
import {
|
||||
AiEngineSettingsData,
|
||||
AiEngineLimits,
|
||||
AiEngineApiResponse,
|
||||
} from "@app/components/shared/config/configSections/aiEngineSettings";
|
||||
|
||||
export default function AdminAiLimitsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { loginEnabled } = useLoginRequired();
|
||||
|
||||
const {
|
||||
settings,
|
||||
setSettings,
|
||||
loading,
|
||||
saving,
|
||||
fetchSettings,
|
||||
saveSettings,
|
||||
isFieldPending,
|
||||
} = useAdminSettings<AiEngineSettingsData>({
|
||||
sectionName: "aiEngine",
|
||||
fetchTransformer: async (): Promise<
|
||||
AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }
|
||||
> => {
|
||||
const response = await apiClient.get<AiEngineApiResponse>(
|
||||
"/api/v1/admin/settings/section/aiEngine",
|
||||
);
|
||||
return response.data || {};
|
||||
},
|
||||
// Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.
|
||||
saveTransformer: (s: AiEngineSettingsData) => ({
|
||||
sectionData: {},
|
||||
deltaSettings: {
|
||||
"aiEngine.limits.maxPages": s.limits?.maxPages ?? 0,
|
||||
"aiEngine.limits.maxCharacters": s.limits?.maxCharacters ?? 0,
|
||||
"aiEngine.limits.modelMaxConcurrency":
|
||||
s.limits?.modelMaxConcurrency ?? 0,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, []);
|
||||
|
||||
const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
|
||||
settings,
|
||||
loading,
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await saveSettings();
|
||||
markSaved();
|
||||
// Engine-facing values are pushed to the AI engine live on save; no restart needed.
|
||||
alert({
|
||||
alertType: "success",
|
||||
title: t("admin.settings.ai.saved.title", "AI settings saved"),
|
||||
body: t(
|
||||
"admin.settings.ai.saved.body",
|
||||
"Changes are pushed to the AI engine automatically.",
|
||||
),
|
||||
});
|
||||
} catch (_error) {
|
||||
alert({
|
||||
alertType: "error",
|
||||
title: t("admin.error", "Error"),
|
||||
body: t("admin.settings.saveError", "Failed to save settings"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDiscard = useCallback(() => {
|
||||
setSettings(resetToSnapshot());
|
||||
}, [resetToSnapshot, setSettings]);
|
||||
|
||||
const setLimits = (patch: Partial<AiEngineLimits>) =>
|
||||
setSettings({
|
||||
...settings,
|
||||
limits: { ...(settings.limits || {}), ...patch },
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h={200}>
|
||||
<Loader size="lg" />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-section-container">
|
||||
<Stack gap="lg" className="settings-section-content">
|
||||
<div>
|
||||
<Text fw={600} size="lg">
|
||||
{t("admin.settings.ai.limits.title", "Limits & Performance")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"admin.settings.ai.limits.description",
|
||||
"Guardrails for how much work AI requests may do and how many run concurrently. Applied to the AI engine when saved.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.limits.maxPages.label",
|
||||
"Max pages per request",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("limits.maxPages")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.limits.maxPages.description",
|
||||
"Guardrail: reject AI requests over this many PDF pages.",
|
||||
)}
|
||||
value={settings.limits?.maxPages ?? 0}
|
||||
onChange={(value) => setLimits({ maxPages: Number(value) })}
|
||||
min={1}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.limits.maxCharacters.label",
|
||||
"Max characters per request",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("limits.maxCharacters")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.limits.maxCharacters.description",
|
||||
"Guardrail: reject AI requests whose extracted text exceeds this length.",
|
||||
)}
|
||||
value={settings.limits?.maxCharacters ?? 0}
|
||||
onChange={(value) => setLimits({ maxCharacters: Number(value) })}
|
||||
min={1}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.limits.modelMaxConcurrency.label",
|
||||
"Model max concurrency",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("limits.modelMaxConcurrency")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.limits.modelMaxConcurrency.description",
|
||||
"Maximum simultaneous in-flight model calls across the whole engine.",
|
||||
)}
|
||||
value={settings.limits?.modelMaxConcurrency ?? 0}
|
||||
onChange={(value) =>
|
||||
setLimits({ modelMaxConcurrency: Number(value) })
|
||||
}
|
||||
min={1}
|
||||
/>
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
|
||||
<SettingsStickyFooter
|
||||
isDirty={isDirty}
|
||||
saving={saving}
|
||||
loginEnabled={loginEnabled}
|
||||
onSave={handleSave}
|
||||
onDiscard={handleDiscard}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
TextInput,
|
||||
NumberInput,
|
||||
PasswordInput,
|
||||
Autocomplete,
|
||||
Select,
|
||||
Stack,
|
||||
Paper,
|
||||
Text,
|
||||
Loader,
|
||||
Group,
|
||||
Alert,
|
||||
} from "@mantine/core";
|
||||
import { alert } from "@app/components/toast";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import { useAdminSettings } from "@app/hooks/useAdminSettings";
|
||||
import { useSettingsDirty } from "@app/hooks/useSettingsDirty";
|
||||
import PendingBadge from "@app/components/shared/config/PendingBadge";
|
||||
import { SettingsStickyFooter } from "@app/components/shared/config/SettingsStickyFooter";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { useLoginRequired } from "@app/hooks/useLoginRequired";
|
||||
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
|
||||
import {
|
||||
AiEngineSettingsData,
|
||||
AiEngineModels,
|
||||
AiEngineApiResponse,
|
||||
MODEL_SUGGESTIONS,
|
||||
} from "@app/components/shared/config/configSections/aiEngineSettings";
|
||||
|
||||
export default function AdminAiModelsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { loginEnabled } = useLoginRequired();
|
||||
|
||||
// Track whether the user actually edited the masked secret. If not, we omit
|
||||
// it from the delta entirely so we never send "********" back to the server.
|
||||
const [apiKeyDirty, setApiKeyDirty] = useState(false);
|
||||
|
||||
const {
|
||||
settings,
|
||||
setSettings,
|
||||
loading,
|
||||
saving,
|
||||
fetchSettings,
|
||||
saveSettings,
|
||||
isFieldPending,
|
||||
} = useAdminSettings<AiEngineSettingsData>({
|
||||
sectionName: "aiEngine",
|
||||
fetchTransformer: async (): Promise<
|
||||
AiEngineSettingsData & { _pending?: Partial<AiEngineSettingsData> }
|
||||
> => {
|
||||
const response = await apiClient.get<AiEngineApiResponse>(
|
||||
"/api/v1/admin/settings/section/aiEngine",
|
||||
);
|
||||
return response.data || {};
|
||||
},
|
||||
// Save ONLY this page's keys as dot-notation so sibling AI keys are preserved.
|
||||
saveTransformer: (s: AiEngineSettingsData) => {
|
||||
const deltaSettings: Record<string, unknown> = {
|
||||
"aiEngine.models.provider": s.models?.provider ?? "anthropic",
|
||||
"aiEngine.models.smartModel": s.models?.smartModel ?? "",
|
||||
"aiEngine.models.fastModel": s.models?.fastModel ?? "",
|
||||
"aiEngine.models.smartMaxTokens": s.models?.smartMaxTokens ?? 0,
|
||||
"aiEngine.models.fastMaxTokens": s.models?.fastMaxTokens ?? 0,
|
||||
"aiEngine.models.baseUrl": s.models?.baseUrl ?? "",
|
||||
};
|
||||
// Only include the secret when the user typed a new value.
|
||||
if (apiKeyDirty) {
|
||||
deltaSettings["aiEngine.models.apiKey"] = s.models?.apiKey ?? "";
|
||||
}
|
||||
return { sectionData: {}, deltaSettings };
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchSettings();
|
||||
}, []);
|
||||
|
||||
const { isDirty, resetToSnapshot, markSaved } = useSettingsDirty(
|
||||
settings,
|
||||
loading,
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await saveSettings();
|
||||
setApiKeyDirty(false);
|
||||
markSaved();
|
||||
// Engine-facing values are pushed to the AI engine live on save; no restart needed.
|
||||
alert({
|
||||
alertType: "success",
|
||||
title: t("admin.settings.ai.saved.title", "AI settings saved"),
|
||||
body: t(
|
||||
"admin.settings.ai.saved.body",
|
||||
"Changes are pushed to the AI engine automatically.",
|
||||
),
|
||||
});
|
||||
} catch (_error) {
|
||||
alert({
|
||||
alertType: "error",
|
||||
title: t("admin.error", "Error"),
|
||||
body: t("admin.settings.saveError", "Failed to save settings"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDiscard = useCallback(() => {
|
||||
setApiKeyDirty(false);
|
||||
setSettings(resetToSnapshot());
|
||||
}, [resetToSnapshot, setSettings]);
|
||||
|
||||
const setModels = (patch: Partial<AiEngineModels>) =>
|
||||
setSettings({
|
||||
...settings,
|
||||
models: { ...(settings.models || {}), ...patch },
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h={200}>
|
||||
<Loader size="lg" />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const provider = settings.models?.provider || "anthropic";
|
||||
const showApiKey = provider !== "ollama";
|
||||
const showBaseUrl = provider === "ollama" || provider === "custom";
|
||||
const modelSuggestions = MODEL_SUGGESTIONS[provider] || [];
|
||||
|
||||
const apiKeyLabel =
|
||||
provider === "anthropic"
|
||||
? t("admin.settings.ai.models.apiKey.anthropic", "Anthropic API key")
|
||||
: provider === "openai"
|
||||
? t("admin.settings.ai.models.apiKey.openai", "OpenAI API key")
|
||||
: t("admin.settings.ai.models.apiKey.generic", "API key");
|
||||
const apiKeyPlaceholder =
|
||||
provider === "anthropic"
|
||||
? "sk-ant-..."
|
||||
: provider === "openai"
|
||||
? "sk-..."
|
||||
: "";
|
||||
|
||||
return (
|
||||
<div className="settings-section-container">
|
||||
<Stack gap="lg" className="settings-section-content">
|
||||
<div>
|
||||
<Text fw={600} size="lg">
|
||||
{t("admin.settings.ai.models.title", "Models & Providers")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t(
|
||||
"admin.settings.ai.models.description",
|
||||
"Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved.",
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<Select
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t("admin.settings.ai.models.provider.label", "Provider")}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("models.provider")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.provider.description",
|
||||
"Which LLM provider the engine talks to.",
|
||||
)}
|
||||
data={[
|
||||
{ value: "anthropic", label: "Anthropic" },
|
||||
{ value: "openai", label: "OpenAI" },
|
||||
{ value: "ollama", label: "Ollama" },
|
||||
{ value: "custom", label: "Custom (OpenAI-compatible)" },
|
||||
]}
|
||||
value={provider}
|
||||
onChange={(v) => setModels({ provider: v || "anthropic" })}
|
||||
allowDeselect={false}
|
||||
comboboxProps={{
|
||||
withinPortal: true,
|
||||
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
|
||||
}}
|
||||
/>
|
||||
|
||||
<Autocomplete
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.models.smartModel.label",
|
||||
"Smart model",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("models.smartModel")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.smartModel.description",
|
||||
"High-capability model for complex reasoning. Free text; suggestions are hints only.",
|
||||
)}
|
||||
data={modelSuggestions}
|
||||
value={settings.models?.smartModel || ""}
|
||||
onChange={(value) => setModels({ smartModel: value })}
|
||||
comboboxProps={{
|
||||
withinPortal: true,
|
||||
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
|
||||
}}
|
||||
/>
|
||||
|
||||
<Autocomplete
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.models.fastModel.label",
|
||||
"Fast model",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("models.fastModel")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.fastModel.description",
|
||||
"Cheaper, faster model for lightweight tasks. Free text; suggestions are hints only.",
|
||||
)}
|
||||
data={modelSuggestions}
|
||||
value={settings.models?.fastModel || ""}
|
||||
onChange={(value) => setModels({ fastModel: value })}
|
||||
comboboxProps={{
|
||||
withinPortal: true,
|
||||
zIndex: Z_INDEX_OVER_CONFIG_MODAL,
|
||||
}}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.models.smartMaxTokens.label",
|
||||
"Smart model max tokens",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge
|
||||
show={isFieldPending("models.smartMaxTokens")}
|
||||
/>
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.smartMaxTokens.description",
|
||||
"Maximum output tokens for the smart model.",
|
||||
)}
|
||||
value={settings.models?.smartMaxTokens ?? 0}
|
||||
onChange={(value) => setModels({ smartMaxTokens: Number(value) })}
|
||||
min={1}
|
||||
/>
|
||||
|
||||
<NumberInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.models.fastMaxTokens.label",
|
||||
"Fast model max tokens",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("models.fastMaxTokens")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.fastMaxTokens.description",
|
||||
"Maximum output tokens for the fast model.",
|
||||
)}
|
||||
value={settings.models?.fastMaxTokens ?? 0}
|
||||
onChange={(value) => setModels({ fastMaxTokens: Number(value) })}
|
||||
min={1}
|
||||
/>
|
||||
|
||||
{showApiKey && (
|
||||
<PasswordInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>{apiKeyLabel}</span>
|
||||
<PendingBadge show={isFieldPending("models.apiKey")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.apiKey.description",
|
||||
"Leave blank to use the engine's own environment credential. Applies to self-hosted single-engine deployments.",
|
||||
)}
|
||||
value={settings.models?.apiKey || ""}
|
||||
onChange={(e) => {
|
||||
setApiKeyDirty(true);
|
||||
setModels({ apiKey: e.target.value });
|
||||
}}
|
||||
placeholder={apiKeyPlaceholder}
|
||||
/>
|
||||
)}
|
||||
|
||||
{showBaseUrl && (
|
||||
<TextInput
|
||||
label={
|
||||
<Group gap="xs">
|
||||
<span>
|
||||
{t(
|
||||
"admin.settings.ai.models.baseUrl.label",
|
||||
"Provider base URL",
|
||||
)}
|
||||
</span>
|
||||
<PendingBadge show={isFieldPending("models.baseUrl")} />
|
||||
</Group>
|
||||
}
|
||||
description={t(
|
||||
"admin.settings.ai.models.baseUrl.description",
|
||||
"Base URL of the OpenAI-compatible / Ollama endpoint, e.g. http://ollama:11434/v1.",
|
||||
)}
|
||||
value={settings.models?.baseUrl || ""}
|
||||
onChange={(e) => setModels({ baseUrl: e.target.value })}
|
||||
placeholder="http://ollama:11434/v1"
|
||||
/>
|
||||
)}
|
||||
|
||||
{showBaseUrl && (
|
||||
<Alert
|
||||
variant="light"
|
||||
color="orange"
|
||||
icon={
|
||||
<LocalIcon
|
||||
icon="warning-rounded"
|
||||
width="1rem"
|
||||
height="1rem"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
"admin.settings.ai.models.baseUrl.warning",
|
||||
"The base URL must point at a trusted internal endpoint. The engine will make server-side requests to it, so an untrusted value is SSRF-sensitive.",
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
)}
|
||||
</Stack>
|
||||
</Paper>
|
||||
</Stack>
|
||||
|
||||
<SettingsStickyFooter
|
||||
isDirty={isDirty}
|
||||
saving={saving}
|
||||
loginEnabled={loginEnabled}
|
||||
onSave={handleSave}
|
||||
onDiscard={handleDiscard}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// Shared types + constants for the aiEngine admin settings section.
|
||||
// The four AI sub-pages fetch the same GET /section/aiEngine payload but each
|
||||
// saves only its own dot-notation keys so sibling keys are preserved.
|
||||
|
||||
/** Secret fields come back masked as this literal when a value is set. */
|
||||
export const MASKED_SECRET = "********";
|
||||
|
||||
export interface AiEngineModels {
|
||||
provider?: string;
|
||||
smartModel?: string;
|
||||
fastModel?: string;
|
||||
smartMaxTokens?: number;
|
||||
fastMaxTokens?: number;
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export interface AiEngineRag {
|
||||
embeddingProvider?: string;
|
||||
embeddingModel?: string;
|
||||
embeddingApiKey?: string;
|
||||
embeddingBaseUrl?: string;
|
||||
topK?: number;
|
||||
maxSearches?: number;
|
||||
}
|
||||
|
||||
export interface AiEngineLimits {
|
||||
maxPages?: number;
|
||||
maxCharacters?: number;
|
||||
modelMaxConcurrency?: number;
|
||||
}
|
||||
|
||||
export interface AiEngineFeatures {
|
||||
chat?: boolean;
|
||||
documentQuestions?: boolean;
|
||||
createPdf?: boolean;
|
||||
mathAuditor?: boolean;
|
||||
pdfComment?: boolean;
|
||||
classify?: boolean;
|
||||
}
|
||||
|
||||
export interface AiEngineSettingsData {
|
||||
enabled?: boolean;
|
||||
url?: string;
|
||||
timeoutSeconds?: number;
|
||||
longRunningTimeoutSeconds?: number;
|
||||
streamTimeoutSeconds?: number;
|
||||
models?: AiEngineModels;
|
||||
rag?: AiEngineRag;
|
||||
limits?: AiEngineLimits;
|
||||
features?: AiEngineFeatures;
|
||||
}
|
||||
|
||||
export interface ApiResponseWithPending<T> {
|
||||
_pending?: Partial<T>;
|
||||
}
|
||||
|
||||
export type AiEngineApiResponse = AiEngineSettingsData &
|
||||
ApiResponseWithPending<AiEngineSettingsData>;
|
||||
|
||||
/** Free-text model suggestions per provider (hints only). */
|
||||
export const MODEL_SUGGESTIONS: Record<string, string[]> = {
|
||||
anthropic: ["claude-haiku-4-5", "claude-sonnet-4-5", "claude-opus-4-1"],
|
||||
openai: ["gpt-4o", "gpt-4o-mini", "o3-mini"],
|
||||
ollama: ["llama3.1", "qwen2.5", "mistral"],
|
||||
custom: ["llama3.1", "qwen2.5", "mistral"],
|
||||
};
|
||||
|
||||
/** Free-text embedding-model suggestions per embedding provider. */
|
||||
export const EMBEDDING_MODEL_SUGGESTIONS: Record<string, string[]> = {
|
||||
voyageai: ["voyage-4", "voyage-3.5"],
|
||||
openai: ["text-embedding-3-small", "text-embedding-3-large"],
|
||||
ollama: ["nomic-embed-text", "mxbai-embed-large", "bge-m3"],
|
||||
custom: ["nomic-embed-text", "mxbai-embed-large", "bge-m3"],
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
POLICY_OPERATIONS,
|
||||
policyEndpoint,
|
||||
policyStep,
|
||||
policyStepFromWire,
|
||||
policyStepToWire,
|
||||
policyToolIdForEndpoint,
|
||||
type PolicyToolId,
|
||||
} from "@app/policies/operations";
|
||||
|
||||
const ALL_TOOL_IDS = Object.keys(POLICY_OPERATIONS) as PolicyToolId[];
|
||||
|
||||
describe("POLICY_OPERATIONS", () => {
|
||||
test("every category operation is a typed descriptor with a known endpoint", () => {
|
||||
// The catalogue uses these six across all categories; each must be wired.
|
||||
expect(ALL_TOOL_IDS.sort()).toEqual([
|
||||
"compress",
|
||||
"flatten",
|
||||
"ocr",
|
||||
"redact",
|
||||
"sanitize",
|
||||
"watermark",
|
||||
]);
|
||||
for (const id of ALL_TOOL_IDS) {
|
||||
expect(POLICY_OPERATIONS[id].endpoint).toBe(policyEndpoint(id));
|
||||
expect(typeof POLICY_OPERATIONS[id].toApi).toBe("function");
|
||||
expect(typeof POLICY_OPERATIONS[id].fromApi).toBe("function");
|
||||
}
|
||||
});
|
||||
|
||||
test("policyEndpoint returns the pinned endpoint literal", () => {
|
||||
expect(policyEndpoint("redact")).toBe("/api/v1/security/auto-redact");
|
||||
expect(policyEndpoint("sanitize")).toBe("/api/v1/security/sanitize-pdf");
|
||||
expect(policyEndpoint("watermark")).toBe("/api/v1/security/add-watermark");
|
||||
expect(policyEndpoint("ocr")).toBe("/api/v1/misc/ocr-pdf");
|
||||
expect(policyEndpoint("flatten")).toBe("/api/v1/misc/flatten");
|
||||
expect(policyEndpoint("compress")).toBe("/api/v1/misc/compress-pdf");
|
||||
});
|
||||
|
||||
test("policyToolIdForEndpoint maps endpoints back, and rejects non-policy ones", () => {
|
||||
for (const id of ALL_TOOL_IDS) {
|
||||
expect(policyToolIdForEndpoint(policyEndpoint(id))).toBe(id);
|
||||
}
|
||||
expect(policyToolIdForEndpoint("/api/v1/misc/repair")).toBeNull();
|
||||
expect(policyToolIdForEndpoint("not-an-endpoint")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("policyStep", () => {
|
||||
test("merges partial params over the tool's defaults", () => {
|
||||
const step = policyStep("redact", {
|
||||
useRegex: true,
|
||||
wordsToRedact: ["ssn", "card"],
|
||||
});
|
||||
expect(step.toolId).toBe("redact");
|
||||
// Overrides applied...
|
||||
expect(step.params.useRegex).toBe(true);
|
||||
expect(step.params.wordsToRedact).toEqual(["ssn", "card"]);
|
||||
// ...and untouched fields fall back to the tool's defaults.
|
||||
expect(step.params.mode).toBe("automatic");
|
||||
expect(step.params.redactColor).toBe("#000000");
|
||||
});
|
||||
});
|
||||
|
||||
describe("wire conversion", () => {
|
||||
test("redact maps frontend params to the backend request model (wordsToRedact -> listOfText)", () => {
|
||||
const wire = policyStepToWire(
|
||||
policyStep("redact", {
|
||||
useRegex: true,
|
||||
convertPDFToImage: true,
|
||||
wordsToRedact: ["ssn", "card"],
|
||||
}),
|
||||
);
|
||||
expect(wire.operation).toBe("/api/v1/security/auto-redact");
|
||||
// The backend field the endpoint actually reads, and no frontend-only `mode`/`wordsToRedact`.
|
||||
expect(wire.parameters).toMatchObject({
|
||||
listOfText: "ssn\ncard",
|
||||
useRegex: true,
|
||||
convertPDFToImage: true,
|
||||
});
|
||||
expect(wire.parameters).not.toHaveProperty("wordsToRedact");
|
||||
expect(wire.parameters).not.toHaveProperty("mode");
|
||||
});
|
||||
|
||||
test("every policy operation round-trips through wire and back", () => {
|
||||
for (const id of ALL_TOOL_IDS) {
|
||||
const step = policyStep(id);
|
||||
const back = policyStepFromWire(policyStepToWire(step));
|
||||
expect(back?.toolId).toBe(id);
|
||||
}
|
||||
});
|
||||
|
||||
test("redact round-trip preserves the configured patterns", () => {
|
||||
const step = policyStep("redact", {
|
||||
useRegex: true,
|
||||
wordsToRedact: ["ssn", "card"],
|
||||
});
|
||||
const back = policyStepFromWire(policyStepToWire(step));
|
||||
expect(back?.toolId).toBe("redact");
|
||||
if (back?.toolId === "redact") {
|
||||
expect(back.params.wordsToRedact).toEqual(["ssn", "card"]);
|
||||
expect(back.params.useRegex).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("a non-policy endpoint decodes to null", () => {
|
||||
expect(
|
||||
policyStepFromWire({ operation: "/api/v1/misc/repair", parameters: {} }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* The tool operations the Policies feature can run, each a typed {@link ToolOperationDescriptor}.
|
||||
* Source of truth for the catalogue, wizard, and wire conversion. Add a tool here to use it in a
|
||||
* policy - the catalogue can't reference an untyped operation.
|
||||
*/
|
||||
|
||||
import { describeToolOperation } from "@app/hooks/tools/shared/toolOperationDescriptor";
|
||||
import { redactOperationConfig } from "@app/hooks/tools/redact/useRedactOperation";
|
||||
import { sanitizeOperationConfig } from "@app/hooks/tools/sanitize/useSanitizeOperation";
|
||||
import { addWatermarkOperationConfig } from "@app/hooks/tools/addWatermark/useAddWatermarkOperation";
|
||||
import { ocrOperationConfig } from "@app/hooks/tools/ocr/useOCROperation";
|
||||
import { flattenOperationConfig } from "@app/hooks/tools/flatten/useFlattenOperation";
|
||||
import { compressOperationConfig } from "@app/hooks/tools/compress/useCompressOperation";
|
||||
import type { ToolOperationDescriptor } from "@app/hooks/tools/shared/toolOperationDescriptor";
|
||||
import type { ToolApiParams, ToolEndpoint } from "@app/types/toolApiTypes";
|
||||
import type { WirePipelineStep } from "@app/policies/types";
|
||||
|
||||
export const POLICY_OPERATIONS = {
|
||||
redact: describeToolOperation(
|
||||
"/api/v1/security/auto-redact",
|
||||
redactOperationConfig,
|
||||
),
|
||||
sanitize: describeToolOperation(
|
||||
"/api/v1/security/sanitize-pdf",
|
||||
sanitizeOperationConfig,
|
||||
),
|
||||
watermark: describeToolOperation(
|
||||
"/api/v1/security/add-watermark",
|
||||
addWatermarkOperationConfig,
|
||||
),
|
||||
ocr: describeToolOperation("/api/v1/misc/ocr-pdf", ocrOperationConfig),
|
||||
flatten: describeToolOperation(
|
||||
"/api/v1/misc/flatten",
|
||||
flattenOperationConfig,
|
||||
),
|
||||
compress: describeToolOperation(
|
||||
"/api/v1/misc/compress-pdf",
|
||||
compressOperationConfig,
|
||||
),
|
||||
} as const;
|
||||
|
||||
export type PolicyToolId = keyof typeof POLICY_OPERATIONS;
|
||||
|
||||
export type PolicyParams<Id extends PolicyToolId> =
|
||||
(typeof POLICY_OPERATIONS)[Id] extends ToolOperationDescriptor<
|
||||
ToolEndpoint,
|
||||
infer P
|
||||
>
|
||||
? P
|
||||
: never;
|
||||
|
||||
/** Discriminated on `toolId` so `params` matches the tool. */
|
||||
export type PolicyToolStep = {
|
||||
[Id in PolicyToolId]: { toolId: Id; params: PolicyParams<Id> };
|
||||
}[PolicyToolId];
|
||||
|
||||
export type PolicyToolStepOf<Id extends PolicyToolId> = Extract<
|
||||
PolicyToolStep,
|
||||
{ toolId: Id }
|
||||
>;
|
||||
|
||||
const POLICY_TOOL_IDS = Object.keys(POLICY_OPERATIONS) as PolicyToolId[];
|
||||
|
||||
const TOOL_ID_BY_ENDPOINT = new Map<string, PolicyToolId>(
|
||||
POLICY_TOOL_IDS.map((id) => [POLICY_OPERATIONS[id].endpoint, id]),
|
||||
);
|
||||
|
||||
export function policyEndpoint(toolId: PolicyToolId): ToolEndpoint {
|
||||
return POLICY_OPERATIONS[toolId].endpoint;
|
||||
}
|
||||
|
||||
/** Tool id for an endpoint path, or null if it isn't a policy tool. */
|
||||
export function policyToolIdForEndpoint(endpoint: string): PolicyToolId | null {
|
||||
return TOOL_ID_BY_ENDPOINT.get(endpoint) ?? null;
|
||||
}
|
||||
|
||||
/** A step for `toolId`, partial params merged over the tool's defaults. */
|
||||
export function policyStep<Id extends PolicyToolId>(
|
||||
toolId: Id,
|
||||
params: Partial<PolicyParams<Id>> = {},
|
||||
): PolicyToolStepOf<Id> {
|
||||
const defaults = POLICY_OPERATIONS[toolId].defaultParameters as object;
|
||||
return {
|
||||
toolId,
|
||||
params: { ...defaults, ...(params as object) },
|
||||
} as PolicyToolStepOf<Id>;
|
||||
}
|
||||
|
||||
export function policyStepToWire(step: PolicyToolStep): WirePipelineStep {
|
||||
return serializeStep(step);
|
||||
}
|
||||
|
||||
// Generic over the id so `params` stays correlated with the descriptor; TS can't do that through
|
||||
// the union, so `op` is widened here (a contained cast at the wire boundary).
|
||||
function serializeStep<Id extends PolicyToolId>(step: {
|
||||
toolId: Id;
|
||||
params: PolicyParams<Id>;
|
||||
}): WirePipelineStep {
|
||||
const op = POLICY_OPERATIONS[step.toolId] as ToolOperationDescriptor<
|
||||
ToolEndpoint,
|
||||
PolicyParams<Id>
|
||||
>;
|
||||
return {
|
||||
operation: op.endpoint,
|
||||
parameters: op.toApi(step.params) as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wire step -> typed policy step, or null if the endpoint isn't a policy tool. */
|
||||
export function policyStepFromWire(
|
||||
wire: WirePipelineStep,
|
||||
): PolicyToolStep | null {
|
||||
const toolId = policyToolIdForEndpoint(wire.operation);
|
||||
if (!toolId) return null;
|
||||
return deserializeStep(toolId, wire.parameters);
|
||||
}
|
||||
|
||||
function deserializeStep<Id extends PolicyToolId>(
|
||||
toolId: Id,
|
||||
parameters: Record<string, unknown>,
|
||||
): PolicyToolStepOf<Id> {
|
||||
const op = POLICY_OPERATIONS[toolId] as ToolOperationDescriptor<
|
||||
ToolEndpoint,
|
||||
PolicyParams<Id>
|
||||
>;
|
||||
// Wire params are untyped JSON; this is the one point they enter the typed model.
|
||||
const params = op.fromApi(
|
||||
parameters as unknown as ToolApiParams[ToolEndpoint],
|
||||
);
|
||||
return { toolId, params } as unknown as PolicyToolStepOf<Id>;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { type TFunction } from "i18next";
|
||||
import { allowConsole } from "@app/tests/failOnConsole";
|
||||
import { createSaasConfigNavSections } from "@app/components/shared/config/saasConfigNavSections";
|
||||
|
||||
// Passthrough i18n stub: return the provided fallback (2nd arg) or the key.
|
||||
const t = ((key: string, fallback?: string) =>
|
||||
fallback ?? key) as unknown as TFunction<"translation", undefined>;
|
||||
|
||||
const Overview = () => null;
|
||||
|
||||
type Sections = ReturnType<typeof createSaasConfigNavSections>;
|
||||
|
||||
function itemKeys(sections: Sections): string[] {
|
||||
return sections.flatMap((s) => s.items.map((i) => i.key));
|
||||
}
|
||||
|
||||
// The admin AI settings pages exist only in the self-hosted proprietary flavor. SaaS builds its
|
||||
// settings nav from scratch here, so this locks in that the AI group can never leak into SaaS -
|
||||
// if someone later wires the AI sections into the SaaS cascade, this fails loudly.
|
||||
describe("saasConfigNavSections", () => {
|
||||
const AI_ITEM_KEYS = [
|
||||
"adminAiGeneral",
|
||||
"adminAiModels",
|
||||
"adminAiDocuments",
|
||||
"adminAiLimits",
|
||||
];
|
||||
|
||||
it("never exposes the admin AI settings group or its pages", () => {
|
||||
// The shared core nav helper warns it is deprecated; incidental to this test.
|
||||
allowConsole.warn(/createConfigNavSections is deprecated/);
|
||||
const sections = createSaasConfigNavSections(Overview, () => {}, { t });
|
||||
|
||||
const keys = itemKeys(sections);
|
||||
for (const aiKey of AI_ITEM_KEYS) {
|
||||
expect(keys).not.toContain(aiKey);
|
||||
}
|
||||
expect(sections.map((s) => s.title)).not.toContain("AI");
|
||||
});
|
||||
|
||||
it("also hides the AI pages for anonymous users", () => {
|
||||
allowConsole.warn(/createConfigNavSections is deprecated/);
|
||||
const sections = createSaasConfigNavSections(Overview, () => {}, {
|
||||
t,
|
||||
isAnonymous: true,
|
||||
});
|
||||
|
||||
const keys = itemKeys(sections);
|
||||
for (const aiKey of AI_ITEM_KEYS) {
|
||||
expect(keys).not.toContain(aiKey);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -83,7 +83,6 @@
|
||||
"web-vitals": "^5.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"docs:sync": "tsx editor/scripts/sync-portal-docs.mts",
|
||||
"update:minor": "node scripts/update-minor.js",
|
||||
"update:major": "npx npm-check-updates -u && npm install",
|
||||
"update:interactive": "npx npm-check-updates -i",
|
||||
|
||||
Reference in New Issue
Block a user