Compare commits

...
Author SHA1 Message Date
james.maesandCodex 36b831dd5a ci: use the shared branch-aware CodeQL worker
Co-Authored-By: Codex <noreply@openai.com>
2026-10-21 10:24:43 -05:00
james.maesandCodex 6bb8c7d826 ci: adopt central orb 0.7.12 and stable gates (#72)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 08:58:48 -05:00
james.maesandCodex 3c04d1d1d7 ci: centralize rc release completion in qqq orb (#71)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 02:29:05 -05:00
james.maesandCodex a348a4b050 ci: adopt shared orb 0.7.11 (#70)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 01:00:37 -05:00
james.maes 4049dffd0a Merge pull request #69 from QRun-IO/feature/central-ci
ci: adopt verified shared orb 0.7.0
2026-10-20 07:30:02 -05:00
james.maesandCodex ebfdae8561 ci: adopt verified shared orb 0.7.0
Co-Authored-By: Codex <noreply@openai.com>
2026-10-20 07:23:15 -05:00
james.maesandOpenAI Codex 429397a4f1 fix(ci): normalize CircleCI runtime booleans
Co-Authored-By: OpenAI Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-20 06:12:58 -05:00
james.maesandOpenAI Codex a0f9187f71 ci: expose safe continuation failure diagnostics
Co-Authored-By: OpenAI Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-20 06:09:40 -05:00
james.maesandOpenAI Codex 141de96626 ci: adopt centralized QQQ pipeline canary
Replace copied workflow logic with the strict orb-owned QBit profile.
Preserve publication opt-outs and full Maven verification.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-20 06:01:46 -05:00
james.maes dcf883fccb Merge pull request #65 from QRun-IO/feature/conversation-management
Conversation management: table access, archive/restore/delete actions, UI API 1.6.0
2026-10-19 09:58:58 -05:00
james.maesandCodex 3637ca3ad0 fix: integrate conversation management with current develop
Preserve current attachment, notification and starter prompt behavior. Encrypt user titles that resemble ciphertext unless they match the same stored record; verify all eight reactor modules.

Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 09:52:41 -05:00
james.maes 63afe0b587 Merge pull request #64 from QRun-IO/feature/starter-prompts-from-access
Starter prompts follow the user's access
2026-10-19 09:33:30 -05:00
james.maesandCodex a353381d02 Merge develop into feature/starter-prompts-from-access
Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 09:20:00 -05:00
james.maesandCodex b250585dde fix(assistant): recheck starter prompt access on every request
Cap combined prompts at three and remove cached authorization-sensitive suggestions. Preserve bounded deterministic generation and cover field, row, table, policy and history changes. Thirty focused tests passed.

Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 08:50:26 -05:00
james.maesandCodex 407bdcdb47 fix(tools): read the flat v1 table metadata response
Preserve field visibility filtering while interpreting the actual API response shape. Verified allowed fields and hidden/password exclusions through the real endpoint.

Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 08:50:25 -05:00
james.maes 2167b77543 Merge pull request #63 from QRun-IO/feature/turns-not-jobs
Chat turns are not jobs; link bulk loads to their job; notification audit
2026-10-19 08:44:43 -05:00
james.maesandCodex 3db34201fc merge: integrate verified assistant attachment support
Preserve both attachment and notification behavior. Full eight-module verify and 45 focused turn, notification, bulk-load and attachment tests passed.

Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 08:36:30 -05:00
james.maes 300bb3b96c Merge pull request #66 from QRun-IO/feature/assistant-attachments
feat(assistant): read files attached in the panel (untrusted, capped, vision-aware)
2026-10-19 08:15:33 -05:00
james.maesandCodex 9adc28f0d9 fix(attachments): validate image data and preserve host PDF fonts
Decode images within frame and pixel limits before provider use, contain malformed attachments per file, and preserve the host PDFBox font mapper.

Co-Authored-By: Codex <noreply@openai.com>
Signed-off-by: James Maes <james@kof22.com>
2026-10-19 07:50:25 -05:00
james.maesandClaude Opus 5.5 de36dbaf8d feat(assistant): give attached files to the model as untrusted data
The turn engine reads pageContext.attachments through AttachmentService and
inlines the framed content (and images for vision models) into the
question's user message, after both cached system blocks. Unreadable files
become notices; image parts are dropped before a call to a model without
vision. In HIPAA mode attachments count as PHI. The system prompt treats
uploaded_file blocks as data and tells the model to propose writes with
create_record/update_record instead of saying it cannot create records.
GET /config reports features.attachments and the attachment limits.
Adds end-to-end, PHI routing and red-team tests.

Part of KofTwentyTwo/Website-Backend#305

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:51:43 -05:00
james.maesandClaude Opus 5.5 589d8f5c1c docs: changelog and upgrade notes for conversation management
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:46:06 -05:00
james.maesandClaude Opus 5.5 b5cd747899 feat(assistant): users manage their own conversations in the table UI
assistant_conversation is open to every assistant user (assistant.hasAccess
or assistant.admin) through AssistantAccessPermissionChecker; rows stay
locked to their owner, and the Assistant app and other tables stay
admin-only. A conversation customizer limits user edits to title, pinned
and status, refuses deleting a conversation with an answer in progress and
deletes the child rows after a table delete, through the same store code
as DELETE /conversations/{id}.

Adds Archive, Restore and Delete conversations as standard streamed-ETL
record actions on the table, acting only on rows the user can see.

UI API extension assistant 1.6.0: conversation list items have running,
PATCH /conversations/{id} accepts {"read": true}, and GET /config has
conversationsTable when the session may query that table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:46:06 -05:00
james.maesandClaude Opus 5.5 c2023aa63f feat(assistant): read attached files safely (sniffing, caps, PDF text, table previews, images)
Adds the attachments package: uploads are read as the signed-in user's own
upload (core UploadRefs plus an owner check) into memory with byte caps;
the type is sniffed from content; executables, archives and unknown binary
data are refused; text and JSON are decoded with charset detection; PDF
page text comes from PDFBox (already on the classpath through core) with
page, character and memory caps and no font scan; CSV and XLSX previews
reuse core's bulk-load parsers; image sizes are read from headers.
Content is framed as an untrusted uploaded_file block with neutralized
delimiters. Limits live in AssistantQBitConfig.attachments.

Part of KofTwentyTwo/Website-Backend#305

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:43:10 -05:00
james.maesandClaude Opus 5.5 e4f369a4e7 feat(config): build starter prompts per user from what they can access
GET /assistant/config returned the profile's starter prompts as static
text, so a user could be offered examples about tables they cannot see.
profile.starterPrompts (same field and shape) is now built per user:
up to three prompts generated from the tables the user can read through
the assistant that have rows (list_tables, count_records and
describe_table via the UI API with the user's own session), cached five
minutes, stable for the day, bounded and fail-soft. Configured prompts
stay only when tagged with tables the user can read.

Part of KofTwentyTwo/Website-Backend#303

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:34:35 -05:00
james.maesandClaude Opus 5.5 fc5026594d docs: changelog and upgrade notes for turns that are not jobs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:29:54 -05:00
james.maesandClaude Opus 5.5 e1f64cfa05 fix(assistant): send scheduled task notifications through core QAlerts
The notification a task owner asked for (output mode Notification or Both)
now goes through core QAlerts.notify: category Job, the owner as the only
audience, severity by run status and a link to the conversation. It replaces
a reflective call into an older alerts SPI that no longer matched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:29:53 -05:00
james.maesandClaude Opus 5.5 f7235690b6 feat(assistant): link a launched bulk load to its job
A confirmed bulk load still launches a real durable job through
POST /qqq/v1/processes/{p}/jobs. Its tool result now carries jobHref (the
job's /app link) next to jobId and a record ref to the job, and the confirm
response's href points at the job, so the conversation links to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:29:51 -05:00
james.maesandClaude Opus 5.5 ac2107bd97 feat(assistant)!: chat turns are not jobs; remove the run tracker SPI
Ordinary chat turns no longer create core tracking jobs, so they stay out
of the Jobs tray and tables and no longer trigger a per-answer "finished"
notification. Crash safety comes from the assistant's own turn table
(leased, heartbeated assistant_turn rows, seq-numbered event replay and the
abandoned-turn sweep), which is unchanged.

Removes AssistantRunTracker, JobTrackingRunTracker, the config accessors and
the tracking id on RunningTurn, with their tests. The panel's Stop
(POST /turns/{id}/cancel) is unchanged and still covered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:29:48 -05:00
james.maesandClaude Opus 5.5 092ea21579 feat(provider-api): add an IMAGE model part and map it in the Anthropic, Bedrock and OpenAI-compatible providers
Claude models report vision. toString on a part never includes text or
image data.

Part of KofTwentyTwo/Website-Backend#305

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:26:01 -05:00
james.maes 2f848c08b7 Merge pull request #62 from QRun-IO/feature/assistant-optional-provider-health
fix(assistant): optional unreachable providers degrade health; add provider setup state
2026-10-16 11:51:19 -05:00
james.maesandClaude Opus 5.5 cfad90eaee fix(assistant): optional unreachable providers degrade health; add provider setup state
An enabled provider that is not the default and not the only route for any
configured routing (enabled profile simple/complex model, budget downgrade,
knowledge source embedding, with no fallback on another usable provider) is
optional. When it is unreachable its provider and model checks now report
DEGRADED with a message naming where requests go, instead of turning the
whole "assistant" component DOWN (central health rolls up worst-of; WARNING
severity does not cap DOWN). The default provider and sole routes stay DOWN.
Failed provider probes carry reachable=false so the circuit breaker still
refuses the provider when its central outcome is only DEGRADED.

New assistant_provider.setup_state (Active / Setting up, empty = Active):
a provider that is Setting up is never routed to (default, profile models,
fallbacks, budget downgrades, embeddings) and gets no provider or model
health checks. Additive guarded DDL in docs/schema-postgres.sql; see
UPGRADE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:43:58 -05:00
james.maes 237dbf98d6 Merge pull request #61 from QRun-IO/fix/assistant-health-tile-wording
fix(assistant): worded health tile instead of raw UNKNOWN
2026-10-16 10:20:16 -05:00
james.maesandClaude Opus 5.5 f14e445e9c fix(assistant): worded health tile instead of the raw UNKNOWN enum
The Assistant health tile showed the HealthStatus name (UP/DEGRADED/DOWN/UNKNOWN). It now shows Healthy / Degraded / Down, and "Not checked yet" when no
check has reported, with the check cadence in the context line. The drill to health_check is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 09:13:32 -05:00
james.maes 3ed622f116 Merge pull request #58 from QRun-IO/ci/release-rc-secrets-inherit
ci(release-rc): pass secrets so the shared workflow can sign the RC tag
2026-10-16 08:03:49 -05:00
james.maes 54f91107eb Merge pull request #60 from QRun-IO/feature/fail-soft-renders
feat(assistant): fail soft - validated renders, error parts, timeouts, turns that always end, client error reports
2026-10-15 21:10:01 -05:00
james.maesandClaude Opus 5.5 38ac805fe7 feat(assistant): POST /assistant/client-errors with the assistant_client_error table and health check
UI API extension assistant 1.5.0 adds POST /qqq/v1/assistant/client-errors
(AssistantClientErrorReportV1 in, AssistantClientErrorResponseV1 out, 202).
Any signed-in user may report; scope and message are required (400
otherwise, also for a non-object body). Every field is bounded, message and
stacks are scrubbed (AiRedactor secrets, e-mails, digit runs over 6, mixed
tokens, query strings), the route keeps only its path, and conversation /
message / turn ids are kept only when they are the user's own. Over
clientErrorsPerUserPerMinute (default 30) the report is acknowledged with
accepted:false and dropped, never a 429.

Rows go to the new owner-locked assistant_client_error table (Assistant app
nav, record screens, bundle help, channel wall by pattern, SET NULL foreign
keys in the reference DDL) and are deleted by retention after
toolResultRetentionDays. The assistant.client-errors health check is
DEGRADED at clientErrorWarnPerHour (default 20) reports in the last hour, so
the Assistant health card shows it too. The deprecated AssistantErrorV1
description again says "since 1.3.0".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:38:12 -05:00
james.maesandClaude Opus 5.5 20758cbc9b feat(assistant): tool and turn timeouts, failures as error parts, and turns that always end
- toolCallTimeoutSeconds (default 60): each tool call is bounded from when
  it gets a permit, and never outlives the turn's deadline; a timed-out call
  gets an ERROR is_error result.
- Tool exceptions (also Errors and toolbox failures) become an ERROR tool
  part plus an error notice; the details go only to the log.
- The engine checks renders and presentations (RenderShapes) before it
  emits or stores them; an undisplayable one is replaced by an error notice.
- Terminal events are emitted independently, so message.end and the
  terminal turn row are always written.
- Conversation detail repairs messages left STREAMING (reaping orphaned
  runs), and retention finalizes runs abandoned past the hard stream limit.
  The recovery writes are shared in AbandonedTurns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:20:44 -05:00
james.maesandClaude Opus 5.5 5180ef6102 feat(assistant): validate every part, render and presentation before it is stored or streamed
RenderShapes now checks all render types (records, record, count, widget,
history, pending_action, bulk_load_dry_run) and presentation blocks (table,
chart, metrics, filterLinks, recordLinks, actions): required lists are always
present, non-object entries are dropped and required strings get safe
defaults. A render that cannot be repaired is dropped and replaced by an
error notice ("This result could not be displayed."); unknown part and
render types pass through. Stored parts and replayed events are normalized
on read, so older rows are repaired too. Problems are logged with the type
and a fixed problem code only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:20:32 -05:00
james.maes f4eb3cc0c4 Merge pull request #59 from QRun-IO/fix/records-render-and-stream-context
fix(assistant): records renders keep empty lists; streamed progress keeps the turn context
2026-10-15 19:55:49 -05:00
james.maesandClaude Opus 5.5 8e473bcb56 fix(assistant): records renders keep empty lists; streamed progress keeps the turn context
A query that matched nothing produced a records render without rows or
columns: QQQ's JSON omits empty lists, and Next crashed reading
rows.length. Parts and stream events are now written keeping empty lists
(RenderShapes), stored ones are completed when read, and extension 1.4.0
documents AssistantRecordsRenderV1.

Streamed deltas arrive on the provider's virtual thread without a QContext,
so the writing-phase progress (JobLogWriter) failed with an NPE; the delta
handler now runs in the turn's captured context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:37:19 -05:00
james.maesandClaude Opus 5.5 fe2ec09a80 ci(release-rc): pass secrets to the shared workflow so it can sign the RC tag
QRun-IO/.github#2 adds a tag-and-release job that signs vX with the
QRUN_TAG_SIGNING_KEY secret after Maven Central confirms the artifact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:22:05 -05:00
james.maes 60435c27e3 Merge pull request #56 from QRun-IO/feature/ui-api-1.6
feat(ui-api): extension for QQQ UI API 1.6.0 (operationIds, BasicErrorResponseV1, QQQ 4.1.0-RC.15)
2026-10-15 16:12:49 -05:00
james.maes 4b7eb81d6d Merge remote-tracking branch 'origin/develop' into feature/ui-api-1.6 2026-10-15 16:01:07 -05:00
james.maes b8aff19826 Merge pull request #57 from QRun-IO/fix/shutdown-hook-weak-runtime
fix(runtime): shutdown hook holds the runtime weakly
2026-10-15 15:57:49 -05:00
james.maesandClaude Opus 5.5 9fc0eed499 fix(runtime): shutdown hook holds the runtime weakly
Every AssistantRuntime registered a JVM shutdown hook that held the
runtime, and so its whole QInstance, until JVM exit. A host test suite
that builds an instance per test leaked every instance (kof22's suite ran
out of heap). The hook now holds a weak reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:53:47 -05:00
james.maesandClaude Opus 5.5 0a23db241b chore: target QQQ 4.1.0-RC.15 (UI API 1.6.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:27:03 -05:00
james.maesandClaude Opus 5.5 c838eb4f67 feat(ui-api): assistant extension 1.3.0 for QQQ UI API 1.6.0 (operationIds, BasicErrorResponseV1, QQQ 4.1.0-RC.14)
Every operation has an operationId and the standard error responses
(BasicErrorResponseV1, keeping the assistant-specific codes); AssistantErrorV1
is kept but deprecated; bodyless 204 responses no longer reference null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 11:54:05 -05:00
james.maes 23779790ab Merge pull request #55 from QRun-IO/fix/help-bundle-version
fix(help): help bundle version comes from the build, not a hardcoded SNAPSHOT
2026-10-14 22:37:20 -05:00
james.maes bbee0d1017 Merge pull request #45 from QRun-IO/feature/health-checks
feat(health): register assistant provider and model checks with core central health
2026-10-14 22:08:14 -05:00
james.maesandClaude Opus 5.5 079e8d39e2 fix(help): the help bundle carries the artifact version (Maven-filtered) instead of a hardcoded SNAPSHOT
On release branches the bundle's version and the producer's differed, so the
bundle test that asserts they match failed, and released bundles recorded
SNAPSHOT as their provenance. help/*.yaml is now filtered:
version: ${project.version}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 22:03:49 -05:00
james.maes dd5edf84d8 Merge remote-tracking branch 'origin/develop' into feature/health-checks
# Conflicts:
#	CHANGELOG.md
#	pom.xml
2026-10-14 22:02:13 -05:00
james.maes ef933d6bea Merge pull request #54 from QRun-IO/feature/jobs-tray
feat(jobs): assistant answers in the Jobs tray (core JobTracking, QQQ RC.8)
2026-10-14 21:25:22 -05:00
james.maesandClaude Opus 5.5 385b61019b docs: Jobs tray tracking (QQQ RC.8) in CHANGELOG and UPGRADE
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:20:46 -05:00
james.maesandClaude Opus 5.5 a7184d3be9 test(jobs): tracked progress and completion, Stop from the tray, failure without transcript text, no runtime, isolated phase state
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:20:45 -05:00
james.maesandClaude Opus 5.5 2a3691c0ea feat(jobs): assistant answers in the Jobs tray through core JobTracking
JobTrackingRunTracker is the default AssistantRunTracker and replaces the
qqq#1210 stand-in: each answer is a tracking job (processName
assistant.turn, label "Assistant answer", linked to its conversation)
with thinking / tool / writing phases and the tool's label as the
message. The tray's Stop stops the turn; the turn's finaliser finishes the
job COMPLETED, CANCELLED or FAILED with fixed messages (never prompt or
answer text). No jobs runtime on the pod: answers are simply not tracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:20:44 -05:00
james.maesandClaude Opus 5.5 b6982eff9f build: QQQ 4.1.0-RC.8 (core job tracking for the Jobs tray)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:20:44 -05:00
james.maesandClaude Opus 5.5 2a7bf77c6d Merge origin/develop into feature/health-checks; pin QQQ 4.1.0-RC.8
RC.8 ships the central health kernel (QRun-IO/qqq#1207).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 21:18:21 -05:00
james.maes 1012b4b497 Merge pull request #53 from QRun-IO/feature/help-bundle
feat(help): qbit-assistant help bundle via QQQ help bundles, with coverage gate
2026-10-14 20:29:39 -05:00
james.maesandClaude Opus 5.5 76f9b286c6 feat(help): ship the qbit-assistant help bundle through QQQ help bundles, with coverage gate
Host-neutral help (deployment-specific facts removed), registered with
HelpBundles, gated by HelpBundleAssertions. QQQ 4.1.0-RC.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:16:55 -05:00
james.maes 9b4708fafc Merge pull request #44 from QRun-IO/feature/transcript-redaction
feat: no raw PII/PHI in stored transcripts (secured data §15, QQQ RC.7)
2026-10-14 19:03:20 -05:00
james.maesandClaude Opus 5.5 15938e07e1 Merge develop (durable turns, defaults, indexes, FKs) into feature/transcript-redaction
- Turn start keeps develop's supersede/concurrency, run tracker,
  register and forceFinalize, and attaches the TranscriptRedactor.
- The shared finalization flushes redaction after the final events and
  before the terminal turn update on every path (supersede, timeout,
  restart recovery, forceFinalize); the redactor always closes.
- Token-bearing columns widened to TEXT (H2-safe upgrade statements),
  entity length limits removed so tokens never truncate.
- Event reader race that could omit terminal events fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:59:03 -05:00
james.maes b2c97d1000 Merge pull request #47 from QRun-IO/feature/foreign-keys
feat(schema): add the missing foreign keys with orphan quarantine
2026-10-14 18:00:36 -05:00
james.maes ae8e394a7b Merge pull request #46 from QRun-IO/feature/schema-indexes
docs(schema): add the missing lookup, retention and FK indexes
2026-10-14 18:00:28 -05:00
james.maesandClaude Opus 5.5 1bae6e26ba test(defaults): keep the reference DDL's DO $$ block whole and skip it on H2
The foreign-key block is PL/pgSQL; the H2 loader in
AssistantDefaultsChangelogTest now splits it as one statement and skips it.
SchemaForeignKeyPostgresTest runs it on real Postgres.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:55:19 -05:00
james.maesandClaude Opus 5.5 80d529e741 Merge feature/schema-indexes (with origin/develop) into feature/foreign-keys
Conflicts in CHANGELOG.md and qbit-assistant/pom.xml: kept develop's
durable-turns and starter-defaults entries and its H2/Liquibase test
dependencies alongside the Testcontainers/Postgres ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:55:19 -05:00
james.maesandClaude Opus 5.5 b50bc4a5c7 Merge origin/develop into feature/schema-indexes
Conflicts in UPGRADE.md and docs/schema-postgres.sql: kept develop's
durable-turns and starter-defaults notes and DDL; the index audit block
now follows the durable-turns block at the end of the schema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:51:27 -05:00
james.maes 6a1bac6a9e Merge pull request #52 from QRun-IO/fix/assistant-defaults-rollback
fix(defaults): empty rollbacks; a rollback never deletes host data
2026-10-14 17:12:49 -05:00
james.maesandClaude Opus 5.5 9c3af04a91 fix(defaults): empty rollbacks so a rollback never deletes host data
A seeded row cannot be told apart from a host's own row with the same name
('default' profile, policy, starter skill names), and Liquibase also rolls
back changesets it marked ran, so the name-based rollback lines could delete
a host's data. Every seed changeset now rolls back to nothing; the test runs
a real Liquibase rollback over host-owned rows and checks they survive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:08:13 -05:00
james.maes 0bfa4e4d01 Merge pull request #49 from QRun-IO/feature/durable-turns
fix: durable assistant turns - lease, heartbeat, cross-pod Stop, never refuse a question
2026-10-14 17:06:18 -05:00
james.maes 3d288ddfe9 Merge remote-tracking branch 'origin/develop' into feature/durable-turns
# Conflicts:
#	CHANGELOG.md
#	UPGRADE.md
2026-10-14 16:59:47 -05:00
james.maes 6d6b4696a5 Merge pull request #50 from QRun-IO/fix/assistant-defaults-guards
fix(defaults): portable Liquibase preconditions; seeds never change an existing host
2026-10-14 16:58:37 -05:00
james.maesandClaude Opus 5.5 ba8e7a6562 fix(defaults): portable preconditions; never change an existing host on deploy
Review of #48 found:
- the formatted-SQL table-exists precondition does not parse in Liquibase 5
  (and is unsupported in 4.19), failing the host's whole migration: use
  sql-checks only;
- the budget and prices were seeded beside a host's own budgets and over its
  configured pricing: seed the policy, budget and prices only into empty
  tables, the profile only when no default profile exists;
- the Setup card ignored registry and configured prices: price the default
  model exactly as calls are costed;
- "Add rows for every table" could read a stale data-access cache.
The changelog test now runs through Liquibase 4.33 (kof22's version):
fresh schema, re-run, an already configured host, and a missing table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:54:36 -05:00
james.maesandClaude Opus 5.5 c751fc055c docs: durable turns upgrade notes and changelog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:36:43 -05:00
james.maesandClaude Opus 5.5 50898a927d test(turns): completion, error after streaming, disconnect, refresh, supersede, concurrency, wedged provider, pod kill, rolling deploy, cross-pod Stop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:36:42 -05:00
james.maesandClaude Opus 5.5 f60009f595 feat(api): never refuse a question; cross-pod Stop; GET /turns/active
A new question supersedes the running one in the conversation (default) or
runs concurrently; the soft per-user cap supersedes the oldest. Stop works
on any replica and on dead runs, and is idempotent. Orphans are reaped once
their lease lapses (45 s) instead of after maxTurnSeconds + 60 s. 503
SHUTTING_DOWN while a replica stops. turn.phase events and startedAt on
message.start. UI API extension assistant 1.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:36:41 -05:00
james.maesandClaude Opus 5.5 ffa7e25bf4 fix(turns): every turn is finalised: watchdog, lease, hard deadline, shutdown
A per-turn watchdog (the user's own session) renews the lease, picks up a
Stop requested on another replica, enforces maxTurnSeconds and force-
finalises a wedged engine. One idempotent finaliser: accounting or event
failures can no longer leave a turn RUNNING or registered. On shutdown the
runtime stops taking turns, cancels, waits a grace and finalises the rest
as interrupted. The in-memory concurrent counter is gone. Runs are
published through the AssistantRunTracker stand-in SPI (qqq#1210).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:36:41 -05:00
james.maesandClaude Opus 5.5 00861af42c feat(turns): lease, heartbeat, cancel request and phase columns on assistant_turn
heartbeat_at, lease_owner, cancel_requested_at, phase and concurrency_mode,
a (user_id, status) index, and a partial unique index so a turn gets one
message.end even when two replicas reap it. Store helpers for a conditional
update of a still-running turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:36:39 -05:00
james.maes 3b56c93da7 Merge pull request #48 from QRun-IO/feature/tables-populated-defaults
feat: starter defaults, setup card and table help (no empty config tables)
2026-10-14 16:33:09 -05:00
james.maesandClaude Opus 5.5 a5c38d74a8 feat: starter defaults, setup card and table help so no config table starts empty
Owner requirement 2026-10-14: every assistant table should be populated and
visibly used, and an empty table should say how to set it up.

- db/liquibase/qbit-assistant/assistant-defaults.changelog.sql (host-included,
  insert-only, self-guarding): default policy, default profile, four starter
  skills linked to it, a $50/month instance budget (warn 80, downgrade 100,
  stop 120), current Anthropic prices, a disabled example scheduled task.
- Assistant home Setup card: each config table, its state and the next step.
- assistant_data_access action "Add rows for every table" writes the default
  access out as editable rows.
- help/qbit-assistant.yaml (help-bundle format) on the app and every table,
  saying what it is for and how rows get created (STAND-IN(core=#1198)).
- Tests: guardrail (every table used at runtime, seeded or explained, with
  empty-state help); changelog seeds a fresh H2 schema insert-only; seeded
  rows drive persona, skills in the model request, budget warning, policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:28:10 -05:00
james.maesandClaude Opus 5.5 e8beb7444a Merge develop (spi package) into feature/transcript-redaction; build on released QQQ 4.1.0-RC.7
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:27:32 -05:00
james.maesandClaude Opus 5.5 fdf8d72367 feat(schema): add the missing foreign keys with orphan quarantine
Reference DDL gains a guarded, re-runnable foreign key block after the
index audit: the conversation tree CASCADEs (matching
AssistantStore.deleteConversation and retention), the message/turn cycle,
usage and the data audit are SET NULL so cost rows and the audit trail
survive, provider references from usage, budget accounting and the data
audit are NO ACTION, profile-skill links CASCADE, and
assistant_model.provider_id becomes CASCADE (fk_assistant_model_provider,
as on kof22). Orphans are recorded in qqq_fk_quarantine first. Every FK
column now leads an index.

SchemaForeignKeyPostgresTest applies the DDL on Postgres (Testcontainers)
and fails any declared relation without a foreign key, a wrong delete
rule, an unindexed FK column, or a broken conversation delete order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:23:25 -05:00
james.maesandClaude Opus 5.5 8aac6cf92d docs(schema): add the missing lookup, retention and FK indexes
The reference Postgres schema gains six IF NOT EXISTS indexes:
- assistant_usage (turn_id): ScheduledTurn.cost
- assistant_turn_event (create_date), assistant_tool_call (create_date) and
  assistant_conversation (modify_date): the retention filters
- assistant_scheduled_run (conversation_id) and (turn_id): the ON DELETE
  SET NULL foreign keys

UPGRADE.md notes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:26:08 -05:00
james.maesandClaude Opus 5.5 02215634bf docs: assistant health checks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:39:46 -05:00
james.maesandClaude Opus 5.5 303cf9a148 refactor(assistant): home shows the central health status instead of its own provider health view
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:39:46 -05:00
james.maesandClaude Opus 5.5 969a7b9101 feat(health): register provider and model checks; breaker reuses the central result
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:39:45 -05:00
james.maesandClaude Opus 5.5 8e47d9a6f5 feat(health): deadline-aware connection test with shared cost-cap accounting
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:39:44 -05:00
james.maesandClaude Opus 5.5 09787bfe22 fix: set forwarded UI API headers instead of appending (QQQ 4.1 develop compatibility)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:39:43 -05:00
james.maesandClaude Opus 5.5 6c36917beb feat: no raw PII/PHI in stored transcripts (secured data §15)
- Stored copies of tool results replace PII/PHI field values with
  ClassifiedValueTokens.forRecordField tokens (core, QRun-IO/qqq#1182);
  model-written text, persisted text deltas, presentation parts, tool
  inputs, run summaries and audit reasons have every classified value
  the turn saw replaced by its token. What the model receives (as the
  PHI routing allows) and the live SSE to the entitled user are
  unchanged.
- Pending writes that would carry a classified value are refused rather
  than stored (follow-up: an encrypted short-lived payload).
- A core log redaction hook masks seen classified values in assistant
  logs.
- Canary test: CANARY-PHI/PII markers never appear (nor any >4-char
  substring) in any assistant_* table, logs or audits, while the model
  did receive them in memory.
- Requires QQQ 4.1.0-RC.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:22:50 -05:00
james.maes befb90a48a Merge pull request #41 from QRun-IO/feature/orb-0.6.9
ci: qqq-orb 0.6.9 (refresh SNAPSHOT dependencies)
2026-10-14 10:56:29 -05:00
james.maes bca3ea9d83 Merge pull request #43 from QRun-IO/feature/provider-spi-package
refactor!: provider SPI in its own package com.kingsrook.qbits.assistant.spi
2026-10-14 10:55:28 -05:00
james.maesandClaude Opus 5.5 8655ea21d4 refactor!: provider SPI in its own package com.kingsrook.qbits.assistant.spi
The qbit-assistant-provider-api artifact now holds exactly one package,
com.kingsrook.qbits.assistant.spi (23 types including ModelPricing), so
consumers such as qbit-marketing depend only on that artifact and the
qbit-bom G1 guardrails can allow it by package. BREAKING: imports change
from ...assistant.provider.X / ...assistant.engine.ModelPricing to
...assistant.spi.X (UPGRADE.md has the table). ArchUnit forbids split
packages between the API and the implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:51:34 -05:00
james.maes 4b7b955a1f Merge pull request #42 from QRun-IO/feature/email-api
refactor(email): use qbit-email's public api package; no G1 allow-list
2026-10-14 10:25:26 -05:00
james.maesandClaude Opus 5.5 ceeb134c90 refactor(email): use qbit-email's public api package; no G1 allow-list
Moves the optional email integration from qbit-email internals to
com.kingsrook.qbits.email.api (qbit-email 0.1.0-RC.2) with identical
behaviour, and moves to qbit-build-parent 2.1.1, whose default G1
allow-lists include qbit-email's API (QRun-IO/qbit-bom#12), so the
per-repo allow-lists are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:20:42 -05:00
james.maesandClaude Opus 5.5 b49e4f4ee0 ci: qqq-orb 0.6.9 (refresh SNAPSHOT dependencies)
Moves qqq-orb@0.6.8 to qqq-orb@0.6.9, which passes --update-snapshots so cached SNAPSHOT dependencies are re-checked on every build (QRun-IO/qqq-orb#22).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:05:56 -05:00
james.maes a15d66ecc7 Merge pull request #40 from QRun-IO/feature/x1-y1-channel-wall
feat: the hard wall between the assistant and its configuration, and audit attribution (X1/Y1)
2026-10-14 09:02:36 -05:00
james.maes 886ee06cc4 Merge remote-tracking branch 'origin/develop' into feature/record-history-opt-in
# Conflicts:
#	CHANGELOG.md
2026-10-14 08:58:56 -05:00
james.maesandClaude Opus 5.5 1020c3b324 feat: withRecordHistory(true) host opt-in for get_record_history
Default off (owner: hard wall; kof22 does not opt in). When on, calls
core's ClientChannelsMetaData.withAssistantAuditReads() (QRun-IO/qqq#1193:
audits readable, never writable, worm_audit_* still denied) through a
STAND-IN(core=QRun-IO/qqq#1193, removeBy=RC.8) lookup, falling back on
RC.6 to removing exactly the audit* pattern. Other patterns are never
touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:53:10 -05:00
james.maes 73b58d7391 Merge pull request #39 from QRun-IO/feature/email-qbit
feat(email): scheduled-result email adapter for qbit-email
2026-10-14 08:27:25 -05:00
james.maes 64268e63d0 Merge remote-tracking branch 'origin/develop' into feature/x1-y1-channel-wall
# Conflicts:
#	CHANGELOG.md
#	UPGRADE.md
2026-10-14 08:19:55 -05:00
james.maesandClaude Opus 5.5 7081debe5f Merge develop into feature/email-qbit
Keeps develop's changes and re-applies the optional qbit-email 0.1.0-RC.1
delivery on top (adapted to develop's refactors; guardrail allow-lists
for the optional integration where the build parent enforces them).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:19:05 -05:00
james.maesandClaude Opus 5.5 b0b80ead3d feat: the hard wall and audit attribution (X1/Y1)
X1:
- Every assistant_* table, process, report and widget (and every object
  the qbit produces) is denied to client channel assistant: the
  assistant_* pattern in ClientChannelsMetaData plus
  QPermissionRules.withDeniedClients on each object.
- Startup fails if any of them is not denied.
- Every UI API call carries assistant/<turnId> (scheduled:
  assistant/scheduled/<taskId>); confirm and explain-access carry the
  owning turn.
- Tests: assistant.admin through the assistant is denied (403, absent
  from list_tables and /metaData) on every configuration object, while the
  same admin through next-ui is allowed; the startup check fails on one
  undenied object; core's security-surface patterns are present.
Y1:
- assistant_tool_call.audit_href: an /app link to the written record's
  audit rows filtered by clientChannel, built with the shared filter-link
  builder.
- Tests: an assistant write audits the human actor with
  clientChannel assistant/<turnId>; the same write from the UI audits
  next-ui. Hosts enable the audit clientChannel field (documented).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:17:35 -05:00
james.maesandClaude Opus 5.5 c40eebd3cd build: qbit-email 0.1.0-RC.1 from Maven Central
Moves from 0.1.0-SNAPSHOT to the first release candidate. Test schemas
gain the RC's email_provider_sender_address table and the message
from_address_id column where they copy the qbit's DDL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:58:48 -05:00
james.maes ff84e35fb3 Merge pull request #19 from QRun-IO/feature/spec-endpoints-core-invoker
feat!: spec'd /qqq/v1 assistant endpoints; tools on core's UiApiInvoker (QQQ RC.6)
2026-10-14 07:57:21 -05:00
james.maesandClaude Opus 5.5 f7faf0a8c0 docs: mark HeaderedUiApiInvoker STAND-IN(core=QRun-IO/qqq#1190, removeBy=RC.8)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:53:43 -05:00
james.maesandClaude Opus 5.5 8fab9a856e Merge develop (P-g scheduled tasks, provider-api) into #19
Scheduled runs go through the invoker as assistant/scheduled/<taskId>;
the designated-user manageSession login stays a plain UI-client login.
get_record_history is offered only when the host opts the audit tables
in (core's default wall denies audit* to the assistant). Reserved-header
filtering in the stand-in header invoker is tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:45:15 -05:00
james.maes a7a4648dd1 Merge pull request #37 from QRun-IO/feature/provider-api-module
refactor: qbit-assistant-provider-api module for the provider SPI and pricing (#30)
2026-10-14 07:35:11 -05:00
james.maesandClaude Opus 5.5 6e7438a2da Merge develop into feature/spec-endpoints-core-invoker (QQQ RC.6)
- CoreUiApiGateway on UiApiInvoker for every tool (P tools, bulk-load,
  presentation), client channel assistant/<turnId>; form params mapped to
  withFormParam; LoopbackUiApiGateway deleted.
- Extra headers (X-QQQ-AI-Route) through HeaderedUiApiInvoker, a stand-in
  until core UiApiRequest has withHeader.
- Core DataClassification replaces the qbit stand-in; the default
  classification source merges core metadata with the config map.
- Bulk-load confirm dispatch kept on the spec'd confirm path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 07:31:39 -05:00
james.maes 467c2199dc Merge remote-tracking branch 'origin/develop' into feature/provider-api-module
# Conflicts:
#	CHANGELOG.md
#	UPGRADE.md
2026-10-14 07:31:36 -05:00
james.maes 01309ddfe9 Merge pull request #36 from QRun-IO/feature/p7-scheduled-tasks
feat: scheduled assistant tasks as a designated user through the UI API (P-g)
2026-10-14 07:18:36 -05:00
james.maes de04965cd7 Merge remote-tracking branch 'origin/develop' into feature/p7-scheduled-tasks
# Conflicts:
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/AssistantRuntime.java
2026-10-14 07:13:09 -05:00
james.maes 61e6f809f1 Merge remote-tracking branch 'origin/develop' into feature/provider-api-module 2026-10-14 07:07:52 -05:00
james.maes 8e8a5c59cd Merge pull request #38 from QRun-IO/feature/bulk-load-tools
feat(bulk-load): assistant tools to use and create saved bulk load profiles
2026-10-14 07:05:51 -05:00
james.maesandClaude Opus 5.5 45593d2e79 feat(email): scheduled-result email adapter for qbit-email
Phase (d) of QRun-IO/qbit-email docs/DESIGN.md section 11. qbit-email is an
optional dependency (0.1.0-SNAPSHOT until its first RC) used through one
adapter class behind a classpath and instance guard; without it the
existing behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 23:12:37 -05:00
james.maesandClaude Opus 5.5 87835961f4 chore(bulk-load): tag the jobs-launch stand-in with the kernel PR (QRun-IO/qqq#1178)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:11:32 -05:00
james.maesandClaude Opus 5.5 c3a828c1c3 feat(bulk-load): assistant tools to use and create saved bulk load profiles
The owner asked (2026-10-13) that the assistant use and create bulk load
profiles. This adds the spec #1171 section 3.4 tools, all through the
/qqq/v1 UI API with the user's own session:

- bulk_profiles_list / bulk_profile_describe: the user's and shared
  profiles, read through the savedBulkLoadProfile table (record locks).
- bulk_file_attach: an upload the panel already made (pageContext
  attachments, refs only), with its masked column profiles.
- bulk_mapping_suggest: core's suggester. The model then refines the
  profile from the headers and the permitted samples.
- bulk_load_dry_run: the table's real bulk-insert validation (SAMPLE or
  FULL), with nothing stored. Error groups come with row numbers, so the
  model can fix the profile and run again.
- bulk_profile_save (write): storeSavedBulkLoadProfile, plus
  insertSharedRecord for each share. It runs only after the user confirms
  the pending action, and only as far as the user may share.
- bulk_load_run (write): goes through a BulkLoadRunner seam after
  confirmation. The default runner is the durable jobs launch, where core
  creates assistant jobs AWAITING_CONFIRMATION. Until that ships, it
  answers that the launch is not available yet (STAND-IN).

PHI: the X-QQQ-AI-Route header (hipaa|standard) comes from the turn's
provider HIPAA eligibility, never the model. The server masks samples and
values. Tool-call logs drop sampleValues, example bullets and value
mappings. Data access READ_WRITE is required to propose and to confirm
writes.

Supporting changes, all additive:
- UiApiCall: form params and headers.
- LoopbackUiApiGateway: multipart bodies.
- UiApiToolbox.Outcome.of.
- One dispatch branch each in ContextBuilder, TurnEngine and
  AssistantApi.confirmAction.
- ToolLabels entries.
- The config seam.

The core operations are QRun-IO/qqq#1179 (STAND-IN until an RC). Until
then the tools say the server does not offer them.

Tests: BulkLoadToolsTest (6), including the golden eval. It uploads a CSV
with messy headers. The assistant proposes a profile, the dry run finds
the missing required field, the assistant defaults it, the dry run
passes, it saves and shares the profile after confirmation, and in a
second turn runs the load after confirmation. Full ./mvnw verify is green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:47:00 -05:00
james.maesandClaude Opus 5.5 de215f8ff9 refactor: qbit-assistant-provider-api module for the provider SPI and pricing (#30)
Architecture review QRun-IO/qqq#1150 F5: qbit-marketing compiled against
assistant internals.

- New artifact qbit-assistant-provider-api with the provider SPI and
  value types (same package names) and engine.ModelPricing; production
  dependency jackson-annotations only. An ArchUnit test keeps it free of
  assistant internals.
- AssistantProviderType's settings validation takes ProviderSettings
  instead of the assistant_provider entity (documented in UPGRADE.md).
- qbit-assistant and the provider modules depend on the API artifact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:49:45 -05:00
james.maes 9e1bda8dae Merge remote-tracking branch 'origin/develop' into feature/p7-scheduled-tasks
# Conflicts:
#	README.md
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/engine/TurnEngine.java
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/metadata/AssistantRecordScreens.java
2026-10-13 20:37:33 -05:00
james.maesandClaude Opus 5.5 907d943f8d feat: scheduled assistant tasks as a designated user through the UI API (P-g)
- assistant_scheduled_task (Scheduled tasks): prompt, run-as user,
  credential env-var reference (allow-listed, never stored), profile,
  Quartz cron + time zone, output mode, write-mode request and per-task
  admin approval (cleared when the prompt, user, credential, profile or
  request changes), per-run cost cap; assistant_scheduled_run child list.
- Runner (60 s schedule): claims a slot via a unique (task, scheduledFor)
  run key, logs in exactly like a UI client (POST /qqq/v1/manageSession
  with accessToken), checks the session's user is the run-as user, then
  runs a normal turn on a new conversation (channel assistant/scheduled,
  X-QQQ-Client assistant/scheduled/<taskId>). No system or constructed
  sessions.
- PHI routing, budgets, routing/fallback apply unchanged; output as the
  conversation and run record, a notification through core alerts, or
  both. Record actions: Approve write mode, Revoke write mode, Run now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:34:46 -05:00
james.maes 5e1c213fd6 Merge pull request #34 from QRun-IO/feature/presentation-demo-shots
test(demo): answer presentation demo turn and panel screenshots
2026-10-13 20:29:45 -05:00
james.maes 1a65aa2257 Merge pull request #33 from QRun-IO/feature/p6-rag
feat: RAG over instance content, permission-filtered through the UI API (P-f)
2026-10-13 20:29:40 -05:00
james.maesandClaude Opus 5.5 17c376c5b1 feat: contingent possible values for provider model and kind (and price model)
assistant_provider.model and .kind, and assistant_model_price.model,
use CUSTOM possible-value providers that read otherValues.providerType:
the type's own models (plus the provider's enabled chat models from the
registry) and kinds. Without a providerType they return the union, so
saved rows and API callers keep working. possibleValueSourceDependsOn
("providerType") follows when the next QQQ RC has it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:26:22 -05:00
james.maes 2e90fbdc5d Merge remote-tracking branch 'origin/develop' into feature/p6-rag
# Conflicts:
#	CHANGELOG.md
#	README.md
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/engine/ContextBuilder.java
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/engine/SystemPrompt.java
#	qbit-assistant/src/main/java/com/kingsrook/qbits/assistant/engine/TurnEngine.java
2026-10-13 20:06:13 -05:00
james.maesandClaude Opus 5.5 6a26a7d4fa test(demo): answer presentation demo turn; panel screenshots
The demo's mock host answers "How many images do I have by type?" with
count_records through the UI API and then present_results, so the
panel shows the owner's example (summary, metric, table with shares and
row links, pie chart, filter links, action). Screenshots light/dark at
390/1440 px with the Next UI build of qqq-frontend-next#111.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:03:20 -05:00
james.maes 1d66154bd2 Merge pull request #32 from QRun-IO/feature/answer-presentation
feat: answer presentation: present_results, presentation parts, default presentation skill
2026-10-13 19:59:57 -05:00
james.maes 57673131ff Merge remote-tracking branch 'origin/develop' into feature/answer-presentation 2026-10-13 19:54:07 -05:00
james.maesandClaude Opus 5.5 c27994c432 feat: answer presentation: present_results tool, presentation parts and the default presentation skill
Owner priority: answers must be easy to read and act on.

- present_results tool: summary, metrics, table (computed percent
  columns, per-row filtered-list links), bar/pie/line chart from the
  table, filter and record links, follow-up actions. Every table and
  field is checked against what the user can see through the UI API;
  hrefs (/app/<table>?filter=<QQQ filter JSON>, records) and number
  formats are built server-side from metadata; the model never writes
  URLs.
- presentation message part (persisted, SSE event) with a server-built
  multi-line GFM markdown fallback for clients without blocks.
- Static system-prompt Presentation section (built-in default skill):
  answer first, no restating, tables for 3+ items, charts for shares and
  trends, filterLinks whenever a list is offered.
- Golden eval of the owner's example: summary, 2-row table with 80.2% /
  19.8%, a 2-point pie and two mimeType filter links; negative cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:54:05 -05:00
james.maes 1947688c34 Merge remote-tracking branch 'origin/develop' into feature/p6-rag 2026-10-13 19:51:42 -05:00
james.maesandClaude Opus 5.5 c487c87051 feat: RAG over instance content, permission-filtered through the UI API (P-f)
- Embeddings: EmbeddingProvider SPI, OpenAI-compatible /embeddings
  (batching, Azure path), assistant_model.model_kind CHAT/EMBEDDING and
  embedding_dimensions; chat selection ignores embedding models.
- VectorStore SPI: in-memory store, and the new qbit-assistant-rag-pgvector
  module (one schema per instance, HNSW cosine index, parameterized SQL).
  The index holds NO record content: table, key, field, chunk, hash and
  vector only.
- assistant_rag_source (Knowledge sources) with Index now / Clear index
  record actions that read through the UI API as the clicking admin,
  skip unchanged chunks and drop removed records.
- search_knowledge tool: vector search, then every hit re-read through the
  UI API with the asking user's session (403/404 hits dropped), AI field
  exposure and masking applied, /app citations; PHI rule for embeddings;
  classification raised by results.
- pgvector container test (pgvector/pgvector:pg16) passes with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:51:40 -05:00
james.maes 14bd4e377c Merge pull request #31 from QRun-IO/fix/core-alerts-rc5
refactor: budget alerts through core QAlerts on QQQ RC.5 (#28)
2026-10-13 19:34:21 -05:00
james.maesandClaude Opus 5.5 cb7d5d4d5a refactor: budget alerts through core QAlerts (QQQ 4.1.0-RC.5), alert types declared
Closes #28 (first half; the DataClassification and loopback gateway
stand-ins go with RC.6).

- Default QQQ is 4.1.0-RC.5.
- BudgetAlerts calls QAlerts.raise(AlertSignal...) directly instead of
  binding by reflection.
- The producer declares assistant.budget.warning, .downgraded and .stopped
  as QAlertTypeMetaData (assistant.admin, subject assistant_budget).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:30:01 -05:00
james.maes 51e0692f46 Merge pull request #27 from QRun-IO/feature/p5-routing-fallback
feat: simple/complex model routing and fallback chains (P-e)
2026-10-13 19:13:26 -05:00
james.maes 6f80dcaff4 Merge remote-tracking branch 'origin/develop' into feature/p5-routing-fallback 2026-10-13 19:09:28 -05:00
james.maesandClaude Opus 5.5 55804d9059 feat: simple/complex model routing and fallback chains across providers (P-e)
- Profiles gain routing (OFF, HEURISTIC, CLASSIFIER) with simple, complex
  and classifier models. The heuristic is a small documented rule set; the
  classifier is one 4-token call on the question text only (ROUTE usage,
  3 s timeout, heuristic on any failure, skipped for PHI on a
  non-eligible provider).
- assistant_model.fallback_model_id chains (cycle-checked, max 4 hops)
  across providers; retryable failures before any output fall back.
  Candidates that are disabled, down, over a STOP budget or fail the PHI
  rule are skipped; without a chain, LOCAL falls back only to LOCAL.
- Circuit breaker (provider health UP/DOWN, down_until) and a cached
  health probe for stale LOCAL providers.
- A mid-turn provider switch rebuilds history from neutral parts and drops
  adapter state (Anthropic thinking signatures).
- Turn route decision, source and fallback count; home shows health and
  fallbacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:09:26 -05:00
james.maes 73159e536e Merge pull request #26 from QRun-IO/feature/p4-budgets
feat: budgets with warn, downgrade, stop and admin overrides (P-d)
2026-10-13 18:46:19 -05:00
james.maes c05c606745 Merge remote-tracking branch 'origin/develop' into feature/p4-budgets 2026-10-13 18:43:47 -05:00
james.maesandClaude Opus 5.5 51fcfa6a33 feat: data-driven budgets with warn, downgrade, stop and admin overrides (P-d)
- assistant_budget (scope INSTANCE/USER/ROLE/PROVIDER/MODEL, DAY/MONTH,
  cost or tokens, warn %, DOWNGRADE or STOP at 100%, hard ceiling),
  assistant_budget_override (reason, grantor, expiry) and
  assistant_budget_event (deduplicated WARNED/DOWNGRADED/STOPPED).
- BudgetService checks before every model call; strictest outcome wins.
  Warnings raise a panel notice and an optional Alerts signal; downgrade
  prefers a cheaper LOCAL model and never crosses the PHI rule.
- assistant_budget_usage: an owner-lock-free accounting projection of
  usage counters so shared-scope sums run under the caller's own session.
- App home: budgets card with state and overrides, 30-day cost and token
  bars with user, model, provider and tool breakdowns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:43:45 -05:00
james.maes 8a7c10fde4 Merge pull request #24 from QRun-IO/feature/p3-hipaa-routing
feat: data classification, PHI routing and HIPAA mode (P-c, stacked on #23)
2026-10-13 18:23:37 -05:00
james.maesandClaude Opus 5.5 d15c7dce12 feat: data classification, PHI routing and HIPAA mode (P-c)
- DataClassification (PUBLIC < CONFIDENTIAL < PII < PHI): a qbit
  stand-in for core's (QRun-IO/qqq#1142) behind a pluggable
  ClassificationSource (config by default; core metadata or
  qbit-secured-data overrides later).
- Each turn tracks the highest classification its page context, history
  and tool results touched (turn.classification, conversation
  max_classification, never lowered).
- PhiRoutingGuard before EVERY model call: PHI only to hipaa_eligible
  provider rows; otherwise the turn ends PHI_BLOCKED with the reason and
  the tool results are never sent.
- HIPAA mode: no non-eligible providers (resolve, enable, code fallback),
  AES-256-GCM conversation storage (key by env-var reference, required),
  PHI retention period, no provider messages or stack traces in logs.
- assistant_data_audit: one row per model call that carried PII/PHI and
  per block (who, classification, tables, provider, model, decision).
- System rule 11: masked values stay masked; never ask to reveal them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:20:13 -05:00
james.maes e8c202ace6 Merge pull request #23 from QRun-IO/feature/p2-bedrock-vertex
feat: AWS Bedrock and Google Vertex adapters (P-b, stacked on #22)
2026-10-13 18:04:12 -05:00
james.maesandClaude Opus 5.5 95f0040748 fix: a cancelled stream ignores the worker's late complete/fail
cancel() closes the stream before it completes the handle, so the
worker's IOException could win and turn a cancel into a NETWORK error
(flaky OpenAiContractTest.timeoutCancelAndNetwork on CI).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:01:21 -05:00
james.maes 9dbb44b8c2 Merge pull request #22 from QRun-IO/feature/p1-provider-registry
feat: provider and model registry, OpenAI-compatible adapter, discovery and health (P-a)
2026-10-13 17:59:52 -05:00
james.maesandClaude Opus 5.5 34b0f67670 feat: Bedrock and Vertex kind labels
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:49:19 -05:00
james.maes 88e1081396 Merge remote-tracking branch 'origin/feature/p1-provider-registry' into feature/p2-bedrock-vertex 2026-10-13 17:47:42 -05:00
james.maesandClaude Opus 5.5 c9ccd4c79b feat: AWS Bedrock and Google Vertex adapters (P-b)
- qbit-assistant-provider-bedrock: Claude on Bedrock through the
  anthropic-java Bedrock backend (AnthropicMapping reused), credentials
  from the server's AWS default chain, region required, no key reference.
  IRSA/web identity needs the host to add software.amazon.awssdk:sts.
- qbit-assistant-provider-vertex: Claude on Vertex through the
  anthropic-java Vertex backend, Gemini through Vertex's OpenAI-compatible
  endpoint with an ADC bearer token refreshed per request (never strict).
  Region and the new cloud_project column are required.
- AnthropicModelProvider.Builder.client(...) and a bearer-token supplier
  on ProviderSettings / the OpenAI adapter.
- Mocked contract tests: a Bedrock event-stream mock with SigV4 checks,
  Vertex rawPredict and OpenAI-compatible mocks, validation, and a golden
  tool round trip per module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:47:40 -05:00
james.maesandClaude Opus 5.5 311c37c23d fix(openai): a transport error at the deadline is a TIMEOUT, not a race with the guard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:47:24 -05:00
james.maesandClaude Opus 5.5 a7be39db0f feat: readable labels for the provider registry; P-a demo server and screenshots
- Kind, source and field labels (HIPAA-eligible, API version, prices
  per million tokens, timeouts) instead of raw ids.
- Test-only OpenAiDemoServer: a mock OpenAI-compatible host, real
  Discover models / Test connection runs and one turn.
- Screenshots of the home providers card, a local provider, its Models
  child list and a model, light and dark at 390 and 1440 px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:33:43 -05:00
james.maesandClaude Opus 5.5 8d869f65cd feat: provider and model registry, OpenAI-compatible adapter, discovery and health (P-a)
- assistant_provider gains kind, location, hipaa_eligible, region, api
  version, timeouts, a CA bundle reference and discovery status.
- New assistant_model table (child list on the provider): capabilities,
  prices per million tokens, enabled flag, last test.
- Provider SPI: ProviderSettings, kinds, discovery and health as default
  methods; create(apiKey, baseUrl) implementations keep working.
- New module qbit-assistant-provider-openai: OpenAI, Azure OpenAI,
  OpenRouter, Ollama, LM Studio, vLLM and llama.cpp over JDK HTTP, with
  streaming, tool calls, usage, timeouts, cancel, strict only where
  supported (and the existing fallback on refusal), keyless local
  endpoints and per-provider private CA trust.
- Record actions: Discover models (provider), Test connection (model);
  provider Test connection checks health first.
- Mock-server contract tests, a golden tool round trip, TLS tests and a
  config-driven live check (skipped unless configured).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:17:39 -05:00
james.maes 4532098e6b Merge pull request #20 from QRun-IO/feature/spec-providers-write-mode-wall
docs: spec for write mode, the config wall, audit attribution and providers
2026-10-13 16:29:02 -05:00
james.maesandClaude Opus 5.5 f2eb20a8bc docs: spec for write mode, the config wall, audit attribution and providers
Owner decisions (2026-10-13), continued, with all recommendations
accepted:
- write mode per conversation (Read-only by default), user preference,
  admin policy, confirmed writes, auto-confirm rules;
- the hard wall: the assistant client channel is denied every assistant_*
  object and the security surfaces in core, plus a startup check;
- audit attribution: the human actor plus via=assistant/<turnId>;
- providers and models as data (OpenAI-compatible, Bedrock, Vertex),
  local models, HIPAA/PHI routing, budgets, routing, RAG and scheduled
  tasks.
Also the phase plan and its dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:20:43 -05:00
james.maesandClaude Opus 5.5 292277908b build: require QQQ 4.1.0-RC.6 (UI API extension point and invoker, qqq#1128)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:09:38 -05:00
james.maes 77bd8df7a2 Merge develop into feature/spec-endpoints-core-invoker 2026-10-13 16:07:23 -05:00
james.maes 3721a69637 Merge pull request #18 from QRun-IO/feature/demo-pending-card
test(demo): the panel proposes a page change; card screenshots
2026-10-13 14:44:50 -05:00
james.maesandClaude Opus 5.5 f6edea4b7b feat!: spec'd /qqq/v1 assistant endpoints; tools on core's UiApiInvoker
Phase (d). Needs QQQ with QRun-IO/qqq#1128 (extension point, invoker,
credentials forwarding).

- AssistantSpecs: the "assistant" UI API extension (1.0.0, established
  prefix /assistant): config, conversations, turns (text/event-stream),
  events, cancel, feedback, actions (get/confirm/reject) and access, with
  the same URLs, bodies and statuses. The raw routes are removed; the
  route provider only learns the local port.
- CoreUiApiGateway over UiApiInvoker replaces the loopback stand-in. The
  caller's credentials (UiApiCredentials.fromContext) flow from the spec
  to the tools; the assistant's own operations are never invocable.
- The OpenAPI fragment is committed and contract-tested with UiApiContract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:44:34 -05:00
james.maes 501d067415 Merge pull request #17 from QRun-IO/feature/release-rc-automation
ci: automate RC releases; hotfix/* pushes no longer publish
2026-10-13 14:42:49 -05:00
james.maesandClaude Opus 5.5 0f34c8a1dc test(demo): the panel proposes a page change; screenshots of the card
The demo queues recorded answers that propose update_record on page 12
(READ_WRITE), so a question in the panel shows the confirmation card;
Save runs it through PATCH /qqq/v1/table/page/12 with the user's session.
Screenshots of the persona, the pending card and the confirmed write
(light/dark, 390/1440), taken locally against the demo server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:34:36 -05:00
james.maes 5f5d6c5b38 Merge pull request #16 from QRun-IO/feature/demo-screens
fix: log denied tool calls against their table; demo persona and data access; screenshots
2026-10-13 14:29:39 -05:00
james.maesandClaude Opus 5.5 b0a6b648bf ci: automate RC releases; hotfix/* pushes no longer publish
Removes publish_hotfix_release: a hotfix/* branch push published a GA
release to Maven Central with no tag or review (QRun-IO/qbit-cdn#12,
QRun-IO/qqq#1121). hotfix/* branches now run test_only; a hotfix
release publishes from a reviewed vX.Y.Z tag through publish_release.
Adds .github/workflows/release-rc.yml (reusable QRun-IO/.github
qbit-release-rc): a manual dispatch, or merging a develop PR labelled
release:rc, merges develop into the release line and the release/* push
runs the existing CircleCI RC publish.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:29:30 -05:00
james.maesandClaude Opus 5.5 af811c99c2 fix: Explain access works before any assistant call, and degrades gracefully
- The route provider learns the server's local port from the first
  /qqq/v1 request (a before-handler), so the loopback UI API is known
  as soon as the UI has loaded, not only after an assistant call.
- The assistantAccess widget says why access could not be computed when
  the UI API is unreachable, instead of failing the dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:26:42 -05:00
james.maesandClaude Opus 5.5 6634d88286 fix: log denied tool calls against their table; demo seeds persona and data access
- The tool's table is recorded before the call, so a call the UI API
  refuses still names its table in the log and in Recent denials.
- AssistantDemoServer seeds a default profile (Ada), an analysts profile,
  two skills (one linked) and data access rows (page READ_WRITE,
  media NONE).
- Screenshots of the Recent denials card, Explain access widget, Data
  access table, profile, skill and policy (light/dark, 390/1440).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:24:30 -05:00
james.maes b5484bace8 Merge pull request #15 from QRun-IO/feature/profiles-skills-access
feat: profiles, skills, explain access and recent denials (phase c)
2026-10-13 14:13:40 -05:00
james.maesandClaude Opus 5.5 0babaa7022 feat: profiles, skills, explain access and recent denials
Owner (2026-10-13): set a name, personality and extra skills for the
assistant, and the assistant stays limited to the UI API and to what the
signed-in user could do through it.

- assistant_profile (persona: display name, icon, bounded personality,
  greeting, starter prompts; default, app- or permission-scoped) and
  assistant_skill (admin Markdown instruction packs, read only when
  relevant, bounded) linked by assistant_profile_skill. Text only: it
  goes into the per-user system block and never reaches tool code.
- Explain access: GET /assistant/access and the assistantAccess home
  widget, per table and tool: allowed or why not, from GET /metaData with
  the user's own session plus data access and policy.
- Recent denials card on the Assistant home.
- Hard guarantee: ArchUnit forbids the tool / UI API / access packages
  from QQQ actions, the AI kernel and the profile/skill classes, and the
  store refuses any non-assistant_ table. A denial matrix proves query,
  get, insert, update and delete are denied identically via the UI API
  and via the assistant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:10:47 -05:00
james.maes 96426ec95a Merge pull request #14 from QRun-IO/feature/ui-api-tools
feat!: assistant tools go through the /qqq/v1 UI API with the user's session (phase b)
2026-10-13 13:59:36 -05:00
james.maesandClaude Opus 5.5 01cc719c5b feat!: assistant tools go through the /qqq/v1 UI API with the user's session
Owner decisions (2026-10-13): tools via the UI API, configurable and
verifiable data access, and confirmation for writes.

- Every data tool runs a spec'd /qqq/v1 operation (UiApiGateway, a
  loopback request carrying the user's own sessionUUID cookie), so it
  passes the UI's authentication, permissions, record locks, validation,
  audit and error mapping. LoopbackUiApiGateway is a stand-in for core's
  UiApiInvoker (QRun-IO/qqq#1128). navigate and search_help (no records)
  stay on the core kernel.
- Data access (assistant_data_access): NONE / READ / READ_WRITE per table
  or process; sensitive tables NONE and cannot be raised; it only narrows.
- Writes (create/update/delete_record) propose a pending action
  (assistant_pending_action) the owner confirms; confirm runs it once
  through the UI API with the confirming request's session.
- Policy: writesRequireConfirmation, allowedTools, maxRowsPerCall,
  redactPii. Tool-call log: UI API operation, HTTP status, audit link,
  pending action; inputs stored with secrets redacted.
- UiApiToolsSecurityTest proves a user without a permission gets the same
  denial through the assistant as through the UI; golden and red-team
  evals run through a real application server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:56:18 -05:00
james.maes 1080a8b1ba Merge pull request #13 from QRun-IO/feature/strict-tools-grammar-fix
fix: stop sending every tool strict; surface provider error reasons (0.1.0-RC.5)
2026-10-13 13:29:57 -05:00
james.maesandClaude Opus 5.5 38bb123140 fix: stop sending every tool strict; surface provider error reasons
Every kof22 turn failed on its first model call with Anthropic 400
invalid_request_error "The compiled grammar is too large ... reduce the
number of strict tools". All ten read tools were strict, and the API
compiles every strict schema of a request into one grammar.

- Tools are not strict by default; hosts opt in with strictToolNames.
  The kernel validates every tool input (INVALID_INPUT) anyway.
- If a provider still refuses strict schemas, the turn retries once
  without strict tools and logs a warning.
- Provider errors carry the API error type, a sanitized message and the
  request id: logged at WARN on 4xx, request id kept on the usage row,
  the reason shown to assistant.admin holders and in Test connection.
- TurnEngine also catches Errors, so a turn never ends silently.
- AnthropicRequestContractTest checks the exact request against the
  Messages API constraints and a conservative strict-tool budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:25:28 -05:00
james.maes bb62e4a7a0 Merge pull request #12 from QRun-IO/feature/app-home-settings
Assistant app home, provider settings, Test connection, per-call usage and prices
2026-10-13 10:09:25 -05:00
339 changed files with 64511 additions and 1349 deletions

No files matched your search

+11 -68
View File
@@ -1,71 +1,14 @@
version: 2.1
setup: true
orbs:
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
qqq-orb: kingsrook/qqq-orb@0.7.12
workflows:
test_only:
jobs:
- qqq-orb/mvn_test_only:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
filters:
branches:
ignore: /(develop|release\/.*|hotfix\/.*)/
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+$/]
publish_hotfix_release:
jobs:
- qqq-orb/mvn_publish:
pre-steps:
- configure-package-install
context: [qqq-maven-registry-credentials]
branch_type: hotfix
filters:
branches:
only: [/hotfix\/.*/]
setup:
jobs:
- qqq-orb/generate_pipeline:
orb_version: 0.7.12
filters:
branches:
ignore: automation/qbit-rc-pending
tags:
only: /^v\d+\.\d+\.\d+$/
+23
View File
@@ -0,0 +1,23 @@
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
+74
View File
@@ -0,0 +1,74 @@
name: Release candidate
'on':
workflow_dispatch:
inputs:
dry_run:
description: Plan a cut without changing release state
type: boolean
default: false
finalize:
description: Retry finalization of an existing cut; do not cut another RC
type: boolean
default: false
recover:
description: Recover the same published RC after a deployment timeout; never
reupload
type: boolean
default: false
circle_build:
description: Original Circle publisher build number (recovery only)
type: string
default: ''
merge_sha:
description: Existing cut merge_sha (finalize retry only)
type: string
default: ''
bump_sha:
description: Existing cut bump_sha (finalize retry only)
type: string
default: ''
branch:
description: Existing cut branch (finalize retry only)
type: string
default: ''
version:
description: Existing cut version (finalize retry only)
type: string
default: ''
pull_request:
types:
- closed
branches:
- develop
repository_dispatch:
types:
- qbit-rc-published
permissions:
contents: write
actions: read
checks: read
jobs:
release-rc:
if: github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch'
|| (github.event_name == 'pull_request' && github.event.pull_request.merged
== true && github.event.pull_request.base.ref == 'develop' && contains(github.event.pull_request.labels.*.name,
'release:rc'))
uses: QRun-IO/qqq-orb/.github/workflows/qbit-release-rc.yml@cc30f599e63c8e41629c99d23395bac1adb8bc44
with:
dry_run: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || false
}}
finalize: ${{ github.event_name == 'repository_dispatch' || (github.event_name
== 'workflow_dispatch' && inputs.finalize) }}
recover: ${{ github.event_name == 'workflow_dispatch' && inputs.recover || false
}}
circle_build: ${{ github.event_name == 'workflow_dispatch' && inputs.circle_build
|| '' }}
merge_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.merge_sha
|| inputs.merge_sha || '' }}
bump_sha: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.bump_sha
|| inputs.bump_sha || '' }}
branch: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.branch
|| inputs.branch || '' }}
version: ${{ github.event_name == 'repository_dispatch' && github.event.client_payload.version
|| inputs.version || '' }}
secrets: inherit
+3
View File
@@ -19,3 +19,6 @@ dependency-reduced-pom.xml
/.env.local
/.cache/
.claude/settings.local.json
# Runtime output from every provider module
log/
+16
View File
@@ -0,0 +1,16 @@
profile: qbit
orb_version: 0.7.12
default_branch: develop
java_version: '21'
browsers: true
api_checks: false
docs_only: false
release_on_main: false
release_tag_policy: stable
test_branch_policy: non-release
publish:
snapshot: true
release_candidate: true
release: true
asciidoc: false
release_completion: true
+9 -2
View File
@@ -29,6 +29,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
## Modules
- `qbit-assistant-provider-api`: standalone provider SPI/value types and `ModelPricing`, all exclusively in `com.kingsrook.qbits.assistant.spi`; only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
- `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.
@@ -37,11 +39,16 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
- `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.
- `provider/`: runtime-backed `RegistryModelProvider`, plus `fake/ScriptedModelProvider` for tests, evals and demos. The SPI lives in `qbit-assistant-provider-api`.
- `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).
- `qbit-assistant-provider-openai`: OpenAI-compatible Chat Completions, model discovery and health using JDK HTTP and Jackson.
- `qbit-assistant-provider-bedrock`: Claude through the Anthropic Bedrock backend, AWS default credentials and SigV4; IRSA/web-identity hosts supply STS.
- `qbit-assistant-provider-vertex`: Claude through the Anthropic Vertex backend and Gemini through OpenAI-compatible Chat Completions, with refreshed Google ADC tokens.
- `qbit-assistant-rag-pgvector`: JDBC vector storage; depends on the runtime RAG interfaces (`VectorStore`, `ChunkVector`).
## Invariants (do not break)
@@ -90,4 +97,4 @@ QQQ style:
- `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}`.
- All seven modules and the parent POM publish. The flatten plugin resolves `${revision}`.
+257 -1
View File
@@ -1,16 +1,272 @@
# Changelog
## Unreleased - Conversation management (UI API extension 1.6.0)
- `assistant_conversation` is open to every assistant user (`assistant.hasAccess` or `assistant.admin`, through the new `AssistantAccessPermissionChecker`) in the standard table UI. Rows stay locked to their owner by the `userId` record lock, so a user only ever sees, updates and deletes their own conversations; admins with the all-access key still see everyone's. The Assistant app (its nav) and every other assistant table stay admin-only.
- Users change only a conversation's title, pinned flag and status (Active / Archived) through the table; the other fields are the assistant's own. A new title is encrypted in HIPAA mode, including literal text beginning with `enc:v1:`. Only an exact match to the same record's stored ciphertext is preserved unchanged; internal SYSTEM writes retain their existing storage path.
- A table delete of a conversation also deletes its messages, turns, turn events, tool calls, feedback, data audits and pending actions (the same rows `DELETE /conversations/{id}` removes), so nothing is orphaned on a database without the cascading foreign keys. A conversation with an answer in progress is refused.
- New record actions on `assistant_conversation`: **Archive conversations**, **Restore conversations** and **Delete conversations** (standard streamed ETL: selected records, Review, Result; same permission as the table; only rows the user can see; delete skips conversations with an answer in progress).
- UI API extension assistant 1.6.0: `GET /conversations` items have `running` (an answer in progress: a RUNNING or CANCELLING turn that is not orphaned); `PATCH /conversations/{id}` accepts `{"read": true}` (sets `unreadCount` to 0); `GET /config` has `conversationsTable: "assistant_conversation"` when the session may query that table.
## Unreleased - Starter prompts follow access
- `profile.starterPrompts` in `GET /assistant/config` is built per user: up to three prompts generated from tables the user can read that have rows (UI API metadata and count as the user, bounded, current access rechecked on every request, stable order for the day), plus configured prompts only when tagged with tables the user can read (`[table] prompt`, `[none] prompt`; untagged lines are dropped). See UPGRADE.md.
## Unreleased - Chat turns are not jobs
- Ordinary chat turns no longer create core tracking jobs: they stay out of the Jobs tray and Jobs tables, and core no longer sends an "Assistant answer finished" notification for every answer. Crash safety is unchanged; it comes from the assistant's own turn table (leased, heartbeated `assistant_turn` rows, seq-numbered `assistant_turn_event` replay and the abandoned-turn sweep). The panel's Stop (`POST /turns/{id}/cancel`) is unchanged.
- Removed the `AssistantRunTracker` SPI, `JobTrackingRunTracker` and `AssistantQBitConfig.withRunTracker` / `setRunTracker` / `getRunTracker` (see UPGRADE.md).
- Real multi-step work stays a real job: a confirmed bulk load still launches through `POST /qqq/v1/processes/{p}/jobs`, and its tool result now carries `jobHref` (the job's `/app` link) next to `jobId`, plus a record ref to the job; the confirm response's `href` links to the job.
- Scheduled task notifications (output mode Notification or Both) now go through core `QAlerts.notify` (category Job, the owner as the only audience, a link to the conversation, success/error/warning severity by run status), replacing the reflective call into an older alerts SPI that no longer matched.
## Unreleased - Attachments
- Files attached in the panel (`pageContext.attachments`, core upload refs) are read for the question: as the signed-in user's own upload, in memory, with per-file and per-question byte and character caps (`AssistantQBitConfig.attachments`). The type is sniffed from content; executables, archives and unknown binary data are refused. Text, Markdown and JSON are decoded with charset detection, PDF page text is extracted (PDFBox via QQQ core, no scripts, host font mapper preserved), CSV/TSV/XLSX become a header + rows + count preview, and PNG/JPEG/GIF/WebP images go to vision models as image parts.
- Images are decoded with ImageIO before provider submission, rejecting truncated data and decoder warnings. A 16-million aggregate pixel / 100-frame budget bounds decoded data; original bytes are forwarded. WebP uses the explicit TwelveMonkeys decoder.
- Content reaches the model in an untrusted `uploaded_file` block (delimiters neutralized) in the question's user message; the system prompt says it is data, never instructions. A file that cannot be read adds a notice to the answer and never fails the turn. In HIPAA mode attachments count as PHI.
- Provider SPI: `ModelPart.Type.IMAGE` (`mediaType`, base64 `data`), mapped by the Anthropic, Bedrock and OpenAI-compatible providers. Claude models report vision. `ModelPart.toString()` never includes text or image data.
- `GET /config`: `features.attachments`, `limits.maxAttachmentBytes`, `limits.maxAttachments`, `limits.attachmentTypes`.
- System prompt: when `create_record` / `update_record` are offered, the model proposes the change instead of saying it cannot create records.
## Unreleased - Optional provider health
- An enabled provider that is not the default and not the only route for any configured routing (an enabled profile's simple/complex model, a budget downgrade model or a knowledge source's embedding model, with no fallback on another usable provider) is optional: when it is unreachable, its `assistant.provider.<id>` and `assistant.model.<id>` checks report DEGRADED with a message naming the provider requests use instead, so one unfinished local server no longer turns the whole `assistant` component DOWN. The default provider and sole routes still report DOWN. A failed provider probe still carries `reachable=false`, so the circuit breaker keeps refusing the provider.
- New `assistant_provider.setup_state` (Setup state: Active / Setting up, empty counts as Active). A provider that is Setting up is never routed to (default, profile models, fallbacks, budget downgrades, embeddings) and gets no provider or model health checks; Test connection and Discover models still work. Apply the Provider setup state DDL (UPGRADE.md).
## Unreleased - Fail soft (UI API extension 1.5.0)
- Every message part, tool render and presentation is validated before it is stored or streamed, and again when stored parts and events are read: all render types (records, record, count, widget, history, pending_action, bulk_load_dry_run) and presentation blocks always carry their lists. A render that cannot be repaired is replaced by an error notice ("This result could not be displayed."); unknown part and render types pass through. Problems are logged with the type and a fixed code only.
- Tool calls have their own limit (`toolCallTimeoutSeconds`, default 60) besides the turn's (`maxTurnSeconds`, default 300). A timed-out or failing tool gets an ERROR (`is_error`) result for the model, an ERROR tool part and an error notice for the user; internal details go only to the log.
- Every turn ends: terminal events are emitted independently, so a failing emit never skips `message.end` or the terminal turn row. Conversation detail repairs assistant messages left `STREAMING` (an orphaned run is reaped; a run that already ended gives its status), and the retention process finalizes runs still `RUNNING` past the hard stream limit (e.g. after a pod restart).
- `POST /qqq/v1/assistant/client-errors` (extension 1.5.0): the panel reports errors it hit (`scope`, `message`, optional stacks, route, ids, part/render type, app version, `occurredAt`). Answers `202 {"accepted": true}`; over `clientErrorsPerUserPerMinute` (default 30) it answers `202 {"accepted": false}` and drops the report. Fields are bounded, message and stacks scrubbed (secrets, e-mails, long numbers, tokens, query strings), ids kept only when they are the user's own. Rows go to the new owner-locked `assistant_client_error` table (Assistant app nav, retention after `toolResultRetentionDays`), and the `assistant.client-errors` health check turns degraded at `clientErrorWarnPerHour` (default 20) reports in an hour. Apply the Fail soft DDL (UPGRADE.md).
## Unreleased - Empty renders and stream context (UI API extension 1.4.0)
- Tool result renders always carry their lists: a `records` render for a query that matched nothing now has `"rows": []` and `"columns": []` (QQQ's JSON omitted empty lists, and Next's Assistant crashed the page reading `rows.length`). Parts and events stored before the fix are completed when read. Extension 1.4.0 documents the shape as `AssistantRecordsRenderV1`.
- Streamed text arrives on the provider's own (virtual) thread; the turn's progress updates now run in the turn's QContext, so job progress no longer fails with "Could not flush job progress" (NPE on the missing instance).
## Unreleased - UI API 1.6.0
- UI API extension assistant 1.3.0 (requires QQQ 4.1.0-RC.15, UI API 1.6.0): operationIds, standard error responses with BasicErrorResponseV1, extension tags and trace IDs. Preserve HTTP statuses and assistant-specific error codes.
- Retain AssistantErrorV1 as a deprecated component for compatibility. Remove dangling `null` schema references from the two bodyless 204 responses (delete conversation and feedback), with an empty-content workaround for core schema traversal. Success payloads are unchanged; the contract test retains the release baseline with explicit exceptions for the error schema migration and these documentation corrections.
## Unreleased - Central health
### Added
- Dynamic `assistant.provider.<id>` and `assistant.model.<id>` dependency checks in component `assistant`, category AI, reusing provider diagnostics and minimal connection calls with deadlines, cost-cap/kill-switch skips and TEST usage accounting.
- LOCAL breaker reuse of central provider outcomes younger than 60 seconds, with its existing lazy probe as fallback.
- Generic Assistant health status card linking to filtered System Health; registration, status, accounting, deadline and sentinel-secret tests.
- QQQ 4.1 compatibility for the header shim: setting extra headers avoids duplicates now that core forwards them too.
### Removed
- The home's independent answering/last-test health indicators and per-provider health/down-until display. Central health owns status and history. Manual Test connection actions, `lastTest*` fields and the circuit breaker remain.
## Unreleased - Jobs tray
- Track assistant answers in the core Jobs tray through `JobTracking`, with thinking, tool and writing progress and Stop support.
- Require QQQ 4.1.0-RC.8 and the host's durable jobs runtime and jobs tables; answers remain untracked when the runtime is absent.
- Default to `JobTrackingRunTracker`; opt out with `withRunTracker(AssistantRunTracker.NOOP)`.
## Unreleased - In-app help
- Ship the host-neutral Assistant help bundle through QQQ's native registry, replacing the temporary loader.
- Cover Assistant tables, fields, actions, widgets and selectors; retain live metadata references and add a bundle coverage gate.
- Document HOST bundle overrides and remove deployment-specific provider, classification, retention and backup guidance.
## Unreleased - Transcript redaction
- Tokenize classified PII/PHI in stored messages, tool inputs/results, replay events, pending actions and derived summaries using QQQ secured-data tokens. Preserve eligible model requests and live SSE.
- Stage content until turn completion, redact split deltas and classify criteria even when no records match; protect assistant logs with a scoped core redactor.
- Reject proposals whose parameters were redacted; prevent confirmation before turn completion.
- Read core table-level classification metadata and add secured-data canary tests for storage, audits, logs and in-memory model access.
- Preserve durable-turn watchdog, supersede, shutdown and restart recovery with turn-scoped transcript redaction; widen token-bearing columns and entity limits, with H2-safe upgrade SQL.
- Require QQQ 4.1.0-RC.7 (qqq#1182); retain the default audit-history opt-in and avoid duplicated routing headers against current core. RC.7 is released.
## Unreleased - Foreign keys
- Reference DDL: add the missing foreign keys (conversation tree, usage, data audit,
budget accounting, profile skills) with orphan quarantine and their indexes; make
`assistant_model.provider_id` `ON DELETE CASCADE`. A Postgres guardrail test fails
any declared relation without a foreign key.
## Unreleased - Durable turns
- Renew user-owned run leases with heartbeats, poll cross-replica Stop, enforce
hard deadlines, and finalize active runs during graceful shutdown. Recover
abandoned runs on replay, active discovery, or the next question.
- Default to superseding a prior answer in the same conversation. Accept explicit
concurrent questions; the per-user cap supersedes the oldest run instead of
refusing another question. Per-minute limits and budgets still apply.
- Add `GET /qqq/v1/assistant/turns/active`, `turn.phase` progress and `startedAt`
on `message.start`. Cancel is idempotent and returns HTTP 200.
- Add the optional `AssistantRunTracker` Jobs tray SPI (no-op by default),
pending QQQ core job tracking (#1210).
- Add the durable-turn schema upgrade; apply it before deploying this runtime.
A partial unique index fences duplicate terminal events from concurrent reapers.
- UI API extension `assistant` 1.2.0 (additive): `turns/active`, the optional
`concurrency` on a new turn, 503 `SHUTTING_DOWN`, `turn.phase`,
`message.start.startedAt`, cancelReason `SUPERSEDED`. The 429 response stays
documented for budgets and per-minute limits; the "answer already in progress"
refusal is no longer returned. Cancel keeps 202 documented for older replicas.
## Unreleased - Starter defaults
- Every seed changeset's rollback is empty: a seeded row cannot be told apart from a host's own row with the same name, and Liquibase also rolls back changesets it marked ran, so a name-based undo would delete host data.
- Fix the defaults changelog: every precondition is a portable `sql-check` (the formatted-SQL `table-exists` form failed to parse); the policy, budget and prices are seeded only into empty tables and the profile only when no default exists, so an existing host never changes on deploy. The test now runs the changelog through Liquibase 4.33, including an already configured host and a missing table.
- The Setup card prices the default model the way calls are costed (registry, price rows, configured prices); "Add rows for every table" reads fresh data-access rows.
- Ship `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql`: insert-only starter rows for the policy, a default profile, four starter skills offered through it, a monthly instance budget (warn, downgrade, stop), current Anthropic prices and a disabled example scheduled task.
- Add the Setup card to the Assistant home: every configuration table with its state (set up, needs setup, using defaults, optional) and the next step.
- Add the `assistant_data_access` table action "Add rows for every table", which writes the default access out as editable rows.
- Add `help/qbit-assistant.yaml` (QQQ help-bundle format) for the app and every assistant table, saying what each table is for and how its rows get created; applied by `AssistantHelp` until core help bundles ship in a release.
- Guardrail tests: every table is used at runtime, seeded or explained, and has empty-state help; the changelog seeds a fresh schema and the seeded rows change the assistant's behavior.
## Unreleased - X1/Y1
- Add default-off `withRecordHistory(true)` host opt-in: remove only `audit*` on RC.6, or invoke core #1193 audit-read/write-deny support when available. Preserve user permissions and all other channel denials; kof22 does not opt in.
- Register explicit assistant-channel denials on every assistant table, process,
report and widget, preserving core security patterns; fail runtime startup
when an assistant object is exposed.
- Bump the assistant UI API extension to 1.1.0 for optional owned-turn attribution
on explain-access, and regenerate its OpenAPI contract.
- Preserve turn attribution in knowledge discovery, RAG reads and explain-access
calls; confirm actions retain the original turn and scheduled runs retain the task.
- Build audit links with the presentation filter-link builder, filtering by
record, table and channel, including deletes; widen audit link storage to TEXT.
Document the host audit migration and the QBit column widening.
- Verify the admin denial matrix through the real invoker and Next UI, startup
failures, and confirmed-write human/channel attribution with decoded audit links.
## Unreleased - Email
### Changed
- Switch scheduled-result email delivery to qbit-email 0.1.0-RC.2's published `com.kingsrook.qbits.email.api` package, preserving templates, categories, idempotency keys, linked records and status mapping.
- Add optional qbit-email 0.1.0-RC.1 delivery of a scheduled task's result (`AssistantEmail.sendScheduledResult`): template `assistant_scheduled_result`, link-only secure message for results above PUBLIC using core's `DataClassification`, owner-recipient hook, opt-in and `emailExternalApproved` gates. Scheduled-task wiring remains a separate integration step.
## Unreleased - Provider API extraction (#30)
- **BREAKING:** move all 23 provider API types, including `ModelPricing`, to `com.kingsrook.qbits.assistant.spi`. Recompile consumers with the new imports; see UPGRADE.md. Enforce exclusive package ownership and API dependency boundaries with ArchUnit.
- Extract provider SPI/value types and `ModelPricing` into `qbit-assistant-provider-api`, now exclusively in `com.kingsrook.qbits.assistant.spi`. Its only production dependency is Jackson annotations.
- Move Anthropic, OpenAI, Bedrock and Vertex main dependencies to the API; retain runtime fixtures in test scope. Pgvector still needs runtime RAG interfaces.
- Provider-specific validation now takes unresolved `ProviderSettings` instead of `AssistantProvider`; add an ArchUnit boundary and standalone coverage gates.
## Unreleased - P-g
- Add admin Scheduled tasks, owner-locked run history, Quartz cron/timezones,
and a 60-second QQQ scheduled process using the host's scheduler context.
- Log in through the loopback UI API with a separately allow-listed credential
environment reference; verify the designated user before starting a normal turn.
- Add Review/Result Approve write mode, Revoke write mode and Run now actions.
Approval binds the task definition; scheduled writes always await confirmation.
- Attribute scheduled UI API requests and tool logs, apply per-run STOP caps,
and send optional Alerts notifications to the designated user. HIPAA summaries
contain only `see conversation`.
- Add unique schedule-slot claims, fixed-clock fixture integration tests and
additive Postgres DDL. No API routes or provider modules change.
## Unreleased - P-f
- Add OpenAI-compatible embeddings (including Azure), explicit CHAT/EMBEDDING
model kinds, editable discovery hints, and budgeted EMBED usage.
- Add admin Knowledge sources with streamed Review/Result Index now and Clear
index actions. Indexing uses the clicking admin's UI API session, chunks text,
skips unchanged hashes and reconciles disappeared records.
- Add content-free in-memory and optional JDBC pgvector stores, per-instance
schemas, HNSW cosine search and transactional record replacement.
- Add permission-filtered `search_knowledge`, fresh UI API reads, existing
masking/redaction, PHI embedding guards, classification propagation and citations.
- Add embedding HTTP contracts, real UI API RAG security/golden tests and
always-on JDBC contracts; the pgvector container test skips without Docker.
## Unreleased - Answer presentation
- Add `present_results`: server-formatted metrics, tables, computed percentages,
charts and validated in-app filter/record/action links.
- Persist and stream presentation parts with a multi-line GFM fallback and
record-data retention; add a static default presentation skill.
- Add the owner's 81 JPEG / 20 PNG golden example, shared live eval coverage,
permission/formatting/input tests and strict-schema budget coverage.
## Unreleased - P-e
- Add per-profile heuristic/classifier model routing, with budgeted ROUTE usage.
- Add bounded cross-provider fallback chains, PHI-safe selection, neutral history
rebuilding, and a 60-second connection circuit breaker with cached local probes.
- Show provider health, fallback totals and turn routing; include additive schema
migration and admin record-screen controls.
## Unreleased - P-d
- Require QQQ RC.5 and send budget alerts directly through core QAlerts, with admin-visible alert type metadata and core sink tests.
- Admin budgets, expiring overrides, deduplicated warning/downgrade/stop events.
- Per-dispatch limits preserving PHI routing and existing caps.
- Home budget cards, 30-day cost/token bars and provider breakdowns.
## Unreleased — P-c
- Add configurable table/field classification, persistent turn/conversation maxima,
and PHI routing checks before every model call, with a safe blocked-turn reason.
- Add HIPAA mode, eligible-provider enforcement, AES-256-GCM conversation storage,
provider diagnostic redaction, and independent PHI conversation retention.
- Add owner-locked, admin read-only data routing audits and HIPAA status on the home.
- Classification levels are core's `DataClassification` (the qbit stand-in is removed); the default source reads core AI metadata merged with configuration.
All notable changes to this project are documented here. The format follows Keep a Changelog, and versions follow semantic versioning.
## [0.1.0] - Unreleased
- Add optional AWS Bedrock (Claude) and Google Vertex (Claude/Gemini) adapters using server credentials, static model discovery and allow-listed endpoint overrides. AWS IRSA/web-identity hosts supply STS themselves; no additional dependency is bundled.
- Add the provider `cloudProject` column, cloud settings validation, injected Anthropic clients and per-request OpenAI bearer-token suppliers. Vertex Gemini prefixes model ids and omits strict tools.
- Add localhost cloud contract tests and golden tool turns, including AWS binary event-stream framing, SigV4, token refresh and cloud HTTP error mapping.
- Add named, server-only CA bundles for HTTPS providers, additive JVM trust and sanitized TLS diagnostics; tolerate repeated/missing streamed tool identities and invalid arguments, with a golden tool round-trip test.
- Add the provider/model registry, per-model capabilities and prices, keyless local providers, discovery and health, and provider/model connection tests.
- Add the optional JDK HTTP OpenAI-compatible adapter for OpenAI, Azure, OpenRouter, Ollama, LM Studio, vLLM and llama.cpp, with strict-schema safeguards and localhost contract tests.
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.7, needs QQQ with QRun-IO/qqq#1128)
- The assistant's endpoints are spec'd `/qqq/v1` operations (UI API extension `assistant` 1.0.0, prefix `/assistant`): same URLs, bodies and statuses, now in the served OpenAPI; turns and events are `text/event-stream`. The raw routes are gone.
- Tools call core's `UiApiInvoker` with the caller's own request credentials (`UiApiCredentials`); the loopback stand-in is removed. The assistant's own operations are never invocable by its tools.
- The OpenAPI fragment is committed (`openapi/qqq-v1/assistant.yaml`) and contract-tested.
### 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`.
- **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.
+25 -5
View File
@@ -11,10 +11,10 @@ This file provides guidance to Claude Code when working with code in this reposi
- 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`).
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.
- 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.
- 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).
## Build Commands
@@ -29,6 +29,8 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
## Modules
- `qbit-assistant-provider-api`: standalone provider SPI/value types and `ModelPricing`, all exclusively in `com.kingsrook.qbits.assistant.spi`; only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
- `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.
@@ -37,21 +39,33 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
- `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.
- `provider/`: runtime-backed `RegistryModelProvider`, plus `fake/ScriptedModelProvider` for tests, evals and demos. The SPI lives in `qbit-assistant-provider-api`.
- `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).
- `qbit-assistant-provider-openai`: OpenAI-compatible Chat Completions, model discovery and health using JDK HTTP and Jackson.
- `qbit-assistant-provider-bedrock`: Claude through the Anthropic Bedrock backend, AWS default credentials and SigV4; IRSA/web-identity hosts supply STS.
- `qbit-assistant-provider-vertex`: Claude through the Anthropic Vertex backend and Gemini through OpenAI-compatible Chat Completions, with refreshed Google ADC tokens.
- `qbit-assistant-rag-pgvector`: optional host-supplied JDBC vector store, isolated by instance schema; depends on runtime RAG interfaces (`VectorStore`, `ChunkVector`), with no QQQ RDBMS internals.
## Invariants (do not break)
- **Transcript redaction:** stored transcripts never contain raw PII/PHI values; tokens via `ClassifiedValueTokens`. Redact storage copies before truncation/encryption; eligible model inputs and live SSE remain unchanged.
- **Sessions:**
- Scheduled runs log in as the designated user through `POST /qqq/v1/manageSession`; resolve only its returned UUID, verify the user id, and never construct or elevate a session. The QQQ-supplied scheduler context touches only assistant bookkeeping.
- 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.
- **Channel wall:** every `assistant_*` object (table, process, report and widget) is denied to the `assistant` channel; startup fails otherwise. Requests carry `assistant/<turnId>` or `assistant/scheduled/<taskId>`; administration uses `next-ui`.
- **Data access:**
- The vector index stores no record content: only source/table/key/field/chunk, content hash and embedding. Retrieval re-reads every hit through the UI API as the asking user, then applies the existing get_record exposure/masking path.
- Only `persistence/` calls QueryAction, InsertAction and the other data actions (ArchUnit).
- Tools run only through `AiToolKernel.execute`.
- 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:**
@@ -59,9 +73,15 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
- 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.
- Scheduled task `credentialEnvName` is a separately allow-listed environment variable NAME. Tokens never enter rows, model context or logs. `credentialStatus` is computed and stripped on save.
- Scheduled write approval is invalidated by changes to prompt, run-as user, credential reference, profile or write request. Scheduled writes always require the designated user's panel confirmation.
- **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`).
- **PHI routing:** PHI only to `hipaaEligible` providers; checked before every model call. Conversation classification never decreases.
- **HIPAA storage:** Conversation storage encrypted in HIPAA mode, only in `AssistantStore`; encryption keys are environment references and never logged or stored in tables.
- **Fallback:** fallback never crosses the PHI rule; never local-to-cloud by default. No retry after partial output from that call; provider switches rebuild neutral history without providerState.
- **Budgets:** budgets are checked before every model call; downgrade never crosses the PHI rule.
- **Kill switch:** read fresh before every model call and every tool step.
## Tests
@@ -90,4 +110,4 @@ QQQ style:
- `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}`.
- All seven modules and the parent POM publish. The flatten plugin resolves `${revision}`.
+543 -6
View File
@@ -4,12 +4,143 @@ An in-app AI assistant for any QQQ application. The user asks a question in a ch
Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`.
## Modules
| 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-api` | Provider SPI, connection settings, messages, usage and pricing types; only Jackson annotations at runtime. |
| `com.kingsrook.qbits:qbit-assistant` | The QBit: conversation tables, turn engine, `/qqq/v1/assistant` routes (JSON + Server-Sent Events), budgets, kill switch, the provider registry, 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. |
| `com.kingsrook.qbits:qbit-assistant-provider-openai` | OpenAI-compatible chat and embedding providers. |
| `com.kingsrook.qbits:qbit-assistant-provider-bedrock` | Claude through AWS Bedrock. |
| `com.kingsrook.qbits:qbit-assistant-provider-vertex` | Claude and Gemini through Google Vertex AI. |
| `com.kingsrook.qbits:qbit-assistant-rag-pgvector` | JDBC vector store; retains the runtime dependency for `VectorStore` and `ChunkVector`. |
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.
### Implementing a provider outside qbit-assistant
Depend on `com.kingsrook.qbits:qbit-assistant-provider-api` at the same version as
QBit Assistant, and implement `AssistantModelProvider` and optionally
`AssistantProviderType`. No assistant runtime dependency is needed. All API types, including
`ModelPricing`, live exclusively in `com.kingsrook.qbits.assistant.spi`. External
consumers such as qbit-marketing allow that package in their G1 guardrails;
qbit-bom will add it to the G1 defaults. See [migration imports](UPGRADE.md#provider-api-extraction-30).
`AssistantProviderType.validate(ProviderSettings)` receives unresolved settings
(including `apiKeyEnvName`), without a database entity or resolved credentials.
Hosts register providers through `AssistantQBitConfig` in `qbit-assistant`.
Data tools use the QQQ UI API (`/qqq/v1`) with the signed-in user's session. The UI API enforces permissions and record locks; assistant data-access policy and field exposure can only narrow access. Only record-free navigation and help use the core AI tool kernel. Every tool result reaches the model wrapped as untrusted data.
## Transcript privacy
QQQ **4.1.0-RC.7** supplies the secured-data tokens and log hook (`qqq#1182`).
Stored transcripts never contain the raw PII/PHI values read by a turn or supplied
in classified tool criteria/fields. Messages, tool logs, replay events, knowledge
snippets and pending payloads store `ClassifiedValueTokens` tokens; scheduled
summaries use the redacted message. The model and live user stream retain the
values permitted by PHI routing. History and replay show tokens instead.
Content is finalized at turn completion; interrupted servers leave value-free
placeholders. Proposals requiring redacted parameters are rejected and must be
completed in the application. Existing transcripts are not migrated. See
[transcript redaction](docs/DESIGN.md#transcript-redaction-secured-data-15).
The dependency upgrade stays draft until RC.7 is published; local verification:
```powershell
.\mvnw.cmd -q verify "-Dqqq.snapshot.version=4.1.0-RC7PRE-SNAPSHOT"
```
## Host audit attribution (X1/Y1)
Use QQQ **4.1.0-RC.6 or later**. The QBit explicitly denies every assistant
configuration table, process, report and widget to the `assistant` channel;
runtime initialization fails if an assistant object is exposed. The same human
can still administer it through Next UI (`next-ui`). Core's security-surface
deny patterns remain in place.
Enable the audit client field in the host's core audit provider **after adding
the backing column**:
```java
new AuditsMetaDataProvider().withClientChannelField(true)
.defineAll(qInstance, backendName, null);
```
Add nullable `audit.client_channel VARCHAR(100)` using the host's migration and
column-naming conventions. For kof22 this requires a feature-named changeset
under `changesets/features/`; this QBit does not migrate the host's audit table.
The actor remains the signed-in human; `clientChannel` distinguishes
`assistant/<turnId>`, `assistant/scheduled/<taskId>` and `next-ui`.
Apply the X1/Y1 DDL in [UPGRADE.md](UPGRADE.md) to widen the existing
`assistant_tool_call.audit_href` column to TEXT for encoded filters.
Successful record writes store `assistant_tool_call.auditHref` as an `/app/audit`
filter link over `recordId`, `auditTable.name` and `clientChannel`. The human
opens this link with their UI permissions; the assistant cannot read audits by
default. Without the audit channel field, the QBit leaves `auditHref` empty.
Confirmed scheduled actions use their original turn id when the human approves.
## RAG setup
Knowledge retrieval is optional. The vector index stores **no record content**:
only source/table/key/field/chunk identifiers, SHA-256 hashes and embeddings.
Indexing reads through the UI API as the clicking administrator. Retrieval
re-reads each hit through that same API as the asking user, silently filters
403/404 results, applies `get_record` field exposure/masking/redaction and returns
fresh snippets with `/app/...` citations. `search_knowledge` follows `allowedTools`
and is offered only with an enabled source the user may read in the UI.
1. Register the OpenAI-compatible provider module and configure the embedding
endpoint through the existing provider settings/URL allowlist. Discover or add
a model, set **Model kind = EMBEDDING** and its dimensions. Known discovery
defaults are `bge-m3` (1024) and `nomic-embed-text` (768); these remain editable.
CHAT models cannot be selected for embedding, and EMBEDDING models cannot answer
chat turns. Each embedding batch contains at most 64 inputs.
2. Use the default `InMemoryVectorStore` for tests/small hosts, or add
`com.kingsrook.qbits:qbit-assistant-rag-pgvector` at the QBit's version for
persistence. The host supplies its JDBC driver and DataSource; this module
does not depend on QQQ RDBMS internals.
3. For pgvector, have the DBA install the extension once in the chosen database:
`CREATE EXTENSION IF NOT EXISTS vector`. Give the application a distinct schema
per QQQ instance. Configure the store before producing the QBit:
```java
PgVectorStore vectors = new PgVectorStore(dataSource, 1024)
.withSchema("assistant_rag_my_instance");
vectors.ensureSchema();
config.withVectorStore(vectors);
config.withUiApiBaseUrl("http://127.0.0.1:8000");
```
The UI API URL is this server's own listening address. Configure it explicitly
so Index now works before any chat request has taught the runtime its local
port. The store creates a content-free `assistant_rag_chunk` table and an HNSW
cosine index. Its fixed dimension must match every source using the store;
different models are searched separately. No credentials go in source rows.
See the [pgvector installation/index documentation](https://github.com/pgvector/pgvector)
and the reference DDL in [schema-postgres.sql](docs/schema-postgres.sql).
4. Open **Assistant → Knowledge sources** as an `assistant.admin`. Add the table,
comma-separated text fields, optional title field and QQQ query-filter JSON,
embedding model, and chunk size/overlap (defaults 1500/200). Tables with AI data
access NONE, `assistant_*` tables, and fields with NONE/METADATA_ONLY exposure
are refused. MASKED fields are masked before embedding and in snippets.
5. Select **Index now**. Review makes no embedding calls; Result reports records
seen, chunks embedded, unchanged, removed and errors. Re-running unchanged
content sends no embeddings. A complete successful scan removes disappeared
records; failed scans preserve unvisited entries. **Clear index** removes only
that source's vectors. Changes after indexing are read fresh, but semantic
ranking becomes current only after re-indexing.
Embedding usage has purpose `EMBED`, counts toward budgets, and observes the kill
switch and provider concurrency limits. PHI sources and queries in PHI
conversations require an eligible embedding provider; the eligibility flag is an
operator assertion, as for chat. Automatic budget downgrades cannot change an
embedding model's vector space, so an incompatible downgrade stops the call.
Scheduling is deferred to P-g. Its designated-user runner can call
`RagService.index` within that user's authenticated context; P-f creates no system
session, stored admin credentials, scheduler or background content crawler.
Data tools call the QQQ UI API through `UiApiToolbox` and `UiApiGateway` with the signed-in user's session. The UI enforces permissions and record security; the assistant further narrows access and caps and redacts returned values. Data tool results reach the model wrapped as untrusted data. Only record-free navigation and help use the core AI tool kernel.
## Requirements
@@ -61,6 +192,15 @@ The key never goes in config, tables or logs. It lives in the application's secr
The provider's `toString` never contains the key. Its errors carry only the HTTP status and the API error type.
### Starter defaults
Include `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql` (shipped in
the jar) after your assistant DDL. A new installation then has a policy row, a
default profile with four starter skills, a $50/month instance budget, current
Anthropic prices and a disabled example scheduled task. Every row is insert-only,
so administrators can edit them freely. The home's **Setup** card shows what is
set up and the next step for the rest (usually: add a provider).
## Provider settings (the Providers table)
Admins set up providers on the **Providers** screen (`assistant_provider`), a standard QQQ table:
@@ -80,12 +220,41 @@ Admins set up providers on the **Providers** screen (`assistant_provider`), a st
**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`.
## Health checks
The producer registers dynamic central checks in component `assistant`, category `AI`:
| Name | Kind | Interval | Timeout |
| --- | --- | --- | --- |
| `assistant.provider.<id>` | DEPENDENCY | 300s; 60s for LOCAL providers | 10s |
| `assistant.model.<id>` | DEPENDENCY | 21600s (6 hours) | 30s |
Suppliers include enabled provider/model rows and refresh with the central registry.
Provider checks reuse `AssistantProviderType.checkHealth`. Unsupported probes use
circuit-breaker state only when less than ten minutes old, otherwise return UNKNOWN.
Model checks reuse `ConnectionTest` (embeddings for embedding models), respect the
provider's monthly cost cap and the kill switch, and leave manual `lastTest*` fields
unchanged. A capped check returns UNKNOWN, `skipped: cost cap`, even on demand.
The automated runner records usage under its own owner key. Provider caps use the
existing shared accounting projection without access to other users' usage records.
Usage purpose is a string, so health diagnostics reuse `TEST` (not a new `HEALTH` enum).
All checks honor their deadlines; messages and details omit provider error text,
credentials, endpoints, prompts and completions.
The LOCAL circuit breaker consults central results less than 60 seconds old before
its lazy probe. UP/DEGRADED avoids a duplicate probe, DOWN rejects the call, and
UNKNOWN or stale/missing results retain the existing probe fallback. The breaker
and manual Test connection actions remain available.
This integration uses the core health SPI released in QQQ 4.1.0-RC.8.
The POM pins that release; verify with `./mvnw -o verify`.
## 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.
The **Assistant** app's home shows configuration, usage and cost read as the viewing admin. A generic status card summarizes the central runner's latest results and links to System Health filtered to `assistant`; it shows UNKNOWN before results are available. Health history and check lists live in System Health.
- **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.
- **Configuration and usage:** default provider, key status, 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, 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).
@@ -126,6 +295,9 @@ The nav lists the home and the main tables: **Providers**, **Conversations**, **
| `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. |
| `emailExternalApproved` | `false` | Stands in for the EXTERNAL approval rule (not built yet): scheduled-task result email is sent only when `true`. |
| `emailRecipientResolver` | owner id if it is an address | Hook: task owner user id to email address. |
| `attachments` | on; 10 MB per file, 25 MB per question | Files attached in the panel (see [Attachments](#attachments)): `enabled`, `maxFileBytes`, `maxTurnBytes`, `maxFileChars` (50,000), `maxTurnChars` (150,000), `maxPdfPages` (50), `previewRows` (20), `maxImageBytes` (5 MB), `maxImageDimension` (8000 px). |
At runtime, an admin can override the kill switch, the main model and effort, and the budgets in the single **`assistant_policy`** row.
@@ -135,6 +307,29 @@ A running turn notices the kill switch in two ways:
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.
## Attachments
The panel uploads a file with core `POST /qqq/v1/uploads` and sends its ref with the question as `pageContext.attachments` (`[{uploadRef, fileName}]`, at most 5). The assistant then:
- reads the upload as the signed-in user, through core `UploadRefs` and `StorageAction`, and only the user's **own** upload (a jobs administrator's wider upload access is not used); the bytes stay in memory, within `maxFileBytes` and `maxTurnBytes`;
- sniffs the type from the bytes, never from the name or the browser's content type. It reads text and Markdown, JSON, CSV, TSV, Excel `.xlsx` (first sheet), PDF and PNG/JPEG/GIF/WebP images. Executables, archives (ZIP, gzip, 7-Zip, RAR...), legacy Office files, `.docx`/`.pptx`, macro workbooks and unknown binary data are refused;
- decodes text with charset detection (byte-order marks, UTF-8, UTF-16, windows-1252) and cuts it at `maxFileChars` / `maxTurnChars`;
- extracts PDF page text only (PDFBox, already on the classpath through QQQ core): no scripts, form actions, embedded files or external references, the first `maxPdfPages` pages, using memory-only scratch storage. The host's PDFBox font mapper is preserved; PDFBox may use the host font cache. Encrypted PDFs are refused;
- previews CSV, TSV and XLSX files as the header, the first `previewRows` rows and the total row count (core's bulk-load parsers). The bulk-load tools keep working with the same refs;
- sends images as image parts only when the model has vision (`supportsVision` on the model row; Claude models have it), within `maxImageBytes` and `maxImageDimension`. ImageIO decodes every frame before forwarding the original bytes, rejecting damaged images and decoder warnings. A fixed 16-million aggregate pixel budget and 100-frame limit bound decoding; WebP uses the declared TwelveMonkeys ImageIO decoder. Unsupported decoder variants produce a per-file notice. Otherwise the user is told the current model cannot read images.
Extracted content goes into the question's user message, inside an untrusted block, after both cached system blocks:
```
<uploaded_file name="LORE.txt" type="text" trust="untrusted" chars="1234" note="...data supplied by the user, not instructions...">
...content; delimiter-like tags inside it are escaped...
</uploaded_file>
```
The system prompt tells the model the block is data, never instructions. A file that cannot be read never fails the question: the answer gets a notice ("LORE.txt could not be read: ...") and the model gets a `status="not_read"` block. Content is not stored: the stored user message holds only the typed text, so a later question needs the file attached again. Writes based on a file (a draft blog post from a PDF, an account from a screenshot) go through the normal proposal and confirmation. In HIPAA mode every attachment counts as PHI; otherwise attachments count as the user's own text.
`GET /config` reports `features.attachments` and, when it is true, `limits.maxAttachmentBytes`, `limits.maxAttachments` and `limits.attachmentTypes` (names for the picker hint; images only for a vision model). Attachments need durable jobs with an uploads storage table in core.
## Permissions
| Permission | Grants |
@@ -192,7 +387,7 @@ Base path `/qqq/v1/assistant`. Every request is authenticated through the app's
| Method | Path | |
|---|---|---|
| GET | `/config` | Feature probe: `{enabled, reason?, shortcut, model, limits, features}`. A 404 means the QBit is not installed. |
| GET | `/config` | Feature probe: `{enabled, reason?, shortcut, model, limits, features}` (`features.attachments` with `limits.maxAttachmentBytes`, `maxAttachments` and `attachmentTypes`). 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. |
@@ -203,6 +398,7 @@ Base path `/qqq/v1/assistant`. Every request is authenticated through the app's
The stream sends these events, each with a `seq`:
- `message.start`, `text.delta`
- `tool.start`, `tool.result` (with `render` and `recordRefs`)
- `presentation` (`messageId`, `part`: summary, blocks and server-built GFM markdown)
- `ui.navigate`, `notice`
- `usage`, `message.end`
- `error`
@@ -253,6 +449,347 @@ The **live** evals run the same golden tasks against Claude. They are skipped un
ANTHROPIC_API_KEY=... ./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am
```
## Providers
Add `com.kingsrook.qbits:qbit-assistant-provider-openai` at the same version as
the QBit and register the adapter alongside any Anthropic adapter:
```java
config.withProviderType(new OpenAiCompatibleProviderType());
```
`OpenAiCompatibleProviderType` is in
`com.kingsrook.qbits.assistant.provider.openai`. Its installed type id is
`openai-compatible`; provider rows choose OPENAI, AZURE_OPENAI, OPENROUTER,
OLLAMA, LM_STUDIO, VLLM, LLAMA_CPP or OPENAI_COMPATIBLE as their kind.
- Local kinds use their localhost endpoint by default and need no key. Leave
`apiKeyEnvName` empty. An auth proxy can use an explicitly allowed key env name.
- Cloud defaults use `OPENAI_API_KEY`, `AZURE_OPENAI_API_KEY` or
`OPENROUTER_API_KEY`. Values stay in the host's secret store.
- An override must match an entry in `config.withAllowedBaseUrls(Set.of(...))`.
Azure and OPENAI_COMPATIBLE have no default URL and always require an entry.
Redirects are not followed. Azure uses the deployment model id and defaults
`apiVersion` to `2024-10-21`.
- **Discover models** adds a provider's Models child list; existing edits survive.
Large cloud catalogs (over 20 models) start disabled. **Test connection** is
available on both providers and models and records a TEST usage row.
- A selected registered model must be enabled. With no model selected, the first
enabled registry model wins; providers with no model rows retain legacy selection.
Registry prices override type/model prices, then configured prices. Unpriced
local models cost zero. Capabilities can be adjusted per registered model.
For Ollama behind a TLS proxy with a private CA and bearer authentication:
```java
config.withProviderType(new OpenAiCompatibleProviderType())
.withAllowedBaseUrls(Set.of("https://llm.example.lan:8443/v1"))
.withAllowedApiKeyEnvNames(Set.of("LOCAL_LLM_API_KEY"))
.withTrustedCaBundleFile("local-llm", Path.of("/etc/app/llm-root-ca.pem"));
```
Set `LOCAL_LLM_API_KEY` in the server environment from your secret store. In the
provider record choose kind `OLLAMA`, base URL `https://llm.example.lan:8443/v1`,
`apiKeyEnvName = LOCAL_LLM_API_KEY`, and `tlsCaBundle = local-llm`. Only the names
are stored. `withTrustedCaBundle("local-llm", pem)` also accepts one or more PEM
certificates directly at startup. Invalid PEM fails configuration immediately.
The named bundle adds to the JVM roots; hostname verification stays enabled.
Leave `tlsCaBundle` empty to use JVM trust alone. Restart after changing a CA file.
Default tests use localhost mocks. To exercise an existing development server,
set `ASSISTANT_LIVE_OPENAI_BASE_URL` and `ASSISTANT_LIVE_OPENAI_MODEL`, optionally
`ASSISTANT_LIVE_OPENAI_KIND` (default OLLAMA), `ASSISTANT_LIVE_OPENAI_KEY_ENV`
(the variable name containing the key), and `ASSISTANT_LIVE_OPENAI_CA_FILE`
(a PEM bundle path). Unset or unreachable endpoints, including TLS failures, skip
the live test. Run:
```sh
./mvnw verify -pl qbit-assistant-provider-openai -am -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true
```
### AWS Bedrock (Claude)
Add `com.kingsrook.qbits:qbit-assistant-provider-bedrock` at the QBit version and
register `com.kingsrook.qbits.assistant.provider.bedrock.BedrockProviderType`:
```java
config.withProviderType(new BedrockProviderType());
```
Create a provider row with type `bedrock`, kind `BEDROCK`, and the required AWS
`region` (for example `us-east-1`). Leave `apiKeyEnvName` empty. The server uses
the AWS default credential chain: environment variables, profiles and container
credentials (ECS/EKS Pod Identity) work with the transitive dependencies.
**For IRSA / web-identity credentials, the host application must add
`software.amazon.awssdk:sts` to its runtime classpath**, matching the transitive
AWS SDK version. The default chain picks it up when present; this adapter does
not include STS or the full AWS SDK. Credentials are never stored in tables.
Leave the base URL empty for the SDK's
`https://bedrock-runtime.<region>.amazonaws.com` endpoint. Overrides, including
VPC endpoints, must be listed in `withAllowedBaseUrls`. Model ids are Bedrock
Claude ids or inference profile ids, for example
`us.anthropic.claude-sonnet-4-5-20250929-v1:0`. The model must be available to the
server's AWS role in that region.
### Google Vertex AI (Claude, Gemini)
Add `com.kingsrook.qbits:qbit-assistant-provider-vertex` at the QBit version and
register `com.kingsrook.qbits.assistant.provider.vertex.VertexProviderType`:
```java
config.withProviderType(new VertexProviderType());
```
Create a row with type `vertex`, kind `VERTEX`, required `region` (for example
`us-east5`) and `cloudProject` (the GCP project id). Leave `apiKeyEnvName` empty.
The server uses Google Application Default Credentials, such as
`GOOGLE_APPLICATION_CREDENTIALS` or workload identity. Access tokens are refreshed
when expired, held only in memory, and obtained afresh for each Gemini request.
Models beginning `claude-` (for example `claude-sonnet-4-5@20250929`) use the
Anthropic Vertex backend's `streamRawPredict` API. All other model ids use Vertex's
OpenAI-compatible endpoint:
```text
https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/endpoints/openapi
```
Unprefixed ids, such as `gemini-2.5-flash`, are sent as `google/gemini-2.5-flash`;
already-prefixed ids are preserved. Gemini requests omit `strict`, including when
a tool opts in. An allow-listed base URL overrides the Claude API origin or the
complete OpenAI-compatible base URL, according to the selected model. Use separate
provider rows when an override needs different URL prefixes for the two APIs.
Both cloud types default to CLOUD and expose a short static model catalog.
**Discover models** returns those defaults; it does not call Bedrock's
`ListFoundationModels` (which needs the control-plane SDK) or Vertex Model Garden.
Health probes are unsupported; **Test connection** performs the existing one-shot
completion. Model access and availability depend on the configured region/project.
`hipaaEligible` is an administrator-recorded fact: a BAA and the associated legal
and operational requirements remain owner responsibilities. The flag does not
establish eligibility or implement PHI routing.
The default build tests both clouds using localhost only, fake credentials, AWS
binary event-stream framing, Claude SSE and Gemini Chat Completions, including
engine/tool golden turns. No cloud credentials or live endpoints are required.
## License
Apache 2.0.
## Email through qbit-email
When the optional [qbit-email](https://github.com/QRun-IO/qbit-email) is on the classpath **and** produced in the instance, a finished scheduled-task run can be emailed to its owner. Without it nothing changes: `AssistantEmail.sendScheduledResult` returns `NOT_AVAILABLE`. The dependency is `optional`; every reference to it is in `AssistantEmailSender`.
This integration uses qbit-email **0.1.0-RC.2** through its published `com.kingsrook.qbits.email.api` package. Scheduled tasks (P-g) are available, but the runner does not yet wire email delivery. Hosts can call `AssistantEmail.sendScheduledResult(qInstance, config, new ScheduledResultNotice(...))` after a run, supplying its owner, classification, absolute run link and explicit opt-in as `emailResult`. Persisting a task-level email opt-in and wiring the runner remain a separate integration step.
Gates, in order (each returns a status and queues nothing):
1. the task opted in (`NOT_REQUESTED`);
2. qbit-email is installed (`NOT_AVAILABLE`);
3. `emailExternalApproved` is `true` (`NOT_APPROVED`). The EXTERNAL approval rule exists only in the spec, so this explicit flag gates it until the rule is built;
4. a recipient resolves (`NO_RECIPIENT`): `emailRecipientResolver` maps the owner's user id to an address; by default an owner id that already is an address is used.
What is sent, one message per recipient, idempotency key `assistant:scheduled:<run id>`, linked record the run:
- result classified PUBLIC (or none): template `assistant_scheduled_result` (NOTIFICATION, Markdown, registered on first send and never overwritten) with the task name, run time, a summary cut to 280 characters and a link to the run. The full model output is never emailed;
- result classified above PUBLIC (core's `DataClassification`): only the link, through qbit-email's `email_secure_message` pattern. No task name, summary or output.
The outbox result maps to `QUEUED`, `DUPLICATE`, `SUPPRESSED` or `REFUSED` (for example a link that is not absolute http(s)). Addresses and bodies are never logged.
## Data classification and HIPAA mode
Classify application tables and fields in core's AI metadata (`AiTableMetaData` / `AiFieldMetaData`, QQQ 4.1.0-RC.6), or in the host configuration (a configured value wins when both are set):
```java
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
AssistantQBitConfig config = new AssistantQBitConfig()
.withDataClassification("patient", DataClassification.PHI)
.withDataClassification("patient", "id", DataClassification.PUBLIC)
.withDataClassification("patient", "email", DataClassification.PII)
.withDataClassification("patient", "status", DataClassification.PUBLIC)
.withHipaaMode(true)
.withHipaaRetentionDays(2190)
.withConversationEncryptionKeyEnvName("ASSISTANT_CONVERSATION_KEY");
```
Set that environment variable through your secret manager to a base64-encoded,
random 256-bit (32-byte) key. Supply only its **name** in config, never the key.
The existing server-side `withSecretResolver` hook also resolves this reference.
Startup validates the key. HIPAA mode defaults off; encryption can also be enabled
with the key reference while HIPAA mode is off.
The levels are core's `DataClassification` (PUBLIC < CONFIDENTIAL < PII < PHI); the
qbit's former stand-in enum is gone. Unconfigured tables default to PUBLIC; a field
falls back to its table unless explicitly overridden. A field subset uses its
selected fields; unrestricted reads and record page contexts use the highest
classification across the table and its fields. Returned columns and record-label
fields also count: tools include a primary key even for subsets, so classify it
explicitly if the host considers it safe for that subset. Cross-table results with unknown
tables use the highest classification anywhere. Metadata-only tools remain PUBLIC.
The assistant's own tables remain denied to tools.
The default `ClassificationSource` reads core's metadata (`AiDataClassifications`,
`AiTableMetaData`, `AiFieldMetaData`) merged with the configured map; configuration
wins when both are set. Hosts can still supply `withClassificationSource(ClassificationSource)`.
PHI is sent only to a persisted provider row explicitly marked `hipaaEligible`.
Every model dispatch rechecks eligibility, including calls after tools and strict
schema retries. Blocks end the turn with `PHI_BLOCKED` or `HIPAA_PROVIDER`; the
PHI tool result is never sent to that provider. There is no automatic fallback.
A conversation keeps its highest classification, so moving to a PUBLIC page does
not make existing PHI history safe for a non-eligible provider.
HIPAA mode also refuses non-eligible providers at resolution and when enabling
settings rows, disables code-only fallback, requires encrypted conversation
storage, and suppresses provider error details in logs and turn errors. The app
home displays HIPAA mode and PHI retention. The eligibility flag records the
operator's decision (including any applicable BAA); it does not establish one.
Both modes audit each PII/PHI model call and every routing block in
`assistant_data_audit` (admin read-only, owner-locked, on the conversation screen).
PHI conversations use `hipaaRetentionDays` even with HIPAA mode off. A null value
uses normal retention; tool-result/replay cleanup remains independently configured.
See [UPGRADE.md](UPGRADE.md) for schema changes, plaintext migration, and key handling.
## Data-driven budgets
Admins configure **Assistant > Budgets** for UTC DAY or MONTH allowances in USD or
TOKENS, scoped to INSTANCE, USER, ROLE (a permission), PROVIDER or MODEL. Provider
and model scope values are registry record ids. Warnings default to 80%; at 100%
the default action is DOWNGRADE, and the hard ceiling defaults to 120% (always
STOP). Multiple budgets apply together and STOP wins.
An explicit downgrade model is optional. Otherwise the cheapest enabled usable
model is selected, preferring LOCAL providers. PHI never goes to a provider that
is not HIPAA-eligible. No eligible target means STOP. Administrators can grant
extra allowance or temporary unlimited use from the budget's Overrides child list,
with a required reason and expiry; the session sets the grantor.
Budget state changes appear once per scope/period/state in the Events child list,
as panel notices and, through core QAlerts, bell alerts when an alerts sink is installed (logging otherwise).
The Assistant home shows budgets, overrides, daily cost and tokens, and breakdowns
by user, model, provider and tool. Existing `AssistantBudgets`/policy limits and
provider monthly caps continue to apply independently of these rows and overrides.
See [UPGRADE.md](UPGRADE.md) for the required additive schema.
### Profile routing and provider fallback
On an Assistant Profile, **Model routing** defaults to OFF. HEURISTIC selects the
complex slot for long questions (>600 characters), two mentioned app tables,
analysis/comparison/explanation/trend/planning requests, pending writes, more than
eight previous turns, or a previous tool limit; otherwise it selects the simple
slot. CLASSIFIER uses an optional registry model with just the question and a
fixed instruction, four output tokens and a three-second timeout. An invalid reply,
error, unavailable classifier or PHI-ineligible classifier uses HEURISTIC. ROUTE
usage counts toward budgets. Empty model slots keep the provider/policy default;
budgets may downgrade either choice. Without a profile, enabled code-level
`AssistantModelRouting.escalation*` supplies the complex default.
A model's **Fallback model** points to its next candidate, including another
provider. Chains are cycle-free and bounded to four hops. Only retryable failures
before any text or tool start from that call permit fallback. Disabled, down,
PHI-ineligible or budget-blocked candidates are skipped. Without explicit links,
only another LOCAL model in the same adapter family is eligible; local requests
never automatically move to cloud. Provider state/signatures are removed when
switching, preserving neutral tool history. Each attempted call is audited as usage.
NETWORK/TIMEOUT marks a provider DOWN for 60 seconds; success marks it UP. Local
health uses recent central results or a lazy probe with a two-second timeout. The
central health card links to System Health; failures show fallback totals, and turn records show the
route and final destination. See [UPGRADE.md](UPGRADE.md) for the additive schema.
## Scheduled tasks
Administrators configure recurring prompts in **Assistant → Scheduled tasks**.
Tasks use Quartz cron syntax (for example `0 0 8 * * ?`) and an IANA timezone
(for example `America/Chicago`; default `UTC`). Tasks start disabled.
```java
config.withUiApiBaseUrl("http://127.0.0.1:8000")
.withScheduledTasksSchedulerName("hostScheduler")
.withAllowedScheduledCredentialEnvNames(Set.of("ASSISTANT_SCHEDULED_TOKEN"));
```
Provide a long-lived access token accepted by the host's authentication provider
in that environment variable. Store only its **name** on the task and set
`runAsUserId` to the corresponding QQQ user id. The runner posts the token to
`/qqq/v1/manageSession`, reads its session cookie and verifies the returned
session's user before starting a new conversation. No system session reads user
data. Configure the loopback URL at startup; a scheduled job cannot rely on a
browser having visited first.
For kof22, provision a designated Authentik account with the intended application
permissions, obtain a token that kof22's QQQ authentication provider accepts as an
`accessToken`, and inject it through the existing secret-manager/ExternalSecret
pipeline. An Authentik management API token is suitable only if the host's auth
adapter explicitly accepts it. Rotate the token in the secret manager, never in
the task table. This feature does not provision an account or token.
**Run now**, **Approve write mode** and **Revoke write mode** are Review/Result
record actions. Write approval names the designated user and displays the exact
prompt SHA-256. Changing prompt, user, credential reference, profile or write-mode
request clears approval. Scheduled writes always wait for that user's panel
confirmation, even if normal policy disables confirmation.
Each run keeps an owner-locked audit row and a normal conversation. RECORD adds
no notification; NOTIFICATION and BOTH also notify the designated user through
the optional Alerts QBit SPI. Without Alerts, notification delivery is log-only.
HIPAA summaries are always `see conversation`. Cost caps stop at dispatch
boundaries, so the last completed call can cross the cap; no further call starts.
Apply the [P-g migration](UPGRADE.md#p-g-scheduled-tasks) before enabling jobs.
### Answer presentation
The always-available `present_results` tool turns retrieved results into metrics,
tables, charts and actionable in-app links. The server validates the user's UI API
visibility, formats field values, computes shares and builds all links. It emits
and stores a `presentation` part with a complete GFM Markdown fallback. Profile
skills can extend the built-in presentation instructions. See the
[part, stream and input contract](docs/answer-presentation.md).
The image-breakdown golden task also runs in the existing opt-in live provider suite:
`./mvnw verify -Dassistant.live=true -Dtest.excludedGroups= -Dgroups=live -Djacoco.skip=true -pl qbit-assistant-provider-anthropic -am`
(with `ANTHROPIC_API_KEY` set). Live calls are excluded from normal verification.
### Record history and the assistant channel
Core's default `ClientChannelsMetaData` denies `audit*` to the `assistant`
channel. Accordingly, `get_record_history` is offered only when all three audit
tables it queries (`auditTable`, `audit`, and `auditDetail`) exist and are not
channel-denied, including their effective permission rules. A host that intends
to expose record history can opt in during instance configuration:
```java
new AssistantQBitConfig()
.withRecordHistory(true);
```
This is an owner decision and a hard wall: record history defaults to disabled;
**kof22 does not opt in**. On QQQ RC.6, the opt-in removes exactly `audit*`
from the assistant's denied patterns (the former manual configuration step).
RC.6 does not add a separate channel write denial for audits. On later RCs that
include QRun-IO/qqq#1193, it calls `withAssistantAuditReads()`, which allows audit
reads but denies audit writes. The user's own audit permissions still apply.
Other patterns, including `worm_audit_*`, `assistant_*`, and security surfaces,
remain untouched, as do explicit object and permission-rule denials.
History visibility uses core's `isDenied` read/all-operation check. RC.6 has no
operation argument; the later write-only deny patterns must remain separate
from that check so they do not hide the read tool.
## In-app help
The QBit registers [`help/qbit-assistant.yaml`](qbit-assistant/src/main/resources/help/qbit-assistant.yaml)
with QQQ's help-bundle registry during production. Hosts with help content storage use QQQ's
startup bundle sync; registration is harmless when the host has no `helpContent` table.
To customize the wording, register a separate bundle with `layer: HOST` using
`HelpBundles.register(qInstance, "help/my-application.yaml")`. Entries with the same key and
role override this QBIT bundle. User-edited help remains protected by core's sync.
Keep live `{{...}}` references so labels and metadata values follow the host's configuration.
`AssistantTablesGuardrailTest.everyOwnedTargetHasBundleHelp` checks coverage and live references
against the produced test instance with `HelpBundleAssertions`; it runs in the normal Maven build.
Update the bundle's literal version alongside the artifact version when releasing.
+520
View File
@@ -1,5 +1,424 @@
# Upgrading qbit-assistant
## Conversation management (Unreleased, UI API extension assistant 1.6.0)
No schema change. `assistant_conversation` is now usable by every user holding
`assistant.hasAccess` (not only `assistant.admin`), together with three new
record actions (Archive, Restore and Delete conversations). Rows stay locked to
their owner. A user's table queries only return their own rows if their session
carries their owner key: call `AssistantSecurity.applySessionKeys` from the
authentication customizer for **every** user, not only for admins. Without it,
non-admin users see an empty table.
The panel can link to the table using `conversationsTable` from `GET /config`.
That field is present only when the user may query the table.
## Starter prompts follow the user's access (Unreleased)
`GET /assistant/config` no longer returns the profile's starter prompts as written.
`profile.starterPrompts` (same field, still `string[]`) is now built per user:
- Up to three prompts are generated from the tables the signed-in user can read
through the assistant and that have rows (a count as the user), using the table
labels, a date field when present, and "What changed in ... this week?" when the
change-history tool is offered. The pick is stable for the user for the day and
rechecked on every request, including table, row and field access. Generation
uses bounded UI API calls and no model calls. Any failure yields no generated prompts.
- A configured starter prompt (Assistant Profile > Starter prompts, one per line) is
shown only when it declares the tables it needs and the user can read all of
them. Declare them with a leading tag: `[blog_post] Which posts are drafts?`, or
`[blog_post, page] ...` for several. `[none] What can you help with?` names no
table and is always shown. A line without a tag is no longer shown, because
nothing says which tables it mentions: add a tag to keep it.
- Shown prompts are the permitted configured ones first, then generated ones, three
in all (a profile with three or more permitted prompts shows only those).
No schema change and no configuration. The panel needs no change.
## Chat turns are not jobs (Unreleased)
Ordinary chat turns no longer create core tracking jobs, so they no longer appear
in the Jobs tray or the Jobs tables and no longer trigger a per-answer "finished"
notification. No schema change and no configuration is needed.
The `AssistantRunTracker` SPI and `JobTrackingRunTracker` are removed, along with
`AssistantQBitConfig.withRunTracker`, `setRunTracker` and `getRunTracker`. A host
that called any of them must delete the call: `withRunTracker(AssistantRunTracker.NOOP)`
is now the only behavior, and a custom tracker has no replacement hook. Turn
progress, Stop and recovery are available through the assistant's own routes
(`GET /turns/active`, the turn events stream and `POST /turns/{id}/cancel`).
Bulk loads the assistant launches are still durable jobs. Their confirmed tool
result now includes `jobHref` (the job's in-app link) and the confirm response's
`href` points at the job.
Scheduled task notifications now use core `QAlerts.notify`; they reach whatever
alerts sink the host installed (or core's logging sink when none is).
## Provider setup state (Unreleased)
Apply the **Provider setup state** block at the end of `docs/schema-postgres.sql`
**before** deploying: the provider table now reads `setup_state`, so the new jar
fails on `assistant_provider` without it. It adds a nullable `VARCHAR(16)` with
default `'ACTIVE'` and a check for `ACTIVE` / `SETTING_UP`; existing rows behave as
before. It is `IF NOT EXISTS` and safe to re-run.
To stop an unfinished provider from being routed to or health-checked, edit it in
Assistant > Assistant Provider (Provider section) and set **Setup state** to **Setting up** (SQL:
`UPDATE assistant_provider SET setup_state = 'SETTING_UP' WHERE id = <id>;`).
Enabled providers that are neither the default nor the only route for a configured
model now report DEGRADED, not DOWN, when unreachable. No configuration change.
## Fail soft (Unreleased, UI API extension assistant 1.5.0)
Apply the **Fail soft** block at the end of `docs/schema-postgres.sql` before
deploying. It creates `assistant_client_error` (errors the panel reports through
`POST /qqq/v1/assistant/client-errors`) with its indexes and `SET NULL` foreign keys
to the conversation, message and turn. It is `IF NOT EXISTS` and safe to re-run.
New configuration, all optional: `toolCallTimeoutSeconds` (default 60),
`clientErrorsPerUserPerMinute` (default 30) and `clientErrorWarnPerHour` (default
20, when the `assistant.client-errors` health check turns degraded). The new table
is in the Assistant app's nav for administrators.
## Transcript redaction (Unreleased)
Apply the transcript-redaction column widening block in `docs/schema-postgres.sql`
to existing databases. Stop reasons, request IDs, tool-call IDs, feedback/data-audit/
budget-override reasons and scheduled-run summaries/errors now use `TEXT`; token
expansion must not fail a write or truncate secured-data tokens. The corresponding
entity field limits are removed, including pending-action and tool-result summaries.
## Foreign keys (2026-10-14)
Recommended: apply the "Foreign keys" block at the end of
`docs/schema-postgres.sql` (after the index audit). It is guarded and safe to re-run.
- Adds the missing foreign keys across the conversation tables, usage, data audit,
budget accounting and profile skills, with the indexes they need.
- Detail rows of a conversation `CASCADE`; the message/turn cycle, usage and the data
audit use `SET NULL`, so usage keeps its cost rows when a conversation is deleted.
- Usage, budget accounting and the data audit hold their provider (`NO ACTION`):
disable a provider with history instead of deleting it.
- `assistant_model.provider_id` changes from `NO ACTION` to `CASCADE`
(constraint renamed `fk_assistant_model_provider`).
- Rows that point at a missing parent are first copied to `qqq_fk_quarantine`
(created if absent), then nulled, or deleted for the `NOT NULL` profile-skill
links. Check that table after the upgrade.
No code change.
## Index audit (2026-10-14)
Recommended, not required: apply the "Index audit" block at the end of
`docs/schema-postgres.sql`. It adds six indexes, every one `IF NOT EXISTS`:
- usage by turn (read on each scheduled run)
- the three retention date filters (turn events, tool calls, inactive conversations)
- the two `ON DELETE SET NULL` foreign keys on `assistant_scheduled_run`
No code change.
## Durable turns (Unreleased)
Apply the **Durable turns** block at the end of `docs/schema-postgres.sql` before
starting the new runtime. It adds nullable `heartbeat_at`, `lease_owner`,
`cancel_requested_at`, `phase`, `concurrency_mode` and the `(user_id, status)`
index. A partial unique index on terminal events also prevents two replicas from
inserting separate `message.end` frames for the same turn. Check for historical
duplicate terminal frames before applying it (resolve any duplicates through your
normal migration process). Fresh installs run the full schema, including ALTERs.
Existing rows with no heartbeat use `started_at` for lease expiry. During the
first upgrade from a runtime without heartbeats, drain old replicas' turns first:
a new replica cannot distinguish an old live turn from a dead owner after 45 s.
Defaults: heartbeat 5 s, lease 45 s, hard duration 300 s, force-finalization grace
20 s, shutdown grace 8 s. Configure these through the corresponding
`AssistantQBitConfig` withers. Heartbeat must be shorter than the lease. The JVM
shutdown hook is enabled by default; tests disable `registerShutdownHook` and
managed hosts may call `runtime.shutdown(Duration)` themselves. Give the process
termination budget enough time for the configured shutdown grace and persistence.
`POST /conversations/{id}/turns` accepts `concurrency: "supersede" | "concurrent"`
(case-insensitive). Default `SUPERSEDE` stops prior runs in that conversation;
`CONCURRENT` permits them. The default per-user cap is now 3; reaching it stops
the oldest run instead of returning the old in-progress 429. Per-minute and
budget 429 responses still apply. Superseded turns record `cancelReason=SUPERSEDED`.
Cancel now returns HTTP **200**, including for terminal turns, with the current
`status`. The OpenAPI fragment retains the old 202 response for mixed-version
rollouts. Active runs are discoverable through `GET /qqq/v1/assistant/turns/active`;
reattach through the existing events route. Consumers should recognize
`turn.phase` and `message.start.startedAt`. Starts during shutdown return
503 `SHUTTING_DOWN`; clients may retry against a ready replica.
`JobTrackingRunTracker` is now the default `AssistantRunTracker`, using core
`JobTracking` in QQQ **4.1.0-RC.8** to publish answers in the Jobs tray. The host
must provide the jobs tables (through qbit-jobs / core `DurableJobsMetaDataProvider`)
and run `DurableJobsRuntime`. Without that runtime, answers complete normally
and are simply not tracked.
Each job is owned by the assistant user, links to its `assistant_conversation`,
and reports thinking, tool and writing phases. Tool progress contains only the
tool label; terminal messages are fixed and never contain prompts or answers.
The tray's Stop cancels the assistant turn. All tracker callbacks remain isolated
from turn execution. Opt out with `withRunTracker(AssistantRunTracker.NOOP)`;
hosts may still supply their own `AssistantRunTracker`.
## Starter defaults, setup card and table help
The jar now ships `db/liquibase/qbit-assistant/assistant-defaults.changelog.sql`.
Include it from the host's master changelog **after** the changesets that create
the `assistant_*` tables:
```yaml
- include: { file: db/liquibase/qbit-assistant/assistant-defaults.changelog.sql }
```
It is insert-only and never changes a host that already configured the
assistant: the policy, the **$50/month instance budget** (warn 80%, downgrade
100%, stop 120%) and the Anthropic list prices are seeded only into empty tables,
and the `default` profile only when no default profile exists. Price rows take
precedence over `AssistantQBitConfig.withPricing`, which is why they are seeded
only when there are none. The four starter skills and a disabled example
scheduled task are always added (by name); on a host with its own default
profile the skills are not linked to it, and the Setup card says so. Requires
Liquibase 4.x or later (preconditions are `sql-check`s).
No DDL changes. New: the Assistant home's Setup card, the `assistant_data_access`
table action **Add rows for every table** (`assistantDataAccessAddDefaults`,
admin only) and bundle help on every assistant table (`help/qbit-assistant.yaml`).
## X1/Y1: channel wall and audit attribution
Requires QQQ 4.1.0-RC.6. Every assistant table, process, report and widget is
explicitly denied to channel `assistant`; startup rejects an exposed object.
Host customizations must preserve these denials. Administration uses `next-ui`.
Before enabling `AuditsMetaDataProvider.withClientChannelField(true)`, add the
nullable `audit.client_channel VARCHAR(100)` column using the host migration
conventions. kof22 needs a feature changeset under `changesets/features/` (for
example `2026-10-14-audit-client-channel.sql`); no host migration is applied here.
Existing audit rows remain null. The test fixture enables the field.
The existing `assistant_tool_call.auditHref` column now points to audit rows
filtered by record, table and client channel, including for deletes. It is empty
when the host has not enabled the audit channel field. Apply the X1/Y1 DDL in
`docs/schema-postgres.sql` to widen the existing `assistant_tool_call.audit_href`
column to TEXT: encoded filters with long table names or string record ids can
exceed the old 500-character limit. No new QBit column is required. `GET /assistant/access` accepts an optional owned `turnId` for attribution.
## Provider API extraction (#30)
**BREAKING:** every provider API type now lives in the exclusive package
`com.kingsrook.qbits.assistant.spi`. Update imports and recompile consumers.
Hosts still receive `qbit-assistant-provider-api` transitively from `qbit-assistant`.
No schema migration is needed.
| Old import | New import |
|---|---|
| `com.kingsrook.qbits.assistant.provider.X` (API types) | `com.kingsrook.qbits.assistant.spi.X` |
| `com.kingsrook.qbits.assistant.engine.ModelPricing` | `com.kingsrook.qbits.assistant.spi.ModelPricing` |
Internal classes such as `provider.RegistryModelProvider` and
`provider.fake.ScriptedModelProvider` stay in the runtime and are not API types.
External consumers such as qbit-marketing depend only on
`com.kingsrook.qbits:qbit-assistant-provider-api` for these contracts and allow
package `com.kingsrook.qbits.assistant.spi` in their guardrails. qbit-bom will add
this package to the G1 defaults.
External providers and applications using only provider/pricing types should
replace their `qbit-assistant` dependency with
`com.kingsrook.qbits:qbit-assistant-provider-api` at the same version. This removes
the assistant runtime and QQQ from that dependency path; only Jackson annotations
are required by the API. Anthropic, OpenAI, Bedrock and Vertex adapters use this
split; pgvector retains `qbit-assistant` for its runtime RAG interfaces.
Recompile custom provider types that override `validate(AssistantProvider)` and
change the signature to `validate(ProviderSettings)`. The settings carry the
configured kind, URL, API version, region, project, CA bundle name, timeouts and
`apiKeyEnvName`; the key and bearer-token supplier are not resolved for validation.
Providers using the default validator need only the import migration. Keep the runtime and
provider artifacts on the same version; old validator overrides must be rebuilt.
## P-g: scheduled tasks
Apply the **P-g** DDL in [docs/schema-postgres.sql](docs/schema-postgres.sql)
before deploying. The unique `(task_id, scheduled_for)` constraint is required
for multi-replica safety; retain run rows as schedule-slot claim history.
Existing conversations default to channel `panel`. Tasks start disabled.
Set `withScheduledTasksSchedulerName(...)` to an existing QQQ scheduler and
configure `withUiApiBaseUrl(...)` with this replica's own listener URL. The runner
polls every 60 seconds. QQQ must supply a scheduler session able to manage the
assistant tables; this QBit never creates that session. The configured backend
must enforce unique keys atomically (Postgres does).
Allow only designated credential references with
`withAllowedScheduledCredentialEnvNames(Set.of("ASSISTANT_SCHEDULED_TOKEN"))`.
Provide that variable through the host's secret manager. It must hold a token
accepted by the host's `manageSession` authentication provider for `runAsUserId`.
The runner fails closed on missing/disallowed credentials or an identity mismatch.
See [scheduled-task setup](README.md#scheduled-tasks) for kof22 provisioning.
QQQ RC.5 has no conditional UpdateInput. The runner uses a database-unique
schedule-slot insertion as its optimistic claim, then advances `nextRunAt`
before starting work. Crashes can skip a slot; they never retry it. No ArchUnit
exception or fabricated session is introduced. Core RC.6 enforces client-channel denials; scheduled requests carry
`assistant/scheduled/<taskId>`.
Notifications use the optional Alerts QBit notification SPI with a single-user
audience. Without it, delivery logs run id/status only. All output modes retain
the owner-locked audit row and conversation. HIPAA run summaries never copy the
answer; they contain only `see conversation`.
## P-f: knowledge retrieval
Apply the **P-f** assistant-table DDL in
[docs/schema-postgres.sql](docs/schema-postgres.sql) before deployment. It adds
`assistant_model.model_kind` (existing rows default to CHAT),
`embedding_dimensions`, and the admin-only `assistant_rag_source` table.
No sources are seeded. Existing chat selections remain unchanged; explicitly
EMBEDDING models are excluded from chat, classifier, fallback and downgrade
selection. Correct discovery's kind/dimensions if a model name is ambiguous.
For persistent vectors, add `qbit-assistant-rag-pgvector` at the same version as
the QBit, supply the host's JDBC DataSource/driver, and install pgvector in the
database. A DBA runs `CREATE EXTENSION IF NOT EXISTS vector`; the application
role needs schema creation rights for initial setup (or a DBA-created schema),
then normal DML rights. `ensureSchema()` checks for an existing extension first
and does not require extension installation privileges when it is already present.
The optional pgvector DDL is a **commented reference block**, separate from the
assistant-table migration. See [RAG setup](README.md#rag-setup).
Use a distinct validated schema for each QQQ instance. `vector(N)` fixes dimensions
for that store; changing dimensions requires a new schema and re-indexing.
Sources can use different models with that dimension; ranking is restricted to
sources using the query's model. If the weights behind an unchanged model id
change, clear and rebuild its sources. Editing source chunk/filter/model settings
or registry model identity/dimensions automatically clears affected vectors.
Every indexing batch produces EMBED usage and updates existing budget rollups.
PHI source content and PHI conversation queries require a HIPAA-eligible embedding
provider. No background runner or designated credentials are installed in P-f.
The default in-memory store is lost on restart and must be indexed again.
## P-e: profile routing and provider fallback
Apply the additive **P-e** ALTER TABLE statements at the end of
[docs/schema-postgres.sql](docs/schema-postgres.sql) before deploying. Existing
profiles default to OFF; optional model references and health columns start null.
No routing or fallback configuration is seeded. Existing turns retain unknown
routing/final-provider values; fallback_count defaults to zero.
Profiles now have a **Model routing** section. Select HEURISTIC or CLASSIFIER,
then optional simple/complex registry models and a classifier model. Empty route
slots retain provider/policy selection. CLASSIFIER with no usable classifier
uses HEURISTIC. OFF preserves prior provider selection. With no effective profile,
code-configured escalation supplies the complex model/effort when enabled.
Set a model's **Fallback model** to opt into a cross-provider chain. Saves reject
cycles, more than four edges, or disabled/missing targets. Provider health is
read-only; NETWORK/TIMEOUT opens a 60-second circuit, and successful calls close
it. Local endpoints with stale health get a bounded two-second probe. Automatic
fallback without an explicit link is confined to local models of the same adapter
family. PHI/HIPAA eligibility and budgets apply to every destination.
Classifier usage is recorded with purpose ROUTE and included in budgets. Reports
that filter usage purpose should include ROUTE. Turn screens show route decision,
source, fallback count and final provider; the home shows health and fallback totals.
All configuration remains assistant.admin-only, with AI exposure NONE.
## P-d: data-driven budgets
Requires QQQ 4.1.0-RC.5 for the core Alerts API and alert type metadata.
Create `assistant_budget`, `assistant_budget_override`, `assistant_budget_event`
and `assistant_budget_usage`
using the P-d DDL in [schema-postgres.sql](docs/schema-postgres.sql) before deploying.
The event unique key is required: it deduplicates each state per budget, scope and
UTC period across replicas. Do not remove it or truncate events during a period.
Budgets appear in Assistant navigation. Overrides and immutable events are child
lists. All four tables require `assistant.admin` and have AI exposure NONE.
Overrides record the actual session grantor and require a reason and expiry.
The standard host QQQ audit configuration applies to budget and override edits.
`assistant_budget_usage` is a private accounting projection populated from persisted
usage writes. It copies only counters, time, user, provider and model, with no owner
lock, so shared INSTANCE/PROVIDER/MODEL sums can run under the caller's own session.
The source usage table retains its owner locks. The projection is read-only, has no
nav entry and no AI exposure. **Pause usage writes during migration and run the DDL's
backfill before restarting**; otherwise shared totals would omit pre-upgrade usage.
Keep accounting rows through their budget periods even if detail rows are removed.
ROLE budgets give each permission holder a separate allowance, checked with their
current session. Override scopeValue, when set, narrows the allowance to one user id.
Existing policy/config budgets and provider monthly caps remain additional limits;
an override of a budget row does not waive those existing caps.
Provider and MODEL scope values are numeric provider/model registry row ids;
USER is a user id and ROLE is a permission name. INSTANCE has no scope value.
Periods reset at midnight UTC or the first of the month UTC. Token usage includes
input, output, cache-read and cache-write tokens; USD uses the recorded micro-dollar
cost, not today's model price. No default budget rows are seeded.
## P-c: classification, PHI routing and encrypted storage
Apply these additive schema changes before deploying P-c (adjust column mappings
for your backend). New conversations/turns record `PUBLIC`, `CONFIDENTIAL`, `PII`
or `PHI`; legacy null classifications read as PUBLIC. Backfill known historical
PHI conversations to PHI before allowing their history to be used with a provider.
```sql
ALTER TABLE assistant_conversation ADD COLUMN max_classification VARCHAR(16);
ALTER TABLE assistant_turn ADD COLUMN classification VARCHAR(16);
ALTER TABLE assistant_turn ADD COLUMN classification_tables VARCHAR(500);
ALTER TABLE assistant_conversation ALTER COLUMN title TYPE TEXT;
ALTER TABLE assistant_tool_call ALTER COLUMN result_summary TYPE TEXT;
ALTER TABLE assistant_pending_action ALTER COLUMN summary TYPE TEXT;
ALTER TABLE assistant_pending_action ALTER COLUMN result_summary TYPE TEXT;
CREATE TABLE assistant_data_audit
(
id SERIAL PRIMARY KEY,
user_id VARCHAR(255),
conversation_id INTEGER,
turn_id INTEGER,
provider_id INTEGER,
provider_name VARCHAR(200),
model VARCHAR(200),
hipaa_eligible BOOLEAN,
classification VARCHAR(16),
tables VARCHAR(500),
decision VARCHAR(16),
reason VARCHAR(1000),
create_date TIMESTAMP WITH TIME ZONE
);
CREATE INDEX assistant_data_audit_user_id ON assistant_data_audit (user_id);
CREATE INDEX assistant_data_audit_conversation_id ON assistant_data_audit (conversation_id);
CREATE INDEX assistant_data_audit_turn_id ON assistant_data_audit (turn_id);
```
`assistant_data_audit` is an admin read-only, owner-locked child list on a
conversation, outside navigation. It records each model call carrying PII/PHI and
each routing block, without record values. It expires with the conversation.
PHI conversations use `hipaaRetentionDays` (2190 by default), even outside HIPAA
mode; null uses normal retention. Existing tool-result/replay cleanup still uses
`toolResultRetentionDays`.
Before enabling HIPAA mode, mark the permitted provider rows `hipaaEligible = true`
and provision `conversationEncryptionKeyEnvName` with a base64-encoded 32-byte
key. Startup refuses missing or invalid keys. A code-only provider is not eligible.
The flag records the operator's eligibility decision; it does not establish a BAA.
New/updated message parts, titles, conversation context, tool payloads/redactions
and summaries, replay data, and pending-action payloads/summaries use
`enc:v1:<base64(iv|ciphertext|tag)>` (AES-256-GCM, random 12-byte IV, 16-byte tag).
Only `AssistantStore` decrypts; direct backend/admin record views show ciphertext.
String columns holding encrypted summaries/titles must be TEXT to allow expansion.
Legacy plaintext reads are supported; existing rows are not automatically rewritten.
For an existing deployment, migrate legacy payloads through AssistantStore under
the appropriate owner/admin session before treating the whole archive as encrypted.
Keep the key available for the lifetime of encrypted data and backups. Changing the
key requires a controlled decrypt/re-encrypt migration; P-c has no key rotation job.
Corrupt ciphertext, a wrong key, and encrypted data without a key fail closed.
## 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):
@@ -107,3 +526,104 @@ QQQ stores table names, permission names and key names outside this qbit. Update
### 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.
## P-a: provider and model registry
Before starting the new version, database-backed hosts add the provider columns
and model sub-table below. Memory-backed hosts need no migration. Existing rows
derive kind and location from the adapter and keep their model behavior until
models are registered. Keys remain environment-variable references.
```sql
ALTER TABLE assistant_provider
ADD COLUMN kind VARCHAR(30),
ADD COLUMN tls_ca_bundle VARCHAR(100),
ADD COLUMN location VARCHAR(10),
ADD COLUMN hipaa_eligible BOOLEAN DEFAULT FALSE,
ADD COLUMN region VARCHAR(50),
ADD COLUMN api_version VARCHAR(30),
ADD COLUMN connect_timeout_seconds INTEGER DEFAULT 10 CHECK (connect_timeout_seconds BETWEEN 1 AND 600),
ADD COLUMN request_timeout_seconds INTEGER DEFAULT 120 CHECK (request_timeout_seconds BETWEEN 1 AND 600),
ADD COLUMN last_discovery_at TIMESTAMP WITH TIME ZONE,
ADD COLUMN last_discovery_status VARCHAR(16),
ADD COLUMN last_discovery_error VARCHAR(500);
ALTER TABLE assistant_provider ALTER COLUMN model TYPE VARCHAR(200);
ALTER TABLE assistant_provider ALTER COLUMN last_test_model TYPE VARCHAR(200);
ALTER TABLE assistant_usage ALTER COLUMN model TYPE VARCHAR(200);
ALTER TABLE assistant_message ALTER COLUMN model TYPE VARCHAR(200);
ALTER TABLE assistant_turn ALTER COLUMN model TYPE VARCHAR(200);
CREATE TABLE assistant_model
(
id SERIAL PRIMARY KEY,
provider_id INTEGER NOT NULL REFERENCES assistant_provider(id),
model_id VARCHAR(200) NOT NULL,
display_name VARCHAR(200),
enabled BOOLEAN,
supports_tools BOOLEAN,
supports_vision BOOLEAN,
supports_streaming BOOLEAN,
supports_reasoning_effort BOOLEAN,
context_window_tokens INTEGER,
max_output_tokens INTEGER,
input_usd_per_m_tok NUMERIC(12, 4),
output_usd_per_m_tok NUMERIC(12, 4),
source VARCHAR(16),
discovered_at TIMESTAMP WITH TIME ZONE,
last_test_at TIMESTAMP WITH TIME ZONE,
last_test_status VARCHAR(16),
last_test_latency_ms INTEGER,
last_test_error VARCHAR(500),
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE,
UNIQUE (provider_id, model_id)
);
```
Register the optional `qbit-assistant-provider-openai` module and
`OpenAiCompatibleProviderType` to offer its kinds. Azure and generic endpoints
require an explicit `allowedBaseUrls` entry; local defaults may be keyless.
Discover models preserves existing rows. Cloud catalogs larger than 20 are added
disabled; enable the models to offer before leaving the provider's model empty.
HIPAA eligibility records an administrator's fact; P-a does not implement PHI routing.
Custom CA bundles are server configuration, never database content. Register them
with `withTrustedCaBundle(name, pem)` or `withTrustedCaBundleFile(name, path)` at
startup, then set the HTTPS provider row's `tlsCaBundle` to that name. Empty
references retain JVM default trust. The bundle adds trust without replacing JVM
roots; hostname verification remains enabled. If the P-a columns were already
applied, add only `tls_ca_bundle VARCHAR(100)` to `assistant_provider`.
## P-b: AWS Bedrock and Google Vertex
Before starting this version, database-backed hosts that already applied P-a add:
```sql
ALTER TABLE assistant_provider ADD COLUMN cloud_project VARCHAR(100);
```
Fresh installations use `docs/schema-postgres.sql`; memory-backed hosts need no
migration. Existing providers leave the new column null. Vertex requires the GCP
project id in `cloudProject`; Bedrock and Vertex both require `region` and reject
`apiKeyEnvName`. They default to CLOUD; `hipaaEligible` remains a manual admin fact.
Add the optional `qbit-assistant-provider-bedrock` and/or
`qbit-assistant-provider-vertex` module at the QBit version and register
`BedrockProviderType` / `VertexProviderType`. Credentials come from the server's
AWS default chain / Google Application Default Credentials. No credentials are
stored in provider rows. Hosts using AWS IRSA or web identity supply
`software.amazon.awssdk:sts` on their own runtime classpath (matching the
transitive AWS SDK version); this QBit does not add it. See README Providers for
configuration, endpoint overrides and static discovery limitations.
+592 -1
View File
@@ -16,6 +16,13 @@ All of it is in standard QQQ tables with full record screens (D6), prefixed `ass
`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.
## Provider SPI boundary
All provider contracts and value types, including `ModelPricing`, belong exclusively
to `com.kingsrook.qbits.assistant.spi` in `qbit-assistant-provider-api`. Consumers
can depend on this artifact alone and allow its package in G1. Runtime provider
registry and fake implementations remain in their existing internal packages.
## 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.
@@ -59,7 +66,7 @@ The result goes on the row (`lastTest*`) and into `assistant_usage` (`TEST`), so
## Cost
`cost = input × in + output × out + cacheRead × read + cacheWrite5m × w5 + cacheWrite1h × w1`, in micro-dollars, rounded up (`ModelPricing.costMicros`).
`cost = input × in + output × out + cacheRead × read + cacheWrite5m × w5 + cacheWrite1h × w1`, in micro-dollars, rounded up (`com.kingsrook.qbits.assistant.spi.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.
@@ -75,3 +82,587 @@ One HTML widget (`assistantHome`) on the Assistant app. It is the only place thi
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 (built per user from the tables the user can read; configured ones need a `[table]` tag, see UPGRADE.md).
- **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).
- `CoreUiApiGateway` adapts core's `UiApiInvoker` (the loopback stand-in is deleted). It labels calls with the client channel `assistant`, plus the turn id as detail (`assistant/<turnId>`). Form params go to the invoker's `withFormParam`; extra headers (the bulk-load tools' `X-QQQ-AI-Route`) go through `HeaderedUiApiInvoker`, a small subclass in core's package because core's request has no `withHeader` yet. A host can still inject its own gateway with `withUiApiGateway`.
- 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.
## Spec'd assistant endpoints and the core invoker (phase d, QQQ 4.1.0-RC.6)
- **The endpoints are spec'd `/qqq/v1` operations.** `api/specs/AssistantSpecs` registers the UI API extension `assistant` (semver 1.0.0, established prefix `/assistant`) through `MiddlewareSpecExtensionsMetaData`.
- The URLs, bodies and statuses stay the same (201 create, 202 cancel, 204 delete and feedback, and the assistant's `{"error","code"}` errors), so Next needs no change.
- They appear in the served `/qqq/v1/openapi.yaml`. The turn and events streams are declared as `text/event-stream`, with `AssistantTurnEventV1` describing the events.
- The fragment is committed as `qbit-assistant/src/main/resources/openapi/qqq-v1/assistant.yaml`. `AssistantSpecsContractTest` checks it against the code, and the release baseline in test resources, with core's `UiApiContract`.
- **No raw routes.** `AssistantRouteProvider` keeps only a before-handler that learns the server's local port from the first `/qqq/v1` request.
- **Tools call core's `UiApiInvoker`** (`CoreUiApiGateway`), and the loopback stand-in is removed.
- The request's credentials (`UiApiCredentials.fromContext`: session cookies, Authorization, API key, exactly as they came in) are captured by the spec that starts the turn, confirms an action or explains access. They are passed to the tools, so OAuth2, table auth and API-key sessions all work. They are never logged.
- The gateway also refuses the assistant's own operations, so a turn can never start a turn.
- QQQ 4.1.0-RC.6 (the default `qqq.snapshot.version`) contains #1128, so no local build is needed.
## 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.
### X1/Y1 as built
- Record history is an explicit, default-off host opt-in (`withRecordHistory(true)`); kof22 does not opt in. RC.6 removes only `audit*`; later core #1193 support allows audit reads with a write-only denial. Other walls and user audit permissions remain intact.
- RC.6's invoker fixes the `assistant` channel server-side and ignores spoofed client headers. Turn context survives knowledge discovery, RAG reads, confirm actions and owned-turn explain-access; scheduled calls retain `scheduled/<taskId>`.
- The producer enumerates assistant tables, processes, reports and widgets (including source-QBit metadata), adds explicit denied-client rules without replacing user permissions, and registers `assistant_*` idempotently. Runtime construction independently validates the wall with core's `isDenied` and fails on exposed objects.
- The fixture enables core's audit channel field. Hosts must migrate the nullable audit column before enabling it; kof22 needs its own feature changeset.
- Successful insert/update/delete tool calls link to `/app/audit` with `recordId`, `auditTable.name` and `clientChannel` criteria, using the same encoder as `present_results`. Hosts without the channel field get no audit link. Existing audit link storage widens to TEXT for long encoded filters.
- HTTP tests enumerate the configuration denial matrix for an admin, contrast Next UI access, reject broken startup metadata, and verify confirmed-write actor/channel plus the decoded audit filter.
### 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.
### P-a as built
- Per-provider `tlsCaBundle` references startup-parsed, transient server CA bundles. OpenAI-compatible chat, health and discovery trust JVM roots plus the bundle, retain hostname verification, and report sanitized NETWORK errors with a trust hint.
- `assistant_provider` records kind, location, HIPAA eligibility, region, API
version, timeouts and discovery status. `assistant_model` is its admin-only
child list: enablement, capabilities, prices and test status, unique per provider/model.
- `ProviderSettings`, discovery and health extend the provider SPI through default
methods. Legacy `create(apiKey, baseUrl)` implementations keep working.
- The OpenAI-compatible module uses JDK HTTP and Jackson, Chat Completions with
SSE or single JSON replies, Azure deployment URLs and api-key auth, and keyless
local endpoints. Keys and URL overrides pass the existing allowlists first.
- Strict tools require explicit opt-in, OpenAI or Azure, and recursively strict
object schemas. A strict/schema/grammar 400 signals the existing one-retry fallback.
- Discovery only adds missing models; it preserves edits and disables catalogs
larger than 20 for cloud providers. Health uses a short models request. Provider
tests probe health then complete; model tests can probe a disabled model before
enabling it. Completion tests record TEST usage.
- Registry prices and capabilities override adapter/type defaults. Empty provider
model selects the first enabled registry model; an explicitly disabled selection
is a setup error. Rows without models retain the prior behavior.
- Localhost contract tests cover dialects, fragmented parallel tool calls, usage,
errors, timeouts, cancellation, discovery and a golden tool round trip. The live
smoke is environment-driven and excluded by default.
### P-b as built
- Optional Bedrock and Vertex modules reuse the Anthropic mapping and streaming
adapter through an injected SDK client. Bedrock retains SDK SigV4 and binary
event-stream decoding; a small Backend delegate supplies allow-listed endpoints
because SDK 2.71.0 has no Bedrock endpoint setter.
- Bedrock uses the server's AWS default credential chain; IRSA/web-identity hosts
supply STS on their runtime classpath. No STS or control-plane SDK is bundled.
- Vertex uses scoped Google ADC. `claude-*` routes to the Anthropic backend; other
ids route to the OpenAI-compatible endpoint with a per-request token supplier,
`google/` for unprefixed ids, and no strict tools.
- Both types require region, reject key references and default to CLOUD. Vertex
additionally requires `cloudProject` (`cloud_project VARCHAR(100)`); it is part
of resolved settings and the provider cache key. Type hooks own validation.
- Discovery is a static catalog, health is unsupported, and Test connection uses
the existing completion. HIPAA eligibility remains an admin fact, not a BAA.
- Localhost contract tests cover wire paths, authentication, text/tools/usage,
expired-token refresh, errors, allowlists and golden turns for all three routes.
### P-c as built
- The qbit classification stand-in is gone: the levels are core's `actions.ai.DataClassification` (QQQ 4.1.0-RC.6, core #1142).
The default `ClassificationSource` reads core metadata (`AiDataClassifications`, `AiTableMetaData`, `AiFieldMetaData`) merged with the configured table/field map; configuration wins when both are set. Hosts can still supply their own source with `withClassificationSource`.
- Turn/page/tool classification is monotonic, persisted on the turn and retained
on the conversation. Field subsets use overrides; unknown cross-table results
conservatively use the highest configured level. Metadata tools stay PUBLIC.
- Small engine hooks check a fresh provider row before every model dispatch,
including strict retries. PHI requires explicit row eligibility; HIPAA mode
requires it for all calls. Blocks withhold results, explain the rule without
values, and write an audit. `ProviderService.eligibleAlternative` is an empty
seam for P-e; P-c never changes providers automatically.
- HIPAA mode refuses non-eligible settings/selection and requires a valid key
reference at startup. AssistantStore alone encrypts/decrypts conversation
payloads using AES-256-GCM; legacy plaintext reads remain supported and corrupt
ciphertext fails closed. No key is persisted. Provider diagnostic text is
suppressed in HIPAA logs and turn errors.
- Admin read-only, owner-locked `assistant_data_audit` records each PII/PHI model
dispatch and each block, outside navigation. PHI conversation retention defaults
to 2190 days in either mode; shorter tool-result/replay cleanup is unchanged.
The app home shows HIPAA mode and PHI retention.
### P-d as built
- ROLE allowances are per permission holder. Shared scopes sum a private immutable
accounting projection of usage counters; owner-locked source rows stay locked.
Migration backfills existing usage before writes resume. No sessions are elevated.
- Standard admin budget rows add daily/monthly cost or token allowances above the
existing config/policy budgets and provider monthly caps. Overrides carry a
reason, session grantor and expiry; they never waive the other limit layers.
- Start-turn checks use the existing 429 BUDGET path through PolicyService.
Every dispatch, including strict retries, evaluates current usage and overrides.
Events deduplicate WARNED, DOWNGRADED and STOPPED.
- QQQ RC.5 core QAlerts sends budget signals alongside panel notices, with three
admin-visible alert types and a default logging sink. Resolution awaits active
alert/recurrence tracking so overrides cannot clear shared alerts incorrectly.
- Explicit registry model selection leaves provider defaults untouched. Automatic
downgrades prefer LOCAL, then price. PHI eligibility and destination provider caps
still apply; a missing eligible target stops the turn.
- The home owns the budget cards and 30-day cost/token bars, with user, model,
provider and tool breakdowns, inherited colors and empty states.
### P-e as built
- Profiles select OFF (the migration default), HEURISTIC or CLASSIFIER and optional
simple/complex/classifier registry models. Selection uses ProfileService's existing
specificity. Without a profile, enabled escalation config supplies the complex
model and effort. Empty slots retain provider row/default/policy selection.
- The documented heuristic is a pure rule table: >600 characters, two distinct app
table names, complexity keywords, pending write context, >8 previous turns or a
previous tool limit. This branch has no conversation write-mode field.
- Classifier transport is non-streaming, bounded to four output tokens/three seconds,
and contains only the fixed instruction and user question. PHI guards apply before
dispatch. Errors/unexpected replies use the heuristic. ROUTE usage enters budget
accounting; normal dispatch budgets may override the selected route.
- FallbackChain follows at most four edges on retryable failures, only before any
text/tool start of that call. Candidates are checked for enablement, health,
PHI/HIPAA eligibility and budgets. Without explicit links only the same LOCAL
adapter family is considered. Provider switches rebuild neutral messages and
discard providerState; failed attempts remain visible in usage.
- ProviderHealth persists UP/DOWN, checked-at and a 60-second connection-failure
circuit. Local stale/unknown health uses a bounded two-second probe. Successful
completions close the breaker. Turn rows persist route/source, fallback count and
final provider/model; notices name only the unavailable and answering providers.
- Admin record screens, additive Postgres DDL and the flow-layout home expose these
settings and counters without granting AI access to assistant configuration.
### P-f as built
- `AssistantModelProvider.embed` is optional and unsupported by default. The
OpenAI-compatible implementation shares chat's JDK HTTP authentication, TLS,
Azure deployment paths, timeout and sanitized error mapping. A request accepts
1–64 inputs; `EmbeddingService` batches larger jobs and records each call as
EMBED, including daily rollups and provider/model budget accounting.
- Registry rows have CHAT/EMBEDDING kinds and embedding dimensions. Legacy rows
remain CHAT. Discovery suggests EMBEDDING for ids containing embed, bge, e5,
gte or nomic; administrators can correct it. Chat routing/fallback/downgrades
cannot select an embedding model. Embedding resolution is explicit and checks
fresh provider enablement and HIPAA eligibility before dispatch.
- `assistant_rag_source` is an admin-only navigation table. Its text fields must
exist and allow VALUES/MASKED exposure; application data access must allow READ.
Index now and Clear index are standard streamed ETL record actions with Review
and Result, never navigation entries. Indexing pages the UI API as the clicking
admin, reuses get_record's masking path, chunks deterministically and compares
hashes. Complete scans alone prune disappeared records; per-record replacement
also removes obsolete field chunks. Configuration/model identity changes clear
stale vectors. No source text is saved on a source or vector row.
- `VectorStore` supplies upsert/delete/search/count plus content-free chunk
reconciliation and atomic record replacement. The in-memory implementation uses
exact cosine; the optional pgvector module uses host JDBC, a validated instance
schema, bound values and an HNSW cosine index. Sources from other embedding
models are excluded before ranking. The DBA installs pgvector; existing
installations do not require extension-installation privileges on startup.
- `KnowledgeTool` is separate from the unchanged `UiApiToolbox`. A small
ContextBuilder hook adds it only for an enabled source, policy permission and
UI-readable source table. Search embeds the question, requests 4× the result
limit, then re-reads each hit through get_record with the asking user's session.
403/404 hits contribute only to the filtered count. Safe current values produce
snippets and `/app` citations; record refs propagate touched tables into P-c
classification and the normal tool-call log. The citation instruction is in
the static rules block. The result limit is capped at eight.
- PHI source content and PHI conversation queries only reach eligible embedding
providers. Embedding budgets, kill switch and provider concurrency checks apply
to each batch. A budget downgrade into another vector space stops embedding.
- Tests exercise real fixture UI API reads, denials, record locks, field masking,
PHI refusal, classification, reconciliation, embedding wire contracts and a
golden cited answer. JDBC shape/transaction tests always run; a pgvector:pg16
Testcontainers test skips on hosts without Docker.
- P-g may invoke the manual service within a designated user's authenticated
context. P-f supplies no scheduled runner or stored/elevated session. Multiple
replicas should serialize manual re-indexing of a source at the host level;
per-record pgvector replacement is transactional, while scan reconciliation is
not a snapshot of concurrently changing application data.
### P-g as built
- `assistant_scheduled_task` is admin-only, AI exposure NONE, and appears as
Scheduled tasks. The owner-locked, read-only `assistant_scheduled_run` child
list retains run status, accounting and a bounded summary. Conversations gain
read-only `scheduledTaskId` and `channel` (`panel` or `assistant/scheduled`).
Task and run timestamps use the runtime clock; cron uses Quartz and a validated
ZoneId, including DST. Enablement and schedule edits recompute `nextRunAt`.
- Credentials are references, never stored tokens. `credentialEnvName` must
match `[A-Z_][A-Z0-9_]*` and the dedicated
`allowedScheduledCredentialEnvNames` allowlist. The existing secret resolver
supplies its value. Read-only `credentialStatus` reports presence without
exposing token characters and is stripped on every save.
- A run sends JSON `{accessToken: ...}` to the same loopback base URL's
`POST /qqq/v1/manageSession`. RC.5 with HTTP-only cookies returns the UUID in
`Set-Cookie: sessionUUID`; legacy JSON `uuid` is also accepted. Only then does
the runner resolve that UUID through the host authentication module, exactly
the UUID lookup used by the UI request pipeline. No direct token authentication,
automated-user session or constructed QSession exists in assistant code.
The resolved user id must equal `runAsUserId` before any model call. MOCK in
the integration fixture maps test tokens to the existing user-prefix sessions;
that token adapter is test code only.
- kof22 provisions an Authentik designated account with normal QQQ permissions
and injects an accepted long-lived token through its secret manager and
ExternalSecret into an allow-listed environment variable. The task holds the
variable name and QQQ user id. Host authentication must accept that token type
as `accessToken`; an Authentik management API token is not automatically an
application access token. Neither account nor credential is provisioned here.
- `assistantScheduledTasksRunner` registers a 60-second QScheduleMetaData when
`scheduledTasksSchedulerName` names a host scheduler. QQQ supplies its normal
scheduler context for assistant-table bookkeeping; no ArchUnit exception is
necessary. Configure `uiApiBaseUrl` at startup. No browser visit is required.
- **Claim compatibility:** RC.5 UpdateInput cannot express a conditional
`WHERE next_run_at = expected`. AssistantStore therefore claims the expected
schedule slot using the database-enforced unique `(taskId, scheduledFor)` run
key and advances `nextRunAt` before login/dispatch. This is a unique-insert
optimistic claim rather than a conditional update. The memory fixture also
serializes claim operations on its instance. The database constraint, not
that monitor, prevents cross-replica duplicate execution. Do not remove claim
history or deploy to a backend without atomic unique keys. A crash can lose a
run; it never retries a claimed slot. A later tick advances an already-claimed
slot left behind by a crash between claim and schedule update.
- The unchanged AssistantApi starts a new normal turn under the logged-in
designated user, preserving start gates, rate limiting, P-c classification,
P-d budgets and P-e routing/fallback. An internal context supplies the task's
selected profile and additional cost cap. Cost includes chat, classifier,
failed calls and knowledge-query embeddings. STOP is checked at dispatch
boundaries; an in-flight call can exceed the cap, and no next call is sent.
- Every scheduled UI API request, including metadata and knowledge retrieval,
carries `X-QQQ-Client: assistant/scheduled/<taskId>`. The only uiapi change is
additive `LoopbackUiApiGateway.invokeWithClient`; custom gateways currently
fail closed for scheduled requests because their channel contract is unknown.
Tool-call rows also record `clientChannel`. Core channel deny enforcement
remains pending the client-channel RC; existing AI exposure/data-access
restrictions continue to apply on RC.5.
- Approve write mode, Revoke write mode and Run now are admin record actions
using standard streamed ETL Review/Result. Review shows the exact prompt's
SHA-256 and run-as user. Result rereads and compares the complete reviewed
definition before recording the actual administrator's user id and time.
A persisted approval hash additionally binds prompt, run-as user, credential
reference, profile and requested mode. Editing any of these clears approval;
ordinary saves cannot set approval or computed bookkeeping fields.
- This base has create/update/delete tools, but no W1 conversation mode/policy
switch. Scheduled runs explicitly narrow the existing tool policy: write tools
require both request and matching approval, a READ_WRITE table and the policy's
allowed-tools list. All scheduled writes require panel confirmation, including
when normal policy allows immediate writes. A pending proposal adds a waiting
notice to the run summary; the scheduler never confirms it.
- RECORD keeps the run and conversation; NOTIFICATION and BOTH also submit an
Alerts notification with `NotificationAudience.user(runAsUserId)` and an
`/app/...` conversation link. Reflection targets the installed Alerts QBit's
RC.5 notification SPI/sink, following WebhooksAlerts' optional-dependency
pattern. Without it, a log contains run id and status only. Notification text
contains no answer data. In HIPAA mode run summaries contain exactly
`see conversation`; conversation payloads retain the existing encryption.
The existing record URL is an admin-screen link. Non-admin owners can read
their scheduled conversations in the panel's conversation list; opening a
particular existing conversation from a notification still needs a frontend
deep-link contract (the current panel only supports open/new-prompt links).
This phase does not broaden existing conversation record-screen permissions.
- Failures close the run as FAILED or BLOCKED with sanitized errors and wait
until the next schedule. All output modes retain their audit record. Tests
exercise real manageSession and UI API requests with a fixed clock, designated
permissions and owner locks, headers, competing runners, approval invalidation,
notification modes, PHI refusal, encrypted HIPAA storage and cost STOP.
### 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.
## Answer presentation (owner priority 2026-10-13)
`present_results` is always offered and reads no records. It takes a direct answer,
metrics, a table, an optional table-derived chart, filtered list links, record links
and next-step actions. The server validates metadata and the user's UI API table
visibility once per turn, formats values using QQQ field types/display formats,
computes percentages and builds every `/app` href. Unknown or denied items are
dropped with an explanation. The assistant must still retrieve every fact through
data tools before presenting it.
The [presentation part and SSE contract](answer-presentation.md) defines `summary`,
`blocks` and the complete server-built GFM `markdown` fallback. Each successful
call emits `presentation` with `{messageId, part}` and persists that part; the tool
response tells the model not to repeat its tables or links. Audit rows contain
only accepted presentation data. Normal record-data retention removes these parts.
The built-in Presentation skill is compact static prompt text in the cached rules
block. It asks for a one-sentence answer first, metrics for single numbers, tables
for breakdowns/comparisons, charts for useful shares/trends and actual filter links
whenever offering a list. Administrator profile skills append after it as before
and extend it; there is no replacement boolean or extra permission surface.
The owner's one-line table was a frontend parsing defect: Next's `AssistantMarkdown`
used react-markdown without `remark-gfm`, so table lines became a paragraph.
The renderer fix belongs to `qqq-frontend-next`; this worktree preserves real
newlines and provides structured blocks plus a proper multi-line GFM fallback.
The frontend change is maintained separately and is not verified by this build.
The shared golden task asks "How many images do I have by type?": five UI count
calls establish 81 JPEG, 20 PNG and zero other configured types, then a presentation
with two rows, 80.2%/19.8% shares, two pie points and working MIME filter links.
The same task is included in the opt-in `live` Anthropic eval suite.
## Transcript redaction (secured data §15)
`TranscriptRedactor` collects classified values from tools using `ClassificationSource`,
including core table/field metadata. Stored record fields use
`ClassifiedValueTokens.forRecordField`; criteria/proposals without a record use
`forContext`. Core selects `shred:v1`, `hmac:v1`, or `changed:v1`. Knowledge snippets
retain their source field's token. Matching is case-sensitive and includes canonical,
displayed, escaped, encoded and explicitly truncated variants.
`AssistantStore` stages content in turn memory and writes placeholders until
finalization, protecting backend writes and their audits. It redacts before truncation
and encryption. This covers messages, tool/bulk logs, replay events, pending payloads
and audit reasons; scheduled summaries derive from redacted messages. Model requests
and live SSE remain unchanged under PHI routing. Persisted text deltas are joined
before redaction, with the text in the first delta and remaining deltas empty;
sequence numbers remain stable.
Crashes or unfinished tools at timeout leave placeholders. Proposals remain
non-executable (`PREPARING`) until finalization; redacted proposals are rejected and
must be completed in the application. A core `LogRedactorInterface` hook covers all
threads until the turn and its tool workers finish, then releases the raw values.
History stays redacted; later turns re-read records. Existing transcripts are not
migrated, and arbitrary text is not inferred to be classified without a matching
observed value or classified criterion/field. Canary tests scan every assistant table,
core audits and captured logs, while proving eligible models receive original values.
Requires QQQ 4.1.0-RC.7 (`qqq#1182`); keep the PR draft until publication.
+56
View File
@@ -0,0 +1,56 @@
# Assistant answer presentation contract (v1)
Owner priority (2026-10-13): answers must ALWAYS be easy to read and act on. Bad example the owner saw, rendered on ONE line:
"| Type | Count | |---|---| | JPEG (image/jpeg) | 81 | | PNG (image/png) | 20 | | WebP, GIF, SVG | 0 |" followed by "You can open the lists filtered by JPEG or PNG" with NO links.
Root cause found in Next: `AssistantMarkdown` uses react-markdown WITHOUT `remark-gfm`, so GFM tables are not parsed and the table's lines collapse into one paragraph (soft line breaks). Backend streaming preserves `\n` (events are JSON).
## New message part: `presentation`
An assistant message's `parts` (persisted in `assistant_message.parts_json`, streamed as an SSE event, returned by the conversation API) may contain, besides `text`, `notice`, `tool`/`render` parts etc., ONE part per `present_results` call:
```json
{
"type": "presentation",
"summary": "101 media files are images: 81 JPEG and 20 PNG.",
"markdown": "<server-built GFM fallback of the whole presentation, for clients that do not render blocks (CLI/TUI)>",
"blocks": [
{ "kind": "metrics", "items": [ { "label": "Images", "value": 101, "display": "101", "href": "/app/media?filter=..." } ] },
{ "kind": "table", "title": "Media by type",
"columns": [ { "key": "type", "label": "Type", "align": "left" },
{ "key": "count", "label": "Count", "align": "right" },
{ "key": "share", "label": "Share", "align": "right" } ],
"rows": [ { "cells": { "type": "JPEG (image/jpeg)", "count": 81, "share": 0.802 },
"display": { "type": "JPEG (image/jpeg)", "count": "81", "share": "80.2%" },
"href": "/app/media?filter=..." } ] },
{ "kind": "chart", "chartType": "pie", "title": "Share by type",
"points": [ { "label": "JPEG", "value": 81, "display": "81", "href": "/app/media?filter=..." },
{ "label": "PNG", "value": 20, "display": "20", "href": "/app/media?filter=..." } ] },
{ "kind": "filterLinks", "items": [ { "label": "Open JPEG media (81)", "tableName": "media", "href": "/app/media?filter=..." } ] },
{ "kind": "recordLinks", "items": [ { "label": "Sunset.jpg", "tableName": "media", "recordId": "12", "href": "/app/media/12" } ] },
{ "kind": "actions", "items": [ { "label": "Show the PNG files", "prompt": "Show me the PNG media files" },
{ "label": "Open media", "href": "/app/media" } ] }
]
}
```
Rules:
- `summary` is required, one sentence, the direct answer first.
- `chartType` ∈ `bar`, `pie`, `line`; ≤ 12 points; values are numbers.
- Every `href` is built SERVER-SIDE from metadata and is an `/app` path (same rules as `TurnEngine.isAppHref`). Filtered list links are `/app/<tableName>?filter=<URL-encoded JSON {"criteria":[{"fieldName":..,"operator":..,"values":[..]}],"booleanOperator":"AND"}>`, which Next's `deserializeFilter` accepts (JSON starting with `{`). The model never writes URLs.
- `display` strings are formatted server-side from field metadata (`displayFormat`, e.g. `%,d`, `$%,.2f`; percent columns as `80.2%`); clients show `display` when present, else the raw value.
- `actions` items have either `prompt` (send as the user's next message) or `href` (navigate), never both.
- Unknown `kind`s must be ignored by clients (forward compatible); clients that do not render blocks render `markdown`.
- The SSE event is `presentation` with `{ "messageId": <id>, "part": <the part above> }`; Next's reducer appends it to the assistant message's parts.
## Tool input and implementation
The input schema is [present-results.schema.json](../qbit-assistant/src/main/resources/present-results.schema.json). `table.rowKeys` supplies one raw filter value per row; `table.rowFilter` names the table, field and optional operator (EQUALS by default). Columns receive stable server keys `c0`, `c1`, etc. Input cells remain raw scalars; each row has a parallel display map. The example keys above are illustrative.
`PresentResultsTool` is instantiated per turn. It caches `GET /metaData` with that turn's session, checks table read visibility and instance fields, validates QQQ criteria operators and builds paths using RC.5 `AiLinkBuilder`. Filter links use URL-encoded JSON accepted by Next. Record ids are encoded as opaque path segments. Metadata denial or invalid item drops that item (an invalid table drops its table/chart), with a short explanation to the model; other items survive. No data query or permission elevation happens here.
Limits: summary 300 characters, display text 2,000 characters, table 20 columns/200 rows, chart 12 points, item lists 100 entries, filters 20 criteria/200 values. Chart truncation is reported to the model. Percent columns reference a raw numeric column; a zero total yields 0.0%. Numbers still must originate in earlier data tool results; presentation is formatting, not a new source of facts.
The schema uses small named, nonrecursive definitions to avoid deeply inlined structures. Each object component is at most two levels of inline containers; the resolved table/criteria structure necessarily has the nesting shown in the owner contract. Strict is off by default. Opting `present_results` into strict mode requires all properties (empty arrays/strings, empty table and -1 for unused percentage indexes), removes provider-unsupported length constraints, and retains server validation. This has zero optional parameters and one shared scalar union in the existing strict-budget test.
Presentation parts are persisted with the assistant message and replayed as `presentation` events with `{messageId, part}` (plus the standard event sequence). They are removed by record-data retention along with tool renders. Model history and text-only consumers can use the server-built Markdown. Unknown block kinds should be ignored. Plain labels must be rendered as text, never parsed as links or HTML; fallback Markdown escapes them. Tool audit input records the accepted presentation only, excluding dropped values.
+522 -11
View File
@@ -6,7 +6,8 @@ CREATE TABLE assistant_conversation
(
id SERIAL PRIMARY KEY,
user_id VARCHAR(255),
title VARCHAR(255),
title TEXT,
max_classification VARCHAR(16),
status VARCHAR(16),
pinned BOOLEAN,
last_message_at TIMESTAMP WITH TIME ZONE,
@@ -30,7 +31,7 @@ CREATE TABLE assistant_message
status VARCHAR(16),
turn_id INTEGER,
seq INTEGER,
model VARCHAR(64),
model VARCHAR(200),
parts_json TEXT,
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE
@@ -46,10 +47,12 @@ CREATE TABLE assistant_turn
user_message_id INTEGER,
assistant_message_id INTEGER,
status VARCHAR(16),
stop_reason VARCHAR(64),
classification VARCHAR(16),
classification_tables VARCHAR(500),
stop_reason TEXT,
error_code VARCHAR(32),
cancel_reason VARCHAR(64),
model VARCHAR(64),
model VARCHAR(200),
started_at TIMESTAMP WITH TIME ZONE,
ended_at TIMESTAMP WITH TIME ZONE,
tool_call_count INTEGER,
@@ -85,7 +88,7 @@ CREATE TABLE assistant_tool_call
turn_id INTEGER,
conversation_id INTEGER,
user_id VARCHAR(255),
tool_call_id VARCHAR(128),
tool_call_id TEXT,
tool_name VARCHAR(64),
input_json TEXT,
outcome VARCHAR(16),
@@ -95,9 +98,13 @@ CREATE TABLE assistant_tool_call
widget_name VARCHAR(128),
row_count INTEGER,
duration_ms BIGINT,
result_summary VARCHAR(500),
result_summary TEXT,
result_json TEXT,
redactions_json TEXT,
ui_api_operation VARCHAR(255),
http_status INTEGER,
audit_href TEXT,
pending_action_id INTEGER,
create_date TIMESTAMP WITH TIME ZONE
);
CREATE INDEX assistant_tool_call_user_id ON assistant_tool_call (user_id);
@@ -111,7 +118,7 @@ CREATE TABLE assistant_feedback
conversation_id INTEGER,
user_id VARCHAR(255),
rating INTEGER,
reason VARCHAR(64),
reason TEXT,
comment TEXT,
create_date TIMESTAMP WITH TIME ZONE
);
@@ -134,6 +141,10 @@ CREATE TABLE assistant_policy
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
);
@@ -165,10 +176,22 @@ CREATE TABLE assistant_provider
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE,
provider_type VARCHAR(50) NOT NULL,
model VARCHAR(100),
kind VARCHAR(30),
location VARCHAR(10),
hipaa_eligible BOOLEAN DEFAULT FALSE,
region VARCHAR(50),
cloud_project VARCHAR(100),
api_version VARCHAR(30),
connect_timeout_seconds INTEGER DEFAULT 10 CHECK (connect_timeout_seconds BETWEEN 1 AND 600),
request_timeout_seconds INTEGER DEFAULT 120 CHECK (request_timeout_seconds BETWEEN 1 AND 600),
last_discovery_at TIMESTAMP WITH TIME ZONE,
last_discovery_status VARCHAR(16),
last_discovery_error VARCHAR(500),
model VARCHAR(200),
enabled BOOLEAN,
is_default BOOLEAN,
base_url VARCHAR(255),
tls_ca_bundle VARCHAR(100),
api_key_env_name VARCHAR(100),
api_key_status VARCHAR(200),
monthly_cost_cap_usd NUMERIC(12, 2),
@@ -177,12 +200,38 @@ CREATE TABLE assistant_provider
last_test_at TIMESTAMP WITH TIME ZONE,
last_test_status VARCHAR(16),
last_test_latency_ms INTEGER,
last_test_model VARCHAR(100),
last_test_model VARCHAR(200),
last_test_error VARCHAR(500),
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE
);
CREATE TABLE assistant_model
(
id SERIAL PRIMARY KEY,
provider_id INTEGER NOT NULL REFERENCES assistant_provider(id),
model_id VARCHAR(200) NOT NULL,
display_name VARCHAR(200),
enabled BOOLEAN,
supports_tools BOOLEAN,
supports_vision BOOLEAN,
supports_streaming BOOLEAN,
supports_reasoning_effort BOOLEAN,
context_window_tokens INTEGER,
max_output_tokens INTEGER,
input_usd_per_m_tok NUMERIC(12, 4),
output_usd_per_m_tok NUMERIC(12, 4),
source VARCHAR(16),
discovered_at TIMESTAMP WITH TIME ZONE,
last_test_at TIMESTAMP WITH TIME ZONE,
last_test_status VARCHAR(16),
last_test_latency_ms INTEGER,
last_test_error VARCHAR(500),
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE,
UNIQUE (provider_id, model_id)
);
CREATE TABLE assistant_model_price
(
id SERIAL PRIMARY KEY,
@@ -207,7 +256,7 @@ CREATE TABLE assistant_usage
turn_id INTEGER,
provider_id INTEGER,
provider_type VARCHAR(50),
model VARCHAR(100),
model VARCHAR(200),
purpose VARCHAR(16),
status VARCHAR(16),
error_kind VARCHAR(32),
@@ -218,7 +267,7 @@ CREATE TABLE assistant_usage
cache_read_tokens BIGINT,
cache_write_tokens BIGINT,
cost_micros BIGINT,
request_id VARCHAR(100),
request_id TEXT,
create_date TIMESTAMP WITH TIME ZONE
);
CREATE INDEX assistant_usage_create_date ON assistant_usage (create_date);
@@ -239,3 +288,465 @@ VALUES
('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 TEXT,
tool_name VARCHAR(64),
ui_api_operation VARCHAR(255),
table_name VARCHAR(128),
record_id VARCHAR(128),
params_json TEXT,
summary TEXT,
status VARCHAR(16),
http_status INTEGER,
result_summary TEXT,
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)
);
CREATE TABLE assistant_data_audit
(
id SERIAL PRIMARY KEY,
user_id VARCHAR(255),
conversation_id INTEGER,
turn_id INTEGER,
provider_id INTEGER,
provider_name VARCHAR(200),
model VARCHAR(200),
hipaa_eligible BOOLEAN,
classification VARCHAR(16),
tables VARCHAR(500),
decision VARCHAR(16),
reason TEXT,
create_date TIMESTAMP WITH TIME ZONE
);
CREATE INDEX assistant_data_audit_user_id ON assistant_data_audit (user_id);
CREATE INDEX assistant_data_audit_conversation_id ON assistant_data_audit (conversation_id);
CREATE INDEX assistant_data_audit_turn_id ON assistant_data_audit (turn_id);
-- P-d: data-driven budgets (UTC periods, USD or whole-token allowances).
CREATE TABLE assistant_budget
(
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
scope_type VARCHAR(16) NOT NULL,
scope_value VARCHAR(200),
period VARCHAR(16) NOT NULL,
metric VARCHAR(16) NOT NULL,
limit_value NUMERIC NOT NULL CHECK (limit_value > 0),
warn_percent INTEGER DEFAULT 80 CHECK (warn_percent >= 0 AND warn_percent < 100),
at_limit_action VARCHAR(16) DEFAULT 'DOWNGRADE',
downgrade_model_id INTEGER REFERENCES assistant_model(id),
hard_ceiling_percent INTEGER DEFAULT 120 CHECK (hard_ceiling_percent >= 100),
notes VARCHAR(2000),
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE
);
CREATE TABLE assistant_budget_override
(
id SERIAL PRIMARY KEY,
budget_id INTEGER NOT NULL REFERENCES assistant_budget(id),
scope_value VARCHAR(200),
extra_value NUMERIC,
unlimited_until TIMESTAMP WITH TIME ZONE,
reason TEXT NOT NULL,
granted_by VARCHAR(200),
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE,
CHECK ((extra_value > 0 AND unlimited_until IS NULL) OR (extra_value IS NULL AND unlimited_until IS NOT NULL))
);
CREATE INDEX assistant_budget_override_budget_id ON assistant_budget_override(budget_id);
CREATE TABLE assistant_budget_event
(
id SERIAL PRIMARY KEY,
budget_id INTEGER NOT NULL REFERENCES assistant_budget(id),
scope_key VARCHAR(400) NOT NULL,
period_start TIMESTAMP WITH TIME ZONE NOT NULL,
state VARCHAR(16) NOT NULL,
used_value NUMERIC,
limit_value NUMERIC,
user_id VARCHAR(200),
create_date TIMESTAMP WITH TIME ZONE,
UNIQUE (budget_id, scope_key, period_start, state)
);
CREATE INDEX assistant_usage_budget_period ON assistant_usage(create_date, user_id, provider_id, model);
-- Private projection: standard admin permissions, AI NONE, no owner lock.
-- No conversation identifiers, text, request ids or credentials are copied.
CREATE TABLE assistant_budget_usage
(
id SERIAL PRIMARY KEY,
usage_id INTEGER NOT NULL UNIQUE,
user_id VARCHAR(255),
provider_id INTEGER,
model VARCHAR(200),
occurred_at TIMESTAMP WITH TIME ZONE NOT NULL,
cost_micros BIGINT,
input_tokens BIGINT,
output_tokens BIGINT,
cache_read_tokens BIGINT,
cache_write_tokens BIGINT
);
CREATE INDEX assistant_budget_usage_period ON assistant_budget_usage(occurred_at, provider_id, model);
-- Run once before enabling P-d, with writes paused, to include existing usage.
INSERT INTO assistant_budget_usage
(usage_id, user_id, provider_id, model, occurred_at, cost_micros, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens)
SELECT id, user_id, provider_id, model, create_date, cost_micros, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens
FROM assistant_usage
ON CONFLICT (usage_id) DO NOTHING;
-- P-e: profile routing, bounded fallback chains, provider health and turn outcome.
ALTER TABLE assistant_profile ADD COLUMN routing_mode VARCHAR(16) DEFAULT 'OFF'
CHECK (routing_mode IN ('OFF', 'HEURISTIC', 'CLASSIFIER'));
ALTER TABLE assistant_profile ADD COLUMN simple_model_id INTEGER REFERENCES assistant_model(id);
ALTER TABLE assistant_profile ADD COLUMN complex_model_id INTEGER REFERENCES assistant_model(id);
ALTER TABLE assistant_profile ADD COLUMN classifier_model_id INTEGER REFERENCES assistant_model(id);
ALTER TABLE assistant_model ADD COLUMN fallback_model_id INTEGER REFERENCES assistant_model(id);
ALTER TABLE assistant_provider ADD COLUMN health_state VARCHAR(8) CHECK (health_state IN ('UP', 'DOWN'));
ALTER TABLE assistant_provider ADD COLUMN health_checked_at TIMESTAMP WITH TIME ZONE;
ALTER TABLE assistant_provider ADD COLUMN down_until TIMESTAMP WITH TIME ZONE;
ALTER TABLE assistant_turn ADD COLUMN route_decision VARCHAR(16);
ALTER TABLE assistant_turn ADD COLUMN route_source VARCHAR(16);
ALTER TABLE assistant_turn ADD COLUMN fallback_count INTEGER DEFAULT 0;
ALTER TABLE assistant_turn ADD COLUMN provider_id INTEGER REFERENCES assistant_provider(id);
-- P-f: embedding registry and admin-only knowledge-source configuration.
ALTER TABLE assistant_model ADD COLUMN model_kind VARCHAR(16) DEFAULT 'CHAT'
CHECK (model_kind IN ('CHAT', 'EMBEDDING'));
ALTER TABLE assistant_model ADD COLUMN embedding_dimensions INTEGER
CHECK (embedding_dimensions > 0);
CREATE TABLE assistant_rag_source (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
table_name VARCHAR(200) NOT NULL,
field_names VARCHAR(500) NOT NULL,
title_field_name VARCHAR(200),
filter_json TEXT,
embedding_model_id INTEGER NOT NULL REFERENCES assistant_model(id),
chunk_chars INTEGER DEFAULT 1500 CHECK (chunk_chars BETWEEN 100 AND 16000),
chunk_overlap_chars INTEGER DEFAULT 200 CHECK (chunk_overlap_chars >= 0 AND chunk_overlap_chars < chunk_chars),
last_indexed_at TIMESTAMPTZ,
last_index_status VARCHAR(200),
last_index_error VARCHAR(500),
indexed_record_count INTEGER,
indexed_chunk_count INTEGER,
create_date TIMESTAMPTZ,
modify_date TIMESTAMPTZ
);
-- Optional pgvector part: reference only. Run the extension step as a DBA.
-- PgVectorStore.ensureSchema() performs the remainder for the host's schema/N.
-- Use a distinct schema per QQQ instance; match N to the embedding model.
-- CREATE EXTENSION IF NOT EXISTS vector;
-- CREATE SCHEMA IF NOT EXISTS assistant_rag;
-- CREATE TABLE IF NOT EXISTS assistant_rag.assistant_rag_chunk (
-- id BIGSERIAL PRIMARY KEY,
-- source_id INT NOT NULL,
-- table_name TEXT NOT NULL,
-- record_pk TEXT NOT NULL,
-- field_name TEXT NOT NULL,
-- chunk_index INT NOT NULL,
-- content_hash CHAR(64) NOT NULL,
-- embedding vector(1024) NOT NULL,
-- indexed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- UNIQUE(source_id, table_name, record_pk, field_name, chunk_index)
-- );
-- CREATE INDEX IF NOT EXISTS assistant_rag_chunk_cosine
-- ON assistant_rag.assistant_rag_chunk USING hnsw (embedding vector_cosine_ops);
-- P-g: designated-user scheduled assistant tasks. Install before enabling jobs.
CREATE TABLE assistant_scheduled_task (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT FALSE,
prompt TEXT NOT NULL CHECK (char_length(prompt) BETWEEN 1 AND 4000),
run_as_user_id VARCHAR(200) NOT NULL,
credential_env_name VARCHAR(200) NOT NULL,
credential_status VARCHAR(200), -- computed; always NULL in stored rows
profile_id INTEGER REFERENCES assistant_profile(id),
cron_expression VARCHAR(200) NOT NULL,
timezone VARCHAR(100) NOT NULL DEFAULT 'UTC',
next_run_at TIMESTAMPTZ,
output_mode VARCHAR(20) NOT NULL DEFAULT 'RECORD' CHECK (output_mode IN ('RECORD', 'NOTIFICATION', 'BOTH')),
write_mode_requested BOOLEAN NOT NULL DEFAULT FALSE,
write_mode_approved_by VARCHAR(200),
write_mode_approved_at TIMESTAMPTZ,
write_mode_approval_hash VARCHAR(64),
max_cost_usd_per_run NUMERIC(18,6) CHECK (max_cost_usd_per_run >= 0),
last_run_at TIMESTAMPTZ,
last_run_status VARCHAR(20),
last_run_error VARCHAR(500),
create_date TIMESTAMPTZ,
modify_date TIMESTAMPTZ
);
CREATE INDEX assistant_scheduled_task_due ON assistant_scheduled_task(next_run_at) WHERE enabled;
ALTER TABLE assistant_conversation ADD COLUMN scheduled_task_id INTEGER REFERENCES assistant_scheduled_task(id);
ALTER TABLE assistant_conversation ADD COLUMN channel VARCHAR(64) NOT NULL DEFAULT 'panel';
ALTER TABLE assistant_tool_call ADD COLUMN client_channel VARCHAR(64);
CREATE TABLE assistant_scheduled_run (
id SERIAL PRIMARY KEY,
task_id INTEGER NOT NULL REFERENCES assistant_scheduled_task(id),
user_id VARCHAR(200) NOT NULL,
scheduled_for TIMESTAMPTZ NOT NULL,
started_at TIMESTAMPTZ,
ended_at TIMESTAMPTZ,
status VARCHAR(20) NOT NULL CHECK (status IN ('RUNNING', 'OK', 'FAILED', 'SKIPPED', 'BLOCKED')),
conversation_id INTEGER REFERENCES assistant_conversation(id) ON DELETE SET NULL,
turn_id INTEGER REFERENCES assistant_turn(id) ON DELETE SET NULL,
summary TEXT,
cost_micros BIGINT,
error TEXT,
create_date TIMESTAMPTZ,
modify_date TIMESTAMPTZ,
UNIQUE (task_id, scheduled_for)
);
CREATE INDEX assistant_scheduled_run_owner ON assistant_scheduled_run(user_id, started_at);
-- X1/Y1: encoded audit filters can exceed the old 500-character record links.
ALTER TABLE assistant_tool_call ALTER COLUMN audit_href TYPE TEXT;
-- Durable turns: apply this additive block before deploying the new runtime.
-- Like earlier additions, fresh installs run the CREATEs followed by ALTERs.
ALTER TABLE assistant_turn ADD COLUMN heartbeat_at TIMESTAMP;
ALTER TABLE assistant_turn ADD COLUMN lease_owner VARCHAR(100);
ALTER TABLE assistant_turn ADD COLUMN cancel_requested_at TIMESTAMP;
ALTER TABLE assistant_turn ADD COLUMN phase VARCHAR(64);
ALTER TABLE assistant_turn ADD COLUMN concurrency_mode VARCHAR(16);
CREATE INDEX assistant_turn_user_status ON assistant_turn (user_id, status);
-- Fence concurrent orphan reapers at the database boundary. A turn ends once.
-- Check for pre-existing duplicate message.end rows before applying this index.
CREATE UNIQUE INDEX assistant_turn_event_terminal ON assistant_turn_event (turn_id)
WHERE event_type = 'message.end';
-- Index audit (2026-10-14): lookup, retention and FK paths with no leading index.
-- ScheduledTurn.cost reads usage by turn on every scheduled run.
CREATE INDEX IF NOT EXISTS assistant_usage_turn ON assistant_usage (turn_id);
-- Retention: deleteTurnEventsBefore, clearToolResultsBefore and listConversationsInactiveSince filter by date.
CREATE INDEX IF NOT EXISTS assistant_turn_event_create_date ON assistant_turn_event (create_date);
CREATE INDEX IF NOT EXISTS assistant_tool_call_create_date ON assistant_tool_call (create_date);
CREATE INDEX IF NOT EXISTS assistant_conversation_modify_date ON assistant_conversation (modify_date);
-- ON DELETE SET NULL children: deleting a conversation or turn would scan scheduled runs without these.
CREATE INDEX IF NOT EXISTS assistant_scheduled_run_conversation ON assistant_scheduled_run (conversation_id);
CREATE INDEX IF NOT EXISTS assistant_scheduled_run_turn ON assistant_scheduled_run (turn_id);
-- Foreign keys (2026-10-14). Run on new and existing databases; every step is guarded
-- and re-runnable. The rules follow how the qbit deletes:
-- * AssistantStore.deleteConversation (also the retention purge) deletes turn events,
-- tool calls, feedback, messages, turns, data audit and pending actions, then the
-- conversation. The conversation's own detail rows CASCADE, so an admin delete of a
-- conversation cleans up the same way.
-- * The message <-> turn cycle (turn.user_message_id / assistant_message_id and
-- message.turn_id) and the other optional pointers are SET NULL. Rows are inserted
-- parent first, so nothing is deferred.
-- * assistant_usage keeps its cost rows when a conversation goes (SET NULL), and the
-- data audit trail is never cascaded into (SET NULL).
-- * Provider references from usage, budget accounting and the data audit are NO ACTION
-- (like assistant_turn.provider_id): disable a provider with history, do not delete
-- it. A provider's model rows are its own (CASCADE).
-- * assistant_budget_usage.usage_id has no foreign key on purpose: the projection
-- outlives its usage row so budgets keep counting the spend.
-- Rows that already point at a missing parent are recorded in qqq_fk_quarantine first,
-- then nulled (nullable columns) or deleted with the full row recorded (NOT NULL).
CREATE INDEX IF NOT EXISTS assistant_message_parent_message ON assistant_message (parent_message_id);
CREATE INDEX IF NOT EXISTS assistant_message_turn ON assistant_message (turn_id);
CREATE INDEX IF NOT EXISTS assistant_turn_user_message ON assistant_turn (user_message_id);
CREATE INDEX IF NOT EXISTS assistant_turn_assistant_message ON assistant_turn (assistant_message_id);
CREATE INDEX IF NOT EXISTS assistant_turn_provider ON assistant_turn (provider_id);
CREATE INDEX IF NOT EXISTS assistant_tool_call_pending_action ON assistant_tool_call (pending_action_id);
CREATE INDEX IF NOT EXISTS assistant_feedback_message ON assistant_feedback (message_id);
CREATE INDEX IF NOT EXISTS assistant_pending_action_turn ON assistant_pending_action (turn_id);
CREATE INDEX IF NOT EXISTS assistant_data_audit_provider ON assistant_data_audit (provider_id);
CREATE INDEX IF NOT EXISTS assistant_budget_usage_provider ON assistant_budget_usage (provider_id);
CREATE INDEX IF NOT EXISTS assistant_profile_skill_skill ON assistant_profile_skill (skill_id);
CREATE INDEX IF NOT EXISTS assistant_budget_downgrade_model ON assistant_budget (downgrade_model_id);
CREATE INDEX IF NOT EXISTS assistant_conversation_scheduled_task ON assistant_conversation (scheduled_task_id);
CREATE INDEX IF NOT EXISTS assistant_model_fallback_model ON assistant_model (fallback_model_id);
CREATE INDEX IF NOT EXISTS assistant_profile_simple_model ON assistant_profile (simple_model_id);
CREATE INDEX IF NOT EXISTS assistant_profile_complex_model ON assistant_profile (complex_model_id);
CREATE INDEX IF NOT EXISTS assistant_profile_classifier_model ON assistant_profile (classifier_model_id);
CREATE INDEX IF NOT EXISTS assistant_rag_source_embedding_model ON assistant_rag_source (embedding_model_id);
CREATE INDEX IF NOT EXISTS assistant_scheduled_task_profile ON assistant_scheduled_task (profile_id);
CREATE TABLE IF NOT EXISTS qqq_fk_quarantine (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, table_name VARCHAR(100) NOT NULL, column_name VARCHAR(100) NOT NULL, row_id VARCHAR(100), missing_parent_id VARCHAR(100), action VARCHAR(20) NOT NULL, row_data TEXT, changeset VARCHAR(200), quarantined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
DO $$
DECLARE
r RECORD;
old TEXT;
BEGIN
FOR r IN SELECT * FROM (VALUES
('assistant_message', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
('assistant_message', 'parent_message_id', 'assistant_message', 'SET NULL', TRUE),
('assistant_message', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
('assistant_turn', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
('assistant_turn', 'user_message_id', 'assistant_message', 'SET NULL', TRUE),
('assistant_turn', 'assistant_message_id', 'assistant_message', 'SET NULL', TRUE),
('assistant_turn_event', 'turn_id', 'assistant_turn', 'CASCADE', TRUE),
('assistant_tool_call', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
('assistant_tool_call', 'turn_id', 'assistant_turn', 'CASCADE', TRUE),
('assistant_tool_call', 'pending_action_id', 'assistant_pending_action', 'SET NULL', TRUE),
('assistant_feedback', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
('assistant_feedback', 'message_id', 'assistant_message', 'CASCADE', TRUE),
('assistant_pending_action', 'conversation_id', 'assistant_conversation', 'CASCADE', TRUE),
('assistant_pending_action', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
('assistant_data_audit', 'conversation_id', 'assistant_conversation', 'SET NULL', TRUE),
('assistant_data_audit', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
('assistant_usage', 'conversation_id', 'assistant_conversation', 'SET NULL', TRUE),
('assistant_usage', 'turn_id', 'assistant_turn', 'SET NULL', TRUE),
('assistant_usage', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
('assistant_data_audit', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
('assistant_budget_usage', 'provider_id', 'assistant_provider', 'NO ACTION', TRUE),
('assistant_profile_skill', 'profile_id', 'assistant_profile', 'CASCADE', FALSE),
('assistant_profile_skill', 'skill_id', 'assistant_skill', 'CASCADE', FALSE)
) AS v(child, col, parent, rule, nullable)
LOOP
IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema = current_schema() AND LOWER(constraint_name) = 'fk_' || r.child || '_' || r.col) THEN
IF r.nullable THEN
EXECUTE format('INSERT INTO qqq_fk_quarantine (table_name, column_name, row_id, missing_parent_id, action, changeset) '
|| 'SELECT %L, %L, c.id::text, c.%I::text, ''NULLED'', ''qbit-assistant 2026-10-14 foreign keys'' FROM %I c '
|| 'WHERE c.%I IS NOT NULL AND NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.child, r.col, r.parent, r.col);
EXECUTE format('UPDATE %I c SET %I = NULL WHERE c.%I IS NOT NULL AND NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.parent, r.col);
ELSE
EXECUTE format('INSERT INTO qqq_fk_quarantine (table_name, column_name, row_id, missing_parent_id, action, row_data, changeset) '
|| 'SELECT %L, %L, c.id::text, c.%I::text, ''DELETED'', row_to_json(c)::text, ''qbit-assistant 2026-10-14 foreign keys'' FROM %I c '
|| 'WHERE NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.col, r.col, r.child, r.parent, r.col);
EXECUTE format('DELETE FROM %I c WHERE NOT EXISTS (SELECT 1 FROM %I p WHERE p.id = c.%I)', r.child, r.parent, r.col);
END IF;
EXECUTE format('ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES %I (id) ON DELETE %s', r.child, 'fk_' || r.child || '_' || r.col, r.col, r.parent, r.rule);
END IF;
END LOOP;
-- assistant_model.provider_id: the inline NO ACTION key becomes CASCADE, named as on kof22.
IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE constraint_schema = current_schema() AND LOWER(constraint_name) = 'fk_assistant_model_provider') THEN
FOR old IN SELECT conname FROM pg_constraint
WHERE contype = 'f' AND conrelid = 'assistant_model'::regclass AND confrelid = 'assistant_provider'::regclass
LOOP
EXECUTE format('ALTER TABLE assistant_model DROP CONSTRAINT %I', old);
END LOOP;
ALTER TABLE assistant_model ADD CONSTRAINT fk_assistant_model_provider FOREIGN KEY (provider_id) REFERENCES assistant_provider (id) ON DELETE CASCADE;
END IF;
END $$;
-- Transcript redaction: tokens can expand beyond the original payload bounds.
-- Apply to existing databases as well; SET DATA TYPE is also valid in H2.
ALTER TABLE assistant_turn ALTER COLUMN stop_reason SET DATA TYPE TEXT;
ALTER TABLE assistant_tool_call ALTER COLUMN tool_call_id SET DATA TYPE TEXT;
ALTER TABLE assistant_feedback ALTER COLUMN reason SET DATA TYPE TEXT;
ALTER TABLE assistant_usage ALTER COLUMN request_id SET DATA TYPE TEXT;
ALTER TABLE assistant_pending_action ALTER COLUMN tool_call_id SET DATA TYPE TEXT;
ALTER TABLE assistant_data_audit ALTER COLUMN reason SET DATA TYPE TEXT;
ALTER TABLE assistant_budget_override ALTER COLUMN reason SET DATA TYPE TEXT;
ALTER TABLE assistant_scheduled_run ALTER COLUMN summary SET DATA TYPE TEXT;
ALTER TABLE assistant_scheduled_run ALTER COLUMN error SET DATA TYPE TEXT;
-- Fail soft (UI API extension assistant 1.5.0): errors the panel reports through
-- POST /qqq/v1/assistant/client-errors. Owner-locked like the other user rows; the
-- message and stacks are scrubbed and bounded before they are stored. The ids are
-- kept only when they are the reporting user's own rows, and SET NULL when those go.
-- Retention deletes rows older than toolResultRetentionDays. Safe to re-run.
CREATE TABLE IF NOT EXISTS assistant_client_error
(
id SERIAL PRIMARY KEY,
user_id VARCHAR(255),
scope VARCHAR(64),
message TEXT,
error_name VARCHAR(100),
stack TEXT,
component_stack TEXT,
request_id VARCHAR(128),
route VARCHAR(300),
conversation_id INTEGER CONSTRAINT fk_assistant_client_error_conversation_id REFERENCES assistant_conversation (id) ON DELETE SET NULL,
message_id INTEGER CONSTRAINT fk_assistant_client_error_message_id REFERENCES assistant_message (id) ON DELETE SET NULL,
turn_id INTEGER CONSTRAINT fk_assistant_client_error_turn_id REFERENCES assistant_turn (id) ON DELETE SET NULL,
part_type VARCHAR(64),
render_type VARCHAR(64),
app_version VARCHAR(64),
occurred_at TIMESTAMP WITH TIME ZONE,
create_date TIMESTAMP WITH TIME ZONE
);
CREATE INDEX IF NOT EXISTS assistant_client_error_user_id ON assistant_client_error (user_id);
CREATE INDEX IF NOT EXISTS assistant_client_error_create_date ON assistant_client_error (create_date);
CREATE INDEX IF NOT EXISTS assistant_client_error_conversation ON assistant_client_error (conversation_id);
CREATE INDEX IF NOT EXISTS assistant_client_error_message ON assistant_client_error (message_id);
CREATE INDEX IF NOT EXISTS assistant_client_error_turn ON assistant_client_error (turn_id);
-- Provider setup state: SETTING_UP marks a provider an admin is still building. The
-- assistant never routes to it and its provider and model health checks do not run.
-- Existing rows (and NULL) behave as ACTIVE, exactly as before. Safe to re-run.
ALTER TABLE assistant_provider ADD COLUMN IF NOT EXISTS setup_state VARCHAR(16) DEFAULT 'ACTIVE'
CONSTRAINT ck_assistant_provider_setup_state CHECK (setup_state IN ('ACTIVE', 'SETTING_UP'));
+30
View File
@@ -10,3 +10,33 @@ Light and dark, 390 and 1440 px:
- `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.
Planned P-a provider registry additions, taken against `OpenAiDemoServer` in the
OpenAI provider's test sources with the Next UI **1.0.0-RC.18** jar. See that
[demo's run instructions](../../qbit-assistant-provider-openai/src/test/java/com/kingsrook/qbits/assistant/provider/openai/demo/README.md).
Discovery and connection-test status, TEST usage and the assistant turn are real
executions against the localhost mock; replies/token counts are synthetic, not
live GPU measurements. No screenshots in this group have been added yet.
Light and dark, 390 and 1440 px:
- `p-provider-local-*`: Local GPU (Ollama), keyless LOCAL settings, discovery/test results and discovered models.
- `p-model-*`: a discovered model's capabilities, compute prices and connection-test result.
- `p-home-providers-*`: the home's provider summary and usage from the executed demo calls, including disabled OpenRouter with its key Not set.
Answer presentation (owner priority, 2026-10-13), taken against `OpenAiDemoServer` with the Next UI build of QRun-IO/qqq-frontend-next#111 (`next dev` proxied to the demo). The demo's OpenAI-compatible mock answers "How many images do I have by type?" the way a model would through the real adapter: five `count_records` calls through the UI API, then `present_results`.
Light and dark, 390 and 1440 px:
- `panel-presentation-*`: the summary line, an Images metric, the "Media by type" table (counts and the server-computed 80.2% and 19.8%, each row a filtered-list link), the pie chart, two filter links (Open JPEG media, Open PNG media) and a follow-up action.
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+39 -4
View File
@@ -28,6 +28,8 @@
<anthropic.version>2.71.0</anthropic.version>
<archunit.version>1.5.1</archunit.version>
<jackson.version>2.21.7</jackson.version>
<!-- optional email delivery; qbit-email from Maven Central -->
<qbit-email.version>0.1.0-RC.2</qbit-email.version>
<!-- live evals call the real API; run them with -Dtest.excludedGroups= -Dgroups=live -->
<test.excludedGroups>live</test.excludedGroups>
</properties>
@@ -35,7 +37,7 @@
<parent>
<groupId>com.kingsrook</groupId>
<artifactId>qbit-build-parent</artifactId>
<version>2.0.0</version>
<version>2.1.1</version>
</parent>
<groupId>com.kingsrook.qbits</groupId>
@@ -50,8 +52,13 @@
<modelVersion>4.0.0</modelVersion>
<modules>
<module>qbit-assistant-provider-api</module>
<module>qbit-assistant</module>
<module>qbit-assistant-provider-anthropic</module>
<module>qbit-assistant-provider-openai</module>
<module>qbit-assistant-provider-bedrock</module>
<module>qbit-assistant-provider-vertex</module>
<module>qbit-assistant-rag-pgvector</module>
</modules>
<licenses>
@@ -81,6 +88,26 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-assistant-provider-api</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-assistant-provider-anthropic</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java-bedrock</artifactId>
<version>${anthropic.version}</version>
</dependency>
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java-vertex</artifactId>
<version>${anthropic.version}</version>
</dependency>
<!-- 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>
@@ -101,6 +128,11 @@
<version>${revision}</version>
<type>test-jar</type>
</dependency>
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-assistant-provider-openai</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
@@ -170,8 +202,9 @@
</build>
<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 -->
<!-- The assistant needs QQQ 4.1.0-RC.7: the AI tool kernel (qqq#1078), the -->
<!-- developer panels (qqq#1076) and the UI API extension point, invoker -->
<!-- and credentials (qqq#1128). 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 -->
@@ -182,7 +215,9 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.4</qqq.snapshot.version>
<!-- RC.7 provides classified-value tokens, log redaction and native help bundles; -->
<!-- RC.8 provides core job tracking (JobTracking, the Jobs tray). -->
<qqq.snapshot.version>4.1.0-RC.15</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -32,9 +32,14 @@
<url>https://github.com/QRun-IO/qbit-assistant</url>
<dependencies>
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-assistant-provider-api</artifactId>
</dependency>
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-assistant</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.kingsrook.qqq</groupId>
@@ -24,9 +24,11 @@ import java.util.Map;
import com.anthropic.core.JsonValue;
import com.anthropic.errors.AnthropicIoException;
import com.anthropic.errors.AnthropicServiceException;
import com.anthropic.models.messages.Base64ImageSource;
import com.anthropic.models.messages.CacheControlEphemeral;
import com.anthropic.models.messages.ContentBlock;
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.ImageBlockParam;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.MessageParam;
@@ -40,15 +42,15 @@ 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;
import com.kingsrook.qbits.assistant.spi.CacheHint;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelPart;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelResponse;
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
import com.kingsrook.qbits.assistant.spi.ModelUsage;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
/*******************************************************************************
@@ -223,6 +225,18 @@ public class AnthropicMapping
}
blocks.add(ContentBlockParam.ofToolResult(result.build()));
}
case IMAGE ->
{
ImageBlockParam.Builder image = ImageBlockParam.builder().source(Base64ImageSource.builder()
.mediaType(Base64ImageSource.MediaType.of(part.getMediaType()))
.data(part.getData() == null ? "" : part.getData())
.build());
if(cache != null)
{
image.cacheControl(cache);
}
blocks.add(ContentBlockParam.ofImage(image.build()));
}
default -> throw (new IllegalStateException("Unknown part type"));
}
}
@@ -313,8 +327,51 @@ public class AnthropicMapping
/*******************************************************************************
** Map an SDK error to a provider error. The message holds the status and
** the API error type only - never request or response bodies.
** 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)
{
@@ -348,7 +405,11 @@ public class AnthropicMapping
{
kind = "overloaded_error".equals(type) ? ModelProviderException.Kind.OVERLOADED : ModelProviderException.Kind.OTHER;
}
return (new ModelProviderException(kind, status >= 400 ? status : null, "Anthropic API error" + (status >= 400 ? " (HTTP " + status + ")" : "") + (type == null ? "" : " " + type)));
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)
{
@@ -29,14 +29,14 @@ 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.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.CompletableStreamHandle;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelUsage;
import com.kingsrook.qbits.assistant.spi.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;
@@ -98,15 +98,16 @@ public class AnthropicModelProvider implements AssistantModelProvider
/*******************************************************************************
** Builds the provider. apiKey is required (a literal from a secret store,
** or "${env.NAME}").
** Builds the provider. Unless a client is supplied, 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;
private String apiKey;
private AnthropicClient client;
private String baseUrl;
private Duration timeout = Duration.ofMinutes(10);
private Integer maxRetries = 2;
@@ -121,6 +122,19 @@ public class AnthropicModelProvider implements AssistantModelProvider
/*******************************************************************************
** Use an already configured client, including a cloud backend. The provider
** owns and closes this client; key, URL, timeout and retry builder options
** apply only when the builder creates its own client.
*******************************************************************************/
public Builder client(AnthropicClient client)
{
this.client = client;
return (this);
}
/*******************************************************************************
** Another API base URL (a gateway, or a test server).
*******************************************************************************/
@@ -159,6 +173,10 @@ public class AnthropicModelProvider implements AssistantModelProvider
*******************************************************************************/
public AnthropicModelProvider build()
{
if(client != null)
{
return (new AnthropicModelProvider(client, baseUrl));
}
String key = resolveSecret(apiKey);
if(!StringUtils.hasContent(key))
{
@@ -227,7 +245,7 @@ public class AnthropicModelProvider implements AssistantModelProvider
/*******************************************************************************
** Claude 5.5 models: tools, parallel tools, prompt caching, (adaptive)
** thinking.
** thinking and vision (image input).
*******************************************************************************/
@Override
public ModelCapabilities getCapabilities(String modelId)
@@ -237,6 +255,7 @@ public class AnthropicModelProvider implements AssistantModelProvider
.withParallelToolCalls(true)
.withPromptCaching(true)
.withThinking(true)
.withVision(true)
.withMaxContextTokens(200_000));
}
@@ -260,6 +279,26 @@ public class AnthropicModelProvider implements AssistantModelProvider
return (handle);
}
if(Boolean.FALSE.equals(request.getStreaming()))
{
java.util.concurrent.Future<?> completion = executor.submit(() ->
{
try
{
handle.complete(AnthropicMapping.toResponse(client.messages().create(params)));
}
catch(Throwable error)
{
if(!handle.isCancelled())
{
handle.fail(AnthropicMapping.toProviderException(error));
}
}
});
handle.setOnCancel(() -> completion.cancel(true));
return (handle);
}
AtomicReference<ModelUsage> seen = new AtomicReference<>();
handle.setPartialUsage(seen::get);
@@ -297,7 +336,21 @@ public class AnthropicModelProvider implements AssistantModelProvider
if(!handle.isCancelled())
{
ModelProviderException exception = AnthropicMapping.toProviderException(t).withPartialUsage(seen.get());
LOG.info("Anthropic stream failed", logPair("kind", exception.getKind()), logPair("httpStatus", exception.getHttpStatus()), logPair("model", request.getModel()));
///////////////////////////////////////////////////////////////////
// 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);
}
}
@@ -18,8 +18,8 @@ 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;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
/*******************************************************************************
@@ -24,16 +24,16 @@ 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.qbits.assistant.spi.CacheHint;
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelPart;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelResponse;
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -51,6 +51,39 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
*******************************************************************************/
class AnthropicModelProviderTest
{
/*******************************************************************************
** Routing requests use a single JSON reply without text deltas.
*******************************************************************************/
@Test
void nonStreamingClassifier() throws Exception
{
server.thenError(200, "classifier-response.json");
ModelRequest request = new ModelRequest().withModel("claude-sonnet-5-5").withMaxTokens(4).withStreaming(false)
.withMessages(List.of(ModelMessage.user("hello")));
List<String> deltas = new ArrayList<>();
ModelResponse response = provider.stream(request, deltas::add).await(Duration.ofSeconds(3));
assertThat(response.getText()).isEqualTo("SIMPLE");
assertThat(response.getUsage().getOutputTokens()).isEqualTo(1L);
assertThat(deltas).isEmpty();
assertThat(sentBody(0).get("stream")).isIn(null, false);
assertThat(sentBody(0).get("max_tokens")).isEqualTo(4);
}
/*******************************************************************************
** Non-streaming errors retain the normal exception mapping.
*******************************************************************************/
@Test
void nonStreamingError() throws Exception
{
server.thenError(401, "unauthorized.json");
assertThatThrownBy(() -> provider.stream(request().withStreaming(false), new StringBuilder()::append).await(Duration.ofSeconds(3)))
.isInstanceOfSatisfying(ModelProviderException.class, error -> assertThat(error.getKind()).isEqualTo(ModelProviderException.Kind.AUTHENTICATION));
}
private static final String TEST_KEY = "sk-ant-test-0000000000000000000000";
private RecordedAnthropicServer server;
@@ -265,7 +298,10 @@ class AnthropicModelProviderTest
{
assertThat(e.getKind()).isEqualTo(ModelProviderException.Kind.AUTHENTICATION);
assertThat(e.getHttpStatus()).isEqualTo(401);
assertThat(e.getMessage()).doesNotContain(TEST_KEY).doesNotContain("invalid x-api-key");
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)))
@@ -339,4 +375,28 @@ class AnthropicModelProviderTest
.hasMessageContaining("ANTHROPIC_API_KEY");
}
/*******************************************************************************
** An injected cloud-capable client wins over the key and HTTP builder options.
*******************************************************************************/
@Test
void injectedClientTakesPrecedence() throws Exception
{
server.thenStream("text-with-thinking.sse", 0);
var client = com.anthropic.client.okhttp.AnthropicOkHttpClient.builder().apiKey(TEST_KEY).baseUrl(server.baseUrl()).maxRetries(0).build();
var injected = AnthropicModelProvider.builder().client(client).apiKey(null).baseUrl("https://unused.invalid").build();
try
{
var response = injected.stream(request(), delta -> {}).await(Duration.ofSeconds(10));
assertThat(response.getText()).isEqualTo("There are 4 published posts.");
assertThat(server.getRequests()).hasSize(1);
assertThat(server.getRequests().getFirst().get("apiKey")).isEqualTo(TEST_KEY);
}
finally
{
injected.close();
}
}
}
@@ -0,0 +1,485 @@
/*
* 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.fake.ScriptedModelProvider;
import com.kingsrook.qbits.assistant.spi.CacheHint;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelPart;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
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>>() {}));
}
/*******************************************************************************
** An image part becomes a base64 image block; as the last block of the
** newest message it carries the cache hint.
*******************************************************************************/
@Test
@SuppressWarnings("unchecked")
void testImagePartMapping() throws Exception
{
ModelRequest request = new ModelRequest().withModel("claude-test").withMaxTokens(64).withMessages(List.of(new ModelMessage().withRole(ModelMessage.Role.USER)
.withPart(ModelPart.text("Describe it")).withPart(ModelPart.image("image/webp", "UklGRg==")).withCacheHint(CacheHint.SHORT)));
String json = ObjectMappers.jsonMapper().writeValueAsString(AnthropicMapping.toParams(request)._body());
Map<String, Object> body = JsonUtils.toObject(json, new TypeReference<Map<String, Object>>() {});
List<Object> content = (List<Object>) ((Map<String, Object>) ((List<Object>) body.get("messages")).get(0)).get("content");
Map<String, Object> image = (Map<String, Object>) content.get(1);
assertThat(image).containsEntry("type", "image").containsKey("cache_control");
assertThat((Map<String, Object>) image.get("source")).containsEntry("type", "base64").containsEntry("media_type", "image/webp").containsEntry("data", "UklGRg==");
assertThat((Map<String, Object>) content.get(0)).doesNotContainKey("cache_control");
}
/*******************************************************************************
** 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));
}
/*******************************************************************************
** Presentation remains inside the actual serialized strict request budget.
*******************************************************************************/
@Test
void testPresentationStrictOptIn() throws Exception
{
Map<String, Object> body = requestBody(new AssistantQBitConfig().withModelProvider(new ScriptedModelProvider()).withStrictToolNames(Set.of("present_results")));
assertThat(violations(body)).isEmpty();
assertThat(strictBudgetViolations(body)).isEmpty();
assertThat(tools(body)).anySatisfy(tool ->
{
assertThat(tool.get("name")).isEqualTo("present_results");
assertThat(tool.get("strict")).isEqualTo(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));
}
}
}
@@ -24,6 +24,7 @@ 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 com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
@@ -102,6 +103,10 @@ class LiveGoldenEvalTest
@MethodSource("tasks")
void live(GoldenTasks.Task task) throws Exception
{
if("D-page-12-this-week".equals(task.id()))
{
ClientChannelsMetaData.ofOrWithNew(qInstance).getDeniedPatterns().get("assistant").remove("audit*");
}
TurnRunner.Outcome outcome = new TurnRunner(qInstance, config).run(task.userId(), task.prompt());
assertThat(outcome.errorCode()).as("error").isNull();
task.liveCheck().accept(outcome);
@@ -24,7 +24,6 @@ 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;
@@ -32,6 +31,7 @@ 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.spi.ModelPricing;
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
import com.kingsrook.qbits.assistant.testing.TurnRunner;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
@@ -129,6 +129,22 @@ public class AssistantDemoServer extends AbstractQQQApplication
"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");
@@ -144,6 +160,15 @@ public class AssistantDemoServer extends AbstractQQQApplication
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);
@@ -0,0 +1 @@
{"id":"msg_classify","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[{"type":"text","text":"SIMPLE"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":18,"output_tokens":1}}
@@ -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,39 @@
event: message_start
data: {"type":"message_start","message":{"id":"msg_tools_01","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":300,"output_tokens":1,"cache_creation_input_tokens":0,"cache_read_input_tokens":5000}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-tools-1"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"I can draft that page change for you."}}
event: content_block_stop
data: {"type":"content_block_stop","index":1}
event: content_block_start
data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_W","name":"update_record","input":{}}}
event: content_block_delta
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"table\": \"page\", \"id\": \"12\", "}}
event: content_block_delta
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"values\": {\"metaDescription\": \"Who I am, what I build, and the home lab behind it.\"}}"}}
event: content_block_stop
data: {"type":"content_block_stop","index":2}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":60}}
event: message_stop
data: {"type":"message_stop"}
@@ -0,0 +1,36 @@
event: message_start
data: {"type":"message_start","message":{"id":"msg_text_01","type":"message","role":"assistant","model":"claude-sonnet-5-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":120,"output_tokens":1,"cache_creation_input_tokens":2048,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":48,"ephemeral_1h_input_tokens":2000}}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"SECRET_THINKING_TEXT"}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-abc-123"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
event: ping
data: {"type":"ping"}
event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"I proposed the new meta description for page 12. Confirm it in the card to save it."}}
event: content_block_stop
data: {"type":"content_block_stop","index":1}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":42}}
event: message_stop
data: {"type":"message_stop"}
+116
View File
@@ -0,0 +1,116 @@
<?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-api</artifactId>
<packaging>jar</packaging>
<name>QBit Assistant - Provider API</name>
<description>Provider SPI and pricing value types, independent of the assistant runtime</description>
<url>https://github.com/QRun-IO/qbit-assistant</url>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</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>
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<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>
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
/*******************************************************************************
@@ -58,4 +58,14 @@ public interface AssistantModelProvider
return (null);
}
/*******************************************************************************
** Optional embedding capability. Unsupported adapters fail before transport.
*******************************************************************************/
default EmbeddingResponse embed(EmbeddingRequest request) throws ModelProviderException
{
throw (new ModelProviderException(ModelProviderException.Kind.INVALID_REQUEST, null, "Embeddings are unsupported by this provider."));
}
}
@@ -0,0 +1,161 @@
/*
* 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.spi;
import java.util.List;
/*******************************************************************************
** A kind of model provider an admin can configure in the assistant_provider
** table (Anthropic now; OpenAI-compatible, Bedrock and others plug in the
** same way). Hosts register types with AssistantQBitConfig.withProviderType;
** the provider settings screen offers the registered types and their models.
**
** create() receives the API key already resolved from its reference; it must
** never log the key or put it in toString or exception messages.
*******************************************************************************/
public interface AssistantProviderType
{
/*******************************************************************************
** The type's id, stored in assistant_provider.providerType (e.g. "anthropic").
*******************************************************************************/
String getType();
/*******************************************************************************
** A label for the settings screen.
*******************************************************************************/
String getLabel();
/*******************************************************************************
** The models offered for this type, best default first.
*******************************************************************************/
List<String> getModels();
/*******************************************************************************
** The environment variable that holds the key by default (e.g.
** ANTHROPIC_API_KEY).
*******************************************************************************/
String getDefaultApiKeyEnvName();
/*******************************************************************************
** The provider's own API base URL (shown when no override is set).
*******************************************************************************/
String getDefaultBaseUrl();
/*******************************************************************************
** Build a provider. apiKey is the resolved secret (never null or empty);
** baseUrl is null for the type's default.
*******************************************************************************/
AssistantModelProvider create(String apiKey, String baseUrl);
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default List<String> getKinds()
{
return (List.of(getType().toUpperCase(java.util.Locale.ROOT).replace('-', '_')));
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default String getDefaultBaseUrl(String kind)
{
return (getDefaultBaseUrl());
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default String getDefaultApiKeyEnvName(String kind)
{
return (getDefaultApiKeyEnvName());
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default String getDefaultLocation(String kind)
{
return ("CLOUD");
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default AssistantModelProvider create(ProviderSettings settings)
{
return (create(settings.getApiKey(), settings.getBaseUrl()));
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default List<DiscoveredModel> discoverModels(ProviderSettings settings) throws ModelProviderException
{
return (getModels().stream().map(id -> new DiscoveredModel(id, id, null, null)).toList());
}
/*******************************************************************************
** Backward-compatible provider registry extension.
*******************************************************************************/
default HealthResult checkHealth(ProviderSettings settings)
{
return (new HealthResult(null, null, "Health check not supported"));
}
/*******************************************************************************
** Additional settings errors, without resolving credentials or doing I/O.
** Settings contain configured values and apiKeyEnvName; apiKey, the bearer
** token supplier and SSLContext are not resolved for validation.
*******************************************************************************/
default List<String> validate(ProviderSettings settings)
{
return (List.of());
}
/*******************************************************************************
** Whether this kind needs an explicit URL when it has no fixed default.
** Cloud SDKs can instead derive their endpoint from region and project.
*******************************************************************************/
default boolean requiresBaseUrl(String kind)
{
return (getDefaultBaseUrl(kind) == null);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
/*******************************************************************************
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.time.Duration;
@@ -79,20 +79,29 @@ public class CompletableStreamHandle implements StreamHandle
/*******************************************************************************
** Finish with a response.
** Finish with a response (ignored once cancelled: cancel() answers with a
** cancelled response, and closing the stream may wake the worker first).
*******************************************************************************/
public void complete(ModelResponse response)
{
if(cancelled.get())
{
return;
}
future.complete(response);
}
/*******************************************************************************
** Finish with an error.
** Finish with an error (ignored once cancelled, see complete()).
*******************************************************************************/
public void fail(ModelProviderException exception)
{
if(cancelled.get())
{
return;
}
future.completeExceptionally(exception);
}
@@ -0,0 +1,25 @@
/*
* 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.spi;
/*******************************************************************************
** A model advertised by the provider, without inferred capabilities.
*******************************************************************************/
public record DiscoveredModel(String modelId, String displayName, Integer contextWindowTokens, String ownedBy)
{
}
@@ -0,0 +1,39 @@
/*
* 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.spi;
import java.util.List;
/*******************************************************************************
** One embedding batch. Providers accept at most 64 inputs per request.
*******************************************************************************/
public record EmbeddingRequest(String model, List<String> input)
{
/*******************************************************************************
** Snapshot the inputs and reject empty or oversized batches before transport.
*******************************************************************************/
public EmbeddingRequest
{
input = List.copyOf(input);
if(model == null || model.isBlank() || input.isEmpty() || input.size() > 64)
{
throw (new IllegalArgumentException("An embedding request needs a model and 1 to 64 inputs."));
}
}
}
@@ -0,0 +1,28 @@
/*
* 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.spi;
import java.util.List;
/*******************************************************************************
** Ordered vectors and billable usage. No input text is retained in the response.
*******************************************************************************/
public record EmbeddingResponse(List<float[]> vectors, ModelUsage usage, String requestId)
{
}
@@ -0,0 +1,32 @@
/*
* 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.spi;
/*******************************************************************************
** A health probe result; null healthy means unsupported.
*******************************************************************************/
public record HealthResult(Boolean healthy, Long latencyMs, String message)
{
/*******************************************************************************
** Sanitize provider diagnostics.
*******************************************************************************/
public HealthResult
{
message = ModelProviderException.sanitizeProviderMessage(message, 300);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
/*******************************************************************************
@@ -23,6 +23,16 @@ package com.kingsrook.qbits.assistant.provider;
*******************************************************************************/
public class ModelCapabilities
{
private Boolean vision = false;
private Boolean streaming = true;
private Boolean reasoningEffort = false;
private Boolean tools = true;
private Boolean parallelToolCalls = true;
private Boolean promptCaching = false;
@@ -182,4 +192,98 @@ public class ModelCapabilities
return (this);
}
/*******************************************************************************
** Getter for vision
*******************************************************************************/
public Boolean getVision()
{
return (this.vision);
}
/*******************************************************************************
** Setter for vision
*******************************************************************************/
public void setVision(Boolean vision)
{
this.vision = vision;
}
/*******************************************************************************
** Fluent setter for vision
*******************************************************************************/
public ModelCapabilities withVision(Boolean vision)
{
this.vision = vision;
return (this);
}
/*******************************************************************************
** Getter for streaming
*******************************************************************************/
public Boolean getStreaming()
{
return (this.streaming);
}
/*******************************************************************************
** Setter for streaming
*******************************************************************************/
public void setStreaming(Boolean streaming)
{
this.streaming = streaming;
}
/*******************************************************************************
** Fluent setter for streaming
*******************************************************************************/
public ModelCapabilities withStreaming(Boolean streaming)
{
this.streaming = streaming;
return (this);
}
/*******************************************************************************
** Getter for reasoningEffort
*******************************************************************************/
public Boolean getReasoningEffort()
{
return (this.reasoningEffort);
}
/*******************************************************************************
** Setter for reasoningEffort
*******************************************************************************/
public void setReasoningEffort(Boolean reasoningEffort)
{
this.reasoningEffort = reasoningEffort;
}
/*******************************************************************************
** Fluent setter for reasoningEffort
*******************************************************************************/
public ModelCapabilities withReasoningEffort(Boolean reasoningEffort)
{
this.reasoningEffort = reasoningEffort;
return (this);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
/*******************************************************************************
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.ArrayList;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.LinkedHashMap;
@@ -22,8 +22,10 @@ import java.util.Map;
/*******************************************************************************
** One content part of a model message: text, a tool_use (assistant) or a
** tool_result (user). Tool results that report a failure set isError.
** One content part of a model message: text, a tool_use (assistant), a
** tool_result (user) or an image (user; base64 data plus its media type).
** Tool results that report a failure set isError. toString never includes
** text or image data, so a part can never leak content into a log line.
*******************************************************************************/
public class ModelPart
{
@@ -34,7 +36,8 @@ public class ModelPart
{
TEXT,
TOOL_USE,
TOOL_RESULT
TOOL_RESULT,
IMAGE
}
private Type type;
@@ -43,6 +46,8 @@ public class ModelPart
private String toolName;
private Map<String, Object> input;
private Boolean isError = false;
private String mediaType;
private String data;
@@ -76,6 +81,30 @@ public class ModelPart
/*******************************************************************************
** An image part: the media type (image/png, image/jpeg, image/gif or
** image/webp) and the base64-encoded bytes. Only for models whose
** capabilities report vision.
*******************************************************************************/
public static ModelPart image(String mediaType, String base64Data)
{
return (new ModelPart().withType(Type.IMAGE).withMediaType(mediaType).withData(base64Data));
}
/*******************************************************************************
** The kind and sizes only; never the text, input or image data.
*******************************************************************************/
@Override
public String toString()
{
return ("ModelPart{type=" + type + ", textChars=" + (text == null ? 0 : text.length()) + ", toolName=" + toolName
+ (mediaType == null ? "" : ", mediaType=" + mediaType) + (data == null ? "" : ", dataChars=" + data.length()) + "}");
}
/*******************************************************************************
** Getter for type
*******************************************************************************/
@@ -260,4 +289,67 @@ public class ModelPart
return (this);
}
/*******************************************************************************
** Getter for mediaType
*******************************************************************************/
public String getMediaType()
{
return (this.mediaType);
}
/*******************************************************************************
** Setter for mediaType
*******************************************************************************/
public void setMediaType(String mediaType)
{
this.mediaType = mediaType;
}
/*******************************************************************************
** Fluent setter for mediaType
*******************************************************************************/
public ModelPart withMediaType(String mediaType)
{
this.mediaType = mediaType;
return (this);
}
/*******************************************************************************
** Getter for data (base64)
*******************************************************************************/
public String getData()
{
return (this.data);
}
/*******************************************************************************
** Setter for data (base64)
*******************************************************************************/
public void setData(String data)
{
this.data = data;
}
/*******************************************************************************
** Fluent setter for data (base64)
*******************************************************************************/
public ModelPart withData(String data)
{
this.data = data;
return (this);
}
}
@@ -14,14 +14,12 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.engine;
package com.kingsrook.qbits.assistant.spi;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import com.kingsrook.qbits.assistant.AssistantModelRouting;
import com.kingsrook.qbits.assistant.provider.ModelUsage;
/*******************************************************************************
@@ -63,9 +61,9 @@ public class ModelPricing implements Serializable
public static Map<String, ModelPricing> defaults()
{
Map<String, ModelPricing> map = new LinkedHashMap<>();
map.put(AssistantModelRouting.SONNET_5_5, of(2.0, 10.0, 0.1));
map.put(AssistantModelRouting.OPUS_5_5, of(4.0, 20.0, 0.05));
map.put(AssistantModelRouting.HAIKU_5_5, of(0.10, 0.50, 0.1));
map.put("claude-sonnet-5-5", of(2.0, 10.0, 0.1));
map.put("claude-opus-5-5", of(4.0, 20.0, 0.05));
map.put("claude-haiku-5-5", of(0.10, 0.50, 0.1));
map.put("claude-fable-5-1", of(10.0, 50.0, 0.025));
map.put("claude-fable-5", of(10.0, 50.0, 0.1));
map.put("claude-opus-5", of(5.0, 25.0, 0.1));
@@ -0,0 +1,203 @@
/*
* 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.spi;
/*******************************************************************************
** A failed model call. The message is safe to show and log: providers must
** never put credentials, prompts or tool results in it.
*******************************************************************************/
public class ModelProviderException extends Exception
{
public static final int MAX_PROVIDER_MESSAGE_CHARS = 300;
/*******************************************************************************
** Error classes the engine reacts to.
*******************************************************************************/
public enum Kind
{
AUTHENTICATION,
RATE_LIMITED,
OVERLOADED,
INVALID_REQUEST,
TIMEOUT,
NETWORK,
SERVER,
OTHER
}
private final Kind kind;
private final Integer httpStatus;
private ModelUsage partialUsage;
private String providerErrorType;
private String providerMessage;
private String requestId;
private boolean strictSchemaRejected;
/*******************************************************************************
**
*******************************************************************************/
public ModelProviderException(Kind kind, Integer httpStatus, String message)
{
super(message);
this.kind = kind;
this.httpStatus = httpStatus;
}
/*******************************************************************************
** Getter for kind
*******************************************************************************/
public Kind getKind()
{
return (kind);
}
/*******************************************************************************
** Getter for httpStatus (null when there was no HTTP response)
*******************************************************************************/
public Integer getHttpStatus()
{
return (httpStatus);
}
/*******************************************************************************
** Usage already incurred by the failed call (e.g. input tokens of a stream
** that broke off), or null. Counted toward budgets and cost.
*******************************************************************************/
public ModelUsage getPartialUsage()
{
return (partialUsage);
}
/*******************************************************************************
** Fluent setter for partialUsage
*******************************************************************************/
public ModelProviderException withPartialUsage(ModelUsage partialUsage)
{
this.partialUsage = partialUsage;
return (this);
}
/*******************************************************************************
** Whether a retry later may succeed.
*******************************************************************************/
public boolean isRetryable()
{
return (kind == Kind.RATE_LIMITED || kind == Kind.OVERLOADED || kind == Kind.TIMEOUT || kind == Kind.NETWORK || kind == Kind.SERVER);
}
/*******************************************************************************
** The provider's own error type (e.g. invalid_request_error), when it sent one.
*******************************************************************************/
public String getProviderErrorType()
{
return (providerErrorType);
}
/*******************************************************************************
** The provider's own error message: one line, capped, with anything that looks
** like a key removed (see {@link #sanitizeProviderMessage}). Safe to log and
** to show to administrators; never contains prompt content.
*******************************************************************************/
public String getProviderMessage()
{
return (providerMessage);
}
/*******************************************************************************
** The provider's request id, for its support.
*******************************************************************************/
public String getRequestId()
{
return (requestId);
}
/*******************************************************************************
** Fluent setter for the provider's error details.
*******************************************************************************/
public ModelProviderException withProviderDetails(String providerErrorType, String providerMessage, String requestId)
{
this.providerErrorType = sanitizeProviderMessage(providerErrorType, 64);
this.providerMessage = sanitizeProviderMessage(providerMessage, MAX_PROVIDER_MESSAGE_CHARS);
this.requestId = sanitizeProviderMessage(requestId, 100);
return (this);
}
/*******************************************************************************
** One line, at most max characters, with key-like tokens (sk-..., long
** base64/hex runs) replaced by [redacted]. Null for blank input.
*******************************************************************************/
public static String sanitizeProviderMessage(String text, int max)
{
if(text == null || text.isBlank())
{
return (null);
}
String line = text.replaceAll("[\\p{Cntrl}\\s]+", " ").strip();
line = line.replaceAll("(?i)\\bsk-[a-z0-9_\\-]{6,}", "[redacted]");
line = line.replaceAll("[A-Za-z0-9+/_\\-]{40,}", "[redacted]");
return (line.length() <= max ? line : line.substring(0, max - 1) + "…");
}
/*******************************************************************************
** Whether the provider refused the request because of its strict tool
** schemas (e.g. Anthropic's "compiled grammar is too large"): the same
** request without strict tools can succeed.
*******************************************************************************/
public boolean isStrictSchemaRejected()
{
return (strictSchemaRejected);
}
/*******************************************************************************
** Fluent setter for strictSchemaRejected
*******************************************************************************/
public ModelProviderException withStrictSchemaRejected(boolean strictSchemaRejected)
{
this.strictSchemaRejected = strictSchemaRejected;
return (this);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.ArrayList;
@@ -32,6 +32,11 @@ import java.util.List;
*******************************************************************************/
public class ModelRequest
{
private ModelCapabilities capabilities;
private Boolean streaming = true;
private String model;
private String effort;
private Integer maxTokens;
@@ -48,7 +53,9 @@ public class ModelRequest
public ModelRequest copy()
{
return (new ModelRequest()
.withStreaming(streaming)
.withModel(model)
.withCapabilities(capabilities)
.withEffort(effort)
.withMaxTokens(maxTokens)
.withParallelToolCalls(parallelToolCalls)
@@ -274,4 +281,57 @@ public class ModelRequest
return (this);
}
/*******************************************************************************
** Getter for capabilities
*******************************************************************************/
public ModelCapabilities getCapabilities()
{
return (this.capabilities);
}
/*******************************************************************************
** Setter for capabilities
*******************************************************************************/
public void setCapabilities(ModelCapabilities capabilities)
{
this.capabilities = capabilities;
}
/*******************************************************************************
** Fluent setter for capabilities
*******************************************************************************/
public ModelRequest withCapabilities(ModelCapabilities capabilities)
{
this.capabilities = capabilities;
return (this);
}
/*******************************************************************************
** Whether to request streaming transport (classifiers use one JSON reply).
*******************************************************************************/
public Boolean getStreaming()
{
return (streaming);
}
/*******************************************************************************
** Select streaming transport independently of model capability.
*******************************************************************************/
public ModelRequest withStreaming(Boolean streaming)
{
this.streaming = streaming;
return (this);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.ArrayList;
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff. Show more