Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2eb20a8bc
|
||
|
|
3721a69637 | ||
|
|
501d067415 | ||
|
|
0f34c8a1dc
|
||
|
|
5f5d6c5b38 | ||
|
|
b0a6b648bf
|
||
|
|
af811c99c2
|
||
|
|
6634d88286
|
||
|
|
b5484bace8 | ||
|
|
0babaa7022
|
||
|
|
96426ec95a | ||
|
|
01cc719c5b
|
||
|
|
1080a8b1ba | ||
|
|
38bb123140
|
||
|
|
bb62e4a7a0 | ||
|
|
e54de89a49
|
||
|
|
fbe2241fc4 | ||
|
|
e9a5980dec
|
||
|
|
73f4b3a640 | ||
|
|
a598fc022f | ||
|
|
7898ea5340 | ||
|
|
59c01dff3e | ||
|
|
000e0f7229 | ||
|
|
45db9e2e87
|
||
|
|
c95e1403c5
|
||
|
|
c04950efc4 | ||
|
|
f031f9f50a | ||
|
|
423c8e106a
|
||
|
|
61a2ba643f | ||
|
|
a4f113ef61 | ||
|
|
f05fe4f346 | ||
|
|
8a3c483350
|
||
|
|
bf914dc76e
|
||
|
|
e5413d8ad0
|
||
|
|
c07cfd3c6c | ||
|
|
abc7a4bd5a
|
||
|
|
6c08f89944
|
||
|
|
2bb0b459cf | ||
|
|
5ea804d53f
|
||
|
|
913a8af6ce
|
||
|
|
5508f4619d
|
||
|
|
a1400d6f05
|
||
|
|
ae01f32006
|
||
|
|
e95fb90228
|
||
|
|
003c66e14f
|
No files matched your search
@@ -1,14 +1,60 @@
|
||||
version: 2.1
|
||||
setup: true
|
||||
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.8
|
||||
qqq-orb: kingsrook/qqq-orb@0.6.8
|
||||
|
||||
commands:
|
||||
configure-package-install:
|
||||
steps:
|
||||
- run:
|
||||
name: Keep package installation unattended
|
||||
command: |
|
||||
# These build machines are discarded after the job.
|
||||
sudo install -d /etc/needrestart/conf.d
|
||||
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
|
||||
|
||||
workflows:
|
||||
setup:
|
||||
jobs:
|
||||
- qqq-orb/generate_pipeline:
|
||||
orb_version: '0.8'
|
||||
filters:
|
||||
branches:
|
||||
ignore: automation/qbit-rc-pending
|
||||
tags:
|
||||
ignore: /.*/
|
||||
test_only:
|
||||
jobs:
|
||||
- qqq-orb/mvn_test_only:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [qqq-maven-registry-credentials]
|
||||
filters:
|
||||
branches:
|
||||
ignore: /(develop|release\/.*)/
|
||||
|
||||
publish_snapshot:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [qqq-maven-registry-credentials]
|
||||
branch_type: snapshot
|
||||
filters:
|
||||
branches:
|
||||
only: [develop]
|
||||
|
||||
publish_release_candidate:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [qqq-maven-registry-credentials]
|
||||
branch_type: release_candidate
|
||||
filters:
|
||||
branches:
|
||||
only: [/release\/.*/]
|
||||
|
||||
publish_release:
|
||||
jobs:
|
||||
- qqq-orb/mvn_publish:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
context: [qqq-maven-registry-credentials]
|
||||
branch_type: release
|
||||
filters:
|
||||
branches:
|
||||
ignore: /.*/
|
||||
tags:
|
||||
only: [/^v\d+\.\d+\.\d+$/]
|
||||
@@ -0,0 +1,20 @@
|
||||
# QRun-IO qbit .editorconfig: the Kingsrook layout (3-space indentation, never tabs).
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
indent_size = 3
|
||||
tab_width = 3
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{cmd,bat}]
|
||||
end_of_line = crlf
|
||||
@@ -0,0 +1,3 @@
|
||||
* text=auto eol=lf
|
||||
*.cmd text eol=crlf
|
||||
mvnw text eol=lf
|
||||
@@ -1,25 +0,0 @@
|
||||
# Standard QRun release caller (v2, thin contract): every push and manual dispatch delegates to the protected qrun-release-v1 channel. Do not edit per repository.
|
||||
name: qrun-release
|
||||
on:
|
||||
push: {}
|
||||
workflow_dispatch: {}
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
jobs:
|
||||
release:
|
||||
uses: self:KofTwentyTwo/platform-ci/.gitea/workflows/java-docker.yaml@qrun-release-v1
|
||||
with:
|
||||
runner: linux-small
|
||||
docker-runner: container-build
|
||||
browsers: true
|
||||
browser-runner: browser-build
|
||||
postpublish:
|
||||
if: ${{ needs.release.outputs.capture == 'true' }}
|
||||
needs: release
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
uses: self:KofTwentyTwo/platform-ci/.gitea/workflows/qrun-source-version.yaml@qrun-release-v1
|
||||
with:
|
||||
runner: linux-small
|
||||
@@ -0,0 +1,25 @@
|
||||
# Weekly, grouped dependency updates. Minor and patch updates arrive as one PR per ecosystem;
|
||||
# major updates stay separate so each gets its own review. At most three version-update PRs per
|
||||
# ecosystem are open at once. Security updates are enabled in the repository settings and are
|
||||
# not limited by this schedule.
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: maven
|
||||
directory: /
|
||||
target-branch: develop
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 3
|
||||
groups:
|
||||
maven-minor-and-patch:
|
||||
update-types: [minor, patch]
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
target-branch: develop
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 3
|
||||
groups:
|
||||
github-actions:
|
||||
patterns: ['*']
|
||||
@@ -1,23 +0,0 @@
|
||||
name: CodeQL
|
||||
'on':
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
- release/**
|
||||
- hotfix/**
|
||||
pull_request: {}
|
||||
schedule:
|
||||
- cron: 41 16 * * 0
|
||||
workflow_dispatch: {}
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
security-events: write
|
||||
packages: read
|
||||
concurrency:
|
||||
group: codeql-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
jobs:
|
||||
analyze:
|
||||
uses: QRun-IO/qqq-orb/.github/workflows/qbit-codeql.yml@c288a8864fe9054f68410e1d78f5863aea4c4d22
|
||||
@@ -0,0 +1,25 @@
|
||||
# Cut the next release candidate (QRun-IO/qqq docs/QRUN-QBIT-REPO-STANDARD.md, C6):
|
||||
# run this workflow by hand, or merge a develop PR labelled `release:rc`. It merges develop into
|
||||
# the release line and the release/* push runs CircleCI publish_release_candidate.
|
||||
name: Release candidate
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: Print the plan without merging or creating branches
|
||||
type: boolean
|
||||
default: false
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches: [develop]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release-rc:
|
||||
if: github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release:rc'))
|
||||
uses: QRun-IO/.github/.github/workflows/qbit-release-rc.yml@main
|
||||
with:
|
||||
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
|
||||
@@ -1,20 +1,21 @@
|
||||
# Maven
|
||||
target/
|
||||
.env
|
||||
.idea
|
||||
*.iml
|
||||
*.class
|
||||
*.log
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.project
|
||||
.classpath
|
||||
.settings/
|
||||
|
||||
# OS
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
hs_err_pid*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
*.sw*
|
||||
.flattened-pom.xml
|
||||
dependency-reduced-pom.xml
|
||||
/.env.local
|
||||
/.cache/
|
||||
.claude/settings.local.json
|
||||
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||
@@ -1,15 +0,0 @@
|
||||
profile: qbit
|
||||
orb_version: '0.8'
|
||||
default_branch: develop
|
||||
java_version: '21'
|
||||
browsers: true
|
||||
api_checks: false
|
||||
docs_only: false
|
||||
release_on_main: false
|
||||
release_tag_policy: none
|
||||
test_branch_policy: all
|
||||
publish:
|
||||
snapshot: false
|
||||
release_candidate: false
|
||||
release: false
|
||||
asciidoc: false
|
||||
@@ -0,0 +1,93 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
**QBit Assistant** adds an in-app AI assistant to any QQQ application. It owns the chat backend:
|
||||
- conversations and audit tables
|
||||
- the turn engine (the agent loop)
|
||||
- the `/qqq/v1/assistant` routes, with SSE
|
||||
- budgets, rate limits and the kill switch
|
||||
- the model-provider SPI.
|
||||
|
||||
The panel UI lives in `qqq-frontend-next`. Data access goes only through the **AI tool kernel in QQQ core** (`com.kingsrook.qqq.backend.core.actions.ai.AiToolKernel`).
|
||||
|
||||
- Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`. The owner decisions D1 to D6 at its top are binding.
|
||||
- Phase 1 is read and navigate only: no write tools and no approval cards.
|
||||
|
||||
## Build Commands
|
||||
|
||||
```bash
|
||||
./mvnw verify # all modules, tests, JaCoCo gate (70% instructions / 90% classes)
|
||||
./mvnw verify -Dqqq.snapshot.version=4.1.0-ASSISTDEV-SNAPSHOT # against a locally installed QQQ build with the kernel (+ developer panels)
|
||||
./mvnw test -pl qbit-assistant -Dtest=RedTeamTest
|
||||
ANTHROPIC_API_KEY=... ./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am
|
||||
```
|
||||
|
||||
Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed default QQQ version (`qqq.snapshot.version` in the root POM) must stay resolvable from Maven Central. Use a local kernel build only through `-D`.
|
||||
|
||||
## Modules
|
||||
|
||||
- `qbit-assistant` (`com.kingsrook.qbits.assistant`):
|
||||
- `AssistantQBitProducer`, `AssistantQBitConfig` (with `AssistantModelRouting` and `AssistantBudgets`), `AssistantRuntime`, `AssistantSecurity`.
|
||||
- `metadata/`: tables, owner key type, the Assistant app (home + main tables in the nav), the retention process, the settings customizer (key-reference checks, masked key status), and the `assistant.admin` custom permission checker.
|
||||
- `home/`: the app home widget (`AssistantHomeData` loads, `AssistantHomeView` renders flow-layout HTML).
|
||||
- `model/`: entities for the `assistant*` tables.
|
||||
- `persistence/AssistantStore`: the **only** code that calls QQQ data actions, and only on the QBit's own tables, under the user's session.
|
||||
- `engine/`: `TurnEngine` (the loop), `ContextBuilder` (cache-prefix order), `SystemPrompt`, `PolicyService` (policy row, budgets), `RateLimiter`, the `TurnEvent` / `TurnEventLog` stream, and `MessageParts`.
|
||||
- `api/`: `AssistantApi` (transport-free) and `AssistantRouteProvider` (Javalin, SSE).
|
||||
- `provider/`: the provider-neutral SPI, plus `fake/ScriptedModelProvider` for tests, evals and demos.
|
||||
- `developer/`: the record Developer-screen panel, on the core developer-panel contract.
|
||||
- `processes/`: `AssistantRetentionStep` and `TestConnectionProcess` (record action on `assistant_provider`).
|
||||
- `engine/ProviderService` (active provider from `assistant_provider` rows, key references, prices), `UsageRecorder` (one `assistant_usage` row per model call), `ConnectionTest`.
|
||||
- `qbit-assistant-provider-anthropic`: `AnthropicModelProvider` and `AnthropicMapping` (anthropic-java streaming).
|
||||
|
||||
## Invariants (do not break)
|
||||
|
||||
- **Sessions:**
|
||||
- Never use `QSystemUserSession` or construct a `QSession` in main code (ArchUnit).
|
||||
- Every route uses `ExecutorSessionUtils.setupSession` (the user's own session).
|
||||
- `AssistantSecurity` only ever adds the user's OWN id key, or the all-access key for `assistant.admin` holders.
|
||||
- **Data access:**
|
||||
- Only `persistence/` calls QueryAction, InsertAction and the other data actions (ArchUnit).
|
||||
- Tools run only through `AiToolKernel.execute`.
|
||||
- Panel API queries also filter `userId = me`, so an admin's all-access key never mixes other users' conversations into the panel.
|
||||
- **Caching:** the request prefix stays byte-stable. The order is tools (kernel-sorted), then system block 1 (rules + primer + app digest, LONG/1h), then system block 2 (user digest + date, SHORT/5m), then messages. Exactly one SHORT hint goes on the newest message. Don't put timestamps or ids in the system prompt.
|
||||
- **Tool results:**
|
||||
- Parallel tool results go back in ONE user message, in call order.
|
||||
- Errors (DENIED, NOT_FOUND, INVALID_INPUT, ERROR) are `is_error` results.
|
||||
- Unknown tools and over-limit calls also get error results.
|
||||
- **Keys:** never stored in a table. `assistant_provider.apiKeyEnvName` holds only an allowed environment variable NAME; `apiKeyStatus` is computed on read (last 4 at most) and stripped on save.
|
||||
- **Logging:** never log message content, prompts, tool results or keys. Structured end-of-turn log only.
|
||||
- **Thinking:** thinking is never streamed or stored. The Anthropic adapter keeps the raw assistant message (with signatures) only in memory, as `providerState`, for the tool loop.
|
||||
- **Links:** only `/app` or `/app/...` hrefs are emitted (`TurnEngine.isAppHref`).
|
||||
- **Kill switch:** read fresh before every model call and every tool step.
|
||||
|
||||
## Tests
|
||||
|
||||
- `testing/` holds the fixture app on the memory backend:
|
||||
- blog, page, media and analytics tables, plus audits
|
||||
- sentinel values in hidden and password fields
|
||||
- a prompt-injection record
|
||||
- MOCK auth where the user-id prefix picks the permissions.
|
||||
- `testing/` also holds `TurnRunner`, `GoldenTasks` and `EvalSupport`. They are published as a test-jar for the provider's live evals.
|
||||
- Tags:
|
||||
- `golden` (`GoldenEvalTest`) and `redteam` (`RedTeamTest`) run in every build. Any failure fails the build.
|
||||
- `live` is excluded unless you pass `-Dtest.excludedGroups= -Dgroups=live` and set the key.
|
||||
|
||||
## Code Style
|
||||
|
||||
QQQ style:
|
||||
- 3-space indent, braces on the next line, `return (x);`
|
||||
- flower-box javadoc on every class and method
|
||||
- fluent `withX` setters
|
||||
- wrapper types.
|
||||
|
||||
## Release
|
||||
|
||||
- CircleCI qqq-orb 0.6.8.
|
||||
- `develop` publishes SNAPSHOTs.
|
||||
- `release/*` publishes RCs; the orb bumps `<revision>` in the root POM.
|
||||
- `v*` tags publish releases.
|
||||
- Both modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project are documented here. The format follows Keep a Changelog, and versions follow semantic versioning.
|
||||
|
||||
## [0.1.0] - Unreleased
|
||||
|
||||
Phase 0/1 of the QQQ Assistant: read-only Q&A and navigation. Requires QQQ 4.1 with:
|
||||
- the AI tool kernel (`qqq-backend-core` `actions.ai`, QRun-IO/qqq#1078)
|
||||
- the developer-panel contract (QRun-IO/qqq#1076).
|
||||
|
||||
### Changed (0.1.0-RC.6): tools go through the UI API (owner decision 2026-10-13)
|
||||
- **Every data tool runs a spec'd `/qqq/v1` operation with the user's own session** (`UiApiGateway`, loopback HTTP with the `sessionUUID` cookie): the same authentication, permissions, record locks, validation, audit and errors as the UI. A user without a permission gets the identical denial through the assistant. `navigate` and `search_help` (no records) stay on the core kernel. `LoopbackUiApiGateway` is a stand-in for core's `UiApiInvoker` (QRun-IO/qqq#1128).
|
||||
- Tools: `list_tables`, `describe_table`, `query_records`, `count_records`, `get_record`, `search_records`, `render_widget`, `get_record_history`, and new **`create_record`, `update_record`, `delete_record`**.
|
||||
|
||||
### Added (0.1.0-RC.6)
|
||||
- **Profiles** (`assistant_profile`, nav "Profiles"): display name, icon, personality (≤ 2,000 chars, appended to the per-user system block), greeting, starter prompts; one default, optional app / permission scope. `/assistant/config` returns `profile`.
|
||||
- **Skills** (`assistant_skill`, nav "Skills", linked through `assistant_profile_skill`, a child list on profiles): admin-written Markdown instructions read only when relevant (keywords / apps), ≤ 6,000 chars each and 12,000 per question. Instructions only: they never grant tools, endpoints or access (ArchUnit-enforced).
|
||||
- **Explain access**: `GET /qqq/v1/assistant/access?table=&prompt=` and the `assistantAccess` home widget: per table and tool, allowed or the reason.
|
||||
- **Recent denials** card on the Assistant home.
|
||||
- `AssistantStore` refuses any table that is not `assistant_*`; ArchUnit forbids the tool / UI API / access packages from using QQQ actions, the AI kernel or the profile and skill classes.
|
||||
- **Data access** (`assistant_data_access`, nav table "Data access"): NONE / READ / READ_WRITE per table or process. Default: NONE for sensitive tables (AI exposure NONE; cannot be raised), READ for other tables, NONE for processes. It only narrows the UI API.
|
||||
- **Pending actions** (`assistant_pending_action`): with confirmation on (the default), a write only proposes; `POST /qqq/v1/assistant/actions/{id}/confirm` runs it through the UI API with the confirming user's session, once; `.../reject`; `GET .../actions/{id}`. Child list on conversations.
|
||||
- **Policy columns** on `assistant_policy`: `writesRequireConfirmation`, `allowedTools`, `maxRowsPerCall`, `redactPii`.
|
||||
- **Tool-call log columns** on `assistant_tool_call`: `uiApiOperation`, `httpStatus`, `auditHref`, `pendingActionId`; tool inputs are stored with secrets redacted.
|
||||
- Config: `uiApiBaseUrl`, `withUiApiGateway`, `pendingActionTtlSeconds`. `/assistant/config` reports `features.writes` (some table is READ_WRITE) and `features.pendingActions`.
|
||||
|
||||
### Fixed (0.1.0-RC.5)
|
||||
- **Every turn failed with "The AI service could not answer this request."** Anthropic refused the request with 400 `invalid_request_error` "The compiled grammar is too large ... reduce the number of strict tools": all ten read tools were sent with `strict: true`, and the API compiles every strict schema of a request into one grammar. Tools are now **not strict by default**. The kernel already validates every tool input and answers `INVALID_INPUT`. A host can opt individual tools in with `withStrictToolNames(...)`.
|
||||
- If a provider still refuses the strict schemas, the turn **retries once without strict tools** and logs a warning (`ModelProviderException.isStrictSchemaRejected`).
|
||||
- Provider errors now carry the **API's own error type, a sanitized message** (one line, capped, key-like tokens redacted) and the **request id**:
|
||||
- they are logged at WARN for 4xx;
|
||||
- they are recorded in the `assistant_usage` row's request id;
|
||||
- they are shown to `assistant.admin` holders in the panel and in Test connection.
|
||||
Before this, a 400 was logged as "INVALID_REQUEST httpStatus=400" with no reason.
|
||||
- A turn that hits a JVM `Error` (for example a linkage problem) now ends as `ERROR` with a log line, instead of being swallowed by the executor and ending as an empty `COMPLETE` answer.
|
||||
- `AnthropicRequestContractTest` checks the exact request against the Messages API constraints and a conservative strict-tool budget.
|
||||
|
||||
### Added (0.1.0-RC.4)
|
||||
- **Provider settings** (`assistant_provider`): type (registered `AssistantProviderType`s; `AnthropicProviderType` in the Anthropic module), model, enabled, default, base URL override, monthly cost cap, max output tokens per request, max concurrent requests, and the last connection test. The default enabled row is the active provider; with no rows the provider registered in code is used, so existing hosts keep working.
|
||||
- **Key handling:** the key is never stored. A row names the environment variable that holds it (`apiKeyEnvName`, allow-listed); `apiKeyStatus` is computed on read (`Set • …abcd`) and dropped on save. A pasted key, an unrelated variable or an unlisted base URL is refused. New config: `withProviderType`, `allowedApiKeyEnvNames`, `allowedBaseUrls`, `withSecretResolver`, `providerTestTimeoutSeconds`.
|
||||
- **Test connection**, a record action on providers (standard streamed ETL Review and Result lines): one short live call, result saved on the row and recorded as a `TEST` usage row.
|
||||
- **Per-call usage** (`assistant_usage`): one row per model call (turn steps and tests) with provider, model, status, error kind, HTTP status, latency, tokens and cost. Child list on conversations and providers.
|
||||
- **Model prices** (`assistant_model_price`), editable, used for every call's cost; the reference DDL seeds the Anthropic list prices of 2026-10. The built-in `pricing` defaults now cover every current Claude model.
|
||||
- **The app home** (`assistantHome` widget): health, providers, usage by day, costs against caps, by user, top tools and recent failures, from real rows with empty states.
|
||||
- `ModelResponse.model`: the model that answered (set by the Anthropic adapter).
|
||||
|
||||
### Changed (0.1.0-RC.4)
|
||||
- The app is labelled **Assistant** (name `assistantAdmin` unchanged). Its nav lists the home and the main tables only (Providers, Conversations, Model prices, Policy); other tables are child lists. `assistantRetention` is a table action on conversations instead of a nav entry.
|
||||
- Every `assistant_*` table has AI exposure `NONE`, so the assistant never reads its own settings or audit tables (before, only the `assistant.admin` permission kept them out).
|
||||
- `AssistantMetaDataBuilder.buildAdminApp(tables)` no longer takes the retention process.
|
||||
|
||||
### Changed (0.1.0-RC.3)
|
||||
- **Snake_case names** (QRun-IO naming rule, 2026-10-12). Metadata only; the physical tables were already `assistant_*`:
|
||||
- tables `assistantConversation` ... `assistantUsageDaily` are now `assistant_conversation`, `assistant_message`, `assistant_turn`, `assistant_turn_event`, `assistant_tool_call`, `assistant_feedback`, `assistant_policy` and `assistant_usage_daily`; the conversation possible-value source follows the table name
|
||||
- permissions are unchanged: `assistant.hasAccess` keeps QQQ's standard `hasAccess` suffix, and `assistant.admin` stays as is
|
||||
- security key type `assistantUserId` is now `assistant_user_id`, with all-access key `assistant_user_id_all_access`
|
||||
- the old names remain as `@Deprecated` `LEGACY_*` constants until 0.2.0. See [UPGRADE.md](UPGRADE.md) for the stored references to update (permissions, saved views and reports, `audit_table` names).
|
||||
|
||||
### Added
|
||||
- **`qbit-assistant`**
|
||||
- `AssistantQBitProducer` and `AssistantQBitConfig`:
|
||||
- enable flag, plus the `QQQ_ASSISTANT_ENABLED` environment variable
|
||||
- provider name, model routing (Sonnet 5.5 at effort medium)
|
||||
- limits: 25 tool calls, 4 parallel, 50 rows, 500 characters per cell, 300 s
|
||||
- budgets, rate limits
|
||||
- retention of 90 / 30 / 365 days
|
||||
- owner key type and pricing.
|
||||
- Standard, visible tables: `assistant_conversation`, `assistant_message`, `assistant_turn`, `assistant_turn_event`, `assistant_tool_call`, `assistant_feedback`, `assistant_policy` and `assistant_usage_daily`. User-owned tables are locked to their owner (`assistant_user_id`), and admins read everything through `assistant_user_id_all_access`.
|
||||
- The Assistant Admin app, gated by `assistant.admin`.
|
||||
- The `assistantRetention` process.
|
||||
- `/qqq/v1/assistant` routes: config probe, conversations CRUD, turns as Server-Sent Events, replay through `/events?after=`, cancel, and feedback. The panel requires `assistant.hasAccess`. The kill switch and budgets are checked when a turn starts, and the kill switch again before every step.
|
||||
- `TurnEngine`:
|
||||
- streams the model's answer
|
||||
- runs read and navigation tools through `AiToolKernel`, with parallel calls bounded
|
||||
- sends results back in one message, with errors marked `is_error`
|
||||
- enforces the limits on tool calls, time, budget, cancel and kill switch
|
||||
- persists messages, turns, tool calls, events and usage.
|
||||
- `ContextBuilder` in cache-prefix order: tools, then the static system block (1 h), then the user digest (5 m), then history, then the new turn.
|
||||
- The provider SPI (`AssistantModelProvider`, `ModelRequest`, `StreamHandle`, `ModelCapabilities`) and `ScriptedModelProvider`.
|
||||
- The record Developer-screen "Assistant" panel, built on the core developer-panel contract, with the "Ask the assistant about this record" deep link.
|
||||
- **`qbit-assistant-provider-anthropic`**: `AnthropicModelProvider` on anthropic-java 2.71.0. It provides:
|
||||
- strict tools and `tool_choice: auto`
|
||||
- adaptive thinking with display omitted, and an explicit effort
|
||||
- cache breakpoints (1 h / 5 m)
|
||||
- refusal and max_tokens handling
|
||||
- cancel
|
||||
- an API key taken only from the environment or a host secret.
|
||||
- **Tests**:
|
||||
- ArchUnit rules
|
||||
- golden evals v1: examples D and the read half of A, plus count, navigate and search
|
||||
- the permission red team (a build gate)
|
||||
- Anthropic tests against recorded SSE streams
|
||||
- live evals against Claude (opt-in).
|
||||
|
||||
### Security review follow-ups
|
||||
- Kernel settings come from config: `allowedWidgetNames` (the kernel denies any widget not listed), `hiddenWidgetNames` and `customRedactionPatterns`.
|
||||
- **Orphaned turns.** A turn left RUNNING by a dead replica is finished as ERROR the first time it is seen, by replay, cancel, delete or a new turn. Its message gets status ERROR, and synthetic `error` (INTERNAL) and `message.end` events are persisted. Replay loops are capped at `maxTurnSeconds` + 60 s.
|
||||
- **Retention.** The tool-result cutoff now also deletes stream events, and removes render payloads and record references from stored messages.
|
||||
- **Usage.** `addUsage` uses per-key locks, a unique key on (scope, userId, usageDate) and an insert-race retry. Usage of cancelled, timed-out and failed model calls is counted when the provider reports it.
|
||||
- **Kill switch.** It fails closed when the policy can't be read. A watcher cancels running turns promptly when it flips.
|
||||
- **Limits.** Page-context scalars are capped (strings up to 512 characters, at most 100 selected ids). Conversation lists are limited to 200, running turns to 50, and replay is paged at 500 events.
|
||||
- **Ordering.** Terminal events (`usage`, `error`, `message.end`) are persisted before the turn's status becomes final.
|
||||
- **Supplemental meta-data.** The `assistant` supplemental instance meta-data is registered when the QBit is enabled.
|
||||
|
||||
## [0.1.0-RC.2] - 2026-10-12
|
||||
|
||||
**Do not use.** 0.1.0-RC.2 on Maven Central is an accidental republish of the RC.1 code by a tag build; do not use it. The next real candidate is 0.1.0-RC.3. (Cause: QRun-IO/qqq-orb#20; the `publish_release` workflow now runs on GA tags only.)
|
||||
@@ -1,17 +1,95 @@
|
||||
# qbit-template-extension
|
||||
# CLAUDE.md
|
||||
|
||||
GitHub template repository for scaffolding QQQ "Extension QBits" (infrastructure-level plugins: table customizers, auth, audit, action wrappers). Not a shipping library — consumers click "Use this template" and rename the `com.kingsrook.qbits.example` package.
|
||||
This file provides guidance to Claude Code when working with code in this repository.
|
||||
|
||||
## QQQ 4.0 baseline — 2026-09-24
|
||||
## Project Overview
|
||||
|
||||
The historical review below predates the 4.0 migration. This template targets Java 21 and the public QQQ 4.0.0 release from Maven Central. The corrected APIs, license references and actual template commands are in README.md and docs/00-getting-started.md. Preserve the documented multi-instance and scaffold limitations.
|
||||
**QBit Assistant** adds an in-app AI assistant to any QQQ application. It owns the chat backend:
|
||||
- conversations and audit tables
|
||||
- the turn engine (the agent loop)
|
||||
- the `/qqq/v1/assistant` routes, with SSE
|
||||
- budgets, rate limits and the kill switch
|
||||
- the model-provider SPI.
|
||||
|
||||
## Knowledge base
|
||||
The panel UI lives in `qqq-frontend-next`. Data access goes only through the **QQQ UI API** (`/qqq/v1`, spec'd operations, the user's own session) via `uiapi/UiApiGateway` and `tools/UiApiToolbox`; only `navigate` and `search_help` (no records) use the core AI tool kernel.
|
||||
|
||||
Reviewed dossiers for this repo and the wider QQQ platform live in the second-brain vault:
|
||||
- Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`. The owner decisions D1 to D6 at its top are binding.
|
||||
- Writes (create/update/delete) are offered only for tables an admin set to READ_WRITE in `assistant_data_access`, and by default wait for the user's confirmation (pending action card).
|
||||
|
||||
- Hub / entry point: `R:/Git.Local/KofTwentyTwo/second-brain/knowledge/qqq/qqq-hub.md`
|
||||
- This repo's dossier: `R:/Git.Local/KofTwentyTwo/second-brain/knowledge/qqq/repos/qbit-template-extension.md`
|
||||
- QBit mechanics refresher: `R:/Git.Local/KofTwentyTwo/second-brain/knowledge/qqq/architecture/metadata-model.md`
|
||||
## Build Commands
|
||||
|
||||
Reviewed at commit `e7d4b4d672cc` (branch `main`, 2026-05-21). Known drift as of that review: no `qbit-build-parent` parent pom (org convention), qqq pinned at 0.35.0 on main (0.40.0-SNAPSHOT on develop), README still claims AGPL-3.0 while LICENSE/NOTICE are Apache-2.0, and README references `scripts/customize_template.py` / `actions/ExampleActionCustomizer.java` which do not exist. See the dossier's "Maturity & risks" and "v4.0 impact" sections before modifying the scaffold.
|
||||
```bash
|
||||
./mvnw verify # all modules, tests, JaCoCo gate (70% instructions / 90% classes)
|
||||
./mvnw verify -Dqqq.snapshot.version=4.1.0-ASSISTDEV-SNAPSHOT # against a locally installed QQQ build with the kernel (+ developer panels)
|
||||
./mvnw test -pl qbit-assistant -Dtest=RedTeamTest
|
||||
ANTHROPIC_API_KEY=... ./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am
|
||||
```
|
||||
|
||||
Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed default QQQ version (`qqq.snapshot.version` in the root POM) must stay resolvable from Maven Central. Use a local kernel build only through `-D`.
|
||||
|
||||
## Modules
|
||||
|
||||
- `qbit-assistant` (`com.kingsrook.qbits.assistant`):
|
||||
- `AssistantQBitProducer`, `AssistantQBitConfig` (with `AssistantModelRouting` and `AssistantBudgets`), `AssistantRuntime`, `AssistantSecurity`.
|
||||
- `metadata/`: tables, owner key type, the Assistant app (home + main tables in the nav), the retention process, the settings customizer (key-reference checks, masked key status), and the `assistant.admin` custom permission checker.
|
||||
- `home/`: the app home widget (`AssistantHomeData` loads, `AssistantHomeView` renders flow-layout HTML).
|
||||
- `model/`: entities for the `assistant_*` tables.
|
||||
- `persistence/AssistantStore`: the **only** code that calls QQQ data actions, and only on the QBit's own tables, under the user's session.
|
||||
- `engine/`: `TurnEngine` (the loop), `ContextBuilder` (cache-prefix order), `SystemPrompt`, `PolicyService` (policy row, budgets), `RateLimiter`, the `TurnEvent` / `TurnEventLog` stream, and `MessageParts`.
|
||||
- `api/`: `AssistantApi` (transport-free) and `AssistantRouteProvider` (Javalin, SSE).
|
||||
- `provider/`: the provider-neutral SPI, plus `fake/ScriptedModelProvider` for tests, evals and demos.
|
||||
- `developer/`: the record Developer-screen panel, on the core developer-panel contract.
|
||||
- `processes/`: `AssistantRetentionStep` and `TestConnectionProcess` (record action on `assistant_provider`).
|
||||
- `engine/ProviderService` (active provider from `assistant_provider` rows, key references, prices), `UsageRecorder` (one `assistant_usage` row per model call), `ConnectionTest`.
|
||||
- `qbit-assistant-provider-anthropic`: `AnthropicModelProvider` and `AnthropicMapping` (anthropic-java streaming).
|
||||
|
||||
## Invariants (do not break)
|
||||
|
||||
- **Sessions:**
|
||||
- Never use `QSystemUserSession` or construct a `QSession` in main code (ArchUnit).
|
||||
- Every route uses `ExecutorSessionUtils.setupSession` (the user's own session).
|
||||
- `AssistantSecurity` only ever adds the user's OWN id key, or the all-access key for `assistant.admin` holders.
|
||||
- **Data access:**
|
||||
- Only `persistence/` calls QueryAction, InsertAction and the other data actions (ArchUnit).
|
||||
- Data tools run only through `UiApiToolbox` → `UiApiGateway` (spec'd `/qqq/v1` operations with the user's `sessionUUID`); never core data actions for user data. Only `navigate` and `search_help` use `AiToolKernel.execute`.
|
||||
- Data access (`DataAccessService`) and the policy only ever narrow what the UI API allows; a table whose AI exposure is NONE stays NONE.
|
||||
- A write runs only after the owner confirms its pending action (unless the policy turns confirmation off), with the confirming request's session, once.
|
||||
- Panel API queries also filter `userId = me`, so an admin's all-access key never mixes other users' conversations into the panel.
|
||||
- **Caching:** the request prefix stays byte-stable. The order is tools (kernel-sorted), then system block 1 (rules + primer + app digest, LONG/1h), then system block 2 (user digest + date, SHORT/5m), then messages. Exactly one SHORT hint goes on the newest message. Don't put timestamps or ids in the system prompt.
|
||||
- **Tool results:**
|
||||
- Parallel tool results go back in ONE user message, in call order.
|
||||
- Errors (DENIED, NOT_FOUND, INVALID_INPUT, ERROR) are `is_error` results.
|
||||
- Unknown tools and over-limit calls also get error results.
|
||||
- **Keys:** never stored in a table. `assistant_provider.apiKeyEnvName` holds only an allowed environment variable NAME; `apiKeyStatus` is computed on read (last 4 at most) and stripped on save.
|
||||
- **Logging:** never log message content, prompts, tool results or keys. Structured end-of-turn log only.
|
||||
- **Thinking:** thinking is never streamed or stored. The Anthropic adapter keeps the raw assistant message (with signatures) only in memory, as `providerState`, for the tool loop.
|
||||
- **Links:** only `/app` or `/app/...` hrefs are emitted (`TurnEngine.isAppHref`).
|
||||
- **Kill switch:** read fresh before every model call and every tool step.
|
||||
|
||||
## Tests
|
||||
|
||||
- `testing/` holds the fixture app on the memory backend:
|
||||
- blog, page, media and analytics tables, plus audits
|
||||
- sentinel values in hidden and password fields
|
||||
- a prompt-injection record
|
||||
- MOCK auth where the user-id prefix picks the permissions.
|
||||
- `testing/` also holds `TurnRunner`, `GoldenTasks` and `EvalSupport`. They are published as a test-jar for the provider's live evals.
|
||||
- Tags:
|
||||
- `golden` (`GoldenEvalTest`) and `redteam` (`RedTeamTest`) run in every build. Any failure fails the build.
|
||||
- `live` is excluded unless you pass `-Dtest.excludedGroups= -Dgroups=live` and set the key.
|
||||
|
||||
## Code Style
|
||||
|
||||
QQQ style:
|
||||
- 3-space indent, braces on the next line, `return (x);`
|
||||
- flower-box javadoc on every class and method
|
||||
- fluent `withX` setters
|
||||
- wrapper types.
|
||||
|
||||
## Release
|
||||
|
||||
- CircleCI qqq-orb 0.6.8.
|
||||
- `develop` publishes SNAPSHOTs.
|
||||
- `release/*` publishes RCs; the orb bumps `<revision>` in the root POM.
|
||||
- `v*` tags publish releases.
|
||||
- Both modules and the parent POM publish. The flatten plugin resolves `${revision}`.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Code of Conduct
|
||||
|
||||
See Project level [Code of Conduct](https://github.com/Kingsrook/qqq/blob/develop/CODE_OF_CONDUCT.md)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Code Style Guide
|
||||
|
||||
* See Project [Code Style Guide](https://github.com/Kingsrook/qqq/blob/develop/CODE_STYLE.md)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Contributing to QBit Quick Search
|
||||
|
||||
* See Project [Contributing](https://github.com/Kingsrook/qqq/blob/develop/CONTRIBUTING.md)
|
||||
@@ -176,7 +176,7 @@
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
Copyright 2022-2025 QRunIO, LLC
|
||||
Copyright 2024 Kingsrook, LLC
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
qBit Template - Extension
|
||||
Copyright 2022-2025 QRunIO, LLC
|
||||
QBit Assistant
|
||||
Copyright 2026 Kingsrook, LLC
|
||||
|
||||
This product includes software developed at QRunIO, LLC (https://qrun.io/).
|
||||
|
||||
|
||||
@@ -1,42 +1,258 @@
|
||||
# QBit Template: Extension
|
||||
# QBit Assistant
|
||||
|
||||
Template repository for creating QQQ Extension QBits - infrastructure extensions, customizers, and action handlers.
|
||||
An in-app AI assistant for any QQQ application. The user asks a question in a chat panel in the Next UI. The assistant reads the application's data **with exactly that user's permissions**, answers with numbers taken from the data, and links to the records and lists it used. This first version only reads data and opens screens. It cannot change anything.
|
||||
|
||||
## What is an Extension QBit?
|
||||
Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`.
|
||||
|
||||
Extension QBits extend or enhance how QQQ operates at the infrastructure/framework level. They provide:
|
||||
- New backend implementations
|
||||
- Authentication mechanisms
|
||||
- Audit capabilities
|
||||
- Table customizers
|
||||
- Action handlers
|
||||
| Artifact | What it is |
|
||||
|---|---|
|
||||
| `com.kingsrook.qbits:qbit-assistant` | The QBit: conversation tables, turn engine, `/qqq/v1/assistant` routes (JSON + Server-Sent Events), budgets, kill switch, the provider SPI, and a scripted provider for tests and demos. |
|
||||
| `com.kingsrook.qbits:qbit-assistant-provider-anthropic` | The Claude provider (`com.anthropic:anthropic-java`). Add it to use Claude. The core QBit has no LLM SDK dependency. |
|
||||
|
||||
## Quick Start
|
||||
The data access itself is done by the AI tool kernel in QQQ core (`com.kingsrook.qqq.backend.core.actions.ai.AiToolKernel`). The kernel checks table permissions and exposure rules, applies record security, and caps and redacts what the model sees. Every tool result reaches the model wrapped as untrusted data.
|
||||
|
||||
Requires **Java 21**, **Maven 3.8+**, and QQQ **4.0.0**. Create your repository, customize its Maven coordinates and Java package/classes, implement the table customizer, then run `mvn clean verify`. See [Getting Started](docs/00-getting-started.md).
|
||||
## Requirements
|
||||
|
||||
## Structure
|
||||
- Java 21.
|
||||
- **QQQ 4.1 with the AI tool kernel (QRun-IO/qqq#1078) and the developer-panel contract (QRun-IO/qqq#1076).** The first QQQ 4.1 RC that contains both is the minimum. `qqq-middleware-javalin` is needed for the routes. Until that RC exists, build against a local QQQ build. See [Build](#build).
|
||||
- A backend for the assistant's tables, e.g. the app's RDBMS backend.
|
||||
- For Claude: an Anthropic API key held in the application's secret store.
|
||||
|
||||
```
|
||||
src/main/java/com/kingsrook/qbits/example/
|
||||
├── ExampleExtensionQBitConfig.java # Configuration
|
||||
├── ExampleExtensionQBitProducer.java # Entry point
|
||||
└── customizers/
|
||||
└── ExampleTableCustomizer.java # Table customization
|
||||
## Install
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<version>${qbit-assistant.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-provider-anthropic</artifactId>
|
||||
<version>${qbit-assistant.version}</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
## Key Characteristics
|
||||
```java
|
||||
AssistantQBitConfig config = new AssistantQBitConfig()
|
||||
.withBackendName("rdbms") // where the assistant_* tables live
|
||||
.withTableMetaDataCustomizer(snakeCaseCustomizer) // optional: backend names for your schema
|
||||
.withModelProvider(AnthropicModelProvider.fromEnvironment()) // fallback while no provider row exists
|
||||
.withProviderType(new AnthropicProviderType()); // offered on the Providers settings screen
|
||||
|
||||
- **No QAppSection** - Pure infrastructure
|
||||
- **No user-facing tables** (or minimal operational)
|
||||
- **Wraps existing tables/processes** with new behavior
|
||||
- **Validates dependencies** on other QQQ components
|
||||
new AssistantQBitProducer().withQBitConfig(config).produce(qInstance);
|
||||
```
|
||||
|
||||
## Documentation
|
||||
`produce` does the following:
|
||||
- Registers the QBit.
|
||||
- Adds the tables, the `assistant_user_id` security key type, the `assistantRetention` and **Test connection** processes, and the **Assistant** app with its home.
|
||||
- Builds the runtime.
|
||||
- Registers the `/qqq/v1/assistant/*` routes when Javalin is on the classpath.
|
||||
- Registers the record Developer-screen panel when QQQ core has the developer-panel contract.
|
||||
|
||||
- [Getting Started](docs/00-getting-started.md)
|
||||
- [Extension Patterns](docs/01-extension-patterns.md)
|
||||
Create the tables in your database: see [Tables](#tables). Then grant the permissions.
|
||||
|
||||
### The API key
|
||||
|
||||
The key never goes in config, tables or logs. It lives in the application's secret store and reaches the server as an environment variable (for kof22: Infisical, then an ExternalSecret, then the pod env).
|
||||
|
||||
- **Provider settings rows** (recommended) name the variable: `assistant_provider.apiKeyEnvName`, default the type's own (`ANTHROPIC_API_KEY`). The server reads the variable when it builds the client.
|
||||
- Without a row, the provider registered in code is used: `AnthropicModelProvider.fromEnvironment()` reads `ANTHROPIC_API_KEY`, and `AnthropicModelProvider.builder().apiKey(valueFromYourSecretStore).build()` takes the key from your own secret store (it also accepts `"${env.NAME}"`).
|
||||
|
||||
The provider's `toString` never contains the key. Its errors carry only the HTTP status and the API error type.
|
||||
|
||||
## Provider settings (the Providers table)
|
||||
|
||||
Admins set up providers on the **Providers** screen (`assistant_provider`), a standard QQQ table:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| Name, Type, Model | The type is one of the registered provider types (`withProviderType`; Anthropic now, others plug in the same way). The model list comes from the type and the price table. An empty model uses the policy's main model. |
|
||||
| Enabled, Default | The assistant uses the default enabled provider, else the first enabled one. Marking one default unmarks the others. With no enabled row, the provider registered in code is used. |
|
||||
| API Key Variable | The **name** of the environment variable that holds the key, never the key. Only allowed names are accepted: each registered type's default plus `allowedApiKeyEnvNames`. A pasted key (or `DATABASE_PASSWORD`) is refused and nothing is stored. |
|
||||
| API Key | Read-only, computed on every read: `Set • …abcd (from ANTHROPIC_API_KEY)` or `Not set (...)`. It shows the last four characters at most. No read path (screen, API, query, export) returns the key. |
|
||||
| Base URL Override | Empty uses the provider's own API. Any other URL must be listed in `allowedBaseUrls`, so a row cannot send the key to a host of an admin's choosing. |
|
||||
| Monthly Cost Cap (USD) | When this provider's cost this month (UTC) reaches the cap, new requests are refused (429 `BUDGET`) and a running answer stops before its next model call. |
|
||||
| Max Output Tokens Per Request, Max Concurrent Requests | Caps one model call's output, and how many calls run at once on this server. |
|
||||
| Last test | Status, time, latency, the model that answered, and the error text, from **Test connection**. |
|
||||
|
||||
**Why a reference and not an encrypted column.** QQQ core has no encrypted or secret field type. The key-provider and cipher work in the QQQ 4.1.0-RC.6 batch (QRun-IO/qqq#1123, #1107) encrypts backup artifacts, not table columns, and is not released. The design spec (§2.8) also says keys never go in tables. A reference keeps the key in the secret store that already holds it, so rotating it there is the "replace key" step, and the database never holds one.
|
||||
|
||||
**Test connection** is a record action on a provider (select one or more). It is a standard streamed ETL: Review lists what will be called and anything wrong with the row (missing key, disallowed variable or URL) before any call. Result has one line per provider: `connected to claude-sonnet-5-5 in 812 ms`, or the error with its kind and HTTP status. It makes one short live call (a 1-sentence prompt, at most 32 output tokens, effort low), saves the result on the row, and records the call in `assistant_usage` with purpose `TEST`.
|
||||
|
||||
## The app home
|
||||
|
||||
The **Assistant** app's home is the one place for the assistant's health, usage and cost (no other dashboard repeats it). All of it comes from the tables below, read as the viewing admin; an empty table gives an empty state, never sample data.
|
||||
|
||||
- **Health:** is it answering (kill switch, default provider, key present, last test), the 7-day error rate of model calls, cost and requests this month against the instance's monthly limit.
|
||||
- **Providers:** one row per provider: type, model, masked key status, last test, cost this month against its cap, limits, and any problem with its settings.
|
||||
- **Usage, last 30 days:** bars of model requests per day, totals (conversations, requests, tokens in and out, cost) and the last 7 days in words.
|
||||
- **Costs this month:** month to date against the policy limit and each provider cap, then by model. Cost is tokens times the model's price from **Model prices**.
|
||||
- **By user, this month**, **Top tools** (calls, failures, average time) and **Recent failures** (model calls and tool calls, linked).
|
||||
|
||||
The nav lists the home and the main tables: **Providers**, **Conversations**, **Model prices** and **Policy**. Messages, turns, tool calls, feedback and model calls are child lists on a conversation; model calls are also listed on their provider. Retention and Test connection are table and record actions, never nav entries.
|
||||
|
||||
## Model prices
|
||||
|
||||
`assistant_model_price` holds USD per million tokens per provider type and model: input, output, cache read, and cache writes (5 minute and 1 hour). Empty cache prices default to 0.1x, 1.25x and 2x the input price. The reference DDL seeds the Anthropic list prices of 2026-10. Edit a row to change what later calls cost; past rows keep the cost they were recorded with. A model with no row uses the `pricing` config map, else costs 0.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `enabled` | `true` | Per-app switch. The environment variable `QQQ_ASSISTANT_ENABLED=false` also turns it off. |
|
||||
| `backendName` | (required) | Backend of the `assistant_*` tables. |
|
||||
| `providerName` | `anthropic` | Which registered provider to use. |
|
||||
| `models` | Sonnet 5.5 at effort `medium` | `mainModel`, `mainEffort`, `mainMaxOutputTokens` (16000). The escalation (Opus 5.5, `high`) and summary (Haiku 5.5) slots are reserved for phase 2. Model ids are the exact strings `claude-sonnet-5-5`, `claude-opus-5-5` and `claude-haiku-5-5`. |
|
||||
| `defaultExposure` | `VALUES` | The kernel's default exposure. Use `METADATA_ONLY` for high-sensitivity apps. |
|
||||
| `maxToolCallsPerTurn` | 25 | Tool calls allowed in one answer. |
|
||||
| `maxParallelToolCalls` | 4 | Independent read tools that run at the same time. |
|
||||
| `maxRowsToModel` / `maxCellChars` | 50 / 500 | Caps on what the model sees (the kernel applies them). |
|
||||
| `maxTurnSeconds` | 300 | Wall-clock limit for one answer. |
|
||||
| `budgets` | none | `userDaily{Tokens,CostMicros}{Soft,Hard}` and `instanceMonthly{Tokens,CostMicros}{Soft,Hard}`. A soft limit adds a warning. A hard limit refuses new turns (429) and stops a running turn after its current step. Tokens counted are uncached input, cache writes and output. Cost is in micro-USD. |
|
||||
| `maxTurnsPerUserPerMinute` / `maxConcurrentTurnsPerUser` | 10 / 1 | Rate limits. |
|
||||
| `conversationRetentionDays` / `toolResultRetentionDays` / `approvalRetentionDays` | 90 / 30 / 365 | Used by `assistantRetention`. |
|
||||
| `retentionSchedulerName` | none | Runs `assistantRetention` daily on that scheduler. |
|
||||
| `ownerSecurityKeyType` | `assistant_user_id` | Key type of the owner record locks. |
|
||||
| `pricing` | Anthropic list prices, 2026-10 | USD per million tokens per model, used for cost and budgets. |
|
||||
| `allowedWidgetNames` | none | Dashboard widgets `render_widget` may render. The kernel denies every widget not on this list. This config list is the **only** way to allow a widget: QQQ widget meta-data has no supplemental hook, so there is no per-widget "assistant-safe" flag. Allow only widgets that render the same data for every user who can see them. |
|
||||
| `hiddenWidgetNames` | none | Widgets that are never rendered, even when allowed. |
|
||||
| `customRedactionPatterns` | none | Extra regular expressions the kernel redacts from tool results. |
|
||||
| `killSwitchPollMillis` | 2000 | How often a running turn re-checks the kill switch while it waits on the model. |
|
||||
| `providerTypes` | none | `withProviderType(...)`: the types the Providers screen offers (`AnthropicProviderType`). |
|
||||
| `allowedApiKeyEnvNames` | none | Extra environment variable names a provider row may name as its key. Each type's default is always allowed. |
|
||||
| `allowedBaseUrls` | none | Base URL overrides a provider row may use. The type's own URL is always allowed. |
|
||||
| `secretResolver` | `System::getenv` | How a key variable name becomes the key (a host secret store, or tests). |
|
||||
| `providerTestTimeoutSeconds` | 30 | How long Test connection waits for the model. |
|
||||
| `homeMaxRows` | 20000 | Rows per table the app home reads for its period; it says when totals are partial. |
|
||||
| `tablePathPrefix` | `/app` | The front of the links the app home makes to tables and records. |
|
||||
|
||||
At runtime, an admin can override the kill switch, the main model and effort, and the budgets in the single **`assistant_policy`** row.
|
||||
|
||||
A running turn notices the kill switch in two ways:
|
||||
- It re-reads the switch before every model call and tool step.
|
||||
- A watcher polls it every `killSwitchPollMillis` while the turn waits on the model.
|
||||
|
||||
When a turn sees the switch on, it cancels every turn running on that replica. If the policy row cannot be read, the switch counts as **on**: it fails closed.
|
||||
|
||||
## Permissions
|
||||
|
||||
| Permission | Grants |
|
||||
|---|---|
|
||||
| `assistant.hasAccess` | Use the panel. It grants **no data access**: the assistant reads only what the user can read anyway. |
|
||||
| `assistant.admin` | The Assistant app (home, settings and audit tables), Test connection and the retention process. |
|
||||
|
||||
There is no assistant-specific data permission. Everything the kernel reads is checked against the user's normal table permissions and record locks. The QBit never uses a system session (an ArchUnit test enforces this).
|
||||
|
||||
When the QBit is enabled, it registers the supplemental instance meta-data `assistant`. The v1 `/metaData` response publishes it as `supplementalInstanceMetaData.assistant: {"available": true, "version": 1, "basePath": "/qqq/v1/assistant"}`. The Next UI only probes `/config` when that object is present.
|
||||
|
||||
### Record locks on the assistant's own tables
|
||||
|
||||
Conversation data belongs to its user. Every user-owned table has a record lock on `userId` with key type `assistant_user_id`:
|
||||
- The panel routes add the user's own id to their session, so users only ever see their own rows.
|
||||
- Admins see everyone's rows in the Assistant app through the key type's all-access key, `assistant_user_id_all_access`. Grant that key to `assistant.admin` holders from your authentication customizer:
|
||||
|
||||
```java
|
||||
// in your QAuthenticationModuleCustomizerInterface.customizeSession(...)
|
||||
AssistantSecurity.applySessionKeys(qSession, assistantConfig);
|
||||
```
|
||||
|
||||
## Data policy
|
||||
|
||||
What reaches the model provider:
|
||||
- the tool definitions
|
||||
- a fixed safety prompt
|
||||
- an app digest (labels and descriptions, no data)
|
||||
- the user's name, timezone and readable-table list
|
||||
- the conversation's text
|
||||
- tool results produced by the kernel.
|
||||
|
||||
The kernel applies these rules to tool results:
|
||||
- Hidden fields, password fields and fields with a security lock are never sent.
|
||||
- Exposure `METADATA_ONLY` and `MASKED` fields are filtered or masked.
|
||||
- Rows are capped at 50 and cells at 500 characters.
|
||||
- Secrets such as keys, JWTs and card numbers are redacted.
|
||||
- The `assistant_*` tables are never visible to the model.
|
||||
|
||||
Old tool results are cleared from the context of later turns; only one-line summaries remain.
|
||||
|
||||
Stored in your database:
|
||||
- every message
|
||||
- every tool call: sanitized input, outcome, permission check, row count, duration, redactions, and the model-visible result. After `toolResultRetentionDays`, the result is cleared, stream events are deleted, and render payloads and record references are removed from stored messages. Summaries and answer text stay until `conversationRetentionDays`.
|
||||
- turn accounting: tokens, cache reads and writes, and cost
|
||||
- streamed events, kept for replay
|
||||
- feedback
|
||||
- daily usage.
|
||||
|
||||
Logs never contain message content.
|
||||
|
||||
## HTTP API
|
||||
|
||||
Base path `/qqq/v1/assistant`. Every request is authenticated through the app's normal session (cookie, bearer token or API key). Request bodies must be JSON.
|
||||
|
||||
| Method | Path | |
|
||||
|---|---|---|
|
||||
| GET | `/config` | Feature probe: `{enabled, reason?, shortcut, model, limits, features}`. A 404 means the QBit is not installed. |
|
||||
| GET / POST | `/conversations` | List your conversations (`?status=ARCHIVED`), or create one. |
|
||||
| GET / PATCH / DELETE | `/conversations/{id}` | Load with paged messages (`?before=&limit=`), rename / pin / archive, or delete. |
|
||||
| POST | `/conversations/{id}/turns` | Ask a question. The response is an SSE stream. |
|
||||
| GET | `/turns/{id}/events?after={seq}` | Replay a turn's events after a sequence number, then follow it live. |
|
||||
| POST | `/turns/{id}/cancel` | Stop an answer. |
|
||||
| POST | `/messages/{id}/feedback` | Rate an answer: `{rating: 1 or -1, reason?, comment?}`. |
|
||||
|
||||
The stream sends these events, each with a `seq`:
|
||||
- `message.start`, `text.delta`
|
||||
- `tool.start`, `tool.result` (with `render` and `recordRefs`)
|
||||
- `ui.navigate`, `notice`
|
||||
- `usage`, `message.end`
|
||||
- `error`
|
||||
- `ping` every 15 seconds.
|
||||
|
||||
The stream ends after `message.end`. Thinking is never streamed.
|
||||
|
||||
### SSE behind a proxy (Traefik, nginx)
|
||||
|
||||
- The responses carry `Cache-Control: no-cache` and `X-Accel-Buffering: no`. Do not compress or buffer `text/event-stream`.
|
||||
- Give the routes an idle timeout longer than the 15-second ping interval and a total timeout of at least `maxTurnSeconds`. For Traefik, raise the entrypoint's `respondingTimeouts` (`readTimeout`, `writeTimeout`, `idleTimeout`) or put the assistant routes on a router whose transport allows it. Don't add a buffering middleware to these routes.
|
||||
- A dropped connection does not stop the answer. The client resumes with `/turns/{id}/events?after=<last seq>`.
|
||||
|
||||
## Tables
|
||||
|
||||
All of these are standard, visible QQQ tables in the Assistant app. The model never reads any of them (AI exposure `NONE`).
|
||||
|
||||
| Table | Holds |
|
||||
|---|---|
|
||||
| `assistant_conversation` | Conversations. |
|
||||
| `assistant_message` | Messages (`partsJson`). |
|
||||
| `assistant_turn` | Turn accounting. |
|
||||
| `assistant_turn_event` | Stream events, for replay. |
|
||||
| `assistant_tool_call` | The audit of every tool call. |
|
||||
| `assistant_feedback` | Feedback on answers. |
|
||||
| `assistant_policy` | The kill switch and overrides. |
|
||||
| `assistant_usage_daily` | Usage rollups: per user per day, plus an instance row whose `userId` is null. |
|
||||
| `assistant_provider` | Provider settings: type, model, key variable (never the key), limits, last connection test. |
|
||||
| `assistant_model_price` | USD per million tokens per model, used for every call's cost. |
|
||||
| `assistant_usage` | One row per model call (a turn step or a connection test): user, conversation, turn, provider, model, status, latency, tokens, cost. Locked to its user like the other audit tables. |
|
||||
|
||||
Table names follow the QRun-IO naming rule: lowercase snake_case with the `assistant_` prefix, the same as the physical tables in `docs/schema-postgres.sql` (the reference DDL). Field names are camelCase. Map them to your columns with a table customizer. Upgrading from 0.1.0-RC.1, which used camelCase table names and the `assistantUserId` key type: see [UPGRADE.md](UPGRADE.md).
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
./mvnw verify # against the committed QQQ version
|
||||
./mvnw verify -Dqqq.snapshot.version=4.1.0-ASSISTDEV-SNAPSHOT # against a local QQQ build with #1078 + #1076
|
||||
```
|
||||
|
||||
Two test groups run in every build and fail it on any error:
|
||||
- the golden evals (JUnit tag `golden`): scripted conversations against a seeded fixture app
|
||||
- the permission red team (tag `redteam`).
|
||||
|
||||
The **live** evals run the same golden tasks against Claude. They are skipped unless both `ANTHROPIC_API_KEY` and `-Dassistant.live=true` are set:
|
||||
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=... ./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||
Apache 2.0.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Security Policy
|
||||
|
||||
* See Project [Security Policy](https://github.com/Kingsrook/qqq/blob/develop/SECURITY.md)
|
||||
@@ -0,0 +1,120 @@
|
||||
# Upgrading qbit-assistant
|
||||
|
||||
## 0.1.0-RC.3 to 0.1.0-RC.4: provider settings, prices, per-call usage, app home
|
||||
|
||||
Three new tables. Create them before you deploy (see `docs/schema-postgres.sql`, which also seeds the Anthropic prices):
|
||||
- `assistant_provider` (with the `api_key_status` column: it is filled on read and never written, but the backend selects it)
|
||||
- `assistant_model_price`
|
||||
- `assistant_usage`
|
||||
|
||||
Then, to keep answering exactly as before:
|
||||
1. Register the provider type: `config.withProviderType(new AnthropicProviderType())`. Keep `withModelProvider(AnthropicModelProvider.fromEnvironment())` as the fallback.
|
||||
2. Add one provider row (or seed it in your migration): type `anthropic`, model = your current main model, enabled, default, `apiKeyEnvName` = `ANTHROPIC_API_KEY` (or leave it empty for the default). No key value is ever written.
|
||||
3. Run **Test connection** on it.
|
||||
|
||||
Until a row exists, the provider registered in code answers, as in RC.3. Other changes: the app label is **Assistant**; the nav no longer lists the retention process (it is a table action on conversations) or the audit tables (they are child lists). Grants on `assistant.admin` cover everything new.
|
||||
|
||||
## 0.1.0-RC.1 to 0.1.0-RC.3: snake_case names
|
||||
|
||||
The rename shipped in 0.1.0-RC.3. 0.1.0-RC.2 on Maven Central is an accidental republish of the RC.1 code (see CHANGELOG.md), so upgrading from RC.2 is the same as upgrading from RC.1.
|
||||
|
||||
RC.3 applies the QRun-IO naming rule (owner decision, 2026-10-12): *"table names should always be lowercase and use _, and qbits should always be prefixed with their name"*. The QQQ table names, the owner security key type and the possible-value source change. Permissions do not. **This is a metadata-only change**: no table, column or index in your database changes, and no Liquibase or DDL step is needed.
|
||||
|
||||
### What changed
|
||||
|
||||
| Kind | RC.1 (and RC.2) name | RC.3 name |
|
||||
|---|---|---|
|
||||
| Table | `assistantConversation` | `assistant_conversation` |
|
||||
| Table | `assistantMessage` | `assistant_message` |
|
||||
| Table | `assistantTurn` | `assistant_turn` |
|
||||
| Table | `assistantTurnEvent` | `assistant_turn_event` |
|
||||
| Table | `assistantToolCall` | `assistant_tool_call` |
|
||||
| Table | `assistantFeedback` | `assistant_feedback` |
|
||||
| Table | `assistantPolicy` | `assistant_policy` |
|
||||
| Table | `assistantUsageDaily` | `assistant_usage_daily` |
|
||||
| Possible-value source (conversations) | `assistantConversation` | `assistant_conversation` |
|
||||
| Permissions | `assistant.hasAccess`, `assistant.admin` | unchanged (QQQ's standard `<base>.hasAccess` suffix; the `assistant` base already follows the rule) |
|
||||
| Security key type | `assistantUserId` | `assistant_user_id` |
|
||||
| All-access key | `assistantUserIdAllAccess` | `assistant_user_id_all_access` |
|
||||
|
||||
Unchanged: Java class names, field names (`userId`, `conversationId`, ...), the `assistantAdmin` app, the `assistantRetention` process, the `/qqq/v1/assistant` routes and the `assistant` supplemental instance meta-data.
|
||||
|
||||
The old names stay available as `@Deprecated` constants for one release, so migration code can refer to them: `<Entity>.LEGACY_TABLE_NAME`, `AssistantQBitConfig.LEGACY_DEFAULT_OWNER_KEY_TYPE` and `AssistantMetaDataBuilder.LEGACY_ALL_ACCESS_SUFFIX`. They will be removed in 0.2.0.
|
||||
|
||||
### Physical tables
|
||||
|
||||
`docs/schema-postgres.sql` already creates `assistant_*` tables. If your RDBMS backend mapped the old QQQ names to those tables (for example with `inferBackendName`), the new QQQ names now equal the physical names and nothing else is needed; the mapping becomes a no-op. If you created tables literally named `assistantConversation` and so on, either rename them:
|
||||
|
||||
```sql
|
||||
ALTER TABLE "assistantConversation" RENAME TO assistant_conversation;
|
||||
ALTER TABLE "assistantMessage" RENAME TO assistant_message;
|
||||
ALTER TABLE "assistantTurn" RENAME TO assistant_turn;
|
||||
ALTER TABLE "assistantTurnEvent" RENAME TO assistant_turn_event;
|
||||
ALTER TABLE "assistantToolCall" RENAME TO assistant_tool_call;
|
||||
ALTER TABLE "assistantFeedback" RENAME TO assistant_feedback;
|
||||
ALTER TABLE "assistantPolicy" RENAME TO assistant_policy;
|
||||
ALTER TABLE "assistantUsageDaily" RENAME TO assistant_usage_daily;
|
||||
```
|
||||
|
||||
or keep them and set `RDBMSTableBackendDetails.tableName` to the old name in your table customizer.
|
||||
|
||||
### Stored references to update
|
||||
|
||||
QQQ stores table names, permission names and key names outside this qbit. Update them in the same deployment. The examples are for Postgres with QQQ's default snake_case backend names; adjust the table and column names to your schema.
|
||||
|
||||
1. **Security keys.** Permission grants (`assistant.hasAccess`, `assistant.admin`) need no change. If your authentication customizer grants the all-access key itself rather than calling `AssistantSecurity.applySessionKeys`, grant `assistant_user_id_all_access`. If you set `ownerSecurityKeyType` explicitly, the all-access key is now `<keyType>_all_access`.
|
||||
|
||||
2. **Saved views and saved reports** on the assistant tables:
|
||||
|
||||
```sql
|
||||
UPDATE saved_view SET table_name = CASE table_name
|
||||
WHEN 'assistantConversation' THEN 'assistant_conversation'
|
||||
WHEN 'assistantMessage' THEN 'assistant_message'
|
||||
WHEN 'assistantTurn' THEN 'assistant_turn'
|
||||
WHEN 'assistantTurnEvent' THEN 'assistant_turn_event'
|
||||
WHEN 'assistantToolCall' THEN 'assistant_tool_call'
|
||||
WHEN 'assistantFeedback' THEN 'assistant_feedback'
|
||||
WHEN 'assistantPolicy' THEN 'assistant_policy'
|
||||
WHEN 'assistantUsageDaily' THEN 'assistant_usage_daily'
|
||||
ELSE table_name END
|
||||
WHERE table_name IN ('assistantConversation', 'assistantMessage', 'assistantTurn', 'assistantTurnEvent',
|
||||
'assistantToolCall', 'assistantFeedback', 'assistantPolicy', 'assistantUsageDaily');
|
||||
```
|
||||
|
||||
Run the same statement against `saved_report` (and `quick_saved_view` / `shared_saved_view` only if they store a table name in your schema).
|
||||
|
||||
3. **Audit table names.** QQQ audits reference tables through the `audit_table` lookup. Rename the rows so old and new audits stay under one table:
|
||||
|
||||
```sql
|
||||
UPDATE audit_table SET name = CASE name
|
||||
WHEN 'assistantConversation' THEN 'assistant_conversation'
|
||||
WHEN 'assistantMessage' THEN 'assistant_message'
|
||||
WHEN 'assistantTurn' THEN 'assistant_turn'
|
||||
WHEN 'assistantTurnEvent' THEN 'assistant_turn_event'
|
||||
WHEN 'assistantToolCall' THEN 'assistant_tool_call'
|
||||
WHEN 'assistantFeedback' THEN 'assistant_feedback'
|
||||
WHEN 'assistantPolicy' THEN 'assistant_policy'
|
||||
WHEN 'assistantUsageDaily' THEN 'assistant_usage_daily'
|
||||
ELSE name END
|
||||
WHERE name IN ('assistantConversation', 'assistantMessage', 'assistantTurn', 'assistantTurnEvent',
|
||||
'assistantToolCall', 'assistantFeedback', 'assistantPolicy', 'assistantUsageDaily');
|
||||
```
|
||||
|
||||
If a new-name row was already created (the app ran RC.3 before this update), repoint `audit.audit_table_id` from the old row to the new one first, then delete the old row.
|
||||
|
||||
4. **Anything else that stores a table name**: frontend links or bookmarks to `/app/.../assistantConversation`, Quick Search index rows (`quick_search_index.table_name`; reindex instead of editing), ESB topics or reports you configured by table name.
|
||||
|
||||
### Order
|
||||
|
||||
Deploy RC.3 and run the statements above in the same maintenance window. Until the update runs, saved views and reports on the assistant tables do not open, and admins who get the all-access key from their own customizer only see their own rows.
|
||||
|
||||
## 0.1.0-RC.6: tools through the UI API
|
||||
|
||||
Database (see `docs/schema-postgres.sql`):
|
||||
- new tables `assistant_data_access`, `assistant_pending_action`, `assistant_profile`, `assistant_skill` and `assistant_profile_skill`;
|
||||
- new columns `assistant_tool_call.ui_api_operation`, `http_status`, `audit_href`, `pending_action_id`;
|
||||
- new columns `assistant_policy.writes_require_confirmation`, `allowed_tools`, `max_rows_per_call`, `redact_pii`.
|
||||
|
||||
Runtime: the tools call this server's own `/qqq/v1` on `127.0.0.1` and the port the first assistant request arrived on. If the server is not reachable that way (a different bind address, a TLS-only listener), set `withUiApiBaseUrl(...)`. Grant `assistant.admin` holders the new tables through the qbit's existing admin permission (no new permission names).
|
||||
|
||||
Behavior: nothing is writable until an admin adds a READ_WRITE data access row; before that the assistant reads exactly what it did before, now through the UI API.
|
||||
@@ -0,0 +1,246 @@
|
||||
<?xml version="1.0"?>
|
||||
<!--
|
||||
~ QQQ - Low-code Application Framework for Engineers.
|
||||
~ Copyright (C) 2021-2022. Kingsrook, LLC
|
||||
~ 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
~ contact@kingsrook.com
|
||||
~ https://github.com/Kingsrook/
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ https://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
|
||||
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
|
||||
<!--
|
||||
See reference at https://checkstyle.sourceforge.io/checks.html
|
||||
-->
|
||||
<module name = "Checker">
|
||||
<property name="charset" value="UTF-8"/>
|
||||
|
||||
<property name="severity" value="warning"/>
|
||||
|
||||
<property name="fileExtensions" value="java, properties, xml"/>
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
|
||||
<module name="FileTabCharacter">
|
||||
<property name="eachLine" value="true"/>
|
||||
</module>
|
||||
|
||||
<!--
|
||||
<module name="LineLength">
|
||||
<property name="max" value="100"/>
|
||||
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
|
||||
</module>
|
||||
-->
|
||||
|
||||
<module name="TreeWalker">
|
||||
<module name="SuppressWarningsHolder"/>
|
||||
<module name="OuterTypeFilename"/>
|
||||
<module name="IllegalTokenText">
|
||||
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
|
||||
<property name="format" value="\\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
|
||||
<property name="message" value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
|
||||
</module>
|
||||
<module name="AvoidEscapedUnicodeCharacters">
|
||||
<property name="allowEscapesForControlCharacters" value="true"/>
|
||||
<property name="allowByTailComment" value="true"/>
|
||||
<property name="allowNonPrintableEscapes" value="true"/>
|
||||
</module>
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="OneTopLevelClass"/>
|
||||
<module name="NoLineWrap"/>
|
||||
<module name="EmptyBlock">
|
||||
<property name="option" value="TEXT"/>
|
||||
<property name="tokens" value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
|
||||
</module>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="LeftCurly">
|
||||
<property name="option" value="nl"/>
|
||||
</module>
|
||||
<module name="RightCurly">
|
||||
<property name="option" value="alone"/>
|
||||
</module>
|
||||
<!--
|
||||
<module name="WhitespaceAround">
|
||||
<property name="allowEmptyConstructors" value="true"/>
|
||||
<property name="allowEmptyMethods" value="true"/>
|
||||
<property name="allowEmptyTypes" value="true"/>
|
||||
<property name="allowEmptyLoops" value="true"/>
|
||||
<message key="ws.notFollowed"
|
||||
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
|
||||
<message key="ws.notPreceded"
|
||||
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
|
||||
</module>
|
||||
-->
|
||||
<module name="OneStatementPerLine"/>
|
||||
<module name="MultipleVariableDeclarations"/>
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<module name="FallThrough"/>
|
||||
<module name="UpperEll"/>
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="EmptyLineSeparator">
|
||||
<property name="allowNoEmptyLineBetweenFields" value="true"/>
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<property name="id" value="SeparatorWrapDot"/>
|
||||
<property name="tokens" value="DOT"/>
|
||||
<property name="option" value="nl"/>
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<property name="id" value="SeparatorWrapComma"/>
|
||||
<property name="tokens" value="COMMA"/>
|
||||
<property name="option" value="EOL"/>
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/258 -->
|
||||
<property name="id" value="SeparatorWrapEllipsis"/>
|
||||
<property name="tokens" value="ELLIPSIS"/>
|
||||
<property name="option" value="EOL"/>
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/259 -->
|
||||
<property name="id" value="SeparatorWrapArrayDeclarator"/>
|
||||
<property name="tokens" value="ARRAY_DECLARATOR"/>
|
||||
<property name="option" value="EOL"/>
|
||||
</module>
|
||||
<module name="SeparatorWrap">
|
||||
<property name="id" value="SeparatorWrapMethodRef"/>
|
||||
<property name="tokens" value="METHOD_REF"/>
|
||||
<property name="option" value="nl"/>
|
||||
</module>
|
||||
<module name="PackageName">
|
||||
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
|
||||
<message key="name.invalidPattern"
|
||||
value="Package name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="TypeName">
|
||||
<message key="name.invalidPattern"
|
||||
value="Type name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="MemberName">
|
||||
<property name="format" value="^[_a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
|
||||
<message key="name.invalidPattern" value="Member name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="ParameterName">
|
||||
<property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
|
||||
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="CatchParameterName">
|
||||
<property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
|
||||
<message key="name.invalidPattern" value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="LocalVariableName">
|
||||
<property name="tokens" value="VARIABLE_DEF"/>
|
||||
<property name="format" value="^[a-zA-Z]([a-z0-9A-Z][a-zA-Z0-9]*)?$"/>
|
||||
<message key="name.invalidPattern" value="Local variable name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="ClassTypeParameterName">
|
||||
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
|
||||
<message key="name.invalidPattern" value="Class type name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="MethodTypeParameterName">
|
||||
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
|
||||
<message key="name.invalidPattern" value="Method type name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="InterfaceTypeParameterName">
|
||||
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][_A-Z0-9]*$)"/>
|
||||
<message key="name.invalidPattern" value="Interface type name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="NoFinalizer"/>
|
||||
<module name="GenericWhitespace">
|
||||
<message key="ws.followed" value="GenericWhitespace ''{0}'' is followed by whitespace."/>
|
||||
<message key="ws.preceded" value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
|
||||
<message key="ws.illegalFollow" value="GenericWhitespace ''{0}'' should followed by whitespace."/>
|
||||
<message key="ws.notPreceded" value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
|
||||
</module>
|
||||
<module name="Indentation">
|
||||
<property name="basicOffset" value="3"/>
|
||||
<property name="braceAdjustment" value="0"/>
|
||||
<property name="caseIndent" value="3"/>
|
||||
<property name="throwsIndent" value="6"/>
|
||||
<property name="lineWrappingIndentation" value="3"/>
|
||||
<property name="arrayInitIndent" value="6"/>
|
||||
</module>
|
||||
<!--
|
||||
<module name="AbbreviationAsWordInName">
|
||||
<property name="ignoreFinal" value="false"/>
|
||||
<property name="allowedAbbreviationLength" value="1"/>
|
||||
</module>
|
||||
<module name="OverloadMethodsDeclarationOrder"/>
|
||||
<module name="VariableDeclarationUsageDistance"/>
|
||||
<module name="CustomImportOrder">
|
||||
<property name="sortImportsInGroupAlphabetically" value="true"/>
|
||||
<property name="separateLineBetweenGroups" value="true"/>
|
||||
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
|
||||
</module>
|
||||
-->
|
||||
<module name="CustomImportOrder">
|
||||
<property name="customImportOrderRules" value="SPECIAL_IMPORTS###STANDARD_JAVA_PACKAGE###THIRD_PARTY_PACKAGE###STATIC"/>
|
||||
<property name="specialImportsRegExp" value="^javax\."/>
|
||||
<property name="standardPackageRegExp" value="^java\."/>
|
||||
<property name="sortImportsInGroupAlphabetically" value="true"/>
|
||||
<property name="separateLineBetweenGroups" value="false"/>
|
||||
</module>
|
||||
<module name="MethodParamPad"/>
|
||||
<module name="NoWhitespaceBefore">
|
||||
<property name="tokens" value="COMMA, SEMI, POST_INC, POST_DEC, DOT, ELLIPSIS, METHOD_REF"/>
|
||||
<property name="allowLineBreaks" value="true"/>
|
||||
</module>
|
||||
<module name="ParenPad"/>
|
||||
<module name="OperatorWrap">
|
||||
<property name="option" value="NL"/>
|
||||
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF "/>
|
||||
</module>
|
||||
<module name="AnnotationLocation">
|
||||
<property name="id" value="AnnotationLocationMostCases"/>
|
||||
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
|
||||
</module>
|
||||
<module name="AnnotationLocation">
|
||||
<property name="id" value="AnnotationLocationVariables"/>
|
||||
<property name="tokens" value="VARIABLE_DEF"/>
|
||||
<property name="allowSamelineMultipleAnnotations" value="true"/>
|
||||
</module>
|
||||
<module name="JavadocMethod">
|
||||
<property name="allowMissingParamTags" value="true"/>
|
||||
<property name="allowMissingReturnTag" value="true"/>
|
||||
<property name="allowedAnnotations" value="Override, Test"/>
|
||||
</module>
|
||||
<module name="MissingJavadocMethod">
|
||||
<property name="scope" value="private"/>
|
||||
</module>
|
||||
<module name="MissingJavadocType">
|
||||
<property name="scope" value="private"/>
|
||||
</module>
|
||||
<module name="MethodName">
|
||||
<property name="format" value="^[a-z][a-zA-Z0-9_]*$"/>
|
||||
<message key="name.invalidPattern"
|
||||
value="Method name ''{0}'' must match pattern ''{1}''."/>
|
||||
</module>
|
||||
<module name="EmptyCatchBlock">
|
||||
<property name="exceptionVariableName" value="expected"/>
|
||||
</module>
|
||||
<module name="CommentsIndentation"/>
|
||||
|
||||
<!-- this would be nice, but requires the the @inheritDoc javadoc tag... -->
|
||||
<module name="MissingOverride"/>
|
||||
|
||||
</module>
|
||||
<module name="Header">
|
||||
<property name="headerFile" value="checkstyle/license.txt"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
<property name="ignoreLines" value="3"/>
|
||||
</module>
|
||||
<module name="SuppressWarningsFilter"/>
|
||||
</module>
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* QQQ - Low-code Application Framework for Engineers.
|
||||
* Copyright (C) 2021-2025. Kingsrook, LLC
|
||||
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
|
||||
* contact@kingsrook.com
|
||||
* https://github.com/Kingsrook/
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
@@ -1,28 +0,0 @@
|
||||
# Getting Started
|
||||
|
||||
Targets Java 21, Maven 3.8 or later, and QQQ 4.0.0. Maven resolves the framework dependencies from Maven Central.
|
||||
|
||||
1. Choose **Use this template** on GitHub, then clone the repository you created.
|
||||
2. In `pom.xml`, set your own `groupId`, `artifactId`, name, description, and version.
|
||||
3. Use your IDE's package refactoring to rename `com.kingsrook.qbits.example` throughout `src/`. Rename the `Example*` classes and update their imports and references with the IDE's rename refactoring.
|
||||
4. Update the QBit producer's `GROUP_ID`, `ARTIFACT_ID`, and `VERSION` constants to match your project. Give the metadata names their own stable names before combining the QBit with other examples.
|
||||
5. Build the generated project:
|
||||
|
||||
```bash
|
||||
mvn clean verify
|
||||
```
|
||||
|
||||
The repository provides example Java sources; customization uses normal package/class refactoring. Keep example coordinates unpublished. After customizing, add tests for your QBit's behavior before setting up its publishing workflow.
|
||||
|
||||
## Register with a host application
|
||||
|
||||
The following uses the original example names; substitute the names chosen above:
|
||||
|
||||
```java
|
||||
new ExampleExtensionQBitProducer()
|
||||
.withConfig(new ExampleExtensionQBitConfig()
|
||||
.withTargetTableName("order"))
|
||||
.produce(qInstance, "my-extension");
|
||||
```
|
||||
|
||||
Register the target table before producing the extension, then implement its customizer. See [Extension Patterns](01-extension-patterns.md).
|
||||
@@ -1,16 +0,0 @@
|
||||
# Extension Patterns
|
||||
|
||||
[ExampleExtensionQBitProducer](../src/main/java/com/kingsrook/qbits/example/ExampleExtensionQBitProducer.java) registers the QBit identity and calls `applyTableCustomizations` for the configured target. That method is the extension point: look up the table, validate that it exists, and call your customized [ExampleTableCustomizer](../src/main/java/com/kingsrook/qbits/example/customizers/ExampleTableCustomizer.java).
|
||||
|
||||
```java
|
||||
QTableMetaData table = qInstance.getTable(tableName);
|
||||
if(table == null)
|
||||
{
|
||||
throw new QException("Target table not found: " + tableName);
|
||||
}
|
||||
new ExampleTableCustomizer().customize(table);
|
||||
```
|
||||
|
||||
When implementing this method, add `throws QException` to its declaration. Run the config's `validate(QInstance, List<String>)` before registering metadata, and report validation errors rather than silently ignoring a missing target. The uncustomized template contains placeholders for this behavior.
|
||||
|
||||
For record hooks, use QQQ's existing table customizer interfaces or `AbstractPreInsertCustomizer`. Its `apply(List<QRecord>)` method returns the records for the next stage; register the customizer through the table's `TableCustomizers.PRE_INSERT_RECORD` role. Check the actual QQQ interface before adding another hook. Add tests proving that the intended table changes and invalid configurations are handled.
|
||||
@@ -0,0 +1,335 @@
|
||||
# qbit-assistant: settings, usage and app home (design)
|
||||
|
||||
The assistant's overall design is the QQQ spec `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md` (owner decisions D1 to D7). This note covers what 0.1.0-RC.4 adds on top of it: provider settings, per-call usage, prices and the app home.
|
||||
|
||||
Owner request (2026-10-13): *"it needs a good homepage for the app for it, and it needs a settings screen where you setup the API keys, provider, test connectivity etc. and the app homepage should show health, usage, costs, etc."*
|
||||
|
||||
## Data
|
||||
|
||||
All of it is in standard QQQ tables with full record screens (D6), prefixed `assistant_`, secured by `assistant.admin` and, for user-owned rows, the `assistant_user_id` record lock. Every `assistant_*` table has AI exposure `NONE`.
|
||||
|
||||
| Table | Written by | Purpose |
|
||||
|---|---|---|
|
||||
| `assistant_provider` | admins | Which provider and model answer, the key reference, limits, the last connection test. |
|
||||
| `assistant_model_price` | admins (seeded) | USD per million tokens per model. |
|
||||
| `assistant_usage` | the qbit only | One row per model call: turn steps (`TURN`) and connection tests (`TEST`). |
|
||||
|
||||
`assistant_turn` keeps the per-turn totals and `assistant_usage_daily` the budget rollups, as before. `assistant_usage` adds the per-call detail the home needs: the provider, the failures and latency.
|
||||
|
||||
## API keys
|
||||
|
||||
Decision: **reference, not storage.** A provider row holds the NAME of an environment variable (`apiKeyEnvName`); `ProviderService` resolves it through `config.getSecretResolver()` (default `System::getenv`) when it builds a client.
|
||||
|
||||
Why:
|
||||
- QQQ core has no encrypted or secret field type. The key-provider SPI and Tink cipher in the RC.6 batch (qqq#1123, #1107) encrypt streamed backup artifacts, not columns, and are not released.
|
||||
- Spec §2.8: keys are `${env.*}` secrets and are never stored in tables.
|
||||
- Deployments already hold the key in a secret store (kof22: Infisical, then an ExternalSecret, then the pod env). Rotating it there is the "replace key" step; the database never has a copy to leak through a backup, an export or the API.
|
||||
|
||||
Guards:
|
||||
- Only allow-listed names: each registered type's default (`ANTHROPIC_API_KEY`) plus `allowedApiKeyEnvNames`. Otherwise an admin could aim a row at `DATABASE_PASSWORD` and send it to a provider.
|
||||
- A base URL override must be in `allowedBaseUrls`. Otherwise an admin could send the real key to their own host.
|
||||
- The variable name must look like one (`[A-Z_][A-Z0-9_]*`), so a key pasted into the field is refused before it is stored. The error never echoes the value.
|
||||
- `apiKeyStatus` is a real, read-only column filled by the post-query customizer: `Set • …abcd (from VAR)` (no characters for keys under 12) or `Not set`. Saves drop it, so it is always null in the database. (A virtual field cannot sit in a base section in QQQ 4.1, hence the column.)
|
||||
- Clients are cached by row settings and a SHA-256 of the key. Keys are never logged, and neither `toString` nor the errors contain one.
|
||||
|
||||
## Choosing the provider
|
||||
|
||||
`ProviderService.resolve(policyModel)`:
|
||||
1. The enabled row marked default (marking one default unmarks the others), else the first enabled row.
|
||||
2. With no enabled row, the provider registered in code (`withModelProvider`) and the policy's main model: hosts that never add a row keep working.
|
||||
3. A row that cannot be used (no key, a disallowed name or URL, an uninstalled type) makes the assistant report `NOT_CONFIGURED` rather than fall back silently.
|
||||
|
||||
The model is the row's, else the policy's main model. The rows and prices are cached for `policyCacheSeconds` and dropped on any change.
|
||||
|
||||
## Limits
|
||||
|
||||
- **Monthly cost cap (USD):** checked when a turn starts (429 `BUDGET`) and before each model call of a running turn, from the provider's `assistant_usage` cost since the 1st (UTC).
|
||||
- **Max output tokens per request:** lowers the request's `max_tokens`.
|
||||
- **Max concurrent requests:** a per-provider semaphore around each model call on this replica.
|
||||
|
||||
These sit next to the existing policy budgets (per user per day, per instance per month), which still apply.
|
||||
|
||||
## Test connection
|
||||
|
||||
A record action on `assistant_provider`, as a standard streamed ETL with Review and Result summary lines and no custom form.
|
||||
- **Review** lists the providers, the masked key status and every settings problem, without calling anything.
|
||||
- **Result** makes one call per provider: the prompt "Connection test. Reply with the single word OK.", at most 32 output tokens, effort low. It reports `connected to <model> in <n> ms`, or a hint, the kind, the HTTP status and the provider's own credential-free message.
|
||||
|
||||
The result goes on the row (`lastTest*`) and into `assistant_usage` (`TEST`), so a test's cost is counted like any other call.
|
||||
|
||||
## Cost
|
||||
|
||||
`cost = input × in + output × out + cacheRead × read + cacheWrite5m × w5 + cacheWrite1h × w1`, in micro-dollars, rounded up (`ModelPricing.costMicros`).
|
||||
|
||||
Prices come from the `assistant_model_price` row for (type, model). Empty cache prices are 0.1x, 1.25x and 2x the input price. A model without a row uses the `pricing` config map, else costs 0. A price change affects later calls only; each usage row keeps the cost it was recorded with.
|
||||
|
||||
## App home
|
||||
|
||||
One HTML widget (`assistantHome`) on the Assistant app. It is the only place this data is summarized: no other dashboard repeats it, and the developer panel stays per-record.
|
||||
|
||||
`AssistantHomeData` reads the tables as the viewing admin, at most `homeMaxRows` rows each, for the last 30 days (UTC) and the current month, and says when totals are partial. `AssistantHomeView` renders it in flow and grid layout only:
|
||||
- no tables, fixed widths or inner scroll areas
|
||||
- inherited text colors, so light and dark both work
|
||||
- a status row, one row per provider, then cards for usage by day, costs, users, tools and failures.
|
||||
|
||||
Every section has an empty state; nothing is invented.
|
||||
|
||||
The nav is the home plus the main tables: Providers, Conversations, Model prices, Policy. Messages, turns, tool calls, feedback and model calls are child lists on a conversation, and model calls also on a provider. Processes are actions on their tables.
|
||||
|
||||
## Strict tools (0.1.0-RC.5)
|
||||
|
||||
**Incident (kof22, 2026-10-13).** Every turn failed on its first model call with 400 `invalid_request_error`: "The compiled grammar is too large, which would cause performance issues. Simplify your tool schemas or reduce the number of strict tools."
|
||||
- The request sent all ten read tools with `strict: true`.
|
||||
- Anthropic compiles every strict schema in a request into one grammar.
|
||||
- The request was inside every documented limit: 20 strict tools, 24 optional parameters, 16 union parameters. The real limit is not published.
|
||||
- The log line only said `INVALID_REQUEST httpStatus=400`, so the reason was invisible.
|
||||
|
||||
**Decision.**
|
||||
- **No tool is strict by default.** `AssistantQBitConfig.strictToolNames` opts tools in.
|
||||
- Strict mode only guaranteed schema-valid input. The kernel already validates every input and returns `INVALID_INPUT` results, and the UI-API tools (below) go through the same validation as the UI.
|
||||
- If a provider still refuses strict schemas (`ModelProviderException.isStrictSchemaRejected`), the turn retries once with no strict tools and logs a WARN.
|
||||
|
||||
**Budget.**
|
||||
- `AnthropicRequestContractTest` fails the build when the strict tools of the default request exceed 3 tools, 6 optional parameters or 2 union parameters. These budgets are far below the shape that failed.
|
||||
- It also checks the documented request rules:
|
||||
- adaptive thinking without `budget_tokens`, and no sampling parameters;
|
||||
- a valid effort, and no forced `tool_choice`;
|
||||
- at most 4 cache breakpoints, with longer TTLs first;
|
||||
- a user-first, user-last message order;
|
||||
- strict-schema keywords.
|
||||
|
||||
**Real-API check (dev).** `ANTHROPIC_API_KEY=... ./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am` runs the live golden evals. They send exactly this request shape.
|
||||
|
||||
**Diagnostics.** On a 4xx the provider's error type, sanitized message and request id are:
|
||||
- logged at WARN;
|
||||
- recorded as the `assistant_usage` request id;
|
||||
- shown to `assistant.admin` holders, in the panel's error and in Test connection.
|
||||
|
||||
## Owner decisions (2026-10-13)
|
||||
|
||||
Owner: *"the agent should have to go through the same API that the UIUX does. that way it is held to the same security boundaries etc"*, plus the ability to configure the assistant and verify its security and data access.
|
||||
|
||||
1. **Tools via the UI API.** Every tool that reads or writes data, or runs a process, report or widget, runs a spec'd `/qqq/v1` operation with the calling user's own session. That means the UI's authentication, permission checks, record locks, validation, audit and error mapping. There are no direct core data actions and no elevated sessions.
|
||||
2. **Data access is configured and verifiable in the UI.**
|
||||
- Each table and process has an AI data access setting: NONE, READ or READ_WRITE. Sensitive tables default to NONE.
|
||||
- Admins can see what the assistant could do for a given user, and why.
|
||||
3. **Writes need confirmation.** A write tool only *proposes* the change, as a pending action card. Nothing changes until the user confirms in the panel, unless the policy turns confirmation off.
|
||||
4. **Persona and skills, never more access** (owner, 2026-10-13): *"in the config for the AI settings, we should be able to set a name and personality and extra skills etc for the agent - and again - the agent should be limited to only using our UIUX API and being able to only do the things that the currently logged in user could do with the same UIUX API via the UIUX"*.
|
||||
- **Profiles** (`assistant_profile`, admin-edited): display name, icon, personality (tone instructions, at most 2,000 characters), greeting and up to 6 starter prompts.
|
||||
- One profile is the default. Others are scoped to an app, to users holding a permission (a role), or to both. The most specific profile wins.
|
||||
- `/assistant/config` returns the profile for the panel header, the greeting and the starter prompts.
|
||||
- **Skills** (`assistant_skill`, linked to profiles through `assistant_profile_skill`): named Markdown instruction packs of at most 6,000 characters, with a description, an enabled flag, trigger keywords and apps.
|
||||
- A skill is read only when relevant: a keyword appears in the question, the user is in one of its apps, or it has neither, in which case it is always read.
|
||||
- All skills read for one question total at most 12,000 characters.
|
||||
- Profile and skill text goes into the per-user system block, framed as "tone and know-how only". The rules come first, and rule 10 says these can never override the rules or give other tools, data or permissions.
|
||||
- **Hard guarantee:**
|
||||
- Every data, process, report or widget capability is a `/qqq/v1` operation, called through the gateway (core `UiApiInvoker` once it is released) with the CURRENT user's session.
|
||||
- The tool list is the spec'd operations ∩ data access ∩ policy. Profiles and skills are never read when tools are built or run.
|
||||
- It is enforced by ArchUnit: the tool, UI API and access code may not use QQQ table, process, report, dashboard or async actions, the core AI kernel, or the profile and skill classes. It is also enforced by a runtime guard: `AssistantStore` refuses any table that is not `assistant_*`.
|
||||
- `UiApiToolsSecurityTest.testDenialMatrix` checks that a user without permission gets the identical status and message from the UI API and through the assistant for query, get, insert, update and delete. The assistant has no process or report tool, and process data access defaults to NONE.
|
||||
5. All other open questions in this section were decided as recommended (shared rule: "all recommendations accepted").
|
||||
|
||||
## Tools through the UI API (0.1.0-RC.6)
|
||||
|
||||
### Transport: loopback HTTP with the user's session
|
||||
|
||||
`UiApiGateway.invoke(UiApiCall)` makes an HTTP request to this server's own `/qqq/v1`, carrying the user's `sessionUUID` cookie and `X-QQQ-Invoked-By: assistant`.
|
||||
- Only operations defined by `MiddlewareVersionV1`'s endpoint specs can be called. Anything else, including the assistant's own raw routes, is refused before a request is made.
|
||||
- A call without a session is also refused.
|
||||
|
||||
**Why loopback rather than calling the spec handlers in process.** The spec's `buildInput(Context)`, session setup, the version's `preExecute`, Javalin filters, permission checks and error mapping all hang off the Javalin request pipeline.
|
||||
- Calling the executors directly would skip some of these and drift over time.
|
||||
- Building a synthetic Javalin `Context` relies on internal API.
|
||||
- A request to the server's own port runs the identical pipeline by construction. It costs one local hop, which is milliseconds next to a model call.
|
||||
|
||||
This matches core's design (`docs/UI-API-EXTENSIONS.md` §5, `UiApiInvoker`, QRun-IO/qqq#1128).
|
||||
- `LoopbackUiApiGateway` is the stand-in until a QQQ release has the invoker. Then an adapter over `UiApiInvoker.forServer(server)` replaces it (or a host injects one with `withUiApiGateway`), and nothing else changes.
|
||||
- The base URL is `uiApiBaseUrl` if configured. Otherwise it is `127.0.0.1` plus the local port the first assistant request arrived on, so in a multi-replica deployment the call stays on the replica that holds the session's process state.
|
||||
|
||||
### The tools
|
||||
|
||||
| tool | `/qqq/v1` operation |
|
||||
|---|---|
|
||||
| `list_tables` | `GET /metaData` (tables with the user's read/insert/edit/delete flags) |
|
||||
| `describe_table` | `GET /metaData/table/{tableName}` |
|
||||
| `query_records` | `POST /table/{tableName}/query` (plus `.../count` when there are more rows) |
|
||||
| `count_records` | `POST /table/{tableName}/count` |
|
||||
| `get_record` | `GET /table/{tableName}/{primaryKey}` |
|
||||
| `search_records` | `POST /search` |
|
||||
| `render_widget` | `POST /widget/{widgetName}` |
|
||||
| `get_record_history` | `GET /table/{tableName}/{primaryKey}`, then `POST /table/{tableName}/query` on `audit_table`, `audit` and `audit_detail` |
|
||||
| `create_record` / `update_record` / `delete_record` | `POST /table/{tableName}` / `PATCH /table/{tableName}/{primaryKey}` / `DELETE /table/{tableName}/{primaryKey}` |
|
||||
|
||||
`navigate` and `search_help` stay on the core kernel because they read no records:
|
||||
- `navigate` only builds an `/app` link, and the page enforces permissions when it opens.
|
||||
- `search_help` reads help text from metadata.
|
||||
|
||||
Running processes and reports through the assistant (`/processes/...`, `/reports/...`) is not offered yet. Process data access rows are stored so that the screens can already show and set them.
|
||||
|
||||
### Layers (each one can only narrow the one before)
|
||||
|
||||
1. **The user's own permissions and record locks**, enforced by the UI API itself. A user who cannot do something in the UI gets the identical status and message through the assistant: the tool result is `DENIED`/`NOT_FOUND`/`INVALID_INPUT` with `"<operation> answered HTTP <status>: <message>"`.
|
||||
2. **Data access** (`assistant_data_access`, editable by `assistant.admin`). A row sets NONE, READ or READ_WRITE per table (`TABLE`) or process (`PROCESS`). Without a row:
|
||||
- tables whose AI exposure is NONE (the `assistant_*` tables, sessions, OAuth, and any table whose metadata says so) are NONE, and a row cannot raise them;
|
||||
- other tables are READ, so the assistant never writes unless an admin allows it;
|
||||
- processes are NONE.
|
||||
The write tools are offered only when some table is READ_WRITE.
|
||||
3. **Policy** (`assistant_policy`):
|
||||
- `writesRequireConfirmation` (default true);
|
||||
- `allowedTools` (empty allows all);
|
||||
- `maxRowsPerCall` (default 50, ceiling 200);
|
||||
- `redactPii` (default true: secrets, card numbers and SSNs are redacted, with the core `AiRedactor`).
|
||||
4. **AI field exposure** from table metadata:
|
||||
- NONE and METADATA_ONLY values never reach the model;
|
||||
- MASKED values are masked;
|
||||
- only VALUES fields can be filtered or sorted on.
|
||||
|
||||
### Writes and confirmation
|
||||
|
||||
With confirmation on, a write tool validates the table's data access and the fields. It then inserts an `assistant_pending_action` row (owner-locked, `PENDING`, expiring after `pendingActionTtlSeconds`, default 15 minutes) and returns a `pending_action` render, which the panel shows as a card. The model is told the change is not done.
|
||||
- `POST /qqq/v1/assistant/actions/{id}/confirm` claims the action (`RUNNING`, so a double click cannot run it twice). It then runs the stored operation through the UI API **with the confirming request's session** and records the outcome as `EXECUTED` or `FAILED`.
|
||||
- `POST /qqq/v1/assistant/actions/{id}/reject` runs nothing.
|
||||
- `GET /qqq/v1/assistant/actions/{id}` reads the action's state.
|
||||
- Only the user who proposed an action can see or decide it.
|
||||
|
||||
### Tool-call log
|
||||
|
||||
Each `assistant_tool_call` row records:
|
||||
- the user and the tool;
|
||||
- the parameters, with secrets redacted;
|
||||
- the UI API operation and the HTTP status the UI would have seen;
|
||||
- the rows touched and the outcome;
|
||||
- the pending action, if there is one;
|
||||
- an in-app link to the written record, whose page shows its audit entries.
|
||||
|
||||
A confirmed write adds its own row. The rows are a child list on conversations, and pending actions are another one.
|
||||
|
||||
### Tests
|
||||
|
||||
`UiApiToolsSecurityTest` runs the fixture app on a real QQQ application server. For each case it makes the UI's own request (a direct `/qqq/v1` call with the user's cookie) next to the assistant's tool call:
|
||||
- read denied: the same 403 and message;
|
||||
- write denied without the insert permission, even with READ_WRITE and no confirmation;
|
||||
- data access only narrows: NONE, READ, and sensitive tables that cannot be raised;
|
||||
- a confirmed write runs once, through the UI API, and is logged;
|
||||
- only the owner can decide an action;
|
||||
- only spec'd operations can be called, and never without a session;
|
||||
- the policy narrows the tools and caps rows.
|
||||
|
||||
The golden and red-team evals now run through the UI API too.
|
||||
|
||||
## Explain access and recent denials (0.1.0-RC.6)
|
||||
|
||||
- **Explain access:**
|
||||
- `GET /qqq/v1/assistant/access?table=&prompt=` returns, for the calling user and each table (or only the named table, or only the tables a prompt mentions):
|
||||
- the user's UI permissions, from `GET /qqq/v1/metaData` with their own session;
|
||||
- the assistant's data access and where it comes from (setting, default, or sensitive table);
|
||||
- each tool's operation, with allowed or the reason it would be denied (policy, data access, not visible in the UI, or no read/insert/edit/delete permission).
|
||||
- The `assistantAccess` widget on the Assistant home renders the same thing for the viewing admin.
|
||||
- Choosing *another* user would need that user's permissions without their session. QQQ core has no API to evaluate another user's permissions, and the assistant never builds or borrows a session. That part waits for a core API, so the report is always computed with the requester's own session.
|
||||
- **Recent denials:** the home's "Recent denials" card lists the newest tool calls the UI API, data access or the policy refused, with who, the table, the operation and the HTTP status, or the assistant setting that refused it.
|
||||
|
||||
## Owner decisions (2026-10-13), continued: write mode, the hard wall, audit attribution, providers
|
||||
|
||||
These were added on the same day. All recommendations below are accepted; we adjust once they can be seen working.
|
||||
|
||||
### W. Write mode: the assistant is just a UI client
|
||||
Owner: *"the assistant should be able to go into 'write mode' too - with a user selection or preference? allowing it to do things like create and schedule a report for you, or update a record. it should ALWAYS only have access via the UIUX API (the assistant is just a UI) and all permissions that the user has via the UIUX should always hard apply at a layer above the assistant. All auditing needs to be aware of this too and audit accordingly"*
|
||||
|
||||
- **Mode per conversation.** A panel toggle switches between **Read-only** (the default) and **Write**.
|
||||
- The default comes from the user's preference (`assistant_user_preference.default_write_mode`).
|
||||
- An admin policy can disable write mode globally (`assistant_policy.write_mode_allowed`), per role (`write_mode_permission`: only holders may switch to Write), or per table or process (data access READ or NONE).
|
||||
- **Read-only:** the write tools are not in the tool list at all. This is decided when the request is built, not by the model.
|
||||
- **Write:** every write is still a pending-action card that the user confirms.
|
||||
- A user may set "auto-confirm low-risk writes" only when the policy allows it (`auto_confirm_allowed`).
|
||||
- Low-risk means a single-record insert or update on a table the admin marked `auto_confirm_ok`.
|
||||
- Deletes, bulk operations, processes, report schedules and notifications are never auto-confirmed.
|
||||
- **What counts as a write.** All of these are `/qqq/v1` UI API operations:
|
||||
- insert, update and delete records;
|
||||
- run a process (`/processes/{name}/init` and steps; every step is a confirmed action);
|
||||
- create, save or schedule a report or saved view (through the saved-report and scheduled-job tables' own insert operations);
|
||||
- create a notification.
|
||||
- **Enforcement is beneath the assistant.** The UI API and core permission layer decide, exactly as for Next UI. The assistant only forwards the user's credentials (`UiApiInvoker`, `UiApiCredentials`, qqq#1128).
|
||||
- The ArchUnit rule (no core actions from the tool code) and the denial matrix stay.
|
||||
- The matrix is extended to every write operation, in both modes.
|
||||
|
||||
### X. The hard wall between the assistant and its configuration
|
||||
Owner: *"there should also be a hard wall between the assistant and the configuration for the assistant. he should never be able to see his own configuration tables etc."*
|
||||
|
||||
AI exposure NONE is not enough, because the assistant acts as the user and an admin user can edit the configuration. The wall is enforced in core, beneath the assistant, by client channel (UI API 1.2.x, approved design):
|
||||
|
||||
- Every `/qqq/v1` request the assistant makes carries `X-QQQ-Client: assistant/<turnId>`. It is set server-side by `UiApiInvoker.forServer(server, "assistant")` and `withClientDetail(turnId)`, and the invoker drops any client-supplied value. Core stores it as `QSession.getClientChannel()`.
|
||||
- **Deny rules:**
|
||||
- `ClientChannelsMetaData.withDeniedPattern("assistant", "assistant_*")`, plus core's defaults: `authentik_*`, `audit*`, `*api_key*`, `*apiKey*`, `*credential*`, `*secret*` and `webhooks_*secret*`;
|
||||
- `QPermissionRules.withDeniedClients(Set.of("assistant"))` on every assistant process (retention, test connection) and widget.
|
||||
|
||||
The rules are enforced in `PermissionsHelper`: the object is left out of metadata, and calls get 403, failing closed.
|
||||
- The qbit registers **every** `assistant_*` table, process and widget in the deny set. A **startup check** fails the instance if any `assistant_*` object is not denied to the `assistant` channel.
|
||||
- Profiles and skills reach the model only as server-assembled instructions. No tool reads or edits them (this is already enforced by ArchUnit), so a prompt injection can never persist itself.
|
||||
- The current conversation's context is read by internal code (`AssistantStore`, assistant tables only), never by a tool.
|
||||
- **Tests:** an admin through the assistant is denied on every configuration table and process (403, and absent from `list_tables` and `/metaData`), while the same admin through Next UI is allowed.
|
||||
|
||||
### Y. Audit attribution
|
||||
- Every action records the human user as the actor **and** the client channel: `actor=james@kof22.com via=assistant/<turnId>`, versus `via=next-ui`.
|
||||
- Core writes `clientChannel` on `audit` (`AuditsMetaDataProvider.withClientChannelField(true)`, filled by `DMLAuditAction`), so audit screens can filter by channel.
|
||||
- `assistant_tool_call` keeps the turn, conversation and model, and links to the audit rows (`auditHref`), so `via=assistant/<turnId>` leads to the conversation, the turn and the model.
|
||||
- **Tests:** an assistant write produces audit rows with the human actor and `via=assistant/<turnId>`; the same write from the UI produces `via=next-ui`.
|
||||
- kof22 needs a feature-named changeset (`changesets/features/...`) for the audit column.
|
||||
|
||||
### P. Providers, local models, HIPAA routing, budgets
|
||||
1. **Providers and models as data, any number, each with an enabled toggle.**
|
||||
- Kinds:
|
||||
- Anthropic (exists);
|
||||
- **OpenAI-compatible**, one adapter for OpenAI, Azure OpenAI, OpenRouter, Ollama, LM Studio, vLLM and the llama.cpp server;
|
||||
- **AWS Bedrock** (Claude and others);
|
||||
- **Google Vertex** (Claude and Gemini).
|
||||
- `assistant_provider` gains: kind, base URL, key env reference (unchanged pattern, no stored secrets), local or cloud, `hipaa_eligible` and region.
|
||||
- The new **`assistant_model`** table holds: provider, model id, display name, capabilities (tools, context window, vision, streaming), price in and out per million tokens (0 or a configured compute cost for local models), and an enabled flag.
|
||||
- Test connection works for every provider and every model.
|
||||
- Tool calling follows each provider's rules. The strict-grammar lesson applies: strict only where supported, and a fallback when it is refused.
|
||||
2. **Local models** (Mac Studio, and the workstation "lora" with an RTX A5000 24 GB, running Ollama, LM Studio or vLLM; another agent sets up the hosts). Any OpenAI-compatible endpoint is supported, with health checks, model discovery (`GET /v1/models` fills `assistant_model`) and per-provider timeouts.
|
||||
3. **HIPAA/PHI routing:**
|
||||
- A data classification on tables and fields in metadata: PHI, PII, CONFIDENTIAL or PUBLIC.
|
||||
- Each turn tracks the highest classification its context and tool results touched.
|
||||
- The policy allows PHI only to `hipaa_eligible` providers (local, or cloud under a BAA). Otherwise it blocks, with a clear reason.
|
||||
- A per-instance **HIPAA mode** (on for MHP, off for kof22) also enforces:
|
||||
- PHI redaction in logs;
|
||||
- encrypted conversation storage;
|
||||
- a separate retention period;
|
||||
- a full audit (who, which classification, which model);
|
||||
- no non-eligible providers.
|
||||
- **BAAs are an owner and legal step**: the flag records a fact; it does not create one.
|
||||
4. **Budgets:**
|
||||
- daily and monthly cost and token budgets per user, group or role, provider or model, and instance;
|
||||
- default behaviour: warn at 80% (bell and alert, through the Alerts SPI when present), downgrade to a cheaper or local model at 100%, and stop at a configurable ceiling;
|
||||
- admins can override;
|
||||
- usage and cost over time on the app home, by user, model, provider and tool.
|
||||
5. **Extras:**
|
||||
- model routing (simple versus complex, per profile) and fallback chains across providers;
|
||||
- **RAG** over the instance's content: a local embedding model, pgvector, and retrieval filtered by permissions through the UI API as the user;
|
||||
- **scheduled assistant tasks**: recurring prompts that run as a designated user (with that user's stored credentials through the UI API, never a system session) and post results as notifications or records.
|
||||
6. Everything goes through the `/qqq/v1` UI API, as the user, with the guarantees above.
|
||||
|
||||
### Phases (each a green PR)
|
||||
| | Scope | Depends on |
|
||||
|---|---|---|
|
||||
| d | Spec'd `/assistant` endpoints, tools on `UiApiInvoker` (#19) | QQQ RC.6 |
|
||||
| W1 | Write mode: conversation toggle, user preference, policy (global, role, table), tool list by mode, auto-confirm rules, write matrix in both modes; Next toggle | — |
|
||||
| X1 | Client channel `assistant/<turnId>` on every call, deny registration for all `assistant_*` objects and the security surfaces, startup check, admin-denied tests | core client-channel PR (UI API 1.2.x) |
|
||||
| Y1 | Audit attribution tests and `auditHref` to audit rows filtered by channel | core audit column |
|
||||
| W2 | Process, report-schedule, saved-view and notification writes as confirmed UI API operations | W1, X1 |
|
||||
| P-a | Provider and model registry, OpenAI-compatible adapter, discovery and health | — |
|
||||
| P-b | Bedrock and Vertex | P-a |
|
||||
| P-c | Classification, HIPAA routing and mode | P-a, core metadata |
|
||||
| P-d | Budgets and dashboards | P-a |
|
||||
| P-e | Routing and fallback chains | P-a |
|
||||
| P-f | RAG (embeddings, pgvector, UI-API-filtered retrieval) | P-a |
|
||||
| P-g | Scheduled assistant tasks | W1, X1 |
|
||||
|
||||
|
||||
## Next phases
|
||||
|
||||
- **(c) Data access screens:**
|
||||
- the Data Access table, in the nav;
|
||||
- an "Explain access" action (for a user, and a table or a prompt, which operations the assistant could call and which it would be denied, with the reason);
|
||||
- a recent-denials widget on the app home.
|
||||
- **(d) Spec'd assistant endpoints:** move `/qqq/v1/assistant/...` (conversations, turns, events, feedback, cancel, config, actions) onto `AbstractEndpointSpec`s through the qbit spec extension point (`MiddlewareSpecExtension`, established prefix `/assistant`, QRun-IO/qqq#1128). The SSE turn and events streams stay raw routes until the spec layer can describe a stream.
|
||||
@@ -0,0 +1,329 @@
|
||||
-- Reference PostgreSQL DDL for the qbit-assistant tables (snake_case, as mapped by a
|
||||
-- snake_case table customizer). Adjust to your conventions; the QBit only needs the
|
||||
-- QQQ field names to map onto columns.
|
||||
|
||||
CREATE TABLE assistant_conversation
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id VARCHAR(255),
|
||||
title VARCHAR(255),
|
||||
status VARCHAR(16),
|
||||
pinned BOOLEAN,
|
||||
last_message_at TIMESTAMP WITH TIME ZONE,
|
||||
unread_count INTEGER,
|
||||
context_json TEXT,
|
||||
total_tokens_in BIGINT,
|
||||
total_tokens_out BIGINT,
|
||||
total_cost_micros BIGINT,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_conversation_user_id ON assistant_conversation (user_id);
|
||||
|
||||
CREATE TABLE assistant_message
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
parent_message_id INTEGER,
|
||||
role VARCHAR(16),
|
||||
status VARCHAR(16),
|
||||
turn_id INTEGER,
|
||||
seq INTEGER,
|
||||
model VARCHAR(64),
|
||||
parts_json TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_message_user_id ON assistant_message (user_id);
|
||||
CREATE INDEX assistant_message_conversation_id ON assistant_message (conversation_id);
|
||||
|
||||
CREATE TABLE assistant_turn
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
user_message_id INTEGER,
|
||||
assistant_message_id INTEGER,
|
||||
status VARCHAR(16),
|
||||
stop_reason VARCHAR(64),
|
||||
error_code VARCHAR(32),
|
||||
cancel_reason VARCHAR(64),
|
||||
model VARCHAR(64),
|
||||
started_at TIMESTAMP WITH TIME ZONE,
|
||||
ended_at TIMESTAMP WITH TIME ZONE,
|
||||
tool_call_count INTEGER,
|
||||
model_call_count INTEGER,
|
||||
input_tokens BIGINT,
|
||||
output_tokens BIGINT,
|
||||
cache_read_tokens BIGINT,
|
||||
cache_write_tokens BIGINT,
|
||||
cost_micros BIGINT,
|
||||
provider_request_ids TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_turn_user_id ON assistant_turn (user_id);
|
||||
CREATE INDEX assistant_turn_conversation_id ON assistant_turn (conversation_id);
|
||||
|
||||
CREATE TABLE assistant_turn_event
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
turn_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
seq INTEGER,
|
||||
event_type VARCHAR(32),
|
||||
data_json TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_turn_event_user_id ON assistant_turn_event (user_id);
|
||||
CREATE INDEX assistant_turn_event_turn ON assistant_turn_event (turn_id, seq);
|
||||
|
||||
CREATE TABLE assistant_tool_call
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
turn_id INTEGER,
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
tool_call_id VARCHAR(128),
|
||||
tool_name VARCHAR(64),
|
||||
input_json TEXT,
|
||||
outcome VARCHAR(16),
|
||||
permission_check VARCHAR(255),
|
||||
table_name VARCHAR(128),
|
||||
process_name VARCHAR(128),
|
||||
widget_name VARCHAR(128),
|
||||
row_count INTEGER,
|
||||
duration_ms BIGINT,
|
||||
result_summary VARCHAR(500),
|
||||
result_json TEXT,
|
||||
redactions_json TEXT,
|
||||
ui_api_operation VARCHAR(255),
|
||||
http_status INTEGER,
|
||||
audit_href VARCHAR(500),
|
||||
pending_action_id INTEGER,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_tool_call_user_id ON assistant_tool_call (user_id);
|
||||
CREATE INDEX assistant_tool_call_conversation_id ON assistant_tool_call (conversation_id);
|
||||
CREATE INDEX assistant_tool_call_turn ON assistant_tool_call (turn_id);
|
||||
|
||||
CREATE TABLE assistant_feedback
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
message_id INTEGER,
|
||||
conversation_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
rating INTEGER,
|
||||
reason VARCHAR(64),
|
||||
comment TEXT,
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_feedback_user_id ON assistant_feedback (user_id);
|
||||
CREATE INDEX assistant_feedback_conversation_id ON assistant_feedback (conversation_id);
|
||||
|
||||
CREATE TABLE assistant_policy
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(64),
|
||||
kill_switch BOOLEAN,
|
||||
kill_switch_reason VARCHAR(255),
|
||||
main_model VARCHAR(64),
|
||||
main_effort VARCHAR(16),
|
||||
user_daily_tokens_soft BIGINT,
|
||||
user_daily_tokens_hard BIGINT,
|
||||
user_daily_cost_micros_soft BIGINT,
|
||||
user_daily_cost_micros_hard BIGINT,
|
||||
instance_monthly_tokens_soft BIGINT,
|
||||
instance_monthly_tokens_hard BIGINT,
|
||||
instance_monthly_cost_micros_soft BIGINT,
|
||||
instance_monthly_cost_micros_hard BIGINT,
|
||||
writes_require_confirmation BOOLEAN,
|
||||
allowed_tools VARCHAR(1000),
|
||||
max_rows_per_call INTEGER,
|
||||
redact_pii BOOLEAN,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_usage_daily
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
scope VARCHAR(16),
|
||||
user_id VARCHAR(255),
|
||||
usage_date DATE,
|
||||
turn_count INTEGER,
|
||||
input_tokens BIGINT,
|
||||
output_tokens BIGINT,
|
||||
cache_read_tokens BIGINT,
|
||||
cache_write_tokens BIGINT,
|
||||
cost_micros BIGINT,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_usage_daily_user_id ON assistant_usage_daily (user_id);
|
||||
CREATE INDEX assistant_usage_daily_date ON assistant_usage_daily (usage_date, scope);
|
||||
|
||||
-- 0.1.0-RC.4: provider settings, model prices and per-call usage.
|
||||
-- api_key_status is filled when a row is read (never written); the API key itself
|
||||
-- is never stored: api_key_env_name holds only the NAME of an environment variable.
|
||||
|
||||
CREATE TABLE assistant_provider
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
provider_type VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100),
|
||||
enabled BOOLEAN,
|
||||
is_default BOOLEAN,
|
||||
base_url VARCHAR(255),
|
||||
api_key_env_name VARCHAR(100),
|
||||
api_key_status VARCHAR(200),
|
||||
monthly_cost_cap_usd NUMERIC(12, 2),
|
||||
max_output_tokens_per_request INTEGER,
|
||||
max_concurrent_requests INTEGER,
|
||||
last_test_at TIMESTAMP WITH TIME ZONE,
|
||||
last_test_status VARCHAR(16),
|
||||
last_test_latency_ms INTEGER,
|
||||
last_test_model VARCHAR(100),
|
||||
last_test_error VARCHAR(500),
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_model_price
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
provider_type VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100) NOT NULL,
|
||||
input_usd_per_m_tok NUMERIC(12, 4) NOT NULL,
|
||||
output_usd_per_m_tok NUMERIC(12, 4) NOT NULL,
|
||||
cache_read_usd_per_m_tok NUMERIC(12, 4),
|
||||
cache_write5m_usd_per_m_tok NUMERIC(12, 4),
|
||||
cache_write1h_usd_per_m_tok NUMERIC(12, 4),
|
||||
notes VARCHAR(255),
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE,
|
||||
UNIQUE (provider_type, model)
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_usage
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id VARCHAR(255),
|
||||
conversation_id INTEGER,
|
||||
turn_id INTEGER,
|
||||
provider_id INTEGER,
|
||||
provider_type VARCHAR(50),
|
||||
model VARCHAR(100),
|
||||
purpose VARCHAR(16),
|
||||
status VARCHAR(16),
|
||||
error_kind VARCHAR(32),
|
||||
http_status INTEGER,
|
||||
latency_ms INTEGER,
|
||||
input_tokens BIGINT,
|
||||
output_tokens BIGINT,
|
||||
cache_read_tokens BIGINT,
|
||||
cache_write_tokens BIGINT,
|
||||
cost_micros BIGINT,
|
||||
request_id VARCHAR(100),
|
||||
create_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_usage_create_date ON assistant_usage (create_date);
|
||||
CREATE INDEX assistant_usage_provider ON assistant_usage (provider_id, create_date);
|
||||
CREATE INDEX assistant_usage_conversation ON assistant_usage (conversation_id);
|
||||
CREATE INDEX assistant_usage_user_id ON assistant_usage (user_id);
|
||||
|
||||
-- Anthropic list prices, USD per million tokens (cached 2026-10-06). Cache writes:
|
||||
-- 1.25x input (5 minute) and 2x input (1 hour). Re-check before budgeting.
|
||||
INSERT INTO assistant_model_price (provider_type, model, input_usd_per_m_tok, output_usd_per_m_tok, cache_read_usd_per_m_tok, cache_write5m_usd_per_m_tok, cache_write1h_usd_per_m_tok, notes, create_date, modify_date)
|
||||
VALUES
|
||||
('anthropic', 'claude-sonnet-5-5', 2.00, 10.00, 0.20, 2.50, 4.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-opus-5-5', 4.00, 20.00, 0.20, 5.00, 8.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-haiku-5-5', 0.10, 0.50, 0.01, 0.125, 0.20, 'Anthropic list price, 2026-10 (prompts up to 100K tokens)', NOW(), NOW()),
|
||||
('anthropic', 'claude-fable-5-1', 10.00, 50.00, 0.25, 12.50, 20.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-opus-5', 5.00, 25.00, 0.50, 6.25, 10.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-sonnet-5', 2.00, 10.00, 0.20, 2.50, 4.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-opus-4-8', 5.00, 25.00, 0.50, 6.25, 10.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-sonnet-4-6', 3.00, 15.00, 0.30, 3.75, 6.00, 'Anthropic list price, 2026-10', NOW(), NOW()),
|
||||
('anthropic', 'claude-haiku-4-5', 1.00, 5.00, 0.10, 1.25, 2.00, 'Anthropic list price, 2026-10', NOW(), NOW());
|
||||
|
||||
-- 0.1.0-RC.6: the assistant's data access per table / process, and writes waiting
|
||||
-- for the user's confirmation. Existing databases: add the tool-call and policy
|
||||
-- columns above with ALTER TABLE ... ADD COLUMN IF NOT EXISTS.
|
||||
CREATE TABLE assistant_data_access
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
object_type VARCHAR(16) NOT NULL,
|
||||
object_name VARCHAR(128) NOT NULL,
|
||||
mode VARCHAR(16) NOT NULL,
|
||||
notes VARCHAR(500),
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE,
|
||||
CONSTRAINT assistant_data_access_object UNIQUE (object_type, object_name)
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_pending_action
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
conversation_id INTEGER,
|
||||
turn_id INTEGER,
|
||||
user_id VARCHAR(255),
|
||||
tool_call_id VARCHAR(128),
|
||||
tool_name VARCHAR(64),
|
||||
ui_api_operation VARCHAR(255),
|
||||
table_name VARCHAR(128),
|
||||
record_id VARCHAR(128),
|
||||
params_json TEXT,
|
||||
summary VARCHAR(500),
|
||||
status VARCHAR(16),
|
||||
http_status INTEGER,
|
||||
result_summary VARCHAR(500),
|
||||
expires_at TIMESTAMP WITH TIME ZONE,
|
||||
decided_at TIMESTAMP WITH TIME ZONE,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
CREATE INDEX assistant_pending_action_user_id ON assistant_pending_action (user_id);
|
||||
CREATE INDEX assistant_pending_action_conversation_id ON assistant_pending_action (conversation_id);
|
||||
|
||||
-- 0.1.0-RC.6: profiles (persona) and skills. Text the model reads; never tools or access.
|
||||
CREATE TABLE assistant_profile
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(64) NOT NULL UNIQUE,
|
||||
display_name VARCHAR(64) NOT NULL,
|
||||
icon VARCHAR(64),
|
||||
personality TEXT,
|
||||
greeting VARCHAR(500),
|
||||
starter_prompts TEXT,
|
||||
is_default BOOLEAN,
|
||||
enabled BOOLEAN,
|
||||
app_name VARCHAR(128),
|
||||
permission_name VARCHAR(128),
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_skill
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(64) NOT NULL UNIQUE,
|
||||
description VARCHAR(500),
|
||||
instructions TEXT NOT NULL,
|
||||
enabled BOOLEAN,
|
||||
trigger_keywords VARCHAR(500),
|
||||
app_names VARCHAR(500),
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
CREATE TABLE assistant_profile_skill
|
||||
(
|
||||
id SERIAL PRIMARY KEY,
|
||||
profile_id INTEGER NOT NULL,
|
||||
skill_id INTEGER NOT NULL,
|
||||
create_date TIMESTAMP WITH TIME ZONE,
|
||||
modify_date TIMESTAMP WITH TIME ZONE,
|
||||
CONSTRAINT assistant_profile_skill_pair UNIQUE (profile_id, skill_id)
|
||||
);
|
||||
@@ -0,0 +1,25 @@
|
||||
# Assistant app home and provider settings screenshots
|
||||
|
||||
Taken 2026-10-13 against the local `AssistantDemoServer` (qbit-assistant-provider-anthropic test sources), never production.
|
||||
- Memory backend and the Next UI 1.0.0-RC.16 jar.
|
||||
- The Anthropic API is the recorded test server: real HTTP through the real adapter, engine, Test connection and usage recording, with canned answers and no key.
|
||||
|
||||
Light and dark, 390 and 1440 px:
|
||||
- `home-*`: the Assistant app home.
|
||||
- `provider-*`: the provider settings screen, with the masked key and the model-call child list.
|
||||
- `provider-not-set-*`: a provider whose key variable is not set.
|
||||
- `provider-edit-*`: the edit form.
|
||||
- `prices-*`: the model price table.
|
||||
|
||||
0.1.0-RC.6 additions, taken 2026-10-13 with the same demo server and the Next UI 1.0.0-RC.17 jar. The demo seeds a profile ("Ada"), two skills, and data access rows (page READ_WRITE, media NONE). Its tools run through the `/qqq/v1` UI API.
|
||||
|
||||
Light and dark, 390 and 1440 px:
|
||||
- `home-denials-*`: the home's "Recent denials" card. The analyst's `count_records` on Blog Post got HTTP 403 from `POST /table/{tableName}/count`.
|
||||
- `home-access-*`: the "Data access: what the assistant can do for you" widget (Explain access), with each table's access and each tool allowed or denied, with the reason.
|
||||
- `data-access-*`: the Data access table.
|
||||
- `profile-*`: a profile (persona), with its personality, its scope and its Skills child list.
|
||||
- `skill-*`: a skill: its instructions and when it is used.
|
||||
- `policy-*`: the policy, with its "Tools and data" section.
|
||||
- `panel-persona-*`: the panel with the configured persona. This is the Next UI build of qqq-frontend-next#94; the demo's admin matches the permission-scoped "Ada (analytics)" profile.
|
||||
- `panel-pending-*`: the assistant proposed `update_record` on page 12, which is READ_WRITE. The card shows the change with Save and Cancel; nothing is saved yet.
|
||||
- `panel-confirmed-*`: after Save, the write ran once through `PATCH /qqq/v1/table/page/12` with the user's session. The card says Done, and the record screen behind the panel shows the new value.
|
||||
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 150 KiB |
|
After Width: | Height: | Size: 138 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 91 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 30 KiB |
@@ -0,0 +1,295 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you under the Apache License, Version 2.0 (the
|
||||
# "License"); you may not use this file except in compliance
|
||||
# with the License. You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing,
|
||||
# software distributed under the License is distributed on an
|
||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# KIND, either express or implied. See the License for the
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
if [ -n "${JAVA_HOME-}" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. You may obtain a copy of the License at
|
||||
@REM
|
||||
@REM http://www.apache.org/licenses/LICENSE-2.0
|
||||
@REM
|
||||
@REM Unless required by applicable law or agreed to in writing,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Apache Maven Wrapper startup batch script, version 3.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
@@ -1,58 +1,212 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<!--
|
||||
~ Copyright 2026 Kingsrook, LLC
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-example-extension</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QBit Example Extension</name>
|
||||
<description>Example Extension QBit - rename this for your QBit</description>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<!-- Multi-module build. The qqq-orb sets the revision here; the modules -->
|
||||
<!-- inherit it, and the flatten plugin resolves it in the published POMs. -->
|
||||
<properties>
|
||||
<revision>0.1.0-SNAPSHOT</revision>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<qqq.version>4.0.0</qqq.version>
|
||||
<jacoco.version>0.8.15</jacoco.version>
|
||||
<anthropic.version>2.71.0</anthropic.version>
|
||||
<archunit.version>1.5.1</archunit.version>
|
||||
<jackson.version>2.21.7</jackson.version>
|
||||
<!-- live evals call the real API; run them with -Dtest.excludedGroups= -Dgroups=live -->
|
||||
<test.excludedGroups>live</test.excludedGroups>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-core</artifactId>
|
||||
<version>${qqq.version}</version>
|
||||
</dependency>
|
||||
<parent>
|
||||
<groupId>com.kingsrook</groupId>
|
||||
<artifactId>qbit-build-parent</artifactId>
|
||||
<version>2.0.0</version>
|
||||
</parent>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.27.7</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>QBit Assistant (parent)</name>
|
||||
<description>In-app AI assistant for QQQ applications: the qbit and its model providers</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<modules>
|
||||
<module>qbit-assistant</module>
|
||||
<module>qbit-assistant-provider-anthropic</module>
|
||||
</modules>
|
||||
|
||||
<licenses>
|
||||
<license>
|
||||
<name>Apache License, Version 2.0</name>
|
||||
<url>https://www.apache.org/licenses/LICENSE-2.0</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
|
||||
<developers>
|
||||
<developer>
|
||||
<id>kingsrook</id>
|
||||
<name>Kingsrook Team</name>
|
||||
<email>contact@kingsrook.com</email>
|
||||
<organization>Kingsrook, LLC</organization>
|
||||
<organizationUrl>https://kingsrook.com</organizationUrl>
|
||||
</developer>
|
||||
</developers>
|
||||
|
||||
<scm>
|
||||
<connection>scm:git:git://github.com/QRun-IO/qbit-assistant.git</connection>
|
||||
<developerConnection>scm:git:ssh://github.com:QRun-IO/qbit-assistant.git</developerConnection>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- QQQ 4.1 is built on Jackson 2.21; the Anthropic SDK asks for 2.19. -->
|
||||
<!-- Pin the newer one so both resolve to the same line. -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<version>${revision}</version>
|
||||
<type>test-jar</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.anthropic</groupId>
|
||||
<artifactId>anthropic-java</artifactId>
|
||||
<version>${anthropic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.27.7</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.tngtech.archunit</groupId>
|
||||
<artifactId>archunit-junit5</artifactId>
|
||||
<version>${archunit.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>${jacoco.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<plugins>
|
||||
<!-- Resolve ${revision} in the installed / deployed POMs. -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.1.2</version>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>flatten-maven-plugin</artifactId>
|
||||
<version>1.7.3</version>
|
||||
<configuration>
|
||||
<updatePomFile>true</updatePomFile>
|
||||
<flattenMode>resolveCiFriendliesOnly</flattenMode>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>flatten</id>
|
||||
<phase>process-resources</phase>
|
||||
<goals>
|
||||
<goal>flatten</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>flatten-clean</id>
|
||||
<phase>clean</phase>
|
||||
<goals>
|
||||
<goal>clean</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
|
||||
<profiles>
|
||||
<!-- The assistant needs QQQ 4.1.0-RC.4: the AI tool kernel (package -->
|
||||
<!-- actions.ai, qqq#1078) and the developer panels (qqq#1076). Until -->
|
||||
<!-- qbit-build-parent imports the 4.1 BOM, this -->
|
||||
<!-- profile is active by default and imports qqq-bom-pom ahead of the -->
|
||||
<!-- parent's 4.0.0 BOM, as in qbit-quick-search (ADR-0007). Override with -->
|
||||
<!-- -Dqqq.snapshot.version=... (e.g. a locally installed kernel build). -->
|
||||
<profile>
|
||||
<id>qqq-snapshot</id>
|
||||
<activation>
|
||||
<activeByDefault>true</activeByDefault>
|
||||
</activation>
|
||||
<properties>
|
||||
<qqq.snapshot.version>4.1.0-RC.4</qqq.snapshot.version>
|
||||
</properties>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-bom-pom</artifactId>
|
||||
<version>${qqq.snapshot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>sonatype-snapshots</id>
|
||||
<url>https://central.sonatype.com/repository/maven-snapshots/</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
@@ -0,0 +1,128 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright 2026 Kingsrook, LLC
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qbit-assistant-provider-anthropic</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QBit Assistant - Anthropic provider</name>
|
||||
<description>Anthropic (Claude) model provider for qbit-assistant, on com.anthropic:anthropic-java</description>
|
||||
<url>https://github.com/QRun-IO/qbit-assistant</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.anthropic</groupId>
|
||||
<artifactId>anthropic-java</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-assistant</artifactId>
|
||||
<type>test-jar</type>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-javalin</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<!-- live evals call the real API: opt-in only -->
|
||||
<excludedGroups>${test.excludedGroups}</excludedGroups>
|
||||
<redirectTestOutputToFile>true</redirectTestOutputToFile>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>check</id>
|
||||
<goals>
|
||||
<goal>check</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<rules>
|
||||
<rule>
|
||||
<element>BUNDLE</element>
|
||||
<limits>
|
||||
<limit>
|
||||
<counter>INSTRUCTION</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.70</minimum>
|
||||
</limit>
|
||||
<limit>
|
||||
<counter>CLASS</counter>
|
||||
<value>COVEREDRATIO</value>
|
||||
<minimum>0.90</minimum>
|
||||
</limit>
|
||||
</limits>
|
||||
</rule>
|
||||
</rules>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,425 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.anthropic.core.JsonValue;
|
||||
import com.anthropic.errors.AnthropicIoException;
|
||||
import com.anthropic.errors.AnthropicServiceException;
|
||||
import com.anthropic.models.messages.CacheControlEphemeral;
|
||||
import com.anthropic.models.messages.ContentBlock;
|
||||
import com.anthropic.models.messages.ContentBlockParam;
|
||||
import com.anthropic.models.messages.Message;
|
||||
import com.anthropic.models.messages.MessageCreateParams;
|
||||
import com.anthropic.models.messages.MessageParam;
|
||||
import com.anthropic.models.messages.OutputConfig;
|
||||
import com.anthropic.models.messages.TextBlockParam;
|
||||
import com.anthropic.models.messages.ThinkingConfigAdaptive;
|
||||
import com.anthropic.models.messages.Tool;
|
||||
import com.anthropic.models.messages.ToolChoiceAuto;
|
||||
import com.anthropic.models.messages.ToolResultBlockParam;
|
||||
import com.anthropic.models.messages.ToolUseBlock;
|
||||
import com.anthropic.models.messages.ToolUseBlockParam;
|
||||
import com.anthropic.models.messages.Usage;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Maps the provider-neutral request / response to the Anthropic Messages
|
||||
** API (anthropic-java):
|
||||
** - system blocks as TextBlockParams; CacheHint LONG = cache_control 1h,
|
||||
** SHORT = 5m (longer TTLs come first in the request, as the API needs);
|
||||
** - tools with strict input schemas, tool_choice auto (forced any / tool is
|
||||
** rejected by Sonnet / Opus 5.5) and disable_parallel_tool_use when the
|
||||
** request asks for one call at a time;
|
||||
** - adaptive thinking with display "omitted" (thinking cannot be disabled
|
||||
** on Sonnet / Opus 5.5; its text is never shown) and an explicit effort;
|
||||
** - an assistant message this provider produced is sent back verbatim
|
||||
** (its MessageParam, with thinking signatures) inside a tool loop.
|
||||
*******************************************************************************/
|
||||
public class AnthropicMapping
|
||||
{
|
||||
|
||||
/*******************************************************************************
|
||||
** The request parameters.
|
||||
*******************************************************************************/
|
||||
public static MessageCreateParams toParams(ModelRequest request)
|
||||
{
|
||||
MessageCreateParams.Builder builder = MessageCreateParams.builder()
|
||||
.model(request.getModel())
|
||||
.maxTokens(request.getMaxTokens() == null ? 16000L : request.getMaxTokens().longValue())
|
||||
.thinking(ThinkingConfigAdaptive.builder().display(ThinkingConfigAdaptive.Display.OMITTED).build());
|
||||
|
||||
if(request.getEffort() != null)
|
||||
{
|
||||
builder.outputConfig(OutputConfig.builder().effort(OutputConfig.Effort.of(request.getEffort())).build());
|
||||
}
|
||||
|
||||
List<TextBlockParam> system = new ArrayList<>();
|
||||
for(SystemBlock block : request.getSystem())
|
||||
{
|
||||
TextBlockParam.Builder text = TextBlockParam.builder().text(block.getText() == null ? "" : block.getText());
|
||||
CacheControlEphemeral cache = cacheControl(block.getCacheHint());
|
||||
if(cache != null)
|
||||
{
|
||||
text.cacheControl(cache);
|
||||
}
|
||||
system.add(text.build());
|
||||
}
|
||||
if(!system.isEmpty())
|
||||
{
|
||||
builder.systemOfTextBlockParams(system);
|
||||
}
|
||||
|
||||
if(!request.getTools().isEmpty())
|
||||
{
|
||||
for(ModelToolDefinition definition : request.getTools())
|
||||
{
|
||||
builder.addTool(toTool(definition));
|
||||
}
|
||||
builder.toolChoice(ToolChoiceAuto.builder().disableParallelToolUse(Boolean.FALSE.equals(request.getParallelToolCalls())).build());
|
||||
}
|
||||
|
||||
for(ModelMessage message : request.getMessages())
|
||||
{
|
||||
builder.addMessage(toMessageParam(message));
|
||||
}
|
||||
return (builder.build());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One tool.
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
static Tool toTool(ModelToolDefinition definition)
|
||||
{
|
||||
Map<String, Object> schema = definition.getInputSchema() == null ? Map.of("type", "object") : definition.getInputSchema();
|
||||
Tool.InputSchema.Builder inputSchema = Tool.InputSchema.builder();
|
||||
for(Map.Entry<String, Object> entry : schema.entrySet())
|
||||
{
|
||||
switch(entry.getKey())
|
||||
{
|
||||
case "type" ->
|
||||
{
|
||||
/////////////////////////////////////////
|
||||
// always "object" (the SDK default) //
|
||||
/////////////////////////////////////////
|
||||
}
|
||||
case "properties" ->
|
||||
{
|
||||
Tool.InputSchema.Properties.Builder properties = Tool.InputSchema.Properties.builder();
|
||||
if(entry.getValue() instanceof Map<?, ?> map)
|
||||
{
|
||||
((Map<String, Object>) map).forEach((name, value) -> properties.putAdditionalProperty(name, JsonValue.from(value)));
|
||||
}
|
||||
inputSchema.properties(properties.build());
|
||||
}
|
||||
case "required" ->
|
||||
{
|
||||
List<String> required = new ArrayList<>();
|
||||
if(entry.getValue() instanceof List<?> list)
|
||||
{
|
||||
list.forEach(o -> required.add(String.valueOf(o)));
|
||||
}
|
||||
inputSchema.required(required);
|
||||
}
|
||||
default -> inputSchema.putAdditionalProperty(entry.getKey(), JsonValue.from(entry.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
return (Tool.builder()
|
||||
.name(definition.getName())
|
||||
.description(definition.getDescription() == null ? "" : definition.getDescription())
|
||||
.strict(!Boolean.FALSE.equals(definition.getStrict()))
|
||||
.inputSchema(inputSchema.build())
|
||||
.build());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One message: the provider's own param when it produced it, else built
|
||||
** from the parts; a cache hint goes on the last block.
|
||||
*******************************************************************************/
|
||||
static MessageParam toMessageParam(ModelMessage message)
|
||||
{
|
||||
if(message.getProviderState() instanceof MessageParam param && CacheHint.NONE.equals(message.getCacheHint()))
|
||||
{
|
||||
return (param);
|
||||
}
|
||||
|
||||
List<ContentBlockParam> blocks = new ArrayList<>();
|
||||
List<ModelPart> parts = message.getParts();
|
||||
for(int i = 0; i < parts.size(); i++)
|
||||
{
|
||||
ModelPart part = parts.get(i);
|
||||
CacheControlEphemeral cache = i == parts.size() - 1 ? cacheControl(message.getCacheHint()) : null;
|
||||
switch(part.getType())
|
||||
{
|
||||
case TEXT ->
|
||||
{
|
||||
TextBlockParam.Builder text = TextBlockParam.builder().text(part.getText() == null || part.getText().isEmpty() ? " " : part.getText());
|
||||
if(cache != null)
|
||||
{
|
||||
text.cacheControl(cache);
|
||||
}
|
||||
blocks.add(ContentBlockParam.ofText(text.build()));
|
||||
}
|
||||
case TOOL_USE ->
|
||||
{
|
||||
ToolUseBlockParam.Input.Builder input = ToolUseBlockParam.Input.builder();
|
||||
if(part.getInput() != null)
|
||||
{
|
||||
part.getInput().forEach((k, v) -> input.putAdditionalProperty(k, JsonValue.from(v)));
|
||||
}
|
||||
ToolUseBlockParam.Builder use = ToolUseBlockParam.builder().id(part.getToolUseId()).name(part.getToolName()).input(input.build());
|
||||
if(cache != null)
|
||||
{
|
||||
use.cacheControl(cache);
|
||||
}
|
||||
blocks.add(ContentBlockParam.ofToolUse(use.build()));
|
||||
}
|
||||
case TOOL_RESULT ->
|
||||
{
|
||||
ToolResultBlockParam.Builder result = ToolResultBlockParam.builder()
|
||||
.toolUseId(part.getToolUseId())
|
||||
.content(part.getText() == null ? "" : part.getText());
|
||||
if(Boolean.TRUE.equals(part.getIsError()))
|
||||
{
|
||||
result.isError(true);
|
||||
}
|
||||
if(cache != null)
|
||||
{
|
||||
result.cacheControl(cache);
|
||||
}
|
||||
blocks.add(ContentBlockParam.ofToolResult(result.build()));
|
||||
}
|
||||
default -> throw (new IllegalStateException("Unknown part type"));
|
||||
}
|
||||
}
|
||||
|
||||
return (MessageParam.builder()
|
||||
.role(message.getRole() == ModelMessage.Role.ASSISTANT ? MessageParam.Role.ASSISTANT : MessageParam.Role.USER)
|
||||
.contentOfBlockParams(blocks)
|
||||
.build());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The response: visible parts (thinking dropped), stop reason, usage, and
|
||||
** the message itself as provider state for the next loop step.
|
||||
*******************************************************************************/
|
||||
public static ModelResponse toResponse(Message message)
|
||||
{
|
||||
List<ModelPart> parts = new ArrayList<>();
|
||||
for(ContentBlock block : message.content())
|
||||
{
|
||||
if(block.text().isPresent())
|
||||
{
|
||||
parts.add(ModelPart.text(block.text().get().text()));
|
||||
}
|
||||
else if(block.toolUse().isPresent())
|
||||
{
|
||||
ToolUseBlock use = block.toolUse().get();
|
||||
parts.add(ModelPart.toolUse(use.id(), use.name(), inputMap(use._input())));
|
||||
}
|
||||
/////////////////////////////////////////////////////////////////
|
||||
// thinking / redacted thinking: never surfaced; they travel //
|
||||
// back to the API only inside the provider state below //
|
||||
/////////////////////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
return (new ModelResponse()
|
||||
.withParts(parts)
|
||||
.withStopReason(message.stopReason().map(s -> s.asString()).orElse(ModelResponse.STOP_END_TURN))
|
||||
.withUsage(toUsage(message.usage()))
|
||||
.withRequestId(message.id())
|
||||
.withModel(message.model().asString())
|
||||
.withProviderState(message.toParam()));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static ModelUsage toUsage(Usage usage)
|
||||
{
|
||||
if(usage == null)
|
||||
{
|
||||
return (new ModelUsage());
|
||||
}
|
||||
long write1h = usage.cacheCreation().map(c -> c.ephemeral1hInputTokens()).orElse(0L);
|
||||
return (new ModelUsage()
|
||||
.withInputTokens(usage.inputTokens())
|
||||
.withOutputTokens(usage.outputTokens())
|
||||
.withCacheReadTokens(usage.cacheReadInputTokens().orElse(0L))
|
||||
.withCacheWriteTokens(usage.cacheCreationInputTokens().orElse(0L))
|
||||
.withCacheWrite1hTokens(write1h));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A tool_use input as a plain map.
|
||||
*******************************************************************************/
|
||||
static Map<String, Object> inputMap(JsonValue input)
|
||||
{
|
||||
if(input == null)
|
||||
{
|
||||
return (new LinkedHashMap<>());
|
||||
}
|
||||
try
|
||||
{
|
||||
Map<String, Object> map = input.convert(new TypeReference<Map<String, Object>>() {});
|
||||
return (map == null ? new LinkedHashMap<>() : map);
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
return (new LinkedHashMap<>());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Whether a 400 message says the strict tool schemas are the problem:
|
||||
** "The compiled grammar is too large ... reduce the number of strict tools"
|
||||
** or "Schema is too complex for compilation".
|
||||
*******************************************************************************/
|
||||
static boolean isStrictSchemaMessage(String message)
|
||||
{
|
||||
if(message == null)
|
||||
{
|
||||
return (false);
|
||||
}
|
||||
String lower = message.toLowerCase(java.util.Locale.ROOT);
|
||||
return (lower.contains("grammar") || lower.contains("too complex for compilation") || lower.contains("strict tool"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The API's own error message ({"error": {"message": ...}}), or null. The
|
||||
** caller sanitizes it; Anthropic's messages name parameters, not content.
|
||||
*******************************************************************************/
|
||||
static String errorMessage(AnthropicServiceException service)
|
||||
{
|
||||
try
|
||||
{
|
||||
Map<String, Object> body = service.body() == null ? null : service.body().convert(new TypeReference<Map<String, Object>>() {});
|
||||
if(body != null && body.get("error") instanceof Map<?, ?> error && error.get("message") instanceof String message)
|
||||
{
|
||||
return (message);
|
||||
}
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
//////////////////////////////////////////////
|
||||
// not JSON / not the documented error shape //
|
||||
//////////////////////////////////////////////
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Map an SDK error to a provider error. The message holds the status, the
|
||||
** API error type and the API's own (sanitized) error message - never request
|
||||
** bodies, prompts or keys.
|
||||
*******************************************************************************/
|
||||
public static ModelProviderException toProviderException(Throwable throwable)
|
||||
{
|
||||
if(throwable instanceof AnthropicServiceException service)
|
||||
{
|
||||
int status = service.statusCode();
|
||||
String type = service.errorType().map(t -> t.asString()).orElse(null);
|
||||
|
||||
ModelProviderException.Kind kind;
|
||||
if(status == 401 || status == 403)
|
||||
{
|
||||
kind = ModelProviderException.Kind.AUTHENTICATION;
|
||||
}
|
||||
else if(status == 429)
|
||||
{
|
||||
kind = ModelProviderException.Kind.RATE_LIMITED;
|
||||
}
|
||||
else if(status == 529 || "overloaded_error".equals(type))
|
||||
{
|
||||
kind = ModelProviderException.Kind.OVERLOADED;
|
||||
}
|
||||
else if(status >= 500)
|
||||
{
|
||||
kind = ModelProviderException.Kind.SERVER;
|
||||
}
|
||||
else if(status >= 400)
|
||||
{
|
||||
kind = ModelProviderException.Kind.INVALID_REQUEST;
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = "overloaded_error".equals(type) ? ModelProviderException.Kind.OVERLOADED : ModelProviderException.Kind.OTHER;
|
||||
}
|
||||
String apiMessage = errorMessage(service);
|
||||
String requestId = service.headers() == null ? null : service.headers().values("request-id").stream().findFirst().orElse(null);
|
||||
ModelProviderException exception = new ModelProviderException(kind, status >= 400 ? status : null, "Anthropic API error" + (status >= 400 ? " (HTTP " + status + ")" : "") + (type == null ? "" : " " + type)
|
||||
+ (apiMessage == null ? "" : ": " + ModelProviderException.sanitizeProviderMessage(apiMessage, ModelProviderException.MAX_PROVIDER_MESSAGE_CHARS)));
|
||||
return (exception.withProviderDetails(type, apiMessage, requestId).withStrictSchemaRejected(status == 400 && isStrictSchemaMessage(apiMessage)));
|
||||
}
|
||||
if(throwable instanceof AnthropicIoException)
|
||||
{
|
||||
return (new ModelProviderException(ModelProviderException.Kind.NETWORK, null, "Could not reach the Anthropic API."));
|
||||
}
|
||||
return (new ModelProviderException(ModelProviderException.Kind.OTHER, null, "Anthropic call failed (" + throwable.getClass().getSimpleName() + ")."));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static CacheControlEphemeral cacheControl(CacheHint hint)
|
||||
{
|
||||
if(CacheHint.LONG.equals(hint))
|
||||
{
|
||||
return (CacheControlEphemeral.builder().ttl(CacheControlEphemeral.Ttl.TTL_1H).build());
|
||||
}
|
||||
if(CacheHint.SHORT.equals(hint))
|
||||
{
|
||||
return (CacheControlEphemeral.builder().ttl(CacheControlEphemeral.Ttl.TTL_5M).build());
|
||||
}
|
||||
return (null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import com.anthropic.client.AnthropicClient;
|
||||
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
|
||||
import com.anthropic.core.http.StreamResponse;
|
||||
import com.anthropic.helpers.MessageAccumulator;
|
||||
import com.anthropic.models.messages.MessageCreateParams;
|
||||
import com.anthropic.models.messages.RawMessageStreamEvent;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.CompletableStreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.utils.StringUtils;
|
||||
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Anthropic (Claude) model provider, on com.anthropic:anthropic-java
|
||||
** streaming (createStreaming + MessageAccumulator).
|
||||
**
|
||||
** The API key comes ONLY from the environment (fromEnvironment(), variable
|
||||
** ANTHROPIC_API_KEY) or from a value the host reads from its own secret
|
||||
** store and passes to builder().apiKey(...) - which also accepts the
|
||||
** reference form "${env.NAME}". The key is held only inside the SDK client:
|
||||
** never logged, never in toString, never in exceptions, never in tables.
|
||||
*******************************************************************************/
|
||||
public class AnthropicModelProvider implements AssistantModelProvider
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(AnthropicModelProvider.class);
|
||||
|
||||
public static final String NAME = "anthropic";
|
||||
public static final String API_KEY_ENV = "ANTHROPIC_API_KEY";
|
||||
private static final Pattern ENV_REFERENCE = Pattern.compile("^\\$\\{env\\.([A-Za-z_][A-Za-z0-9_]*)}$");
|
||||
|
||||
private final AnthropicClient client;
|
||||
private final String baseUrl;
|
||||
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AnthropicModelProvider(AnthropicClient client, String baseUrl)
|
||||
{
|
||||
this.client = client;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A provider with the key from ANTHROPIC_API_KEY.
|
||||
*******************************************************************************/
|
||||
public static AnthropicModelProvider fromEnvironment()
|
||||
{
|
||||
return (builder().apiKey("${env." + API_KEY_ENV + "}").build());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A builder.
|
||||
*******************************************************************************/
|
||||
public static Builder builder()
|
||||
{
|
||||
return (new Builder());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Builds the provider. apiKey is required (a literal from a secret store,
|
||||
** or "${env.NAME}").
|
||||
*******************************************************************************/
|
||||
public static class Builder
|
||||
{
|
||||
private String apiKey;
|
||||
private String baseUrl;
|
||||
private Duration timeout = Duration.ofMinutes(10);
|
||||
private Integer maxRetries = 2;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The API key, or "${env.NAME}" to read it from the environment.
|
||||
*******************************************************************************/
|
||||
public Builder apiKey(String apiKey)
|
||||
{
|
||||
this.apiKey = apiKey;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Another API base URL (a gateway, or a test server).
|
||||
*******************************************************************************/
|
||||
public Builder baseUrl(String baseUrl)
|
||||
{
|
||||
this.baseUrl = baseUrl;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Request timeout (default 10 minutes; the turn engine has its own).
|
||||
*******************************************************************************/
|
||||
public Builder timeout(Duration timeout)
|
||||
{
|
||||
this.timeout = timeout;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** SDK retries of connection errors, 408 / 409 / 429 / 5xx (default 2).
|
||||
*******************************************************************************/
|
||||
public Builder maxRetries(Integer maxRetries)
|
||||
{
|
||||
this.maxRetries = maxRetries;
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public AnthropicModelProvider build()
|
||||
{
|
||||
String key = resolveSecret(apiKey);
|
||||
if(!StringUtils.hasContent(key))
|
||||
{
|
||||
throw (new IllegalStateException("No Anthropic API key: set " + API_KEY_ENV + " or pass a key from the application's secret store."));
|
||||
}
|
||||
|
||||
AnthropicOkHttpClient.Builder clientBuilder = AnthropicOkHttpClient.builder().apiKey(key);
|
||||
if(StringUtils.hasContent(baseUrl))
|
||||
{
|
||||
clientBuilder.baseUrl(baseUrl);
|
||||
}
|
||||
if(timeout != null)
|
||||
{
|
||||
clientBuilder.timeout(timeout);
|
||||
}
|
||||
if(maxRetries != null)
|
||||
{
|
||||
clientBuilder.maxRetries(maxRetries);
|
||||
}
|
||||
return (new AnthropicModelProvider(clientBuilder.build(), StringUtils.hasContent(baseUrl) ? baseUrl : "https://api.anthropic.com"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A key literal, or the value of "${env.NAME}".
|
||||
*******************************************************************************/
|
||||
static String resolveSecret(String value)
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
return (null);
|
||||
}
|
||||
Matcher matcher = ENV_REFERENCE.matcher(value.trim());
|
||||
if(matcher.matches())
|
||||
{
|
||||
return (System.getenv(matcher.group(1)));
|
||||
}
|
||||
return (value.trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** No key in here.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return ("AnthropicModelProvider.Builder{baseUrl=" + baseUrl + ", apiKey=" + (apiKey == null ? "unset" : "[set]") + "}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return (NAME);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Claude 5.5 models: tools, parallel tools, prompt caching, (adaptive)
|
||||
** thinking.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public ModelCapabilities getCapabilities(String modelId)
|
||||
{
|
||||
return (new ModelCapabilities()
|
||||
.withTools(true)
|
||||
.withParallelToolCalls(true)
|
||||
.withPromptCaching(true)
|
||||
.withThinking(true)
|
||||
.withMaxContextTokens(200_000));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public StreamHandle stream(ModelRequest request, ModelEventListener listener)
|
||||
{
|
||||
CompletableStreamHandle handle = new CompletableStreamHandle();
|
||||
MessageCreateParams params;
|
||||
try
|
||||
{
|
||||
params = AnthropicMapping.toParams(request);
|
||||
}
|
||||
catch(RuntimeException e)
|
||||
{
|
||||
handle.fail(new ModelProviderException(ModelProviderException.Kind.INVALID_REQUEST, null, "Could not build the Anthropic request."));
|
||||
return (handle);
|
||||
}
|
||||
|
||||
AtomicReference<ModelUsage> seen = new AtomicReference<>();
|
||||
handle.setPartialUsage(seen::get);
|
||||
|
||||
executor.submit(() ->
|
||||
{
|
||||
try(StreamResponse<RawMessageStreamEvent> response = client.messages().createStreaming(params))
|
||||
{
|
||||
handle.setOnCancel(response::close);
|
||||
if(handle.isCancelled())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
MessageAccumulator accumulator = MessageAccumulator.create();
|
||||
response.stream().forEach(event ->
|
||||
{
|
||||
accumulator.accumulate(event);
|
||||
event.messageStart().ifPresent(start -> seen.set(AnthropicMapping.toUsage(start.message().usage())));
|
||||
event.messageDelta().ifPresent(delta ->
|
||||
{
|
||||
ModelUsage current = seen.get() == null ? new ModelUsage() : seen.get();
|
||||
seen.set(current.withOutputTokens(delta.usage().outputTokens()));
|
||||
});
|
||||
event.contentBlockDelta().flatMap(delta -> delta.delta().text()).ifPresent(text -> listener.onTextDelta(text.text()));
|
||||
event.contentBlockStart().flatMap(start -> start.contentBlock().toolUse()).ifPresent(use -> listener.onToolUseStart(use.id(), use.name()));
|
||||
});
|
||||
|
||||
if(!handle.isCancelled())
|
||||
{
|
||||
handle.complete(AnthropicMapping.toResponse(accumulator.message()));
|
||||
}
|
||||
}
|
||||
catch(Throwable t)
|
||||
{
|
||||
if(!handle.isCancelled())
|
||||
{
|
||||
ModelProviderException exception = AnthropicMapping.toProviderException(t).withPartialUsage(seen.get());
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// a 4xx is a request or account problem an operator must see: //
|
||||
// log the API's error type, its (sanitized) message and the //
|
||||
// request id - never the prompt //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
if(exception.getHttpStatus() != null && exception.getHttpStatus() >= 400 && exception.getHttpStatus() < 500)
|
||||
{
|
||||
LOG.warn("Anthropic stream failed", logPair("kind", exception.getKind()), logPair("httpStatus", exception.getHttpStatus()), logPair("model", request.getModel()),
|
||||
logPair("errorType", exception.getProviderErrorType()), logPair("errorMessage", exception.getProviderMessage()), logPair("requestId", exception.getRequestId()));
|
||||
}
|
||||
else
|
||||
{
|
||||
LOG.info("Anthropic stream failed", logPair("kind", exception.getKind()), logPair("httpStatus", exception.getHttpStatus()), logPair("model", request.getModel()),
|
||||
logPair("errorType", exception.getProviderErrorType()), logPair("requestId", exception.getRequestId()));
|
||||
}
|
||||
handle.fail(exception);
|
||||
}
|
||||
}
|
||||
});
|
||||
return (handle);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Release the HTTP client and threads.
|
||||
*******************************************************************************/
|
||||
public void close()
|
||||
{
|
||||
executor.shutdownNow();
|
||||
client.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** No key in here.
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String toString()
|
||||
{
|
||||
return ("AnthropicModelProvider{baseUrl=" + baseUrl + "}");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Anthropic (Claude) provider type for the assistant_provider settings
|
||||
** table. Register it with AssistantQBitConfig.withProviderType(new
|
||||
** AnthropicProviderType()). The key comes from the row's key variable
|
||||
** (default ANTHROPIC_API_KEY).
|
||||
*******************************************************************************/
|
||||
public class AnthropicProviderType implements AssistantProviderType
|
||||
{
|
||||
public static final String DEFAULT_BASE_URL = "https://api.anthropic.com";
|
||||
|
||||
/*******************************************************************************
|
||||
** The current Claude models, the default (Sonnet 5.5) first.
|
||||
*******************************************************************************/
|
||||
public static final List<String> MODELS = List.of(
|
||||
"claude-sonnet-5-5", "claude-opus-5-5", "claude-haiku-5-5", "claude-fable-5-1",
|
||||
"claude-opus-5", "claude-sonnet-5", "claude-opus-4-8", "claude-sonnet-4-6", "claude-haiku-4-5");
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getType()
|
||||
{
|
||||
return (AnthropicModelProvider.NAME);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getLabel()
|
||||
{
|
||||
return ("Anthropic (Claude)");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public List<String> getModels()
|
||||
{
|
||||
return (MODELS);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getDefaultApiKeyEnvName()
|
||||
{
|
||||
return (AnthropicModelProvider.API_KEY_ENV);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public String getDefaultBaseUrl()
|
||||
{
|
||||
return (DEFAULT_BASE_URL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A provider with the resolved key (passed as a literal, never logged).
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public AssistantModelProvider create(String apiKey, String baseUrl)
|
||||
{
|
||||
AnthropicModelProvider.Builder builder = AnthropicModelProvider.builder().apiKey(apiKey);
|
||||
if(baseUrl != null)
|
||||
{
|
||||
builder.baseUrl(baseUrl);
|
||||
}
|
||||
return (builder.build());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.provider.CacheHint;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelMessage;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelPart;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelResponse;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.StreamHandle;
|
||||
import com.kingsrook.qbits.assistant.provider.SystemBlock;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Anthropic adapter against recorded SSE streams served locally:
|
||||
** request shape (caching, strict tools, tool_choice auto, adaptive thinking
|
||||
** with omitted display, explicit effort), streaming text, thinking never
|
||||
** forwarded, parallel tool_use, the thinking signature sent back verbatim,
|
||||
** refusal, errors, cancel, and that the key never shows.
|
||||
*******************************************************************************/
|
||||
class AnthropicModelProviderTest
|
||||
{
|
||||
private static final String TEST_KEY = "sk-ant-test-0000000000000000000000";
|
||||
|
||||
private RecordedAnthropicServer server;
|
||||
private AnthropicModelProvider provider;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws Exception
|
||||
{
|
||||
server = new RecordedAnthropicServer();
|
||||
provider = AnthropicModelProvider.builder().apiKey(TEST_KEY).baseUrl(server.baseUrl()).maxRetries(0).timeout(Duration.ofSeconds(20)).build();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void tearDown()
|
||||
{
|
||||
provider.close();
|
||||
server.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A request like the turn engine builds.
|
||||
*******************************************************************************/
|
||||
static ModelRequest request()
|
||||
{
|
||||
Map<String, Object> schema = new LinkedHashMap<>();
|
||||
schema.put("type", "object");
|
||||
schema.put("additionalProperties", false);
|
||||
schema.put("required", List.of("table"));
|
||||
schema.put("properties", Map.of("table", Map.of("type", "string")));
|
||||
|
||||
ModelRequest request = new ModelRequest()
|
||||
.withModel("claude-sonnet-5-5")
|
||||
.withEffort("medium")
|
||||
.withMaxTokens(16000)
|
||||
.withTools(new ArrayList<>(List.of(new ModelToolDefinition().withName("count_records").withDescription("Count").withInputSchema(schema).withStrict(true))));
|
||||
request.getSystem().add(new SystemBlock("static rules and app digest", CacheHint.LONG));
|
||||
request.getSystem().add(new SystemBlock("user digest", CacheHint.SHORT));
|
||||
request.getMessages().add(ModelMessage.user("how many posts?").withCacheHint(CacheHint.SHORT));
|
||||
return (request);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> sentBody(int index) throws Exception
|
||||
{
|
||||
return (JsonUtils.toObject(server.getRequests().get(index).get("body"), new TypeReference<Map<String, Object>>() {}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void testTextStreamRequestShapeAndNoThinking() throws Exception
|
||||
{
|
||||
server.thenStream("text-with-thinking.sse", 0);
|
||||
List<String> deltas = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
ModelResponse response = provider.stream(request(), deltas::add).await(Duration.ofSeconds(10));
|
||||
|
||||
assertThat(String.join("", deltas)).isEqualTo("There are 4 published posts.");
|
||||
assertThat(response.getText()).isEqualTo("There are 4 published posts.");
|
||||
assertThat(response.getStopReason()).isEqualTo("end_turn");
|
||||
assertThat(response.getUsage().getInputTokens()).isEqualTo(120);
|
||||
assertThat(response.getUsage().getOutputTokens()).isEqualTo(42);
|
||||
assertThat(response.getUsage().getCacheWriteTokens()).isEqualTo(2048);
|
||||
assertThat(response.getUsage().getCacheWrite1hTokens()).isEqualTo(2000);
|
||||
assertThat(response.getRequestId()).isEqualTo("msg_text_01");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
// thinking never reaches deltas or the parts //
|
||||
////////////////////////////////////////////////
|
||||
assertThat(String.join("", deltas)).doesNotContain("SECRET_THINKING_TEXT");
|
||||
assertThat(JsonUtils.toJson(response.getParts())).doesNotContain("SECRET_THINKING_TEXT");
|
||||
|
||||
Map<String, Object> body = sentBody(0);
|
||||
assertThat(body.get("model")).isEqualTo("claude-sonnet-5-5");
|
||||
assertThat(body.get("max_tokens")).isEqualTo(16000);
|
||||
assertThat((Map<String, Object>) body.get("thinking")).containsEntry("type", "adaptive").containsEntry("display", "omitted");
|
||||
assertThat((Map<String, Object>) body.get("output_config")).containsEntry("effort", "medium");
|
||||
assertThat((Map<String, Object>) body.get("tool_choice")).containsEntry("type", "auto").containsEntry("disable_parallel_tool_use", false);
|
||||
|
||||
List<Map<String, Object>> system = (List<Map<String, Object>>) body.get("system");
|
||||
assertThat((Map<String, Object>) system.get(0).get("cache_control")).containsEntry("type", "ephemeral").containsEntry("ttl", "1h");
|
||||
assertThat((Map<String, Object>) system.get(1).get("cache_control")).containsEntry("ttl", "5m");
|
||||
|
||||
Map<String, Object> tool = ((List<Map<String, Object>>) body.get("tools")).get(0);
|
||||
assertThat(tool.get("strict")).isEqualTo(true);
|
||||
assertThat((Map<String, Object>) tool.get("input_schema")).containsEntry("additionalProperties", false).containsEntry("type", "object");
|
||||
|
||||
List<Map<String, Object>> messages = (List<Map<String, Object>>) body.get("messages");
|
||||
Map<String, Object> lastBlock = ((List<Map<String, Object>>) messages.get(0).get("content")).get(0);
|
||||
assertThat((Map<String, Object>) lastBlock.get("cache_control")).containsEntry("ttl", "5m");
|
||||
|
||||
assertThat(server.getRequests().get(0).get("apiKey")).isEqualTo(TEST_KEY);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void testParallelToolsAndRoundTrip() throws Exception
|
||||
{
|
||||
server.thenStream("parallel-tools.sse", 0).thenStream("text-with-thinking.sse", 0);
|
||||
List<String> started = Collections.synchronizedList(new ArrayList<>());
|
||||
ModelEventListener listener = new ModelEventListener()
|
||||
{
|
||||
@Override
|
||||
public void onTextDelta(String text)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public void onToolUseStart(String toolUseId, String toolName)
|
||||
{
|
||||
started.add(toolName);
|
||||
}
|
||||
};
|
||||
|
||||
ModelRequest request = request();
|
||||
ModelResponse response = provider.stream(request, listener).await(Duration.ofSeconds(10));
|
||||
assertThat(response.getStopReason()).isEqualTo("tool_use");
|
||||
assertThat(started).containsExactly("count_records", "list_tables");
|
||||
assertThat(response.getToolUses()).hasSize(2);
|
||||
assertThat(response.getToolUses().get(0).getToolUseId()).isEqualTo("toolu_A");
|
||||
assertThat(response.getToolUses().get(0).getInput()).containsEntry("table", "blog_post");
|
||||
assertThat(response.getToolUses().get(1).getInput()).isEmpty();
|
||||
assertThat(response.getUsage().getCacheReadTokens()).isEqualTo(5000);
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
// next step: assistant message verbatim + both results in ONE message //
|
||||
/////////////////////////////////////////////////////////////////////////
|
||||
request.getMessages().forEach(m -> m.setCacheHint(CacheHint.NONE));
|
||||
request.getMessages().add(new ModelMessage().withRole(ModelMessage.Role.ASSISTANT).withParts(response.getParts()).withProviderState(response.getProviderState()));
|
||||
request.getMessages().add(new ModelMessage().withRole(ModelMessage.Role.USER)
|
||||
.withPart(ModelPart.toolResult("toolu_A", "<qqq_data source=\"count_records\" trust=\"untrusted\">{\"count\":4}</qqq_data>", false))
|
||||
.withPart(ModelPart.toolResult("toolu_B", "denied", true))
|
||||
.withCacheHint(CacheHint.SHORT));
|
||||
provider.stream(request, t -> { }).await(Duration.ofSeconds(10));
|
||||
|
||||
List<Map<String, Object>> messages = (List<Map<String, Object>>) sentBody(1).get("messages");
|
||||
assertThat(messages).hasSize(3);
|
||||
|
||||
List<Map<String, Object>> assistantBlocks = (List<Map<String, Object>>) messages.get(1).get("content");
|
||||
assertThat(assistantBlocks.get(0)).containsEntry("type", "thinking").containsEntry("signature", "sig-tools-1");
|
||||
assertThat(assistantBlocks).extracting(b -> b.get("type")).containsExactly("thinking", "text", "tool_use", "tool_use");
|
||||
|
||||
List<Map<String, Object>> results = (List<Map<String, Object>>) messages.get(2).get("content");
|
||||
assertThat(results).hasSize(2);
|
||||
assertThat(results.get(0)).containsEntry("type", "tool_result").containsEntry("tool_use_id", "toolu_A");
|
||||
assertThat(results.get(1)).containsEntry("is_error", true);
|
||||
assertThat((Map<String, Object>) results.get(1).get("cache_control")).containsEntry("ttl", "5m");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testRefusal() throws Exception
|
||||
{
|
||||
server.thenStream("refusal.sse", 0);
|
||||
ModelResponse response = provider.stream(request(), t -> { }).await(Duration.ofSeconds(10));
|
||||
assertThat(response.getStopReason()).isEqualTo(ModelResponse.STOP_REFUSAL);
|
||||
assertThat(response.getParts()).isEmpty();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testErrors() throws Exception
|
||||
{
|
||||
server.thenError(529, "overloaded.json").thenError(401, "unauthorized.json").thenStream("midstream-error.sse", 0);
|
||||
|
||||
assertThatThrownBy(() -> provider.stream(request(), t -> { }).await(Duration.ofSeconds(10)))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e ->
|
||||
{
|
||||
assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.OVERLOADED);
|
||||
assertThat(e.isRetryable()).isTrue();
|
||||
assertThat(e.getMessage()).doesNotContain(TEST_KEY);
|
||||
});
|
||||
|
||||
assertThatThrownBy(() -> provider.stream(request(), t -> { }).await(Duration.ofSeconds(10)))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e ->
|
||||
{
|
||||
assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.AUTHENTICATION);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(401);
|
||||
assertThat(e.getMessage()).doesNotContain(TEST_KEY).contains("authentication_error");
|
||||
assertThat(e.getProviderErrorType()).isEqualTo("authentication_error");
|
||||
assertThat(e.getProviderMessage()).isEqualTo("invalid x-api-key");
|
||||
assertThat(e.isStrictSchemaRejected()).isFalse();
|
||||
});
|
||||
|
||||
assertThatThrownBy(() -> provider.stream(request(), t -> { }).await(Duration.ofSeconds(10)))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e -> assertThat(e.getPartialUsage().getInputTokens()).isEqualTo(50));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testCancel() throws Exception
|
||||
{
|
||||
server.thenStream("slow-start.sse", 10_000);
|
||||
List<String> deltas = Collections.synchronizedList(new ArrayList<>());
|
||||
StreamHandle handle = provider.stream(request(), deltas::add);
|
||||
|
||||
long deadline = System.currentTimeMillis() + 5000;
|
||||
while(deltas.isEmpty() && System.currentTimeMillis() < deadline)
|
||||
{
|
||||
Thread.sleep(20);
|
||||
}
|
||||
assertThat(deltas).containsExactly("Partial");
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
handle.cancel();
|
||||
ModelResponse response = handle.await(Duration.ofSeconds(5));
|
||||
assertThat(response.getStopReason()).isEqualTo(ModelResponse.STOP_CANCELLED);
|
||||
assertThat(System.currentTimeMillis() - start).isLessThan(3000);
|
||||
assertThat(response.getUsage().getInputTokens()).as("usage of the cancelled call is kept").isEqualTo(50);
|
||||
assertThat(handle.isCancelled()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testTimeoutCancels() throws Exception
|
||||
{
|
||||
server.thenStream("slow-start.sse", 10_000);
|
||||
StreamHandle handle = provider.stream(request(), t -> { });
|
||||
assertThatThrownBy(() -> handle.await(Duration.ofMillis(300)))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e -> assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.TIMEOUT));
|
||||
assertThat(handle.isCancelled()).isTrue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testKeyHandling()
|
||||
{
|
||||
assertThat(provider.toString()).doesNotContain(TEST_KEY);
|
||||
assertThat(provider.getName()).isEqualTo("anthropic");
|
||||
assertThat(provider.getCapabilities("claude-sonnet-5-5").getPromptCaching()).isTrue();
|
||||
|
||||
AnthropicModelProvider.Builder builder = AnthropicModelProvider.builder().apiKey(TEST_KEY);
|
||||
assertThat(builder.toString()).doesNotContain(TEST_KEY).contains("[set]");
|
||||
|
||||
assertThat(AnthropicModelProvider.Builder.resolveSecret("${env.QBIT_ASSISTANT_SURELY_UNSET_VAR}")).isNull();
|
||||
assertThat(AnthropicModelProvider.Builder.resolveSecret(" literal ")).isEqualTo("literal");
|
||||
assertThat(AnthropicModelProvider.Builder.resolveSecret("${env.PATH}")).isEqualTo(System.getenv("PATH"));
|
||||
|
||||
assertThatThrownBy(() -> AnthropicModelProvider.builder().apiKey("${env.QBIT_ASSISTANT_SURELY_UNSET_VAR}").build())
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("ANTHROPIC_API_KEY");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.engine.ConnectionTest;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantUsage;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The Anthropic provider type with Test connection against a recorded HTTP
|
||||
** server (no live calls): the key from the row's variable reaches the API as
|
||||
** x-api-key, the result and the TEST usage row are saved, and a 401 becomes
|
||||
** an admin-readable error without the key.
|
||||
*******************************************************************************/
|
||||
class AnthropicProviderTypeTest
|
||||
{
|
||||
private static final String KEY = "sk-ant-test-0000000000000000-abcd";
|
||||
|
||||
private AssistantQBitConfig config;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void tearDown()
|
||||
{
|
||||
if(config != null && config.getRuntime() != null)
|
||||
{
|
||||
config.getRuntime().close();
|
||||
}
|
||||
QContext.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** An instance with the Anthropic type allowed to use the recorded server.
|
||||
*******************************************************************************/
|
||||
private QInstance instance(String baseUrl) throws Exception
|
||||
{
|
||||
config = new AssistantQBitConfig()
|
||||
.withProviderName(ScriptedModelProvider.DEFAULT_NAME)
|
||||
.withModelProvider(new ScriptedModelProvider())
|
||||
.withProviderType(new AnthropicProviderType())
|
||||
.withAllowedBaseUrls(Set.of(baseUrl))
|
||||
.withSecretResolver(Map.of(AnthropicModelProvider.API_KEY_ENV, KEY)::get);
|
||||
QInstance qInstance = AssistantTestFixture.build(config);
|
||||
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
|
||||
return (qInstance);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private AssistantProvider insertProvider(String baseUrl) throws Exception
|
||||
{
|
||||
QRecord record = new InsertAction().execute(new InsertInput(AssistantProvider.TABLE_NAME).withRecord(new QRecord()
|
||||
.withValue("name", "Claude").withValue("providerType", "anthropic").withValue("model", "claude-sonnet-5-5")
|
||||
.withValue("enabled", true).withValue("isDefault", true).withValue("baseUrl", baseUrl))).getRecords().get(0);
|
||||
assertThat(record.getErrors()).isEmpty();
|
||||
return (config.getRuntime().getStore().getProvider(record.getValueInteger("id")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A good connection.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testConnectionOk() throws Exception
|
||||
{
|
||||
try(RecordedAnthropicServer server = new RecordedAnthropicServer())
|
||||
{
|
||||
instance(server.baseUrl());
|
||||
server.thenStream("text-with-thinking.sse", 0);
|
||||
AssistantProvider row = insertProvider(server.baseUrl());
|
||||
assertThat(row.getApiKeyStatus()).isEqualTo("Set • …abcd (from ANTHROPIC_API_KEY)");
|
||||
|
||||
ConnectionTest.Result result = ConnectionTest.run(config.getRuntime(), row, AssistantTestFixture.ADMIN);
|
||||
assertThat(result.ok()).as(result.error()).isTrue();
|
||||
assertThat(result.model()).isEqualTo("claude-sonnet-5-5");
|
||||
assertThat(server.getRequests()).hasSize(1);
|
||||
assertThat(server.getRequests().get(0).get("apiKey")).isEqualTo(KEY);
|
||||
assertThat(server.getRequests().get(0).get("body")).contains("\"max_tokens\":" + ConnectionTest.PING_MAX_TOKENS);
|
||||
|
||||
AssistantProvider saved = config.getRuntime().getStore().getProvider(row.getId());
|
||||
assertThat(saved.getLastTestStatus()).isEqualTo("OK");
|
||||
assertThat(saved.getLastTestModel()).isEqualTo("claude-sonnet-5-5");
|
||||
|
||||
QRecord usage = new QueryAction().execute(new QueryInput(AssistantUsage.TABLE_NAME).withFilter(new QQueryFilter())).getRecords().get(0);
|
||||
assertThat(usage.getValueString("purpose")).isEqualTo("TEST");
|
||||
assertThat(usage.getValueString("status")).isEqualTo("OK");
|
||||
assertThat(usage.getValueLong("inputTokens")).isPositive();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A refused key.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testConnectionUnauthorized() throws Exception
|
||||
{
|
||||
try(RecordedAnthropicServer server = new RecordedAnthropicServer())
|
||||
{
|
||||
instance(server.baseUrl());
|
||||
server.thenError(401, "unauthorized.json");
|
||||
AssistantProvider row = insertProvider(server.baseUrl());
|
||||
|
||||
ConnectionTest.Result result = ConnectionTest.run(config.getRuntime(), row, AssistantTestFixture.ADMIN);
|
||||
assertThat(result.ok()).isFalse();
|
||||
assertThat(result.error()).contains("API key was refused").contains("HTTP 401").doesNotContain(KEY);
|
||||
|
||||
AssistantProvider saved = config.getRuntime().getStore().getProvider(row.getId());
|
||||
assertThat(saved.getLastTestStatus()).isEqualTo("ERROR");
|
||||
assertThat(saved.getLastTestError()).doesNotContain(KEY);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The type itself.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testType()
|
||||
{
|
||||
AnthropicProviderType type = new AnthropicProviderType();
|
||||
assertThat(type.getType()).isEqualTo("anthropic");
|
||||
assertThat(type.getModels().get(0)).isEqualTo("claude-sonnet-5-5");
|
||||
assertThat(type.getDefaultApiKeyEnvName()).isEqualTo("ANTHROPIC_API_KEY");
|
||||
assertThat(type.getDefaultBaseUrl()).isEqualTo("https://api.anthropic.com");
|
||||
assertThat(type.getLabel()).contains("Anthropic");
|
||||
assertThat(type.create(KEY, null).toString()).doesNotContain(KEY);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.anthropic.core.ObjectMappers;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelRequest;
|
||||
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The exact Messages API request the turn engine sends, checked against the
|
||||
** API's documented constraints, plus a conservative budget for strict tools.
|
||||
**
|
||||
** Why the budget: Anthropic compiles every strict tool schema of a request
|
||||
** into one grammar and refuses the request when that grammar is too large
|
||||
** (400 invalid_request_error "The compiled grammar is too large ... reduce the
|
||||
** number of strict tools"). With all ten read tools strict (0.1.0-RC.3 to
|
||||
** RC.4) every kof22 turn failed that way, though the request stayed inside
|
||||
** the documented limits (20 strict tools, 24 optional parameters, 16 union
|
||||
** parameters). The real limit is not published, so the budget below is far
|
||||
** under the shape that failed (10 tools / 12 optional / 3 unions). A real-API
|
||||
** check is in docs/DESIGN.md ("Strict tools") for dev use with a key.
|
||||
*******************************************************************************/
|
||||
class AnthropicRequestContractTest
|
||||
{
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
// conservative strict-tool budget (see the class comment) //
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
static final int MAX_STRICT_TOOLS = 3;
|
||||
static final int MAX_STRICT_OPTIONAL_PARAMS = 6;
|
||||
static final int MAX_STRICT_UNION_PARAMS = 2;
|
||||
|
||||
private static final Set<String> EFFORTS = Set.of("low", "medium", "high", "xhigh", "max");
|
||||
private static final Set<String> UNSUPPORTED_STRICT = Set.of("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minLength", "maxLength",
|
||||
"maxItems", "uniqueItems", "oneOf", "not", "if", "then", "else", "patternProperties");
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void tearDown()
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The request body for the fixture app, as the SDK serializes it.
|
||||
*******************************************************************************/
|
||||
static Map<String, Object> requestBody(AssistantQBitConfig config) throws Exception
|
||||
{
|
||||
QContext.init(AssistantTestFixture.build(config), AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
|
||||
ModelRequest request = config.getRuntime().getContextBuilder().build(QContext.getQSession(), config.getModels().getMainModel(), config.getModels().getMainEffort(),
|
||||
List.of(), "How many published posts are there?", Map.of("tableName", "blog_post"));
|
||||
String json = ObjectMappers.jsonMapper().writeValueAsString(AnthropicMapping.toParams(request)._body());
|
||||
return (JsonUtils.toObject(json, new TypeReference<Map<String, Object>>() {}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The default request meets every documented constraint and the budget.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testDefaultRequestMeetsTheApiContract() throws Exception
|
||||
{
|
||||
Map<String, Object> body = requestBody(new AssistantQBitConfig().withModelProvider(new ScriptedModelProvider()));
|
||||
assertThat(violations(body)).isEmpty();
|
||||
assertThat(strictBudgetViolations(body)).isEmpty();
|
||||
assertThat(tools(body)).hasSizeGreaterThanOrEqualTo(8).allSatisfy(tool -> assertThat(tool.get("strict")).isNotEqualTo(true));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The RC.3 shape (every tool strict) is recognized as over budget, and a
|
||||
** host can still opt a few tools in.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testStrictBudget() throws Exception
|
||||
{
|
||||
AssistantQBitConfig probe = new AssistantQBitConfig().withModelProvider(new ScriptedModelProvider());
|
||||
Set<String> all = new LinkedHashSet<>();
|
||||
requestBody(probe);
|
||||
for(ModelToolDefinition tool : probe.getRuntime().getContextBuilder().tools())
|
||||
{
|
||||
all.add(tool.getName());
|
||||
}
|
||||
QContext.clear();
|
||||
|
||||
Map<String, Object> rc3 = requestBody(new AssistantQBitConfig().withModelProvider(new ScriptedModelProvider()).withStrictToolNames(all));
|
||||
assertThat(violations(rc3)).isEmpty();
|
||||
assertThat(strictBudgetViolations(rc3)).isNotEmpty();
|
||||
QContext.clear();
|
||||
|
||||
Map<String, Object> few = requestBody(new AssistantQBitConfig().withModelProvider(new ScriptedModelProvider()).withStrictToolNames(Set.of("get_record", "describe_table")));
|
||||
assertThat(violations(few)).isEmpty();
|
||||
assertThat(strictBudgetViolations(few)).isEmpty();
|
||||
assertThat(tools(few).stream().filter(t -> Boolean.TRUE.equals(t.get("strict"))).map(t -> t.get("name"))).containsExactlyInAnyOrder("get_record", "describe_table");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A 400 about the grammar is flagged as a strict-schema rejection, carries
|
||||
** the API's message and request id, and never the key.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testGrammarRejectionIsRecognized() throws Exception
|
||||
{
|
||||
try(RecordedAnthropicServer server = new RecordedAnthropicServer())
|
||||
{
|
||||
server.thenError(400, "grammar-too-large.json");
|
||||
AnthropicModelProvider provider = AnthropicModelProvider.builder().apiKey("sk-ant-test-0000000000000000000000").baseUrl(server.baseUrl()).maxRetries(0).build();
|
||||
assertThatThrownBy(() -> provider.stream(AnthropicModelProviderTest.request(), t -> { }).await(Duration.ofSeconds(10)))
|
||||
.isInstanceOfSatisfying(ModelProviderException.class, e ->
|
||||
{
|
||||
assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.INVALID_REQUEST);
|
||||
assertThat(e.isStrictSchemaRejected()).isTrue();
|
||||
assertThat(e.getProviderErrorType()).isEqualTo("invalid_request_error");
|
||||
assertThat(e.getProviderMessage()).startsWith("The compiled grammar is too large");
|
||||
assertThat(e.getMessage()).contains("compiled grammar").doesNotContain("sk-ant-test");
|
||||
});
|
||||
provider.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** End to end: when the provider refuses strict schemas, the turn retries
|
||||
** once without strict tools and answers.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testTurnRetriesWithoutStrictTools() throws Exception
|
||||
{
|
||||
try(RecordedAnthropicServer server = new RecordedAnthropicServer())
|
||||
{
|
||||
server.thenError(400, "grammar-too-large.json").thenStream("text-with-thinking.sse", 0);
|
||||
AnthropicModelProvider provider = AnthropicModelProvider.builder().apiKey("sk-ant-test-0000000000000000000000").baseUrl(server.baseUrl()).maxRetries(0).build();
|
||||
AssistantQBitConfig config = new AssistantQBitConfig().withModelProvider(provider).withStrictToolNames(Set.of("get_record", "count_records", "query_records"));
|
||||
TurnRunner runner = new TurnRunner(AssistantTestFixture.build(config), config);
|
||||
|
||||
TurnRunner.Outcome outcome = runner.run(AssistantTestFixture.EDITOR, "How many published posts are there?");
|
||||
assertThat(outcome.end().get("status")).isEqualTo("COMPLETE");
|
||||
assertThat(server.getRequests()).hasSize(2);
|
||||
assertThat(server.getRequests().get(0).get("body")).contains("\"strict\":true");
|
||||
assertThat(server.getRequests().get(1).get("body")).doesNotContain("\"strict\":true");
|
||||
provider.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Documented request constraints (Messages API, claude-sonnet-5-5 family).
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<String> violations(Map<String, Object> body)
|
||||
{
|
||||
List<String> errors = new ArrayList<>();
|
||||
if(!(body.get("model") instanceof String model) || !model.matches("claude-[a-z]+-[0-9]+(-[0-9]+)?"))
|
||||
{
|
||||
errors.add("model id " + body.get("model"));
|
||||
}
|
||||
if(!(body.get("max_tokens") instanceof Number max) || max.intValue() < 1 || max.intValue() > 128_000)
|
||||
{
|
||||
errors.add("max_tokens " + body.get("max_tokens"));
|
||||
}
|
||||
for(String sampling : List.of("temperature", "top_p", "top_k"))
|
||||
{
|
||||
if(body.containsKey(sampling))
|
||||
{
|
||||
errors.add(sampling + " is rejected with thinking on current models");
|
||||
}
|
||||
}
|
||||
Map<String, Object> thinking = (Map<String, Object>) body.get("thinking");
|
||||
if(thinking != null && (!"adaptive".equals(thinking.get("type")) || thinking.containsKey("budget_tokens")))
|
||||
{
|
||||
errors.add("thinking must be adaptive without budget_tokens: " + thinking);
|
||||
}
|
||||
Map<String, Object> outputConfig = (Map<String, Object>) body.get("output_config");
|
||||
if(outputConfig != null && outputConfig.get("effort") != null && !EFFORTS.contains(outputConfig.get("effort")))
|
||||
{
|
||||
errors.add("effort " + outputConfig.get("effort"));
|
||||
}
|
||||
Map<String, Object> toolChoice = (Map<String, Object>) body.get("tool_choice");
|
||||
if(toolChoice != null && !"auto".equals(toolChoice.get("type")) && !"none".equals(toolChoice.get("type")))
|
||||
{
|
||||
errors.add("forced tool_choice is rejected: " + toolChoice);
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// cache breakpoints: at most 4, longer TTLs before shorter ones //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
List<String> ttls = new ArrayList<>();
|
||||
collectCacheTtls(body.get("tools"), ttls);
|
||||
collectCacheTtls(body.get("system"), ttls);
|
||||
collectCacheTtls(body.get("messages"), ttls);
|
||||
if(ttls.size() > 4)
|
||||
{
|
||||
errors.add("more than 4 cache breakpoints: " + ttls);
|
||||
}
|
||||
for(int i = 1; i < ttls.size(); i++)
|
||||
{
|
||||
if("1h".equals(ttls.get(i)) && "5m".equals(ttls.get(i - 1)))
|
||||
{
|
||||
errors.add("a 1h cache entry after a 5m one: " + ttls);
|
||||
}
|
||||
}
|
||||
|
||||
List<Map<String, Object>> messages = (List<Map<String, Object>>) body.get("messages");
|
||||
if(messages == null || messages.isEmpty() || !"user".equals(messages.get(0).get("role")))
|
||||
{
|
||||
errors.add("messages must start with a user message");
|
||||
}
|
||||
else if(!"user".equals(messages.get(messages.size() - 1).get("role")))
|
||||
{
|
||||
errors.add("no assistant prefill on current models");
|
||||
}
|
||||
for(Map<String, Object> message : messages == null ? List.<Map<String, Object>>of() : messages)
|
||||
{
|
||||
for(Map<String, Object> block : (List<Map<String, Object>>) message.get("content"))
|
||||
{
|
||||
if("text".equals(block.get("type")) && (!(block.get("text") instanceof String text) || text.isBlank()))
|
||||
{
|
||||
errors.add("empty text block");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> names = new LinkedHashSet<>();
|
||||
for(Map<String, Object> tool : tools(body))
|
||||
{
|
||||
String name = String.valueOf(tool.get("name"));
|
||||
if(!name.matches("[a-zA-Z0-9_-]{1,64}") || !names.add(name))
|
||||
{
|
||||
errors.add("tool name " + name);
|
||||
}
|
||||
Map<String, Object> schema = (Map<String, Object>) tool.get("input_schema");
|
||||
if(schema == null || !"object".equals(schema.get("type")))
|
||||
{
|
||||
errors.add(name + ": input_schema must be an object schema");
|
||||
continue;
|
||||
}
|
||||
if(Boolean.TRUE.equals(tool.get("strict")))
|
||||
{
|
||||
checkStrictSchema(name, schema, errors);
|
||||
}
|
||||
}
|
||||
return (errors);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The strict-tool budget: count, optional parameters and unions across all
|
||||
** strict schemas.
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
static List<String> strictBudgetViolations(Map<String, Object> body)
|
||||
{
|
||||
int[] counts = new int[2];
|
||||
int strict = 0;
|
||||
for(Map<String, Object> tool : tools(body))
|
||||
{
|
||||
if(Boolean.TRUE.equals(tool.get("strict")))
|
||||
{
|
||||
strict++;
|
||||
countOptionalAndUnions(tool.get("input_schema"), counts);
|
||||
}
|
||||
}
|
||||
List<String> errors = new ArrayList<>();
|
||||
if(strict > MAX_STRICT_TOOLS)
|
||||
{
|
||||
errors.add(strict + " strict tools (budget " + MAX_STRICT_TOOLS + ")");
|
||||
}
|
||||
if(counts[0] > MAX_STRICT_OPTIONAL_PARAMS)
|
||||
{
|
||||
errors.add(counts[0] + " optional parameters in strict tools (budget " + MAX_STRICT_OPTIONAL_PARAMS + ")");
|
||||
}
|
||||
if(counts[1] > MAX_STRICT_UNION_PARAMS)
|
||||
{
|
||||
errors.add(counts[1] + " union parameters in strict tools (budget " + MAX_STRICT_UNION_PARAMS + ")");
|
||||
}
|
||||
return (errors);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static List<Map<String, Object>> tools(Map<String, Object> body)
|
||||
{
|
||||
return (body.get("tools") instanceof List<?> list ? (List<Map<String, Object>>) list : List.of());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Strict schemas: additionalProperties false on every object, no
|
||||
** unsupported keywords, minItems 0 or 1 only, no recursive $ref.
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void checkStrictSchema(String path, Object node, List<String> errors)
|
||||
{
|
||||
if(node instanceof Map<?, ?> map)
|
||||
{
|
||||
Map<String, Object> schema = (Map<String, Object>) map;
|
||||
if(("object".equals(schema.get("type")) || schema.containsKey("properties")) && !Boolean.FALSE.equals(schema.get("additionalProperties")))
|
||||
{
|
||||
errors.add(path + ": additionalProperties must be false");
|
||||
}
|
||||
for(String keyword : UNSUPPORTED_STRICT)
|
||||
{
|
||||
if(schema.containsKey(keyword))
|
||||
{
|
||||
errors.add(path + ": unsupported keyword " + keyword);
|
||||
}
|
||||
}
|
||||
if(schema.get("minItems") instanceof Number minItems && minItems.intValue() > 1)
|
||||
{
|
||||
errors.add(path + ": minItems above 1");
|
||||
}
|
||||
if(schema.get("$defs") instanceof Map<?, ?> defs)
|
||||
{
|
||||
for(Map.Entry<?, ?> def : defs.entrySet())
|
||||
{
|
||||
if(JsonUtils.toJson(def.getValue()).contains("\"#/$defs/" + def.getKey() + "\""))
|
||||
{
|
||||
errors.add(path + ": recursive $defs/" + def.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
schema.forEach((key, value) -> checkStrictSchema(path + "/" + key, value, errors));
|
||||
}
|
||||
else if(node instanceof List<?> list)
|
||||
{
|
||||
list.forEach(value -> checkStrictSchema(path, value, errors));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void countOptionalAndUnions(Object node, int[] counts)
|
||||
{
|
||||
if(node instanceof Map<?, ?> map)
|
||||
{
|
||||
Map<String, Object> schema = (Map<String, Object>) map;
|
||||
if(schema.get("properties") instanceof Map<?, ?> properties)
|
||||
{
|
||||
List<Object> required = schema.get("required") instanceof List<?> r ? (List<Object>) r : List.of();
|
||||
for(Object name : properties.keySet())
|
||||
{
|
||||
if(!required.contains(name))
|
||||
{
|
||||
counts[0]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(schema.get("type") instanceof List<?> || schema.containsKey("anyOf"))
|
||||
{
|
||||
counts[1]++;
|
||||
}
|
||||
schema.values().forEach(value -> countOptionalAndUnions(value, counts));
|
||||
}
|
||||
else if(node instanceof List<?> list)
|
||||
{
|
||||
list.forEach(value -> countOptionalAndUnions(value, counts));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static void collectCacheTtls(Object node, List<String> ttls)
|
||||
{
|
||||
if(node instanceof Map<?, ?> map)
|
||||
{
|
||||
if(map.get("cache_control") instanceof Map<?, ?> cache)
|
||||
{
|
||||
ttls.add(cache.get("ttl") == null ? "5m" : String.valueOf(cache.get("ttl")));
|
||||
}
|
||||
for(Map.Entry<?, ?> entry : map.entrySet())
|
||||
{
|
||||
if(!"cache_control".equals(entry.getKey()) && !"input_schema".equals(entry.getKey()))
|
||||
{
|
||||
collectCacheTtls(entry.getValue(), ttls);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(node instanceof List<?> list)
|
||||
{
|
||||
list.forEach(value -> collectCacheTtls(value, ttls));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.GoldenTasks;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.condition.EnabledIf;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The golden tasks against the real model (claude-sonnet-5-5). Opt-in:
|
||||
** runs only with ANTHROPIC_API_KEY set AND -Dassistant.live=true (and the
|
||||
** "live" group, which the default build excludes). Never in CI by default.
|
||||
*******************************************************************************/
|
||||
@Tag("live")
|
||||
@EnabledIf("liveEnabled")
|
||||
class LiveGoldenEvalTest
|
||||
{
|
||||
private AssistantQBitConfig config;
|
||||
private QInstance qInstance;
|
||||
private AnthropicModelProvider provider;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static boolean liveEnabled()
|
||||
{
|
||||
String key = System.getenv(AnthropicModelProvider.API_KEY_ENV);
|
||||
return (key != null && !key.isBlank() && Boolean.getBoolean("assistant.live"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@BeforeEach
|
||||
void setUp() throws Exception
|
||||
{
|
||||
provider = AnthropicModelProvider.fromEnvironment();
|
||||
config = new AssistantQBitConfig().withModelProvider(provider);
|
||||
qInstance = AssistantTestFixture.build(config);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@AfterEach
|
||||
void tearDown()
|
||||
{
|
||||
config.getRuntime().close();
|
||||
provider.close();
|
||||
QContext.clear();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static Stream<GoldenTasks.Task> tasks()
|
||||
{
|
||||
return (GoldenTasks.all().stream());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@MethodSource("tasks")
|
||||
void live(GoldenTasks.Task task) throws Exception
|
||||
{
|
||||
TurnRunner.Outcome outcome = new TurnRunner(qInstance, config).run(task.userId(), task.prompt());
|
||||
assertThat(outcome.errorCode()).as("error").isNull();
|
||||
task.liveCheck().accept(outcome);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A local stand-in for the Anthropic API that replays recorded responses
|
||||
** (SSE streams or JSON errors) for POST /v1/messages and records what it
|
||||
** was sent. No network, no real key.
|
||||
*******************************************************************************/
|
||||
public class RecordedAnthropicServer implements AutoCloseable
|
||||
{
|
||||
private final HttpServer server;
|
||||
private final ConcurrentLinkedQueue<Reply> replies = new ConcurrentLinkedQueue<>();
|
||||
private final List<Map<String, String>> requests = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** One canned reply: status, content type, body, and an optional pause
|
||||
** after the body before the stream is closed.
|
||||
*******************************************************************************/
|
||||
public record Reply(int status, String contentType, String body, long holdOpenMillis)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
public RecordedAnthropicServer() throws IOException
|
||||
{
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/v1/messages", this::handle);
|
||||
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
|
||||
server.start();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Queue a recorded SSE stream (from src/test/resources/fixtures).
|
||||
*******************************************************************************/
|
||||
public RecordedAnthropicServer thenStream(String fixture, long holdOpenMillis) throws IOException
|
||||
{
|
||||
replies.add(new Reply(200, "text/event-stream", fixture(fixture), holdOpenMillis));
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Queue a JSON error.
|
||||
*******************************************************************************/
|
||||
public RecordedAnthropicServer thenError(int status, String fixture) throws IOException
|
||||
{
|
||||
replies.add(new Reply(status, "application/json", fixture(fixture), 0));
|
||||
return (this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private void handle(HttpExchange exchange) throws IOException
|
||||
{
|
||||
String body;
|
||||
try(InputStream in = exchange.getRequestBody())
|
||||
{
|
||||
body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
requests.add(Map.of("body", body, "apiKey", String.valueOf(exchange.getRequestHeaders().getFirst("x-api-key")),
|
||||
"version", String.valueOf(exchange.getRequestHeaders().getFirst("anthropic-version"))));
|
||||
|
||||
Reply reply = replies.poll();
|
||||
if(reply == null)
|
||||
{
|
||||
reply = new Reply(500, "application/json", "{\"type\":\"error\",\"error\":{\"type\":\"api_error\",\"message\":\"no recorded reply\"}}", 0);
|
||||
}
|
||||
|
||||
byte[] bytes = reply.body().getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().add("Content-Type", reply.contentType());
|
||||
exchange.getResponseHeaders().add("request-id", "req_recorded_" + requests.size());
|
||||
exchange.sendResponseHeaders(reply.status(), reply.holdOpenMillis() > 0 ? 0 : bytes.length);
|
||||
try(OutputStream out = exchange.getResponseBody())
|
||||
{
|
||||
out.write(bytes);
|
||||
out.flush();
|
||||
if(reply.holdOpenMillis() > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Thread.sleep(reply.holdOpenMillis());
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
///////////////////////////////////
|
||||
// client went away (cancelled) //
|
||||
///////////////////////////////////
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
static String fixture(String name) throws IOException
|
||||
{
|
||||
try(InputStream in = RecordedAnthropicServer.class.getResourceAsStream("/fixtures/" + name))
|
||||
{
|
||||
if(in == null)
|
||||
{
|
||||
throw (new IOException("missing fixture " + name));
|
||||
}
|
||||
return (new String(in.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The base URL to point the SDK at.
|
||||
*******************************************************************************/
|
||||
public String baseUrl()
|
||||
{
|
||||
return ("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The requests received (body, apiKey, version).
|
||||
*******************************************************************************/
|
||||
public List<Map<String, String>> getRequests()
|
||||
{
|
||||
return (new ArrayList<>(requests));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void close()
|
||||
{
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qbits.assistant.provider.anthropic.demo;
|
||||
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
|
||||
import com.kingsrook.qbits.assistant.engine.ConnectionTest;
|
||||
import com.kingsrook.qbits.assistant.engine.ModelPricing;
|
||||
import com.kingsrook.qbits.assistant.metadata.AssistantMetaDataBuilder;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
|
||||
import com.kingsrook.qbits.assistant.model.AssistantProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicProviderType;
|
||||
import com.kingsrook.qbits.assistant.provider.anthropic.RecordedAnthropicServer;
|
||||
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
|
||||
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
|
||||
import com.kingsrook.qbits.assistant.testing.TurnRunner;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.instances.AbstractQQQApplication;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleCustomizerInterface;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationJavalinServer;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Local demo of the Assistant app home and provider settings, for
|
||||
** screenshots (never against production). The Anthropic API is the
|
||||
** recorded test server, so every call is a real HTTP call through the real
|
||||
** adapter, engine, Test connection and usage recording - with canned
|
||||
** answers and no key. Everyone is an admin.
|
||||
**
|
||||
** Run with the test classpath plus the qqq-frontend-next jar; open
|
||||
** http://localhost:8099/ and the Assistant app.
|
||||
*******************************************************************************/
|
||||
public class AssistantDemoServer extends AbstractQQQApplication
|
||||
{
|
||||
private static QInstance instance;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Every browser session is an admin with the all-access key.
|
||||
*******************************************************************************/
|
||||
public static class DemoSessionCustomizer implements QAuthenticationModuleCustomizerInterface
|
||||
{
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public void customizeSession(QInstance qInstance, QSession qSession, Map<String, Object> context)
|
||||
{
|
||||
QSession admin = AssistantTestFixture.sessionFor("admin-demo");
|
||||
qSession.setUser(admin.getUser());
|
||||
qSession.setPermissions(admin.getPermissions());
|
||||
qSession.withSecurityKeyValue(AssistantMetaDataBuilder.allAccessKeyName(AssistantQBitConfig.DEFAULT_OWNER_KEY_TYPE), true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
@Override
|
||||
public QInstance defineQInstance() throws QException
|
||||
{
|
||||
return (instance);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Build, run real traffic against the recorded API, then serve.
|
||||
*******************************************************************************/
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
int port = args.length > 0 ? Integer.parseInt(args[0]) : 8099;
|
||||
|
||||
RecordedAnthropicServer api = new RecordedAnthropicServer();
|
||||
AssistantQBitConfig config = new AssistantQBitConfig()
|
||||
.withProviderName(ScriptedModelProvider.DEFAULT_NAME)
|
||||
.withModelProvider(new ScriptedModelProvider())
|
||||
.withProviderType(new AnthropicProviderType())
|
||||
.withAllowedBaseUrls(Set.of(api.baseUrl()))
|
||||
.withAllowedApiKeyEnvNames(Set.of("ANTHROPIC_API_KEY_STAGING"))
|
||||
.withSecretResolver(Map.of(AnthropicModelProvider.API_KEY_ENV, "sk-ant-demo-not-a-real-key-7f3a")::get)
|
||||
.withAllowedWidgetNames(Set.of());
|
||||
instance = AssistantTestFixture.build(config);
|
||||
|
||||
QContext.init(instance, AssistantTestFixture.sessionFor("admin-1"));
|
||||
Integer production = insert(AssistantProvider.TABLE_NAME, Map.of("name", "Claude (production)", "providerType", "anthropic", "model", "claude-sonnet-5-5",
|
||||
"enabled", true, "isDefault", true, "baseUrl", api.baseUrl(), "monthlyCostCapUsd", new BigDecimal("25.00"),
|
||||
"maxOutputTokensPerRequest", 16000, "maxConcurrentRequests", 4));
|
||||
Integer staging = insert(AssistantProvider.TABLE_NAME, Map.of("name", "Claude (staging key)", "providerType", "anthropic", "model", "claude-haiku-5-5",
|
||||
"enabled", false, "isDefault", false, "apiKeyEnvName", "ANTHROPIC_API_KEY_STAGING"));
|
||||
for(Map.Entry<String, ModelPricing> price : ModelPricing.defaults().entrySet())
|
||||
{
|
||||
ModelPricing p = price.getValue();
|
||||
insert(AssistantModelPrice.TABLE_NAME, Map.of("providerType", "anthropic", "model", price.getKey(),
|
||||
"inputUsdPerMTok", BigDecimal.valueOf(p.getInputUsdPerMTok()), "outputUsdPerMTok", BigDecimal.valueOf(p.getOutputUsdPerMTok()),
|
||||
"cacheReadUsdPerMTok", BigDecimal.valueOf(p.getCacheReadUsdPerMTok()), "cacheWrite5mUsdPerMTok", BigDecimal.valueOf(p.getCacheWrite5mUsdPerMTok()),
|
||||
"cacheWrite1hUsdPerMTok", BigDecimal.valueOf(p.getCacheWrite1hUsdPerMTok()), "notes", "Anthropic list price, 2026-10"));
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
// persona, a skill, and data access (page READ_WRITE, media NONE) //
|
||||
////////////////////////////////////////////////////////////////////
|
||||
Integer ada = insert("assistant_profile", Map.of("name", "default", "displayName", "Ada", "icon", "school", "isDefault", true,
|
||||
"personality", "Friendly and brief. Use plain words and short lists.", "greeting", "Hi, I'm Ada. Ask me about your posts and pages.",
|
||||
"starterPrompts", "How many published posts are there?\nWhat changed on page 12 this week?\nWhich posts have no excerpt?"));
|
||||
insert("assistant_profile", Map.of("name", "analysts", "displayName", "Ada (analytics)", "icon", "insights", "permissionName", "analytics_daily_stat.read",
|
||||
"personality", "Lead with the number, then one sentence of context."));
|
||||
Integer style = insert("assistant_skill", Map.of("name", "blog-style-guide", "description", "House style for titles and excerpts",
|
||||
"instructions", "## Blog style\n- Titles: sentence case, at most 60 characters.\n- Excerpts: one sentence, no links.", "triggerKeywords", "title, excerpt, headline"));
|
||||
insert("assistant_skill", Map.of("name", "seo-basics", "description", "Meta description rules", "instructions", "Meta descriptions are 120 to 155 characters.",
|
||||
"triggerKeywords", "seo, meta description", "enabled", true));
|
||||
insert("assistant_profile_skill", Map.of("profileId", ada, "skillId", style));
|
||||
insert("assistant_data_access", Map.of("objectType", "TABLE", "objectName", "page", "mode", "READ_WRITE", "notes", "Editors may let the assistant draft page changes (confirmed in the panel)."));
|
||||
insert("assistant_data_access", Map.of("objectType", "TABLE", "objectName", "media", "mode", "NONE", "notes", "Not needed for content questions."));
|
||||
|
||||
api.thenStream("text-with-thinking.sse", 0);
|
||||
ConnectionTest.run(config.getRuntime(), config.getRuntime().getStore().getProvider(production), "admin-1");
|
||||
ConnectionTest.run(config.getRuntime(), config.getRuntime().getStore().getProvider(staging), "admin-1");
|
||||
QContext.clear();
|
||||
|
||||
TurnRunner runner = new TurnRunner(instance, config);
|
||||
api.thenStream("parallel-tools.sse", 0).thenStream("text-with-thinking.sse", 0);
|
||||
runner.run(AssistantTestFixture.EDITOR, "How many published posts are there, and what tables can I see?");
|
||||
api.thenStream("text-with-thinking.sse", 0);
|
||||
runner.run(AssistantTestFixture.EDITOR, "Summarize this week's page changes.");
|
||||
api.thenStream("parallel-tools.sse", 0).thenStream("text-with-thinking.sse", 0);
|
||||
runner.run(AssistantTestFixture.ANALYST, "What were the pageviews yesterday?");
|
||||
api.thenError(529, "overloaded.json").thenError(529, "overloaded.json").thenError(529, "overloaded.json");
|
||||
runner.run(AssistantTestFixture.OTHER_EDITOR, "Draft a post outline.");
|
||||
|
||||
///////////////////////////////////////////////////////////////////
|
||||
// the first question asked in the panel proposes a page change //
|
||||
// (page is READ_WRITE): the panel shows the confirmation card //
|
||||
///////////////////////////////////////////////////////////////////
|
||||
for(int i = 0; i < 8; i++)
|
||||
{
|
||||
api.thenStream("propose-page-update.sse", 0).thenStream("proposed-answer.sse", 0);
|
||||
}
|
||||
|
||||
instance.withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK)
|
||||
.withCustomizer(new QCodeReference(DemoSessionCustomizer.class)));
|
||||
instance.setHomeAppName(AssistantMetaDataBuilder.APP_NAME);
|
||||
|
||||
new QApplicationJavalinServer(new AssistantDemoServer()).withPort(port).withServeFrontendNext(true).start();
|
||||
System.out.println("Assistant demo on http://localhost:" + port + "/");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
**
|
||||
*******************************************************************************/
|
||||
private static Integer insert(String table, Map<String, Serializable> values) throws QException
|
||||
{
|
||||
QRecord record = new QRecord();
|
||||
record.setValues(new LinkedHashMap<>(values));
|
||||
QRecord inserted = new InsertAction().execute(new InsertInput(table).withRecord(record)).getRecords().get(0);
|
||||
if(!inserted.getErrors().isEmpty())
|
||||
{
|
||||
throw (new QException("Demo insert failed: " + inserted.getErrors()));
|
||||
}
|
||||
return (inserted.getValueInteger("id"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"type":"error","error":{"type":"invalid_request_error","message":"The compiled grammar is too large, which would cause performance issues. Simplify your tool schemas or reduce the number of strict tools."},"request_id":"req_test_grammar"}
|
||||
@@ -0,0 +1,6 @@
|
||||
event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_err_01","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":50,"output_tokens":1}}}
|
||||
|
||||
event: error
|
||||
data: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}
|
||||