Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Merge mcp-live; live mode follows the studio policy (mcp.live never, categories) and writes the audit log

islandmed4bbde71aad38
diff --cc docs/guide/studios.md
index 66e6210c,3f7504a7..b67c35b5
--- a/docs/guide/studios.md
+++ b/docs/guide/studios.md
@@@ -244,172 -241,6 +244,173 @@@ To install on machines without interne
4. To test studio mode on any machine, `sculptforge --offline` turns it on with nothing allowed; `SF_OFFLINE=1`
does the same for the CLI and Python.
+## IT deployment
+
+Everything an IT team needs to roll SculptForge out under its own rules: a policy file that locks settings, an
+audit log of what AI did, the studio's own AI gateway and single sign-on, and offline use. Nothing here needs a
+studio build; it works on the public one. For a security review, see the [security overview](security.md).
+
+### The policy file
+
+Put a `policy.json` where only administrators can write it:
+
+| OS | Path |
+|---|---|
+| Linux | `/etc/sculptforge/policy.json` |
+| macOS | `/Library/Application Support/SculptForge/policy.json` |
+| Windows | `C:\ProgramData\SculptForge\policy.json` (deploy it with Group Policy, Intune, SCCM or your usual tool) |
+
+SculptForge reads it at every start (the app, `sculptforge-cli`, MCP and the Python module). Each setting it locks
+is greyed out in **Edit > Preferences** with **Managed by your studio** next to it. Without a system file,
+`SF_POLICY=/path/policy.json` names one, for testing a policy or setting it from a launcher or a Rez package; while
+the system file exists, `SF_POLICY` is ignored, so an artist can't loosen it.
+
+```json
+{
+ "format": "sculptforge-policy", "version": 1,
+ "organization": "Acme Animation",
+ "ai": {"enabled": true, "providers": ["litellm", "comfyui"],
+ "endpoints": ["https://llm.acme.internal/", "http://comfy.acme.internal:8188/"], "requireSignIn": true},
+ "network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": false},
+ "mcp": {"enabled": true, "live": "never", "categories": ["info", "edit", "files"]},
+ "audit": {"path": "//fs01/audit/sculptforge/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},
+ "signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1example",
+ "useFor": ["https://llm.acme.internal/"]},
+ "telemetry": "none",
+ "updates": {"check": true, "channel": "stable", "feed": "https://sw.acme.internal/sculptforge/latest.json"}
+}
+```
+
+Every key is optional: what the policy leaves out stays the artist's choice. An unknown key or a wrong value is an
+error, so a typo never quietly drops a lock, and **a broken or unreadable policy fails closed**: AI, network
+features and AI tools stay off until it is fixed. `sculptforge-cli --policy` shows what the policy manages (exit
+code 2 when it is broken); use it to check a file before you deploy it.
+
+| Key | What it does |
+|---|---|
+| `organization` | Shown as "Managed by Acme Animation" |
+| `ai.enabled` | `false`: every AI feature off and locked (as `SF_AI=off`). `true`: on and locked. Left out: the artist's choice |
+| `ai.providers` | The only AI providers artists can pick: `free`, `anthropic`, `openai`, `ollama`, `lmstudio`, `vllm`, `llamacpp`, `litellm`, `openrouter`, `openai-compatible` (Brush Lab) and `huggingface`, `fal`, `meshy`, `comfyui`, `command` (Generate 3D) |
+| `ai.endpoints` | The only addresses AI requests may go to (URL prefixes, matched at a `/`) |
+| `ai.requireSignIn` | AI works only while the artist is signed in with the studio account (needs `signIn`) |
+| `network.enabled` | `false`: studio mode (see [Offline deployment](#offline-deployment)): no outside connection except `network.allow`, `ai.endpoints`, the identity provider and your update feed |
+| `network.allow` | More URL prefixes that stay reachable while the network is off |
+| `network.localNetwork` | `true`: the Unreal link and phone capture may use the studio network while the network is off |
+| `mcp.enabled` | `false`: no AI tool can connect (`sculptforge-cli --mcp` refuses to start, and **Help > Connect an AI tool** is gone) |
- | `mcp.live` | `"never"`: AI tools work only on their own scene and can never control an open SculptForge window |
++| `mcp.live` | `"never"`: AI tools work only on their own scene and can never control an open SculptForge window (the window never listens for them; **Let AI tools control this window** is locked off) |
+| `mcp.categories` | The kinds of command AI tools may use: `info` (read the scene), `edit` (change it in memory), `files` (open, save, export, bridges), `scripts` (macros), `network` (brush gallery, Unreal), `ai` (AI generation). Left out: all |
+| `audit.path`, `audit.maxMB`, `audit.keep` | Where the [audit log](#audit-log) goes, when it rotates (10 MB) and how many old files it keeps (5) |
+| `audit.required` | `true`: an AI action whose audit line can't be written (the share is down) is refused |
+| `signIn.issuer`, `signIn.clientId` | Your identity provider and the app registration (see [Single sign-on](#single-sign-on)) |
+| `signIn.clientSecret` | Only for providers that issue one to installed apps and require it (Google); it isn't secret there, and artists can read the policy |
+| `signIn.scopes`, `signIn.audience` | Scopes to ask for (default `openid profile email offline_access`); an audience, if your provider needs one (Auth0) |
+| `signIn.useFor` | Addresses that get the sign-in as a bearer token (default: `ai.endpoints`) |
+| `telemetry` | Only `"none"`: SculptForge has no telemetry. The key is there so your checklist can state it |
+| `updates.check` | `false`: no update check, and the artist can't turn it on |
+| `updates.channel` | `"stable"` or `"preview"`, locked |
+| `updates.feed`, `updates.mirror` | Your own update feed (a URL) and mirror (a URL or a file on a share) instead of the public one |
+
+The policy works alongside a [studio profile](#your-studio-build): a profile bakes in content and branding, the
+policy locks settings. When both turn the network off, both allow lists apply.
+
+### Audit log
+
- Every AI action is one line of JSON in a local file: each command an AI tool (MCP) runs, refused ones included, and
- every Brush Lab and Generate 3D request, from the app, `sculptforge-cli` and Python.
++Every AI action is one line of JSON in a local file: each command an AI tool (MCP) runs, refused ones included (`"tool":
++"mcp"`, or `"mcp-live"` when it controls an open window), and every Brush Lab and Generate 3D request (`"ai"`), from
++the app, `sculptforge-cli` and Python.
+
+```json
+{"time":"2026-11-05T14:03:22.120Z","user":"ana","host":"ws042","client":"mcp:claude-code 2.1.0","tool":"mcp",
+ "command":"export_glb","args":{"path":"/show/troll/assets/rock.glb"},"result":"ok","message":"Exported","ms":930}
+```
+
+- **What is never written:** artwork (meshes, images, textures), keys and tokens (any argument named like a key,
+ token, password or secret is `<redacted>`), and long text (strings are cut to 120 characters; a long prompt is
+ recorded as its length). File paths are kept: they say what was read or written.
+- **Where:** `audit.path` from the policy, with `{user}`, `{host}` and `{date}` filled in, so each machine can write
+ its own file on a share. Without a policy, `audit/ai-audit.jsonl` in the [settings
+ folder](troubleshooting.md#where-settings-live). **Edit > Preferences > AI** shows the path;
+ `sculptforge-cli --audit-log` prints it.
+- **Rotation:** past `audit.maxMB` the file becomes `.1`, `.1` becomes `.2`, and so on up to `audit.keep`.
+- Nothing is sent anywhere: collect the files with your own tools (any log shipper reads JSON lines).
+
+### AI providers
+
+**Edit > Preferences > AI > Provider** has presets that fill in the address and a model, so artists pick a name
+instead of typing URLs:
+
+| Preset | Address | Key |
+|---|---|---|
+| Anthropic (Claude) | `https://api.anthropic.com/v1/messages` | The artist's or the studio's API key |
+| OpenAI | `https://api.openai.com/v1/chat/completions` | API key |
+| Ollama | `http://localhost:11434/v1/chat/completions` | None |
+| LM Studio | `http://localhost:1234/v1/chat/completions` | None |
+| vLLM server | `http://localhost:8000/v1/chat/completions` (or your GPU server) | Optional |
+| llama.cpp server | `http://localhost:8080/v1/chat/completions` (or your server) | None |
+| LiteLLM proxy (studio gateway) | `http://localhost:4000/v1/chat/completions` (change it to your gateway) | A virtual key, or the studio sign-in |
+| OpenRouter | `https://openrouter.ai/api/v1/chat/completions` | API key |
+
+**Amazon Bedrock, Google Vertex AI and Azure OpenAI** go through a [LiteLLM proxy](https://docs.litellm.ai/docs/simple_proxy)
+your studio runs: the proxy holds the cloud credentials, applies your budgets and model list, and SculptForge talks
+only to it. A minimal proxy configuration:
+
+```yaml
+model_list:
+ - model_name: claude
+ litellm_params: {model: "bedrock/<Bedrock model id>", aws_region_name: us-west-2}
+ - model_name: gemini
+ litellm_params: {model: "vertex_ai/<Vertex model id>", vertex_project: acme-render, vertex_location: us-central1}
+ - model_name: gpt
+ litellm_params: {model: "azure/<your deployment>", api_base: "https://acme.openai.azure.com", api_version: "<API version>"}
+```
+
+Point the preset at `https://llm.acme.internal/v1/chat/completions`, list that prefix in `ai.endpoints`, allow only
+`litellm` in `ai.providers`, and artists can reach no other AI service. To validate the studio sign-in at the
+gateway, use LiteLLM's JWT authentication with your identity provider's keys.
+
+**Keys are kept in the operating system's keychain**: macOS Keychain, Windows Credential Manager, or the Secret
+Service on Linux (GNOME Keyring, KWallet, KeePassXC). They are never written to a settings file; keys from older
+versions move into the keychain at the first start. Where there is no keychain (`SF_KEYCHAIN=none`, a render node),
+a key typed in lasts until SculptForge quits; the environment variables `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
+`OPENROUTER_API_KEY`, `HF_TOKEN`, `FAL_KEY` and `MESHY_API_KEY` work everywhere.
+
+### Single sign-on
+
+With `signIn` in the policy, **Edit > Preferences > AI > Studio sign-in** signs the artist in with the studio
+account (Okta, Microsoft Entra ID, Google Workspace, Auth0, Keycloak or any OpenID Connect provider). It uses the
+**device authorization grant** only: SculptForge shows a short code and opens your provider's page, and the artist
+signs in there, in their browser, with your usual login and MFA. Nothing on the artist's computer listens for the
+answer: no local port, no redirect, no embedded browser. `sculptforge-cli --sign-in` does the same in a terminal.
+
+The tokens are kept in the keychain and refreshed when they expire. The access token is sent as
+`Authorization: Bearer` only to the addresses in `signIn.useFor` (default: `ai.endpoints`), such as your AI gateway;
+never to anyone else. SculptForge reads the ID token's name and email only to show who is signed in: your
+services verify the access token.
+
+To set it up, register a **public client** (no client secret) with the device flow turned on:
+
+| Provider | Where | Issuer |
+|---|---|---|
+| Okta | Applications > Create App Integration > OIDC > Native Application; Grant type: Device Authorization | `https://<org>.okta.com/oauth2/default` |
+| Microsoft Entra ID | App registrations > New registration; Authentication > Allow public client flows: Yes | `https://login.microsoftonline.com/<tenant id>/v2.0` |
+| Google Workspace | Google Cloud console > Credentials > OAuth client ID > TVs and Limited Input devices | `https://accounts.google.com` (list `https://oauth2.googleapis.com/` in `network.allow` when the network is off) |
+| Auth0 | Applications > Native; Advanced settings > Grant types: Device Code | `https://<tenant>.auth0.com/` (set `signIn.audience` to your API) |
+| Keycloak | Clients > Create; Client authentication: Off; OAuth 2.0 Device Authorization Grant: On | `https://<host>/realms/<realm>` |
+
+Put the client id in `signIn.clientId`. Google's device flow also wants the client's secret, which Google documents
+as not confidential for this client type: put it in `signIn.clientSecret`. Google's access tokens are meant for
+Google's own APIs, so with Google Workspace have your gateway validate the ID token instead.
+
+### Offline and air-gapped use
+
+- `"network": {"enabled": false}` in the policy, or `sculptforge --offline` / `SF_OFFLINE=1`, turns on studio
+ mode: every request goes through one gate that refuses anything not allowed before it is sent, follows no redirect,
+ and sockets open only on loopback (see [Offline deployment](#offline-deployment)).
+- AI can stay on in an air-gapped facility with local models: allow `ollama`, `lmstudio`, `vllm`, `llamacpp` or
+ `comfyui` and list their addresses in `ai.endpoints`.
+- Updates come from `updates.feed` / `updates.mirror` only; copy a release's `latest.json` there when you are ready.
+- Install from the signed checksums as described under [Offline deployment](#offline-deployment).
+
## Not yet
Planned pipeline features, roughly in order: OpenColorIO viewport display, Alembic export, fuller USD
diff --cc src/app/App.h
index 9f6be065,a97769a6..4327323b
--- a/src/app/App.h
+++ b/src/app/App.h
@@@ -542,15 -542,33 +543,39 @@@ private
// Preferences > AI (PanelAi.cpp, ai/AiPolicy.h): Enable AI features. Off removes the AI commands, the Brush Lab
// and Generate 3D entries and closes their windows; saved in ai.json at once (not in tests). SF_AI / --no-ai lock it.
void setAiFeatures(bool on);
+ void applyAiFeatures(bool on, bool save); // the switch itself, whatever locks it (setAiFeatures, a policy)
+ void registerPolicyTestCommand(); // ui_policy: UI tests only (tests/ui/studio_policy.sfui)
void registerAiActions(); // ui.brush_lab, ui.generate3d: only while AI is on
void drawAiPrefs(); // the Preferences > AI section and the first-run question
+ void drawAiStudioPrefs(); // Preferences > AI: what the studio's policy manages, the studio sign-in, the audit log
- void storeAiKeys();
- void applyUpdatePolicy(); // a studio policy's update check and channel (core/ManagedPolicy.h) over the saved ones // the keys aiSettings_ holds, into the OS keychain (a worker; ai/Secrets.h)
++ void storeAiKeys(); // the keys aiSettings_ holds, into the OS keychain (a worker; ai/Secrets.h)
++ void applyUpdatePolicy(); // a studio policy's update check and channel (core/ManagedPolicy.h) over the saved ones
+ // Live mode (PanelAiLink.cpp, link/AiLink.h): Preferences > AI > Let AI tools control this window. An AI tool
+ // (sculptforge-cli --mcp --attach) connects over a local socket / pipe only this user can open, is approved in
+ // a dialog (a one-time code), shows an "AI connected" badge with Disconnect while it works, and asks first
+ // before files outside the project, overwrites, scripts or the network. Off by default; gone while AI is off.
+ struct AiLinkState;
+ struct AiLinkStateDeleter {
+ void operator()(AiLinkState* s) const;
+ };
+ std::unique_ptr<AiLinkState, AiLinkStateDeleter> aiLink_;
+ void setAiLiveControl(bool on);
+ void syncAiLink(); // starts or stops the listener to match the switch (and the AI switch)
+ void pollAiLink(); // every frame: the connection's messages, one at a time
+ void drawAiLink(); // the Approve and Allow dialogs, the "AI connected" badge
+ void drawAiLinkPrefs(); // its switch in Preferences > AI
+ void aiLinkDisconnect(const std::string& why); // the kill switch: closes the connection now
+ void aiLinkPicked(const std::string& path); // a file the user chose: an AI tool may use it without asking
+ int aiLinkStateValue() const; // UI tests: 0 off, 1 listening, 2 waiting for approval, 3 connected, 4 asking
+ std::vector<std::string> aiLinkPickedPaths_; // files the user chose this run (each connection starts with them)
+ void aiLinkExecute(const link::AiLinkCall& call);
+ uint32_t activePartInfoId() const;
+ void labelAiUndo(uint32_t part, size_t undoCountBefore, uint64_t revisionBefore); // "AI: " on the new undo steps
+ bool aiApplyView(const Args& args, std::string& error); // view_set's preset / yaw / elevation / frame / zoom / ortho
+ bool aiRenderView(const Camera& cam, int width, int height, Image& img, std::string& error);
+ Json aiLiveTool(const std::string& name, const Args& args, bool& ok); // viewport_image, view_set, ...
// Brush Lab (AI brush designer)
+ std::shared_ptr<StudioSignInJob> signInJob_; // Preferences > AI > Studio sign-in, while it runs
bool showBrushLab_ = false; // floating; opened from the top shelf's AI Brush or the Brush palette
bool hideUi_ = false;
uint64_t seenSplatsVersion_ = 0;
diff --cc src/app/PanelAi.cpp
index a2af8a6b,4417431c..132ad057
--- a/src/app/PanelAi.cpp
+++ b/src/app/PanelAi.cpp
@@@ -62,6 -28,27 +62,27 @@@ void App::registerAiActions()
sw.checked = [] { return ai::aiEnabled(); };
sw.enabled = [] { return !ai::aiPolicyLocked(); };
actions_.add(std::move(sw));
+ if (!actions_.find("prefs.ai_live")) { // live mode (PanelAiLink.cpp): its switch and the kill switch
+ Action live;
+ live.id = "prefs.ai_live";
+ live.label = "Let AI tools control this window";
+ live.palette = "Preferences > AI";
+ live.description = "Live mode: an AI tool on this computer (sculptforge-cli --mcp --attach) can ask to sculpt in this "
+ "window while you watch. You approve each connection; files outside the project, scripts and "
+ "the network ask first. Nothing listens on the network.";
+ live.run = [this] { setAiLiveControl(!aiSettings_.liveControl); };
+ live.checked = [this] { return aiSettings_.liveControl; };
- live.enabled = [] { return ai::aiEnabled(); };
++ live.enabled = [] { return ai::aiEnabled() && policy::mcpLiveAllowed(); };
+ actions_.add(std::move(live));
+ Action cut;
+ cut.id = "ai.live_disconnect";
+ cut.label = "Disconnect AI tool";
+ cut.palette = "Preferences > AI";
+ cut.description = "Stop the AI tool controlling this window now (its steps stay in Undo).";
+ cut.run = [this] { aiLinkDisconnect("AI tool disconnected"); };
+ cut.enabled = [this] { return aiLinkStateValue() >= 2; };
+ actions_.add(std::move(cut));
+ }
commands_.remove("ai_features"); // (called again when AI is turned back on)
commands_.add({"ai_features", "Turn the AI features on or off (Preferences > AI > Enable AI features).",
{{"on", ParamSpec::Type::Bool, "true: on, false: off.", true}},
@@@ -131,7 -114,7 +152,8 @@@ void App::applyAiFeatures(bool on, boo
showBrushLab_ = false;
showImageTo3D_ = false;
}
+ syncAiLink(); // AI off: live mode stops and any AI tool is disconnected
+ if (!save) return;
std::string err;
if (!uiConfigDeterministic_ && !aiSettingsPath_.empty() && !aiSettings_.save(aiSettingsPath_, err))
status_ = "AI features " + std::string(on ? "on" : "off") + ", but " + err;
diff --cc src/app/PanelAiLink.cpp
index 00000000,72ac6465..aaf88344
mode 000000,100644..100644
--- a/src/app/PanelAiLink.cpp
+++ b/src/app/PanelAiLink.cpp
@@@ -1,0 -1,734 +1,787 @@@
+ // SculptForge - open source digital sculpting
+ // SPDX-License-Identifier: GPL-3.0-or-later
+ //
+ // Live mode: Preferences > AI > Let AI tools control this window (off by default; hidden while AI is off).
+ // `sculptforge-cli --mcp --attach` connects through link/AiLink.h (a Unix socket / named pipe only this user can
+ // open; no network port). The rules are link/AiLinkSession.h's; here they meet the window:
+ // - the Approve dialog, with the one-time code the user can read to the AI tool instead of clicking;
+ // - the "AI connected" badge with Disconnect (the kill switch; turning the switch or AI off also cuts it);
+ // - the Allow dialog before files outside the project, overwrites, scripts and the network;
+ // - every command runs as if typed in the console (App::runCommand), its undo steps labelled "AI: ...";
+ // - the live-window tools: viewport_image (what the user sees, as an image), view_set (camera), view_turntable
+ // (the model from every side in one image) and stroke_screen (a brush stroke drawn in screen space).
+ // A background thread accepts and reads; everything else happens here on the main thread, one message at a time.
+ #include "app/App.h"
+
+ #include "app/I18n.h"
+ #include "app/Theme.h"
+ #include "app/Ui.h"
+ #include "cli/McpServer.h"
+ #include "cli/McpTools.h"
++#include "core/AuditLog.h"
++#include "core/ManagedPolicy.h"
+ #include "link/AiLink.h"
+ #include "link/AiLinkSession.h"
+
+ #include <IconsLucide.h>
+ #include <imgui.h>
+
+ #include <atomic>
++#include <chrono>
+ #include <cmath>
+ #include <cstring>
+ #include <deque>
+ #include <optional>
+ #include <sstream>
+ #include <mutex>
+ #include <thread>
+ #include <utility>
+
+ namespace sf {
+
+ namespace {
+
+ constexpr double kApprovalSeconds = 120.0; // an unanswered Approve dialog says no
+
+ double seconds() { return double(SDL_GetTicksNS()) * 1e-9; }
+
+ Json schemaProp(const char* type, const char* description) {
+ Json p = Json::object();
+ p.set("type", type);
+ p.set("description", description);
+ return p;
+ }
+
+ Json liveTool(const char* name, const char* description, std::vector<std::pair<const char*, Json>> props) {
+ Json properties = Json::object();
+ for (auto& [k, v] : props) properties.set(k, std::move(v));
+ Json schema = Json::object();
+ schema.set("type", "object");
+ schema.set("properties", std::move(properties));
+ schema.set("required", Json::array());
+ Json t = Json::object();
+ t.set("name", name);
+ t.set("description", description);
+ t.set("inputSchema", std::move(schema));
+ return t;
+ }
+
+ Json liveTools() {
+ Json tools = Json::array();
+ const auto view = [] {
+ return std::vector<std::pair<const char*, Json>>{
+ {"preset", schemaProp("string", "front, back, left, right, top, bottom or three_quarter (front-right, a little from above).")},
+ {"yaw", schemaProp("number", "Degrees around the vertical axis: 0 = front, 90 = the model's right side, 180 = back.")},
+ {"elevation", schemaProp("number", "Degrees above the model (-89..89): 0 = level, 30 = looking down a little.")},
+ {"frame", schemaProp("string", "Frame the view on: all (every visible Part), active (the active Part) or a Part's name.")},
+ {"zoom", schemaProp("number", "Closer (2 = twice as close) or further (0.5) after framing.")},
+ {"ortho", schemaProp("boolean", "Orthographic (true) or perspective (false).")}};
+ };
+ Json image = viewportImageTool(); // (one schema with the headless server: cli/McpTools.h)
+ image.set("description", "See the model: the viewport exactly as the user sees it (without the interface), as a PNG. "
+ "The view options turn the user's camera too (they stay; with none, the view as it is). "
+ "Look after every step and correct what you see.");
+ tools.push(std::move(image));
+ tools.push(liveTool("view_set", "Turn and frame the camera the user sees (and viewport_image renders).", view()));
+ tools.push(liveTool("view_turntable",
+ "The model from several sides in one image (a grid, labelled by yaw), to check form and "
+ "proportions all around. The user's camera is put back afterwards.",
+ {{"views", schemaProp("number", "4, 6 or 8 views around (default 4: front, right, back, left).")},
+ {"elevation", schemaProp("number", "Degrees above the model (default 10).")},
+ {"size", schemaProp("number", "Each view's side in pixels (192-512, default 320).")}}));
+ tools.push(liveTool(
+ "stroke_screen",
+ "Brush stroke drawn on the screen, as a user drags across the viewport: points in viewport coordinates "
+ "(0,0 = top left, 1,1 = bottom right), projected onto the model (points off the model are skipped). Use "
+ "viewport_image to see where things are. One undo step.",
+ {{"points", schemaProp("string", "\"u,v u,v ...\" in 0..1 viewport coordinates (at least one on the model).")},
+ {"brush", schemaProp("string", "Brush name (Standard, Clay, Clay Block, Crease, Inflate, Smooth, Pinch...). Default: the active brush.")},
+ {"radius", schemaProp("number", "Brush radius as a fraction of the viewport's height (default 0.04).")},
+ {"strength", schemaProp("number", "0-1 (default 0.5).")},
+ {"invert", schemaProp("boolean", "Carve instead of build (like holding Alt).")},
+ {"symmetry", schemaProp("string", "Mirror across these world planes, e.g. \"x\" (default none).")}}));
+ return tools;
+ }
+
+ bool isLiveTool(const std::string& name) {
+ return name == "viewport_image" || name == "view_set" || name == "view_turntable" || name == "stroke_screen";
+ }
+
++// A studio's policy (core/ManagedPolicy.h) may allow only some kinds of tool: the rest are neither listed nor run.
++bool policyAllowsTool(const Command* cmd, const std::string& name, std::string* why = nullptr) {
++ std::vector<std::string> params;
++ if (cmd)
++ for (const auto& p : cmd->params) params.push_back(p.name);
++ return policy::mcpToolAllowed(name, params, why);
++}
++
++// One line in the audit log (core/AuditLog.h) per live-mode call, refusals too.
++void auditLive(const std::string& client, const std::string& name, const Args& args, bool ok, const std::string& message,
++ int64_t ms = -1) {
++ audit::Entry entry;
++ entry.client = "mcp-live:" + client;
++ entry.tool = "mcp-live";
++ entry.command = name;
++ entry.args = audit::summarizeArgs(args);
++ entry.ok = ok;
++ entry.message = message;
++ entry.ms = ms;
++ audit::record(entry);
++}
++
+ // Commands that start a new scene (Document::setMesh: the edit history is cleared).
+ bool replacesScene(const std::string& name) {
+ static const char* const kNames[] = {"new_sphere", "new_plane", "new_head", "new_starter_mesh", "new_bench_sphere",
+ "open", "open_obj", "open_project", "calibrate", "bridge_import", "bridge_receive",
+ "blender_receive", "maya_receive"};
+ for (const char* n : kNames)
+ if (name == n) return true;
+ return false;
+ }
+
+ std::string degrees(float radians) {
+ char buf[16];
+ std::snprintf(buf, sizeof buf, "%.0f", double(glm::degrees(radians)));
+ return buf;
+ }
+
+ } // namespace
+
+ // ---------------------------------------------------------------------------
+ // State: the listener thread and what the main thread is doing with the connection
+ // ---------------------------------------------------------------------------
+
+ struct App::AiLinkState {
+ link::AiLinkListener listener;
+ link::AiLinkConn conn;
+ std::mutex connMutex; // conn: reads (thread) and writes (main thread)
+ std::thread thread;
+ std::atomic<bool> stop{false};
+ std::atomic<bool> connected{false};
+ std::atomic<bool> drop{false}; // the main thread asks the thread to close the connection
+
+ struct Event {
+ enum class Kind { Connected, Line, Closed } kind;
+ std::string line;
+ };
+ std::mutex eventMutex;
+ std::deque<Event> events;
+
+ std::unique_ptr<link::AiLinkSession> session;
+ std::deque<std::string> waiting; // lines that came while a dialog was open
+ double approvalSince = 0.0;
+ bool approving = false;
+ bool focusDialog = false; // a dialog just opened: bring it to the front once
+ struct Pending {
+ link::AiLinkCall call;
+ std::string reason;
+ };
+ std::optional<Pending> confirm;
+ std::string error; // why the listener isn't running
+ int commands = 0; // tool calls run this connection
+
+ void push(Event e) {
+ {
+ std::lock_guard lock(eventMutex);
+ events.push_back(std::move(e));
+ }
+ wakeMainLoop();
+ }
+
+ void send(const std::string& line) {
+ std::lock_guard lock(connMutex);
+ conn.writeLine(line);
+ }
+
+ void run() {
+ while (!stop) {
+ if (!connected) {
+ link::AiLinkConn client;
+ bool refused = false;
+ if (!listener.accept(client, 200, &refused)) continue;
+ std::lock_guard lock(connMutex);
+ conn = std::move(client);
+ connected = true;
+ drop = false;
+ push({Event::Kind::Connected, {}});
+ continue;
+ }
+ // A second client while one is connected: told so and closed.
+ {
+ link::AiLinkConn other;
+ if (listener.accept(other, 0)) other.writeLine(R"({"error":"SculptForge is already connected to an AI tool"})");
+ }
+ std::string line;
+ int got;
+ {
+ std::lock_guard lock(connMutex);
+ got = drop ? -1 : conn.readLine(line, 50);
+ if (got < 0) conn.close();
+ }
+ if (got > 0) push({Event::Kind::Line, std::move(line)});
+ else if (got < 0) {
+ connected = false;
+ push({Event::Kind::Closed, {}});
+ } else {
+ std::this_thread::sleep_for(std::chrono::milliseconds(5)); // (lets the main thread write)
+ }
+ }
+ }
+ };
+
+ void App::AiLinkStateDeleter::operator()(AiLinkState* s) const {
+ if (!s) return;
+ s->stop = true;
+ if (s->thread.joinable()) s->thread.join();
+ delete s;
+ }
+
+ // ---------------------------------------------------------------------------
+ // The switch
+ // ---------------------------------------------------------------------------
+
+ void App::setAiLiveControl(bool on) {
++ if (std::string why; on && !policy::mcpLiveAllowed(&why)) {
++ status_ = why;
++ return;
++ }
+ aiSettings_.liveControl = on;
+ std::string err;
+ if (!uiConfigDeterministic_ && !aiSettingsPath_.empty() && !aiSettings_.save(aiSettingsPath_, err)) status_ = err;
+ syncAiLink();
+ if (!aiLink_ && on && ai::aiEnabled()) return; // (status_ says why)
+ status_ = on && aiLink_ ? tr("AI tools can ask to control this window (Preferences > AI)")
+ : tr("AI tools can't control this window");
+ }
+
+ void App::syncAiLink() {
- const bool want = ai::aiEnabled() && aiSettings_.liveControl;
++ const bool want = ai::aiEnabled() && aiSettings_.liveControl && policy::mcpLiveAllowed(); // (a policy: never listen)
+ if (want == bool(aiLink_)) return;
+ if (!want) {
+ if (aiLink_ && aiLink_->session) consoleEcho("ai_live", {}, {true, "AI tool disconnected"});
+ aiLink_.reset();
+ return;
+ }
+ std::unique_ptr<AiLinkState, AiLinkStateDeleter> s(new AiLinkState);
+ std::string err;
+ const std::string endpoint = link::aiLinkEndpoint(err);
+ if (endpoint.empty() || !s->listener.open(endpoint, err)) {
+ status_ = std::string(tr("Live mode can't start: ")) + err;
+ SDL_Log("Live mode: %s", err.c_str());
+ aiSettings_.liveControl = false;
+ return;
+ }
+ SDL_Log("Live mode: listening on %s", endpoint.c_str());
+ AiLinkState* raw = s.get();
+ s->thread = std::thread([raw] { raw->run(); });
+ aiLink_ = std::move(s);
+ }
+
+ void App::aiLinkDisconnect(const std::string& why) {
+ if (!aiLink_ || !aiLink_->connected) return;
+ aiLink_->drop = true;
+ {
+ std::lock_guard lock(aiLink_->connMutex);
+ aiLink_->conn.shutdown();
+ }
+ status_ = why;
+ }
+
+ void App::aiLinkPicked(const std::string& path) {
+ if (aiLink_ && aiLink_->session) aiLink_->session->policy.addPicked(path);
+ aiLinkPickedPaths_.push_back(path);
+ }
+
+ int App::aiLinkStateValue() const {
+ if (!aiLink_) return 0;
+ if (!aiLink_->session) return 1;
+ if (aiLink_->session->state() == link::AiLinkSession::State::Pairing) return 2;
+ return aiLink_->confirm ? 4 : 3;
+ }
+
+ void App::drawAiLinkPrefs() {
+ if (!ai::aiEnabled()) return;
++ if (!policy::mcpLiveAllowed()) { // the studio's policy says never: the switch stays off and nothing listens
++ ImGui::BeginDisabled();
++ bool off = false;
++ ImGui::Checkbox(tr("Let AI tools control this window##prefs.ai_live"), &off);
++ ImGui::EndDisabled();
++ ImGui::SameLine();
++ ui::ManagedBadge();
++ return;
++ }
+ bool on = aiSettings_.liveControl;
+ if (ImGui::Checkbox(tr("Let AI tools control this window##prefs.ai_live"), &on)) setAiLiveControl(on);
+ ui::HelpAction(*this, "prefs.ai_live");
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("%s", tr("An AI tool on this computer (sculptforge-cli --mcp --attach) can ask to sculpt here while "
+ "you watch. You approve each connection; it can see the viewport, and what it sees goes "
+ "to that tool's AI service. Files outside the project, scripts and the network ask "
+ "you first. Nothing listens on the network."));
+ ImGui::PopStyleColor();
+ if (aiLink_ && !aiLink_->error.empty()) ImGui::TextColored(theme::danger, "%s", aiLink_->error.c_str());
+ }
+
+ // ---------------------------------------------------------------------------
+ // Messages
+ // ---------------------------------------------------------------------------
+
+ void App::pollAiLink() {
+ syncAiLink();
+ if (!aiLink_) return;
+ AiLinkState& s = *aiLink_;
+ std::deque<AiLinkState::Event> events;
+ {
+ std::lock_guard lock(s.eventMutex);
+ events.swap(s.events);
+ }
+ for (auto& e : events) {
+ if (e.kind == AiLinkState::Event::Kind::Connected) {
+ s.session = std::make_unique<link::AiLinkSession>(link::makePairingCode());
+ s.session->policy.projectDir = macroProjectDir();
+ for (const std::string& p : aiLinkPickedPaths_) s.session->policy.addPicked(p);
+ s.waiting.clear();
+ s.confirm.reset();
+ s.approving = false;
+ s.commands = 0;
+ } else if (e.kind == AiLinkState::Event::Kind::Closed) {
+ if (s.session && s.session->state() == link::AiLinkSession::State::Paired) {
+ status_ = tr("AI tool disconnected");
+ consoleEcho("ai_live", {}, {true, "AI tool disconnected"});
+ }
+ s.session.reset();
+ s.waiting.clear();
+ s.confirm.reset();
+ s.approving = false;
+ } else if (s.session) {
+ s.waiting.push_back(std::move(e.line));
+ }
+ }
+ if (!s.session) return;
+ if (s.approving && seconds() - s.approvalSince > kApprovalSeconds) {
+ s.send(s.session->deny());
+ s.approving = false;
+ aiLinkDisconnect(tr("AI connection request timed out"));
+ return;
+ }
+ // One message at a time; none while a dialog waits for the user.
+ while (!s.waiting.empty() && !s.confirm && s.session && s.session->state() != link::AiLinkSession::State::Closed) {
+ const bool wasPairing = s.session->state() == link::AiLinkSession::State::Pairing;
+ const std::string line = std::move(s.waiting.front());
+ s.waiting.pop_front();
+ link::AiLinkSession::Step step = s.session->handle(line, seconds());
+ using K = link::AiLinkSession::Step::Kind;
+ if (!step.reply.empty() && step.kind != K::Execute && step.kind != K::ListTools) s.send(step.reply);
+ if (wasPairing && s.session->state() == link::AiLinkSession::State::Paired) { // the right code
+ s.approving = false;
+ status_ = std::string(tr("AI connected: ")) + s.session->client();
+ consoleEcho("ai_live", {}, {true, "AI connected: " + s.session->client()});
+ }
+ switch (step.kind) {
+ case K::None:
+ case K::Reply: break;
+ case K::Close:
+ aiLinkDisconnect(tr("AI tool disconnected"));
+ return;
+ case K::ShowApproval:
+ s.approving = true;
+ s.focusDialog = true;
+ s.approvalSince = seconds();
+ break;
+ case K::ListTools: {
+ Json tools = Json::array();
+ const Json commands = mcpToolList(commands_), live = liveTools();
- for (const Json& t : commands.items())
++ for (const Json& t : commands.items()) // (mcpToolList leaves out what the policy doesn't allow)
+ if (!link::AiLinkPolicy::hidden(t["name"].asString())) tools.push(t);
- for (const Json& t : live.items()) tools.push(t);
++ for (const Json& t : live.items())
++ if (policyAllowsTool(nullptr, t["name"].asString())) tools.push(t);
+ s.send(link::AiLinkSession::listReply(step.call.id, std::move(tools)));
+ break;
+ }
+ case K::Execute:
+ case K::Confirm: {
+ const std::string& name = step.call.name;
+ const Command* cmd = commands_.find(name);
+ if (!cmd && !isLiveTool(name)) {
+ s.send(link::AiLinkSession::resultReply(step.call.id, false, "Unknown tool: " + name));
+ break;
+ }
++ if (std::string why; !policyAllowsTool(isLiveTool(name) ? nullptr : cmd, name, &why) ||
++ (audit::required() && !audit::writable(&why))) {
++ auditLive(s.session->client(), name, step.call.args, false, why);
++ s.send(link::AiLinkSession::resultReply(step.call.id, false, why));
++ break;
++ }
+ s.session->policy.projectDir = macroProjectDir();
+ link::AiDecision d = s.session->policy.classify(isLiveTool(name) ? nullptr : cmd, name, step.call.args);
+ // A new scene clears the history: unsaved work couldn't be undone back.
+ if (d.verdict == link::AiVerdict::Allow && doc_.dirty() && replacesScene(name))
+ d = {link::AiVerdict::Confirm, "Replaces the scene: your unsaved changes would be lost"};
+ if (d.verdict == link::AiVerdict::Deny) {
++ auditLive(s.session->client(), name, step.call.args, false, d.reason);
+ s.send(link::AiLinkSession::resultReply(step.call.id, false, d.reason));
+ } else if (d.verdict == link::AiVerdict::Confirm) {
+ s.confirm = AiLinkState::Pending{std::move(step.call), d.reason};
+ s.focusDialog = true;
+ status_ = std::string(tr("Your AI tool asks: ")) + d.reason;
+ } else {
+ aiLinkExecute(step.call);
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ void App::aiLinkExecute(const link::AiLinkCall& call) {
+ AiLinkState& s = *aiLink_;
+ ++s.commands;
++ const auto start = std::chrono::steady_clock::now();
++ const auto elapsedMs = [&] {
++ return int64_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count());
++ };
+ if (isLiveTool(call.name)) {
+ bool ok = true;
+ Json content = aiLiveTool(call.name, call.args, ok);
++ auditLive(s.session->client(), call.name, call.args, ok, ok ? "" : "failed", elapsedMs()); // (never the image)
+ s.send(link::AiLinkSession::contentReply(call.id, std::move(content), !ok));
+ return;
+ }
+ // As if typed in the console; the steps it adds to the history say who made them.
+ const uint32_t part = activePartInfoId();
+ const size_t before = doc_.undo.undoCount();
+ const uint64_t revision = doc_.undo.revision();
+ runCommand(call.name, call.args);
+ labelAiUndo(part, before, revision);
++ auditLive(s.session->client(), call.name, call.args, lastCommandOk_, status_, elapsedMs());
+ s.send(link::AiLinkSession::resultReply(call.id, lastCommandOk_, status_));
+ }
+
+ uint32_t App::activePartInfoId() const { return doc_.activePartInfo().id; }
+
+ void App::labelAiUndo(uint32_t part, size_t before, uint64_t revision) {
+ if (doc_.undo.revision() == revision || !doc_.undo.canUndo()) return;
+ // New steps on the same Part: every one of them; on another Part (a new Part made active): its last one.
+ const size_t added = doc_.activePartInfo().id == part && doc_.undo.undoCount() > before ? doc_.undo.undoCount() - before : 1;
+ for (size_t k = 0; k < added; ++k) {
+ UndoRecord* r = k == 0 ? doc_.undo.lastUndo() : nullptr;
+ if (k > 0) r = const_cast<UndoRecord*>(doc_.undo.undoStep(k));
+ if (r && r->label.rfind("AI: ", 0) != 0) r->label = "AI: " + r->label;
+ }
+ }
+
+ // ---------------------------------------------------------------------------
+ // The live-window tools
+ // ---------------------------------------------------------------------------
+
+ bool App::aiApplyView(const Args& args, std::string& error) {
+ const std::string preset = argString(args, "preset");
+ if (!preset.empty()) {
+ static const struct { const char* name; float yaw, pitch; } kPresets[] = {
+ {"front", 0, 0}, {"back", 180, 0}, {"right", 90, 0}, {"left", -90, 0},
+ {"top", 0, -89}, {"bottom", 0, 89}, {"three_quarter", 35, -15}};
+ bool found = false;
+ for (const auto& p : kPresets)
+ if (preset == p.name) {
+ camera_.yaw = glm::radians(p.yaw);
+ camera_.pitch = glm::radians(p.pitch);
+ camera_.roll = 0.0f;
+ found = true;
+ }
+ if (!found) {
+ error = "preset must be front, back, left, right, top, bottom or three_quarter";
+ return false;
+ }
+ }
+ if (args.contains("yaw")) camera_.yaw = glm::radians(float(argNumber(args, "yaw", 0.0))), camera_.roll = 0.0f;
+ if (args.contains("elevation"))
+ camera_.pitch = -glm::radians(std::clamp(float(argNumber(args, "elevation", 0.0)), -89.0f, 89.0f)), camera_.roll = 0.0f;
+ if (args.contains("ortho")) camera_.ortho = argBool(args, "ortho", false), autoOrtho_ = false;
+ const std::string frame = argString(args, "frame");
+ if (frame == "all") camera_.frame(sceneBounds());
+ else if (frame == "active") camera_.frame(doc_.mesh.bounds());
+ else if (!frame.empty()) {
+ const int i = doc_.findPart(frame);
+ if (i < 0) {
+ error = "No Part \"" + frame + "\" (see scene_overview)";
+ return false;
+ }
+ camera_.frame(doc_.partMesh(i).bounds());
+ }
+ if (args.contains("zoom")) {
+ const float z = float(argNumber(args, "zoom", 1.0));
+ if (!(z > 0.05f && z < 20.0f)) {
+ error = "zoom must be between 0.05 and 20";
+ return false;
+ }
+ camera_.distance /= z;
+ }
+ return true;
+ }
+
+ bool App::aiRenderView(const Camera& cam, int width, int height, Image& img, std::string& error) {
+ img.width = width;
+ img.height = height;
+ RenderSettings settings = renderSettings_;
+ settings.dimInactive = false;
+ settings.showMask = true; // (the agent sees the mask it painted)
+ settings.resolutionScale = 1.0f;
+ constexpr GLenum kFramebufferBinding = 0x8CA6, kViewport = 0x0BA2;
+ GLint fbo = 0, viewport[4] = {};
+ gl::GetIntegerv(kFramebufferBinding, &fbo);
+ gl::GetIntegerv(kViewport, viewport);
+ const bool ok = renderer_.renderToImage(cam, width, height, settings, img.rgba, error);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, GLuint(fbo));
+ gl::Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
+ return ok;
+ }
+
+ Json App::aiLiveTool(const std::string& name, const Args& args, bool& ok) {
+ Json content = Json::array();
+ auto text = [&](const std::string& t) {
+ Json j = Json::object();
+ j.set("type", "text");
+ j.set("text", t);
+ content.push(std::move(j));
+ };
+ auto image = [&](const Image& img) {
+ std::vector<uint8_t> png;
+ if (!img.encodePng(png)) return false;
+ Json j = Json::object();
+ j.set("type", "image");
+ j.set("data", link::base64Encode(png.data(), png.size()));
+ j.set("mimeType", "image/png");
+ content.push(std::move(j));
+ return true;
+ };
+ auto fail = [&](const std::string& e) {
+ ok = false;
+ text(e);
+ return content;
+ };
+ ok = true;
+ std::string err;
+ const auto viewText = [this] {
+ return "Camera: yaw " + degrees(camera_.yaw) + ", elevation " + degrees(-camera_.pitch) +
+ (camera_.ortho ? ", orthographic" : ", perspective") + "; active Part: " + doc_.activePartInfo().name;
+ };
+
+ if (name == "view_set" || name == "viewport_image") {
+ if (!aiApplyView(args, err)) return fail(err);
+ if (name == "view_set") {
+ text(viewText());
+ return content;
+ }
+ const CanvasRect c = canvasRect();
+ const float aspect = c.h > 1.0f ? c.w / c.h : 1.0f;
+ const int longSide = std::clamp(int(argNumber(args, "size", 768)), 256, 1536);
+ const int w = aspect >= 1.0f ? longSide : std::max(1, int(std::lround(longSide * aspect)));
+ const int h = aspect >= 1.0f ? std::max(1, int(std::lround(longSide / aspect))) : longSide;
+ Camera cam = camera_;
+ cam.aspect = float(w) / float(h);
+ Image img;
+ if (!aiRenderView(cam, w, h, img, err) || !image(img)) return fail("Can't render the view: " + err);
+ text(viewText() + " (" + std::to_string(w) + "x" + std::to_string(h) + ")");
+ return content;
+ }
+
+ if (name == "view_turntable") {
+ const int views = int(argNumber(args, "views", 4));
+ if (views != 4 && views != 6 && views != 8) return fail("views must be 4, 6 or 8");
+ const int tile = std::clamp(int(argNumber(args, "size", 320)), 192, 512);
+ const int cols = views / 2, rows = 2;
+ Camera cam = camera_;
+ cam.frame(sceneBounds());
+ cam.aspect = 1.0f;
+ cam.roll = 0.0f;
+ cam.pitch = -glm::radians(std::clamp(float(argNumber(args, "elevation", 10.0)), -89.0f, 89.0f));
+ Image sheet;
+ sheet.width = cols * tile;
+ sheet.height = rows * tile;
+ sheet.rgba.assign(size_t(sheet.width) * sheet.height * 4, 0);
+ std::string yaws;
+ for (int v = 0; v < views; ++v) {
+ cam.yaw = glm::radians(360.0f * float(v) / float(views));
+ Image img;
+ if (!aiRenderView(cam, tile, tile, img, err)) return fail("Can't render the view: " + err);
+ const int ox = (v % cols) * tile, oy = (v / cols) * tile;
+ for (int y = 0; y < tile; ++y)
+ std::memcpy(&sheet.rgba[(size_t(oy + y) * sheet.width + ox) * 4], &img.rgba[size_t(y) * tile * 4], size_t(tile) * 4);
+ yaws += (v ? ", " : "") + degrees(cam.yaw);
+ }
+ if (!image(sheet)) return fail("Can't encode the image");
+ text(std::to_string(views) + " views, left to right then top to bottom, yaw " + yaws + " degrees (0 = front, 90 = "
+ "the model's right side); elevation " + degrees(-cam.pitch) + ". The user's camera didn't move.");
+ return content;
+ }
+
+ if (name == "stroke_screen") {
+ const CanvasRect c = canvasRect();
+ if (c.w < 2.0f || c.h < 2.0f) return fail("The viewport is too small");
+ std::string worldPoints;
+ int hits = 0, misses = 0;
+ float radius = 0.0f;
+ const float radiusFrac = std::clamp(float(argNumber(args, "radius", 0.04)), 0.002f, 0.5f);
+ std::stringstream in(argString(args, "points"));
+ std::string token;
+ while (in >> token) {
+ float u = 0, v = 0;
+ if (std::sscanf(token.c_str(), "%f,%f", &u, &v) != 2 || !std::isfinite(u) || !std::isfinite(v))
+ return fail("points must be \"u,v u,v ...\" in 0..1 (bad: " + token + ")");
+ glm::vec3 origin, dir;
+ camera_.screenRay(u * c.w, v * c.h, c.w, c.h, origin, dir);
+ RayHit hit;
+ if (!doc_.bvh.raycast(doc_.mesh, origin, dir, hit)) {
+ ++misses;
+ continue;
+ }
+ if (radius == 0.0f) radius = camera_.worldPerPixel(hit.position, c.h) * radiusFrac * c.h;
+ char buf[96];
+ std::snprintf(buf, sizeof buf, "%s%g,%g,%g", worldPoints.empty() ? "" : " ", double(hit.position.x),
+ double(hit.position.y), double(hit.position.z));
+ worldPoints += buf;
+ ++hits;
+ if (hits > 2000) return fail("at most 2000 points");
+ }
+ if (hits == 0) return fail("No point is on the active Part (see viewport_image; 0,0 is the top left)");
+ const glm::vec3 f = camera_.forward();
+ char view[96];
+ std::snprintf(view, sizeof view, "%g,%g,%g", double(f.x), double(f.y), double(f.z));
+ Args a{{"points", worldPoints}, {"view", std::string(view)}, {"radius", double(radius)},
+ {"strength", argNumber(args, "strength", 0.5)}, {"invert", argBool(args, "invert", false)}};
+ if (args.contains("brush")) a["brush"] = argString(args, "brush");
+ if (args.contains("symmetry")) a["symmetry"] = argString(args, "symmetry");
+ const uint32_t part = activePartInfoId();
+ const size_t before = doc_.undo.undoCount();
+ const uint64_t revision = doc_.undo.revision();
+ runCommand("stroke", a);
+ labelAiUndo(part, before, revision);
+ ok = lastCommandOk_;
+ text(status_ + (misses ? " (" + std::to_string(misses) + " points were off the model)" : ""));
+ return content;
+ }
+ return fail("Unknown tool: " + name);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Dialogs and the badge
+ // ---------------------------------------------------------------------------
+
+ void App::drawAiLink() {
+ if (!aiLink_ || !aiLink_->session) return;
+ AiLinkState& s = *aiLink_;
+ const float sc = uiScale_;
+ const ImGuiViewport* vp = ImGui::GetMainViewport();
+ const ImVec2 centre(vp->WorkPos.x + vp->WorkSize.x * 0.5f, vp->WorkPos.y + vp->WorkSize.y * 0.5f);
+ const ImGuiWindowFlags dialog = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_AlwaysAutoResize;
+
+ if (s.approving && s.session->state() == link::AiLinkSession::State::Pairing) {
+ ImGui::SetNextWindowPos(centre, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (std::exchange(s.focusDialog, false)) ImGui::SetNextWindowFocus();
+ bool open = true;
+ if (ImGui::Begin(tr("Let an AI tool control this window?###ailinkapprove"), &open, dialog)) {
+ ImGui::PushTextWrapPos(460 * sc);
+ ImGui::TextWrapped(tr("\"%s\" on this computer asks to sculpt in this window."), s.session->client().c_str());
+ ImGui::Spacing();
+ ImGui::TextUnformatted(tr("Code"));
+ const std::string& code = s.session->code();
+ ImGui::PushFont(nullptr);
+ ImGui::SetWindowFontScale(2.2f);
+ ImGui::TextColored(theme::accent, "%s %s", code.substr(0, 3).c_str(), code.substr(3).c_str());
+ ImGui::SetWindowFontScale(1.0f);
+ ImGui::PopFont();
+ ImGui::TextWrapped("%s", tr("Click Approve, or tell your AI tool this code. Approval lasts until it disconnects."));
+ ImGui::Spacing();
+ ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled));
+ ImGui::TextWrapped("%s", tr("It can run SculptForge's commands and see the viewport; what it sees goes to that "
+ "tool's AI service. Every step is in Undo. Files outside the project, scripts "
+ "and the network ask you first."));
+ ImGui::PopStyleColor();
+ ImGui::PopTextWrapPos();
+ ImGui::Spacing();
+ ImGui::PushStyleColor(ImGuiCol_Button, theme::accent);
+ ImGui::PushStyleColor(ImGuiCol_ButtonHovered, theme::accentHover);
+ ImGui::PushStyleColor(ImGuiCol_Text, theme::textOnAccent);
+ const bool approve = ImGui::Button(tr("Approve##ailink"), ImVec2(140 * sc, 0));
+ ImGui::PopStyleColor(3);
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Deny##ailink"), ImVec2(120 * sc, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) open = false;
+ if (approve) {
+ s.send(s.session->approve());
+ s.approving = false;
+ status_ = std::string(tr("AI connected: ")) + s.session->client();
+ consoleEcho("ai_live", {}, {true, "AI connected: " + s.session->client()});
+ }
+ }
+ ImGui::End();
+ if (!open) {
+ s.send(s.session->deny());
+ s.approving = false;
+ aiLinkDisconnect(tr("AI connection declined"));
+ }
+ return;
+ }
+ if (s.session->state() != link::AiLinkSession::State::Paired) return;
+
+ // The badge: bottom right of the canvas (clear of the history strip on top), while connected.
+ const CanvasRect c = canvasRect();
+ ImGui::SetNextWindowPos(ImVec2(c.x + c.w - 12 * sc, c.y + c.h - 12 * sc), ImGuiCond_Always, ImVec2(1.0f, 1.0f));
+ ImGui::SetNextWindowBgAlpha(0.92f);
+ ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 8 * sc);
+ ImGui::PushStyleColor(ImGuiCol_Border, theme::accent);
+ if (ImGui::Begin("##ailinkbadge", nullptr,
+ ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |
+ ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) {
+ const float pulse = 0.55f + 0.45f * std::sin(float(seconds()) * 3.0f);
+ ImVec4 dot = theme::accent;
+ dot.w = pulse;
+ ImGui::TextColored(dot, ICON_LC_SPARKLES);
+ ImGui::SameLine();
+ ImGui::Text(tr("AI connected: %s"), s.session->client().c_str());
+ ImGui::SameLine();
+ ImGui::TextDisabled(tr("%d steps"), s.commands);
+ ImGui::SameLine();
+ if (ImGui::SmallButton(tr("Disconnect##ailink"))) aiLinkDisconnect(tr("AI tool disconnected"));
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", tr("Stop the AI tool now. Its steps stay in Undo."));
+ }
+ ImGui::End();
+ ImGui::PopStyleColor();
+ ImGui::PopStyleVar();
+
+ if (!s.confirm) return;
+ ImGui::SetNextWindowPos(centre, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
+ if (std::exchange(s.focusDialog, false)) ImGui::SetNextWindowFocus();
+ bool open = true;
+ bool allow = false;
+ if (ImGui::Begin(tr("Allow this AI step?###ailinkconfirm"), &open, dialog)) {
+ ImGui::PushTextWrapPos(480 * sc);
+ ImGui::TextWrapped(tr("%s wants to run:"), s.session->client().c_str());
+ ImGui::TextColored(theme::accent, "%s", s.confirm->call.name.c_str());
+ const std::string args = link::describeArgs(s.confirm->call.args);
+ if (!args.empty()) ImGui::TextWrapped("%s", args.c_str());
+ ImGui::Spacing();
+ ImGui::TextColored(theme::danger, "%s", s.confirm->reason.c_str());
+ ImGui::PopTextWrapPos();
+ ImGui::Spacing();
+ allow = ImGui::Button(tr("Allow once##ailink"), ImVec2(140 * sc, 0));
+ ImGui::SameLine();
+ if (ImGui::Button(tr("Deny##ailinkconfirm"), ImVec2(120 * sc, 0)) || ImGui::IsKeyPressed(ImGuiKey_Escape)) open = false;
+ }
+ ImGui::End();
+ if (allow) {
+ AiLinkState::Pending p = std::move(*s.confirm);
+ s.confirm.reset();
+ // The user said yes to this file: later steps may use it without asking again (as if picked).
+ for (const char* key : {"path", "file", "folder", "out"})
+ if (const std::string f = argString(p.call.args, key); !f.empty()) aiLinkPicked(f);
+ aiLinkExecute(p.call);
+ } else if (!open) {
++ auditLive(s.session->client(), s.confirm->call.name, s.confirm->call.args, false, "Declined by the user");
+ s.send(link::AiLinkSession::declinedReply(s.confirm->call.id, s.confirm->call.name));
+ s.confirm.reset();
+ status_ = tr("AI step declined");
+ }
+ }
+
+ } // namespace sf
diff --cc src/cli/McpServer.cpp
index dc198c76,873decd4..92933b2b
--- a/src/cli/McpServer.cpp
+++ b/src/cli/McpServer.cpp
@@@ -197,11 -160,9 +197,13 @@@ std::string handleMcpMessage(const Comm
return errorReply(id, -32601, "Method not found: " + method).dump();
}
+ Json mcpToolList(const CommandRegistry& registry) { return toolList(registry)["tools"]; }
+
int runMcpServer(const CommandRegistry& registry, std::istream& in, std::ostream& out) {
+ if (std::string why; !policy::mcpAllowed(&why)) {
+ std::cerr << "sculptforge: " << why << "\n";
+ return 3;
+ }
Document doc;
// stdout is the protocol: library messages go to stderr.
for (const auto& message : loadBrushLibrary(doc)) std::cerr << "sculptforge: " << message << "\n";
diff --cc src/cli/main.cpp
index eec09923,74d32d57..fe035a8f
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@@ -5,15 -5,12 +5,16 @@@
// pipelines and AI agents.
#include "ai/AiCommands.h"
#include "ai/AiPolicy.h"
+#include "ai/Oidc.h"
+#include "ai/Secrets.h"
#include "ai/SplatTrainer.h"
+ #include "cli/McpAttach.h"
#include "cli/McpServer.h"
#include "core/Benchmark.h"
+#include "core/AuditLog.h"
#include "core/BrushLibrary.h"
#include "core/Commands.h"
+#include "core/ManagedPolicy.h"
#include "core/Pack.h"
#include "core/Script.h"
#include "core/StudioProfile.h"
@@@ -141,35 -129,10 +143,38 @@@ int main(int argc, char** argv)
std::printf(" %s%s %s\n", p.name.c_str(), p.required ? " (required)" : "", p.description.c_str());
}
return 0;
+ } else if (a == "--policy") {
+ const sf::policy::Policy& p = sf::policy::current();
+ std::printf("%s\n", p.present ? ("Policy " + p.source + "\n" + sf::policy::describe(p)).c_str()
+ : ("No policy (" + sf::policy::systemPolicyPath() + " or SF_POLICY): nothing is managed").c_str());
+ return p.broken ? 2 : 0;
+ } else if (a == "--audit-log") {
+ std::printf("%s\n", sf::audit::logPath().c_str());
+ return 0;
+ } else if (a == "--sign-in") {
+ std::string err;
+ const bool ok = sf::ai::oidc::signIn(
+ [](const sf::ai::oidc::DeviceCode& c) {
+ std::fprintf(stderr, "To sign in, open %s and enter the code %s\n",
+ c.verificationUri.c_str(), c.userCode.c_str());
+ if (!c.verificationUriComplete.empty()) std::fprintf(stderr, "(or open %s)\n", c.verificationUriComplete.c_str());
+ return true;
+ },
+ {}, err);
+ if (!ok) {
+ std::fprintf(stderr, "error: %s\n", err.c_str());
+ return 1;
+ }
+ std::printf("Signed in as %s\n", sf::ai::oidc::signedInAs().c_str());
+ return 0;
+ } else if (a == "--sign-out") {
+ sf::ai::oidc::signOut();
+ std::puts("Signed out");
+ return 0;
} else if (a == "--mcp") {
+ // --attach: drive the open app (live mode, cli/McpAttach.h) instead of a scene of our own.
+ for (int j = i + 1; j < argc; ++j)
+ if (std::string(argv[j]) == "--attach") return sf::runMcpAttach(std::cin, std::cout);
return sf::runMcpServer(registry, std::cin, std::cout);
} else if (a == "--schema") {
std::puts(registry.toolSchemaJson().c_str());
diff --cc src/core/ManagedPolicy.cpp
index cb214604,00000000..640ce690
mode 100644,000000..100644
--- a/src/core/ManagedPolicy.cpp
+++ b/src/core/ManagedPolicy.cpp
@@@ -1,421 -1,0 +1,425 @@@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/ManagedPolicy.h"
+
+#include "core/Json.h"
+#include "core/NetworkPolicy.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdlib>
+#include <ctime>
+#include <fstream>
+#include <iterator>
+#include <mutex>
+#include <sstream>
+
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#define NOMINMAX
+#include <windows.h>
+#else
+#include <sys/stat.h>
+#include <unistd.h>
+#endif
+
+namespace sf::policy {
+
+namespace {
+
+Policy gPolicy;
+std::once_flag gOnce;
+
+bool isUrl(const std::string& s) { return s.rfind("https://", 0) == 0 || s.rfind("http://", 0) == 0; }
+
+bool contains(const std::vector<std::string>& v, std::string_view s) { return std::find(v.begin(), v.end(), s) != v.end(); }
+
+bool checkKeys(const Json& j, std::initializer_list<const char*> keys, const std::string& where, std::string& error) {
+ if (!j.isObject()) return (error = where + " must be an object", false);
+ for (const auto& [k, v] : j.members()) {
+ bool known = false;
+ for (const char* key : keys) known = known || k == key;
+ if (!known) return (error = "unknown key \"" + (where.empty() ? k : where + "." + k) + "\"", false);
+ }
+ return true;
+}
+
+bool readLock(const Json& j, const char* key, Lock& out, const std::string& where, std::string& error) {
+ if (!j.has(key)) return true;
+ if (!j[key].isBool()) return (error = where + "." + key + " must be true or false", false);
+ out = j[key].asBool() ? Lock::On : Lock::Off;
+ return true;
+}
+
+bool readStrings(const Json& j, const char* key, std::vector<std::string>& out, const std::string& where,
+ std::string& error) {
+ if (!j.has(key)) return true;
+ if (!j[key].isArray()) return (error = where + "." + key + " must be a list of strings", false);
+ for (const Json& v : j[key].items()) {
+ if (!v.isString() || v.asString().empty()) return (error = where + "." + key + " must be a list of strings", false);
+ out.push_back(v.asString());
+ }
+ return true;
+}
+
+// http(s) URL prefixes with no user info. Plain http only to this computer (a local model server, the mock IdP).
+bool readUrls(const Json& j, const char* key, std::vector<std::string>& out, const std::string& where, std::string& error,
+ bool httpsOnly = false) {
+ if (!readStrings(j, key, out, where, error)) return false;
+ for (const std::string& u : out) {
+ net::UrlParts p;
+ if (!isUrl(u) || !net::parseUrl(u, p)) return (error = where + "." + key + ": \"" + u + "\" is not an http(s) URL", false);
+ if (httpsOnly && p.scheme != "https" && !net::isLoopbackAddress(p.host))
+ return (error = where + "." + key + ": \"" + u + "\" must be https", false);
+ }
+ return true;
+}
+
+std::string envOr(const char* a, const char* b = nullptr) {
+ if (const char* v = std::getenv(a); v && *v) return v;
+ if (b)
+ if (const char* v = std::getenv(b); v && *v) return v;
+ return {};
+}
+
+// Path-safe: letters, digits, '.', '-', '_' (a user or host name that would climb out of the folder can't).
+std::string safePart(std::string s) {
+ for (char& c : s)
+ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_'))
+ c = '_';
+ if (s.empty() || s == "." || s == "..") s = "unknown";
+ return s;
+}
+
+std::string hostName() {
+#if defined(_WIN32)
+ char buf[256];
+ DWORD n = sizeof buf;
+ if (GetComputerNameA(buf, &n)) return std::string(buf, n);
+ return envOr("COMPUTERNAME");
+#else
+ char buf[256] = {};
+ if (gethostname(buf, sizeof buf - 1) == 0) return buf;
+ return {};
+#endif
+}
+
+void replaceAll(std::string& s, const std::string& from, const std::string& to) {
+ for (size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) s.replace(at, from.size(), to);
+}
+
+Policy failClosed(const std::string& source, const std::string& error) {
+ Policy p;
+ p.present = true;
+ p.broken = true;
+ p.source = source;
+ p.error = error;
+ p.ai = Lock::Off;
+ p.network = Lock::Off;
+ p.mcp = Lock::Off;
+ p.mcpLiveAllowed = false;
+ p.updateCheck = Lock::Off;
+ return p;
+}
+
+} // namespace
+
+const std::vector<std::string>& mcpCategoryNames() {
+ static const std::vector<std::string> names = {"info", "edit", "files", "scripts", "network", "ai"};
+ return names;
+}
+
+const std::vector<std::string>& aiProviderIds() {
+ static const std::vector<std::string> ids = {
+ // Brush Lab (ai/Providers.h)
+ "free", "anthropic", "openai", "ollama", "lmstudio", "vllm", "llamacpp", "litellm", "openrouter", "openai-compatible",
+ // Generate 3D (ai/ImageTo3DService.h)
+ "huggingface", "fal", "meshy", "comfyui", "command"};
+ return ids;
+}
+
+bool parsePolicy(const std::string& text, const std::string& source, Policy& out, std::string& error) {
+ Json j;
+ if (!Json::parseStrict(text, j, error)) return false;
+ if (!checkKeys(j, {"format", "version", "organization", "ai", "network", "mcp", "audit", "signIn", "telemetry", "updates"},
+ "", error))
+ return false;
+ if (j["format"].asString() != kPolicyFormat) return (error = "format must be \"sculptforge-policy\"", false);
+ if (!j["version"].isNumber() || int(j["version"].asNumber()) != kPolicyVersion) return (error = "unsupported version (1 is current)", false);
+ Policy p;
+ p.present = true;
+ p.source = source;
+ p.organization = j["organization"].asString();
+ if (p.organization.size() > 80) return (error = "organization: at most 80 characters", false);
+
+ if (j.has("ai")) {
+ const Json& a = j["ai"];
+ if (!checkKeys(a, {"enabled", "providers", "endpoints", "requireSignIn"}, "ai", error)) return false;
+ if (!readLock(a, "enabled", p.ai, "ai", error) || !readStrings(a, "providers", p.aiProviders, "ai", error) ||
+ !readUrls(a, "endpoints", p.aiEndpoints, "ai", error))
+ return false;
+ for (const std::string& id : p.aiProviders)
+ if (!contains(aiProviderIds(), id)) return (error = "ai.providers: unknown provider \"" + id + "\"", false);
+ if (a.has("requireSignIn") && !a["requireSignIn"].isBool()) return (error = "ai.requireSignIn must be true or false", false);
+ p.requireSignIn = a["requireSignIn"].asBool(false);
+ }
+ if (j.has("network")) {
+ const Json& n = j["network"];
+ if (!checkKeys(n, {"enabled", "allow", "localNetwork"}, "network", error)) return false;
+ if (!readLock(n, "enabled", p.network, "network", error) || !readUrls(n, "allow", p.networkAllow, "network", error))
+ return false;
+ if (n.has("localNetwork") && !n["localNetwork"].isBool()) return (error = "network.localNetwork must be true or false", false);
+ p.localNetwork = n["localNetwork"].asBool(false);
+ }
+ if (j.has("mcp")) {
+ const Json& m = j["mcp"];
+ if (!checkKeys(m, {"enabled", "live", "categories"}, "mcp", error)) return false;
+ if (!readLock(m, "enabled", p.mcp, "mcp", error) || !readStrings(m, "categories", p.mcpCategories, "mcp", error))
+ return false;
+ for (const std::string& c : p.mcpCategories)
+ if (!contains(mcpCategoryNames(), c)) return (error = "mcp.categories: unknown category \"" + c + "\"", false);
+ if (m.has("live")) {
+ const std::string live = m["live"].asString();
+ if (live != "never" && live != "allowed") return (error = "mcp.live must be \"never\" or \"allowed\"", false);
+ p.mcpLiveAllowed = live == "allowed";
+ }
+ if (p.mcp == Lock::Off) p.mcpLiveAllowed = false;
+ }
+ if (j.has("audit")) {
+ const Json& a = j["audit"];
+ if (!checkKeys(a, {"path", "maxMB", "keep", "required"}, "audit", error)) return false;
+ if (a.has("path") && (!a["path"].isString() || a["path"].asString().empty()))
+ return (error = "audit.path must be a file path", false);
+ p.auditPath = a["path"].asString();
+ if (a.has("maxMB")) {
+ if (!a["maxMB"].isNumber() || a["maxMB"].asNumber() < 0.1 || a["maxMB"].asNumber() > 4096)
+ return (error = "audit.maxMB: 0.1 to 4096", false);
+ p.auditMaxMB = a["maxMB"].asNumber();
+ }
+ if (a.has("keep")) {
+ if (!a["keep"].isNumber() || a["keep"].asNumber() < 0 || a["keep"].asNumber() > 1000)
+ return (error = "audit.keep: 0 to 1000 old files", false);
+ p.auditKeep = int(a["keep"].asNumber());
+ }
+ if (a.has("required") && !a["required"].isBool()) return (error = "audit.required must be true or false", false);
+ p.auditRequired = a["required"].asBool(false);
+ }
+ if (j.has("signIn")) {
+ const Json& s = j["signIn"];
+ if (!checkKeys(s, {"issuer", "clientId", "clientSecret", "scopes", "audience", "useFor"}, "signIn", error)) return false;
+ p.issuer = s["issuer"].asString();
+ p.clientId = s["clientId"].asString();
+ p.audience = s["audience"].asString();
+ p.clientSecret = s["clientSecret"].asString();
+ net::UrlParts u;
+ if (!isUrl(p.issuer) || !net::parseUrl(p.issuer, u) || (u.scheme != "https" && !net::isLoopbackAddress(u.host)))
+ return (error = "signIn.issuer must be the identity provider's https URL", false);
+ if (p.clientId.empty() || p.clientId.size() > 256) return (error = "signIn.clientId: the app's client id", false);
+ if (!readStrings(s, "scopes", p.scopes, "signIn", error) || !readUrls(s, "useFor", p.signInUseFor, "signIn", error, true))
+ return false;
+ for (const std::string& sc : p.scopes)
+ if (sc.find_first_of(" \t\r\n\"") != std::string::npos) return (error = "signIn.scopes: one scope per entry", false);
+ }
+ if (p.requireSignIn && !p.signInConfigured()) return (error = "ai.requireSignIn needs signIn.issuer and signIn.clientId", false);
+ if (j.has("telemetry")) {
+ // SculptForge has no telemetry. The key exists so an IT checklist can state it; anything but "none" is a mistake.
+ const Json& t = j["telemetry"];
+ if (!((t.isString() && (t.asString() == "none" || t.asString() == "off")) || (t.isBool() && !t.asBool())))
+ return (error = "telemetry: SculptForge has no telemetry; the only value is \"none\"", false);
+ }
+ if (j.has("updates")) {
+ const Json& u = j["updates"];
+ if (!checkKeys(u, {"check", "channel", "feed", "mirror"}, "updates", error)) return false;
+ if (!readLock(u, "check", p.updateCheck, "updates", error)) return false;
+ p.updateChannel = u["channel"].asString();
+ if (u.has("channel") && p.updateChannel != "stable" && p.updateChannel != "preview")
+ return (error = "updates.channel must be \"stable\" or \"preview\"", false);
+ p.updateFeed = u["feed"].asString();
+ p.updateMirror = u["mirror"].asString();
+ net::UrlParts parts;
+ if (!p.updateFeed.empty() && (!isUrl(p.updateFeed) || !net::parseUrl(p.updateFeed, parts)))
+ return (error = "updates.feed must be an http(s) URL", false);
+ if (!p.updateMirror.empty() && isUrl(p.updateMirror) && !net::parseUrl(p.updateMirror, parts))
+ return (error = "updates.mirror must be an http(s) URL or a file", false);
+ }
+ out = std::move(p);
+ return true;
+}
+
+std::string systemPolicyPath() {
+#if defined(_WIN32)
+ const std::string base = envOr("ProgramData", "ALLUSERSPROFILE");
+ return (base.empty() ? std::string("C:\\ProgramData") : base) + "\\SculptForge\\policy.json";
+#elif defined(__APPLE__)
+ return "/Library/Application Support/SculptForge/policy.json";
+#else
+ return "/etc/sculptforge/policy.json";
+#endif
+}
+
+Policy loadPolicyFile(const std::string& path, const std::string& origin, std::vector<std::string>* messages) {
+ std::ifstream f(path, std::ios::binary);
+ if (!f) {
+ if (messages) messages->push_back("Policy " + origin + " can't be read: AI, network features and MCP are off");
+ return failClosed(origin, "can't be read");
+ }
+ const std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ std::string error;
+ Policy p;
+ if (text.size() > (1u << 20)) error = "larger than 1 MB";
+ else if (parsePolicy(text, origin, p, error)) {
+#if !defined(_WIN32)
+ // A system policy anyone can edit locks nothing: say so (it still applies).
+ struct stat st{};
+ if (stat(path.c_str(), &st) == 0 && (st.st_mode & 0022) && messages)
+ messages->push_back("Policy " + path + " is writable by other users: make it writable by administrators only");
+#endif
+ return p; // (describe() says what it locks: sculptforge-cli --policy, Preferences > AI)
+ }
+ if (messages) messages->push_back("Policy " + origin + ": " + error + ". AI, network features and MCP are off until it is fixed");
+ return failClosed(origin, error);
+}
+
+const Policy& startPolicy(std::vector<std::string>* messages) {
+ std::call_once(gOnce, [messages] {
+ const std::string system = systemPolicyPath();
+ const std::string env = envOr("SF_POLICY");
+ if (std::ifstream(system, std::ios::binary)) {
+ if (!env.empty() && messages) messages->push_back("Policy: SF_POLICY is ignored while " + system + " is installed");
+ gPolicy = loadPolicyFile(system, system, messages);
+ } else if (!env.empty()) {
+ gPolicy = loadPolicyFile(env, "SF_POLICY=" + env, messages);
+ }
+ });
+ return gPolicy;
+}
+
+const Policy& current() { return gPolicy; }
+
+void setPolicyForTests(const Policy& p) { gPolicy = p; }
+void resetPolicyForTests() { gPolicy = Policy{}; }
+
+std::string managedBy() {
+ return gPolicy.organization.empty() ? std::string(kManagedLabel) : "Managed by " + gPolicy.organization;
+}
+
+bool aiProviderAllowed(std::string_view providerId, std::string* why) {
+ if (gPolicy.ai == Lock::Off) {
+ if (why) *why = "AI features are turned off by your studio's policy";
+ return false;
+ }
+ if (gPolicy.aiProviders.empty() || contains(gPolicy.aiProviders, providerId)) return true;
+ if (why) *why = "Your studio's policy doesn't allow this AI provider (" + std::string(providerId) + ")";
+ return false;
+}
+
+bool aiEndpointAllowed(const std::string& url, std::string* why) {
+ if (gPolicy.ai == Lock::Off) {
+ if (why) *why = "AI features are turned off by your studio's policy";
+ return false;
+ }
+ if (gPolicy.aiEndpoints.empty()) return true;
+ for (const std::string& prefix : gPolicy.aiEndpoints)
+ if (net::urlUnderPrefix(url, prefix)) return true;
+ if (why) *why = "Your studio's policy doesn't allow AI requests to this address";
+ return false;
+}
+
+bool mcpAllowed(std::string* why) {
+ if (gPolicy.mcp != Lock::Off) return true;
+ if (why) *why = "AI tools (MCP) are turned off by your studio's policy";
+ return false;
+}
+
+bool mcpLiveAllowed(std::string* why) {
+ if (gPolicy.mcp != Lock::Off && gPolicy.mcpLiveAllowed) return true;
+ if (why) *why = "Your studio's policy doesn't let AI tools control the app window";
+ return false;
+}
+
+std::vector<std::string> mcpCategories(std::string_view name, const std::vector<std::string>& paramNames) {
+ static const char* kNetwork[] = {"brush_gallery_search", "brush_gallery_install", "unreal_editors", "unreal_send",
+ "export_unreal"};
+ static const char* kScripts[] = {"macro_run", "run_script", "python"};
+ static const char* kBridges[] = {"goz_send", "blender_send", "blender_receive", "maya_send", "maya_receive"};
+ static const char* kAi[] = {"brush_ai", "image_to_3d", "text_to_3d", "comfyui_check"};
+ auto in = [&](const auto& list) {
+ for (const char* n : list)
+ if (name == n) return true;
+ return false;
+ };
+ std::vector<std::string> c;
+ if (in(kAi)) c.push_back("ai"), c.push_back("network");
+ if (in(kNetwork)) c.push_back("network");
+ if (in(kScripts)) c.push_back("scripts");
+ bool files = in(kBridges);
- for (const std::string& p : paramNames) files = files || p == "path" || p == "folder" || p == "file";
++ for (const std::string& p : paramNames) // (link/AiLinkSession.cpp isPathParam: the same names)
++ files = files || p == "path" || p == "file" || p == "folder" || p == "out" || p == "dir" || p == "directory" ||
++ p == "output";
+ if (files) c.push_back("files");
- const bool info = name == "mesh_info" || name.ends_with("_info") || name.ends_with("_list") || name == "brush_library";
++ // Looking (the viewport as an image, the camera) reads the scene; stroke_screen edits it.
++ const bool info = name == "mesh_info" || name.ends_with("_info") || name.ends_with("_list") || name == "brush_library" ||
++ name == "viewport_image" || name == "view_turntable" || name == "view_set";
+ if (c.empty()) c.push_back(info ? "info" : "edit");
+ return c;
+}
+
+bool mcpToolAllowed(std::string_view name, const std::vector<std::string>& paramNames, std::string* why) {
+ if (!mcpAllowed(why)) return false;
+ if (gPolicy.mcpCategories.empty()) return true;
+ for (const std::string& c : mcpCategories(name, paramNames))
+ if (!contains(gPolicy.mcpCategories, c)) {
+ if (why) *why = "Your studio's policy doesn't allow AI tools to use " + std::string(name) + " (" + c + ")";
+ return false;
+ }
+ return true;
+}
+
+std::string describe(const Policy& p) {
+ if (!p.present) return "no policy: nothing is managed";
+ if (p.broken) return "broken (" + p.error + "): AI, network features and MCP are off";
+ std::ostringstream o;
+ auto lock = [](Lock l) { return l == Lock::Off ? "off" : l == Lock::On ? "on" : "artist's choice"; };
+ auto list = [](const std::vector<std::string>& v, const char* none) {
+ if (v.empty()) return std::string(none);
+ std::string s;
+ for (const std::string& x : v) s += (s.empty() ? "" : ", ") + x;
+ return s;
+ };
+ if (!p.organization.empty()) o << p.organization << ": ";
+ o << "AI " << lock(p.ai);
+ if (p.ai != Lock::Off) {
+ o << " (providers: " << list(p.aiProviders, "any") << "; endpoints: " << list(p.aiEndpoints, "any");
+ if (p.requireSignIn) o << "; sign-in required";
+ o << ")";
+ }
+ o << "; network " << (p.network == Lock::Off ? "off (allowed: " + list(p.networkAllow, "nothing") + ")" : "on");
+ o << "; MCP " << (p.mcp == Lock::Off ? "off" : "on (tools: " + list(p.mcpCategories, "all") + "; live mode " +
+ (p.mcpLiveAllowed ? "allowed" : "never") + ")");
+ o << "; audit log " << (p.auditPath.empty() ? "default path" : p.auditPath) << (p.auditRequired ? " (required)" : "");
+ if (p.signInConfigured()) o << "; sign-in " << p.issuer;
+ o << "; telemetry none (SculptForge has none)";
+ o << "; updates " << (p.updateCheck == Lock::Off ? "off" : p.updateChannel.empty() ? "artist's choice" : p.updateChannel);
+ if (!p.updateFeed.empty()) o << " from " << p.updateFeed;
+ return o.str();
+}
+
+std::string expandPathTemplate(const std::string& path) {
+ std::string out = path;
+ if (out.find('{') == std::string::npos) return out;
+ const std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
+ std::tm tm{};
+#if defined(_WIN32)
+ gmtime_s(&tm, &t);
+#else
+ gmtime_r(&t, &tm);
+#endif
+ char date[16];
+ std::strftime(date, sizeof date, "%Y-%m-%d", &tm);
+ replaceAll(out, "{user}", safePart(envOr("USER", "USERNAME")));
+ replaceAll(out, "{host}", safePart(hostName()));
+ replaceAll(out, "{date}", date);
+ return out;
+}
+
+} // namespace sf::policy
diff --cc tests/test_studio_policy.cpp
index 3bc4004b,00000000..5c064e5b
mode 100644,000000..100644
--- a/tests/test_studio_policy.cpp
+++ b/tests/test_studio_policy.cpp
@@@ -1,532 -1,0 +1,534 @@@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Studio controls (docs/guide/studios.md "IT deployment"): the managed policy file (core/ManagedPolicy.h), the AI
+// audit log (core/AuditLog.h), provider presets and keys in the keychain (ai/Providers.h, ai/Secrets.h) and the
+// studio sign-in against a mock identity provider (ai/Oidc.h).
+#include "TestHarness.h"
+
+#include "ai/AiCommands.h"
+#include "ai/AiPolicy.h"
+#include "ai/Http.h"
+#include "ai/Oidc.h"
+#include "ai/Providers.h"
+#include "ai/Secrets.h"
+#include "cli/McpServer.h"
+#include "core/AuditLog.h"
+#include "core/Keychain.h"
+#include "core/ManagedPolicy.h"
+#include "core/StudioProfile.h"
+
+#include <filesystem>
+#include <fstream>
+#include <set>
+#include <sstream>
+
+using namespace sf;
+namespace fs = std::filesystem;
+
+namespace {
+
+std::string tempDir(const char* name) {
+ const fs::path d = fs::temp_directory_path() / (std::string("sf_studio_") + name);
+ std::error_code ec;
+ fs::remove_all(d, ec);
+ fs::create_directories(d, ec);
+ return d.string();
+}
+
+std::string readFile(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ std::stringstream ss;
+ ss << f.rdbuf();
+ return ss.str();
+}
+
+std::vector<std::string> lines(const std::string& text) {
+ std::vector<std::string> out;
+ std::stringstream ss(text);
+ for (std::string l; std::getline(ss, l);)
+ if (!l.empty()) out.push_back(l);
+ return out;
+}
+
+policy::Policy parsed(const std::string& text) {
+ policy::Policy p;
+ std::string error;
+ CHECK(policy::parsePolicy(text, "test", p, error));
+ if (!error.empty()) std::printf(" policy error: %s\n", error.c_str());
+ return p;
+}
+
+std::string parseError(const std::string& text) {
+ policy::Policy p;
+ std::string error;
+ CHECK(!policy::parsePolicy(text, "test", p, error));
+ return error;
+}
+
+// The policy, the audit log path, the keychain and the AI switch back as they were, whatever a test did.
+struct StudioState {
+ std::string auditDir;
+ explicit StudioState(const char* name) : auditDir(tempDir(name)) {
+ policy::resetPolicyForTests();
+ audit::setPathForTests(auditDir + "/audit.jsonl");
+ keychain::useMemoryForTests(true);
+ ai::secrets::clearCacheForTests();
+ ai::setAiEnabled(true);
+ }
+ ~StudioState() {
+ policy::resetPolicyForTests();
+ audit::setPathForTests({});
+ audit::setClient("app");
+ ai::secrets::clearCacheForTests();
+ ai::oidc::setTransportForTests({});
+ ai::oidc::setSleepForTests({});
+ ai::oidc::setClockForTests({});
+ ai::setAiEnabled(true);
+ }
+ std::string auditPath() const { return auditDir + "/audit.jsonl"; }
+};
+
+constexpr const char* kFullPolicy = R"({
+ "format": "sculptforge-policy", "version": 1,
+ "organization": "Acme Animation",
+ "ai": {"enabled": true, "providers": ["litellm", "comfyui"], "endpoints": ["https://llm.acme.internal/"], "requireSignIn": true},
+ "network": {"enabled": false, "allow": ["https://sw.acme.internal/"], "localNetwork": true},
+ "mcp": {"enabled": true, "live": "never", "categories": ["info", "edit"]},
+ "audit": {"path": "/mnt/audit/{user}@{host}.jsonl", "maxMB": 20, "keep": 10, "required": true},
+ "signIn": {"issuer": "https://acme.okta.com/oauth2/default", "clientId": "0oa1abc", "scopes": ["openid", "email"],
+ "useFor": ["https://llm.acme.internal/"]},
+ "telemetry": "none",
+ "updates": {"check": true, "channel": "stable", "feed": "https://sw.acme.internal/sculptforge/latest.json"}
+})";
+
+} // namespace
+
+TEST(studio_policy_parses_every_key) {
+ const policy::Policy p = parsed(kFullPolicy);
+ CHECK(p.present && !p.broken && p.organization == "Acme Animation");
+ CHECK(p.ai == policy::Lock::On && p.aiProviders.size() == 2 && p.aiEndpoints.size() == 1 && p.requireSignIn);
+ CHECK(p.network == policy::Lock::Off && p.networkAllow.size() == 1 && p.localNetwork);
+ CHECK(p.mcp == policy::Lock::On && !p.mcpLiveAllowed && p.mcpCategories.size() == 2);
+ CHECK(p.auditPath == "/mnt/audit/{user}@{host}.jsonl" && p.auditMaxMB == 20 && p.auditKeep == 10 && p.auditRequired);
+ CHECK(p.signInConfigured() && p.clientId == "0oa1abc" && p.scopes.size() == 2 && p.signInUseFor.size() == 1);
+ CHECK(p.updateCheck == policy::Lock::On && p.updateChannel == "stable" && !p.updateFeed.empty());
+ // Everything is optional: the smallest policy manages nothing.
+ const policy::Policy empty = parsed(R"({"format": "sculptforge-policy", "version": 1})");
+ CHECK(empty.ai == policy::Lock::Unset && empty.network == policy::Lock::Unset && empty.mcpLiveAllowed);
+ CHECK(policy::describe(p).find("telemetry none") != std::string::npos);
+}
+
+TEST(studio_policy_rejects_mistakes) {
+ // A typo never quietly drops a lock.
+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "AI": {}})").find("unknown key") != std::string::npos);
+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enable": false}})").find("ai.enable") !=
+ std::string::npos);
+ CHECK(!parseError(R"({"format": "sculptforge-studio", "version": 1})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 2})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": "no"}})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"providers": ["skynet"]}})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"endpoints": ["ftp://x/"]}})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"categories": ["everything"]}})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"live": "sometimes"}})").empty());
+ // There is no telemetry to turn on.
+ CHECK(parseError(R"({"format": "sculptforge-policy", "version": 1, "telemetry": true})").find("no telemetry") !=
+ std::string::npos);
+ CHECK(parsed(R"({"format": "sculptforge-policy", "version": 1, "telemetry": false})").present);
+ // Sign-in required needs an identity provider; the issuer must be https.
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "ai": {"requireSignIn": true}})").empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "signIn": {"issuer": "http://idp.acme.com", "clientId": "x"}})")
+ .empty());
+ CHECK(!parseError(R"({"format": "sculptforge-policy", "version": 1, "updates": {"channel": "nightly"}})").empty());
+ CHECK(!parseError("not json").empty());
+}
+
+TEST(studio_policy_fails_closed) {
+ const std::string dir = tempDir("failclosed");
+ std::ofstream(dir + "/policy.json") << R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabeld": true}})";
+ std::vector<std::string> messages;
+ const policy::Policy broken = policy::loadPolicyFile(dir + "/policy.json", "test", &messages);
+ CHECK(broken.present && broken.broken && !messages.empty());
+ CHECK(broken.ai == policy::Lock::Off && broken.network == policy::Lock::Off && broken.mcp == policy::Lock::Off);
+ CHECK(!broken.mcpLiveAllowed && broken.updateCheck == policy::Lock::Off);
+ const policy::Policy missing = policy::loadPolicyFile(dir + "/none.json", "test");
+ CHECK(missing.broken && missing.ai == policy::Lock::Off);
+ std::ofstream(dir + "/good.json") << kFullPolicy;
+ CHECK(!policy::loadPolicyFile(dir + "/good.json", "test").broken);
+}
+
+TEST(studio_policy_locks_the_ai_switch) {
+ StudioState state("ai_switch");
+ CHECK(!ai::aiManaged());
+ policy::Policy off = parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": false}})");
+ policy::setPolicyForTests(off);
+ CHECK(ai::aiManaged() && ai::aiPolicyLocked() && !ai::aiFeaturesAllowed(true));
+ CHECK(ai::aiOffError().find("studio") != std::string::npos);
+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"enabled": true}})"));
+ CHECK(ai::aiManaged() && ai::aiPolicyLocked() && ai::aiFeaturesAllowed(false));
+ policy::resetPolicyForTests();
+ CHECK(!ai::aiFeaturesAllowed(false) && ai::aiFeaturesAllowed(true));
+}
+
+TEST(studio_policy_gates_ai_providers_and_endpoints) {
+ StudioState state("gate");
+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1,
+ "ai": {"providers": ["litellm", "ollama"], "endpoints": ["https://llm.acme.internal/v1/", "http://localhost:11434/"]}})"));
+ std::string error;
+ CHECK(ai::aiRequestAllowed("litellm", "https://llm.acme.internal/v1/chat/completions", error));
+ CHECK(!ai::aiRequestAllowed("anthropic", "https://llm.acme.internal/v1/chat/completions", error) &&
+ error.find("provider") != std::string::npos);
+ CHECK(!ai::aiRequestAllowed("litellm", "https://llm.acme.internal.evil.com/v1/chat", error));
+ CHECK(!ai::aiRequestAllowed("litellm", "https://llm.acme.internal/v10/chat", error)); // a '/' boundary
+ // Nothing is sent for a refused request: Brush Lab with the free tier, Generate 3D with Hugging Face.
+ const uint64_t before = ai::httpRequestCount();
+ ai::AiSettings free = ai::AiSettings::defaults(ai::AiSettings::Provider::Free);
+ ai::ChatMessage m{ai::ChatMessage::Role::User, "a clay brush", "a clay brush"};
+ const ai::BrushSuggestion s = ai::requestBrush(free, {m}, nullptr);
+ CHECK(!s.ok && s.error.find("policy") != std::string::npos);
+ ai::AiSettings anthropic = ai::withPreset(free, "anthropic");
+ anthropic.apiKey = "sk-test";
+ CHECK(!ai::requestBrush(anthropic, {m}, nullptr).ok);
+ CHECK(ai::httpRequestCount() == before);
+ // Sign-in required: refused until signed in.
+ policy::Policy signIn = parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"requireSignIn": true},
+ "signIn": {"issuer": "https://idp.acme.test", "clientId": "sf"}})");
+ policy::setPolicyForTests(signIn);
+ ai::oidc::setTransportForTests({}); // (starts signed out)
+ CHECK(!ai::aiRequestAllowed("free", "https://text.pollinations.ai/openai", error) && error.find("Sign in") != std::string::npos);
+}
+
+TEST(studio_policy_mcp_categories) {
+ StudioState state("mcp_categories");
+ CHECK(policy::mcpCategories("mesh_info", {}) == std::vector<std::string>{"info"});
++ CHECK(policy::mcpCategories("viewport_image", {}) == std::vector<std::string>{"info"});
++ CHECK(policy::mcpCategories("stroke_screen", {"points"}) == std::vector<std::string>{"edit"});
+ CHECK(policy::mcpCategories("remesh", {"resolution"}) == std::vector<std::string>{"edit"});
+ CHECK(policy::mcpCategories("export_glb", {"path"}) == std::vector<std::string>{"files"});
+ CHECK(policy::mcpCategories("macro_run", {"name"}) == std::vector<std::string>{"scripts"});
+ const auto ai = policy::mcpCategories("image_to_3d", {"path"});
+ CHECK(std::set<std::string>(ai.begin(), ai.end()) == std::set<std::string>({"ai", "network", "files"}));
+ for (const auto& c : {"info", "edit", "files", "scripts", "network", "ai"})
+ CHECK(std::find(policy::mcpCategoryNames().begin(), policy::mcpCategoryNames().end(), c) != policy::mcpCategoryNames().end());
+
+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"categories": ["info", "edit"]}})"));
+ CommandRegistry registry;
+ Document doc;
+ // tools/list leaves out what the policy doesn't allow.
+ Json list;
+ std::string err;
+ CHECK(Json::parse(handleMcpMessage(registry, doc, R"({"jsonrpc":"2.0","id":1,"method":"tools/list"})"), list, err));
+ std::set<std::string> names;
+ for (const auto& t : list["result"]["tools"].items()) names.insert(t["name"].asString());
+ CHECK(names.count("new_sphere") && names.count("mesh_info") && !names.count("export_glb") && !names.count("open"));
+ // tools/call refuses it, says why, and the refusal is in the audit log.
+ Json call;
+ CHECK(Json::parse(handleMcpMessage(registry, doc,
+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"export_glb","arguments":{"path":"/tmp/x.glb"}}})"),
+ call, err));
+ CHECK(call["result"]["isError"].asBool() && call["result"]["content"][0]["text"].asString().find("policy") != std::string::npos);
+ CHECK(readFile(state.auditPath()).find("\"export_glb\"") != std::string::npos);
+ // MCP off: the server doesn't start.
+ policy::setPolicyForTests(parsed(R"({"format": "sculptforge-policy", "version": 1, "mcp": {"enabled": false}})"));
+ std::istringstream in(R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}})");
+ std::ostringstream out;
+ CHECK(runMcpServer(registry, in, out) == 3 && out.str().empty());
+ CHECK(!policy::mcpLiveAllowed());
+ policy::resetPolicyForTests();
+ CHECK(policy::mcpLiveAllowed() && policy::mcpToolAllowed("export_glb", {"path"}));
+}
+
+TEST(studio_audit_log_records_mcp_calls) {
+ StudioState state("audit_mcp");
+ CommandRegistry registry;
+ Document doc;
+ handleMcpMessage(registry, doc,
+ R"({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"claude-code","version":"2.1.0"}}})");
+ handleMcpMessage(registry, doc,
+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"new_sphere","arguments":{"subdivisions":3}}})");
+ handleMcpMessage(registry, doc,
+ R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"brush_install","arguments":{"code":"SFB1-0123456789abcdef","api_key":"sk-secret"}}})");
+ const auto l = lines(readFile(state.auditPath()));
+ CHECK(l.size() == 2);
+ Json first, second;
+ std::string err;
+ CHECK(Json::parse(l[0], first, err) && Json::parse(l[1], second, err));
+ CHECK(first["client"].asString() == "mcp:claude-code 2.1.0" && first["tool"].asString() == "mcp");
+ CHECK(first["command"].asString() == "new_sphere" && first["args"]["subdivisions"].asNumber() == 3);
+ CHECK(first["result"].asString() == "ok" && first["time"].asString().size() == 24 && first["ms"].isNumber());
+ CHECK(!first["user"].isNull() && !first["host"].asString().empty());
+ // Secrets and artwork never reach the log.
+ CHECK(second["args"]["api_key"].asString() == "<redacted>");
+ CHECK(second["args"]["code"].asString().find("bytes") != std::string::npos);
+ CHECK(l[1].find("sk-secret") == std::string::npos && l[1].find("0123456789abcdef") == std::string::npos);
+}
+
+TEST(studio_audit_log_rotates_and_can_be_required) {
+ StudioState state("audit_rotate");
+ policy::Policy p = parsed(R"({"format": "sculptforge-policy", "version": 1, "audit": {"maxMB": 0.1, "keep": 2}})");
+ policy::setPolicyForTests(p);
+ audit::Entry e;
+ e.tool = "ai";
+ e.command = "brush_ai";
+ e.message = std::string(400, 'x');
+ for (int i = 0; i < 1200; ++i) CHECK(audit::record(e));
+ CHECK(fs::exists(state.auditPath()) && fs::exists(state.auditPath() + ".1") && fs::exists(state.auditPath() + ".2"));
+ CHECK(!fs::exists(state.auditPath() + ".3"));
+ CHECK(fs::file_size(state.auditPath()) <= uint64_t(0.1 * 1024 * 1024) + 1024);
+ // Required and unwritable: the AI tool's call is refused before it runs.
+ p.auditRequired = true;
+ policy::setPolicyForTests(p);
+ const std::string blocker = state.auditDir + "/file";
+ std::ofstream(blocker) << "x";
+ audit::setPathForTests(blocker + "/audit.jsonl"); // (a folder under a file can't exist)
+ CommandRegistry registry;
+ Document doc;
+ Json call;
+ std::string err;
+ CHECK(Json::parse(handleMcpMessage(registry, doc,
+ R"({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"new_sphere","arguments":{}}})"),
+ call, err));
+ CHECK(call["result"]["isError"].asBool() && call["result"]["content"][0]["text"].asString().find("audit log") != std::string::npos);
+ // The path template: user and host names can't climb out of the folder.
+ CHECK(policy::expandPathTemplate("/a/{user}/x").find("..") == std::string::npos);
+ CHECK(policy::expandPathTemplate("/a/b.jsonl") == "/a/b.jsonl");
+}
+
+TEST(studio_provider_presets) {
+ std::set<std::string> ids;
+ for (const ai::ProviderPreset& p : ai::providerPresets()) {
+ CHECK(ids.insert(p.id).second); // unique
+ // Every preset is one a studio's policy can name.
+ CHECK(std::find(policy::aiProviderIds().begin(), policy::aiProviderIds().end(), p.id) != policy::aiProviderIds().end());
+ CHECK(*p.label && *p.note);
+ }
+ for (const char* id : {"anthropic", "ollama", "lmstudio", "vllm", "llamacpp", "litellm", "openrouter"}) CHECK(ids.count(id));
+ ai::AiSettings s = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "litellm");
+ CHECK(s.provider == ai::AiSettings::Provider::OpenAICompatible && ai::providerId(s) == "litellm");
+ s.endpoint = "https://llm.acme.internal/v1/chat/completions"; // the studio's own address keeps the preset
+ CHECK(ai::providerId(ai::AiSettings::fromJson(s.toJson())) == "litellm");
+ // An ai.json from before presets: its endpoint names the server.
+ ai::AiSettings old = ai::AiSettings::defaults(ai::AiSettings::Provider::OpenAICompatible);
+ CHECK(ai::providerId(old) == "ollama");
+ old.endpoint = "http://gpu7:9000/v1/chat/completions";
+ CHECK(ai::providerId(old) == "openai-compatible");
+}
+
+TEST(studio_keys_live_in_the_keychain) {
+ StudioState state("keys");
+ ai::AiSettings s = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "openrouter");
+ s.apiKey = "sk-or-test";
+ s.hfToken = "hf_test";
+ s.falKey = "fal-test";
+ s.meshyKey = "msy-test";
+ const std::string json = s.toJson().dump();
+ for (const char* secret : {"sk-or-test", "hf_test", "fal-test", "msy-test"}) CHECK(json.find(secret) == std::string::npos);
+ CHECK(ai::secrets::storeKeys(s));
+ std::string v;
+ CHECK(keychain::load("ai/openrouter", v) && v == "sk-or-test");
+ CHECK(keychain::load(ai::secrets::kHuggingFace, v) && v == "hf_test");
+ // A fresh load gets them from the keychain.
+ ai::secrets::clearCacheForTests();
+ const ai::AiSettings loaded = ai::AiSettings::fromJson(s.toJson());
+ CHECK(loaded.apiKey.empty() && loaded.resolvedKey() == "sk-or-test" && loaded.resolvedHfToken() == "hf_test");
+ CHECK(loaded.resolvedFalKey() == "fal-test" && loaded.resolvedMeshyKey() == "msy-test");
+ // An older ai.json with keys in it: moved to the keychain, and out of the file.
+ keychain::useMemoryForTests(true);
+ ai::secrets::clearCacheForTests();
+ const std::string path = state.auditDir + "/ai.json";
+ Json legacy = s.toJson();
+ legacy.set("apiKey", "sk-or-old");
+ legacy.set("hfToken", "hf_old");
+ std::ofstream(path) << legacy.dump();
+ std::string message;
+ CHECK(ai::secrets::migrateLegacyKeys(path, message) && message.find("keychain") != std::string::npos);
+ const std::string after = readFile(path);
+ CHECK(after.find("sk-or-old") == std::string::npos && after.find("hf_old") == std::string::npos);
+ CHECK(keychain::load("ai/openrouter", v) && v == "sk-or-old");
+ CHECK(ai::AiSettings::load(path).resolvedHfToken() == "hf_old");
+ // Nothing to move: the file is left alone.
+ const auto stamp = fs::last_write_time(path);
+ CHECK(ai::secrets::migrateLegacyKeys(path, message) && message.empty() && fs::last_write_time(path) == stamp);
+}
+
+namespace {
+
+// A mock identity provider: discovery, device authorization and a token endpoint that answers "pending" a few
+// times, then "slow_down" once, then tokens. It records what it was sent.
+struct MockIdp {
+ std::string issuer = "https://idp.acme.test/realms/art";
+ int pendingPolls = 2;
+ bool slowDownOnce = true;
+ bool deny = false;
+ bool advertiseDevice = true;
+ std::string discoveredIssuer;
+ std::vector<std::string> posts;
+ int64_t clock = 1'800'000'000;
+ int slept = 0;
+ int refreshes = 0;
+
+ static std::string idToken() {
+ // {"sub":"u1","email":"[email protected]","name":"Ana Ruiz"} base64url, unsigned (display only)
+ return "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ1MSIsImVtYWlsIjoiYW5hQGFjbWUudGVzdCIsIm5hbWUiOiJBbmEgUnVpeiJ9.";
+ }
+ void install() {
+ ai::oidc::setTransportForTests(
+ {[this](const std::string& url) {
+ ai::HttpResponse r;
+ if (url != issuer + "/.well-known/openid-configuration") return r.status = 404, r;
+ Json d = Json::object();
+ d.set("issuer", discoveredIssuer.empty() ? issuer : discoveredIssuer);
+ if (advertiseDevice) d.set("device_authorization_endpoint", issuer + "/device");
+ d.set("token_endpoint", issuer + "/token");
+ r.status = 200;
+ r.body = d.dump();
+ return r;
+ },
+ [this](const std::string& url, const std::string& body) {
+ posts.push_back(url + " " + body);
+ ai::HttpResponse r;
+ r.status = 200;
+ if (url == issuer + "/device") {
+ r.body = R"({"device_code":"dev-123","user_code":"WDJB-MJHT","verification_uri":"https://idp.acme.test/device",
+ "verification_uri_complete":"https://idp.acme.test/device?code=WDJB-MJHT","interval":2,"expires_in":300})";
+ } else if (body.find("grant_type=refresh_token") != std::string::npos) {
+ ++refreshes;
+ r.body = R"({"access_token":"at-2","token_type":"Bearer","expires_in":3600})";
+ } else if (deny) {
+ r.status = 400, r.body = R"({"error":"access_denied"})";
+ } else if (pendingPolls > 0) {
+ --pendingPolls;
+ r.status = 400, r.body = R"({"error":"authorization_pending"})";
+ } else if (slowDownOnce) {
+ slowDownOnce = false;
+ r.status = 400, r.body = R"({"error":"slow_down"})";
+ } else {
+ Json t = Json::object();
+ t.set("access_token", "at-1");
+ t.set("token_type", "Bearer");
+ t.set("expires_in", 600);
+ t.set("refresh_token", "rt-1");
+ t.set("id_token", idToken());
+ r.body = t.dump();
+ }
+ return r;
+ }});
+ ai::oidc::setSleepForTests([this](int s) {
+ slept += s;
+ clock += s;
+ });
+ ai::oidc::setClockForTests([this] { return clock; });
+ }
+ policy::Policy policyFor() const {
+ return parsed(R"({"format": "sculptforge-policy", "version": 1, "ai": {"endpoints": ["https://llm.acme.test/"]},
+ "signIn": {"issuer": ")" + issuer + R"(", "clientId": "sculptforge-desktop", "audience": "sf-gateway"}})");
+ }
+};
+
+} // namespace
+
+TEST(studio_sign_in_device_flow_with_a_mock_idp) {
+ StudioState state("oidc");
+ MockIdp idp;
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut);
+ std::string shownCode, error;
+ const bool ok = ai::oidc::signIn(
+ [&](const ai::oidc::DeviceCode& c) {
+ shownCode = c.userCode;
+ CHECK(c.verificationUriComplete.find("WDJB-MJHT") != std::string::npos);
+ return true;
+ },
+ {}, error);
+ CHECK(ok && error.empty() && shownCode == "WDJB-MJHT");
+ // Pending twice (2 s each), slow_down (+5 s), then the tokens: the client waited as RFC 8628 asks.
+ CHECK(idp.slept == 2 + 2 + 2 + 7);
+ CHECK(idp.posts.front().find("client_id=sculptforge-desktop") != std::string::npos);
+ CHECK(idp.posts.front().find("scope=openid+profile+email+offline_access") != std::string::npos);
+ CHECK(idp.posts.front().find("audience=sf-gateway") != std::string::npos);
+ CHECK(idp.posts.back().find("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code") != std::string::npos);
+ CHECK(ai::oidc::state() == ai::oidc::State::SignedIn && ai::oidc::signedInAs() == "Ana Ruiz");
+ // The tokens are in the keychain, not a file.
+ std::string secret;
+ CHECK(keychain::load("sso/sculptforge-desktop", secret) && secret.find("at-1") != std::string::npos);
+ // The bearer goes to the studio gateway only.
+ CHECK(ai::oidc::bearerHeaderFor("https://llm.acme.test/v1/chat/completions") == "Authorization: Bearer at-1");
+ CHECK(ai::oidc::bearerHeaderFor("https://api.openai.com/v1/chat/completions").empty());
+ ai::AiSettings gw = ai::withPreset(ai::AiSettings::defaults(ai::AiSettings::Provider::Free), "litellm");
+ gw.endpoint = "https://llm.acme.test/v1/chat/completions";
+ gw.apiKey = "should-not-be-sent";
+ const auto headers = ai::requestHeaders(gw);
+ CHECK(std::find(headers.begin(), headers.end(), "Authorization: Bearer at-1") != headers.end());
+ for (const auto& h : headers) CHECK(h.find("should-not-be-sent") == std::string::npos);
+ // Expired: refreshed with the refresh token.
+ idp.clock += 3600;
+ CHECK(ai::oidc::accessToken() == "at-2" && idp.refreshes == 1);
+ // Signing out forgets them.
+ ai::oidc::signOut();
+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut && !keychain::load("sso/sculptforge-desktop", secret));
+ CHECK(ai::oidc::bearerHeaderFor("https://llm.acme.test/v1/chat/completions").empty());
+}
+
+TEST(studio_sign_in_refusals) {
+ StudioState state("oidc_refusals");
+ std::string error;
+ {
+ MockIdp idp;
+ idp.deny = true;
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("declined") != std::string::npos);
+ CHECK(ai::oidc::state() == ai::oidc::State::SignedOut);
+ }
+ {
+ MockIdp idp; // another issuer in the discovery document: refused before anything is posted
+ idp.discoveredIssuer = "https://evil.test/";
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("issuer") != std::string::npos && idp.posts.empty());
+ }
+ {
+ MockIdp idp;
+ idp.advertiseDevice = false;
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("device") != std::string::npos);
+ }
+ {
+ MockIdp idp; // the code runs out while the artist is away
+ idp.pendingPolls = 1000;
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ CHECK(!ai::oidc::signIn({}, {}, error) && error.find("expired") != std::string::npos);
+ }
+ {
+ MockIdp idp; // cancelled from the panel
+ idp.pendingPolls = 1000;
+ policy::setPolicyForTests(idp.policyFor());
+ idp.install();
+ int calls = 0;
+ CHECK(!ai::oidc::signIn({}, [&] { return ++calls > 3; }, error) && error.find("cancelled") != std::string::npos);
+ }
+ // Parsers on their own.
+ ai::oidc::Tokens t;
+ CHECK(ai::oidc::parseTokenReply(400, R"({"error":"expired_token"})", 0, t, error) == ai::oidc::TokenReply::Expired);
+ CHECK(ai::oidc::parseTokenReply(200, R"({"access_token":"x","token_type":"mac"})", 0, t, error) == ai::oidc::TokenReply::Error);
+ ai::oidc::DeviceCode d;
+ CHECK(!ai::oidc::parseDeviceCode(R"({"device_code":"a","user_code":"b","verification_uri":"http://evil.test/"})", 0, d, error));
+ CHECK(ai::oidc::parseIdToken("garbage").display().empty());
+ policy::resetPolicyForTests();
+ CHECK(ai::oidc::state() == ai::oidc::State::NotConfigured && !ai::oidc::signIn({}, {}, error));
+}
+
+TEST(studio_policy_network_off_is_studio_mode) {
+ const policy::Policy p = parsed(kFullPolicy);
+ const net::NetworkPolicy n = withManagedPolicy({}, p);
+ CHECK(n.offline && n.localNetwork);
+ auto allowed = [&](const std::string& u) { return std::find(n.allow.begin(), n.allow.end(), u) != n.allow.end(); };
+ CHECK(allowed("https://sw.acme.internal/") && allowed("https://llm.acme.internal/") && allowed("https://acme.okta.com/"));
+ CHECK(allowed("https://sw.acme.internal/sculptforge/latest.json"));
+ // Network on (or not managed): unchanged.
+ const net::NetworkPolicy open = withManagedPolicy({}, parsed(R"({"format": "sculptforge-policy", "version": 1})"));
+ CHECK(!open.offline && open.allow.empty());
+}
diff --cc tests/ui/ai_live.sfui
index 00000000,abb28797..056764e4
mode 000000,100644..100644
--- a/tests/ui/ai_live.sfui
+++ b/tests/ui/ai_live.sfui
@@@ -1,0 -1,76 +1,99 @@@
+ # Live mode (PanelAiLink.cpp): Preferences > AI > Let AI tools control this window. Off by default; a scripted AI
+ # tool over the real local socket / pipe: refused before approval, a wrong code refused, the right code (or Approve)
+ # connects, the badge shows, a step outside the project asks first, every step is in Undo labelled "AI:",
+ # Disconnect cuts it, and turning AI features off stops it.
+ run ui_look look=classic layout=classic
+ run new_sphere subdivisions=3
+ expect_value ai_link_state == 0
+ click "Preferences##palette.preferences"
+ click "AI##preferences.ai"
+ expect_text "Let AI tools control this window"
+ click "Let AI tools control this window##prefs.ai_live"
+ expect_value ai_link_state == 1
+ shot ai-live-prefs
+ click "Preferences##palette.preferences"
+
+ # Before approval nothing runs; a wrong code is refused.
+ ai_client connect
+ ai_client send {"hello":"sculptforge-live","v":1,"client":"Claude Code"}
+ wait_value ai_link_state == 2 5
+ ai_client expect waiting
+ ai_client send {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"new_sphere","arguments":{}}}
+ ai_client expect -32001
+ ai_client send {"pair":"000000"}
+ ai_client expect attempts_left
+ expect_text "Let an AI tool control this window?"
+ expect_text "Claude Code"
+ shot ai-live-approve
+ click "Approve##ailink"
+ ai_client expect paired":true
+ wait_value ai_link_state == 3 5
+
+ # Connected: the badge; the tools include the live ones; a step lands in Undo as "AI: ...".
+ ai_client send {"jsonrpc":"2.0","id":2,"method":"tools/list"}
+ ai_client expect viewport_image
+ ai_client send {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"view_set","arguments":{"preset":"three_quarter","frame":"all"}}}
+ ai_client expect "Camera: yaw 35"
+ ai_client send {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"stroke_screen","arguments":{"points":"0.4,0.45 0.5,0.4 0.6,0.45","brush":"Clay Block","radius":0.06,"strength":0.8}}}
+ ai_client expect id":4,
+ ai_client send {"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"viewport_image","arguments":{"size":256}}}
+ ai_client expect image/png
+ expect_text "AI connected: Claude Code"
+ expect_value undo_ai == 1
+ shot ai-live-badge
+
+ # Outside the project: asks first. Deny tells the tool not to retry.
+ ai_client send {"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"export_glb","arguments":{"path":"/tmp/elsewhere/out.glb"}}}
+ wait_value ai_link_state == 4 5
+ expect_text "Allow this AI step?"
+ expect_text "outside the project folder"
+ shot ai-live-confirm
+ click "Deny##ailinkconfirm"
+ ai_client expect "declined export_glb"
+ wait_value ai_link_state == 3 5
+
+ # Packs and the AI switch are never offered.
+ ai_client send {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"ai_features","arguments":{"on":false}}}
+ ai_client expect "Unknown tool: ai_features"
+ expect_value ai_enabled == 1
+
+ # The kill switch.
+ click "Disconnect##ailink"
+ wait_value ai_link_state == 1 5
+ expect_status "AI tool disconnected"
+ ai_client close
+
+ # AI features off: live mode stops (and the switch is hidden).
+ ai_client connect
+ ai_client send {"hello":"sculptforge-live","v":1,"client":"Again"}
+ wait_value ai_link_state == 2 5
+ run ai_features on=false
+ expect_value ai_link_state == 0
+ click "Preferences##palette.preferences"
+ expect_not "Let AI tools control this window##prefs.ai_live"
+ ai_client close
+ run ai_features on=true
+ expect_value ai_link_state == 1 # (the switch stays on: back with AI)
++
++# A studio's policy (core/ManagedPolicy.h): only some kinds of tool are listed and run (refusals are audited), and
++# "live": "never" stops the listener and locks the switch off.
++run ui_policy json="{\"format\":\"sculptforge-policy\",\"version\":1,\"mcp\":{\"categories\":[\"info\"]}}"
++expect_value ai_link_state == 1
++ai_client connect
++ai_client send {"hello":"sculptforge-live","v":1,"client":"Studio"}
++wait_value ai_link_state == 2 5
++click "Approve##ailink"
++ai_client expect paired":true
++wait_value ai_link_state == 3 5
++ai_client send {"jsonrpc":"2.0","id":8,"method":"tools/list"}
++ai_client expect viewport_image
++ai_client send {"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"stroke_screen","arguments":{"points":"0.5,0.5"}}}
++ai_client expect "doesn't allow AI tools to use stroke_screen"
++expect_value undo_ai == 1
++run ui_policy json="{\"format\":\"sculptforge-policy\",\"version\":1,\"organization\":\"Acme Animation\",\"mcp\":{\"live\":\"never\"}}"
++wait_value ai_link_state == 0 5
++ai_client close
++expect_text Managed by your studio # (Preferences > AI is still open)
++shot ai-live-managed
++run ui_policy json=""
++wait_value ai_link_state == 1 5