Compare commits

...
2 Commits
Author SHA1 Message Date
james.maesandClaude Opus 5.5 8dd92de98e Merge develop into feature/write-mode; preferences through core Preferences
- Resolve against develop (#19 spec'd endpoints on UiApiInvoker, P-a..P-g,
  presentation, bulk-load, X1/Y1): write-mode gating now also covers
  scheduled runs (per-task approval AND policy) and bulk-load writes.
- Drop the bespoke /assistant/preferences endpoints; the assistant's
  per-user settings are a core Preferences section "assistant"
  (/qqq/v1/preferences/assistant) with AssistantPreferencesProvider over
  assistant_user_preference, policy-validated, denied to the assistant
  channel. /assistant/config still returns the effective defaults.
- Requires QQQ RC.8 (core Preferences, QRun-IO/qqq#1162).

Closes #29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:33:55 -05:00
james.maesandClaude Opus 5.5 a9ff632750 feat: write mode (Read-only by default), user preferences, auto-confirm rules
Owner (2026-10-13): the assistant can go into write mode by user choice,
and stays only a UI client of the /qqq/v1 API.

- writeMode per conversation; the write tools exist only in Write mode,
  and a write tool called in Read-only mode is refused before any request.
- Policy: writeModeAllowed, writeModePermission (role),
  autoConfirmAllowed; data access autoConfirmOk per table.
- assistant_user_preference: default mode, auto-confirm of low-risk
  writes (single-record insert/update on auto-confirm-OK tables; never
  deletes); GET/PATCH /assistant/preferences as spec'd operations.
- The denial matrix covers the write tools in both modes; WriteModeTest
  covers the tool list, policy, preferences and auto-confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:27:08 -05:00
30 changed files with 1471 additions and 48 deletions

No files matched your search

+18
View File
@@ -1,5 +1,17 @@
# Changelog
### Changed: W1 core Preferences (F13 / #29)
- Replace the bespoke assistant preferences operations with the core `assistant`
section at `/qqq/v1/preferences/assistant`, backed by the existing visible table.
User ownership, partial updates, policy validation, read-only explanations and
explicit assistant-channel denial apply to the section.
- Keep effective defaults on `/assistant/config`; preserve Read-only/Write tools,
low-risk auto-confirm, develop's core invoker, provider routing and audit context.
- Require per-task approval and Write-mode policy for scheduled writes; gate bulk
write definitions and calls by mode. Preserve default-off audit history on core develop.
- Target QQQ 4.1.0-RC.8; use the local PREFS snapshot override until publication.
## 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.
@@ -106,6 +118,12 @@ 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).
### Added (0.1.0-RC.7): write mode (owner decision 2026-10-13)
- Per-conversation **Read-only** (default) or **Write** mode: `writeMode` on conversations (PATCH, create), the write tools exist only in Write mode, and a write tool called in Read-only mode is refused before any request (`mode:READ_ONLY`).
- Policy: `writeModeAllowed`, `writeModePermission` (role), `autoConfirmAllowed`. Data access: `autoConfirmOk` per table.
- `assistant_user_preference` (own rows): default mode of new conversations, auto-confirm of low-risk writes (single-record insert/update on auto-confirm-OK tables; never deletes). Core `GET`/`PATCH /qqq/v1/preferences/assistant`; `/config` reports `features.writeMode`, `features.autoConfirm` and `preferences`.
- The denial matrix covers the write tools in both modes.
### 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.
+27 -3
View File
@@ -1,6 +1,6 @@
# QBit Assistant
An in-app AI assistant for any QQQ application. The user asks a question in a chat panel in the Next UI. The assistant reads the application's data **with exactly that user's permissions**, answers with numbers taken from the data, and links to the records and lists it used. This first version only reads data and opens screens. It cannot change anything.
An in-app AI assistant for any QQQ application. The user asks a question in a chat panel in the Next UI. The assistant reads the application's data **with exactly that user's permissions**, answers with numbers taken from the data, and links to the records and lists it used. Conversations start Read-only. Users can select Write mode when policy permits it; changes normally wait for their confirmation.
Design spec: `QRun-IO/qqq` `docs/specs/2026-10-11-qqq-assistant-qbit-design.md`.
@@ -29,9 +29,33 @@ 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.
## Write mode and personal preferences
The **Assistant** section on the core Preferences page controls **Start conversations
in Write mode** and **Auto-confirm low-risk changes**. It is available to users
with `assistant.hasAccess`, without requiring `assistant.admin` or permission on
the backing table. The standard visible `assistant_user_preference` table remains
available to administrators.
Clients read and partially update settings through `GET` / `PATCH
/qqq/v1/preferences/assistant`, with a PATCH body such as
`{"values":{"defaultWriteMode":true}}`. There is no user-id parameter. The former
`/qqq/v1/assistant/preferences` operations are removed. The panel reads effective
defaults from `/qqq/v1/assistant/config` under `preferences`; conversation responses
include `writeMode`. Policy can make the effective default Read-only even when
the saved preference is Write.
Write tools, including bulk profile saves and bulk loads, are absent in Read-only
mode. Write mode requires policy permission and READ_WRITE data access. Low-risk
auto-confirm is limited to single-record inserts/updates on `auto_confirm_ok`
tables, with both policy and user opt-in. Its preference is read-only with a reason
when policy disallows it. Scheduled tasks additionally require their own approval
and always wait for confirmation. The assistant client channel cannot access the
preferences section.
## Host audit attribution (X1/Y1)
Use QQQ **4.1.0-RC.6 or later**. The QBit explicitly denies every assistant
Use QQQ **4.1.0-RC.8 or later** (core Preferences, qqq#1162). Until RC.8 is published, build with `-Dqqq.snapshot.version=4.1.0-PREFS-SNAPSHOT`. 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
@@ -354,7 +378,7 @@ Table names follow the QRun-IO naming rule: lowercase snake_case with the `assis
```bash
./mvnw verify # against the committed QQQ version
./mvnw verify -Dqqq.snapshot.version=4.1.0-ASSISTDEV-SNAPSHOT # against a local QQQ build with #1078 + #1076
./mvnw verify -Dqqq.snapshot.version=4.1.0-PREFS-SNAPSHOT # local core Preferences build until RC.8 is published
```
Two test groups run in every build and fail it on any error:
+28
View File
@@ -1,5 +1,33 @@
# Upgrading qbit-assistant
## W1 preferences migration (F13 / #29)
Requires QQQ **4.1.0-RC.8** for core Preferences (qqq#1162). Until publication,
verify with `.\mvnw.cmd -q verify "-Dqqq.snapshot.version=4.1.0-PREFS-SNAPSHOT"`.
The root default is RC.8; do not commit the local snapshot override.
Replace `GET` / `PATCH /qqq/v1/assistant/preferences` with
`GET` / `PATCH /qqq/v1/preferences/assistant`. PATCH now wraps changed fields in
`values`, for example `{"values":{"defaultWriteMode":true}}`; GET returns the
core section metadata and `values`. Do not send a user id. Core returns 400 for
invalid or policy-read-only values and 404 for a hidden section. These removed
operations were on the unmerged W1 branch; the fragment and baseline now describe
the core integration. The panel's initial toggle continues to use effective
`preferences.defaultWriteMode` from `/qqq/v1/assistant/config`.
Existing `assistant_user_preference` rows need no data migration. Hosts installing
W1 for the first time must apply its DDL in `docs/schema-postgres.sql` (conversation
`write_mode`, policy fields, data-access `auto_confirm_ok`, and the preference
table). Keep it as a standard visible admin table. The Preferences page is scoped
by `assistant.hasAccess`, not the admin-only Assistant app. The provider explicitly
refuses the `assistant` channel because core's section channel checks only apply
to app-bound sections.
Scheduled writes now require task approval plus global/role Write-mode policy.
Bulk write tools obey the same conversation mode. Record history stays default-off
when running on core versions whose channel defaults allow audit reads.
## X1/Y1: channel wall and audit attribution
Requires QQQ 4.1.0-RC.6. Every assistant table, process, report and widget is
+35 -12
View File
@@ -238,7 +238,7 @@ The golden and red-team evals now run through the UI API too.
- **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.
- QQQ 4.1.0-RC.6 contains #1128; W1 now targets RC.8 for core Preferences (see W as built).
## Owner decisions (2026-10-13), continued: write mode, the hard wall, audit attribution, providers
@@ -264,6 +264,34 @@ Owner: *"the assistant should be able to go into 'write mode' too - with a user
- The ArchUnit rule (no core actions from the tool code) and the denial matrix stay.
- The matrix is extended to every write operation, in both modes.
### W as built (F13 / #29)
- W1 is integrated with develop's spec'd operations, `CoreUiApiGateway`, client
attribution, provider routing, presentation and bulk-load tools. Conversation
`writeMode` and all policy/data-access gates remain in force.
- `UserPreferencesMetaData` registers section `assistant` (Assistant, smart_toy),
scoped to `assistant.hasAccess`. It has no app scope because the Assistant app
requires admin access. `AssistantPreferencesProvider` implements core's SPI,
loads and updates `assistant_user_preference` through `AssistantStore`, and
obtains ownership only from the request context. The visible table remains the
administrative interface. No new preference storage is introduced.
- Core serves `GET` / `PATCH /qqq/v1/preferences/assistant`; the bespoke
`/assistant/preferences` specs are removed. PATCH uses `values` and preserves
omitted settings. Policy rejects unavailable Write defaults and auto-confirm.
Fresh field metadata marks auto-confirm read-only with policy help text when
unavailable, without mutating shared metadata. Core validates types and names.
- `/assistant/config.preferences` returns effective defaults for the panel;
new conversations apply the saved default only if Write mode is available.
The provider refuses `assistant` (including scheduled details) before accessing
rows: core only applies section channel rules through an app binding.
- Bulk write tools are absent and forged calls are denied in Read-only mode.
Scheduled mode requires the task approval and policy's global/role permission;
scheduled tools always require confirmation, regardless of user auto-confirm.
- HTTP tests cover permission visibility, own-user GET/PATCH, rejected identity
injection, policy metadata/validation, defaults and channel denial. W1's denial
matrix and both record and bulk mode paths remain covered. Build against QQQ
RC.8, or `-Dqqq.snapshot.version=4.1.0-PREFS-SNAPSHOT` before publication.
### X. The hard wall between the assistant and its configuration
Owner: *"there should also be a hard wall between the assistant and the configuration for the assistant. he should never be able to see his own configuration tables etc."*
@@ -423,7 +451,7 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
model and effort. Empty slots retain provider row/default/policy selection.
- The documented heuristic is a pure rule table: >600 characters, two distinct app
table names, complexity keywords, pending write context, >8 previous turns or a
previous tool limit. This branch has no conversation write-mode field.
previous tool limit. W1 additionally persists conversation write mode.
- Classifier transport is non-streaming, bounded to four output tokens/three seconds,
and contains only the fixed instruction and user question. PHI guards apply before
dispatch. Errors/unexpected replies use the heuristic. ROUTE usage enters budget
@@ -536,12 +564,8 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
failed calls and knowledge-query embeddings. STOP is checked at dispatch
boundaries; an in-flight call can exceed the cap, and no next call is sent.
- Every scheduled UI API request, including metadata and knowledge retrieval,
carries `X-QQQ-Client: assistant/scheduled/<taskId>`. The only uiapi change is
additive `LoopbackUiApiGateway.invokeWithClient`; custom gateways currently
fail closed for scheduled requests because their channel contract is unknown.
Tool-call rows also record `clientChannel`. Core channel deny enforcement
remains pending the client-channel RC; existing AI exposure/data-access
restrictions continue to apply on RC.5.
carries `X-QQQ-Client: assistant/scheduled/<taskId>` through `CoreUiApiGateway`.
Tool-call rows also record `clientChannel`; core enforces the configuration wall.
- Approve write mode, Revoke write mode and Run now are admin record actions
using standard streamed ETL Review/Result. Review shows the exact prompt's
SHA-256 and run-as user. Result rereads and compares the complete reviewed
@@ -549,10 +573,9 @@ AI exposure NONE is not enough, because the assistant acts as the user and an ad
A persisted approval hash additionally binds prompt, run-as user, credential
reference, profile and requested mode. Editing any of these clears approval;
ordinary saves cannot set approval or computed bookkeeping fields.
- This base has create/update/delete tools, but no W1 conversation mode/policy
switch. Scheduled runs explicitly narrow the existing tool policy: write tools
require both request and matching approval, a READ_WRITE table and the policy's
allowed-tools list. All scheduled writes require panel confirmation, including
- Scheduled runs narrow W1's tool policy: record and bulk write tools require
both request and matching approval, the designated user's global/role Write-mode
permission, a READ_WRITE table and the policy's allowed-tools list. All scheduled writes require panel confirmation, including
when normal policy allows immediate writes. A pending proposal adds a waiting
notice to the run summary; the scheduler never confirms it.
- RECORD keeps the run and conversation; NOTIFICATION and BOTH also submit an
+16
View File
@@ -369,6 +369,22 @@ CREATE TABLE assistant_profile_skill
CONSTRAINT assistant_profile_skill_pair UNIQUE (profile_id, skill_id)
);
-- 0.1.0-RC.7: write mode (per conversation, user preference, policy) and auto-confirm.
ALTER TABLE assistant_conversation ADD COLUMN IF NOT EXISTS write_mode BOOLEAN;
ALTER TABLE assistant_policy ADD COLUMN IF NOT EXISTS write_mode_allowed BOOLEAN;
ALTER TABLE assistant_policy ADD COLUMN IF NOT EXISTS write_mode_permission VARCHAR(128);
ALTER TABLE assistant_policy ADD COLUMN IF NOT EXISTS auto_confirm_allowed BOOLEAN;
ALTER TABLE assistant_data_access ADD COLUMN IF NOT EXISTS auto_confirm_ok BOOLEAN;
CREATE TABLE assistant_user_preference
(
id SERIAL PRIMARY KEY,
user_id VARCHAR(255) NOT NULL UNIQUE,
default_write_mode BOOLEAN,
auto_confirm_low_risk BOOLEAN,
create_date TIMESTAMP WITH TIME ZONE,
modify_date TIMESTAMP WITH TIME ZONE
);
CREATE TABLE assistant_data_audit
(
id SERIAL PRIMARY KEY,
+2 -1
View File
@@ -215,7 +215,8 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.6</qqq.snapshot.version>
<!-- requires QQQ RC.8 (core Preferences, qqq#1162); until it is published build with -Dqqq.snapshot.version=4.1.0-PREFS-SNAPSHOT -->
<qqq.snapshot.version>4.1.0-RC.8</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -29,6 +29,7 @@ import com.kingsrook.qbits.assistant.metadata.AssistantChannelWall;
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.metadata.AssistantPreferencesProvider;
import com.kingsrook.qbits.assistant.model.AssistantBudget;
import com.kingsrook.qbits.assistant.processes.DiscoverModelsProcess;
import com.kingsrook.qbits.assistant.processes.KnowledgeIndexProcess;
@@ -203,11 +204,16 @@ public class AssistantQBitProducer implements QBitMetaDataProducer<AssistantQBit
QAppMetaData app = builder.buildAdminApp(tables);
qInstance.addApp(app);
AssistantPreferencesProvider.register(qInstance);
AssistantChannelWall.register(qInstance);
if(Boolean.TRUE.equals(qBitConfig.getRecordHistory()))
{
enableRecordHistory(ClientChannelsMetaData.ofOrWithNew(qInstance));
}
else
{
ClientChannelsMetaData.ofOrWithNew(qInstance).withDeniedPattern("assistant", "audit*");
}
postProduceActions(new MetaDataProducerMultiOutput(), qInstance);
return (new MetaDataProducerMultiOutput());
}
@@ -132,6 +132,18 @@ public class DataAccessService
/*******************************************************************************
** Whether an admin marked the table's single-record inserts and updates as
** low-risk (auto-confirmable, when the policy and the user allow it).
*******************************************************************************/
public boolean autoConfirmOk(String tableName)
{
AssistantDataAccess row = rows().get(key(AssistantDataAccess.TYPE_TABLE, tableName));
return (row != null && Boolean.TRUE.equals(row.getAutoConfirmOk()) && forTable(tableName).mode().allowsWrite());
}
/*******************************************************************************
** Drop the cache (after a change to the table).
*******************************************************************************/
@@ -44,6 +44,7 @@ import com.kingsrook.qbits.assistant.model.AssistantPendingAction;
import com.kingsrook.qbits.assistant.model.AssistantToolCall;
import com.kingsrook.qbits.assistant.model.AssistantTurn;
import com.kingsrook.qbits.assistant.model.AssistantTurnEvent;
import com.kingsrook.qbits.assistant.model.AssistantUserPreference;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.tools.UiApiToolbox;
import com.kingsrook.qbits.assistant.tools.bulkload.BulkLoadTools;
@@ -140,7 +141,10 @@ public class AssistantApi
result.put("shortcut", config.getShortcut());
result.put("model", reason == null ? activeProvider().model() : config.getModels().getMainModel());
result.put("limits", Map.of("maxTurnSeconds", config.getMaxTurnSeconds(), "maxToolCallsPerTurn", config.getMaxToolCallsPerTurn()));
result.put("features", Map.of("writes", runtime.getToolbox().anyWritableTable(), "pendingActions", true));
boolean writeMode = reason == null && writeModeAvailable();
result.put("features", Map.of("writes", runtime.getToolbox().anyWritableTable(), "pendingActions", true, "writeMode", writeMode,
"autoConfirm", writeMode && runtime.getPolicyService().current(false).tools().autoConfirmAllowed()));
result.put("preferences", reason == null ? preferences() : Map.of());
ProfileService.Persona persona = runtime.getProfileService().persona(session, null);
Map<String, Object> profile = new LinkedHashMap<>();
profile.put("displayName", persona.displayName());
@@ -180,6 +184,12 @@ public class AssistantApi
String title = body.get("title") instanceof String s && StringUtils.hasContent(s) ? truncate(s.trim(), 255) : null;
Map<String, Object> context = body.get("context") instanceof Map<?, ?> m ? ContextBuilder.sanitizePageContext((Map<String, Object>) m) : null;
AssistantConversation conversation = store.createConversation(userId, title, context == null || context.isEmpty() ? null : JsonUtils.toJson(context));
boolean write = body.get("writeMode") instanceof Boolean requested ? requested : defaultWriteMode();
if(write && writeModeAvailable())
{
store.updateFields(AssistantConversation.TABLE_NAME, new QRecord().withValue("id", conversation.getId()).withValue("writeMode", true));
conversation.setWriteMode(true);
}
return (toJson(conversation));
}
@@ -255,6 +265,19 @@ public class AssistantApi
conversation.setStatus((String) status);
}
if(body.containsKey("writeMode"))
{
if(!(body.get("writeMode") instanceof Boolean writeMode))
{
throw (new AssistantApiException(400, "writeMode must be true or false."));
}
if(writeMode && !writeModeAvailable())
{
throw (new AssistantApiException(403, "WRITE_MODE_UNAVAILABLE", "Write mode is not available to you. An administrator controls it in the assistant policy."));
}
update.setValue("writeMode", writeMode);
conversation.setWriteMode(writeMode);
}
store.updateFields(AssistantConversation.TABLE_NAME, update);
return (toJson(conversation));
}
@@ -776,6 +799,43 @@ public class AssistantApi
/*******************************************************************************
** Whether this user may use Write mode at all: the policy allows it, they
** hold its permission (when one is set), and some table is READ_WRITE.
*******************************************************************************/
public boolean writeModeAvailable() throws QException
{
return (runtime.getPolicyService().current(false).tools().writeModeAvailableTo(session) && runtime.getToolbox().anyWritableTable());
}
/*******************************************************************************
** The default mode of the user's new conversations (Read-only unless they
** chose Write).
*******************************************************************************/
private boolean defaultWriteMode() throws QException
{
AssistantUserPreference preference = store.getPreference(userId);
return (preference != null && Boolean.TRUE.equals(preference.getDefaultWriteMode()));
}
/*******************************************************************************
** Effective defaults for the panel config, narrowed by current policy.
*******************************************************************************/
private Map<String, Object> preferences() throws QException
{
AssistantUserPreference preference = userId == null ? null : store.getPreference(userId);
Map<String, Object> map = new LinkedHashMap<>();
map.put("defaultWriteMode", writeModeAvailable() && preference != null && Boolean.TRUE.equals(preference.getDefaultWriteMode()));
map.put("autoConfirmLowRisk", runtime.getPolicyService().current(false).tools().autoConfirmAllowed() && preference != null && Boolean.TRUE.equals(preference.getAutoConfirmLowRisk()));
return (map);
}
/*******************************************************************************
** The configured turn time limit (replay loops are capped by it).
*******************************************************************************/
@@ -874,6 +934,7 @@ public class AssistantApi
map.put("title", conversation.getTitle());
map.put("status", conversation.getStatus());
map.put("pinned", Boolean.TRUE.equals(conversation.getPinned()));
map.put("writeMode", Boolean.TRUE.equals(conversation.getWriteMode()));
map.put("lastMessageAt", conversation.getLastMessageAt() == null ? null : conversation.getLastMessageAt().toString());
map.put("unreadCount", conversation.getUnreadCount() == null ? 0 : conversation.getUnreadCount());
map.put("createDate", conversation.getCreateDate() == null ? null : conversation.getCreateDate().toString());
@@ -199,9 +199,10 @@ public final class AssistantSpecs
"model", string("The model that answers."),
"limits", freeObject("maxTurnSeconds and maxToolCallsPerTurn."),
"features", freeObject("writes: some table allows writes; pendingActions: writes wait for confirmation."),
"preferences", ref("AssistantPreferencesV1"),
"profile", ref("AssistantProfileV1")));
rs.put("AssistantConversationV1", object("One of the user's own conversations.",
"id", integer(null), "title", string(null).withNullable(true), "status", string("ACTIVE or ARCHIVED."), "pinned", bool(null),
"id", integer(null), "title", string(null).withNullable(true), "status", string("ACTIVE or ARCHIVED."), "pinned", bool(null), "writeMode", bool("Write mode (default Read-only): the write tools exist only in Write mode."),
"lastMessageAt", string("ISO-8601 instant.").withNullable(true), "unreadCount", integer(null), "createDate", string("ISO-8601 instant.").withNullable(true)));
rs.put("AssistantConversationListResponseV1", object("The user's conversations, newest first.", "conversations", array(ref("AssistantConversationV1"), null)));
rs.put("AssistantMessageV1", object("A message: the user's text or the assistant's reply as parts (text, tool, record_refs, navigate, notice).",
@@ -221,6 +222,9 @@ public final class AssistantSpecs
rs.put("AssistantTurnEventV1", object("One server-sent event of a turn (event: <type>, id: <seq>, data: this object). Types: message.start, text.delta, tool.start, tool.result, ui.navigate, notice, usage, message.end, error, ping.",
"seq", integer("Sequence number; resume with ?after=<seq>."), "type", string("The event type (also the SSE event name)."),
"data", freeObject("The event's fields, by type.")));
rs.put("AssistantPreferencesV1", object("The user's own assistant preferences.",
"defaultWriteMode", bool("New conversations start in Write mode (when write mode is available)."),
"autoConfirmLowRisk", bool("Auto-confirm low-risk writes (only when the policy allows it; never deletes, bulk writes or processes).")));
rs.put("AssistantErrorV1", object("An error.", "error", string("A message for the user."), "code", string("BUDGET, RATE_LIMIT, NOT_CONFIGURED, KILL_SWITCH, DISABLED, NO_PERMISSION...").withNullable(true)));
return (rs);
}
@@ -594,7 +598,8 @@ public final class AssistantSpecs
@Override
protected Schema defineRequestBodySchema()
{
return (object("Optional title and the page context it starts from.", "title", string(null), "context", freeObject("route, tableName, recordId, filter, selectedIds.")));
return (object("Optional title, the page context it starts from, and the mode (default: the user's preference).", "title", string(null),
"context", freeObject("route, tableName, recordId, filter, selectedIds."), "writeMode", bool(null)));
}
@@ -719,7 +724,8 @@ public final class AssistantSpecs
@Override
protected Schema defineRequestBodySchema()
{
return (object("The changed properties.", "title", string(null), "pinned", bool(null), "status", string("ACTIVE or ARCHIVED.")));
return (object("The changed properties.", "title", string(null), "pinned", bool(null), "status", string("ACTIVE or ARCHIVED."),
"writeMode", bool("Switch to Write mode (true) or Read-only (false); 403 when write mode is not available to the user.")));
}
@@ -1333,4 +1339,6 @@ public final class AssistantSpecs
}
}
}
@@ -24,6 +24,7 @@ import com.kingsrook.qbits.assistant.model.AssistantUsageDaily;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.utils.StringUtils;
import java.time.Clock;
import java.time.Instant;
@@ -81,8 +82,50 @@ public class PolicyService
** @param redactPii redact secrets and personal identifiers from tool
** results (default true)
*******************************************************************************/
public record ToolPolicy(boolean writesRequireConfirmation, Set<String> allowedTools, int maxRowsPerCall, boolean redactPii)
public record ToolPolicy(boolean writesRequireConfirmation, Set<String> allowedTools, int maxRowsPerCall, boolean redactPii,
boolean writeModeAllowed, String writeModePermission, boolean autoConfirmAllowed, boolean writeMode, boolean autoConfirm)
{
/*******************************************************************************
** Write mode on, no auto-confirm, write mode allowed for everyone (tests
** and hosts that build a policy by hand).
*******************************************************************************/
public ToolPolicy(boolean writesRequireConfirmation, Set<String> allowedTools, int maxRowsPerCall, boolean redactPii)
{
this(writesRequireConfirmation, allowedTools, maxRowsPerCall, redactPii, true, null, false, true, false);
}
/*******************************************************************************
** This policy for a conversation in Write (true) or Read-only (false) mode.
*******************************************************************************/
public ToolPolicy withWriteMode(boolean writeMode)
{
return (new ToolPolicy(writesRequireConfirmation, allowedTools, maxRowsPerCall, redactPii, writeModeAllowed, writeModePermission, autoConfirmAllowed, writeMode, autoConfirm));
}
/*******************************************************************************
** This policy with the user's auto-confirm (only effective when the policy
** allows it).
*******************************************************************************/
public ToolPolicy withAutoConfirm(boolean autoConfirm)
{
return (new ToolPolicy(writesRequireConfirmation, allowedTools, maxRowsPerCall, redactPii, writeModeAllowed, writeModePermission, autoConfirmAllowed, writeMode,
autoConfirm && autoConfirmAllowed));
}
/*******************************************************************************
** Whether this user may switch a conversation to Write mode (the policy
** allows it, and they hold the write-mode permission when one is set).
*******************************************************************************/
public boolean writeModeAvailableTo(QSession session)
{
return (writeModeAllowed && (!StringUtils.hasContent(writeModePermission) || (session != null && session.hasPermission(writeModePermission.strip()))));
}
public static final int DEFAULT_MAX_ROWS_PER_CALL = 50;
public static final int MAX_ROWS_PER_CALL_CEILING = 200;
@@ -93,7 +136,7 @@ public class PolicyService
*******************************************************************************/
public static ToolPolicy defaults()
{
return (new ToolPolicy(true, Set.of(), DEFAULT_MAX_ROWS_PER_CALL, true));
return (new ToolPolicy(true, Set.of(), DEFAULT_MAX_ROWS_PER_CALL, true, true, null, false, false, false));
}
@@ -129,7 +172,8 @@ public class PolicyService
}
}
int maxRows = row.getMaxRowsPerCall() == null || row.getMaxRowsPerCall() < 1 ? DEFAULT_MAX_ROWS_PER_CALL : Math.min(MAX_ROWS_PER_CALL_CEILING, row.getMaxRowsPerCall());
return (new ToolPolicy(!Boolean.FALSE.equals(row.getWritesRequireConfirmation()), allowed, maxRows, !Boolean.FALSE.equals(row.getRedactPii())));
return (new ToolPolicy(!Boolean.FALSE.equals(row.getWritesRequireConfirmation()), allowed, maxRows, !Boolean.FALSE.equals(row.getRedactPii()),
!Boolean.FALSE.equals(row.getWriteModeAllowed()), row.getWriteModePermission(), Boolean.TRUE.equals(row.getAutoConfirmAllowed()), false, false));
}
}
@@ -43,6 +43,7 @@ import com.kingsrook.qbits.assistant.model.AssistantPendingAction;
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.model.AssistantUserPreference;
import com.kingsrook.qbits.assistant.persistence.AssistantStore;
import com.kingsrook.qbits.assistant.provider.AssistantModelProvider;
import com.kingsrook.qbits.assistant.provider.CacheHint;
@@ -134,7 +135,7 @@ public class TurnEngine implements Runnable
private long lastTextFlush = System.currentTimeMillis();
private AssistantScheduledTask scheduledTask;
private PolicyService.ToolPolicy toolPolicy;
private Instant startedAt;
private Instant deadline;
@@ -150,6 +151,7 @@ public class TurnEngine implements Runnable
private volatile boolean finished = false;
private UiApiCredentials credentials;
private PolicyService.ToolPolicy toolPolicy;
@@ -213,7 +215,7 @@ public class TurnEngine implements Runnable
{
throw (new QException("Scheduled execution context is no longer available; start a new conversation."));
}
toolPolicy = scheduledTask == null ? policy.tools() : ScheduledTurn.tools(runtime, scheduledTask, policy.tools());
toolPolicy = scheduledTask == null ? toolPolicy() : ScheduledTurn.tools(runtime, scheduledTask, policy.tools());
ScheduledTurn.checkCost(runtime, conversation.getId(), turn.getId());
classification = new TurnClassification(config.getClassificationSource(), conversation, pageContext);
store.saveClassification(userId, conversation.getId(), turn.getId(), classification);
@@ -910,6 +912,34 @@ public class TurnEngine implements Runnable
/*******************************************************************************
** The policy's tool settings for this turn: Write mode only when the
** conversation is in Write mode and write mode is available to this user;
** auto-confirm only when the policy allows it and the user chose it.
*******************************************************************************/
PolicyService.ToolPolicy toolPolicy()
{
if(toolPolicy == null)
{
PolicyService.ToolPolicy base = policy.tools();
boolean write = Boolean.TRUE.equals(conversation.getWriteMode()) && base.writeModeAvailableTo(session);
boolean auto = false;
try
{
AssistantUserPreference preference = store.getPreference(userId);
auto = preference != null && Boolean.TRUE.equals(preference.getAutoConfirmLowRisk());
}
catch(QException | RuntimeException e)
{
LOG.debug("Could not read the user's assistant preferences", e);
}
toolPolicy = base.withWriteMode(write).withAutoConfirm(auto);
}
return (toolPolicy);
}
/*******************************************************************************
** Where a data tool runs: the user's own session (by its UUID, for the UI
** API), the gateway, the policy's tool settings, and the pending-action
@@ -47,6 +47,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.model.AssistantUserPreference;
import com.kingsrook.qbits.assistant.processes.AssistantRetentionStep;
import com.kingsrook.qqq.backend.core.actions.ai.AiExposure;
import com.kingsrook.qqq.backend.core.actions.ai.AiTableMetaData;
@@ -236,6 +237,10 @@ public class AssistantMetaDataBuilder
.withUniqueKey(new UniqueKey("profileId", "skillId"))
.withRecordLabelFormat("%s · %s").withRecordLabelFields("profileId", "skillId"));
tables.add(owned(base(AssistantUserPreference.TABLE_NAME, "Assistant User Preference", "tune", AssistantUserPreference.class), false)
.withUniqueKey(new UniqueKey("userId"))
.withRecordLabelFormat("%s").withRecordLabelFields("userId"));
tables.add(readOnly(owned(base(AssistantPendingAction.TABLE_NAME, "Assistant Pending Action", "pending_actions", AssistantPendingAction.class), false))
.withRecordLabelFormat("%s #%s").withRecordLabelFields("toolName", "id"));
text(tables.get(tables.size() - 1), "paramsJson");
@@ -0,0 +1,178 @@
/*
* 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.List;
import java.util.Map;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.AssistantSecurity;
import com.kingsrook.qbits.assistant.engine.PolicyService;
import com.kingsrook.qbits.assistant.model.AssistantUserPreference;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QNotFoundException;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
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.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferenceChange;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferenceProviderInterface;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferenceRequestContext;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferenceSectionMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferenceValues;
import com.kingsrook.qqq.backend.core.model.metadata.preferences.UserPreferencesMetaData;
/*******************************************************************************
** Core preferences over the standard assistant_user_preference table. Core
** supplies the authenticated user and trusted scope, retaining audit identity.
*******************************************************************************/
public class AssistantPreferencesProvider implements UserPreferenceProviderInterface
{
public static final String SECTION = "assistant";
public static final String AUTO_CONFIRM_REASON = "Auto-confirm is not allowed by the assistant policy.";
/*******************************************************************************
** The admin app is intentionally not the scope: ordinary assistant users
** must see their own preferences without assistant.admin.
*******************************************************************************/
public static void register(QInstance qInstance)
{
UserPreferencesMetaData.ofOrWithNew(qInstance).withSection(new Section()
.withName(SECTION).withLabel("Assistant").withIcon(new QIcon("smart_toy"))
.withDescription("Defaults for new conversations and confirmation of changes.")
.withPermissionName(AssistantQBitConfig.ACCESS_PERMISSION)
.withProvider(new QCodeReference(AssistantPreferencesProvider.class)));
}
/*******************************************************************************
** Core only applies channel rules to app-scoped sections. Explicitly deny
** this unbound configuration section before loading or changing any rows.
*******************************************************************************/
private AssistantRuntime runtime(UserPreferenceRequestContext context) throws QException
{
if("assistant".equals(context.getSession().getClientChannelName()))
{
throw (new QNotFoundException("Preference section not found"));
}
AssistantRuntime runtime = AssistantRuntime.of(QContext.getQInstance());
AssistantSecurity.ownerKey(context.getSession(), runtime.getConfig());
return (runtime);
}
/*******************************************************************************
** Read only the context user's row, even if they hold an admin owner key.
*******************************************************************************/
@Override
public UserPreferenceValues load(UserPreferenceRequestContext context) throws QException
{
AssistantUserPreference preference = runtime(context).getStore().getPreference(context.getUserId());
return (new UserPreferenceValues().withValues(Map.of(
"defaultWriteMode", preference != null && Boolean.TRUE.equals(preference.getDefaultWriteMode()),
"autoConfirmLowRisk", preference != null && Boolean.TRUE.equals(preference.getAutoConfirmLowRisk()))));
}
/*******************************************************************************
** Re-read policy at the write boundary; the submitted defaults grant nothing.
*******************************************************************************/
@Override
public List<String> validate(UserPreferenceRequestContext context, UserPreferenceChange change) throws QException
{
PolicyService.ToolPolicy policy = runtime(context).getPolicyService().current(true).tools();
List<String> errors = new ArrayList<>();
if(change.getValues().containsKey("autoConfirmLowRisk") && !policy.autoConfirmAllowed())
{
errors.add("Auto-confirm low-risk changes: " + AUTO_CONFIRM_REASON);
}
if(Boolean.TRUE.equals(change.getValues().get("defaultWriteMode")) && !policy.writeModeAvailableTo(context.getSession()))
{
errors.add("Start conversations in Write mode: Write mode is not available to you under the assistant policy.");
}
return (errors);
}
/*******************************************************************************
** Apply only supplied fields; all ownership comes from the context.
*******************************************************************************/
@Override
public void store(UserPreferenceRequestContext context, UserPreferenceChange change) throws QException
{
AssistantRuntime runtime = runtime(context);
AssistantUserPreference preference = runtime.getStore().getPreference(context.getUserId());
if(preference == null)
{
preference = runtime.getStore().insert(new AssistantUserPreference().withUserId(context.getUserId())
.withDefaultWriteMode(false).withAutoConfirmLowRisk(false));
}
QRecord update = new QRecord().withValue("id", preference.getId());
change.getValues().forEach(update::setValue);
runtime.getStore().updateFields(AssistantUserPreference.TABLE_NAME, update);
}
/*******************************************************************************
** Return fresh field metadata for each request, so policy editability never
** mutates the shared instance metadata or leaks between concurrent users.
*******************************************************************************/
public static class Section extends UserPreferenceSectionMetaData
{
/*******************************************************************************
** Scalar read-only metadata uses the standard field help text for its reason.
*******************************************************************************/
@Override
public List<QFieldMetaData> getFields()
{
boolean autoConfirmAllowed = false;
AssistantRuntime runtime = AssistantRuntime.of(QContext.getQInstance());
if(runtime != null && QContext.getQSession() != null)
{
try
{
autoConfirmAllowed = runtime.getPolicyService().current(false).tools().autoConfirmAllowed();
}
catch(QException e)
{
// Fail closed when policy cannot be read; provider validation also rechecks it.
}
}
QFieldMetaData autoConfirm = new QFieldMetaData("autoConfirmLowRisk", QFieldType.BOOLEAN)
.withLabel("Auto-confirm low-risk changes").withIsEditable(autoConfirmAllowed);
if(!autoConfirmAllowed)
{
autoConfirm.withHelpContent(new QHelpContent(AUTO_CONFIRM_REASON));
}
return (List.of(new QFieldMetaData("defaultWriteMode", QFieldType.BOOLEAN).withLabel("Start conversations in Write mode"), autoConfirm));
}
}
}
@@ -574,8 +574,10 @@ public final class AssistantRecordScreens
.withHelpContent(new QHelpContent("The table or process name, e.g. blog_post. Tables without a row use the default: NONE for sensitive tables, READ for the others. Processes default to NONE."));
table.getField("mode").withLabel("Assistant access").withDefaultValue(DataAccessMode.READ.name())
.withHelpContent(new QHelpContent("NONE: the assistant never sees it. READ: the read tools may use it. READ and write: the create, update and delete tools may too. The assistant always acts with the user's own permissions and record locks; this can only narrow them. A sensitive table (AI exposure NONE) stays NONE."));
table.getField("autoConfirmOk").withLabel("Auto-confirm OK")
.withHelpContent(new QHelpContent("Single-record inserts and updates here count as low-risk: users who chose auto-confirm (where the policy allows it) skip the confirmation card. Never deletes."));
sections(table,
section("access", "Data Access", "admin_panel_settings", Tier.T1, "id", "objectType", "objectName", "mode"),
section("access", "Data Access", "admin_panel_settings", Tier.T1, "id", "objectType", "objectName", "mode", "autoConfirmOk"),
section("notes", "Notes", "notes", Tier.T2, "notes"));
}
@@ -712,6 +714,9 @@ public final class AssistantRecordScreens
help(table, "killSwitch", "On: the assistant takes no new requests from anyone.");
help(table, "killSwitchReason", "Shown to users while the kill switch is on.");
help(table, "writesRequireConfirmation", "On (or empty): every create, update or delete the assistant proposes waits for the user to confirm it in the panel. Off: writes run at once, still with the user's own permissions.");
help(table, "writeModeAllowed", "On (or empty): users may switch a conversation to Write mode, where the create, update and delete tools exist. Off: every conversation stays Read-only.");
help(table, "writeModePermission", "Optional: only users holding this permission (a role) may use Write mode.");
help(table, "autoConfirmAllowed", "On: users may choose to auto-confirm low-risk writes (single-record inserts and updates on tables marked auto-confirm OK). Never deletes, bulk writes or processes. Off (or empty): every write waits for confirmation.");
help(table, "allowedTools", "Comma-separated tool names the assistant may use (e.g. list_tables, query_records, count_records). Empty allows every tool.");
help(table, "maxRowsPerCall", "Most rows one tool call returns to the model. Empty: 50; at most 200.");
help(table, "redactPii", "On (or empty): API keys, tokens, private keys, card numbers and social security numbers are redacted from tool results before the model sees them.");
@@ -728,7 +733,7 @@ public final class AssistantRecordScreens
sections(table,
section("policy", "Policy", "policy", Tier.T1, "id", "name", "killSwitch", "killSwitchReason"),
section("model", "Model", "smart_toy", Tier.T2, "mainModel", "mainEffort"),
section("tools", "Tools and data", "build", Tier.T2, "writesRequireConfirmation", "allowedTools", "maxRowsPerCall", "redactPii"),
section("tools", "Tools and data", "build", Tier.T2, "writeModeAllowed", "writeModePermission", "writesRequireConfirmation", "autoConfirmAllowed", "allowedTools", "maxRowsPerCall", "redactPii"),
section("userDaily", "Per user, per day", "person", Tier.T2, "userDailyTokensSoft", "userDailyTokensHard", "userDailyCostMicrosSoft", "userDailyCostMicrosHard"),
section("instanceMonthly", "Whole instance, per month", "domain", Tier.T2, "instanceMonthlyTokensSoft", "instanceMonthlyTokensHard", "instanceMonthlyCostMicrosSoft", "instanceMonthlyCostMicrosHard"));
}
@@ -71,6 +71,9 @@ public class AssistantConversation extends QRecordEntity
@QField(isEditable = false)
private String contextJson;
@QField()
private Boolean writeMode;
@QField(isEditable = false)
private Long totalTokensIn;
@@ -509,6 +512,36 @@ public class AssistantConversation extends QRecordEntity
}
/*******************************************************************************
** Getter for writeMode (Write mode for this conversation (default Read-only); the write tools exist only in Write mode)
*******************************************************************************/
public Boolean getWriteMode()
{
return (this.writeMode);
}
/*******************************************************************************
** Setter for writeMode
*******************************************************************************/
public void setWriteMode(Boolean writeMode)
{
this.writeMode = writeMode;
}
/*******************************************************************************
** Fluent setter for writeMode
*******************************************************************************/
public AssistantConversation withWriteMode(Boolean writeMode)
{
this.writeMode = writeMode;
return (this);
}
/*******************************************************************************
** Getter for maxClassification
@@ -49,6 +49,9 @@ public class AssistantDataAccess extends QRecordEntity
@QField(maxLength = 500, valueTooLongBehavior = ValueTooLongBehavior.TRUNCATE_ELLIPSIS)
private String notes;
@QField()
private Boolean autoConfirmOk;
@QField(isEditable = false)
private Instant createDate;
@@ -285,4 +288,34 @@ public class AssistantDataAccess extends QRecordEntity
return (this);
}
/*******************************************************************************
** Getter for autoConfirmOk (single-record inserts and updates here may be auto-confirmed (when the policy and the user allow it))
*******************************************************************************/
public Boolean getAutoConfirmOk()
{
return (this.autoConfirmOk);
}
/*******************************************************************************
** Setter for autoConfirmOk
*******************************************************************************/
public void setAutoConfirmOk(Boolean autoConfirmOk)
{
this.autoConfirmOk = autoConfirmOk;
}
/*******************************************************************************
** Fluent setter for autoConfirmOk
*******************************************************************************/
public AssistantDataAccess withAutoConfirmOk(Boolean autoConfirmOk)
{
this.autoConfirmOk = autoConfirmOk;
return (this);
}
}
@@ -94,6 +94,15 @@ public class AssistantPolicy extends QRecordEntity
@QField()
private Boolean redactPii;
@QField()
private Boolean writeModeAllowed;
@QField(maxLength = 128)
private String writeModePermission;
@QField()
private Boolean autoConfirmAllowed;
@QField(isEditable = false)
private Instant createDate;
@@ -735,4 +744,94 @@ public class AssistantPolicy extends QRecordEntity
return (this);
}
/*******************************************************************************
** Getter for writeModeAllowed (whether any conversation may switch to Write mode (default true))
*******************************************************************************/
public Boolean getWriteModeAllowed()
{
return (this.writeModeAllowed);
}
/*******************************************************************************
** Setter for writeModeAllowed
*******************************************************************************/
public void setWriteModeAllowed(Boolean writeModeAllowed)
{
this.writeModeAllowed = writeModeAllowed;
}
/*******************************************************************************
** Fluent setter for writeModeAllowed
*******************************************************************************/
public AssistantPolicy withWriteModeAllowed(Boolean writeModeAllowed)
{
this.writeModeAllowed = writeModeAllowed;
return (this);
}
/*******************************************************************************
** Getter for writeModePermission (only holders of this permission may switch to Write mode (empty: everyone))
*******************************************************************************/
public String getWriteModePermission()
{
return (this.writeModePermission);
}
/*******************************************************************************
** Setter for writeModePermission
*******************************************************************************/
public void setWriteModePermission(String writeModePermission)
{
this.writeModePermission = writeModePermission;
}
/*******************************************************************************
** Fluent setter for writeModePermission
*******************************************************************************/
public AssistantPolicy withWriteModePermission(String writeModePermission)
{
this.writeModePermission = writeModePermission;
return (this);
}
/*******************************************************************************
** Getter for autoConfirmAllowed (whether users may auto-confirm low-risk writes (default false))
*******************************************************************************/
public Boolean getAutoConfirmAllowed()
{
return (this.autoConfirmAllowed);
}
/*******************************************************************************
** Setter for autoConfirmAllowed
*******************************************************************************/
public void setAutoConfirmAllowed(Boolean autoConfirmAllowed)
{
this.autoConfirmAllowed = autoConfirmAllowed;
}
/*******************************************************************************
** Fluent setter for autoConfirmAllowed
*******************************************************************************/
public AssistantPolicy withAutoConfirmAllowed(Boolean autoConfirmAllowed)
{
this.autoConfirmAllowed = autoConfirmAllowed;
return (this);
}
}
@@ -0,0 +1,252 @@
/*
* 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.model;
import java.time.Instant;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.data.QField;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import com.kingsrook.qqq.backend.core.model.data.QRecordEntity;
/*******************************************************************************
** A user's own assistant preferences: the default mode of new conversations and auto-confirm of low-risk writes (only where the policy allows it).
*******************************************************************************/
public class AssistantUserPreference extends QRecordEntity
{
public static final String TABLE_NAME = "assistant_user_preference";
@QField(isEditable = false, isPrimaryKey = true)
private Integer id;
@QField(isEditable = false, maxLength = 255)
private String userId;
@QField()
private Boolean defaultWriteMode;
@QField()
private Boolean autoConfirmLowRisk;
@QField(isEditable = false)
private Instant createDate;
@QField(isEditable = false)
private Instant modifyDate;
/*******************************************************************************
** Default constructor.
*******************************************************************************/
public AssistantUserPreference()
{
}
/*******************************************************************************
** Constructor that populates from a QRecord.
*******************************************************************************/
public AssistantUserPreference(QRecord record) throws QException
{
populateFromQRecord(record);
}
/*******************************************************************************
** Getter for id
*******************************************************************************/
public Integer getId()
{
return (this.id);
}
/*******************************************************************************
** Setter for id
*******************************************************************************/
public void setId(Integer id)
{
this.id = id;
}
/*******************************************************************************
** Fluent setter for id
*******************************************************************************/
public AssistantUserPreference withId(Integer id)
{
this.id = id;
return (this);
}
/*******************************************************************************
** Getter for userId
*******************************************************************************/
public String getUserId()
{
return (this.userId);
}
/*******************************************************************************
** Setter for userId
*******************************************************************************/
public void setUserId(String userId)
{
this.userId = userId;
}
/*******************************************************************************
** Fluent setter for userId
*******************************************************************************/
public AssistantUserPreference withUserId(String userId)
{
this.userId = userId;
return (this);
}
/*******************************************************************************
** Getter for defaultWriteMode
*******************************************************************************/
public Boolean getDefaultWriteMode()
{
return (this.defaultWriteMode);
}
/*******************************************************************************
** Setter for defaultWriteMode
*******************************************************************************/
public void setDefaultWriteMode(Boolean defaultWriteMode)
{
this.defaultWriteMode = defaultWriteMode;
}
/*******************************************************************************
** Fluent setter for defaultWriteMode
*******************************************************************************/
public AssistantUserPreference withDefaultWriteMode(Boolean defaultWriteMode)
{
this.defaultWriteMode = defaultWriteMode;
return (this);
}
/*******************************************************************************
** Getter for autoConfirmLowRisk
*******************************************************************************/
public Boolean getAutoConfirmLowRisk()
{
return (this.autoConfirmLowRisk);
}
/*******************************************************************************
** Setter for autoConfirmLowRisk
*******************************************************************************/
public void setAutoConfirmLowRisk(Boolean autoConfirmLowRisk)
{
this.autoConfirmLowRisk = autoConfirmLowRisk;
}
/*******************************************************************************
** Fluent setter for autoConfirmLowRisk
*******************************************************************************/
public AssistantUserPreference withAutoConfirmLowRisk(Boolean autoConfirmLowRisk)
{
this.autoConfirmLowRisk = autoConfirmLowRisk;
return (this);
}
/*******************************************************************************
** Getter for createDate
*******************************************************************************/
public Instant getCreateDate()
{
return (this.createDate);
}
/*******************************************************************************
** Setter for createDate
*******************************************************************************/
public void setCreateDate(Instant createDate)
{
this.createDate = createDate;
}
/*******************************************************************************
** Fluent setter for createDate
*******************************************************************************/
public AssistantUserPreference withCreateDate(Instant createDate)
{
this.createDate = createDate;
return (this);
}
/*******************************************************************************
** Getter for modifyDate
*******************************************************************************/
public Instant getModifyDate()
{
return (this.modifyDate);
}
/*******************************************************************************
** Setter for modifyDate
*******************************************************************************/
public void setModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
}
/*******************************************************************************
** Fluent setter for modifyDate
*******************************************************************************/
public AssistantUserPreference withModifyDate(Instant modifyDate)
{
this.modifyDate = modifyDate;
return (this);
}
}
@@ -51,6 +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.model.AssistantUserPreference;
import com.kingsrook.qbits.assistant.provider.ModelUsage;
import com.kingsrook.qbits.assistant.scheduled.ScheduledTasks;
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
@@ -384,6 +385,16 @@ public class AssistantStore
/*******************************************************************************
** The user's own preferences, or null.
*******************************************************************************/
public AssistantUserPreference getPreference(String userId) throws QException
{
return (first(query(AssistantUserPreference.TABLE_NAME, owned(userId).withLimit(1), AssistantUserPreference.class)));
}
/*******************************************************************************
** One of the user's own pending actions, or null.
*******************************************************************************/
@@ -23,14 +23,13 @@ package com.kingsrook.qbits.assistant.scheduled;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.engine.BudgetService;
import com.kingsrook.qbits.assistant.engine.PolicyService;
import com.kingsrook.qbits.assistant.model.AssistantScheduledTask;
import com.kingsrook.qbits.assistant.model.AssistantUsage;
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.QQueryFilter;
@@ -103,14 +102,9 @@ public class ScheduledTurn
*******************************************************************************/
public static PolicyService.ToolPolicy tools(AssistantRuntime runtime, AssistantScheduledTask task, PolicyService.ToolPolicy policy) throws QException
{
Set<String> allowed = runtime.getContextBuilder().toolNames(policy).stream()
.filter(name -> !Set.of("create_record", "update_record", "delete_record").contains(name) || approved(task))
.collect(Collectors.toSet());
if(allowed.isEmpty())
{
allowed = Set.of("__no_tools__");
}
return (new PolicyService.ToolPolicy(true, allowed, policy.maxRowsPerCall(), policy.redactPii()));
boolean write = approved(task) && policy.writeModeAvailableTo(QContext.getQSession());
return (new PolicyService.ToolPolicy(true, policy.allowedTools(), policy.maxRowsPerCall(), policy.redactPii(),
policy.writeModeAllowed(), policy.writeModePermission(), policy.autoConfirmAllowed(), write, false));
}
@@ -400,7 +400,8 @@ public class UiApiToolbox
List<ModelToolDefinition> rs = new ArrayList<>();
for(ModelToolDefinition definition : definitions())
{
if((policy == null || policy.allows(definition.getName())) && (anyWritableTable || !WRITE_TOOLS.contains(definition.getName())))
boolean write = WRITE_TOOLS.contains(definition.getName());
if((policy == null || policy.allows(definition.getName())) && (!write || (anyWritableTable && (policy == null || policy.writeMode()))))
{
rs.add(definition);
}
@@ -448,6 +449,11 @@ public class UiApiToolbox
deny(result, "policy:tool", "The administrator has not allowed the " + toolName + " tool.");
return (outcome);
}
if(WRITE_TOOLS.contains(toolName) && context.policy() != null && !context.policy().writeMode())
{
deny(result, "mode:READ_ONLY", "This conversation is in Read-only mode: the assistant cannot change data. The user can switch it to Write mode in the panel.");
return (outcome);
}
if(!context.gateway().isInvocable(operation[0], operation[1]))
{
deny(result, "uiApi:notSpecd", "The operation " + outcome.operation + " is not a spec'd UI API operation.");
@@ -1211,7 +1217,12 @@ public class UiApiToolbox
}
}
if(context.policy() == null || context.policy().writesRequireConfirmation())
///////////////////////////////////////////////////////////////////
// auto-confirm: only when the policy allows it, the user chose //
// it, and the admin marked the table low-risk; never deletes //
///////////////////////////////////////////////////////////////////
boolean autoConfirmed = context.policy() != null && context.policy().autoConfirm() && !DELETE_RECORD.equals(toolName) && dataAccess.autoConfirmOk(tableName);
if(!autoConfirmed && (context.policy() == null || context.policy().writesRequireConfirmation()))
{
String summary = describeWrite(toolName, table, recordId, values);
Integer actionId = context.pendingActions() == null ? null
@@ -151,7 +151,7 @@ public class BulkLoadTools
AiJsonSchema.object(AiJsonSchema.properties("uploadRef", upload, "tableName", table, "profile", profile,
"mode", AiJsonSchema.enumOf(List.of("SAMPLE", "FULL"), "SAMPLE (default) or FULL.")), List.of("uploadRef", "tableName", "profile")));
if(anyWritable)
if(anyWritable && (policy == null || policy.writeMode()))
{
Map<String, Object> share = AiJsonSchema.object(AiJsonSchema.properties(
"audienceType", AiJsonSchema.enumOf(List.of("user", "group"), "Share with a user (email) or a group."),
@@ -205,6 +205,12 @@ public class BulkLoadTools
return (UiApiToolbox.Outcome.of(result, null, null, null));
}
if(WRITE_TOOLS.contains(toolName) && context.policy() != null && !context.policy().writeMode())
{
deny(result, "mode:readOnly", "This conversation is Read-only. Switch to Write mode to make changes.");
return (UiApiToolbox.Outcome.of(result, null, null, null));
}
String tableName = in.get("tableName") instanceof String t ? t.strip() : null;
if(tableName != null)
{
@@ -78,6 +78,8 @@ components:
description: "writes: some table allows writes; pendingActions: writes wait\
\ for confirmation."
type: "object"
preferences:
$ref: "#/components/schemas/AssistantPreferencesV1"
profile:
$ref: "#/components/schemas/AssistantProfileV1"
type: "object"
@@ -112,6 +114,10 @@ components:
type: "string"
pinned:
type: "boolean"
writeMode:
description: "Write mode (default Read-only): the write tools exist only\
\ in Write mode."
type: "boolean"
lastMessageAt:
description: "ISO-8601 instant."
nullable: true
@@ -159,6 +165,18 @@ components:
type: "object"
type: "array"
type: "object"
AssistantPreferencesV1:
description: "The user's own assistant preferences."
properties:
defaultWriteMode:
description: "New conversations start in Write mode (when write mode is\
\ available)."
type: "boolean"
autoConfirmLowRisk:
description: "Auto-confirm low-risk writes (only when the policy allows\
\ it; never deletes, bulk writes or processes)."
type: "boolean"
type: "object"
AssistantProfileV1:
description: "How the assistant presents itself (admin-configured; text only,\
\ it never changes access)."
@@ -329,7 +347,8 @@ paths:
content:
application/json:
schema:
description: "Optional title and the page context it starts from."
description: "Optional title, the page context it starts from, and the\
\ mode (default: the user's preference)."
properties:
title:
type: "string"
@@ -337,6 +356,8 @@ paths:
additionalProperties: true
description: "route, tableName, recordId, filter, selectedIds."
type: "object"
writeMode:
type: "boolean"
type: "object"
required: true
responses:
@@ -533,6 +554,10 @@ paths:
status:
description: "ACTIVE or ARCHIVED."
type: "string"
writeMode:
description: "Switch to Write mode (true) or Read-only (false);\
\ 403 when write mode is not available to the user."
type: "boolean"
type: "object"
required: true
responses:
@@ -0,0 +1,183 @@
/*
* 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.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.kingsrook.qbits.assistant.model.AssistantDataAccess;
import com.kingsrook.qbits.assistant.model.AssistantPolicy;
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
import com.kingsrook.qbits.assistant.testing.BaseAssistantTest;
import com.kingsrook.qbits.assistant.testing.UiApiTestServer;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import org.json.JSONObject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static com.kingsrook.qbits.assistant.testing.AssistantTestFixture.EDITOR;
import static com.kingsrook.qbits.assistant.testing.AssistantTestFixture.NO_ACCESS;
import static com.kingsrook.qbits.assistant.testing.AssistantTestFixture.OTHER_EDITOR;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** The core preferences HTTP contract, user isolation, policy and channel wall.
*******************************************************************************/
class AssistantPreferencesTest extends BaseAssistantTest
{
private String base;
private final HttpClient client = HttpClient.newHttpClient();
/*******************************************************************************
** Serve the same core specs as a host application.
*******************************************************************************/
@BeforeEach
void start()
{
QContext.clear();
base = UiApiTestServer.serve(qInstance, config) + "/qqq/v1";
}
/*******************************************************************************
** Authenticate as a human user; no identity is accepted in the body.
*******************************************************************************/
private HttpResponse<String> send(String method, String path, String user, String channel, String body) throws Exception
{
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
.header("Cookie", "sessionId=" + user).header("X-QQQ-Client", channel);
if(body != null)
{
request.header("Content-Type", "application/json");
}
return (client.send(request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString()));
}
/*******************************************************************************
** A regular assistant user sees the section, without admin table permissions.
*******************************************************************************/
@Test
void visibilityAndRemovedEndpoint() throws Exception
{
HttpResponse<String> visible = send("GET", "/preferences/assistant", EDITOR, "next-ui", null);
assertThat(visible.statusCode()).as(visible.body()).isEqualTo(200);
assertThat(new JSONObject(visible.body()).getString("name")).isEqualTo("assistant");
assertThat(send("GET", "/preferences", EDITOR, "next-ui", null).body()).contains("Start conversations in Write mode");
assertThat(send("GET", "/preferences/assistant", NO_ACCESS, "next-ui", null).statusCode()).isEqualTo(404);
assertThat(send("GET", "/preferences", NO_ACCESS, "next-ui", null).body()).doesNotContain("Start conversations in Write mode");
assertThat(send("PATCH", "/preferences/assistant", NO_ACCESS, "next-ui", "{\"values\":{\"defaultWriteMode\":true}}").statusCode()).isEqualTo(404);
assertThat(send("GET", "/assistant/preferences", EDITOR, "next-ui", null).statusCode()).isEqualTo(404);
assertThat(send("PATCH", "/assistant/preferences", EDITOR, "next-ui", "{}").statusCode()).isEqualTo(404);
}
/*******************************************************************************
** Partial patches and new conversations use only the authenticated user's row.
*******************************************************************************/
@Test
void roundTripIsolationAndDefault() throws Exception
{
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
config.getRuntime().getStore().insert(new AssistantDataAccess().withObjectType("TABLE").withObjectName("page").withMode("READ_WRITE"));
config.getRuntime().getDataAccessService().invalidate();
config.getRuntime().getStore().insert(new AssistantPolicy().withName("default").withAutoConfirmAllowed(true));
config.getRuntime().getPolicyService().invalidate();
QContext.clear();
assertThat(send("PATCH", "/preferences/assistant", OTHER_EDITOR, "next-ui", "{\"values\":{\"defaultWriteMode\":false,\"autoConfirmLowRisk\":true}}").statusCode()).isEqualTo(200);
HttpResponse<String> patched = send("PATCH", "/preferences/assistant", EDITOR, "next-ui", "{\"values\":{\"defaultWriteMode\":true}}");
assertThat(patched.statusCode()).as(patched.body()).isEqualTo(200);
JSONObject values = new JSONObject(send("GET", "/preferences/assistant", EDITOR, "next-ui", null).body()).getJSONObject("values");
assertThat(values.getBoolean("defaultWriteMode")).isTrue();
assertThat(values.getBoolean("autoConfirmLowRisk")).isFalse();
JSONObject other = new JSONObject(send("GET", "/preferences/assistant", OTHER_EDITOR, "next-ui", null).body()).getJSONObject("values");
assertThat(other.getBoolean("defaultWriteMode")).isFalse();
assertThat(other.getBoolean("autoConfirmLowRisk")).isTrue();
JSONObject conversation = new JSONObject(send("POST", "/assistant/conversations", EDITOR, "next-ui", "{}").body());
assertThat(conversation.getBoolean("writeMode")).isTrue();
JSONObject probe = new JSONObject(send("GET", "/assistant/config", EDITOR, "next-ui", null).body());
assertThat(probe.getJSONObject("preferences").getBoolean("defaultWriteMode")).isTrue();
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
AssistantPolicy policy = config.getRuntime().getStore().loadPolicy();
config.getRuntime().getStore().updateFields(AssistantPolicy.TABLE_NAME, new QRecord().withValue("id", policy.getId()).withValue("writeModeAllowed", false));
config.getRuntime().getPolicyService().invalidate();
QContext.clear();
assertThat(new JSONObject(send("GET", "/assistant/config", EDITOR, "next-ui", null).body()).getJSONObject("preferences").getBoolean("defaultWriteMode")).isFalse();
assertThat(new JSONObject(send("POST", "/assistant/conversations", EDITOR, "next-ui", "{}").body()).getBoolean("writeMode")).isFalse();
assertThat(send("PATCH", "/preferences/assistant", EDITOR, "next-ui", "{\"values\":{\"defaultWriteMode\":true}}").statusCode()).isEqualTo(400);
}
/*******************************************************************************
** The UI sees a read-only field with a reason; the server rejects a bypass.
*******************************************************************************/
@Test
void policyDisablesAutoConfirm() throws Exception
{
String body = send("GET", "/preferences/assistant", EDITOR, "next-ui", null).body();
assertThat(body).contains("Auto-confirm is not allowed by the assistant policy.");
HttpResponse<String> denied = send("PATCH", "/preferences/assistant", EDITOR, "next-ui", "{\"values\":{\"autoConfirmLowRisk\":true}}");
assertThat(denied.statusCode()).as(denied.body()).isEqualTo(400);
assertThat(denied.body()).contains("can't be changed");
assertThat(new JSONObject(send("GET", "/preferences/assistant", EDITOR, "next-ui", null).body()).getJSONObject("values").getBoolean("autoConfirmLowRisk")).isFalse();
}
/*******************************************************************************
** Core rejects identity injection and unknown fields before any provider write.
*******************************************************************************/
@Test
void invalidPatchDoesNotWrite() throws Exception
{
for(String body : new String[] { "{\"userId\":\"other\",\"values\":{\"defaultWriteMode\":true}}",
"{\"values\":{\"userId\":\"other\"}}", "{\"values\":{\"unknown\":true}}", "{\"values\":{\"defaultWriteMode\":[]}}" })
{
assertThat(send("PATCH", "/preferences/assistant", EDITOR, "next-ui", body).statusCode()).isEqualTo(400);
}
assertThat(new JSONObject(send("GET", "/preferences/assistant", EDITOR, "next-ui", null).body()).getJSONObject("values").getBoolean("defaultWriteMode")).isFalse();
}
/*******************************************************************************
** Even an administrator acting through the assistant cannot read or patch it.
*******************************************************************************/
@Test
void assistantChannelCannotUsePreferences() throws Exception
{
for(String user : new String[] { EDITOR, AssistantTestFixture.ADMIN })
{
for(String channel : new String[] { "assistant/turn-42", "assistant/scheduled/12" })
{
assertThat(send("GET", "/preferences/assistant", user, channel, null).statusCode()).isEqualTo(404);
assertThat(send("PATCH", "/preferences/assistant", user, channel, "{\"values\":{\"defaultWriteMode\":true}}").statusCode()).isEqualTo(404);
}
assertThat(send("GET", "/preferences/assistant", user, "next-ui", null).statusCode()).isEqualTo(200);
}
}
}
@@ -38,6 +38,8 @@ import java.util.concurrent.Executors;
import java.util.stream.Stream;
import com.kingsrook.qbits.assistant.AssistantQBitConfig;
import com.kingsrook.qbits.assistant.AssistantRuntime;
import com.kingsrook.qbits.assistant.engine.PolicyService;
import com.kingsrook.qbits.assistant.model.AssistantPolicy;
import com.kingsrook.qbits.assistant.AssistantSecurity;
import com.kingsrook.qbits.assistant.model.AssistantDataAccess;
import com.kingsrook.qbits.assistant.model.AssistantPendingAction;
@@ -347,6 +349,33 @@ class ScheduledTasksTest extends BaseAssistantTest
/*******************************************************************************
** Per-task approval never overrides global or role write policy. User
** auto-confirm preferences never bypass scheduled confirmation.
*******************************************************************************/
@Test
void approvedTaskStillRequiresWritePolicy() throws Exception
{
AssistantScheduledTask task = task();
runtime.getStore().updateFields(AssistantScheduledTask.TABLE_NAME, new QRecord().withValue("id", task.getId()).withValue("writeModeRequested", true));
task = runtime.getStore().scheduledTask(task.getId());
action(task, "Approve");
task = runtime.getStore().scheduledTask(task.getId());
QContext.init(qInstance, AssistantTestFixture.ownerSession(AssistantTestFixture.EDITOR, config));
PolicyService.ToolPolicy allowed = PolicyService.ToolPolicy.defaults();
PolicyService.ToolPolicy blocked = PolicyService.ToolPolicy.of(new AssistantPolicy().withWriteModeAllowed(false));
PolicyService.ToolPolicy role = PolicyService.ToolPolicy.of(new AssistantPolicy().withWriteModePermission("assistant.write"));
assertThat(ScheduledTurn.tools(runtime, task, blocked).writeMode()).isFalse();
assertThat(ScheduledTurn.tools(runtime, task, role).writeMode()).isFalse();
PolicyService.ToolPolicy effective = ScheduledTurn.tools(runtime, task, allowed);
assertThat(effective.writeMode()).isTrue();
assertThat(effective.writesRequireConfirmation()).isTrue();
assertThat(effective.autoConfirm()).isFalse();
assertThat(ScheduledTurn.tools(runtime, new AssistantScheduledTask(), allowed.withWriteMode(true)).writeMode()).isFalse();
}
/*******************************************************************************
** Exercise the same Review/Result steps the record action uses.
*******************************************************************************/
@@ -307,7 +307,7 @@ class UiApiToolsSecurityTest extends BaseAssistantTest
void testConfirmedWriteRunsThroughTheUiApi() throws Exception
{
setAccess("blog_post", DataAccessMode.READ_WRITE);
UiApiToolbox.Outcome proposed = tool(AssistantTestFixture.ADMIN, PolicyService.ToolPolicy.defaults(), UiApiToolbox.CREATE_RECORD,
UiApiToolbox.Outcome proposed = tool(AssistantTestFixture.ADMIN, PolicyService.ToolPolicy.defaults().withWriteMode(true), UiApiToolbox.CREATE_RECORD,
input("table", "blog_post", "values", Map.of("title", "Proposed by the assistant", "status", "DRAFT")));
assertThat(proposed.getResult().getOutcome()).isEqualTo(AiToolOutcome.OK);
assertThat(proposed.getHttpStatus()).as("nothing runs before confirmation").isNull();
@@ -345,7 +345,7 @@ class UiApiToolsSecurityTest extends BaseAssistantTest
void testOnlyTheOwnerDecides() throws Exception
{
setAccess("blog_post", DataAccessMode.READ_WRITE);
UiApiToolbox.Outcome proposed = tool(AssistantTestFixture.EDITOR, PolicyService.ToolPolicy.defaults(), UiApiToolbox.UPDATE_RECORD,
UiApiToolbox.Outcome proposed = tool(AssistantTestFixture.EDITOR, PolicyService.ToolPolicy.defaults().withWriteMode(true), UiApiToolbox.UPDATE_RECORD,
input("table", "blog_post", "id", "1", "values", Map.of("title", "Changed")));
Integer actionId = proposed.getPendingActionId();
assertThat(actionId).isNotNull();
@@ -440,6 +440,27 @@ class UiApiToolsSecurityTest extends BaseAssistantTest
}
}
//////////////////////////////////////////////////////////////////
// Read-only mode: the same writes never reach the UI API, for //
// the analyst and for the admin who could make them in the UI //
//////////////////////////////////////////////////////////////////
PolicyService.ToolPolicy readOnly = noConfirmation().withWriteMode(false);
for(String who : List.of(AssistantTestFixture.ANALYST, AssistantTestFixture.ADMIN))
{
for(Object[] row : new Object[][] {
{UiApiToolbox.CREATE_RECORD, input("table", "blog_post", "values", Map.of("title", "x"))},
{UiApiToolbox.UPDATE_RECORD, input("table", "blog_post", "id", "1", "values", Map.of("title", "x"))},
{UiApiToolbox.DELETE_RECORD, input("table", "blog_post", "id", "1")}})
{
@SuppressWarnings("unchecked")
UiApiToolbox.Outcome outcome = tool(who, readOnly, (String) row[0], (Map<String, Object>) row[1]);
assertThat(outcome.getResult().getOutcome()).as(who + " " + row[0]).isEqualTo(AiToolOutcome.DENIED);
assertThat(outcome.getHttpStatus()).as(who + " " + row[0] + ": no request").isNull();
assertThat(outcome.getResult().getPermissionCheck()).isEqualTo("mode:READ_ONLY");
}
}
assertThat(ui("PATCH", "/table/blog_post/1", AssistantTestFixture.ADMIN, "{\"title\":\"Admin via the UI\"}").statusCode()).as("the admin may write in the UI").isBetween(200, 299);
//////////////////////////////////////////////////////////////////
// process: no tool, and no process has data access by default //
//////////////////////////////////////////////////////////////////
@@ -0,0 +1,209 @@
/*
* 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.tools;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.assistant.api.AssistantApi;
import com.kingsrook.qbits.assistant.model.AssistantDataAccess;
import com.kingsrook.qbits.assistant.model.AssistantPolicy;
import com.kingsrook.qbits.assistant.model.AssistantToolCall;
import com.kingsrook.qbits.assistant.provider.ModelRequest;
import com.kingsrook.qbits.assistant.testing.AssistantTestFixture;
import com.kingsrook.qbits.assistant.testing.BaseAssistantTest;
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
import com.kingsrook.qqq.backend.core.actions.preferences.UserPreferencesAction;
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.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/*******************************************************************************
** Write mode (owner, 2026-10-13): Read-only by default; the write tools exist
** only in Write mode; the policy can turn write mode off or limit it to a
** role; the user's preference sets the default; auto-confirm only where the
** policy allows it, on tables marked low-risk, never for deletes.
*******************************************************************************/
class WriteModeTest extends BaseAssistantTest
{
/*******************************************************************************
**
*******************************************************************************/
@AfterEach
void clear()
{
QContext.clear();
}
/*******************************************************************************
**
*******************************************************************************/
private void save(String table, Map<String, Serializable> values) throws QException
{
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
try
{
QRecord record = new QRecord();
record.setValues(new LinkedHashMap<>(values));
QRecord saved = new InsertAction().execute(new InsertInput(table).withRecord(record)).getRecords().get(0);
assertThat(saved.getErrors()).isEmpty();
}
finally
{
QContext.clear();
}
}
/*******************************************************************************
**
*******************************************************************************/
private AssistantApi api(String user)
{
QContext.init(qInstance, AssistantTestFixture.sessionFor(user));
return (new AssistantApi(config.getRuntime(), QContext.getQSession()));
}
/*******************************************************************************
** Read-only by default: no write tools in the request; Write mode adds
** them; the conversation remembers its mode.
*******************************************************************************/
@Test
void testModeControlsTheToolList() throws Exception
{
save(AssistantDataAccess.TABLE_NAME, Map.of("objectType", "TABLE", "objectName", "page", "mode", "READ_WRITE"));
AssistantApi admin = api(AssistantTestFixture.ADMIN);
Map<String, Object> conversation = admin.createConversation(new LinkedHashMap<>());
assertThat(conversation.get("writeMode")).isEqualTo(false);
Integer id = (Integer) conversation.get("id");
QContext.clear();
provider.thenText("ok").thenText("ok");
runner.run(AssistantTestFixture.ADMIN, id, "read only please", null);
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
assertThat(new AssistantApi(config.getRuntime(), QContext.getQSession()).patchConversation(id, Map.of("writeMode", true)).get("writeMode")).isEqualTo(true);
QContext.clear();
runner.run(AssistantTestFixture.ADMIN, id, "now write", null);
List<ModelRequest> requests = provider.getRequests();
assertThat(requests.get(0).getTools()).extracting(t -> t.getName()).doesNotContain(UiApiToolbox.CREATE_RECORD, UiApiToolbox.UPDATE_RECORD, UiApiToolbox.DELETE_RECORD);
assertThat(requests.get(1).getTools()).extracting(t -> t.getName()).contains(UiApiToolbox.CREATE_RECORD, UiApiToolbox.UPDATE_RECORD, UiApiToolbox.DELETE_RECORD);
}
/*******************************************************************************
** A write tool called in a Read-only conversation is refused before any
** request (the model cannot get around the tool list).
*******************************************************************************/
@Test
void testReadOnlyRefusesAWriteCall() throws Exception
{
save(AssistantDataAccess.TABLE_NAME, Map.of("objectType", "TABLE", "objectName", "page", "mode", "READ_WRITE"));
provider.thenToolUse(UiApiToolbox.UPDATE_RECORD, Map.of("table", "page", "id", "12", "values", Map.of("title", "Hacked"))).thenText("ok");
var outcome = runner.run(AssistantTestFixture.ADMIN, "change page 12");
assertThat(outcome.toolCalls()).extracting(AssistantToolCall::getOutcome).containsExactly("INVALID_INPUT");
}
/*******************************************************************************
** The policy: write mode off for everyone, or only for a role; then 403.
*******************************************************************************/
@Test
void testPolicyLimitsWriteMode() throws Exception
{
save(AssistantDataAccess.TABLE_NAME, Map.of("objectType", "TABLE", "objectName", "page", "mode", "READ_WRITE"));
AssistantApi editor = api(AssistantTestFixture.EDITOR);
Integer id = (Integer) editor.createConversation(new LinkedHashMap<>()).get("id");
assertThat(editor.patchConversation(id, Map.of("writeMode", true)).get("writeMode")).isEqualTo(true);
QContext.clear();
save(AssistantPolicy.TABLE_NAME, Map.of("name", "default", "writeModePermission", "assistant.write"));
config.getRuntime().getPolicyService().invalidate();
AssistantApi again = api(AssistantTestFixture.EDITOR);
assertThatThrownBy(() -> again.patchConversation(id, Map.of("writeMode", true))).hasMessageContaining("Write mode is not available");
assertThat(again.config()).extracting(c -> ((Map<?, ?>) c.get("features")).get("writeMode")).isEqualTo(false);
}
/*******************************************************************************
** No READ_WRITE table: write mode is not available at all.
*******************************************************************************/
@Test
void testNoWritableTableNoWriteMode() throws Exception
{
AssistantApi admin = api(AssistantTestFixture.ADMIN);
Integer id = (Integer) admin.createConversation(new LinkedHashMap<>()).get("id");
assertThatThrownBy(() -> admin.patchConversation(id, Map.of("writeMode", true))).hasMessageContaining("Write mode is not available");
}
/*******************************************************************************
** Preferences: the default mode applies to new conversations; auto-confirm
** is refused unless the policy allows it, and then runs a low-risk insert at
** once but never a delete.
*******************************************************************************/
@Test
void testPreferencesAndAutoConfirm() throws Exception
{
save(AssistantDataAccess.TABLE_NAME, Map.of("objectType", "TABLE", "objectName", "page", "mode", "READ_WRITE", "autoConfirmOk", true));
AssistantApi admin = api(AssistantTestFixture.ADMIN);
new UserPreferencesAction().patchSection("assistant", Map.of("values", Map.of("defaultWriteMode", true)));
assertThat(admin.createConversation(new LinkedHashMap<>()).get("writeMode")).isEqualTo(true);
assertThatThrownBy(() -> new UserPreferencesAction().patchSection("assistant", Map.of("values", Map.of("autoConfirmLowRisk", true)))).hasMessageContaining("can't be changed");
QContext.clear();
save(AssistantPolicy.TABLE_NAME, Map.of("name", "default", "autoConfirmAllowed", true));
config.getRuntime().getPolicyService().invalidate();
AssistantApi allowed = api(AssistantTestFixture.ADMIN);
assertThat(new UserPreferencesAction().patchSection("assistant", Map.of("values", Map.of("autoConfirmLowRisk", true))).getValues().getValues().get("autoConfirmLowRisk")).isEqualTo(true);
QContext.clear();
provider.thenToolUses("Saving.", List.of(
new Object[] {UiApiToolbox.CREATE_RECORD, Map.of("table", "page", "values", Map.of("title", "Auto"))},
new Object[] {UiApiToolbox.DELETE_RECORD, Map.of("table", "page", "id", "12")}))
.thenText("done");
var outcome = runner.run(AssistantTestFixture.ADMIN, "make a page and delete page 12");
AssistantToolCall create = outcome.toolCalls().stream().filter(c -> UiApiToolbox.CREATE_RECORD.equals(c.getToolName())).findFirst().orElseThrow();
AssistantToolCall delete = outcome.toolCalls().stream().filter(c -> UiApiToolbox.DELETE_RECORD.equals(c.getToolName())).findFirst().orElseThrow();
assertThat(create.getHttpStatus()).as("auto-confirmed: ran through the UI API").isBetween(200, 299);
assertThat(create.getPendingActionId()).isNull();
assertThat(delete.getHttpStatus()).as("a delete is never auto-confirmed").isNull();
assertThat(delete.getPendingActionId()).isNotNull();
}
}
@@ -129,7 +129,7 @@ class BulkLoadToolsTest extends BaseAssistantTest
QContext.init(qInstance, AssistantTestFixture.ownerSession(AssistantTestFixture.ADMIN, config));
try
{
return (config.getRuntime().getBulkLoadTools().execute(new UiApiToolbox.Context("session-1", null, server, PolicyService.ToolPolicy.defaults(),
return (config.getRuntime().getBulkLoadTools().execute(new UiApiToolbox.Context("session-1", null, server, PolicyService.ToolPolicy.defaults().withWriteMode(true),
write -> config.getRuntime().getStore().insert(new AssistantPendingAction().withUserId(AssistantTestFixture.ADMIN).withToolName(write.toolName())
.withTableName(write.tableName()).withUiApiOperation(write.operation()).withParamsJson(JsonUtils.toJson(write.values()))
.withSummary(write.summary()).withStatus(AssistantPendingAction.STATUS_PENDING).withExpiresAt(java.time.Instant.now().plusSeconds(600))).getId()),
@@ -151,7 +151,7 @@ class BulkLoadToolsTest extends BaseAssistantTest
{
List<String> names = config.getRuntime().getContextBuilder().tools().stream().map(d -> d.getName()).toList();
assertThat(names).contains(BulkLoadTools.LIST, BulkLoadTools.DESCRIBE, BulkLoadTools.ATTACH, BulkLoadTools.SUGGEST, BulkLoadTools.DRY_RUN);
assertThat(config.getRuntime().getBulkLoadTools().definitions(PolicyService.ToolPolicy.defaults(), true))
assertThat(config.getRuntime().getBulkLoadTools().definitions(PolicyService.ToolPolicy.defaults().withWriteMode(true), true))
.extracting(d -> d.getName()).containsExactlyInAnyOrderElementsOf(BulkLoadTools.NAMES);
assertThat(config.getRuntime().getBulkLoadTools().definitions(PolicyService.ToolPolicy.defaults(), false))
.extracting(d -> d.getName()).doesNotContain(BulkLoadTools.SAVE, BulkLoadTools.RUN);
@@ -159,6 +159,30 @@ class BulkLoadToolsTest extends BaseAssistantTest
/*******************************************************************************
** Read-only suppresses both bulk write tools and denies forged calls before
** a proposal or request, even for an administrator with READ_WRITE access.
*******************************************************************************/
@Test
void testReadOnlyDeniesBulkWrites()
{
PolicyService.ToolPolicy policy = PolicyService.ToolPolicy.defaults();
assertThat(config.getRuntime().getBulkLoadTools().definitions(policy, true))
.extracting(d -> d.getName()).doesNotContain(BulkLoadTools.SAVE, BulkLoadTools.RUN);
for(String name : BulkLoadTools.WRITE_TOOLS)
{
UiApiToolbox.Context context = new UiApiToolbox.Context("session-1", null, server, policy,
write -> { throw new AssertionError("Read-only must not propose a write"); });
UiApiToolbox.Outcome outcome = config.getRuntime().getBulkLoadTools().execute(context, "forged", name, Map.of("tableName", "blog_post"), false);
assertThat(outcome.getResult().getOutcome()).isEqualTo(AiToolOutcome.DENIED);
assertThat(outcome.getHttpStatus()).isNull();
assertThat(outcome.getPendingActionId()).isNull();
}
assertThat(runs).isEmpty();
}
/*******************************************************************************
**
*******************************************************************************/
@@ -292,7 +316,10 @@ class BulkLoadToolsTest extends BaseAssistantTest
})
.thenText("The file maps cleanly once Status defaults to DRAFT (2 rows, no errors). Confirm to save the profile \"CMS post export\".");
TurnRunner.Outcome first = runner.run(AssistantTestFixture.ADMIN, null, "Load the attached posts.csv into blog posts and save the mapping for next time.", attachments);
QContext.init(qInstance, AssistantTestFixture.sessionFor(AssistantTestFixture.ADMIN));
Integer conversationId = (Integer) new AssistantApi(config.getRuntime(), QContext.getQSession()).createConversation(Map.of("writeMode", true)).get("id");
QContext.clear();
TurnRunner.Outcome first = runner.run(AssistantTestFixture.ADMIN, conversationId, "Load the attached posts.csv into blog posts and save the mapping for next time.", attachments);
List<String> tools = first.toolCalls().stream().map(AssistantToolCall::getToolName).toList();
assertThat(tools).containsExactly(BulkLoadTools.ATTACH, BulkLoadTools.SUGGEST, BulkLoadTools.DRY_RUN, BulkLoadTools.DRY_RUN, BulkLoadTools.SAVE);
@@ -78,6 +78,8 @@ components:
description: "writes: some table allows writes; pendingActions: writes wait\
\ for confirmation."
type: "object"
preferences:
$ref: "#/components/schemas/AssistantPreferencesV1"
profile:
$ref: "#/components/schemas/AssistantProfileV1"
type: "object"
@@ -112,6 +114,10 @@ components:
type: "string"
pinned:
type: "boolean"
writeMode:
description: "Write mode (default Read-only): the write tools exist only\
\ in Write mode."
type: "boolean"
lastMessageAt:
description: "ISO-8601 instant."
nullable: true
@@ -159,6 +165,18 @@ components:
type: "object"
type: "array"
type: "object"
AssistantPreferencesV1:
description: "The user's own assistant preferences."
properties:
defaultWriteMode:
description: "New conversations start in Write mode (when write mode is\
\ available)."
type: "boolean"
autoConfirmLowRisk:
description: "Auto-confirm low-risk writes (only when the policy allows\
\ it; never deletes, bulk writes or processes)."
type: "boolean"
type: "object"
AssistantProfileV1:
description: "How the assistant presents itself (admin-configured; text only,\
\ it never changes access)."
@@ -212,7 +230,7 @@ info:
description: "QQQ Assistant: conversations, streamed turns, feedback, pending actions\
\ and data access explanations"
title: "QQQ Middleware API extension: assistant"
version: "1.0.0"
version: "1.1.0"
openapi: "3.0.3"
paths:
/qqq/v1/assistant/config:
@@ -329,7 +347,8 @@ paths:
content:
application/json:
schema:
description: "Optional title and the page context it starts from."
description: "Optional title, the page context it starts from, and the\
\ mode (default: the user's preference)."
properties:
title:
type: "string"
@@ -337,6 +356,8 @@ paths:
additionalProperties: true
description: "route, tableName, recordId, filter, selectedIds."
type: "object"
writeMode:
type: "boolean"
type: "object"
required: true
responses:
@@ -533,6 +554,10 @@ paths:
status:
description: "ACTIVE or ARCHIVED."
type: "string"
writeMode:
description: "Switch to Write mode (true) or Read-only (false);\
\ 403 when write mode is not available to the user."
type: "boolean"
type: "object"
required: true
responses:
@@ -1038,6 +1063,12 @@ paths:
required: false
schema:
type: "string"
- description: "Attribute this request to an owned turn."
in: "query"
name: "turnId"
required: false
schema:
type: "integer"
responses:
400:
content: