Compare commits

..
Author SHA1 Message Date
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 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.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.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 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.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
158 changed files with 11823 additions and 1498 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
version: 2.1
orbs:
qqq-orb: kingsrook/qqq-orb@0.6.8
qqq-orb: kingsrook/qqq-orb@0.6.9
commands:
configure-package-install:
+1 -1
View File
@@ -29,7 +29,7 @@ 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 `engine.ModelPricing` (original package names); only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
- `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`.
+73 -2
View File
@@ -1,8 +1,74 @@
# Changelog
## 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.
||||||| befb90a
## 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)
- Extract provider SPI/value types and `engine.ModelPricing` into `qbit-assistant-provider-api`, preserving package names. Its only production dependency is Jackson annotations.
- **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
@@ -66,7 +132,7 @@
- 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.
- Keep QQQ RC.4 compatibility with a classification stand-in and core #1142 adapter seam.
- 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.
@@ -84,6 +150,11 @@ Phase 0/1 of the QQQ Assistant: read-only Q&A and navigation. Requires QQQ 4.1 w
- 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`**.
+2 -1
View File
@@ -29,7 +29,7 @@ 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 `engine.ModelPricing` (original package names); only Jackson annotations in production. Provider validation takes unresolved `ProviderSettings`, not an entity.
- `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`.
@@ -57,6 +57,7 @@ Always use the wrapper: Maven 3.10 cannot read the parent POM. The committed def
- 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).
+97 -11
View File
@@ -20,15 +20,47 @@ Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`.
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. Existing
`com.kingsrook.qbits.assistant.provider.*` imports and
`com.kingsrook.qbits.assistant.engine.ModelPricing` stay the same.
`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.
## 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**:
@@ -141,6 +173,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:
@@ -206,6 +247,8 @@ 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. |
At runtime, an admin can override the kill switch, the main model and effort, and the budgets in the single **`assistant_policy`** row.
@@ -464,12 +507,30 @@ engine/tool golden turns. No cloud credentials or live endpoints are required.
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
On QQQ 4.1.0-RC.5, classify application tables/fields in the host configuration:
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.qbits.assistant.classification.DataClassification;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
AssistantQBitConfig config = new AssistantQBitConfig()
.withDataClassification("patient", DataClassification.PHI)
@@ -487,8 +548,8 @@ 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 qbit `DataClassification` enum is a stand-in for core QRun-IO/qqq#1142, with
PUBLIC < CONFIDENTIAL < PII < PHI. Unconfigured tables default to PUBLIC; a field
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
@@ -497,10 +558,9 @@ explicitly if the host considers it safe for that subset. Cross-table results wi
tables use the highest classification anywhere. Metadata-only tools remain PUBLIC.
The assistant's own tables remain denied to tools.
Hosts can supply `withClassificationSource(ClassificationSource)` instead. When
upgrading to an RC containing core #1142, implement that interface with
`AiDataClassifications`/`AiTableMetaData`/`AiFieldMetaData` (map enum names), then
replace the stand-in once the qbit's minimum core version includes it.
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
@@ -620,3 +680,29 @@ skills can extend the built-in presentation instructions. See the
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.
+131 -6
View File
@@ -1,10 +1,135 @@
# Upgrading qbit-assistant
## 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.
Hosts may wire `AssistantRunTracker` for Jobs tray publication, progress, Stop,
and terminal notification. It is a no-op by default and all callbacks are
isolated from turn execution. Tracking ids are local to the owning runtime;
reaping an already dead owner does not invent another tracking job. Hosts should
associate their durable tracking row with the supplied turn id. The SPI is a
stand-in for QQQ #1210.
||||||| befb90a
## 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)
Hosts that depend on `qbit-assistant` keep working: it now brings in
`qbit-assistant-provider-api` transitively. Package names are unchanged, including
`com.kingsrook.qbits.assistant.engine.ModelPricing`. No schema migration is needed.
**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
@@ -17,7 +142,7 @@ 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 no source change. Keep the runtime and
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
@@ -42,8 +167,8 @@ 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 client-channel enforcement
arrives with the client-channel RC; the header and tool audit are already sent.
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
+31 -6
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.
@@ -143,7 +150,7 @@ Owner: *"the agent should have to go through the same API that the UIUX does. th
- A request to the server's own port runs the identical pipeline by construction. It costs one local hop, which is milliseconds next to a model call.
This matches core's design (`docs/UI-API-EXTENSIONS.md` §5, `UiApiInvoker`, QRun-IO/qqq#1128).
- `LoopbackUiApiGateway` is the stand-in until a QQQ release has the invoker. Then an adapter over `UiApiInvoker.forServer(server)` replaces it (or a host injects one with `withUiApiGateway`), and nothing else changes.
- `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
@@ -228,6 +235,18 @@ The golden and red-team evals now run through the UI API too.
- 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.
@@ -275,6 +294,14 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
- **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:
@@ -354,10 +381,8 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
### P-c as built
- The qbit classification enum is a stand-in for core #1142 until a released RC
includes it. Configured table/field overrides are the default; hosts can supply
a `ClassificationSource` over core metadata, mapping enum names, then replace
the stand-in when the minimum QQQ version advances.
- 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.
+128 -1
View File
@@ -103,7 +103,7 @@ CREATE TABLE assistant_tool_call
redactions_json TEXT,
ui_api_operation VARCHAR(255),
http_status INTEGER,
audit_href VARCHAR(500),
audit_href TEXT,
pending_action_id INTEGER,
create_date TIMESTAMP WITH TIME ZONE
);
@@ -574,3 +574,130 @@ CREATE TABLE assistant_scheduled_run (
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 $$;
+7 -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>
@@ -200,8 +202,9 @@
</build>
<profiles>
<!-- The assistant needs QQQ 4.1.0-RC.5: the AI tool kernel (package -->
<!-- actions.ai, qqq#1078) and the developer panels (qqq#1076). Until -->
<!-- The assistant needs QQQ 4.1.0-RC.6: 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 -->
@@ -212,7 +215,7 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.5</qqq.snapshot.version>
<qqq.snapshot.version>4.1.0-RC.6</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -40,15 +40,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;
/*******************************************************************************
@@ -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;
@@ -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;
@@ -26,10 +26,10 @@ import java.util.Set;
import com.anthropic.core.ObjectMappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
import com.kingsrook.qbits.assistant.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;
@@ -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;
@@ -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.List;
@@ -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;
@@ -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.List;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.List;
@@ -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;
/*******************************************************************************
@@ -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;
@@ -14,13 +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.provider.ModelUsage;
/*******************************************************************************
@@ -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.ArrayList;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.Map;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
/*******************************************************************************
@@ -14,12 +14,12 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.function.Supplier;
import javax.net.ssl.SSLContext;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.net.ssl.SSLContext;
/*******************************************************************************
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.time.Duration;
@@ -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;
/*******************************************************************************
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.io.ByteArrayInputStream;
@@ -1,75 +0,0 @@
/*
* 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;
import java.util.Set;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import com.tngtech.archunit.core.importer.ImportOption;
import org.junit.jupiter.api.Test;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
/*******************************************************************************
** Keep external provider consumers independent of the assistant runtime and QQQ.
*******************************************************************************/
class ProviderApiArchitectureTest
{
/*******************************************************************************
** Allow only the extracted types, including their nested enums, under the
** assistant namespace. A future dependency on any runtime package must fail.
*******************************************************************************/
@Test
void dependsOnlyOnApiTypes()
{
Set<String> apiTypes = Set.of(
"com.kingsrook.qbits.assistant.provider.AssistantModelProvider",
"com.kingsrook.qbits.assistant.provider.AssistantProviderType",
"com.kingsrook.qbits.assistant.provider.CacheHint",
"com.kingsrook.qbits.assistant.provider.CompletableStreamHandle",
"com.kingsrook.qbits.assistant.provider.DiscoveredModel",
"com.kingsrook.qbits.assistant.provider.EmbeddingRequest",
"com.kingsrook.qbits.assistant.provider.EmbeddingResponse",
"com.kingsrook.qbits.assistant.provider.HealthResult",
"com.kingsrook.qbits.assistant.provider.ModelCapabilities",
"com.kingsrook.qbits.assistant.provider.ModelEventListener",
"com.kingsrook.qbits.assistant.provider.ModelMessage",
"com.kingsrook.qbits.assistant.provider.ModelPart",
"com.kingsrook.qbits.assistant.provider.ModelProviderException",
"com.kingsrook.qbits.assistant.provider.ModelRequest",
"com.kingsrook.qbits.assistant.provider.ModelResponse",
"com.kingsrook.qbits.assistant.provider.ModelToolDefinition",
"com.kingsrook.qbits.assistant.provider.ModelUsage",
"com.kingsrook.qbits.assistant.provider.ProviderSettings",
"com.kingsrook.qbits.assistant.provider.StreamHandle",
"com.kingsrook.qbits.assistant.provider.SystemBlock",
"com.kingsrook.qbits.assistant.provider.TokenCount",
"com.kingsrook.qbits.assistant.provider.TrustedCaBundle",
"com.kingsrook.qbits.assistant.engine.ModelPricing");
JavaClasses imported = new ClassFileImporter()
.withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS)
.importPackages("com.kingsrook.qbits.assistant");
DescribedPredicate<JavaClass> outsideRuntime = DescribedPredicate.describe("outside assistant or an extracted API type", type ->
!type.getName().startsWith("com.kingsrook.qbits.assistant.") || apiTypes.contains(type.getName().split("\\$", 2)[0]));
classes().should().onlyDependOnClassesThat(outsideRuntime).check(imported);
noClasses().should().dependOnClassesThat().resideInAnyPackage("com.kingsrook.qqq..").check(imported);
}
}
@@ -0,0 +1,46 @@
/*
* 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 com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.importer.ClassFileImporter;
import org.junit.jupiter.api.Test;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideOutsideOfPackage;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
/*******************************************************************************
** Keep external provider consumers independent of the assistant runtime and QQQ.
*******************************************************************************/
class ProviderApiArchitectureTest
{
/*******************************************************************************
** Import the entire artifact so an accidental package outside spi also fails.
*******************************************************************************/
@Test
void dependsOnlyOnApiTypes()
{
String spiPackage = "com.kingsrook.qbits.assistant.spi";
JavaClasses imported = new ClassFileImporter().importUrl(AssistantModelProvider.class.getProtectionDomain().getCodeSource().getLocation());
classes().should().resideInAPackage(spiPackage).check(imported);
noClasses().should().dependOnClassesThat(resideInAPackage("com.kingsrook.qbits..").and(resideOutsideOfPackage(spiPackage))).check(imported);
noClasses().should().dependOnClassesThat().resideInAnyPackage("com.kingsrook.qqq..").check(imported);
}
}
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.time.Duration;
@@ -23,11 +23,10 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingsrook.qbits.assistant.engine.ModelPricing;
import javax.net.ssl.SSLContext;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -14,11 +14,10 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.time.Duration;
import com.kingsrook.qbits.assistant.engine.ModelPricing;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.util.List;
@@ -14,7 +14,7 @@
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.provider;
package com.kingsrook.qbits.assistant.spi;
import java.security.KeyStore;
@@ -24,11 +24,11 @@ import com.anthropic.backends.Backend;
import com.anthropic.bedrock.backends.BedrockBackend;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.Timeout;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
@@ -27,13 +27,13 @@ import java.util.Set;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.engine.ProviderService;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
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.spi.ProviderSettings;
import com.kingsrook.qbits.assistant.testing.CloudProviderTestServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -36,19 +36,19 @@ import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.CompletableStreamHandle;
import com.kingsrook.qbits.assistant.provider.EmbeddingRequest;
import com.kingsrook.qbits.assistant.provider.EmbeddingResponse;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
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.ModelUsage;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
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.EmbeddingRequest;
import com.kingsrook.qbits.assistant.spi.EmbeddingResponse;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
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.ModelUsage;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
/*******************************************************************************
@@ -18,12 +18,12 @@ package com.kingsrook.qbits.assistant.provider.openai;
import java.util.List;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
import com.kingsrook.qbits.assistant.provider.HealthResult;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
import com.kingsrook.qbits.assistant.spi.HealthResult;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
/*******************************************************************************
@@ -33,12 +33,12 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLHandshakeException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import javax.net.ssl.SSLHandshakeException;
/*******************************************************************************
@@ -24,12 +24,12 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
import com.kingsrook.qbits.assistant.provider.ModelPart;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
import com.kingsrook.qbits.assistant.provider.SystemBlock;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelPart;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
/*******************************************************************************
@@ -21,10 +21,10 @@ import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -22,16 +22,16 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
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.ProviderSettings;
import com.kingsrook.qbits.assistant.provider.SystemBlock;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
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.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -18,9 +18,9 @@ package com.kingsrook.qbits.assistant.provider.openai;
import java.util.List;
import com.kingsrook.qbits.assistant.provider.EmbeddingRequest;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.EmbeddingRequest;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -24,14 +24,14 @@ import java.nio.file.Path;
import java.security.KeyStore;
import java.time.Duration;
import java.util.Set;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
import com.kingsrook.qqq.backend.core.context.QContext;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.assertj.core.api.Assertions.assertThat;
@@ -36,9 +36,9 @@ import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.processes.DiscoverModelsProcess;
import com.kingsrook.qbits.assistant.processes.TestConnectionProcess;
import com.kingsrook.qbits.assistant.processes.TestModelConnectionProcess;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.fake.ScriptedModelProvider;
import com.kingsrook.qbits.assistant.provider.openai.OpenAiCompatibleProviderType;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
import com.kingsrook.qbits.assistant.testing.EvalSupport;
import com.kingsrook.qbits.assistant.testing.GoldenTasks;
@@ -23,14 +23,14 @@ import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.core.Timeout;
import com.anthropic.vertex.backends.VertexBackend;
import com.google.auth.oauth2.GoogleCredentials;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.provider.StreamHandle;
import com.kingsrook.qbits.assistant.provider.anthropic.AnthropicModelProvider;
import com.kingsrook.qbits.assistant.provider.openai.OpenAiCompatibleModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
import com.kingsrook.qbits.assistant.spi.ModelEventListener;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
/*******************************************************************************
@@ -19,10 +19,10 @@ package com.kingsrook.qbits.assistant.provider.vertex;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
/*******************************************************************************
@@ -29,11 +29,11 @@ import com.google.auth.oauth2.GoogleCredentials;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.engine.ProviderService;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
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.spi.ProviderSettings;
import com.kingsrook.qbits.assistant.testing.CloudProviderTestServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+42
View File
@@ -49,6 +49,15 @@
<optional>true</optional>
</dependency>
<!-- Optional email delivery of scheduled-task results. Every reference is in -->
<!-- the email package; without the jar nothing changes. -->
<dependency>
<groupId>com.kingsrook.qbits</groupId>
<artifactId>qbit-email</artifactId>
<version>${qbit-email.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
@@ -64,6 +73,39 @@
<artifactId>archunit-junit5</artifactId>
<scope>test</scope>
</dependency>
<!-- AssistantDefaultsChangelogTest runs the shipped seed changelog against H2 (PostgreSQL mode). -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
<scope>test</scope>
</dependency>
<!-- ...through real Liquibase (the version kof22 runs), so preconditions and bookkeeping are exercised. -->
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.33.0</version>
<scope>test</scope>
</dependency>
<!-- the reference DDL guardrail (SchemaForeignKeyPostgresTest) -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.21.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.14</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -32,14 +32,15 @@ import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.kingsrook.qbits.assistant.classification.ClassificationSource;
import com.kingsrook.qbits.assistant.classification.ConfiguredClassificationSource;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.engine.ModelPricing;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.TrustedCaBundle;
import com.kingsrook.qbits.assistant.jobs.AssistantRunTracker;
import com.kingsrook.qbits.assistant.rag.VectorStore;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.ModelPricing;
import com.kingsrook.qbits.assistant.spi.TrustedCaBundle;
import com.kingsrook.qbits.assistant.uiapi.UiApiGateway;
import com.kingsrook.qqq.backend.core.actions.ai.AiExposure;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.producers.MetaDataCustomizerInterface;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitConfig;
@@ -90,6 +91,7 @@ public class AssistantQBitConfig implements QBitConfig
private String conversationEncryptionKeyEnvName;
private Boolean enabled = true;
private Boolean recordHistory = false;
private String backendName;
private String providerName = DEFAULT_PROVIDER_NAME;
private AssistantModelRouting models = new AssistantModelRouting();
@@ -98,12 +100,20 @@ public class AssistantQBitConfig implements QBitConfig
private Integer maxParallelToolCalls = 4;
private Integer maxRowsToModel = 50;
private Integer maxCellChars = 500;
private Integer turnHeartbeatSeconds = 5;
private Integer turnLeaseSeconds = 45;
private Integer turnForceFinalizeGraceSeconds = 20;
private Integer shutdownGraceSeconds = 8;
private String defaultConcurrencyMode = "SUPERSEDE";
private Boolean registerShutdownHook = true;
private AssistantRunTracker runTracker = AssistantRunTracker.NOOP;
private Integer maxTurnSeconds = 300;
private Integer maxUserMessageChars = 8000;
private Integer historyMessageLimit = 40;
private AssistantBudgets budgets = new AssistantBudgets();
private Integer maxTurnsPerUserPerMinute = 10;
private Integer maxConcurrentTurnsPerUser = 1;
private Integer maxConcurrentTurnsPerUser = 3;
private Integer conversationRetentionDays = 90;
private Integer toolResultRetentionDays = 30;
private Integer approvalRetentionDays = 365;
@@ -145,11 +155,13 @@ public class AssistantQBitConfig implements QBitConfig
private Integer providerTestTimeoutSeconds = 30;
private Integer homeMaxRows = 20000;
private String tablePathPrefix = "/app";
private Boolean emailExternalApproved = false;
private transient MetaDataCustomizerInterface<QTableMetaData> tableMetaDataCustomizer;
private transient Map<String, AssistantModelProvider> modelProviders = new LinkedHashMap<>();
private transient Map<String, AssistantProviderType> providerTypes = new LinkedHashMap<>();
private transient Function<String, String> secretResolver = System::getenv;
private transient Function<String, String> emailRecipientResolver;
private transient AssistantRuntime runtime;
@@ -203,6 +215,23 @@ public class AssistantQBitConfig implements QBitConfig
requirePositive(errors, "maxRowsToModel", maxRowsToModel);
requirePositive(errors, "maxCellChars", maxCellChars);
requirePositive(errors, "maxTurnSeconds", maxTurnSeconds);
requirePositive(errors, "turnHeartbeatSeconds", turnHeartbeatSeconds);
requirePositive(errors, "turnLeaseSeconds", turnLeaseSeconds);
requirePositive(errors, "turnForceFinalizeGraceSeconds", turnForceFinalizeGraceSeconds);
requirePositive(errors, "shutdownGraceSeconds", shutdownGraceSeconds);
if(turnHeartbeatSeconds != null && turnLeaseSeconds != null && turnLeaseSeconds < 2 * turnHeartbeatSeconds)
{
errors.add("turnLeaseSeconds must be at least twice turnHeartbeatSeconds.");
}
if(!"SUPERSEDE".equals(defaultConcurrencyMode) && !"CONCURRENT".equals(defaultConcurrencyMode))
{
errors.add("defaultConcurrencyMode must be SUPERSEDE or CONCURRENT.");
}
if(turnHeartbeatSeconds != null && turnLeaseSeconds != null && turnHeartbeatSeconds >= turnLeaseSeconds)
{
errors.add("turnHeartbeatSeconds must be less than turnLeaseSeconds.");
}
requirePositive(errors, "maxUserMessageChars", maxUserMessageChars);
requirePositive(errors, "historyMessageLimit", historyMessageLimit);
requirePositive(errors, "maxTurnsPerUserPerMinute", maxTurnsPerUserPerMinute);
@@ -1502,6 +1531,62 @@ public class AssistantQBitConfig implements QBitConfig
/*******************************************************************************
** Whether the host's EXTERNAL approval rule allows a scheduled task's result
** to leave the app by email. There is no approval rule in the qbit yet (the
** scheduled runner is P-g), so this explicit flag stands in; default false.
*******************************************************************************/
public Boolean getEmailExternalApproved()
{
return (this.emailExternalApproved);
}
/*******************************************************************************
** Setter for emailExternalApproved
*******************************************************************************/
public void setEmailExternalApproved(Boolean emailExternalApproved)
{
this.emailExternalApproved = emailExternalApproved;
}
/*******************************************************************************
** Fluent setter for emailExternalApproved
*******************************************************************************/
public AssistantQBitConfig withEmailExternalApproved(Boolean emailExternalApproved)
{
this.emailExternalApproved = emailExternalApproved;
return (this);
}
/*******************************************************************************
** The hook that turns a task owner's user id into an email address; null
** means the default (an owner id that already is an address).
*******************************************************************************/
@JsonIgnore
public Function<String, String> getEmailRecipientResolver()
{
return (emailRecipientResolver);
}
/*******************************************************************************
** Fluent setter for emailRecipientResolver
*******************************************************************************/
public AssistantQBitConfig withEmailRecipientResolver(Function<String, String> emailRecipientResolver)
{
this.emailRecipientResolver = emailRecipientResolver;
return (this);
}
/*******************************************************************************
** Getter for allowedApiKeyEnvNames (extra API key environment variable names a provider row may reference)
*******************************************************************************/
@@ -1700,6 +1785,28 @@ public class AssistantQBitConfig implements QBitConfig
/*******************************************************************************
** Whether the host opts into record history; false by default.
*******************************************************************************/
public Boolean getRecordHistory()
{
return (recordHistory);
}
/*******************************************************************************
** Owner decision — hard wall: record history requires explicit host opt-in.
** kof22 does not opt in. The user's own audit permissions still apply.
*******************************************************************************/
public AssistantQBitConfig withRecordHistory(boolean recordHistory)
{
this.recordHistory = recordHistory;
return (this);
}
/*******************************************************************************
** Getter for hipaaMode
*******************************************************************************/
@@ -1927,4 +2034,223 @@ public class AssistantQBitConfig implements QBitConfig
this.scheduledTasksSchedulerName = scheduledTasksSchedulerName;
return (this);
}
/*******************************************************************************
** Getter for turnHeartbeatSeconds
*******************************************************************************/
public Integer getTurnHeartbeatSeconds()
{
return (this.turnHeartbeatSeconds);
}
/*******************************************************************************
** Setter for turnHeartbeatSeconds
*******************************************************************************/
public void setTurnHeartbeatSeconds(Integer turnHeartbeatSeconds)
{
this.turnHeartbeatSeconds = turnHeartbeatSeconds;
}
/*******************************************************************************
** Fluent setter for turnHeartbeatSeconds
*******************************************************************************/
public AssistantQBitConfig withTurnHeartbeatSeconds(Integer turnHeartbeatSeconds)
{
this.turnHeartbeatSeconds = turnHeartbeatSeconds;
return (this);
}
/*******************************************************************************
** Getter for turnLeaseSeconds
*******************************************************************************/
public Integer getTurnLeaseSeconds()
{
return (this.turnLeaseSeconds);
}
/*******************************************************************************
** Setter for turnLeaseSeconds
*******************************************************************************/
public void setTurnLeaseSeconds(Integer turnLeaseSeconds)
{
this.turnLeaseSeconds = turnLeaseSeconds;
}
/*******************************************************************************
** Fluent setter for turnLeaseSeconds
*******************************************************************************/
public AssistantQBitConfig withTurnLeaseSeconds(Integer turnLeaseSeconds)
{
this.turnLeaseSeconds = turnLeaseSeconds;
return (this);
}
/*******************************************************************************
** Getter for turnForceFinalizeGraceSeconds
*******************************************************************************/
public Integer getTurnForceFinalizeGraceSeconds()
{
return (this.turnForceFinalizeGraceSeconds);
}
/*******************************************************************************
** Setter for turnForceFinalizeGraceSeconds
*******************************************************************************/
public void setTurnForceFinalizeGraceSeconds(Integer turnForceFinalizeGraceSeconds)
{
this.turnForceFinalizeGraceSeconds = turnForceFinalizeGraceSeconds;
}
/*******************************************************************************
** Fluent setter for turnForceFinalizeGraceSeconds
*******************************************************************************/
public AssistantQBitConfig withTurnForceFinalizeGraceSeconds(Integer turnForceFinalizeGraceSeconds)
{
this.turnForceFinalizeGraceSeconds = turnForceFinalizeGraceSeconds;
return (this);
}
/*******************************************************************************
** Getter for shutdownGraceSeconds
*******************************************************************************/
public Integer getShutdownGraceSeconds()
{
return (this.shutdownGraceSeconds);
}
/*******************************************************************************
** Setter for shutdownGraceSeconds
*******************************************************************************/
public void setShutdownGraceSeconds(Integer shutdownGraceSeconds)
{
this.shutdownGraceSeconds = shutdownGraceSeconds;
}
/*******************************************************************************
** Fluent setter for shutdownGraceSeconds
*******************************************************************************/
public AssistantQBitConfig withShutdownGraceSeconds(Integer shutdownGraceSeconds)
{
this.shutdownGraceSeconds = shutdownGraceSeconds;
return (this);
}
/*******************************************************************************
** Getter for defaultConcurrencyMode
*******************************************************************************/
public String getDefaultConcurrencyMode()
{
return (this.defaultConcurrencyMode);
}
/*******************************************************************************
** Setter for defaultConcurrencyMode
*******************************************************************************/
public void setDefaultConcurrencyMode(String defaultConcurrencyMode)
{
this.defaultConcurrencyMode = defaultConcurrencyMode;
}
/*******************************************************************************
** Fluent setter for defaultConcurrencyMode
*******************************************************************************/
public AssistantQBitConfig withDefaultConcurrencyMode(String defaultConcurrencyMode)
{
this.defaultConcurrencyMode = defaultConcurrencyMode;
return (this);
}
/*******************************************************************************
** Getter for registerShutdownHook
*******************************************************************************/
public Boolean getRegisterShutdownHook()
{
return (this.registerShutdownHook);
}
/*******************************************************************************
** Setter for registerShutdownHook
*******************************************************************************/
public void setRegisterShutdownHook(Boolean registerShutdownHook)
{
this.registerShutdownHook = registerShutdownHook;
}
/*******************************************************************************
** Fluent setter for registerShutdownHook
*******************************************************************************/
public AssistantQBitConfig withRegisterShutdownHook(Boolean registerShutdownHook)
{
this.registerShutdownHook = registerShutdownHook;
return (this);
}
/*******************************************************************************
** Getter for runTracker
*******************************************************************************/
@JsonIgnore
public AssistantRunTracker getRunTracker()
{
return (this.runTracker == null ? AssistantRunTracker.NOOP : this.runTracker);
}
/*******************************************************************************
** Setter for runTracker
*******************************************************************************/
public void setRunTracker(AssistantRunTracker runTracker)
{
this.runTracker = runTracker;
}
/*******************************************************************************
** Fluent setter for runTracker
*******************************************************************************/
public AssistantQBitConfig withRunTracker(AssistantRunTracker runTracker)
{
this.runTracker = runTracker;
return (this);
}
}
@@ -25,10 +25,13 @@ import com.kingsrook.qbits.assistant.api.AssistantRoutes;
import com.kingsrook.qbits.assistant.developer.AssistantDeveloperPanels;
import com.kingsrook.qbits.assistant.home.AssistantAccessWidget;
import com.kingsrook.qbits.assistant.home.AssistantHome;
import com.kingsrook.qbits.assistant.metadata.AssistantChannelWall;
import com.kingsrook.qbits.assistant.metadata.AssistantHelp;
import com.kingsrook.qbits.assistant.metadata.AssistantInstanceMetaData;
import com.kingsrook.qbits.assistant.metadata.AssistantMetaDataBuilder;
import com.kingsrook.qbits.assistant.metadata.AssistantRecordScreens;
import com.kingsrook.qbits.assistant.model.AssistantBudget;
import com.kingsrook.qbits.assistant.processes.DataAccessDefaultsProcess;
import com.kingsrook.qbits.assistant.processes.DiscoverModelsProcess;
import com.kingsrook.qbits.assistant.processes.KnowledgeIndexProcess;
import com.kingsrook.qbits.assistant.processes.ScheduledTaskProcess;
@@ -41,6 +44,7 @@ import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerMultiOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaDataProducer;
@@ -178,7 +182,7 @@ public class AssistantQBitProducer implements QBitMetaDataProducer<AssistantQBit
QProcessMetaData testConnection = TestConnectionProcess.process();
testConnection.setSourceQBitName(qBitMetaData.getName());
qInstance.addProcess(testConnection);
for(QProcessMetaData process : List.of(DiscoverModelsProcess.process(), TestModelConnectionProcess.process()))
for(QProcessMetaData process : List.of(DiscoverModelsProcess.process(), TestModelConnectionProcess.process(), DataAccessDefaultsProcess.process()))
{
process.setSourceQBitName(qBitMetaData.getName());
qInstance.addProcess(process);
@@ -200,13 +204,44 @@ public class AssistantQBitProducer implements QBitMetaDataProducer<AssistantQBit
QAppMetaData app = builder.buildAdminApp(tables);
qInstance.addApp(app);
AssistantHelp.apply(qInstance);
AssistantChannelWall.register(qInstance);
if(Boolean.TRUE.equals(qBitConfig.getRecordHistory()))
{
enableRecordHistory(ClientChannelsMetaData.ofOrWithNew(qInstance));
}
postProduceActions(new MetaDataProducerMultiOutput(), qInstance);
return (new MetaDataProducerMultiOutput());
}
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1193, removeBy=RC.8): call withAssistantAuditReads() directly once the qbit builds on a QQQ RC that has it
*******************************************************************************/
private void enableRecordHistory(ClientChannelsMetaData channels)
{
try
{
channels.getClass().getMethod("withAssistantAuditReads").invoke(channels);
}
catch(NoSuchMethodException e)
{
List<String> denied = channels.getDeniedPatterns().get("assistant");
if(denied != null)
{
denied.removeIf("audit*"::equals);
}
}
catch(ReflectiveOperationException e)
{
throw (new IllegalStateException("Could not enable assistant audit reads.", e));
}
}
/*******************************************************************************
** Declare budget alerts as top-level core metadata for admin visibility.
*******************************************************************************/
@@ -17,8 +17,11 @@
package com.kingsrook.qbits.assistant;
import java.net.InetAddress;
import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -32,15 +35,16 @@ import com.kingsrook.qbits.assistant.engine.ProfileService;
import com.kingsrook.qbits.assistant.engine.ProviderService;
import com.kingsrook.qbits.assistant.engine.RateLimiter;
import com.kingsrook.qbits.assistant.engine.RunningTurn;
import com.kingsrook.qbits.assistant.metadata.AssistantChannelWall;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.rag.InMemoryVectorStore;
import com.kingsrook.qbits.assistant.rag.RagService;
import com.kingsrook.qbits.assistant.rag.VectorStore;
import com.kingsrook.qbits.assistant.scheduled.ScheduledTurn;
import com.kingsrook.qbits.assistant.tools.KnowledgeTool;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
import com.kingsrook.qbits.assistant.uiapi.LoopbackUiApiGateway;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qbits.assistant.uiapi.CoreUiApiGateway;
import com.kingsrook.qbits.assistant.uiapi.UiApiCall;
import com.kingsrook.qbits.assistant.uiapi.UiApiGateway;
import com.kingsrook.qbits.assistant.uiapi.UiApiResult;
@@ -49,6 +53,7 @@ import com.kingsrook.qqq.backend.core.actions.ai.AiToolKernelSettings;
import com.kingsrook.qqq.backend.core.actions.ai.exposure.AiExposurePolicy;
import com.kingsrook.qqq.backend.core.actions.ai.output.AiRedactor;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
@@ -61,6 +66,11 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
*******************************************************************************/
public class AssistantRuntime
{
private static final QLogger LOG = QLogger.getLogger(AssistantRuntime.class);
private final String instanceId = instanceId();
private volatile boolean shuttingDown;
private Thread shutdownHook;
private final ScheduledTurn scheduledTurn = new ScheduledTurn();
private final RagService ragService;
@@ -103,10 +113,21 @@ public class AssistantRuntime
*******************************************************************************/
public AssistantRuntime(QInstance qInstance, AssistantQBitConfig config, Clock clock)
{
this(qInstance, config, clock, new AssistantStore(config));
}
/*******************************************************************************
** Explicit persistence collaborator for embedded runtimes and fault tests.
*******************************************************************************/
public AssistantRuntime(QInstance qInstance, AssistantQBitConfig config, Clock clock, AssistantStore store)
{
AssistantChannelWall.validate(qInstance);
this.qInstance = qInstance;
this.config = config;
this.clock = clock;
this.store = new AssistantStore(config);
this.store = store;
this.policyService = new PolicyService(config, store, clock);
this.providerService = new ProviderService(config, store, clock);
this.budgetService = new BudgetService(store, providerService, clock);
@@ -120,7 +141,7 @@ public class AssistantRuntime
this.accessExplainer = new AccessExplainer(qInstance, dataAccessService);
this.toolbox = new UiApiToolbox(qInstance, dataAccessService, exposurePolicy, new AiRedactor(settings.getCustomRedactionPatterns()),
config.getMaxCellChars() == null ? AiToolKernelSettings.DEFAULT_MAX_CELL_CHARS : config.getMaxCellChars());
UiApiGateway delegate = config.getUiApiGateway() != null ? config.getUiApiGateway() : new LoopbackUiApiGateway(this::uiApiBaseUrl, qInstance);
UiApiGateway delegate = config.getUiApiGateway() != null ? config.getUiApiGateway() : new CoreUiApiGateway(this::uiApiBaseUrl, qInstance);
this.uiApiGateway = new UiApiGateway()
{
/*******************************************************************************
@@ -141,11 +162,11 @@ public class AssistantRuntime
String channel = scheduledTurn.channel(call.getSessionUUID());
if(channel != null)
{
if(delegate instanceof LoopbackUiApiGateway loopback)
if(!(delegate instanceof CoreUiApiGateway))
{
return (loopback.invokeWithClient(call, channel));
throw (new QException("Scheduled tasks require the core UI API gateway for client attribution."));
}
throw (new QException("Scheduled tasks require the loopback gateway for client attribution."));
call.withClientDetail(channel.substring(CoreUiApiGateway.CLIENT_CHANNEL.length() + 1));
}
return (delegate.invoke(call));
}
@@ -155,6 +176,21 @@ public class AssistantRuntime
this.knowledgeTool = new KnowledgeTool(this, ragService, vectors);
this.bulkLoadTools = new BulkLoadTools(qInstance, dataAccessService, config.getBulkLoadRunner());
this.contextBuilder = new ContextBuilder(config, kernel, toolbox).withKnowledgeTool(knowledgeTool).withBulkLoadTools(bulkLoadTools);
if(Boolean.TRUE.equals(config.getRegisterShutdownHook()))
{
shutdownHook = new Thread(() ->
{
try
{
shutdown(Duration.ofSeconds(config.getShutdownGraceSeconds()));
}
catch(Throwable ignored)
{
// Shutdown must never fail the JVM hook.
}
}, "assistant-shutdown-" + instanceId);
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
@@ -310,8 +346,13 @@ public class AssistantRuntime
/*******************************************************************************
** Track a turn running here.
*******************************************************************************/
public RunningTurn register(RunningTurn turn)
public synchronized RunningTurn register(RunningTurn turn)
{
if(shuttingDown)
{
turn.forceFinalize("SHUTDOWN");
return (turn);
}
runningTurns.put(turn.getTurnId(), turn);
return (turn);
}
@@ -343,7 +384,17 @@ public class AssistantRuntime
*******************************************************************************/
public void cancelAll(String reason)
{
runningTurns.values().forEach(t -> t.cancel(reason));
runningTurns.values().forEach(t ->
{
try
{
t.cancel(reason);
}
catch(Exception e)
{
LOG.warn("Assistant cancellation failed; finalization will still run");
}
});
}
@@ -353,8 +404,7 @@ public class AssistantRuntime
*******************************************************************************/
public void close()
{
runningTurns.values().forEach(t -> t.cancel("SHUTDOWN"));
executor.shutdownNow();
shutdown(Duration.ZERO);
}
@@ -502,4 +552,97 @@ public class AssistantRuntime
return (bulkLoadTools);
}
/*******************************************************************************
** Stop accepting work, cancel, wait a bounded grace, then force finalization.
*******************************************************************************/
public void shutdown(Duration grace)
{
synchronized(this)
{
shuttingDown = true;
}
cancelAll("SHUTDOWN");
long until = System.nanoTime() + Math.max(0, grace.toNanos());
while(!runningTurns.isEmpty() && System.nanoTime() < until)
{
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
break;
}
}
runningTurns.values().forEach(t ->
{
try
{
t.forceFinalize("SHUTDOWN");
}
catch(Exception e)
{
LOG.warn("Assistant shutdown finalization failed");
}
});
executor.shutdownNow();
if(shutdownHook != null && Thread.currentThread() != shutdownHook)
{
try
{
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
catch(IllegalStateException ignored)
{
// The JVM is already shutting down.
}
}
}
/*******************************************************************************
** Getter for shuttingDown
*******************************************************************************/
public boolean isShuttingDown()
{
return (shuttingDown);
}
/*******************************************************************************
** Getter for instanceId
*******************************************************************************/
public String getInstanceId()
{
return (instanceId);
}
/*******************************************************************************
** A stable, bounded hostname plus a per-runtime random suffix.
*******************************************************************************/
private static String instanceId()
{
String host = System.getenv("HOSTNAME");
if(!StringUtils.hasContent(host))
{
try
{
host = InetAddress.getLocalHost().getHostName();
}
catch(Exception ignored)
{
host = "unknown";
}
}
return (host.substring(0, Math.min(87, host.length())) + ":" + UUID.randomUUID().toString().substring(0, 8));
}
}
@@ -31,6 +31,7 @@ import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.specs.invoke.UiApiCredentials;
/*******************************************************************************
@@ -92,7 +93,27 @@ public class AccessExplainer
*******************************************************************************/
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, PolicyService.ToolPolicy policy, String tableName, String prompt) throws QException
{
UiApiResult response = gateway.invoke(new UiApiCall("GET", "/metaData").withSessionUUID(sessionUUID).withInvokedBy("assistant-explain"));
return (explain(gateway, sessionUUID, null, policy, tableName, prompt));
}
/*******************************************************************************
** Explain, with the caller's request credentials when they are known.
*******************************************************************************/
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, UiApiCredentials credentials, PolicyService.ToolPolicy policy, String tableName, String prompt) throws QException
{
return (explain(gateway, sessionUUID, credentials, policy, tableName, prompt, null));
}
/*******************************************************************************
** Preserve a known turn's attribution on the metadata request.
*******************************************************************************/
public List<TableAccess> explain(UiApiGateway gateway, String sessionUUID, UiApiCredentials credentials, PolicyService.ToolPolicy policy, String tableName, String prompt, String turnId) throws QException
{
UiApiResult response = gateway.invoke(new UiApiCall("GET", "/metaData").withSessionUUID(sessionUUID).withCredentials(credentials).withInvokedBy("assistant-explain").withClientDetail(turnId));
if(!response.isSuccess())
{
throw (new QException("GET /metaData answered HTTP " + response.status() + (response.errorMessage() == null ? "" : ": " + response.errorMessage())));
@@ -17,11 +17,14 @@
package com.kingsrook.qbits.assistant.api;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
@@ -51,10 +54,13 @@ import com.kingsrook.qqq.backend.core.actions.ai.AiToolOutcome;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolResult;
import com.kingsrook.qqq.backend.core.actions.ai.output.AiRedactor;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.specs.invoke.UiApiCredentials;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
@@ -64,6 +70,8 @@ import com.kingsrook.qqq.backend.core.utils.StringUtils;
*******************************************************************************/
public class AssistantApi
{
private static final QLogger LOG = QLogger.getLogger(AssistantApi.class);
public static final int TITLE_MAX_CHARS = 60;
private final AssistantRuntime runtime;
@@ -71,6 +79,7 @@ public class AssistantApi
private final AssistantStore store;
private final QSession session;
private final String userId;
private UiApiCredentials credentials;
@@ -93,6 +102,18 @@ public class AssistantApi
/*******************************************************************************
** The credentials of the request this API serves, exactly as they came in;
** the tools forward them to the UI API. Never logged.
*******************************************************************************/
public AssistantApi withCredentials(UiApiCredentials credentials)
{
this.credentials = credentials;
return (this);
}
/*******************************************************************************
** GET /config - the feature probe. Never throws for a signed-in user.
*******************************************************************************/
@@ -275,6 +296,19 @@ public class AssistantApi
public RunningTurn startTurn(Integer conversationId, Map<String, Object> body) throws QException, AssistantApiException
{
requireAccess();
if(runtime.isShuttingDown())
{
throw (new AssistantApiException(503, "SHUTTING_DOWN", "The server is restarting. Try again in a moment."));
}
String concurrency = config.getDefaultConcurrencyMode();
if(body.containsKey("concurrency"))
{
if(!(body.get("concurrency") instanceof String mode) || !("supersede".equalsIgnoreCase(mode) || "concurrent".equalsIgnoreCase(mode)))
{
throw (new AssistantApiException(400, "concurrency must be supersede or concurrent."));
}
concurrency = mode.toUpperCase(Locale.ROOT);
}
AssistantConversation conversation = requireConversation(conversationId);
if(!(body.get("text") instanceof String text) || !StringUtils.hasContent(text))
@@ -310,25 +344,36 @@ public class AssistantApi
throw (new AssistantApiException(429, "BUDGET", budget.message()));
}
long running = 0;
for(AssistantTurn other : store.listRunningTurns(userId))
{
if(isRunning(reapIfOrphaned(other)))
{
running++;
}
}
if(running >= config.getMaxConcurrentTurnsPerUser())
{
throw (new AssistantApiException(429, "RATE_LIMIT", "You already have an assistant answer in progress. Wait for it to finish or stop it."));
}
String limited = runtime.getRateLimiter().tryAcquire(userId, config.getMaxTurnsPerUserPerMinute(), config.getMaxConcurrentTurnsPerUser());
if(limited != null)
{
throw (new AssistantApiException(429, "RATE_LIMIT", limited));
}
List<AssistantTurn> remaining = new ArrayList<>();
for(AssistantTurn other : store.listRunningTurns(userId))
{
other = reapIfOrphaned(other);
if(!isRunning(other) || "SUPERSEDED".equals(other.getCancelReason()))
{
continue;
}
if("SUPERSEDE".equals(concurrency) && conversationId.equals(other.getConversationId()))
{
requestStop(other, "SUPERSEDED");
}
else
{
remaining.add(other);
}
}
remaining.sort(Comparator.comparing(AssistantTurn::getStartedAt, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(AssistantTurn::getId));
while(remaining.size() >= config.getMaxConcurrentTurnsPerUser())
{
requestStop(remaining.removeFirst(), "SUPERSEDED");
}
try
{
if(!StringUtils.hasContent(conversation.getTitle()))
@@ -347,13 +392,18 @@ public class AssistantApi
.withSeq(seq)
.withPartsJson(new MessageParts().addText(text).toJson()));
Instant startedAt = runtime.getClock().instant();
AssistantTurn turn = store.insert(new AssistantTurn()
.withConversationId(conversationId)
.withUserId(userId)
.withUserMessageId(userMessage.getId())
.withStatus("RUNNING")
.withModel(active.model())
.withStartedAt(runtime.getClock().instant())
.withStartedAt(startedAt)
.withHeartbeatAt(startedAt)
.withLeaseOwner(runtime.getInstanceId())
.withPhase("starting")
.withConcurrencyMode(concurrency)
.withToolCallCount(0)
.withModelCallCount(0));
@@ -371,10 +421,37 @@ public class AssistantApi
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord().withValue("id", turn.getId()).withValue("assistantMessageId", assistantMessage.getId()));
turn.setAssistantMessageId(assistantMessage.getId());
RunningTurn runningTurn = runtime.register(new RunningTurn(turn.getId(), userId));
RunningTurn runningTurn = new RunningTurn(turn.getId(), userId);
TurnEngine engine = new TurnEngine(runtime, session, userId, conversation, userMessage, assistantMessage, turn, text, pageContext, policy, runningTurn,
budget.softExceeded() ? budget.message() : null);
runtime.getExecutor().submit(engine);
budget.softExceeded() ? budget.message() : null).withCredentials(credentials);
try
{
if(config.getRunTracker() != null)
{
///////////////////////////////////////////////////////////////////
// never the conversation title: it is derived from the prompt //
///////////////////////////////////////////////////////////////////
runningTurn.setTrackingId(config.getRunTracker().start(userId, turn.getId(), conversationId, "Assistant answer"));
config.getRunTracker().onCancel(runningTurn.getTrackingId(), () -> runningTurn.cancel("USER"));
}
}
catch(Exception e)
{
LOG.warn("Assistant run tracker start failed", logPair("turnId", turn.getId()));
}
runtime.register(runningTurn);
if(!runningTurn.isFinalized())
{
try
{
runtime.getExecutor().submit(engine);
}
catch(RuntimeException e)
{
runningTurn.forceFinalize("SHUTDOWN");
throw (e);
}
}
return (runningTurn);
}
catch(QException | RuntimeException e)
@@ -429,22 +506,94 @@ public class AssistantApi
{
requireAccess();
AssistantTurn turn = requireTurn(turnId);
if(runtime.getRunningTurn(turnId) == null)
if(isRunning(turn))
{
turn = requestStop(turn, "USER");
}
return (Map.of("status", turn.getStatus()));
}
/*******************************************************************************
** Durable Stop, shared by the API and superseding another question.
*******************************************************************************/
private AssistantTurn requestStop(AssistantTurn turn, String reason) throws QException
{
synchronized(store)
{
turn = store.getTurn(userId, turn.getId());
if(!isRunning(turn))
{
return (turn);
}
RunningTurn live = runtime.getRunningTurn(turn.getId());
if(live == null && orphaned(turn))
{
return (reap(turn, reason));
}
Instant now = runtime.getClock().instant();
if(!store.updateRunningTurn(userId, new QRecord().withValue("id", turn.getId())
.withValue("status", "CANCELLING").withValue("cancelReason", reason).withValue("cancelRequestedAt", now)))
{
return (store.getTurn(userId, turn.getId()));
}
turn.setStatus("CANCELLING");
turn.setCancelReason(reason);
turn.setCancelRequestedAt(now);
if(live != null)
{
try
{
live.cancel(reason);
}
catch(Exception e)
{
LOG.warn("Assistant stream cancellation failed; watchdog will finalize");
}
}
return (turn);
}
}
/*******************************************************************************
** GET /turns/active: the caller's runs, newest first, after orphan recovery.
*******************************************************************************/
public Map<String, Object> activeTurns() throws QException, AssistantApiException
{
requireAccess();
List<AssistantTurn> turns = new ArrayList<>();
for(AssistantTurn turn : store.listRunningTurns(userId))
{
turn = reapIfOrphaned(turn);
if(isRunning(turn))
{
turns.add(turn);
}
}
if(!isRunning(turn))
turns.sort(Comparator.comparing(AssistantTurn::getStartedAt, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(AssistantTurn::getId).reversed());
List<Map<String, Object>> rows = new ArrayList<>();
for(AssistantTurn turn : turns)
{
throw (new AssistantApiException(409, "This answer has already finished."));
RunningTurn live = runtime.getRunningTurn(turn.getId());
Map<String, Object> row = new LinkedHashMap<>();
row.put("turnId", turn.getId());
row.put("conversationId", turn.getConversationId());
row.put("assistantMessageId", turn.getAssistantMessageId());
row.put("userMessageId", turn.getUserMessageId());
row.put("status", turn.getStatus());
row.put("phase", live == null ? turn.getPhase() : live.getPhase());
row.put("startedAt", turn.getStartedAt() == null ? null : turn.getStartedAt().toString());
row.put("heartbeatAt", turn.getHeartbeatAt() == null ? null : turn.getHeartbeatAt().toString());
row.put("elapsedMs", turn.getStartedAt() == null ? 0 : Math.max(0, Duration.between(turn.getStartedAt(), runtime.getClock().instant()).toMillis()));
row.put("live", live != null);
row.put("concurrencyMode", turn.getConcurrencyMode());
rows.add(row);
}
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord().withValue("id", turnId).withValue("status", "CANCELLING"));
RunningTurn live = runtime.getRunningTurn(turnId);
if(live != null && userId.equals(live.getUserId()))
{
live.cancel("USER");
}
return (Map.of("status", "CANCELLING"));
return (Map.of("turns", rows));
}
@@ -460,60 +609,104 @@ public class AssistantApi
/*******************************************************************************
** A turn whose replica died: it still says RUNNING / CANCELLING, no turn
** of this runtime owns it, and it started longer ago than maxTurnSeconds
** + 60 s (a live engine always ends itself by then). On first sight it is
** finished as ERROR: the assistant message gets status ERROR and a
** notice, and synthetic error (INTERNAL) + message.end events are
** persisted, so replays end. Returns the (possibly updated) turn.
** A remote run loses its lease, exceeds the absolute deadline, or has a
** cancellation request that its owner did not acknowledge in time.
*******************************************************************************/
private boolean orphaned(AssistantTurn turn)
{
Instant now = runtime.getClock().instant();
Instant heartbeat = turn.getHeartbeatAt() == null ? turn.getStartedAt() : turn.getHeartbeatAt();
return ((heartbeat != null && heartbeat.isBefore(now.minusSeconds(config.getTurnLeaseSeconds())))
|| (turn.getStartedAt() != null && turn.getStartedAt().isBefore(now.minusSeconds(maxStreamSeconds())))
|| ("CANCELLING".equals(turn.getStatus()) && turn.getCancelRequestedAt() != null
&& turn.getCancelRequestedAt().isBefore(now.minusSeconds(config.getTurnLeaseSeconds()))));
}
/*******************************************************************************
** Recover an abandoned run and leave a terminal replay for refreshes.
*******************************************************************************/
AssistantTurn reapIfOrphaned(AssistantTurn turn) throws QException
{
if(!isRunning(turn) || runtime.getRunningTurn(turn.getId()) != null || turn.getStartedAt() == null)
synchronized(store)
{
return (turn);
}
Instant stale = runtime.getClock().instant().minusSeconds(config.getMaxTurnSeconds() + 60L);
if(!turn.getStartedAt().isBefore(stale))
{
return (turn);
}
String text = "This answer was interrupted (the server restarted). Ask again.";
if(turn.getAssistantMessageId() != null)
{
AssistantMessage message = store.getMessage(userId, turn.getAssistantMessageId());
if(message != null)
if(!isRunning(turn) || runtime.getRunningTurn(turn.getId()) != null || !orphaned(turn))
{
store.updateFields(AssistantMessage.TABLE_NAME, new QRecord()
.withValue("id", message.getId())
.withValue("status", "ERROR")
.withValue("partsJson", MessageParts.fromJson(message.getPartsJson()).addNotice("error", text).toJson()));
return (turn);
}
String reason = "CANCELLING".equals(turn.getStatus()) && turn.getCancelRequestedAt() != null
&& turn.getCancelRequestedAt().isBefore(runtime.getClock().instant().minusSeconds(config.getTurnLeaseSeconds()))
? (turn.getCancelReason() == null ? "USER" : turn.getCancelReason()) : null;
return (reap(turn, reason));
}
}
/*******************************************************************************
** Re-read before recovery; never overwrite an already terminal row or
** append another terminal event. Each persistence step is independent.
*******************************************************************************/
private AssistantTurn reap(AssistantTurn turn, String cancelReason) throws QException
{
AssistantTurn current = store.getTurn(userId, turn.getId());
if(!isRunning(current))
{
return (current);
}
if(!orphaned(current))
{
return (cancelReason == null ? current : requestStop(current, cancelReason));
}
String status = cancelReason == null ? "ERROR" : "CANCELLED";
String text = cancelReason == null ? "This answer was interrupted (the server restarted). Ask again."
: ("SUPERSEDED".equals(cancelReason) ? TurnEngine.SUPERSEDED_TEXT : "Stopped by you.");
if(current.getAssistantMessageId() != null)
{
try
{
AssistantMessage message = store.getMessage(userId, current.getAssistantMessageId());
if(message != null)
{
store.updateFields(AssistantMessage.TABLE_NAME, new QRecord().withValue("id", message.getId()).withValue("status", status)
.withValue("partsJson", MessageParts.fromJson(message.getPartsJson()).addNotice(cancelReason == null ? "error" : "info", text).toJson()));
}
}
catch(Exception e)
{
LOG.warn("Could not persist recovered assistant message");
}
}
int seq = store.lastEventSeq(userId, turn.getId());
store.insertEvent(turn.getId(), userId, seq + 1, TurnEvent.ERROR, new TurnEvent(seq + 1, TurnEvent.ERROR, Map.of("code", "INTERNAL", "message", text)).toJson());
Map<String, Object> end = new java.util.LinkedHashMap<>();
if(turn.getAssistantMessageId() != null)
try
{
end.put("messageId", turn.getAssistantMessageId());
int seq = store.lastEventSeq(userId, current.getId());
List<AssistantTurnEvent> last = store.listEvents(userId, current.getId(), Math.max(0, seq - 1), 1);
if(last.isEmpty() || !TurnEvent.MESSAGE_END.equals(last.getFirst().getEventType()))
{
if(cancelReason == null)
{
seq++;
store.insertEvent(current.getId(), userId, seq, TurnEvent.ERROR,
new TurnEvent(seq, TurnEvent.ERROR, Map.of("code", "INTERNAL", "message", text)).toJson());
}
seq++;
Map<String, Object> end = new LinkedHashMap<>();
end.put("messageId", current.getAssistantMessageId());
end.put("status", status);
end.put("stopReason", cancelReason == null ? "interrupted" : "cancelled");
store.insertEvent(current.getId(), userId, seq, TurnEvent.MESSAGE_END, new TurnEvent(seq, TurnEvent.MESSAGE_END, end).toJson());
}
}
catch(Exception e)
{
LOG.warn("Could not persist recovered assistant events");
}
end.put("status", "ERROR");
end.put("stopReason", "interrupted");
store.insertEvent(turn.getId(), userId, seq + 2, TurnEvent.MESSAGE_END, new TurnEvent(seq + 2, TurnEvent.MESSAGE_END, end).toJson());
Instant now = runtime.getClock().instant();
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord()
.withValue("id", turn.getId())
.withValue("status", "ERROR")
.withValue("errorCode", "INTERNAL")
.withValue("stopReason", "interrupted")
.withValue("endedAt", now));
turn.setStatus("ERROR");
turn.setErrorCode("INTERNAL");
turn.setEndedAt(now);
return (turn);
store.updateRunningTurn(userId, new QRecord().withValue("id", current.getId()).withValue("status", status)
.withValue("errorCode", cancelReason == null ? "INTERNAL" : null).withValue("cancelReason", cancelReason)
.withValue("stopReason", cancelReason == null ? "interrupted" : "cancelled").withValue("phase", "done").withValue("endedAt", now));
return (store.getTurn(userId, current.getId()));
}
@@ -598,7 +791,7 @@ public class AssistantApi
throw (new QException("The stored values of action " + id + " are not valid JSON", e));
}
PolicyService.EffectivePolicy policy = runtime.getPolicyService().current(true);
UiApiToolbox.Context context = new UiApiToolbox.Context(session.getUuid(), session.getValue(QSession.VALUE_KEY_USER_TIMEZONE), runtime.getUiApiGateway(), policy.tools(), null);
UiApiToolbox.Context context = new UiApiToolbox.Context(session.getUuid(), session.getValue(QSession.VALUE_KEY_USER_TIMEZONE), runtime.getUiApiGateway(), policy.tools(), null, credentials, action.getTurnId() == null ? null : String.valueOf(action.getTurnId()));
UiApiToolbox.Outcome outcome = BulkLoadTools.WRITE_TOOLS.contains(action.getToolName())
? runtime.getBulkLoadTools().executeConfirmed(context, action.getToolCallId(), action.getToolName(), action.getTableName(), values)
: runtime.getToolbox().executeConfirmedWrite(context, action.getToolCallId(), action.getToolName(), action.getTableName(), action.getRecordId(), values);
@@ -613,6 +806,7 @@ public class AssistantApi
store.insert(new AssistantToolCall()
.withTurnId(action.getTurnId())
.withClientChannel("assistant" + (action.getTurnId() == null ? "" : "/" + action.getTurnId()))
.withConversationId(action.getConversationId())
.withUserId(userId)
.withToolCallId(action.getToolCallId())
@@ -719,10 +913,24 @@ public class AssistantApi
** reason.
*******************************************************************************/
public Map<String, Object> access(String table, String prompt) throws QException, AssistantApiException
{
return (access(table, prompt, null));
}
/*******************************************************************************
** A supplied turn must belong to this user before using it for attribution.
*******************************************************************************/
public Map<String, Object> access(String table, String prompt, Integer turnId) throws QException, AssistantApiException
{
requireAccess();
if(turnId != null)
{
requireTurn(turnId);
}
List<Map<String, Object>> tables = new ArrayList<>();
for(AccessExplainer.TableAccess access : runtime.getAccessExplainer().explain(runtime.getUiApiGateway(), session.getUuid(), runtime.getPolicyService().current(false).tools(), table, prompt))
for(AccessExplainer.TableAccess access : runtime.getAccessExplainer().explain(runtime.getUiApiGateway(), session.getUuid(), credentials, runtime.getPolicyService().current(false).tools(), table, prompt, turnId == null ? null : String.valueOf(turnId)))
{
if(!access.uiVisible() && access.mode() == DataAccessMode.NONE)
{
@@ -757,6 +965,16 @@ public class AssistantApi
/*******************************************************************************
** Hard upper bound for remote stream polling and stale-run recovery.
*******************************************************************************/
public long maxStreamSeconds()
{
return (config.getMaxTurnSeconds() + (long) config.getTurnForceFinalizeGraceSeconds() + config.getTurnLeaseSeconds());
}
/*******************************************************************************
** The user may use the panel: enabled, signed in, assistant.hasAccess.
*******************************************************************************/
@@ -17,63 +17,27 @@
package com.kingsrook.qbits.assistant.api;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.engine.RunningTurn;
import com.kingsrook.qbits.assistant.engine.TurnEvent;
import com.kingsrook.qbits.assistant.engine.TurnEventLog;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface;
import com.kingsrook.qqq.middleware.javalin.QJavalinUtils;
import com.kingsrook.qqq.middleware.javalin.executors.ExecutorSessionUtils;
import io.javalin.config.JavalinConfig;
import io.javalin.http.ContentType;
import io.javalin.http.Context;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Javalin routes under /qqq/v1/assistant (contract section 3).
**
** Every request gets the user's own session from the instance's
** authentication module (ExecutorSessionUtils.setupSession: session cookie,
** bearer token or API key) - never a system session. Bodies must be JSON
** (a cross-site form cannot send that without a CORS preflight).
**
** Streams (POST /conversations/{id}/turns, GET /turns/{id}/events) are
** Server-Sent Events written to the response as they happen: "id: seq",
** "event: type", "data: json", a blank line; a ping every 15 seconds;
** Cache-Control no-cache and X-Accel-Buffering no (proxies must not
** buffer; give the route a long idle timeout). The turn itself runs on its
** own thread, so a client disconnect does not stop it; the client resumes
** with /events?after=<last seq>.
**
** Request and response bodies are never logged.
** No routes any more: the assistant's endpoints are spec'd /qqq/v1
** operations ({@link com.kingsrook.qbits.assistant.api.specs.AssistantSpecs}).
** What is left is a before-handler that learns this server's local port from
** the first /qqq/v1 request, so the tools (and Explain access) can call the
** UI API on 127.0.0.1 before any assistant operation has run.
*******************************************************************************/
public class AssistantRouteProvider implements QJavalinRouteProviderInterface
{
private static final QLogger LOG = QLogger.getLogger(AssistantRouteProvider.class);
public static final String BASE_PATH = "/qqq/v1/assistant";
public static final long PING_MILLIS = 15_000;
public static final long REMOTE_POLL_MS = 1_000;
public static final String BASE_PATH = "/qqq/v1/assistant";
private QInstance qInstance;
private long pingMillis = PING_MILLIS;
@@ -88,28 +52,12 @@ public class AssistantRouteProvider implements QJavalinRouteProviderInterface
/*******************************************************************************
** Ping interval (tests use a short one).
*******************************************************************************/
public AssistantRouteProvider withPingMillis(long pingMillis)
{
this.pingMillis = pingMillis;
return (this);
}
/*******************************************************************************
**
*******************************************************************************/
@Override
public void acceptJavalinConfig(JavalinConfig config)
{
///////////////////////////////////////////////////////////////////////
// learn this server's local port from the first UI request (e.g. //
// the metaData load), so tools and Explain access can loop back to //
// /qqq/v1 before any assistant route has been called //
///////////////////////////////////////////////////////////////////////
config.routes.before("/qqq/v1/*", ctx ->
{
AssistantRuntime runtime = AssistantRuntime.of(qInstance);
@@ -125,412 +73,6 @@ public class AssistantRouteProvider implements QJavalinRouteProviderInterface
}
}
});
config.routes.get(BASE_PATH + "/config", ctx -> json(ctx, false, (api, body) -> api.config()));
config.routes.get(BASE_PATH + "/conversations", ctx -> json(ctx, false, (api, body) -> api.listConversations(ctx.queryParam("status"))));
config.routes.post(BASE_PATH + "/conversations", ctx -> json(ctx, true, (api, body) ->
{
ctx.status(201);
return (api.createConversation(body));
}));
config.routes.get(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, false, (api, body) -> api.getConversation(pathInt(ctx, "id"), queryInt(ctx, "before"), queryInt(ctx, "limit"))));
config.routes.patch(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, true, (api, body) -> api.patchConversation(pathInt(ctx, "id"), body)));
config.routes.delete(BASE_PATH + "/conversations/{id}", ctx -> json(ctx, false, (api, body) ->
{
api.deleteConversation(pathInt(ctx, "id"));
ctx.status(204);
return (null);
}));
config.routes.post(BASE_PATH + "/conversations/{id}/turns", this::startTurn);
config.routes.get(BASE_PATH + "/turns/{turnId}/events", this::turnEvents);
config.routes.post(BASE_PATH + "/turns/{turnId}/cancel", ctx -> json(ctx, true, (api, body) ->
{
ctx.status(202);
return (api.cancelTurn(pathInt(ctx, "turnId")));
}));
config.routes.get(BASE_PATH + "/access", ctx -> json(ctx, false, (api, body) -> api.access(ctx.queryParam("table"), ctx.queryParam("prompt"))));
config.routes.get(BASE_PATH + "/actions/{id}", ctx -> json(ctx, false, (api, body) -> api.getAction(pathInt(ctx, "id"))));
config.routes.post(BASE_PATH + "/actions/{id}/confirm", ctx -> json(ctx, true, (api, body) -> api.confirmAction(pathInt(ctx, "id"))));
config.routes.post(BASE_PATH + "/actions/{id}/reject", ctx -> json(ctx, true, (api, body) -> api.rejectAction(pathInt(ctx, "id"))));
config.routes.post(BASE_PATH + "/messages/{id}/feedback", ctx -> json(ctx, true, (api, body) ->
{
api.feedback(pathInt(ctx, "id"), body);
ctx.status(204);
return (null);
}));
}
/*******************************************************************************
** Session, runtime, body, handler, JSON - or the error.
*******************************************************************************/
private void json(Context context, boolean readsBody, Handler handler)
{
try
{
AssistantApi api = api(context);
Map<String, Object> body = readsBody ? readJsonBody(context) : Map.of();
Object result = handler.handle(api, body);
if(result != null)
{
context.contentType(ContentType.APPLICATION_JSON);
context.result(JsonUtils.toJsonCustomized(result, builder -> builder.serializationInclusion(JsonInclude.Include.ALWAYS)));
}
}
catch(Exception e)
{
handleException(context, e);
}
finally
{
QContext.clear();
}
}
/*******************************************************************************
** POST /conversations/{id}/turns
*******************************************************************************/
private void startTurn(Context context)
{
RunningTurn turn;
try
{
AssistantApi api = api(context);
turn = api.startTurn(pathInt(context, "id"), readJsonBody(context));
}
catch(Exception e)
{
handleException(context, e);
QContext.clear();
return;
}
QContext.clear();
streamLive(context, turn.getLog(), 0);
}
/*******************************************************************************
** GET /turns/{turnId}/events?after=
*******************************************************************************/
private void turnEvents(Context context)
{
Integer turnId;
int after;
AssistantApi api;
AssistantApi.TurnEvents events;
try
{
api = api(context);
turnId = pathInt(context, "turnId");
Integer afterParam = queryInt(context, "after");
after = afterParam == null ? 0 : Math.max(0, afterParam);
events = api.turnEvents(turnId, after);
}
catch(Exception e)
{
handleException(context, e);
QContext.clear();
return;
}
if(events.live() != null)
{
QContext.clear();
streamLive(context, events.live().getLog(), after);
return;
}
///////////////////////////////////////////////////////////////////////
// persisted events; if the turn still runs on another replica, poll //
///////////////////////////////////////////////////////////////////////
try
{
OutputStream out = startStream(context);
int last = after;
long lastWrite = System.currentTimeMillis();
long giveUpAt = System.currentTimeMillis() + (api.maxTurnSeconds() + 60L) * 1000L;
AssistantApi.TurnEvents current = events;
while(true)
{
boolean ended = false;
for(TurnEvent event : current.persisted())
{
write(out, event.toSseFrame());
last = event.getSeq();
lastWrite = System.currentTimeMillis();
ended |= event.isTerminal();
}
if(ended || (current.finished() && !current.more()) || System.currentTimeMillis() > giveUpAt)
{
return;
}
if(!current.more())
{
Thread.sleep(REMOTE_POLL_MS);
}
if(System.currentTimeMillis() - lastWrite >= pingMillis)
{
write(out, ping());
lastWrite = System.currentTimeMillis();
}
current = api.turnEvents(turnId, last);
if(current.live() != null)
{
QContext.clear();
writeLive(out, current.live().getLog(), last);
return;
}
}
}
catch(IOException e)
{
LOG.debug("Assistant event stream closed by the client", logPair("turnId", turnId));
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch(Exception e)
{
LOG.warn("Assistant event replay failed", e, logPair("turnId", turnId));
}
finally
{
QContext.clear();
}
}
/*******************************************************************************
** Stream a live log from a sequence number until message.end.
*******************************************************************************/
private void streamLive(Context context, TurnEventLog log, int after)
{
try
{
writeLive(startStream(context), log, after);
}
catch(IOException e)
{
LOG.debug("Assistant stream closed by the client (the turn continues)");
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
/*******************************************************************************
**
*******************************************************************************/
private void writeLive(OutputStream out, TurnEventLog log, int after) throws IOException, InterruptedException
{
int last = after;
while(true)
{
List<TurnEvent> events = log.after(last, pingMillis);
if(events.isEmpty())
{
if(log.isClosed())
{
return;
}
write(out, ping());
continue;
}
for(TurnEvent event : events)
{
write(out, event.toSseFrame());
last = event.getSeq();
if(event.isTerminal())
{
return;
}
}
}
}
/*******************************************************************************
** Start an SSE response.
*******************************************************************************/
private static OutputStream startStream(Context context) throws IOException
{
context.status(200);
context.disableCompression();
context.res().setContentType("text/event-stream; charset=utf-8");
context.res().setHeader("Cache-Control", "no-cache");
context.res().setHeader("X-Accel-Buffering", "no");
context.res().setHeader("Connection", "keep-alive");
OutputStream out = context.res().getOutputStream();
out.flush();
return (out);
}
/*******************************************************************************
**
*******************************************************************************/
private static void write(OutputStream out, String frame) throws IOException
{
out.write(frame.getBytes(StandardCharsets.UTF_8));
out.flush();
}
/*******************************************************************************
**
*******************************************************************************/
private static String ping()
{
return ("event: " + TurnEvent.PING + "\ndata: {}\n\n");
}
/*******************************************************************************
** Session + API for a request. 404 when the QBit is not in the instance.
*******************************************************************************/
private AssistantApi api(Context context) throws Exception
{
AssistantRuntime runtime = AssistantRuntime.of(qInstance);
if(runtime == null)
{
throw (new AssistantApiException(404, "The assistant is not installed."));
}
////////////////////////////////////////////////////////////////////
// the tools call /qqq/v1 on this server: remember its local port //
////////////////////////////////////////////////////////////////////
try
{
runtime.learnLocalPort(context.req().getLocalPort());
}
catch(RuntimeException e)
{
LOG.debug("Could not read the local port", e);
}
QSession session = ExecutorSessionUtils.setupSession(context, qInstance);
return (new AssistantApi(runtime, session));
}
/*******************************************************************************
** Map errors: API errors with their status, others through QQQ's handler
** (401 / 403 / 404 / 500).
*******************************************************************************/
private static void handleException(Context context, Exception e)
{
if(e instanceof AssistantApiException apiException)
{
Map<String, Object> body = new LinkedHashMap<>();
body.put("error", apiException.getMessage());
if(apiException.getCode() != null)
{
body.put("code", apiException.getCode());
}
context.status(apiException.getStatus());
context.contentType(ContentType.APPLICATION_JSON);
context.result(JsonUtils.toJson(body));
return;
}
if(!(e instanceof QException))
{
LOG.warn("Assistant request failed", e);
}
QJavalinUtils.handleException(null, context, e);
}
/*******************************************************************************
** A JSON object body (empty body = empty object).
*******************************************************************************/
static Map<String, Object> readJsonBody(Context context) throws AssistantApiException
{
String body = context.body();
if(!StringUtils.hasContent(body))
{
return (new LinkedHashMap<>());
}
String contentType = context.contentType();
if(contentType == null || !contentType.toLowerCase().startsWith("application/json"))
{
throw (new AssistantApiException(400, "Request bodies must be JSON (Content-Type: application/json)."));
}
try
{
Map<String, Object> map = JsonUtils.toObject(body, new TypeReference<Map<String, Object>>() {}, mapper -> mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS));
return (map == null ? new LinkedHashMap<>() : map);
}
catch(Exception e)
{
throw (new AssistantApiException(400, "The request body is not a JSON object."));
}
}
/*******************************************************************************
**
*******************************************************************************/
private static Integer pathInt(Context context, String name) throws AssistantApiException
{
try
{
return (Integer.parseInt(context.pathParam(name)));
}
catch(NumberFormatException e)
{
throw (new AssistantApiException(400, name + " must be an integer."));
}
}
/*******************************************************************************
**
*******************************************************************************/
private static Integer queryInt(Context context, String name) throws AssistantApiException
{
String value = context.queryParam(name);
if(!StringUtils.hasContent(value))
{
return (null);
}
try
{
return (Integer.parseInt(value.trim()));
}
catch(NumberFormatException e)
{
throw (new AssistantApiException(400, name + " must be an integer."));
}
}
/*******************************************************************************
** One JSON endpoint's work.
*******************************************************************************/
@FunctionalInterface
private interface Handler
{
/*******************************************************************************
**
*******************************************************************************/
Object handle(AssistantApi api, Map<String, Object> body) throws Exception;
}
}
@@ -17,10 +17,12 @@
package com.kingsrook.qbits.assistant.api;
import com.kingsrook.qbits.assistant.api.specs.AssistantSpecs;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.utils.CollectionUtils;
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
import com.kingsrook.qqq.middleware.javalin.specs.extensions.MiddlewareSpecExtensionsMetaData;
/*******************************************************************************
@@ -43,6 +45,16 @@ public class AssistantRoutes
{
javalinMetaData.withAdditionalRouteProviderReference(new QCodeReference(AssistantRouteProvider.class));
}
////////////////////////////////////////////////////////////////////
// the endpoints: the spec'd "assistant" UI API extension //
////////////////////////////////////////////////////////////////////
MiddlewareSpecExtensionsMetaData extensions = MiddlewareSpecExtensionsMetaData.ofOrWithNew(qInstance);
boolean hasExtension = extensions.getExtensions() != null && extensions.getExtensions().containsKey(AssistantSpecs.EXTENSION_NAME);
if(!hasExtension)
{
extensions.withExtension(AssistantSpecs.extension());
}
}
}
@@ -0,0 +1,229 @@
/*
* 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.api;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.assistant.engine.TurnEvent;
import com.kingsrook.qbits.assistant.engine.TurnEventLog;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import io.javalin.http.Context;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** Writes a turn's events as server-sent events: the live log of a turn
** running here, or the persisted events (polling while the turn runs on
** another replica), with a ping every pingMillis while idle.
*******************************************************************************/
public final class TurnStreams
{
private static final QLogger LOG = QLogger.getLogger(TurnStreams.class);
public static final long PING_MILLIS = 15_000;
public static final long REMOTE_POLL_MS = 1_000;
private static volatile long pingMillis = PING_MILLIS;
/*******************************************************************************
** Utility class.
*******************************************************************************/
private TurnStreams()
{
}
/*******************************************************************************
** The ping interval (tests use a short one).
*******************************************************************************/
public static void setPingMillis(long millis)
{
pingMillis = millis;
}
/*******************************************************************************
** Stream a live log from a sequence number until message.end.
*******************************************************************************/
public static void streamLive(Context context, TurnEventLog log, int after)
{
try
{
writeLive(startStream(context), log, after);
}
catch(IOException e)
{
LOG.debug("Assistant stream closed by the client (the turn continues)");
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
/*******************************************************************************
** Stream the events of a turn after a sequence number: live when it runs
** here, else the persisted ones (polling while it runs elsewhere). The
** caller's QContext (session) must be set: the replay reads the store.
*******************************************************************************/
public static void streamEvents(Context context, AssistantApi api, Integer turnId, int after, AssistantApi.TurnEvents first)
{
if(first.live() != null)
{
streamLive(context, first.live().getLog(), after);
return;
}
try
{
OutputStream out = startStream(context);
int last = after;
long lastWrite = System.currentTimeMillis();
long giveUpAt = System.currentTimeMillis() + api.maxStreamSeconds() * 1000L;
AssistantApi.TurnEvents current = first;
while(true)
{
boolean ended = false;
for(TurnEvent event : current.persisted())
{
write(out, event.toSseFrame());
last = event.getSeq();
lastWrite = System.currentTimeMillis();
ended |= event.isTerminal();
}
if(ended || (current.finished() && !current.more()))
{
return;
}
if(System.currentTimeMillis() > giveUpAt)
{
write(out, new TurnEvent(last + 1, TurnEvent.ERROR, Map.of("code", "TIMEOUT", "message", "The event stream timed out. Reconnect to check this answer.")).toSseFrame());
write(out, new TurnEvent(last + 2, TurnEvent.MESSAGE_END, Map.of("status", "ERROR", "stopReason", "stream_timeout")).toSseFrame());
return;
}
if(!current.more())
{
Thread.sleep(REMOTE_POLL_MS);
}
if(System.currentTimeMillis() - lastWrite >= pingMillis)
{
write(out, ping());
lastWrite = System.currentTimeMillis();
}
current = api.turnEvents(turnId, last);
if(current.live() != null)
{
writeLive(out, current.live().getLog(), last);
return;
}
}
}
catch(IOException e)
{
LOG.debug("Assistant event stream closed by the client", logPair("turnId", turnId));
}
catch(InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch(Exception e)
{
LOG.warn("Assistant event replay failed", e, logPair("turnId", turnId));
}
}
/*******************************************************************************
**
*******************************************************************************/
private static void writeLive(OutputStream out, TurnEventLog log, int after) throws IOException, InterruptedException
{
int last = after;
while(true)
{
List<TurnEvent> events = log.after(last, pingMillis);
if(events.isEmpty())
{
if(log.isClosed())
{
return;
}
write(out, ping());
continue;
}
for(TurnEvent event : events)
{
write(out, event.toSseFrame());
last = event.getSeq();
if(event.isTerminal())
{
return;
}
}
}
}
/*******************************************************************************
** Start an SSE response.
*******************************************************************************/
private static OutputStream startStream(Context context) throws IOException
{
context.status(200);
context.disableCompression();
context.res().setContentType("text/event-stream; charset=utf-8");
context.res().setHeader("Cache-Control", "no-cache");
context.res().setHeader("X-Accel-Buffering", "no");
context.res().setHeader("Connection", "keep-alive");
OutputStream out = context.res().getOutputStream();
out.flush();
return (out);
}
/*******************************************************************************
**
*******************************************************************************/
private static void write(OutputStream out, String frame) throws IOException
{
out.write(frame.getBytes(StandardCharsets.UTF_8));
out.flush();
}
/*******************************************************************************
**
*******************************************************************************/
private static String ping()
{
return ("event: " + TurnEvent.PING + "\ndata: {}\n\n");
}
}
@@ -22,11 +22,12 @@ package com.kingsrook.qbits.assistant.classification;
import java.util.Collection;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.context.QContext;
/*******************************************************************************
** Host seam for table and field classifications; a core metadata adapter can replace the configured source.
** Host seam for table and field classifications; the default reads core metadata merged with configuration.
*******************************************************************************/
public interface ClassificationSource
{
@@ -63,7 +64,7 @@ public interface ClassificationSource
DataClassification result = DataClassification.PUBLIC;
for(String field : fields)
{
result = DataClassification.max(result, field == null || "*".equals(field) ? highest(table) : ofField(table, field));
result = Classifications.max(result, field == null || "*".equals(field) ? highest(table) : ofField(table, field));
}
return (result);
}
@@ -80,7 +81,7 @@ public interface ClassificationSource
{
if(!table.startsWith("assistant_"))
{
result = DataClassification.max(result, highest(table));
result = Classifications.max(result, highest(table));
}
}
return (result);
@@ -1,15 +1,11 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
* 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,
@@ -21,24 +17,31 @@
package com.kingsrook.qbits.assistant.classification;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
/*******************************************************************************
** Stand-in for core DataClassification (QRun-IO/qqq#1142); replace when the qbit builds on an RC that has it.
** The assistant's conventions over core's {@link DataClassification}: an
** absent classification is PUBLIC, and a stored level this version does not
** know is treated as PHI (fail conservative).
*******************************************************************************/
public enum DataClassification
public final class Classifications
{
PUBLIC, CONFIDENTIAL, PII, PHI;
/*******************************************************************************
** Utility class.
*******************************************************************************/
private Classifications()
{
}
/*******************************************************************************
** Whether this classification is at least the supplied level; null means PUBLIC.
** The level, or PUBLIC when absent.
*******************************************************************************/
public boolean isAtLeast(DataClassification other)
public static DataClassification orPublic(DataClassification classification)
{
return (ordinal() >= (other == null ? PUBLIC : other).ordinal());
return (classification == null ? DataClassification.PUBLIC : classification);
}
@@ -48,9 +51,7 @@ public enum DataClassification
*******************************************************************************/
public static DataClassification max(DataClassification left, DataClassification right)
{
DataClassification a = left == null ? PUBLIC : left;
DataClassification b = right == null ? PUBLIC : right;
return (a.isAtLeast(b) ? a : b);
return (DataClassification.max(orPublic(left), orPublic(right)));
}
@@ -62,15 +63,15 @@ public enum DataClassification
{
if(value == null)
{
return (PUBLIC);
return (DataClassification.PUBLIC);
}
try
{
return (valueOf(value));
return (DataClassification.valueOf(value));
}
catch(IllegalArgumentException e)
{
return (PHI);
return (DataClassification.PHI);
}
}
}
@@ -23,12 +23,21 @@ package com.kingsrook.qbits.assistant.classification;
import java.util.LinkedHashMap;
import java.util.Map;
import com.kingsrook.qqq.backend.core.actions.ai.AiDataClassifications;
import com.kingsrook.qqq.backend.core.actions.ai.AiFieldMetaData;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
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.tables.QTableMetaData;
/*******************************************************************************
** Default classification source for RCs without core classification metadata.
** The default classification source: core's AI classification metadata
** (AiTableMetaData / AiFieldMetaData, via AiDataClassifications) merged with
** the classifications configured on the qbit. A configured value wins when
** both are set; a field falls back to its own core classification, then to
** its table's; anything unclassified (and the assistant's own tables) is
** PUBLIC.
*******************************************************************************/
public class ConfiguredClassificationSource implements ClassificationSource
{
@@ -71,7 +80,7 @@ public class ConfiguredClassificationSource implements ClassificationSource
@Override
public DataClassification ofTable(String table)
{
return (table == null || table.startsWith("assistant_") ? DataClassification.PUBLIC : DataClassification.max(null, tables.get(table)));
return (table == null || table.startsWith("assistant_") ? DataClassification.PUBLIC : Classifications.max(null, tables.get(table)));
}
@@ -87,11 +96,28 @@ public class ConfiguredClassificationSource implements ClassificationSource
return (DataClassification.PUBLIC);
}
DataClassification value = field == null ? null : fields.getOrDefault(table, Map.of()).get(field);
if(value == null)
{
QTableMetaData metadata = coreTable(table);
AiFieldMetaData coreField = metadata == null || metadata.getFields() == null || field == null ? null : AiFieldMetaData.of(metadata.getFields().get(field));
value = coreField == null ? null : coreField.getClassification();
}
return (value == null ? ofTable(table) : value);
}
/*******************************************************************************
** The table's core metadata, or null (no instance in context, or unknown).
*******************************************************************************/
private static QTableMetaData coreTable(String table)
{
QInstance qInstance = QContext.getQInstance();
return (qInstance == null ? null : qInstance.getTable(table));
}
/*******************************************************************************
** Resolve all field names from the current instance, also retaining configured overrides.
*******************************************************************************/
@@ -108,12 +134,12 @@ public class ConfiguredClassificationSource implements ClassificationSource
{
for(String field : metadata.getFields().keySet())
{
result = DataClassification.max(result, ofField(table, field));
result = Classifications.max(result, ofField(table, field));
}
}
for(DataClassification value : fields.getOrDefault(table, Map.of()).values())
{
result = DataClassification.max(result, value);
result = Classifications.max(result, value);
}
return (result);
}
@@ -129,11 +155,11 @@ public class ConfiguredClassificationSource implements ClassificationSource
DataClassification result = ClassificationSource.super.highestAnywhere();
for(String table : tables.keySet())
{
result = DataClassification.max(result, highest(table));
result = Classifications.max(result, highest(table));
}
for(String table : fields.keySet())
{
result = DataClassification.max(result, highest(table));
result = Classifications.max(result, highest(table));
}
return (result);
}
@@ -0,0 +1,111 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.email;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
/*******************************************************************************
** Email delivery of a scheduled task's result, when the optional qbit-email
** is present. This class names no qbit-email type, so it loads without the
** jar; the adapter (AssistantEmailSender) is only loaded after the guard passes.
**
** Hosts can call sendScheduledResult after a run; the scheduled-task runner
** does not yet wire email delivery. The gates below apply to every call:
** the task opted in, the host approved EXTERNAL delivery
** (AssistantQBitConfig.getEmailExternalApproved, until the approval rule
** exists), and there is a recipient address.
*******************************************************************************/
public final class AssistantEmail
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AssistantEmail()
{
}
/*******************************************************************************
** Whether qbit-email is on the classpath and produced in this instance.
*******************************************************************************/
public static boolean isAvailable(QInstance qInstance)
{
try
{
Class.forName("com.kingsrook.qbits.email.api.EmailApi");
}
catch(ClassNotFoundException | LinkageError e)
{
return (false);
}
return (AssistantEmailSender.isInstalled(qInstance));
}
/*******************************************************************************
** Email a finished scheduled run to its owner, if the task opted in and
** every gate allows it. A missing email qbit is not an error; the status
** says what happened.
*******************************************************************************/
public static ScheduledEmailStatus sendScheduledResult(QInstance qInstance, AssistantQBitConfig config, ScheduledResultNotice notice) throws QException
{
if(notice == null || !notice.emailResult())
{
return (ScheduledEmailStatus.NOT_REQUESTED);
}
if(!isAvailable(qInstance))
{
return (ScheduledEmailStatus.NOT_AVAILABLE);
}
if(!Boolean.TRUE.equals(config.getEmailExternalApproved()))
{
return (ScheduledEmailStatus.NOT_APPROVED);
}
String recipient = recipient(config, notice.ownerUserId());
if(recipient == null)
{
return (ScheduledEmailStatus.NO_RECIPIENT);
}
return (AssistantEmailSender.send(notice, recipient));
}
/*******************************************************************************
** The owner's address: the host's resolver, else the owner id when it is
** itself an address. Null when there is none.
*******************************************************************************/
static String recipient(AssistantQBitConfig config, String ownerUserId)
{
if(ownerUserId == null || ownerUserId.isBlank())
{
return (null);
}
String address = config.getEmailRecipientResolver() != null ? config.getEmailRecipientResolver().apply(ownerUserId) : (ownerUserId.contains("@") ? ownerUserId : null);
return (address == null || address.isBlank() ? null : address.trim());
}
}
@@ -0,0 +1,156 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.email;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import com.kingsrook.qbits.email.api.EmailApi;
import com.kingsrook.qbits.email.api.EmailApiCategory;
import com.kingsrook.qbits.email.api.EmailApiRequest;
import com.kingsrook.qbits.email.api.EmailApiResult;
import com.kingsrook.qbits.email.api.EmailApiTemplate;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
/*******************************************************************************
** The only class that touches qbit-email. Registers the scheduled-result
** template on first use (never overwriting edits) and queues one message per
** recipient. Addresses, summaries and bodies are never logged.
*******************************************************************************/
final class AssistantEmailSender
{
static final String TEMPLATE_NAME = "assistant_scheduled_result";
static final String SECURE_TEMPLATE = "email_secure_message";
static final String SENDER_QBIT = "assistant";
static final String SENDER_PROCESS = "assistantScheduledTask";
private static final int MAX_SUMMARY = 280;
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AssistantEmailSender()
{
}
/*******************************************************************************
** Whether the email qbit is produced in this instance.
*******************************************************************************/
static boolean isInstalled(QInstance qInstance)
{
return (EmailApi.isInstalled(qInstance));
}
/*******************************************************************************
** Queue one message to one recipient. A result classified above PUBLIC
** sends only the link, with the secure-message pattern.
*******************************************************************************/
static ScheduledEmailStatus send(ScheduledResultNotice notice, String recipient) throws QException
{
boolean linkOnly = notice.classification() != null && notice.classification().isAtLeast(DataClassification.CONFIDENTIAL);
EmailApiRequest request = new EmailApiRequest().withTo(recipient)
.withIdempotencyKey("assistant:scheduled:" + notice.runId())
.withLinkedRecord(notice.runTable(), notice.runId())
.withSender(SENDER_QBIT, SENDER_PROCESS);
Map<String, Serializable> variables = new LinkedHashMap<>();
variables.put("link", notice.link());
if(linkOnly)
{
request.withTemplateName(SECURE_TEMPLATE);
}
else
{
ensureTemplate();
request.withTemplateName(TEMPLATE_NAME);
variables.put("taskName", notice.taskName());
variables.put("runTime", notice.runTime() == null ? null : notice.runTime().toString());
variables.put("summary", summary(notice.summary()));
}
request.withVariables(variables);
return (map(EmailApi.send(request)));
}
/*******************************************************************************
** One line, cut short; the full model output never goes in an email.
*******************************************************************************/
static String summary(String value)
{
if(value == null)
{
return (null);
}
String oneLine = value.replaceAll("\\s+", " ").trim();
return (oneLine.length() <= MAX_SUMMARY ? oneLine : oneLine.substring(0, MAX_SUMMARY - 3) + "...");
}
/*******************************************************************************
** Outbox result to the qbit's own vocabulary.
*******************************************************************************/
private static ScheduledEmailStatus map(EmailApiResult result)
{
return (switch(result.status())
{
case QUEUED -> ScheduledEmailStatus.QUEUED;
case DUPLICATE -> ScheduledEmailStatus.DUPLICATE;
case SUPPRESSED -> ScheduledEmailStatus.SUPPRESSED;
case REFUSED -> ScheduledEmailStatus.REFUSED;
});
}
/*******************************************************************************
** Register the NOTIFICATION template once; an existing template is left alone.
*******************************************************************************/
static void ensureTemplate() throws QException
{
EmailApi.ensureTemplate(new EmailApiTemplate()
.withName(TEMPLATE_NAME)
.withLabel("Assistant scheduled task result")
.withCategory(EmailApiCategory.NOTIFICATION)
.withKind("MARKDOWN")
.withOwnerQbit(SENDER_QBIT)
.withSubject("Assistant task result: {{taskName}}")
.withBody("Your scheduled assistant task **{{taskName}}** finished at {{runTime}}.\n\n{{summary}}\n\n[Open the run]({{link}}){.button}")
.withVariable("taskName", "Task name", "STRING", true, "CONFIDENTIAL")
.withVariable("runTime", "Run time", "DATE_TIME", true, "PUBLIC")
.withVariable("summary", "Short summary", "STRING", false, "CONFIDENTIAL")
.withVariable("link", "Link to the run", "URL", true, "PUBLIC")
.withSampleVariables("{\"taskName\":\"Weekly review\",\"runTime\":\"2026-10-12T09:00:00Z\",\"summary\":\"Three items need attention.\",\"link\":\"https://app.example.com/app/assistant_run/1\"}"));
}
}
@@ -0,0 +1,38 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.email;
/*******************************************************************************
** Outcome of trying to email a scheduled task's result. The first four mean
** nothing was queued and why; the rest mirror the outbox result.
*******************************************************************************/
public enum ScheduledEmailStatus
{
NOT_REQUESTED,
NOT_AVAILABLE,
NOT_APPROVED,
NO_RECIPIENT,
QUEUED,
DUPLICATE,
SUPPRESSED,
REFUSED
}
@@ -0,0 +1,46 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.assistant.email;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
/*******************************************************************************
** What the scheduled-task runner knows about one finished run, for the
** result email. The full model output is deliberately not part of it: only a
** short summary, and only when the result is classified PUBLIC.
**
** @param runTable the table holding the run record (the email's linked record)
** @param runId the run's id (also the idempotency key)
** @param taskName the scheduled task's name
** @param runTime when the run finished
** @param summary a short summary (cut to 280 characters; never the model output)
** @param classification the result's classification; null means PUBLIC
** @param ownerUserId the task owner's user id (the way the qbit identifies users)
** @param emailResult whether the task opted in to email delivery
** @param link absolute link to the run record in the app
*******************************************************************************/
public record ScheduledResultNotice(String runTable, Object runId, String taskName, Instant runTime, String summary, DataClassification classification,
String ownerUserId, boolean emailResult, String link)
{
}
@@ -21,18 +21,19 @@ import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.HealthResult;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
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.RegistryModelProvider;
import com.kingsrook.qbits.assistant.provider.StreamHandle;
import com.kingsrook.qbits.assistant.rag.EmbeddingService;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.HealthResult;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelPricing;
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.StreamHandle;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
@@ -28,16 +28,16 @@ import java.util.Set;
import java.util.TreeMap;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.model.AssistantMessage;
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.ModelRequest;
import com.kingsrook.qbits.assistant.provider.ModelToolDefinition;
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.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelToolDefinition;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
import com.kingsrook.qbits.assistant.tools.KnowledgeTool;
import com.kingsrook.qbits.assistant.tools.PresentResultsTool;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolDefinition;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolKernel;
import com.kingsrook.qqq.backend.core.context.QContext;
@@ -106,6 +106,16 @@ public class ContextBuilder
** kernel's navigate and search_help.
*******************************************************************************/
public List<ModelToolDefinition> tools(PolicyService.ToolPolicy policy)
{
return (tools(policy, null));
}
/*******************************************************************************
** Attribute tool-discovery requests to the turn that needs them.
*******************************************************************************/
private List<ModelToolDefinition> tools(PolicyService.ToolPolicy policy, String turnId)
{
Map<String, ModelToolDefinition> byName = new TreeMap<>();
for(ModelToolDefinition definition : toolbox.definitions(policy, toolbox.anyWritableTable()))
@@ -123,7 +133,7 @@ public class ContextBuilder
.withStrict(isStrict(definition.getName(), !Boolean.FALSE.equals(definition.getStrict()))));
}
}
if(knowledgeTool != null && knowledgeTool.offered(policy, QContext.getQSession()))
if(knowledgeTool != null && knowledgeTool.offered(policy, QContext.getQSession(), turnId))
{
byName.put(KnowledgeTool.NAME, knowledgeTool.definition());
}
@@ -216,12 +226,23 @@ public class ContextBuilder
*******************************************************************************/
public ModelRequest build(QSession session, String model, String effort, List<AssistantMessage> history, String userText, Map<String, Object> pageContext, PolicyService.ToolPolicy toolPolicy,
String profileInstructions)
{
return (build(session, model, effort, history, userText, pageContext, toolPolicy, profileInstructions, null));
}
/*******************************************************************************
** Include the turn in any UI API calls needed to discover available tools.
*******************************************************************************/
public ModelRequest build(QSession session, String model, String effort, List<AssistantMessage> history, String userText, Map<String, Object> pageContext, PolicyService.ToolPolicy toolPolicy,
String profileInstructions, String turnId)
{
ModelRequest request = new ModelRequest()
.withModel(model)
.withEffort(effort)
.withMaxTokens(config.getModels().getMainMaxOutputTokens())
.withTools(tools(toolPolicy));
.withTools(tools(toolPolicy, turnId));
request.getSystem().add(new SystemBlock(SystemPrompt.staticBlock(appDigest()), CacheHint.LONG));
request.getSystem().add(new SystemBlock(userBlock(session) + (StringUtils.hasContent(profileInstructions) ? "\n" + profileInstructions : ""), CacheHint.SHORT));
@@ -27,15 +27,15 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.provider.ModelEventListener;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
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.spi.ModelEventListener;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelRequest;
import com.kingsrook.qbits.assistant.spi.ModelResponse;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@@ -24,11 +24,11 @@ import java.util.Set;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.DiscoveredModel;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.DiscoveredModel;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
@@ -29,21 +29,21 @@ import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.model.AssistantConversation;
import com.kingsrook.qbits.assistant.model.AssistantPendingAction;
import com.kingsrook.qbits.assistant.model.AssistantProfile;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.provider.CacheHint;
import com.kingsrook.qbits.assistant.provider.ModelMessage;
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.ModelUsage;
import com.kingsrook.qbits.assistant.provider.StreamHandle;
import com.kingsrook.qbits.assistant.provider.SystemBlock;
import com.kingsrook.qbits.assistant.scheduled.ScheduledTurn;
import com.kingsrook.qbits.assistant.spi.CacheHint;
import com.kingsrook.qbits.assistant.spi.ModelMessage;
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.ModelUsage;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
import com.kingsrook.qbits.assistant.spi.SystemBlock;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
@@ -22,8 +22,8 @@ package com.kingsrook.qbits.assistant.engine;
import java.util.Optional;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
/*******************************************************************************
@@ -23,9 +23,9 @@ import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.provider.HealthResult;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.spi.HealthResult;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
@@ -17,18 +17,6 @@
package com.kingsrook.qbits.assistant.engine;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.provider.ProviderSettings;
import com.kingsrook.qbits.assistant.provider.RegistryModelProvider;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
@@ -43,6 +31,19 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.RegistryModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.ModelPricing;
import com.kingsrook.qbits.assistant.spi.ProviderSettings;
import com.kingsrook.qqq.backend.core.exceptions.QException;
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;
@@ -742,7 +743,7 @@ public class ProviderService
/*******************************************************************************
** P-e seam: no automatic alternative is selected in P-c. Never downgrade PHI eligibility.
*******************************************************************************/
public java.util.Optional<Active> eligibleAlternative(com.kingsrook.qbits.assistant.classification.DataClassification classification, AssistantProvider blockedProvider)
public java.util.Optional<Active> eligibleAlternative(com.kingsrook.qqq.backend.core.actions.ai.DataClassification classification, AssistantProvider blockedProvider)
{
return (java.util.Optional.empty());
}
@@ -26,15 +26,12 @@ import java.util.Map;
/*******************************************************************************
** Per-user turn rate limits (spec 3.9): turns started per minute and turns
** running at once. In memory, per replica - with several replicas the
** effective limit is per replica (the concurrent limit is also checked
** against the turn table by the API).
** Per-user starts per minute, in memory per replica. The API implements
** concurrency by superseding turns, never by refusing another question.
*******************************************************************************/
public class RateLimiter
{
private final Map<String, Deque<Instant>> starts = new HashMap<>();
private final Map<String, Integer> running = new HashMap<>();
private final Clock clock;
@@ -61,17 +58,12 @@ public class RateLimiter
queue.pollFirst();
}
if(running.getOrDefault(userId, 0) >= concurrent)
{
return ("You already have an assistant answer in progress. Wait for it to finish or stop it.");
}
if(queue.size() >= perMinute)
{
return ("Too many assistant requests in the last minute. Try again shortly.");
}
queue.addLast(now);
running.merge(userId, 1, Integer::sum);
return (null);
}
@@ -82,7 +74,7 @@ public class RateLimiter
*******************************************************************************/
public synchronized void release(String userId)
{
running.computeIfPresent(userId, (k, v) -> v <= 1 ? null : v - 1);
// Only starts per minute are counted; completion does not refund a start.
}
}
@@ -17,8 +17,11 @@
package com.kingsrook.qbits.assistant.engine;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import com.kingsrook.qbits.assistant.provider.StreamHandle;
import java.util.function.Consumer;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
/*******************************************************************************
@@ -30,6 +33,14 @@ public class RunningTurn
private final String userId;
private final TurnEventLog log = new TurnEventLog();
private final AtomicReference<String> cancelReason = new AtomicReference<>();
private final AtomicBoolean finalized = new AtomicBoolean();
private Instant startedAt;
private volatile String phase = "starting";
private volatile String toolName;
private volatile Thread engineThread;
private volatile Consumer<String> forceFinalizer;
private volatile long cancelledNanos;
private volatile String trackingId;
private volatile StreamHandle currentHandle;
@@ -39,6 +50,7 @@ public class RunningTurn
*******************************************************************************/
public RunningTurn(Integer turnId, String userId)
{
this.startedAt = Instant.now();
this.turnId = turnId;
this.userId = userId;
}
@@ -50,12 +62,24 @@ public class RunningTurn
*******************************************************************************/
public void cancel(String reason)
{
if(cancelReason.compareAndSet(null, reason))
if(!finalized.get() && cancelReason.compareAndSet(null, reason))
{
StreamHandle handle = currentHandle;
if(handle != null)
cancelledNanos = System.nanoTime();
try
{
handle.cancel();
StreamHandle handle = currentHandle;
if(handle != null)
{
handle.cancel();
}
}
finally
{
Thread thread = engineThread;
if(thread != null && thread != Thread.currentThread())
{
thread.interrupt();
}
}
}
}
@@ -124,4 +148,140 @@ public class RunningTurn
return (log);
}
/*******************************************************************************
** Claim terminal processing exactly once.
*******************************************************************************/
public boolean tryFinalize()
{
return (finalized.compareAndSet(false, true));
}
/*******************************************************************************
** Whether terminal processing has been claimed.
*******************************************************************************/
public boolean isFinalized()
{
return (finalized.get());
}
/*******************************************************************************
** Getter for startedAt
*******************************************************************************/
public Instant getStartedAt()
{
return (startedAt);
}
/*******************************************************************************
** Setter for startedAt
*******************************************************************************/
public void setStartedAt(Instant startedAt)
{
this.startedAt = startedAt;
}
/*******************************************************************************
** Getter for phase
*******************************************************************************/
public String getPhase()
{
return (phase);
}
/*******************************************************************************
** Getter for toolName
*******************************************************************************/
public String getToolName()
{
return (toolName);
}
/*******************************************************************************
** Record the current phase and optional tool.
*******************************************************************************/
public void setPhase(String phase, String toolName)
{
this.phase = phase;
this.toolName = toolName;
}
/*******************************************************************************
** Record the thread to interrupt when cancelling.
*******************************************************************************/
public void setEngineThread(Thread engineThread)
{
this.engineThread = engineThread;
}
/*******************************************************************************
** Install the engine finalizer before registration.
*******************************************************************************/
public void setForceFinalizer(Consumer<String> forceFinalizer)
{
this.forceFinalizer = forceFinalizer;
}
/*******************************************************************************
** Force terminal processing using the original user session.
*******************************************************************************/
public void forceFinalize(String reason)
{
Consumer<String> finalizer = forceFinalizer;
if(finalizer != null)
{
finalizer.accept(reason);
}
}
/*******************************************************************************
** Whether cancellation has exceeded its bounded grace period.
*******************************************************************************/
public boolean cancelGraceElapsed(int seconds)
{
return (isCancelled() && cancelledNanos != 0 && System.nanoTime() - cancelledNanos >= seconds * 1_000_000_000L);
}
/*******************************************************************************
** Getter for trackingId
*******************************************************************************/
public String getTrackingId()
{
return (trackingId);
}
/*******************************************************************************
** Setter for trackingId
*******************************************************************************/
public void setTrackingId(String trackingId)
{
this.trackingId = trackingId;
}
}
@@ -27,11 +27,12 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.assistant.classification.ClassificationSource;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.classification.Classifications;
import com.kingsrook.qbits.assistant.model.AssistantConversation;
import com.kingsrook.qbits.assistant.provider.ModelPart;
import com.kingsrook.qbits.assistant.spi.ModelPart;
import com.kingsrook.qqq.backend.core.actions.ai.AiRecordRef;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolResult;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
@@ -55,7 +56,7 @@ public class TurnClassification
public TurnClassification(ClassificationSource source, AssistantConversation conversation, Map<String, Object> pageContext)
{
this.source = source;
classification = DataClassification.stored(conversation.getMaxClassification());
classification = Classifications.stored(conversation.getMaxClassification());
if(pageContext != null && pageContext.get("tableName") instanceof String table)
{
touch(table, pageContext.get("recordId") == null ? source.ofTable(table) : source.highest(table));
@@ -210,7 +211,7 @@ public class TurnClassification
*******************************************************************************/
private void touchUnknown()
{
classification = DataClassification.max(classification, source.highestAnywhere());
classification = Classifications.max(classification, source.highestAnywhere());
for(String table : QContext.getQInstance().getTables().keySet())
{
if(!table.startsWith("assistant_") && source.highest(table) != DataClassification.PUBLIC)
@@ -229,7 +230,7 @@ public class TurnClassification
{
if(table != null && !table.startsWith("assistant_"))
{
classification = DataClassification.max(classification, value);
classification = Classifications.max(classification, value);
if(QContext.getQInstance().getTable(table) != null)
{
tables.add(table);
@@ -256,7 +257,7 @@ public class TurnClassification
{
if(conversation != null)
{
classification = DataClassification.max(classification, DataClassification.stored(conversation.getMaxClassification()));
classification = Classifications.max(classification, Classifications.stored(conversation.getMaxClassification()));
}
}
@@ -22,10 +22,10 @@ package com.kingsrook.qbits.assistant.engine;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.classification.DataClassification;
import com.kingsrook.qbits.assistant.model.AssistantDataAudit;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qqq.backend.core.actions.ai.DataClassification;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@@ -44,22 +44,23 @@ import com.kingsrook.qbits.assistant.model.AssistantScheduledTask;
import com.kingsrook.qbits.assistant.model.AssistantToolCall;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.CacheHint;
import com.kingsrook.qbits.assistant.provider.ModelCapabilities;
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.ModelUsage;
import com.kingsrook.qbits.assistant.provider.StreamHandle;
import com.kingsrook.qbits.assistant.scheduled.ScheduledTurn;
import com.kingsrook.qbits.assistant.spi.AssistantModelProvider;
import com.kingsrook.qbits.assistant.spi.CacheHint;
import com.kingsrook.qbits.assistant.spi.ModelCapabilities;
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.ModelPricing;
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.ModelUsage;
import com.kingsrook.qbits.assistant.spi.StreamHandle;
import com.kingsrook.qbits.assistant.tools.KnowledgeTool;
import com.kingsrook.qbits.assistant.tools.PresentResultsTool;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
import com.kingsrook.qqq.backend.core.actions.ai.AiRecordRef;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolCall;
import com.kingsrook.qqq.backend.core.actions.ai.AiToolOutcome;
@@ -72,6 +73,7 @@ import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import com.kingsrook.qqq.middleware.javalin.specs.invoke.UiApiCredentials;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
@@ -100,6 +102,10 @@ public class TurnEngine implements Runnable
{
private static final QLogger LOG = QLogger.getLogger(TurnEngine.class);
public static final String SUPERSEDED_TEXT = "Stopped because you asked something else.";
public static final String TIMEOUT_TEXT = "The assistant took too long to answer, so it was stopped. Ask again.";
public static final String RESTART_TEXT = "The server restarted while answering. Ask again.";
private static final int MAX_INPUT_JSON_CHARS = 4000;
private static final AiRedactor INPUT_REDACTOR = new AiRedactor(List.of());
@@ -148,6 +154,7 @@ public class TurnEngine implements Runnable
private ProviderService.Active budgetOrigin;
private volatile boolean finished = false;
private UiApiCredentials credentials;
@@ -172,6 +179,23 @@ public class TurnEngine implements Runnable
this.policy = policy;
this.running = running;
this.softBudgetNotice = softBudgetNotice;
this.startedAt = turn.getStartedAt() == null ? runtime.getClock().instant() : turn.getStartedAt();
this.deadline = startedAt.plusSeconds(config.getMaxTurnSeconds());
running.setStartedAt(startedAt);
running.setForceFinalizer(this::forceFinish);
}
/*******************************************************************************
** The credentials of the request that started the turn, forwarded to the
** UI API by the tools (session cookies, Authorization, API key as they came
** in). Without them the session UUID is used. Never logged.
*******************************************************************************/
public TurnEngine withCredentials(UiApiCredentials credentials)
{
this.credentials = credentials;
return (this);
}
@@ -182,8 +206,11 @@ public class TurnEngine implements Runnable
@Override
public void run()
{
startedAt = runtime.getClock().instant();
deadline = startedAt.plusSeconds(config.getMaxTurnSeconds());
if(running.isFinalized())
{
return;
}
running.setEngineThread(Thread.currentThread());
String status = "COMPLETE";
String stopReason = null;
@@ -193,6 +220,7 @@ public class TurnEngine implements Runnable
try
{
QContext.init(runtime.getQInstance(), session);
startWatchdog();
scheduledTask = runtime.getScheduledTurn().task(conversation.getId());
if(conversation.getScheduledTaskId() != null && scheduledTask == null)
{
@@ -202,9 +230,9 @@ public class TurnEngine implements Runnable
ScheduledTurn.checkCost(runtime, conversation.getId(), turn.getId());
classification = new TurnClassification(config.getClassificationSource(), conversation, pageContext);
store.saveClassification(userId, conversation.getId(), turn.getId(), classification);
startKillSwitchWatcher();
emit(TurnEvent.MESSAGE_START, map("turnId", turn.getId(), "conversationId", conversation.getId(), "userMessageId", userMessage.getId(), "messageId", assistantMessage.getId()));
emit(TurnEvent.MESSAGE_START, map("turnId", turn.getId(), "conversationId", conversation.getId(), "userMessageId", userMessage.getId(), "messageId", assistantMessage.getId(), "startedAt", startedAt.toString()));
if(softBudgetNotice != null)
{
notice("warning", softBudgetNotice);
@@ -216,6 +244,7 @@ public class TurnEngine implements Runnable
ModelRouter.Route route;
try
{
phase("thinking", null);
route = router.route(session, conversation, turn, userText, pageContext, policy, classification, running, deadline, text -> notice("warning", text));
}
finally
@@ -247,7 +276,7 @@ public class TurnEngine implements Runnable
String appName = runtime.appNameFor(pageContext);
ProfileService.Persona persona = runtime.getProfileService().persona(session, appName, scheduledTask == null ? null : scheduledTask.getProfileId());
String profileText = ProfileService.instructions(persona, runtime.getProfileService().relevantSkills(persona.profileId(), userText, appName));
ModelRequest request = runtime.getContextBuilder().build(session, model, route.effort(), history, userText, pageContext, toolPolicy, profileText);
ModelRequest request = runtime.getContextBuilder().build(session, model, route.effort(), history, userText, pageContext, toolPolicy, profileText, turn.getId() == null ? null : String.valueOf(turn.getId()));
Integer maxPerRequest = active.row() == null ? null : active.row().getMaxOutputTokensPerRequest();
if(maxPerRequest != null && (request.getMaxTokens() == null || request.getMaxTokens() > maxPerRequest))
{
@@ -404,8 +433,21 @@ public class TurnEngine implements Runnable
}
finally
{
finished = true;
// Clear interruption while persisting the terminal state.
boolean interrupted = Thread.interrupted();
if(running.isCancelled())
{
Stop stop = cancelledStop();
status = stop.status();
stopReason = stop.stopReason();
errorCode = stop.errorCode();
errorText = stop.message();
}
finish(status, stopReason, errorCode, errorText);
if(interrupted)
{
Thread.currentThread().interrupt();
}
QContext.clear();
}
}
@@ -413,35 +455,56 @@ public class TurnEngine implements Runnable
/*******************************************************************************
** Poll the kill switch while the turn runs (with the user's own session),
** so a flip cancels the turn - and every other turn here - even while it
** waits on the model.
** Renew the lease, poll cancellation and the kill switch with the user's
** own session, and enforce a hard deadline even if a provider is wedged.
*******************************************************************************/
private void startKillSwitchWatcher()
private void startWatchdog()
{
long pollMillis = config.getKillSwitchPollMillis() == null ? 2000 : config.getKillSwitchPollMillis();
Thread.ofVirtual().name("assistant-killswitch-" + turn.getId()).start(() ->
long heartbeatMillis = config.getTurnHeartbeatSeconds() * 1000L;
long pollMillis = Math.min(heartbeatMillis, config.getKillSwitchPollMillis() == null ? 2000 : config.getKillSwitchPollMillis());
Thread.ofVirtual().name("assistant-watchdog-" + turn.getId()).start(() ->
{
long lastHeartbeat = System.nanoTime();
try
{
while(!finished && !running.isCancelled())
QContext.init(runtime.getQInstance(), session);
while(!running.isFinalized())
{
Thread.sleep(pollMillis);
if(finished)
if(running.isFinalized())
{
return;
break;
}
QContext.init(runtime.getQInstance(), session);
try
{
if(System.nanoTime() - lastHeartbeat >= heartbeatMillis * 1_000_000L)
{
lastHeartbeat = System.nanoTime();
heartbeat();
}
if(runtime.getPolicyService().isKillSwitchOn())
{
runtime.cancelAll("KILL_SWITCH");
}
}
catch(Exception e)
{
LOG.warn("Assistant watchdog tick failed", hipaaSafe(e), logPair("turnId", turn.getId()));
}
finally
{
QContext.clear();
// Deadlines do not depend on successful database or policy reads.
Instant now = runtime.getClock().instant();
if(!now.isBefore(deadline))
{
safely(() -> running.cancel("TIMEOUT"));
}
if(!now.isBefore(deadline.plusSeconds(config.getTurnForceFinalizeGraceSeconds()))
|| running.cancelGraceElapsed(config.getTurnForceFinalizeGraceSeconds()))
{
Stop stop = running.isCancelled() ? cancelledStop() : new Stop("ERROR", "TIMEOUT", TIMEOUT_TEXT, "timeout");
finish(stop.status(), stop.stopReason(), stop.errorCode(), stop.message());
}
}
}
}
@@ -449,11 +512,63 @@ public class TurnEngine implements Runnable
{
Thread.currentThread().interrupt();
}
finally
{
QContext.clear();
}
});
}
/*******************************************************************************
** Renew only an active row, then observe persisted cancellation requests.
*******************************************************************************/
private synchronized void heartbeat() throws QException
{
if(running.isFinalized())
{
return;
}
AssistantTurn row = store.getTurn(userId, turn.getId());
if(row == null || !("RUNNING".equals(row.getStatus()) || "CANCELLING".equals(row.getStatus())))
{
safely(() -> running.cancel("USER"));
finish(row == null ? "ERROR" : row.getStatus(), row == null ? "interrupted" : row.getStopReason(),
row == null ? "INTERNAL" : row.getErrorCode(), null);
return;
}
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord().withValue("id", turn.getId())
.withValue("heartbeatAt", runtime.getClock().instant()).withValue("phase", running.getPhase()));
row = store.getTurn(userId, turn.getId());
if(row != null && (row.getCancelRequestedAt() != null || "CANCELLING".equals(row.getStatus())))
{
running.cancel(row.getCancelReason() == null ? "USER" : row.getCancelReason());
}
}
/*******************************************************************************
** Finalize from shutdown using the original authenticated user's context.
*******************************************************************************/
private void forceFinish(String reason)
{
try
{
QContext.init(runtime.getQInstance(), session);
safely(() -> running.cancel(reason));
Stop stop = "SHUTDOWN".equals(reason) ? new Stop("ERROR", "INTERRUPTED", RESTART_TEXT, "interrupted") : cancelledStop();
finish(stop.status(), stop.stopReason(), stop.errorCode(), stop.message());
}
finally
{
QContext.clear();
}
}
/*******************************************************************************
** Why a turn stops.
*******************************************************************************/
@@ -488,14 +603,15 @@ public class TurnEngine implements Runnable
}
if(!runtime.getClock().instant().isBefore(deadline))
{
return (new Stop("ERROR", "TIMEOUT", "The assistant ran out of time for this question.", "timeout"));
running.cancel("TIMEOUT");
return (cancelledStop());
}
try
{
AssistantTurn row = store.getTurn(userId, turn.getId());
if(row != null && "CANCELLING".equals(row.getStatus()))
{
running.cancel("USER");
running.cancel(row.getCancelReason() == null ? "USER" : row.getCancelReason());
return (cancelledStop());
}
}
@@ -513,6 +629,18 @@ public class TurnEngine implements Runnable
*******************************************************************************/
private Stop cancelledStop()
{
if("TIMEOUT".equals(running.getCancelReason()))
{
return (new Stop("ERROR", "TIMEOUT", TIMEOUT_TEXT, "timeout"));
}
if("SHUTDOWN".equals(running.getCancelReason()))
{
return (new Stop("ERROR", "INTERRUPTED", RESTART_TEXT, "interrupted"));
}
if("SUPERSEDED".equals(running.getCancelReason()))
{
return (new Stop("CANCELLED", null, SUPERSEDED_TEXT, ModelResponse.STOP_CANCELLED));
}
if("KILL_SWITCH".equals(running.getCancelReason()))
{
String reason = StringUtils.hasContent(policy.killSwitchReason()) ? " " + policy.killSwitchReason() : "";
@@ -602,6 +730,7 @@ public class TurnEngine implements Runnable
@Override
public void onTextDelta(String text)
{
phase("writing", null);
bufferText(text);
}
};
@@ -623,6 +752,7 @@ public class TurnEngine implements Runnable
TurnDataRouting.beforeModelCall(runtime, classification, turn, active);
fallback.beforeCall(active);
modelCallCount++;
phase("thinking", null);
StreamHandle handle = provider.stream(request.copy(), fallback.listener(listener));
running.setCurrentHandle(handle);
try
@@ -691,6 +821,7 @@ public class TurnEngine implements Runnable
continue;
}
toolCallCount++;
phase("tool", use.getToolName());
emit(TurnEvent.TOOL_START, map("messageId", assistantMessage.getId(), "toolCallId", use.getToolUseId(), "name", use.getToolName(), "summary", ToolLabels.running(use.getToolName())));
if(!allowedTools.contains(use.getToolName()))
@@ -870,7 +1001,7 @@ public class TurnEngine implements Runnable
.withUserId(userId)
.withToolCallId(use.getToolUseId())
.withToolName(use.getToolName())
.withClientChannel(scheduledTask == null ? null : "assistant/scheduled/" + scheduledTask.getId())
.withClientChannel(scheduledTask == null ? "assistant/" + turn.getId() : "assistant/scheduled/" + scheduledTask.getId())
.withInputJson(truncate(redactInput(PresentResultsTool.NAME.equals(use.getToolName()) ? (presentation ? result.getRender() : Map.of()) : use.getInput()), MAX_INPUT_JSON_CHARS))
.withOutcome(outcome)
.withPermissionCheck(result.getPermissionCheck())
@@ -917,7 +1048,7 @@ public class TurnEngine implements Runnable
*******************************************************************************/
private UiApiToolbox.Context toolContext()
{
return (new UiApiToolbox.Context(session.getUuid(), userTimezone(), runtime.getUiApiGateway(), toolPolicy, this::proposeWrite));
return (new UiApiToolbox.Context(session.getUuid(), userTimezone(), runtime.getUiApiGateway(), toolPolicy, this::proposeWrite, credentials, turn.getId() == null ? null : String.valueOf(turn.getId())));
}
@@ -980,93 +1111,100 @@ public class TurnEngine implements Runnable
/*******************************************************************************
** Persist the message, turn, conversation and usage; emit the end events.
*******************************************************************************/
private void finish(String status, String stopReason, String errorCode, String errorText)
private synchronized void finish(String status, String stopReason, String errorCode, String errorText)
{
if(!running.tryFinalize())
{
return;
}
try
{
persistClassification();
flushText(true);
Instant now = runtime.getClock().instant();
if(errorText != null)
{
parts.addNotice("error", errorText);
}
String model = this.model != null ? this.model : (policy == null ? null : policy.mainModel());
AssistantTurn persistedTurn = null;
try
{
store.updateFields(AssistantMessage.TABLE_NAME, new QRecord()
.withValue("id", assistantMessage.getId())
.withValue("status", status)
.withValue("model", model)
.withValue("partsJson", parts.toJson()));
AssistantConversation current = store.getConversation(userId, conversation.getId());
if(current != null)
{
store.updateFields(AssistantConversation.TABLE_NAME, new QRecord()
.withValue("id", current.getId())
.withValue("lastMessageAt", now)
.withValue("unreadCount", (current.getUnreadCount() == null ? 0 : current.getUnreadCount()) + 1)
.withValue("totalTokensIn", nz(current.getTotalTokensIn()) + nz(usage.getInputTokens()) + nz(usage.getCacheReadTokens()) + nz(usage.getCacheWriteTokens()))
.withValue("totalTokensOut", nz(current.getTotalTokensOut()) + nz(usage.getOutputTokens()))
.withValue("totalCostMicros", nz(current.getTotalCostMicros()) + costMicros));
}
store.addUsage(userId, LocalDate.now(runtime.getClock().withZone(ZoneOffset.UTC)), usage, costMicros, true);
persistedTurn = store.getTurn(userId, turn.getId());
}
catch(QException e)
catch(Exception e)
{
LOG.warn("Could not persist the end of an assistant turn", hipaaSafe(e), logPair("turnId", turn.getId()));
LOG.warn("Could not read final assistant status", hipaaSafe(e), logPair("turnId", turn.getId()));
}
boolean alreadyTerminal = persistedTurn != null && !("RUNNING".equals(persistedTurn.getStatus()) || "CANCELLING".equals(persistedTurn.getStatus()));
if(alreadyTerminal)
{
status = persistedTurn.getStatus();
stopReason = persistedTurn.getStopReason();
errorCode = persistedTurn.getErrorCode();
}
String finalStatus = status;
String finalStopReason = stopReason;
String finalErrorCode = errorCode;
String model = this.model != null ? this.model : (policy == null ? null : policy.mainModel());
Instant now = runtime.getClock().instant();
safely(() -> flushText(true));
if(errorText != null && !alreadyTerminal)
{
parts.addNotice("CANCELLED".equals(status) ? "info" : "error", errorText);
}
running.setPhase("done", null);
if(!alreadyTerminal)
{
safely(() -> persistClassification());
safely(() -> store.updateFields(AssistantMessage.TABLE_NAME, new QRecord()
.withValue("id", assistantMessage.getId()).withValue("status", finalStatus)
.withValue("model", model).withValue("partsJson", parts.toJson())));
}
/////////////////////////////////////////////////////////////////////
// terminal events are persisted BEFORE the turn row turns final, //
// so a replay of a finished turn always ends with message.end //
/////////////////////////////////////////////////////////////////////
emit(TurnEvent.USAGE, map("turnId", turn.getId(), "inputTokens", usage.getInputTokens(), "outputTokens", usage.getOutputTokens(),
"cacheReadTokens", usage.getCacheReadTokens(), "cacheWriteTokens", usage.getCacheWriteTokens(), "costMicros", costMicros));
if(errorCode != null)
{
emit(TurnEvent.ERROR, map("code", errorCode, "message", errorText));
}
Map<String, Object> end = map("messageId", assistantMessage.getId(), "status", status);
if(stopReason != null)
emit(TurnEvent.MESSAGE_END, map("messageId", assistantMessage.getId(), "status", status, "stopReason", stopReason));
if(!alreadyTerminal)
{
end.put("stopReason", stopReason);
safely(this::persistPendingEvents);
// Accounting failures cannot skip the terminal row or local cleanup.
safely(() ->
{
store.updateRunningTurn(userId, new QRecord()
.withValue("id", turn.getId())
.withValue("status", finalStatus)
.withValue("phase", "done")
.withValue("stopReason", truncate(finalStopReason, 64))
.withValue("errorCode", finalErrorCode)
.withValue("cancelReason", running.getCancelReason())
.withValue("model", model)
.withValue("providerId", active == null ? null : active.providerId())
.withValue("routeDecision", turn.getRouteDecision())
.withValue("routeSource", turn.getRouteSource())
.withValue("fallbackCount", turn.getFallbackCount())
.withValue("endedAt", now)
.withValue("toolCallCount", toolCallCount)
.withValue("modelCallCount", modelCallCount)
.withValue("inputTokens", usage.getInputTokens())
.withValue("outputTokens", usage.getOutputTokens())
.withValue("cacheReadTokens", usage.getCacheReadTokens())
.withValue("cacheWriteTokens", usage.getCacheWriteTokens())
.withValue("costMicros", costMicros)
.withValue("providerRequestIds", requestIds.isEmpty() ? null : String.join(",", requestIds)));
});
safely(() ->
{
AssistantConversation current = store.getConversation(userId, conversation.getId());
if(current != null)
{
store.updateFields(AssistantConversation.TABLE_NAME, new QRecord()
.withValue("id", current.getId())
.withValue("lastMessageAt", now)
.withValue("unreadCount", (current.getUnreadCount() == null ? 0 : current.getUnreadCount()) + 1)
.withValue("totalTokensIn", nz(current.getTotalTokensIn()) + nz(usage.getInputTokens()) + nz(usage.getCacheReadTokens()) + nz(usage.getCacheWriteTokens()))
.withValue("totalTokensOut", nz(current.getTotalTokensOut()) + nz(usage.getOutputTokens()))
.withValue("totalCostMicros", nz(current.getTotalCostMicros()) + costMicros));
}
});
safely(() -> store.addUsage(userId, LocalDate.now(runtime.getClock().withZone(ZoneOffset.UTC)), usage, costMicros, true));
}
emit(TurnEvent.MESSAGE_END, end);
persistPendingEvents();
try
{
store.updateFields(AssistantTurn.TABLE_NAME, new QRecord()
.withValue("id", turn.getId())
.withValue("status", status)
.withValue("stopReason", truncate(stopReason, 64))
.withValue("errorCode", errorCode)
.withValue("cancelReason", running.getCancelReason())
.withValue("model", model)
.withValue("providerId", active == null ? null : active.providerId())
.withValue("routeDecision", turn.getRouteDecision())
.withValue("routeSource", turn.getRouteSource())
.withValue("fallbackCount", turn.getFallbackCount())
.withValue("endedAt", now)
.withValue("toolCallCount", toolCallCount)
.withValue("modelCallCount", modelCallCount)
.withValue("inputTokens", usage.getInputTokens())
.withValue("outputTokens", usage.getOutputTokens())
.withValue("cacheReadTokens", usage.getCacheReadTokens())
.withValue("cacheWriteTokens", usage.getCacheWriteTokens())
.withValue("costMicros", costMicros)
.withValue("providerRequestIds", requestIds.isEmpty() ? null : String.join(",", requestIds)));
}
catch(QException e)
{
LOG.warn("Could not persist the end of an assistant turn", hipaaSafe(e), logPair("turnId", turn.getId()));
}
LOG.info("Assistant turn finished",
logPair("turnId", turn.getId()),
logPair("conversationId", conversation.getId()),
@@ -1075,6 +1213,7 @@ public class TurnEngine implements Runnable
logPair("status", status),
logPair("stopReason", stopReason),
logPair("errorCode", errorCode),
logPair("cancelReason", running.getCancelReason()),
logPair("modelCalls", modelCallCount),
logPair("toolCalls", toolCallCount),
logPair("inputTokens", usage.getInputTokens()),
@@ -1084,29 +1223,90 @@ public class TurnEngine implements Runnable
logPair("costMicros", costMicros),
logPair("durationMs", Duration.between(startedAt, now).toMillis()));
}
catch(QException | RuntimeException e)
{
LOG.warn("Assistant turn finish failed", hipaaSafe(e), logPair("turnId", turn.getId()));
}
finally
{
finished = true;
running.getLog().close();
if(scheduledTask != null)
safely(() ->
{
runtime.getScheduledTurn().detach(conversation.getId(), session.getUuid());
if(scheduledTask != null)
{
runtime.getScheduledTurn().detach(conversation.getId(), session.getUuid());
}
});
String finalStatus = status;
String finalText = errorText;
try
{
safely(() -> config.getRunTracker().finish(running.getTrackingId(), finalStatus, finalText));
}
finally
{
runtime.unregister(turn.getId());
runtime.getRateLimiter().release(userId);
}
runtime.unregister(turn.getId());
runtime.getRateLimiter().release(userId);
}
}
/*******************************************************************************
** One independently fallible finalization operation.
*******************************************************************************/
@FunctionalInterface
private interface FinishStep
{
/*******************************************************************************
** Execute the step.
*******************************************************************************/
void run() throws Exception;
}
/*******************************************************************************
** A failure in a collaborator must not strand the run.
*******************************************************************************/
private void safely(FinishStep step)
{
try
{
step.run();
}
catch(Exception e)
{
LOG.warn("Assistant lifecycle step failed", hipaaSafe(e), logPair("turnId", turn.getId()));
}
}
/*******************************************************************************
** Emit and track only phase changes, including the current tool label.
*******************************************************************************/
private synchronized void phase(String phase, String toolName)
{
if(running.isFinalized() || (phase.equals(running.getPhase()) && Objects.equals(toolName, running.getToolName())))
{
return;
}
running.setPhase(phase, toolName);
String label = toolName == null ? phase : ToolLabels.running(toolName);
emit(TurnEvent.TURN_PHASE, map("phase", phase, "toolName", toolName, "label", label));
safely(() -> config.getRunTracker().progress(running.getTrackingId(), phase, label));
}
/*******************************************************************************
** Buffer streamed text; emit it in small chunks (provider thread).
*******************************************************************************/
private void bufferText(String text)
private synchronized void bufferText(String text)
{
if(running.isFinalized())
{
return;
}
synchronized(textBuffer)
{
textBuffer.append(text);
@@ -1119,7 +1319,7 @@ public class TurnEngine implements Runnable
/*******************************************************************************
** Emit buffered text as one text.delta (when big or old enough, or forced).
*******************************************************************************/
private void flushText(boolean force)
private synchronized void flushText(boolean force)
{
String chunk;
synchronized(textBuffer)
@@ -1154,8 +1354,12 @@ public class TurnEngine implements Runnable
** Append to the live log; queue for persistence (done on the engine
** thread, which has the QContext).
*******************************************************************************/
private void emit(String type, Map<String, Object> data)
private synchronized void emit(String type, Map<String, Object> data)
{
if(finished)
{
return;
}
toPersist.add(running.getLog().append(type, data));
}
@@ -1173,7 +1377,7 @@ public class TurnEngine implements Runnable
{
store.insertEvent(turn.getId(), userId, event.getSeq(), event.getType(), event.toJson());
}
catch(QException e)
catch(Exception e)
{
LOG.warn("Could not persist assistant turn event", hipaaSafe(e), logPair("turnId", turn.getId()), logPair("seq", event.getSeq()));
}
@@ -29,6 +29,7 @@ import com.kingsrook.qqq.backend.core.utils.JsonUtils;
*******************************************************************************/
public class TurnEvent
{
public static final String TURN_PHASE = "turn.phase";
public static final String MESSAGE_START = "message.start";
public static final String TEXT_DELTA = "text.delta";
public static final String TOOL_START = "tool.start";
@@ -19,9 +19,10 @@ package com.kingsrook.qbits.assistant.engine;
import com.kingsrook.qbits.assistant.model.AssistantUsage;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.ModelProviderException;
import com.kingsrook.qbits.assistant.provider.ModelResponse;
import com.kingsrook.qbits.assistant.provider.ModelUsage;
import com.kingsrook.qbits.assistant.spi.ModelPricing;
import com.kingsrook.qbits.assistant.spi.ModelProviderException;
import com.kingsrook.qbits.assistant.spi.ModelResponse;
import com.kingsrook.qbits.assistant.spi.ModelUsage;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
@@ -17,7 +17,15 @@
package com.kingsrook.qbits.assistant.home;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.AssistantSecurity;
import com.kingsrook.qbits.assistant.engine.BudgetService;
@@ -29,23 +37,15 @@ import com.kingsrook.qbits.assistant.model.AssistantBudgetOverride;
import com.kingsrook.qbits.assistant.model.AssistantConversation;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.model.AssistantToolCall;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.model.AssistantUsage;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterOrderBy;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*******************************************************************************
@@ -75,6 +75,7 @@ public class AssistantHomeData
private final List<Totals> byProvider = new ArrayList<>();
private Long fallbackCount = 0L;
private List<AssistantSetupStatus.Item> setup = List.of();
private Boolean hipaaMode;
private Integer hipaaRetentionDays;
private LocalDate today;
@@ -313,6 +314,7 @@ public class AssistantHomeData
data.providers.add(new ProviderHealth(row, type == null ? row.getProviderType() : type.getLabel(), status, (status.startsWith("Set") || status.startsWith("Not needed")), service.validate(row), active != null && active.getId().equals(row.getId()),
providerMonth.getOrDefault(row.getId(), 0L), ProviderService.capMicros(row), service.kind(row), service.location(row), service.models(row.getId()).stream().filter(m -> Boolean.TRUE.equals(m.getEnabled())).count()));
}
data.setup = AssistantSetupStatus.load(runtime, data.providers);
return (data);
}
@@ -578,4 +580,15 @@ public class AssistantHomeData
{
return (fallbackCount);
}
/*******************************************************************************
** The Setup card: each configuration table, its state and the next step.
*******************************************************************************/
public List<AssistantSetupStatus.Item> getSetup()
{
return (setup);
}
}
@@ -90,6 +90,7 @@ public final class AssistantHomeView
public static String render(AssistantHomeData data, String prefix)
{
StringBuilder html = new StringBuilder("<div class=\"assistant-home\" style=\"" + ROOT + "\">");
setup(html, data, prefix);
status(html, data, prefix);
providers(html, data, prefix);
html.append("<div style=\"").append(GRID).append("\">");
@@ -111,6 +112,52 @@ public final class AssistantHomeView
/*******************************************************************************
** The Setup card: each part of the assistant, set up or not, and the next
** step, linked to its table.
*******************************************************************************/
private static void setup(StringBuilder html, AssistantHomeData data, String prefix)
{
if(data.getSetup().isEmpty())
{
return;
}
open(html, "Setup");
long todo = data.getSetup().stream().filter(i -> i.state() == AssistantSetupStatus.State.TODO).count();
html.append("<p style=\"margin:0 0 .6rem;font-size:.9rem;\">")
.append(todo == 0 ? "Everything the assistant needs is set up." : esc(todo + (todo == 1 ? " item needs" : " items need") + " attention."))
.append("</p><ul style=\"list-style:none;margin:0;padding:0;\">");
for(AssistantSetupStatus.Item item : data.getSetup())
{
String color = switch(item.state())
{
case OK -> GREEN;
case TODO -> RED;
case DEFAULT -> AMBER;
case OPTIONAL -> GREY;
};
String label = switch(item.state())
{
case OK -> "Set up";
case TODO -> "Needs setup";
case DEFAULT -> "Using defaults";
case OPTIONAL -> "Optional";
};
html.append("<li style=\"").append(ROW).append("\"><div style=\"display:flex;flex-wrap:wrap;align-items:center;gap:.5rem .75rem;\">")
.append("<strong><a style=\"").append(LINK).append("\" href=\"").append(esc(prefix + "/" + item.tableName())).append("\">").append(esc(item.label())).append("</a></strong>")
.append(chip(color, label)).append("</div><div style=\"font-size:.9rem;margin-top:.35rem;\">").append(esc(item.detail())).append("</div>");
if(item.nextStep() != null)
{
html.append("<div style=\"").append(MUTED).append("font-size:.9rem;margin-top:.2rem;\">Next: ").append(esc(item.nextStep())).append("</div>");
}
html.append("</li>");
}
html.append("</ul>");
close(html);
}
/*******************************************************************************
** The status row: is the assistant answering, with what, at what cost.
*******************************************************************************/
@@ -0,0 +1,231 @@
/*
* 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.home;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.engine.ProviderService;
import com.kingsrook.qbits.assistant.model.AssistantBudget;
import com.kingsrook.qbits.assistant.model.AssistantDataAccess;
import com.kingsrook.qbits.assistant.model.AssistantModelPrice;
import com.kingsrook.qbits.assistant.model.AssistantPolicy;
import com.kingsrook.qbits.assistant.model.AssistantProfile;
import com.kingsrook.qbits.assistant.model.AssistantProfileSkill;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.model.AssistantRagSource;
import com.kingsrook.qbits.assistant.model.AssistantScheduledTask;
import com.kingsrook.qbits.assistant.model.AssistantSkill;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.spi.ModelPricing;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
/*******************************************************************************
** The Setup card on the Assistant home: each configuration table, whether it
** is set up, and the next step. Only reads the QBit's own configuration
** tables (small), as the signed-in administrator.
*******************************************************************************/
public final class AssistantSetupStatus
{
private static final int LIMIT = 1000;
/*******************************************************************************
** OK: working. TODO: the assistant needs it. DEFAULT: working on built-in
** defaults (nothing to do). OPTIONAL: a feature that is off until set up.
*******************************************************************************/
public enum State
{
OK, TODO, DEFAULT, OPTIONAL
}
/*******************************************************************************
** One line of the card.
*******************************************************************************/
public record Item(String label, String tableName, State state, String detail, String nextStep)
{
}
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AssistantSetupStatus()
{
}
/*******************************************************************************
** Build the items. `providers` is what the home already loaded.
*******************************************************************************/
public static List<Item> load(AssistantRuntime runtime, List<AssistantHomeData.ProviderHealth> providers) throws QException
{
AssistantStore store = runtime.getStore();
List<Item> items = new ArrayList<>();
///////////////
// providers //
///////////////
AssistantHomeData.ProviderHealth active = providers.stream().filter(AssistantHomeData.ProviderHealth::active).findFirst().orElse(null);
if(active != null && active.keyPresent() && active.problems().isEmpty())
{
items.add(new Item("Provider", AssistantProvider.TABLE_NAME, State.OK, active.row().getName() + " answers questions.", null));
}
else if(providers.isEmpty())
{
items.add(new Item("Provider", AssistantProvider.TABLE_NAME, State.TODO, "No provider yet.", "Add one with New: pick the type and model, and name the environment variable that holds the API key."));
}
else
{
items.add(new Item("Provider", AssistantProvider.TABLE_NAME, State.TODO, "The default provider cannot be used.", "Turn one on, set it as default, make sure its key variable is set, then run Test connection."));
}
//////////////////////////////////////////////////////////////////////
// prices: resolved exactly as calls are costed (registry row, price //
// row, then the configured price table); local models cost nothing //
//////////////////////////////////////////////////////////////////////
int priceRows = store.query(AssistantModelPrice.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantModelPrice.class).size();
String rowsText = priceRows + " price row" + (priceRows == 1 ? "" : "s");
if(active == null)
{
items.add(new Item("Model prices", AssistantModelPrice.TABLE_NAME, State.DEFAULT, rowsText + "; checked once a provider answers.", null));
}
else
{
AssistantProvider row = active.row();
ModelPricing price = runtime.getProviderService().pricing(new ProviderService.Active(row, row.getProviderType(), row.getModel(), null), row.getModel());
boolean local = "LOCAL".equals(active.location());
boolean known = price != null && (positive(price.getInputUsdPerMTok()) || positive(price.getOutputUsdPerMTok()));
items.add(known || local
? new Item("Model prices", AssistantModelPrice.TABLE_NAME, State.OK, local && !known ? "The default model is local and costs nothing. " + rowsText + "."
: "The default model is priced at $" + price.getInputUsdPerMTok() + " in / $" + price.getOutputUsdPerMTok() + " out per million tokens. " + rowsText + ".", null)
: new Item("Model prices", AssistantModelPrice.TABLE_NAME, State.TODO, "The default model (" + row.getModel() + ") has no price, so its calls cost $0 and cost budgets never trigger.",
"Add a price row for its provider type and model."));
}
////////////
// policy //
////////////
List<AssistantPolicy> policies = store.query(AssistantPolicy.TABLE_NAME, new QQueryFilter().withLimit(1), AssistantPolicy.class);
if(policies.isEmpty())
{
items.add(new Item("Policy", AssistantPolicy.TABLE_NAME, State.DEFAULT, "No policy row: the code configuration applies.", "Add one to control the kill switch, confirmations and tool limits here."));
}
else if(Boolean.TRUE.equals(policies.get(0).getKillSwitch()))
{
items.add(new Item("Policy", AssistantPolicy.TABLE_NAME, State.TODO, "The kill switch is on: the assistant answers nothing.", "Turn it off on the policy row when ready."));
}
else
{
items.add(new Item("Policy", AssistantPolicy.TABLE_NAME, State.OK, "Writes " + (Boolean.FALSE.equals(policies.get(0).getWritesRequireConfirmation()) ? "do not wait" : "wait") + " for confirmation.", null));
}
////////////////////////
// profiles and skills //
////////////////////////
List<AssistantProfile> profiles = enabled(store.query(AssistantProfile.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantProfile.class));
boolean hasDefault = profiles.stream().anyMatch(p -> Boolean.TRUE.equals(p.getIsDefault()));
items.add(profiles.isEmpty()
? new Item("Profiles", AssistantProfile.TABLE_NAME, State.DEFAULT, "No profile: the built-in assistant answers, with no skills.", "Add a default profile to name the assistant, set its tone and offer skills.")
: new Item("Profiles", AssistantProfile.TABLE_NAME, hasDefault ? State.OK : State.DEFAULT,
profiles.size() + " profile" + (profiles.size() == 1 ? "" : "s") + (hasDefault ? ", with a default." : ", none of them the default."),
hasDefault ? null : "Mark one as the default so it applies everywhere else."));
Set<Integer> linkedSkillIds = new HashSet<>();
Set<Integer> profileIds = new HashSet<>(profiles.stream().map(AssistantProfile::getId).toList());
for(AssistantProfileSkill link : store.query(AssistantProfileSkill.TABLE_NAME, new QQueryFilter().withLimit(LIMIT * 5), AssistantProfileSkill.class))
{
if(profileIds.contains(link.getProfileId()))
{
linkedSkillIds.add(link.getSkillId());
}
}
List<AssistantSkill> skills = enabled(store.query(AssistantSkill.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantSkill.class));
long offered = skills.stream().filter(s -> linkedSkillIds.contains(s.getId())).count();
items.add(skills.isEmpty()
? new Item("Skills", AssistantSkill.TABLE_NAME, State.OPTIONAL, "No skills.", "Write know-how for your business terms, then link it to a profile.")
: offered == 0
? new Item("Skills", AssistantSkill.TABLE_NAME, State.TODO, skills.size() + " skill" + (skills.size() == 1 ? "" : "s") + ", but none is linked to a turned-on profile, so the model never sees them.", "Link them to a profile (Profile skills).")
: new Item("Skills", AssistantSkill.TABLE_NAME, State.OK, offered + " of " + skills.size() + " skill" + (skills.size() == 1 ? " is" : "s are") + " offered through a profile.", null));
/////////////
// budgets //
/////////////
List<AssistantBudget> budgets = store.budgets();
items.add(budgets.isEmpty()
? new Item("Budgets", AssistantBudget.TABLE_NAME, State.TODO, "No budget: spending is limited only by the policy's configured caps.", "Add a monthly instance budget (warn, downgrade, stop).")
: new Item("Budgets", AssistantBudget.TABLE_NAME, State.OK, budgets.size() + " budget" + (budgets.size() == 1 ? "" : "s") + " checked before every question.", null));
/////////////////
// data access //
/////////////////
int accessRows = store.query(AssistantDataAccess.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantDataAccess.class).size();
items.add(accessRows == 0
? new Item("Data access", AssistantDataAccess.TABLE_NAME, State.DEFAULT, "Defaults: the assistant may read what each user can read; it proposes no changes.",
"Run Add rows for every table to review them, then raise tables to READ_WRITE where it may propose changes.")
: new Item("Data access", AssistantDataAccess.TABLE_NAME, State.OK, accessRows + " row" + (accessRows == 1 ? "" : "s") + "; tables without a row use the default.", null));
///////////////////////////////////////
// optional: knowledge and schedules //
///////////////////////////////////////
long sources = enabled(store.query(AssistantRagSource.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantRagSource.class)).size();
items.add(sources == 0
? new Item("Knowledge sources", AssistantRagSource.TABLE_NAME, State.OPTIONAL, "Off: search by meaning is not offered.", "Add a source (a readable table, its text fields and an embedding model), then index it.")
: new Item("Knowledge sources", AssistantRagSource.TABLE_NAME, State.OK, sources + " source" + (sources == 1 ? "" : "s") + " turned on.", null));
List<AssistantScheduledTask> tasks = store.query(AssistantScheduledTask.TABLE_NAME, new QQueryFilter().withLimit(LIMIT), AssistantScheduledTask.class);
long onTasks = tasks.stream().filter(t -> Boolean.TRUE.equals(t.getEnabled())).count();
items.add(onTasks == 0
? new Item("Scheduled tasks", AssistantScheduledTask.TABLE_NAME, State.OPTIONAL, tasks.isEmpty() ? "None." : tasks.size() + " task" + (tasks.size() == 1 ? "" : "s") + ", all turned off.",
"Set a run-as user and an allowed credential variable on a task, then turn it on.")
: new Item("Scheduled tasks", AssistantScheduledTask.TABLE_NAME, State.OK, onTasks + " task" + (onTasks == 1 ? "" : "s") + " turned on.", null));
return (items);
}
/*******************************************************************************
** Rows not explicitly turned off.
*******************************************************************************/
private static <T extends QRecordEntity> List<T> enabled(List<T> rows)
{
return (rows.stream().filter(row -> !Boolean.FALSE.equals(row.toQRecord().getValueBoolean("enabled"))).toList());
}
/*******************************************************************************
**
*******************************************************************************/
private static boolean positive(Double value)
{
return (value != null && value > 0);
}
}
@@ -0,0 +1,75 @@
/*
* 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.jobs;
/*******************************************************************************
** STAND-IN(core=QRun-IO/qqq#1210, removeBy=RC.9): core job tracking
** (jobs_job tracking rows) will implement this contract; hosts may wire their own.
*******************************************************************************/
public interface AssistantRunTracker
{
AssistantRunTracker NOOP = new AssistantRunTracker()
{
/*******************************************************************************
** No tracking is configured.
*******************************************************************************/
@Override
public String start(String userId, Integer turnId, Integer conversationId, String label)
{
return (null);
}
/*******************************************************************************
** No tracking is configured.
*******************************************************************************/
@Override
public void progress(String trackingId, String phase, String message)
{
}
/*******************************************************************************
** No tracking is configured.
*******************************************************************************/
@Override
public void finish(String trackingId, String status, String message)
{
}
};
/*******************************************************************************
** Publish a run and return its tracking id.
*******************************************************************************/
String start(String userId, Integer turnId, Integer conversationId, String label);
/*******************************************************************************
** Publish a changed phase.
*******************************************************************************/
void progress(String trackingId, String phase, String message);
/*******************************************************************************
** Publish the terminal outcome.
*******************************************************************************/
void finish(String trackingId, String status, String message);
/*******************************************************************************
** Wire the host's Stop action to the owner's cancellation path.
*******************************************************************************/
default void onCancel(String trackingId, Runnable cancel)
{
}
}
@@ -0,0 +1,96 @@
/*
* 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.metadata;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.kingsrook.qbits.assistant.AssistantQBitProducer;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.ClientChannelsMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.qbits.SourceQBitAware;
/*******************************************************************************
** Register and verify the assistant's configuration wall beneath user permissions.
*******************************************************************************/
public final class AssistantChannelWall
{
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AssistantChannelWall()
{
}
/*******************************************************************************
** Enumerate the instance so new assistant metadata cannot miss registration.
** Preserve host permissions and other denied channels.
*******************************************************************************/
public static void register(QInstance qInstance)
{
ClientChannelsMetaData.ofOrWithNew(qInstance).withDeniedPattern("assistant", "assistant_*");
for(MetaDataWithPermissionRules object : objects(qInstance))
{
QPermissionRules rules = object.getPermissionRules();
rules = rules == null ? qInstance.getDefaultPermissionRules().clone() : rules.clone();
Set<String> denied = new HashSet<>(rules.getDeniedClients() == null ? Set.of() : rules.getDeniedClients());
denied.add("assistant");
object.setPermissionRules(rules.withDeniedClients(denied));
}
}
/*******************************************************************************
** Fail before runtime initialization if a host customization opens the wall.
*******************************************************************************/
public static void validate(QInstance qInstance)
{
ClientChannelsMetaData channels = ClientChannelsMetaData.of(qInstance);
for(MetaDataWithPermissionRules object : objects(qInstance))
{
QPermissionRules rules = object.getPermissionRules() == null ? qInstance.getDefaultPermissionRules() : object.getPermissionRules();
if(!channels.isDenied("assistant", object.getName(), rules))
{
throw (new IllegalStateException("Assistant channel wall: " + object.getName() + " must be denied to client channel assistant before startup."));
}
}
}
/*******************************************************************************
** Tables, processes, reports and widgets, including host-added assistant objects.
*******************************************************************************/
private static List<MetaDataWithPermissionRules> objects(QInstance qInstance)
{
List<MetaDataWithPermissionRules> objects = new ArrayList<>();
objects.addAll(qInstance.getTables().values());
objects.addAll(qInstance.getProcesses().values());
objects.addAll(qInstance.getReports().values());
objects.addAll(qInstance.getWidgets().values());
return (objects.stream().filter(object -> (object.getName() != null && object.getName().startsWith("assistant"))
|| (object instanceof SourceQBitAware source && (AssistantQBitProducer.GROUP_ID + ":" + AssistantQBitProducer.ARTIFACT_ID).equals(source.getSourceQBitName()))).toList());
}
}
@@ -0,0 +1,126 @@
/*
* 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.metadata;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QAppMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
/*******************************************************************************
** Applies help/qbit-assistant.yaml (the QQQ help-bundle format) to the
** Assistant app and its assistant_* tables: what each table is for and how
** its rows get created, shown on the table screen and when it is empty.
** STAND-IN(core=#1198): replace with HelpBundles.register once the pinned
** QQQ release includes it; the bundle file stays the same.
*******************************************************************************/
public final class AssistantHelp
{
public static final String RESOURCE = "/help/qbit-assistant.yaml";
public static final String SLOT = "help";
/*******************************************************************************
** Utility class.
*******************************************************************************/
private AssistantHelp()
{
}
/*******************************************************************************
** The bundle's entries by key, validated (fails startup if malformed).
*******************************************************************************/
public static Map<String, JsonNode> entries() throws QException
{
try(InputStream stream = AssistantHelp.class.getResourceAsStream(RESOURCE))
{
if(stream == null)
{
throw (new IOException("missing resource"));
}
JsonNode bundle = new ObjectMapper(new YAMLFactory()).readTree(stream);
if(!"qbit-assistant".equals(bundle.path("bundle").asText()) || !"QBIT".equals(bundle.path("layer").asText()))
{
throw (new IOException("invalid bundle header"));
}
Map<String, JsonNode> entries = new LinkedHashMap<>();
for(JsonNode entry : bundle.path("entries"))
{
String key = entry.path("key").asText();
String summary = entry.path("summary").asText();
if(key.isBlank() || summary.isBlank() || summary.length() > 120 || entry.path("content").asText().isBlank() || entries.put(key, entry) != null)
{
throw (new IOException("invalid or duplicate entry: " + key));
}
}
return (entries);
}
catch(IOException | RuntimeException e)
{
throw (new QException("Could not load " + RESOURCE, e));
}
}
/*******************************************************************************
** Apply the help to the app and every assistant_* table in the instance.
** A host's own help on a table is kept (the bundle only fills the slot).
*******************************************************************************/
public static void apply(QInstance qInstance) throws QException
{
Map<String, JsonNode> entries = entries();
for(QTableMetaData table : qInstance.getTables().values())
{
JsonNode entry = entries.get("table:" + table.getName() + ";slot:" + SLOT);
if(entry != null && (table.getHelpContent() == null || !table.getHelpContent().containsKey(SLOT)))
{
table.withHelpContent(SLOT, content(entry));
}
}
QAppMetaData app = qInstance.getApp(AssistantMetaDataBuilder.APP_NAME);
JsonNode appEntry = entries.get("app:" + AssistantMetaDataBuilder.APP_NAME + ";slot:" + SLOT);
if(app != null && appEntry != null && (app.getHelpContent() == null || !app.getHelpContent().containsKey(SLOT)))
{
app.withHelpContent(SLOT, content(appEntry));
}
}
/*******************************************************************************
** Summary as the first paragraph, then the content, as markdown.
*******************************************************************************/
static QHelpContent content(JsonNode entry)
{
return (new QHelpContent().withContentAsMarkdown(entry.path("summary").asText().strip() + "\n\n" + entry.path("content").asText().strip()));
}
}
@@ -51,7 +51,7 @@ import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.model.AssistantTurnEvent;
import com.kingsrook.qbits.assistant.model.AssistantUsage;
import com.kingsrook.qbits.assistant.model.AssistantUsageDaily;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.ChildRecordListRenderer;
import com.kingsrook.qqq.backend.core.instances.QInstanceEnricher;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
@@ -26,7 +26,7 @@ import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.model.AssistantModel;
import com.kingsrook.qbits.assistant.model.AssistantProvider;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.AssistantProviderType;
import com.kingsrook.qbits.assistant.spi.AssistantProviderType;
import com.kingsrook.qqq.backend.core.actions.values.QCustomPossibleValueProvider;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
@@ -100,7 +100,7 @@ public class AssistantToolCall extends QRecordEntity
@QField(isEditable = false)
private Integer httpStatus;
@QField(isEditable = false, maxLength = 500)
@QField(isEditable = false)
private String auditHref;
@QField(isEditable = false, possibleValueSourceName = AssistantPendingAction.TABLE_NAME)
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff. Show more