diff --git a/Database/pb_migrations/1764100000_ai.js b/Database/pb_migrations/1764100000_ai.js new file mode 100644 index 0000000..fb00df6 --- /dev/null +++ b/Database/pb_migrations/1764100000_ai.js @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Phase E of docs/AFFINE.md: AI and MCP (ADR-15). +// +// - ai_profiles: provider settings (BYOK). workspace empty = an instance +// default a superadmin manages. api_key is AES-GCM ciphertext (base64). +// - workspaces.ai_settings: { enabled, useInstanceProfiles, index, ignored }. +// - ai_sessions: one person's chat in a workspace, messages inline as JSON. +// - ai_files: extra documents for retrieval; their text is extracted on upload. + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + const workspaces = app.findCollectionByNameOrId("workspaces"); + + workspaces.fields.add(new JSONField({ name: "ai_settings", maxSize: 200000 })); + app.save(workspaces); + + app.save( + new Collection({ + type: "base", + name: "ai_profiles", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, cascadeDelete: true }, + { name: "name", type: "text", required: true, max: 80 }, + { name: "kind", type: "select", required: true, maxSelect: 1, values: ["openai", "anthropic", "ollama"] }, + { name: "base_url", type: "text", max: 500 }, + { name: "api_key", type: "text", max: 2000 }, + { name: "chat_model", type: "text", max: 200 }, + { name: "embed_model", type: "text", max: 200 }, + { name: "effort", type: "text", max: 20 }, + { name: "enabled", type: "bool" }, + { name: "position", type: "number" }, + { name: "requests", type: "number" }, + { name: "input_tokens", type: "number" }, + { name: "output_tokens", type: "number" }, + { name: "last_used", type: "date" }, + { name: "last_error", type: "text", max: 500 }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE INDEX idx_ai_profiles_ws ON ai_profiles (workspace, position)"], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "ai_sessions", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "title", type: "text", max: 200 }, + { name: "scope", type: "select", maxSelect: 1, values: ["workspace", "space", "page"] }, + { name: "scope_id", type: "text", max: 15 }, + { name: "messages", type: "json", maxSize: 5000000 }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE INDEX idx_ai_sessions_user ON ai_sessions (user, workspace, updated)"], + }), + ); + + app.save( + new Collection({ + type: "base", + name: "ai_files", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "name", type: "text", required: true, max: 200 }, + { name: "content_text", type: "text", max: 2000000 }, + { name: "size", type: "number" }, + { name: "created_by", type: "relation", collectionId: users.id, maxSelect: 1 }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE INDEX idx_ai_files_ws ON ai_files (workspace)"], + }), + ); + }, + (app) => { + for (const name of ["ai_files", "ai_sessions", "ai_profiles"]) { + app.delete(app.findCollectionByNameOrId(name)); + } + const ws = app.findCollectionByNameOrId("workspaces"); + ws.fields.removeByName("ai_settings"); + app.save(ws); + }, +); diff --git a/Docs-Site/guide/administration.md b/Docs-Site/guide/administration.md index 778a4ba..e06de71 100644 --- a/Docs-Site/guide/administration.md +++ b/Docs-Site/guide/administration.md @@ -42,6 +42,24 @@ an 8-digit code; both work once, for 15 minutes. Email must be set up first. Switching storage does not move files that were uploaded before: copy them from `pb_data/storage` to the bucket with your usual tools (for example `rclone`), keeping the folder structure, before switching. +## AI + +Docwell brings no AI of its own: you choose a provider, and nothing is sent anywhere until one is set up. + +- **Providers.** *Admin panel → AI* holds the server's default providers; each workspace can add its own under + *Workspace settings → AI* and use them before (or instead of) the server's. A provider is an OpenAI-compatible + API (OpenAI, Azure, OpenRouter, LiteLLM, vLLM, LocalAI…), Anthropic, or Ollama, with a chat model and, except + for Anthropic, optionally an embedding model. Providers are tried from the top: when one fails, the next one + answers. **Test** checks a provider; requests and tokens are counted per provider. +- **Search by meaning.** *Index pages for AI* in a workspace's settings sends every page's text to the first + provider with an embedding model and keeps the vectors in `DOCWELL_DATA_DIR`. Without it, the chat finds sources + with keyword search. Pages can be left out (with their subpages), and extra text, Markdown, HTML or Word files + can be added as sources. Changing the embedding model indexes the workspace again. +- **Keys** are encrypted with `DOCWELL_SECRET_KEY` (see *Configuration*) and never shown again. +- **MCP.** AI agents and tools (Claude, IDEs, …) can use Docwell as an MCP server at `https:///mcp` with a + personal API token: read-only tokens can list, search and read pages and ask the workspace's AI; write tokens can + also create and update pages. Changes made through MCP are in the audit log. + ## Rebuilding the search index Search follows edits within a few seconds. If results ever look wrong, run **search.rebuild** in *Maintenance*. diff --git a/Docs-Site/guide/configuration.md b/Docs-Site/guide/configuration.md index 57aa9cf..b1a7e17 100644 --- a/Docs-Site/guide/configuration.md +++ b/Docs-Site/guide/configuration.md @@ -30,10 +30,11 @@ Docwell's collections in it when it starts. Change the image with `DB_IMAGE`. | `DOCWELL_ADMIN_EMAIL`, `DOCWELL_ADMIN_PASSWORD` | | Creates the first account as superadmin when the server starts and there are no accounts yet. Set both or neither; the password needs 8 characters or more. Once any account exists the server ignores them, so a restart never resets the password or the role. Empty: the first person to sign up becomes the superadmin. | | `DOCWELL_ADMIN_NAME` | `Admin` | The display name of that account. | | `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. | -| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index. It is rebuilt from the database when missing, so a volume is optional but makes restarts faster. | +| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index and the AI vectors (`ai.db`). Both are rebuilt from the database when missing, so a volume is optional but makes restarts faster (and saves embedding every page again). | +| `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers. Without it, a key derived from `DOCWELL_PB_PASSWORD` is used; changing whichever is in use means entering the provider keys again. | | `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. | | `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. | -| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks call loopback and link-local addresses. For development only. | +| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, and the AI providers of workspaces, call loopback and link-local addresses. For development only (AI providers set up in the admin panel may always use local addresses). | ### PocketBase settings diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index 8453518..8ecb207 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -129,6 +129,19 @@ Press **Ctrl+K** (⌘K on a Mac) or click **Search** in the sidebar. With nothin visited last; type to search titles and text in every space you can open. The filters narrow results by space, tag, author or date. Star a page (☆ in the header) to keep it under **Favorites** in the sidebar. +## AI + +When AI is set up in a workspace (see *Administration → AI*), the ✦ button in the header (**Ctrl+J**) opens the +**AI chat** beside the page. Ask about the open page, its space or the whole workspace; answers cite their sources +as [1], [2]… and the links open the page at the cited block. Chats are private to you: pick earlier ones from the +list, delete them, or **continue in a new chat** from any answer to try another direction. + +Select text in a page and choose **Ask AI** in the toolbar to improve, shorten, lengthen, fix, summarise, translate +or continue it, or to give your own instruction. The result shows first; **Replace selection** or **Insert below** +puts it in the page, where undo and page history work as for any edit. + +AI only ever reads what you can open yourself. + ## Properties, tags and collections Under each page title, **Properties** shows the page's tags, the workspace's custom properties (text, number, diff --git a/Docs-Site/reference/api.md b/Docs-Site/reference/api.md index 52fed2a..5b67156 100644 --- a/Docs-Site/reference/api.md +++ b/Docs-Site/reference/api.md @@ -17,6 +17,21 @@ docwell-server's API is described in [`api/openapi.yaml`](https://github.com/doc Health checks for load balancers: `GET /healthz` (process up) and `GET /readyz` (database reachable). +## MCP + +`POST /mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server (Streamable HTTP, JSON +responses). Authenticate with an API token. Tools: `list_workspaces`, `list_spaces`, `list_pages`, `search`, +`read_page` (Markdown) and `ask` (the workspace's AI, with sources); write tokens also get `create_page` and +`update_page` (replace or append Markdown). For example, in an MCP client's configuration: + +```json +{ "mcpServers": { "docwell": { "type": "http", "url": "https://wiki.example.com/mcp", + "headers": { "Authorization": "Bearer dw_…" } } } } +``` + +AI chat answers (`POST /api/v1/ai/sessions/{id}/messages`) and writing actions +(`POST /api/v1/workspaces/{id}/ai/write`) stream as server-sent events; see the OpenAPI file for the events. + ## Example ```bash diff --git a/Packages/api-client/src/index.test.ts b/Packages/api-client/src/index.test.ts index c1bc33e..1053f05 100644 --- a/Packages/api-client/src/index.test.ts +++ b/Packages/api-client/src/index.test.ts @@ -1,7 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { describe, expect, it, vi } from "vitest"; -import { ApiError, createClient, isManager } from "./index"; +import { ApiError, createClient, isManager, readEventStream } from "./index"; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); @@ -85,3 +85,26 @@ describe("createClient", () => { expect(isManager(null)).toBe(false); }); }); + +describe("readEventStream", () => { + it("splits server-sent events, across chunk boundaries, and parses JSON data", async () => { + const chunks = [ + 'event: sources\ndata: {"citations":[]}\n\nevent: del', + 'ta\ndata: {"text":"Hi"}\n\n', + "data: plain\n\n", + ]; + const body = new ReadableStream({ + start(c) { + for (const ch of chunks) c.enqueue(new TextEncoder().encode(ch)); + c.close(); + }, + }); + const got = []; + for await (const e of readEventStream(body)) got.push(e); + expect(got).toEqual([ + { event: "sources", data: { citations: [] } }, + { event: "delta", data: { text: "Hi" } }, + { event: "message", data: "plain" }, + ]); + }); +}); diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 9983734..07fc3c4 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -96,6 +96,62 @@ export type Collection = Schemas["Collection"]; export type CollectionInput = Schemas["CollectionInput"]; export type JournalDay = Schemas["JournalDay"]; export type JournalInfo = Schemas["JournalInfo"]; +export type AiAvailability = Schemas["AiAvailability"]; +export type AiSettings = Schemas["AiSettings"]; +export type AiProviderKind = Schemas["AiProviderKind"]; +export type AiProfile = Schemas["AiProfile"]; +export type AiProfileInput = Schemas["AiProfileInput"]; +export type AiTestResult = Schemas["AiTestResult"]; +export type AiIndexStatus = Schemas["AiIndexStatus"]; +export type AiFile = Schemas["AiFile"]; +export type AiScope = Schemas["AiScope"]; +export type AiSessionSummary = Schemas["AiSessionSummary"]; +export type AiSession = Schemas["AiSession"]; +export type AiSessionInput = Schemas["AiSessionInput"]; +export type AiCitation = Schemas["AiCitation"]; +export type AiMessage = Schemas["AiMessage"]; +export type AiWriteAction = Schemas["AiWriteAction"]; +export type AiWriteInput = Schemas["AiWriteInput"]; + +/** One server-sent event of a streamed AI answer. */ +export interface AiStreamEvent { + event: string; + data: unknown; +} + +/** Splits a text/event-stream body into events (see AiStreamEvent). */ +export async function* readEventStream(body: ReadableStream): AsyncGenerator { + const reader = body.getReader(); + const decoder = new TextDecoder(); + let buf = ""; + for (;;) { + const { value, done } = await reader.read(); + if (value) buf += decoder.decode(value, { stream: true }); + if (done) buf += decoder.decode(); + let cut: number; + buf = buf.replace(/\r\n/g, "\n"); + while ((cut = buf.indexOf("\n\n")) >= 0) { + const block = buf.slice(0, cut); + buf = buf.slice(cut + 2); + let event = "message"; + const data: string[] = []; + for (const line of block.split("\n")) { + if (line.startsWith("event:")) event = line.slice(6).trim(); + else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, "")); + } + if (!data.length) continue; + let parsed: unknown = data.join("\n"); + try { + parsed = JSON.parse(parsed as string); + } catch { + // plain text data + } + yield { event, data: parsed }; + } + if (done) return; + } +} + export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility }; export type UpdateSpaceRequest = Partial>; @@ -138,6 +194,8 @@ export interface ClientOptions { fetch?: typeof fetch; } +const enc = encodeURIComponent; + export function createClient(opts: ClientOptions) { const base = opts.baseUrl.replace(/\/+$/, ""); const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis); @@ -179,6 +237,24 @@ export function createClient(opts: ClientOptions) { return { blob: await res.blob(), filename: m ? decodeURIComponent(m[1]!) : "download" }; } + /** + * POSTs JSON and yields the server-sent events of the answer. An error + * before the stream starts is thrown as ApiError, like request's. + */ + async function* stream(path: string, body: unknown, signal?: AbortSignal): AsyncGenerator { + const headers: Record = { Accept: "text/event-stream", "Content-Type": "application/json" }; + const token = opts.token?.(); + if (token) headers.Authorization = `Bearer ${token}`; + const res = await doFetch(base + path, { method: "POST", headers, body: JSON.stringify(body), signal }); + if (!res.ok || !res.body) { + const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text(); + const err = new ApiError(res.status, data); + if (res.status === 401 && token && err.code === "unauthorized") opts.onUnauthorized?.(); + throw err; + } + yield* readEventStream(res.body); + } + /** Sends a multipart form; the browser sets the boundary header itself. */ async function upload(path: string, form: FormData): Promise { const headers: Record = { Accept: "application/json" }; @@ -237,6 +313,59 @@ export function createClient(opts: ClientOptions) { revokeToken: (id: string) => request("DELETE", `/api/v1/me/tokens/${encodeURIComponent(id)}`), }, + /** AI chat, writing actions and their setup (ADR-15). */ + ai: { + available: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai`), + settings: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/settings`), + saveSettings: (workspace: string, input: AiSettings) => + request("PUT", `/api/v1/workspaces/${enc(workspace)}/ai/settings`, input), + /** A workspace's profiles; pass "" for the instance defaults (superadmins). */ + profiles: (workspace: string) => + request( + "GET", + workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles` : "/api/v1/admin/ai/profiles", + ), + createProfile: (workspace: string, input: AiProfileInput) => + post( + workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles` : "/api/v1/admin/ai/profiles", + input, + ), + orderProfiles: (workspace: string, ids: string[]) => + request( + "PUT", + workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles/order` : "/api/v1/admin/ai/profiles/order", + { ids }, + ), + updateProfile: (id: string, input: AiProfileInput) => + request("PATCH", `/api/v1/ai/profiles/${enc(id)}`, input), + deleteProfile: (id: string) => request("DELETE", `/api/v1/ai/profiles/${enc(id)}`), + testProfile: (id: string) => post(`/api/v1/ai/profiles/${enc(id)}/test`), + index: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/index`), + rebuildIndex: (workspace: string) => post(`/api/v1/workspaces/${enc(workspace)}/ai/index/rebuild`), + files: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/files`), + addFile: (workspace: string, file: Blob, name: string) => { + const form = new FormData(); + form.append("file", file, name); + return upload(`/api/v1/workspaces/${enc(workspace)}/ai/files`, form); + }, + deleteFile: (id: string) => request("DELETE", `/api/v1/ai/files/${enc(id)}`), + sessions: (workspace: string) => + request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/sessions`), + createSession: (workspace: string, input: AiSessionInput) => + post(`/api/v1/workspaces/${enc(workspace)}/ai/sessions`, input), + session: (id: string) => request("GET", `/api/v1/ai/sessions/${enc(id)}`), + updateSession: (id: string, input: AiSessionInput) => + request("PATCH", `/api/v1/ai/sessions/${enc(id)}`, input), + deleteSession: (id: string) => request("DELETE", `/api/v1/ai/sessions/${enc(id)}`), + forkSession: (id: string, message = "") => post(`/api/v1/ai/sessions/${enc(id)}/fork`, { message }), + /** Events: sources {citations}, delta {text}, done {user, message}, error {message}. */ + ask: (id: string, content: string, signal?: AbortSignal) => + stream(`/api/v1/ai/sessions/${enc(id)}/messages`, { content }, signal), + /** Events: delta {text}, done {}, error {message}. */ + write: (workspace: string, input: AiWriteInput, signal?: AbortSignal) => + stream(`/api/v1/workspaces/${enc(workspace)}/ai/write`, input, signal), + }, + webhooks: { list: (workspace: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(workspace)}/webhooks`), diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index f1e6897..fe21f48 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -2455,6 +2455,356 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/ai": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** What AI offers in the workspace to the caller (member) */ + get: operations["getWorkspaceAi"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/settings": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The workspace's AI switches (workspace admin) */ + get: operations["getAiSettings"]; + /** Replace the workspace's AI switches (workspace admin) */ + put: operations["saveAiSettings"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/profiles": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The workspace's AI provider profiles, in order (workspace admin) */ + get: operations["listAiProfiles"]; + put?: never; + /** + * Add a provider profile at the end (workspace admin) + * @description Workspace profiles follow the webhook address rules: they cannot reach loopback or private addresses unless DOCWELL_WEBHOOKS_ALLOW_LOCAL is set. + */ + post: operations["createAiProfile"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/profiles/order": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + /** Set the order of the workspace's profiles (workspace admin) */ + put: operations["orderAiProfiles"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/admin/ai/profiles": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The instance's default AI profiles (superadmin) */ + get: operations["listInstanceAiProfiles"]; + put?: never; + /** Add an instance default profile (superadmin) */ + post: operations["createInstanceAiProfile"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/admin/ai/profiles/order": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + /** Set the order of the instance's profiles (superadmin) */ + put: operations["orderInstanceAiProfiles"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ai/profiles/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Remove a profile */ + delete: operations["deleteAiProfile"]; + options?: never; + head?: never; + /** Change a profile; a missing apiKey keeps the stored one (workspace admin, or superadmin for instance profiles) */ + patch: operations["updateAiProfile"]; + trace?: never; + }; + "/api/v1/ai/profiles/{id}/test": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Send a one-word chat (and a one-line embedding) through a profile */ + post: operations["testAiProfile"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/index": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Embeddings progress of the workspace (workspace admin) */ + get: operations["getAiIndex"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/index/rebuild": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Drop the workspace's vectors and embed every page again (workspace admin) */ + post: operations["rebuildAiIndex"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/files": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Extra documents chat retrieves from (workspace admin) */ + get: operations["listAiFiles"]; + put?: never; + /** Add a text, Markdown, HTML or Word file (up to 10 MB) for retrieval (workspace admin) */ + post: operations["addAiFile"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ai/files/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Remove an extra file and its vectors (workspace admin) */ + delete: operations["deleteAiFile"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/sessions": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The caller's AI chats in the workspace, newest first */ + get: operations["listAiSessions"]; + put?: never; + /** Start an AI chat about the workspace, a space or a page */ + post: operations["createAiSession"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ai/sessions/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** One of the caller's chats with its messages */ + get: operations["getAiSession"]; + put?: never; + post?: never; + /** Delete a chat */ + delete: operations["deleteAiSession"]; + options?: never; + head?: never; + /** Rename a chat or change what it asks about */ + patch: operations["updateAiSession"]; + trace?: never; + }; + "/api/v1/ai/sessions/{id}/fork": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Copy a chat up to a message (all of it without one) */ + post: operations["forkAiSession"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/ai/sessions/{id}/messages": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Ask a question in a chat; the answer streams as server-sent events */ + post: operations["askAi"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/workspaces/{id}/ai/write": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** Run a writing action on a piece of text; the result (Markdown) streams as server-sent events */ + post: operations["aiWrite"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Model Context Protocol endpoint (Streamable HTTP, JSON responses) + * @description One JSON-RPC 2.0 message or batch per request: initialize, ping, tools/list, tools/call. Authenticate with a Docwell API token; read tokens get list_workspaces, list_spaces, list_pages, search, read_page and ask, write tokens also create_page and update_page. Notifications are answered with 202. + */ + post: operations["mcp"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -3364,6 +3714,160 @@ export interface components { /** @description Empty when the account is gone */ name: string; }; + IdList: { + ids: string[]; + }; + AiAvailability: { + /** @description A profile with a chat model is set up and AI is on */ + chat: boolean; + /** @description The workspace is indexed for retrieval */ + embeddings: boolean; + /** @description The caller may change the workspace's AI settings */ + canManage: boolean; + }; + AiSettings: { + enabled: boolean; + /** @description After its own profiles */ + useInstanceProfiles: boolean; + /** @description Embed pages for retrieval (sends every page to the embedding provider) */ + index: boolean; + /** @description Pages (with their subpages) that are neither indexed nor retrieved */ + ignored: string[]; + }; + /** + * @description openai is any OpenAI-compatible API + * @enum {string} + */ + AiProviderKind: "openai" | "anthropic" | "ollama"; + AiProfile: { + id: string; + /** @description Empty for an instance default */ + workspace: string; + name: string; + kind: components["schemas"]["AiProviderKind"]; + /** @description Empty for the kind's default address */ + baseUrl: string; + /** @description An API key is stored (keys are never returned) */ + keySet: boolean; + chatModel: string; + /** @description Empty when the profile is not used for embeddings */ + embedModel: string; + /** @description Anthropic effort level */ + effort: string; + enabled: boolean; + position: number; + usage: { + requests: number; + inputTokens: number; + outputTokens: number; + }; + lastUsed: string; + lastError: string; + created: string; + }; + /** @description Creating needs name and kind; updating changes the fields that are set */ + AiProfileInput: { + name?: string; + kind?: components["schemas"]["AiProviderKind"]; + baseUrl?: string; + /** @description Write-only; an empty string removes the key */ + apiKey?: string; + chatModel?: string; + embedModel?: string; + /** @enum {string} */ + effort?: "" | "low" | "medium" | "high" | "xhigh" | "max"; + enabled?: boolean; + }; + AiTestResult: { + ok: boolean; + /** @description The model's reply */ + chat: string; + embeddings: string; + dimensions: number; + latencyMs: number; + error: string; + }; + AiIndexStatus: { + enabled: boolean; + /** @description The profile vectors come from; empty when none has an embedding model */ + profile: string; + model: string; + /** @description Pages that can be indexed */ + pages: number; + indexed: number; + files: number; + chunks: number; + running: boolean; + lastRun: string; + lastError: string; + }; + AiFile: { + id: string; + name: string; + size: number; + chars: number; + indexed: boolean; + created: string; + }; + /** @enum {string} */ + AiScope: "workspace" | "space" | "page"; + AiSessionSummary: { + id: string; + title: string; + scope: components["schemas"]["AiScope"]; + /** @description The space or page; empty for the workspace */ + scopeId: string; + created: string; + updated: string; + }; + AiCitation: { + /** @description The number the answer cites as [n] */ + n: number; + page?: string; + /** @description The cited block (link with #b-) */ + block?: string; + /** @description An extra file instead of a page */ + file?: string; + title: string; + snippet: string; + }; + AiMessage: { + id: string; + /** @enum {string} */ + role: "user" | "assistant"; + /** @description Markdown */ + content: string; + citations?: components["schemas"]["AiCitation"][]; + /** @description Why the answer stopped */ + error?: string; + created: string; + }; + AiSession: components["schemas"]["AiSessionSummary"] & { + workspace: string; + messages: components["schemas"]["AiMessage"][]; + }; + AiSessionInput: { + title?: string; + scope?: components["schemas"]["AiScope"]; + scopeId?: string; + }; + AiForkInput: { + /** @description The last message to copy; empty copies all */ + message?: string; + }; + /** @enum {string} */ + AiWriteAction: "rewrite" | "summarize" | "translate" | "continue" | "shorter" | "longer" | "fix" | "custom"; + AiWriteInput: { + action: components["schemas"]["AiWriteAction"]; + /** @description The selection */ + text: string; + /** @description Text in front of the selection (continue) */ + before?: string; + /** @description Target language (translate) */ + language?: string; + /** @description What to do (custom) */ + instruction?: string; + }; }; responses: { /** @description Signed in */ @@ -7769,4 +8273,684 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + getWorkspaceAi: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiAvailability"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + getAiSettings: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSettings"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + saveAiSettings: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiSettings"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSettings"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listAiProfiles: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"][]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + createAiProfile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiProfileInput"]; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + orderAiProfiles: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["IdList"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"][]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listInstanceAiProfiles: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"][]; + }; + }; + 403: components["responses"]["Error"]; + }; + }; + createInstanceAiProfile: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiProfileInput"]; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + }; + }; + orderInstanceAiProfiles: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["IdList"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"][]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + }; + }; + deleteAiProfile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + updateAiProfile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiProfileInput"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiProfile"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + testAiProfile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiTestResult"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + getAiIndex: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiIndexStatus"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + rebuildAiIndex: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Started */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listAiFiles: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiFile"][]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + addAiFile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "multipart/form-data": { + /** Format: binary */ + file: string; + }; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiFile"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + deleteAiFile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listAiSessions: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSessionSummary"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + createAiSession: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiSessionInput"]; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSession"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + getAiSession: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSession"]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + deleteAiSession: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Deleted */ + 204: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 404: components["responses"]["Error"]; + }; + }; + updateAiSession: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiSessionInput"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSession"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + forkAiSession: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiForkInput"]; + }; + }; + responses: { + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiSession"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + askAi: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + content: string; + }; + }; + }; + responses: { + /** @description Events: sources ({citations: AiCitation[]}), delta ({text}), then done ({user: AiMessage, message: AiMessage}) or error ({message}). Errors before the stream starts are JSON. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/event-stream": string; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + aiWrite: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiWriteInput"]; + }; + }; + responses: { + /** @description Events: delta ({text}), then done ({}) or error ({message}). Errors before the stream starts are JSON. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/event-stream": string; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + mcp: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + responses: { + /** @description The JSON-RPC response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + /** @description A notification was received */ + 202: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + 401: components["responses"]["Error"]; + }; + }; } diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue index 07d79fb..54ee06d 100644 --- a/Packages/editor/src/DocwellEditor.vue +++ b/Packages/editor/src/DocwellEditor.vue @@ -6,6 +6,7 @@ import { BubbleMenu } from "@tiptap/vue-3/menus"; import { CellSelection } from "@tiptap/pm/tables"; import { DwIcon, type IconName } from "@docwell/ui"; import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue"; +import { aiActions, type AiAction, type AiHost } from "./ai"; import { copyBlockLink } from "./blocklinks"; import { palette, type PaletteColor } from "./colors"; import { docwellExtensions, type CollabUser } from "./extensions"; @@ -48,6 +49,8 @@ const props = withDefaults( syncedPages?: SyncedPageHost; /** Opens a database record as a full page; without it records open beside the page only. */ recordPage?: (database: string, row: string) => void; + /** Offers AI writing actions on selections (rewrite, translate …). */ + ai?: AiHost; /** Edits this fragment of a document instead (a note on the canvas), without carets. */ fragment?: { doc: Y.Doc; fragment: Y.XmlFragment }; }>(), @@ -118,8 +121,8 @@ onBeforeUnmount(() => editor.value?.destroy()); // The selection toolbar: formatting for editors, Comment for anyone allowed. type Tool = { id: string; icon: IconName; label: string; active: () => boolean; run: () => void }; /** The colour or alignment choices open under the toolbar, if any. */ -const panel = ref<"color" | "align" | null>(null); -const togglePanel = (p: "color" | "align") => (panel.value = panel.value === p ? null : p); +const panel = ref<"color" | "align" | "ai" | null>(null); +const togglePanel = (p: "color" | "align" | "ai") => (panel.value = panel.value === p ? null : p); const alignment = (e: Editor) => String(e.getAttributes("paragraph").textAlign ?? e.getAttributes("heading").textAlign ?? "left"); @@ -183,6 +186,15 @@ const tools = computed(() => { }, }, ]; + if (props.ai) { + list.unshift({ + id: "ai", + icon: "sparkles", + label: labels.value.ai.button, + active: () => panel.value === "ai", + run: () => togglePanel("ai"), + }); + } const pages = props.pages; if (pages?.create) { list.push({ @@ -217,6 +229,84 @@ function setColor(kind: "text" | "highlight", color: PaletteColor | null) { else (color ? c.setHighlight({ color }) : c.unsetHighlight()).run(); } +// AI writing actions: the result streams into the panel, then replaces the +// selection or goes below it. +const aiText = ref(""); +const aiBusy = ref(false); +const aiError = ref(""); +const aiLanguage = ref(""); +const aiInstruction = ref(""); +const aiLast = ref("rewrite"); +let aiRange = { from: 0, to: 0 }; +let aiAbort: AbortController | null = null; +const aiStarted = computed(() => aiBusy.value || aiText.value !== "" || aiError.value !== ""); +const aiQuick = aiActions.filter((a) => a !== "translate" && a !== "custom"); + +async function runAi(action: AiAction) { + const e = editor.value; + const host = props.ai; + if (!e || !host || aiBusy.value) return; + if (action === "custom" && !aiInstruction.value.trim()) return; + const { from, to } = e.state.selection; + aiRange = { from, to }; + aiLast.value = action; + aiText.value = aiError.value = ""; + aiBusy.value = true; + const abort = new AbortController(); + aiAbort = abort; + try { + await host.run( + { + action, + text: e.state.doc.textBetween(from, to, "\n\n"), + before: e.state.doc.textBetween(Math.max(0, from - 4000), from, "\n\n"), + language: aiLanguage.value || host.languages[0], + instruction: aiInstruction.value.trim(), + }, + (t) => (aiText.value += t), + abort.signal, + ); + } catch (err) { + if (!abort.signal.aborted) + aiError.value = err instanceof Error && err.message ? err.message : labels.value.ai.failed; + } finally { + aiBusy.value = false; + if (aiAbort === abort) aiAbort = null; + } +} + +function stopAi() { + aiAbort?.abort(); +} + +function resetAi() { + stopAi(); + aiText.value = aiError.value = ""; +} + +function applyAi(where: "replace" | "below") { + const e = editor.value; + const host = props.ai; + if (!e || !host || !aiText.value.trim()) return; + const html = host.toHTML(aiText.value); + const size = e.state.doc.content.size; + const from = Math.min(aiRange.from, size); + const to = Math.min(aiRange.to, size); + if (where === "replace") { + e.chain().focus().insertContentAt({ from, to }, html).run(); + } else { + const $to = e.state.doc.resolve(to); + const at = $to.depth >= 1 ? $to.after(1) : to; + e.chain().focus().insertContentAt(at, html).run(); + } + resetAi(); + panel.value = null; +} + +watch(panel, (p) => { + if (p !== "ai") resetAi(); +}); + function setAlign(a: "left" | "center" | "right") { editor.value?.chain().focus().setTextAlign(a).run(); panel.value = null; @@ -538,6 +628,125 @@ defineExpose({ editor, openFind }); +
+ + +
void, signal: AbortSignal): Promise; + toHTML(markdown: string): string; + /** Languages offered for "translate" (names in the reader's language). */ + languages: string[]; +} diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts index 3453363..7a5f8d8 100644 --- a/Packages/editor/src/index.ts +++ b/Packages/editor/src/index.ts @@ -18,6 +18,7 @@ export { linkedRecord, openRecord, recordHash } from "./database/links"; export { followLink, isTargetHash } from "./hashlinks"; export { embedSource, type LinkHost, type LinkPreview } from "./embeds"; export { dateChoices, formatDate, type DateChoice } from "./dates"; +export { aiActions, type AiAction, type AiHost, type AiWriteRequest } from "./ai"; export { default as DocwellEdgeless } from "./DocwellEdgeless.vue"; export type { ElementComment } from "@docwell/canvas"; export { diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts index c17fc84..951e5ec 100644 --- a/Packages/editor/src/labels.ts +++ b/Packages/editor/src/labels.ts @@ -135,6 +135,28 @@ export interface EditorLabels { count: string; none: string; }; + /** AI writing actions on a selection (ai.ts), where the host offers AI. */ + ai: { + button: string; + rewrite: string; + summarize: string; + translate: string; + continue: string; + shorter: string; + longer: string; + fix: string; + custom: string; + customPlaceholder: string; + language: string; + run: string; + working: string; + replace: string; + insertBelow: string; + discard: string; + stop: string; + retry: string; + failed: string; + }; /** Dates in the text ("@tomorrow") and their reminders. */ dates: { today: string; @@ -308,6 +330,27 @@ export const englishLabels: EditorLabels = { count: "{current} of {total}", none: "No matches", }, + ai: { + button: "Ask AI", + rewrite: "Improve writing", + summarize: "Summarise", + translate: "Translate", + continue: "Continue writing", + shorter: "Make shorter", + longer: "Make longer", + fix: "Fix spelling and grammar", + custom: "Ask AI to…", + customPlaceholder: "Tell AI what to do with the selection", + language: "Language", + run: "Go", + working: "Writing…", + replace: "Replace selection", + insertBelow: "Insert below", + discard: "Discard", + stop: "Stop", + retry: "Try again", + failed: "AI could not finish this.", + }, dates: { today: "Today", tomorrow: "Tomorrow", diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index d590839..46e6ac9 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -177,6 +177,14 @@ export const iconPaths = { "M4 14v-4", "M8 8h8v8H8z", ], + // AI (Phase E): sparkles for AI features, a paper plane for sending. + sparkles: [ + "M10 4l1.6 4.4L16 10l-4.4 1.6L10 16l-1.6-4.4L4 10l4.4-1.6z", + "M17 14l.8 2.2L20 17l-2.2.8L17 20l-.8-2.2L14 17l2.2-.8z", + "M17 3v4", + "M15 5h4", + ], + send: ["M4 12l16-8-6 16-2-6z", "M12 14l8-10"], } as const; export type IconName = keyof typeof iconPaths; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 4e1f78a..15714f4 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -4159,3 +4159,754 @@ class PageUser { Map toJson() => {'id': id, 'name': name}; } + +class IdList { + const IdList({required this.ids}); + + factory IdList.fromJson(Map json) => + IdList(ids: (json['ids'] as List).map((e) => e as String).toList()); + + final List ids; + + Map toJson() => {'ids': ids.map((e) => e).toList()}; +} + +class AiAvailability { + const AiAvailability({ + required this.chat, + required this.embeddings, + required this.canManage, + }); + + factory AiAvailability.fromJson(Map json) => AiAvailability( + chat: json['chat'] as bool, + embeddings: json['embeddings'] as bool, + canManage: json['canManage'] as bool, + ); + + /// A profile with a chat model is set up and AI is on + final bool chat; + + /// The workspace is indexed for retrieval + final bool embeddings; + + /// The caller may change the workspace's AI settings + final bool canManage; + + Map toJson() => { + 'chat': chat, + 'embeddings': embeddings, + 'canManage': canManage, + }; +} + +class AiSettings { + const AiSettings({ + required this.enabled, + required this.useInstanceProfiles, + required this.index, + required this.ignored, + }); + + factory AiSettings.fromJson(Map json) => AiSettings( + enabled: json['enabled'] as bool, + useInstanceProfiles: json['useInstanceProfiles'] as bool, + index: json['index'] as bool, + ignored: (json['ignored'] as List).map((e) => e as String).toList(), + ); + + final bool enabled; + + /// After its own profiles + final bool useInstanceProfiles; + + /// Embed pages for retrieval (sends every page to the embedding provider) + final bool index; + + /// Pages (with their subpages) that are neither indexed nor retrieved + final List ignored; + + Map toJson() => { + 'enabled': enabled, + 'useInstanceProfiles': useInstanceProfiles, + 'index': index, + 'ignored': ignored.map((e) => e).toList(), + }; +} + +/// openai is any OpenAI-compatible API +enum AiProviderKind { + openai('openai'), + anthropic('anthropic'), + ollama('ollama'); + + const AiProviderKind(this.value); + final String value; + + static AiProviderKind fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown AiProviderKind', value), + ); + + String toJson() => value; +} + +class AiProfileUsage { + const AiProfileUsage({ + required this.requests, + required this.inputTokens, + required this.outputTokens, + }); + + factory AiProfileUsage.fromJson(Map json) => AiProfileUsage( + requests: (json['requests'] as num).toInt(), + inputTokens: (json['inputTokens'] as num).toInt(), + outputTokens: (json['outputTokens'] as num).toInt(), + ); + + final int requests; + + final int inputTokens; + + final int outputTokens; + + Map toJson() => { + 'requests': requests, + 'inputTokens': inputTokens, + 'outputTokens': outputTokens, + }; +} + +class AiProfile { + const AiProfile({ + required this.id, + required this.workspace, + required this.name, + required this.kind, + required this.baseUrl, + required this.keySet, + required this.chatModel, + required this.embedModel, + required this.effort, + required this.enabled, + required this.position, + required this.usage, + required this.lastUsed, + required this.lastError, + required this.created, + }); + + factory AiProfile.fromJson(Map json) => AiProfile( + id: json['id'] as String, + workspace: json['workspace'] as String, + name: json['name'] as String, + kind: AiProviderKind.fromJson(json['kind'] as String), + baseUrl: json['baseUrl'] as String, + keySet: json['keySet'] as bool, + chatModel: json['chatModel'] as String, + embedModel: json['embedModel'] as String, + effort: json['effort'] as String, + enabled: json['enabled'] as bool, + position: (json['position'] as num).toInt(), + usage: AiProfileUsage.fromJson(json['usage'] as Map), + lastUsed: json['lastUsed'] as String, + lastError: json['lastError'] as String, + created: json['created'] as String, + ); + + final String id; + + /// Empty for an instance default + final String workspace; + + final String name; + + final AiProviderKind kind; + + /// Empty for the kind's default address + final String baseUrl; + + /// An API key is stored (keys are never returned) + final bool keySet; + + final String chatModel; + + /// Empty when the profile is not used for embeddings + final String embedModel; + + /// Anthropic effort level + final String effort; + + final bool enabled; + + final int position; + + final AiProfileUsage usage; + + final String lastUsed; + + final String lastError; + + final String created; + + Map toJson() => { + 'id': id, + 'workspace': workspace, + 'name': name, + 'kind': kind.toJson(), + 'baseUrl': baseUrl, + 'keySet': keySet, + 'chatModel': chatModel, + 'embedModel': embedModel, + 'effort': effort, + 'enabled': enabled, + 'position': position, + 'usage': usage.toJson(), + 'lastUsed': lastUsed, + 'lastError': lastError, + 'created': created, + }; +} + +enum AiProfileInputEffort { + none(''), + low('low'), + medium('medium'), + high('high'), + xhigh('xhigh'), + max('max'); + + const AiProfileInputEffort(this.value); + final String value; + + static AiProfileInputEffort fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown AiProfileInputEffort', value), + ); + + String toJson() => value; +} + +/// Creating needs name and kind; updating changes the fields that are set +class AiProfileInput { + const AiProfileInput({ + this.name, + this.kind, + this.baseUrl, + this.apiKey, + this.chatModel, + this.embedModel, + this.effort, + this.enabled, + }); + + factory AiProfileInput.fromJson(Map json) => AiProfileInput( + name: json['name'] == null ? null : json['name'] as String, + kind: json['kind'] == null + ? null + : AiProviderKind.fromJson(json['kind'] as String), + baseUrl: json['baseUrl'] == null ? null : json['baseUrl'] as String, + apiKey: json['apiKey'] == null ? null : json['apiKey'] as String, + chatModel: json['chatModel'] == null ? null : json['chatModel'] as String, + embedModel: json['embedModel'] == null + ? null + : json['embedModel'] as String, + effort: json['effort'] == null + ? null + : AiProfileInputEffort.fromJson(json['effort'] as String), + enabled: json['enabled'] == null ? null : json['enabled'] as bool, + ); + + final String? name; + + final AiProviderKind? kind; + + final String? baseUrl; + + /// Write-only; an empty string removes the key + final String? apiKey; + + final String? chatModel; + + final String? embedModel; + + final AiProfileInputEffort? effort; + + final bool? enabled; + + Map toJson() => { + 'name': ?name, + 'kind': ?kind?.toJson(), + 'baseUrl': ?baseUrl, + 'apiKey': ?apiKey, + 'chatModel': ?chatModel, + 'embedModel': ?embedModel, + 'effort': ?effort?.toJson(), + 'enabled': ?enabled, + }; +} + +class AiTestResult { + const AiTestResult({ + required this.ok, + required this.chat, + required this.embeddings, + required this.dimensions, + required this.latencyMs, + required this.error, + }); + + factory AiTestResult.fromJson(Map json) => AiTestResult( + ok: json['ok'] as bool, + chat: json['chat'] as String, + embeddings: json['embeddings'] as String, + dimensions: (json['dimensions'] as num).toInt(), + latencyMs: (json['latencyMs'] as num).toInt(), + error: json['error'] as String, + ); + + final bool ok; + + /// The model's reply + final String chat; + + final String embeddings; + + final int dimensions; + + final int latencyMs; + + final String error; + + Map toJson() => { + 'ok': ok, + 'chat': chat, + 'embeddings': embeddings, + 'dimensions': dimensions, + 'latencyMs': latencyMs, + 'error': error, + }; +} + +class AiIndexStatus { + const AiIndexStatus({ + required this.enabled, + required this.profile, + required this.model, + required this.pages, + required this.indexed, + required this.files, + required this.chunks, + required this.running, + required this.lastRun, + required this.lastError, + }); + + factory AiIndexStatus.fromJson(Map json) => AiIndexStatus( + enabled: json['enabled'] as bool, + profile: json['profile'] as String, + model: json['model'] as String, + pages: (json['pages'] as num).toInt(), + indexed: (json['indexed'] as num).toInt(), + files: (json['files'] as num).toInt(), + chunks: (json['chunks'] as num).toInt(), + running: json['running'] as bool, + lastRun: json['lastRun'] as String, + lastError: json['lastError'] as String, + ); + + final bool enabled; + + /// The profile vectors come from; empty when none has an embedding model + final String profile; + + final String model; + + /// Pages that can be indexed + final int pages; + + final int indexed; + + final int files; + + final int chunks; + + final bool running; + + final String lastRun; + + final String lastError; + + Map toJson() => { + 'enabled': enabled, + 'profile': profile, + 'model': model, + 'pages': pages, + 'indexed': indexed, + 'files': files, + 'chunks': chunks, + 'running': running, + 'lastRun': lastRun, + 'lastError': lastError, + }; +} + +class AiFile { + const AiFile({ + required this.id, + required this.name, + required this.size, + required this.chars, + required this.indexed, + required this.created, + }); + + factory AiFile.fromJson(Map json) => AiFile( + id: json['id'] as String, + name: json['name'] as String, + size: (json['size'] as num).toInt(), + chars: (json['chars'] as num).toInt(), + indexed: json['indexed'] as bool, + created: json['created'] as String, + ); + + final String id; + + final String name; + + final int size; + + final int chars; + + final bool indexed; + + final String created; + + Map toJson() => { + 'id': id, + 'name': name, + 'size': size, + 'chars': chars, + 'indexed': indexed, + 'created': created, + }; +} + +enum AiScope { + workspace('workspace'), + space('space'), + page('page'); + + const AiScope(this.value); + final String value; + + static AiScope fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown AiScope', value), + ); + + String toJson() => value; +} + +class AiSessionSummary { + const AiSessionSummary({ + required this.id, + required this.title, + required this.scope, + required this.scopeId, + required this.created, + required this.updated, + }); + + factory AiSessionSummary.fromJson(Map json) => + AiSessionSummary( + id: json['id'] as String, + title: json['title'] as String, + scope: AiScope.fromJson(json['scope'] as String), + scopeId: json['scopeId'] as String, + created: json['created'] as String, + updated: json['updated'] as String, + ); + + final String id; + + final String title; + + final AiScope scope; + + /// The space or page; empty for the workspace + final String scopeId; + + final String created; + + final String updated; + + Map toJson() => { + 'id': id, + 'title': title, + 'scope': scope.toJson(), + 'scopeId': scopeId, + 'created': created, + 'updated': updated, + }; +} + +class AiCitation { + const AiCitation({ + required this.n, + this.page, + this.block, + this.file, + required this.title, + required this.snippet, + }); + + factory AiCitation.fromJson(Map json) => AiCitation( + n: (json['n'] as num).toInt(), + page: json['page'] == null ? null : json['page'] as String, + block: json['block'] == null ? null : json['block'] as String, + file: json['file'] == null ? null : json['file'] as String, + title: json['title'] as String, + snippet: json['snippet'] as String, + ); + + /// The number the answer cites as [n] + final int n; + + final String? page; + + /// The cited block (link with #b-``) + final String? block; + + /// An extra file instead of a page + final String? file; + + final String title; + + final String snippet; + + Map toJson() => { + 'n': n, + 'page': ?page, + 'block': ?block, + 'file': ?file, + 'title': title, + 'snippet': snippet, + }; +} + +enum AiMessageRole { + user('user'), + assistant('assistant'); + + const AiMessageRole(this.value); + final String value; + + static AiMessageRole fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown AiMessageRole', value), + ); + + String toJson() => value; +} + +class AiMessage { + const AiMessage({ + required this.id, + required this.role, + required this.content, + this.citations, + this.error, + required this.created, + }); + + factory AiMessage.fromJson(Map json) => AiMessage( + id: json['id'] as String, + role: AiMessageRole.fromJson(json['role'] as String), + content: json['content'] as String, + citations: json['citations'] == null + ? null + : (json['citations'] as List) + .map((e) => AiCitation.fromJson(e as Map)) + .toList(), + error: json['error'] == null ? null : json['error'] as String, + created: json['created'] as String, + ); + + final String id; + + final AiMessageRole role; + + /// Markdown + final String content; + + final List? citations; + + /// Why the answer stopped + final String? error; + + final String created; + + Map toJson() => { + 'id': id, + 'role': role.toJson(), + 'content': content, + 'citations': ?citations?.map((e) => e.toJson()).toList(), + 'error': ?error, + 'created': created, + }; +} + +class AiSession { + const AiSession({ + required this.id, + required this.title, + required this.scope, + required this.scopeId, + required this.created, + required this.updated, + required this.workspace, + required this.messages, + }); + + factory AiSession.fromJson(Map json) => AiSession( + id: json['id'] as String, + title: json['title'] as String, + scope: AiScope.fromJson(json['scope'] as String), + scopeId: json['scopeId'] as String, + created: json['created'] as String, + updated: json['updated'] as String, + workspace: json['workspace'] as String, + messages: (json['messages'] as List) + .map((e) => AiMessage.fromJson(e as Map)) + .toList(), + ); + + final String id; + + final String title; + + final AiScope scope; + + /// The space or page; empty for the workspace + final String scopeId; + + final String created; + + final String updated; + + final String workspace; + + final List messages; + + Map toJson() => { + 'id': id, + 'title': title, + 'scope': scope.toJson(), + 'scopeId': scopeId, + 'created': created, + 'updated': updated, + 'workspace': workspace, + 'messages': messages.map((e) => e.toJson()).toList(), + }; +} + +class AiSessionInput { + const AiSessionInput({this.title, this.scope, this.scopeId}); + + factory AiSessionInput.fromJson(Map json) => AiSessionInput( + title: json['title'] == null ? null : json['title'] as String, + scope: json['scope'] == null + ? null + : AiScope.fromJson(json['scope'] as String), + scopeId: json['scopeId'] == null ? null : json['scopeId'] as String, + ); + + final String? title; + + final AiScope? scope; + + final String? scopeId; + + Map toJson() => { + 'title': ?title, + 'scope': ?scope?.toJson(), + 'scopeId': ?scopeId, + }; +} + +class AiForkInput { + const AiForkInput({this.message}); + + factory AiForkInput.fromJson(Map json) => AiForkInput( + message: json['message'] == null ? null : json['message'] as String, + ); + + /// The last message to copy; empty copies all + final String? message; + + Map toJson() => {'message': ?message}; +} + +enum AiWriteAction { + rewrite('rewrite'), + summarize('summarize'), + translate('translate'), + continue_('continue'), + shorter('shorter'), + longer('longer'), + fix('fix'), + custom('custom'); + + const AiWriteAction(this.value); + final String value; + + static AiWriteAction fromJson(String value) => values.firstWhere( + (e) => e.value == value, + orElse: () => throw FormatException('unknown AiWriteAction', value), + ); + + String toJson() => value; +} + +class AiWriteInput { + const AiWriteInput({ + required this.action, + required this.text, + this.before, + this.language, + this.instruction, + }); + + factory AiWriteInput.fromJson(Map json) => AiWriteInput( + action: AiWriteAction.fromJson(json['action'] as String), + text: json['text'] as String, + before: json['before'] == null ? null : json['before'] as String, + language: json['language'] == null ? null : json['language'] as String, + instruction: json['instruction'] == null + ? null + : json['instruction'] as String, + ); + + final AiWriteAction action; + + /// The selection + final String text; + + /// Text in front of the selection (continue) + final String? before; + + /// Target language (translate) + final String? language; + + /// What to do (custom) + final String? instruction; + + Map toJson() => { + 'action': action.toJson(), + 'text': text, + 'before': ?before, + 'language': ?language, + 'instruction': ?instruction, + }; +} diff --git a/Phone-App/tool/generate_api.dart b/Phone-App/tool/generate_api.dart index 23d130b..8a0b27e 100644 --- a/Phone-App/tool/generate_api.dart +++ b/Phone-App/tool/generate_api.dart @@ -337,6 +337,10 @@ class _Generator { 'switch', 'in', 'is', + 'continue', + 'break', + 'return', + 'case', }; static String _ident(String s) { diff --git a/Server/admin/src/App.vue b/Server/admin/src/App.vue index 9a8d2bf..bec3dfe 100644 --- a/Server/admin/src/App.vue +++ b/Server/admin/src/App.vue @@ -26,6 +26,7 @@ const nav = computed(() => [ { to: "/branding", label: t("nav.branding") }, { to: "/storage", label: t("nav.storage") }, { to: "/email", label: t("nav.email") }, + { to: "/ai", label: t("nav.ai") }, { to: "/maintenance", label: t("nav.maintenance") }, ] : []), diff --git a/Server/admin/src/locales/de.json b/Server/admin/src/locales/de.json index e953a97..b342578 100644 --- a/Server/admin/src/locales/de.json +++ b/Server/admin/src/locales/de.json @@ -48,7 +48,8 @@ "branding": "Erscheinungsbild", "storage": "Speicher", "email": "E-Mail", - "maintenance": "Wartung" + "maintenance": "Wartung", + "ai": "KI" }, "shell": { "badge": "Admin", @@ -268,5 +269,44 @@ "failed": "Fehlgeschlagen", "ok": "OK", "runNow": "Jetzt ausführen" + }, + "ai": { + "title": "KI", + "hint": "Standard-KI-Anbieter für alle Arbeitsbereiche. Arbeitsbereiche versuchen zuerst ihre eigenen Anbieter, dann diese, sofern sie das nicht ausschalten.", + "keyNote": "Schlüssel werden mit DOCWELL_SECRET_KEY verschlüsselt gespeichert (ohne diese Variable mit einem aus dem PocketBase-Passwort abgeleiteten Schlüssel). Wird dieses Geheimnis geändert, müssen die Schlüssel neu eingegeben werden. Anbieter des Servers dürfen lokale Adressen erreichen, etwa ein Ollama auf demselben Rechner.", + "profiles": "Standardanbieter", + "total": "Insgesamt {requests} Anfragen, {input} Tokens hinein, {output} heraus", + "kinds": { + "openai": "OpenAI-kompatibel", + "anthropic": "Anthropic", + "ollama": "Ollama" + }, + "embeddings": "Embeddings", + "keySet": "Schlüssel gespeichert", + "noKey": "kein Schlüssel", + "usage": "{requests} Anfragen, {input} Tokens hinein, {output} heraus", + "test": "Testen", + "disable": "Ausschalten", + "enable": "Einschalten", + "testOk": "Funktioniert ({ms} ms).", + "lastError": "Letzter Fehler: {error}", + "none": "Keine Standardanbieter. Arbeitsbereiche können trotzdem eigene hinzufügen.", + "deleteConfirm": "{name} löschen?", + "kind": "Anbieter", + "name": "Name", + "baseUrl": "Adresse", + "baseUrlDefault": { + "openai": "https://api.openai.com/v1", + "anthropic": "https://api.anthropic.com", + "ollama": "http://localhost:11434" + }, + "apiKey": "API-Schlüssel", + "chatModel": "Chat-Modell", + "embedModel": "Embedding-Modell", + "effort": "Aufwand", + "effortDefault": "Standard des Modells", + "add": "Anbieter hinzufügen", + "mcpTitle": "MCP-Server", + "mcpHint": "KI-Agenten und Werkzeuge verbinden sich mit /mcp auf diesem Server über ein persönliches API-Token (lesen oder lesen und schreiben). Sie handeln als Besitzer des Tokens, mit dessen Rechten." } } diff --git a/Server/admin/src/locales/en.json b/Server/admin/src/locales/en.json index 750ae3d..7c6840c 100644 --- a/Server/admin/src/locales/en.json +++ b/Server/admin/src/locales/en.json @@ -48,7 +48,8 @@ "branding": "Branding", "storage": "Storage", "email": "Email", - "maintenance": "Maintenance" + "maintenance": "Maintenance", + "ai": "AI" }, "shell": { "badge": "Admin", @@ -268,5 +269,44 @@ "failed": "Failed", "ok": "OK", "runNow": "Run now" + }, + "ai": { + "title": "AI", + "hint": "Default AI providers for every workspace. Workspaces try their own providers first, then these, unless they turn them off.", + "keyNote": "Keys are stored encrypted with DOCWELL_SECRET_KEY (or a key derived from the PocketBase password when it is not set). Changing that secret means entering the keys again. Instance providers may reach local addresses, such as an Ollama on the same host.", + "profiles": "Default providers", + "total": "{requests} requests, {input} tokens in, {output} out in total", + "kinds": { + "openai": "OpenAI-compatible", + "anthropic": "Anthropic", + "ollama": "Ollama" + }, + "embeddings": "embeddings", + "keySet": "key stored", + "noKey": "no key", + "usage": "{requests} requests, {input} tokens in, {output} out", + "test": "Test", + "disable": "Turn off", + "enable": "Turn on", + "testOk": "Works ({ms} ms).", + "lastError": "Last error: {error}", + "none": "No default providers. Workspaces can still add their own.", + "deleteConfirm": "Delete {name}?", + "kind": "Provider", + "name": "Name", + "baseUrl": "Address", + "baseUrlDefault": { + "openai": "https://api.openai.com/v1", + "anthropic": "https://api.anthropic.com", + "ollama": "http://localhost:11434" + }, + "apiKey": "API key", + "chatModel": "Chat model", + "embedModel": "Embedding model", + "effort": "Effort", + "effortDefault": "Model default", + "add": "Add a provider", + "mcpTitle": "MCP server", + "mcpHint": "AI agents and tools connect to /mcp on this server with a personal API token (read, or read and write). They act as the token's owner, with that person's rights." } } diff --git a/Server/admin/src/locales/es.json b/Server/admin/src/locales/es.json index 1c102d8..96df0d1 100644 --- a/Server/admin/src/locales/es.json +++ b/Server/admin/src/locales/es.json @@ -48,7 +48,8 @@ "branding": "Apariencia", "storage": "Almacenamiento", "email": "Correo", - "maintenance": "Mantenimiento" + "maintenance": "Mantenimiento", + "ai": "IA" }, "shell": { "badge": "Admin", @@ -268,5 +269,44 @@ "failed": "Fallida", "ok": "OK", "runNow": "Ejecutar ahora" + }, + "ai": { + "title": "IA", + "hint": "Proveedores de IA predeterminados para todos los espacios de trabajo. Cada espacio prueba primero los suyos y luego estos, salvo que lo desactive.", + "keyNote": "Las claves se guardan cifradas con DOCWELL_SECRET_KEY (o, si no está definida, con una clave derivada de la contraseña de PocketBase). Si cambias ese secreto, hay que volver a introducir las claves. Los proveedores del servidor pueden usar direcciones locales, como un Ollama en la misma máquina.", + "profiles": "Proveedores predeterminados", + "total": "En total {requests} solicitudes, {input} tokens de entrada, {output} de salida", + "kinds": { + "openai": "Compatible con OpenAI", + "anthropic": "Anthropic", + "ollama": "Ollama" + }, + "embeddings": "embeddings", + "keySet": "clave guardada", + "noKey": "sin clave", + "usage": "{requests} solicitudes, {input} tokens de entrada, {output} de salida", + "test": "Probar", + "disable": "Desactivar", + "enable": "Activar", + "testOk": "Funciona ({ms} ms).", + "lastError": "Último error: {error}", + "none": "No hay proveedores predeterminados. Los espacios de trabajo pueden añadir los suyos.", + "deleteConfirm": "¿Eliminar {name}?", + "kind": "Proveedor", + "name": "Nombre", + "baseUrl": "Dirección", + "baseUrlDefault": { + "openai": "https://api.openai.com/v1", + "anthropic": "https://api.anthropic.com", + "ollama": "http://localhost:11434" + }, + "apiKey": "Clave de API", + "chatModel": "Modelo de chat", + "embedModel": "Modelo de embeddings", + "effort": "Esfuerzo", + "effortDefault": "El del modelo", + "add": "Añadir un proveedor", + "mcpTitle": "Servidor MCP", + "mcpHint": "Los agentes y herramientas de IA se conectan a /mcp en este servidor con un token de API personal (lectura, o lectura y escritura). Actúan como el dueño del token, con sus permisos." } } diff --git a/Server/admin/src/locales/fr.json b/Server/admin/src/locales/fr.json index df31ac0..5d4b407 100644 --- a/Server/admin/src/locales/fr.json +++ b/Server/admin/src/locales/fr.json @@ -48,7 +48,8 @@ "branding": "Apparence", "storage": "Stockage", "email": "E-mail", - "maintenance": "Maintenance" + "maintenance": "Maintenance", + "ai": "IA" }, "shell": { "badge": "Admin", @@ -268,5 +269,44 @@ "failed": "En échec", "ok": "OK", "runNow": "Lancer maintenant" + }, + "ai": { + "title": "IA", + "hint": "Fournisseurs d’IA par défaut pour tous les espaces de travail. Les espaces de travail essaient d’abord les leurs, puis ceux-ci, sauf s’ils le désactivent.", + "keyNote": "Les clés sont chiffrées avec DOCWELL_SECRET_KEY (ou, sans cette variable, avec une clé dérivée du mot de passe PocketBase). Changer ce secret oblige à saisir les clés à nouveau. Les fournisseurs du serveur peuvent joindre des adresses locales, comme un Ollama sur la même machine.", + "profiles": "Fournisseurs par défaut", + "total": "Au total {requests} requêtes, {input} jetons en entrée, {output} en sortie", + "kinds": { + "openai": "Compatible OpenAI", + "anthropic": "Anthropic", + "ollama": "Ollama" + }, + "embeddings": "embeddings", + "keySet": "clé enregistrée", + "noKey": "aucune clé", + "usage": "{requests} requêtes, {input} jetons en entrée, {output} en sortie", + "test": "Tester", + "disable": "Désactiver", + "enable": "Activer", + "testOk": "Fonctionne ({ms} ms).", + "lastError": "Dernière erreur : {error}", + "none": "Aucun fournisseur par défaut. Les espaces de travail peuvent toujours ajouter les leurs.", + "deleteConfirm": "Supprimer {name} ?", + "kind": "Fournisseur", + "name": "Nom", + "baseUrl": "Adresse", + "baseUrlDefault": { + "openai": "https://api.openai.com/v1", + "anthropic": "https://api.anthropic.com", + "ollama": "http://localhost:11434" + }, + "apiKey": "Clé d’API", + "chatModel": "Modèle de chat", + "embedModel": "Modèle d’embeddings", + "effort": "Effort", + "effortDefault": "Valeur du modèle", + "add": "Ajouter un fournisseur", + "mcpTitle": "Serveur MCP", + "mcpHint": "Les agents et outils d’IA se connectent à /mcp sur ce serveur avec un jeton d’API personnel (lecture, ou lecture et écriture). Ils agissent comme le propriétaire du jeton, avec ses droits." } } diff --git a/Server/admin/src/locales/pl.json b/Server/admin/src/locales/pl.json index c2ec77f..9f4dc64 100644 --- a/Server/admin/src/locales/pl.json +++ b/Server/admin/src/locales/pl.json @@ -48,7 +48,8 @@ "branding": "Wygląd", "storage": "Pliki", "email": "E-mail", - "maintenance": "Konserwacja" + "maintenance": "Konserwacja", + "ai": "AI" }, "shell": { "badge": "Admin", @@ -268,5 +269,44 @@ "failed": "Błąd", "ok": "OK", "runNow": "Uruchom teraz" + }, + "ai": { + "title": "AI", + "hint": "Domyślni dostawcy AI dla wszystkich obszarów roboczych. Obszary najpierw próbują własnych dostawców, potem tych, chyba że to wyłączą.", + "keyNote": "Klucze są szyfrowane za pomocą DOCWELL_SECRET_KEY (a bez tej zmiennej kluczem wyprowadzonym z hasła PocketBase). Zmiana tego sekretu oznacza ponowne wpisanie kluczy. Dostawcy serwera mogą łączyć się z adresami lokalnymi, np. z Ollamą na tym samym komputerze.", + "profiles": "Domyślni dostawcy", + "total": "Łącznie zapytania: {requests}, tokeny wejściowe: {input}, wyjściowe: {output}", + "kinds": { + "openai": "Zgodny z OpenAI", + "anthropic": "Anthropic", + "ollama": "Ollama" + }, + "embeddings": "embeddingi", + "keySet": "klucz zapisany", + "noKey": "brak klucza", + "usage": "Zapytania: {requests}, tokeny wejściowe: {input}, wyjściowe: {output}", + "test": "Testuj", + "disable": "Wyłącz", + "enable": "Włącz", + "testOk": "Działa ({ms} ms).", + "lastError": "Ostatni błąd: {error}", + "none": "Brak domyślnych dostawców. Obszary robocze mogą dodać własnych.", + "deleteConfirm": "Usunąć {name}?", + "kind": "Dostawca", + "name": "Nazwa", + "baseUrl": "Adres", + "baseUrlDefault": { + "openai": "https://api.openai.com/v1", + "anthropic": "https://api.anthropic.com", + "ollama": "http://localhost:11434" + }, + "apiKey": "Klucz API", + "chatModel": "Model czatu", + "embedModel": "Model embeddingów", + "effort": "Wysiłek", + "effortDefault": "Domyślny modelu", + "add": "Dodaj dostawcę", + "mcpTitle": "Serwer MCP", + "mcpHint": "Agenci i narzędzia AI łączą się z /mcp na tym serwerze za pomocą osobistego tokenu API (odczyt albo odczyt i zapis). Działają jako właściciel tokenu, z jego uprawnieniami." } } diff --git a/Server/admin/src/main.ts b/Server/admin/src/main.ts index 1ce4f9d..1a89c42 100644 --- a/Server/admin/src/main.ts +++ b/Server/admin/src/main.ts @@ -32,6 +32,7 @@ const router = createRouter({ component: () => import("./views/StorageView.vue"), meta: { superadmin: true }, }, + { path: "/ai", name: "ai", component: () => import("./views/AiView.vue"), meta: { superadmin: true } }, { path: "/email", name: "email", component: () => import("./views/EmailView.vue"), meta: { superadmin: true } }, { path: "/security", name: "security", component: () => import("./views/SecurityView.vue") }, { diff --git a/Server/admin/src/views/AiView.vue b/Server/admin/src/views/AiView.vue new file mode 100644 index 0000000..0ae1089 --- /dev/null +++ b/Server/admin/src/views/AiView.vue @@ -0,0 +1,244 @@ + + + + diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go index d9670d3..c86e3d5 100644 --- a/Server/cmd/docwell-server/main.go +++ b/Server/cmd/docwell-server/main.go @@ -17,6 +17,7 @@ import ( "time" "docwell/server/internal/admin" + "docwell/server/internal/ai" "docwell/server/internal/audit" "docwell/server/internal/auth" "docwell/server/internal/collab" @@ -157,6 +158,21 @@ func run(log *slog.Logger) error { func(ctx context.Context) error { return auditLog.Prune(ctx, time.Duration(days)*24*time.Hour) }) go reg.Every(indexCtx, "audit.prune", 24*time.Hour) } + // AI (ADR-15): provider keys are sealed with DOCWELL_SECRET_KEY, or with a + // key derived from the PocketBase password when it is not set. + secret := cfg.SecretKey + if secret == "" { + secret = "pb:" + cfg.PocketBasePassword + } + aiSvc, err := ai.New(db, dirSvc, log, ai.Options{Secret: secret, DataDir: cfg.DataDir, AllowLocal: cfg.WebhooksAllowLocal}) + if err != nil { + return err + } + defer aiSvc.Close() + aiSvc.Track(reg.Track) + reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second, + func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) }) + go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute) dirSvc.SetPublicURL(cfg.PublicURL) dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20) dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string { @@ -182,6 +198,7 @@ func run(log *slog.Logger) error { Audit: auditLog, Previews: unfurl.New(), Push: pushSvc, + AI: aiSvc, Admin: admin.Handler("/admin"), Log: log, }), diff --git a/Server/go.mod b/Server/go.mod index dc38b80..9e5d8fb 100644 --- a/Server/go.mod +++ b/Server/go.mod @@ -17,6 +17,8 @@ require ( require ( github.com/RoaringBitmap/roaring/v2 v2.14.5 // indirect + github.com/anthropics/anthropic-sdk-go/v2 v2.9.0 // indirect + github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/bits-and-blooms/bitset v1.24.2 // indirect github.com/blevesearch/bleve_index_api v1.4.1 // indirect github.com/blevesearch/geo v0.2.6 // indirect @@ -37,12 +39,16 @@ require ( github.com/blevesearch/zapx/v16 v16.3.4 // indirect github.com/blevesearch/zapx/v17 v17.2.3 // indirect github.com/boombuler/barcode v1.0.1 // indirect + github.com/buger/jsonparser v1.1.2 // indirect github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect github.com/getkin/kin-openapi v0.142.0 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.23.1 // indirect github.com/go-openapi/swag/jsonname v0.26.0 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/invopop/jsonschema v0.14.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect @@ -50,12 +56,23 @@ require ( github.com/oapi-codegen/oapi-codegen/v2 v2.8.1 // indirect github.com/oasdiff/yaml v0.1.1 // indirect github.com/oasdiff/yaml3 v0.0.14 // indirect + github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect github.com/speakeasy-api/jsonpath v0.6.3 // indirect github.com/speakeasy-api/openapi v1.24.0 // indirect + github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect + github.com/tidwall/gjson v1.18.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/sjson v1.2.5 // indirect github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect go.etcd.io/bbolt v1.4.0 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/otel v1.33.0 // indirect + go.opentelemetry.io/otel/metric v1.33.0 // indirect + go.opentelemetry.io/otel/trace v1.33.0 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect + go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect diff --git a/Server/go.sum b/Server/go.sum index 9aafaea..23ec19b 100644 --- a/Server/go.sum +++ b/Server/go.sum @@ -1,5 +1,9 @@ github.com/RoaringBitmap/roaring/v2 v2.14.5 h1:ckd0o545JqDPeVJDgeFoaM21eBixUnlWfYgjE5VnyWw= github.com/RoaringBitmap/roaring/v2 v2.14.5/go.mod h1:eq4wdNXxtJIS/oikeCzdX1rBzek7ANzbth041hrU8Q4= +github.com/anthropics/anthropic-sdk-go/v2 v2.9.0 h1:kn8rCJlgcOTd5/yjofmTuUdfMRP14OL9vDS4tsdJqZg= +github.com/anthropics/anthropic-sdk-go/v2 v2.9.0/go.mod h1:LAOInMKgn6reTIrPvKXa5weyqzxsJkxSBuzhnxzukpQ= +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/bits-and-blooms/bitset v1.24.2 h1:M7/NzVbsytmtfHbumG+K2bremQPMJuqv1JD3vOaFxp0= github.com/bits-and-blooms/bitset v1.24.2/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8= github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ= @@ -43,6 +47,8 @@ github.com/blevesearch/zapx/v17 v17.2.3/go.mod h1:r7mb4QWbDQSkbAnOjCb9iCfkcrzajB github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/boombuler/barcode v1.0.1 h1:NDBbPmhS+EqABEs5Kg3n/5ZNjy73Pz7SIV+KCeqyXcs= github.com/boombuler/barcode v1.0.1/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= +github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -62,6 +68,11 @@ github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/getkin/kin-openapi v0.142.0 h1:izj0vBdFprMhitfzaX8sTqztsEQyvwhssBoB6n8NO7w= github.com/getkin/kin-openapi v0.142.0/go.mod h1:3BH9M9XDe/y9M5DSvEocVYAYq1w0qrhJHjC/vZi0AaY= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= @@ -94,6 +105,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= +github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -133,6 +146,8 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= +github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -148,6 +163,8 @@ github.com/speakeasy-api/jsonpath v0.6.3 h1:c+QPwzAOdrWvzycuc9HFsIZcxKIaWcNpC+xh github.com/speakeasy-api/jsonpath v0.6.3/go.mod h1:2cXloNuQ+RSXi5HTRaeBh7JEmjRXTiaKpFTdZiL7URI= github.com/speakeasy-api/openapi v1.24.0 h1:opoD27rupX7zBVPq1HkIGLeMOzNNA7JalhYP8q34i04= github.com/speakeasy-api/openapi v1.24.0/go.mod h1:g3+dIMe0AYgbbGvnlQZqesmjAVWSm9BmsjLevnefQrg= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -156,6 +173,16 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -163,8 +190,18 @@ github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI= github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk= go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= +go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= +go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= +go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= +go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= +go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= +go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= diff --git a/Server/internal/ai/ai_test.go b/Server/internal/ai/ai_test.go new file mode 100644 index 0000000..25d39ea --- /dev/null +++ b/Server/internal/ai/ai_test.go @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "docwell/server/internal/access" +) + +func TestSealerRoundTrip(t *testing.T) { + s := newSealer("secret") + sealed := s.seal("sk-test") + if sealed == "sk-test" || !strings.HasPrefix(sealed, "v1:") { + t.Fatalf("not sealed: %q", sealed) + } + if got, err := s.open(sealed); err != nil || got != "sk-test" { + t.Fatalf("open = %q, %v", got, err) + } + if _, err := newSealer("other").open(sealed); err == nil { + t.Fatal("another secret opened the key") + } + if s.seal("") != "" { + t.Fatal("an empty key should stay empty") + } +} + +func TestChunkDoc(t *testing.T) { + long := strings.Repeat("word ", 400) + doc := `{"type":"doc","content":[ + {"type":"paragraph","attrs":{"blockId":"intro1"},"content":[{"type":"text","text":"Intro text."}]}, + {"type":"heading","attrs":{"level":2,"blockId":"setup1"},"content":[{"type":"text","text":"Setup"}]}, + {"type":"bulletList","content":[ + {"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]}]}, + {"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"two"}]}]}]}, + {"type":"paragraph","content":[{"type":"text","text":"` + long + `"}]} + ]}` + pieces := chunkDoc("Guide", json.RawMessage(doc)) + if len(pieces) < 3 { + t.Fatalf("want at least 3 pieces, got %d: %+v", len(pieces), pieces) + } + if pieces[0].Block != "intro1" || pieces[0].Text != "Intro text." { + t.Errorf("first piece = %+v", pieces[0]) + } + if pieces[1].Block != "setup1" || !strings.Contains(pieces[1].Text, "one\ntwo") { + t.Errorf("heading piece = %+v", pieces[1]) + } + if !strings.HasPrefix(pieces[1].Embed, "Guide › Setup") { + t.Errorf("embed text lacks its context: %q", pieces[1].Embed[:30]) + } + for _, p := range pieces { + if len([]rune(p.Text)) > chunkSize*3/2 { + t.Errorf("piece too long: %d", len([]rune(p.Text))) + } + } +} + +func TestStoreSearch(t *testing.T) { + st, err := OpenStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer st.Close() + vec := func(x, y float32) []float32 { return normalize([]float32{x, y}) } + if err := st.Put("ws1", "page/a", "h1", []Chunk{ + {Page: "a", Space: "s1", Title: "A", Text: "east", Vector: vec(1, 0)}, + {Page: "a", Space: "s1", Title: "A", Text: "north", Vector: vec(0, 1)}, + }); err != nil { + t.Fatal(err) + } + if err := st.Put("ws1", "page/b", "h2", []Chunk{{Page: "b", Space: "s2", Title: "B", Text: "north-east", Vector: vec(1, 1)}}); err != nil { + t.Fatal(err) + } + hits, err := st.Search("ws1", vec(0, 1), 2, nil) + if err != nil || len(hits) != 2 { + t.Fatalf("hits = %v, %v", hits, err) + } + if hits[0].Text != "north" || hits[1].Text != "north-east" || hits[0].Source != "page/a" { + t.Errorf("order = %q, %q (%s)", hits[0].Text, hits[1].Text, hits[0].Source) + } + only, _ := st.Search("ws1", vec(0, 1), 5, func(c Chunk) bool { return c.Space == "s2" }) + if len(only) != 1 || only[0].Page != "b" { + t.Errorf("filter = %+v", only) + } + if h, _ := st.Hash("ws1", "page/a"); h != "h1" { + t.Errorf("hash = %q", h) + } + // Replacing a source drops its old chunks. + _ = st.Put("ws1", "page/a", "h3", []Chunk{{Page: "a", Space: "s1", Text: "only", Vector: vec(1, 0)}}) + pages, _, chunks, _ := st.Counts("ws1") + if pages != 2 || chunks != 2 { + t.Errorf("counts = %d pages, %d chunks", pages, chunks) + } + _ = st.Drop("ws1", "page/b") + if src, _ := st.Sources("ws1"); len(src) != 1 { + t.Errorf("sources = %v", src) + } + _ = st.DropWorkspace("ws1") + if m, _ := st.Meta("ws1"); m.Model != "" { + t.Error("meta survived dropping the workspace") + } +} + +func TestReadSSE(t *testing.T) { + var got []string + err := readSSE(strings.NewReader("event: x\ndata: one\n\ndata: two\ndata: more\n\n: comment\n\ndata: [DONE]\n\ndata: after\n\n"), func(d string) error { + if d == "[DONE]" { + return io.EOF + } + got = append(got, d) + return nil + }) + if err != nil || len(got) != 2 || got[1] != "two\nmore" { + t.Fatalf("got %q, %v", got, err) + } +} + +func TestOpenAIDriver(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer k" { + w.WriteHeader(401) + _, _ = io.WriteString(w, `{"error":{"message":"bad key"}}`) + return + } + switch r.URL.Path { + case "/v1/chat/completions": + w.Header().Set("Content-Type", "text/event-stream") + for _, d := range []string{"Hel", "lo"} { + fmt.Fprintf(w, "data: {\"choices\":[{\"delta\":{\"content\":%q}}]}\n\n", d) + } + _, _ = io.WriteString(w, "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":2}}\n\ndata: [DONE]\n\n") + case "/v1/embeddings": + _, _ = io.WriteString(w, `{"data":[{"index":1,"embedding":[0,1]},{"index":0,"embedding":[1,0]}],"usage":{"prompt_tokens":3}}`) + } + })) + defer srv.Close() + p, _ := NewProvider(KindOpenAI, srv.URL+"/v1/", "k", srv.Client()) + var out strings.Builder + u, err := p.Chat(context.Background(), ChatRequest{Model: "m", Messages: []Message{{"user", "hi"}}}, func(d string) { out.WriteString(d) }) + if err != nil || out.String() != "Hello" || u.InputTokens != 7 || u.OutputTokens != 2 { + t.Fatalf("chat = %q %+v %v", out.String(), u, err) + } + vecs, _, err := p.Embed(context.Background(), "e", []string{"a", "b"}) + if err != nil || vecs[0][0] != 1 || vecs[1][1] != 1 { + t.Fatalf("embed = %v %v", vecs, err) + } + bad, _ := NewProvider(KindOpenAI, srv.URL+"/v1", "wrong", srv.Client()) + _, err = bad.Chat(context.Background(), ChatRequest{Model: "m"}, func(string) {}) + var pe *ProviderError + if !asProviderError(err, &pe) || pe.Status != 401 || pe.Message != "bad key" { + t.Fatalf("error = %v", err) + } +} + +func asProviderError(err error, out **ProviderError) bool { + pe, ok := err.(*ProviderError) + *out = pe + return ok +} + +func TestOllamaDriver(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/chat": + _, _ = io.WriteString(w, `{"message":{"content":"Hi"},"done":false}`+"\n"+`{"message":{"content":" there"},"done":false}`+"\n"+`{"done":true,"prompt_eval_count":5,"eval_count":2}`+"\n") + case "/api/embed": + _, _ = io.WriteString(w, `{"embeddings":[[0.5,0.5]]}`) + } + })) + defer srv.Close() + p, _ := NewProvider(KindOllama, srv.URL, "", srv.Client()) + var out strings.Builder + u, err := p.Chat(context.Background(), ChatRequest{Model: "llama"}, func(d string) { out.WriteString(d) }) + if err != nil || out.String() != "Hi there" || u.OutputTokens != 2 { + t.Fatalf("chat = %q %+v %v", out.String(), u, err) + } + if v, _, err := p.Embed(context.Background(), "e", []string{"x"}); err != nil || len(v[0]) != 2 { + t.Fatalf("embed = %v %v", v, err) + } +} + +func TestRankPieces(t *testing.T) { + pieces := []piece{{Text: "cats and dogs"}, {Text: "invoice approval steps"}, {Text: "lunch"}, {Text: "approval of an invoice by finance"}} + got := rankPieces(pieces, "How does invoice approval work?", 2) + if len(got) != 2 || got[0].Text != "invoice approval steps" || got[1].Text != "approval of an invoice by finance" { + t.Fatalf("got %+v", got) + } +} + +func TestMCPProtocol(t *testing.T) { + s := &Service{log: slog.New(slog.NewTextHandler(io.Discard, nil))} + c := access.Caller{ID: "u1"} + call := func(write bool, body string) map[string]any { + t.Helper() + raw, err := s.MCP(context.Background(), c, write, []byte(body), nil) + if err != nil { + t.Fatal(err) + } + if raw == nil { + return nil + } + var out map[string]any + if err := json.Unmarshal(raw, &out); err != nil { + t.Fatalf("%s: %v", raw, err) + } + return out + } + init := call(false, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}`) + res := init["result"].(map[string]any) + if res["protocolVersion"] != "2025-06-18" { + t.Errorf("version = %v", res["protocolVersion"]) + } + if call(false, `{"jsonrpc":"2.0","method":"notifications/initialized"}`) != nil { + t.Error("a notification got an answer") + } + names := func(write bool) []string { + r := call(write, `{"jsonrpc":"2.0","id":2,"method":"tools/list"}`)["result"].(map[string]any) + var out []string + for _, tool := range r["tools"].([]any) { + out = append(out, tool.(map[string]any)["name"].(string)) + } + return out + } + if read := strings.Join(names(false), ","); strings.Contains(read, "update_page") || !strings.Contains(read, "read_page") { + t.Errorf("read tools = %s", read) + } + if write := strings.Join(names(true), ","); !strings.Contains(write, "create_page") { + t.Errorf("write tools = %s", write) + } + denied := call(false, `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"update_page","arguments":{}}}`) + if denied["error"] == nil { + t.Error("a read token could call a write tool") + } + missing := call(false, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"read_page","arguments":{}}}`) + if r := missing["result"].(map[string]any); r["isError"] != true { + t.Errorf("missing argument = %v", r) + } + if call(false, `{"jsonrpc":"2.0","id":5,"method":"nope"}`)["error"] == nil { + t.Error("unknown method answered") + } +} diff --git a/Server/internal/ai/anthropic.go b/Server/internal/ai/anthropic.go new file mode 100644 index 0000000..90e21a5 --- /dev/null +++ b/Server/internal/ai/anthropic.go @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "errors" + "net/http" + "strings" + + "github.com/anthropics/anthropic-sdk-go/v2" + "github.com/anthropics/anthropic-sdk-go/v2/option" +) + +// DefaultAnthropicModel is offered for new Anthropic profiles. +const DefaultAnthropicModel = "claude-opus-5-5" + +type anthropicProvider struct { + client anthropic.Client + // official is true for api.anthropic.com, where server-side refusal + // fallbacks exist; gateways and proxies may not accept the field. + official bool +} + +func newAnthropic(base, key string, client *http.Client) *anthropicProvider { + opts := []option.RequestOption{ + option.WithHTTPClient(client), + option.WithMaxRetries(1), + option.WithBaseURL(base + "/"), + } + if key != "" { + opts = append(opts, option.WithAPIKey(key)) + } + return &anthropicProvider{ + client: anthropic.NewClient(opts...), + official: strings.HasPrefix(base, "https://api.anthropic.com"), + } +} + +// fallbackModels are the models with the server-side refusal fallback. +var fallbackModels = []string{"claude-fable-5", "claude-opus-5", "claude-sonnet-5-5"} + +func hasFallback(model string) bool { + for _, p := range fallbackModels { + if strings.HasPrefix(model, p) { + return true + } + } + return false +} + +func (p *anthropicProvider) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) { + maxTokens := int64(req.MaxTokens) + if maxTokens <= 0 { + maxTokens = 16000 + } + params := anthropic.BetaMessageNewParams{ + Model: anthropic.Model(req.Model), + MaxTokens: maxTokens, + } + if req.System != "" { + params.System = []anthropic.BetaTextBlockParam{{Text: req.System}} + } + for _, m := range req.Messages { + block := anthropic.NewBetaTextBlock(m.Content) + if m.Role == "assistant" { + params.Messages = append(params.Messages, anthropic.BetaMessageParam{ + OfAssistant: &anthropic.BetaAssistantMessageParam{Content: []anthropic.BetaContentBlockParamUnion{block}}, + }) + } else { + params.Messages = append(params.Messages, anthropic.NewBetaUserMessage(block)) + } + } + if req.Effort != "" { + params.OutputConfig = anthropic.BetaOutputConfigParam{Effort: anthropic.BetaOutputConfigEffort(req.Effort)} + } + if p.official && hasFallback(req.Model) { + params.Betas = []anthropic.AnthropicBeta{anthropic.AnthropicBetaServerSideFallback2026_07_01} + params.Fallbacks = anthropic.BetaFallbacksParamOfDefault() + } + + stream := p.client.Beta.Messages.NewStreaming(ctx, params) + defer stream.Close() + msg := anthropic.BetaMessage{} + for stream.Next() { + ev := stream.Current() + _ = msg.Accumulate(ev) + if d, ok := ev.AsAny().(anthropic.BetaRawContentBlockDeltaEvent); ok { + if t, ok := d.Delta.AsAny().(anthropic.BetaTextDelta); ok && t.Text != "" { + onDelta(t.Text) + } + } + } + usage := Usage{InputTokens: int(msg.Usage.InputTokens + msg.Usage.CacheReadInputTokens + msg.Usage.CacheCreationInputTokens), OutputTokens: int(msg.Usage.OutputTokens)} + if err := stream.Err(); err != nil { + var apiErr *anthropic.Error + if errors.As(err, &apiErr) { + return usage, &ProviderError{Status: apiErr.StatusCode, Message: anthropicMessage(apiErr)} + } + return usage, err + } + if msg.StopReason == anthropic.BetaStopReasonRefusal { + return usage, ErrRefused + } + return usage, nil +} + +func anthropicMessage(e *anthropic.Error) string { + raw := e.RawJSON() + if i := strings.Index(raw, `"message":"`); i >= 0 { + rest := raw[i+len(`"message":"`):] + if j := strings.Index(rest, `"`); j >= 0 { + return rest[:j] + } + } + return http.StatusText(e.StatusCode) +} + +func (p *anthropicProvider) Embed(context.Context, string, []string) ([][]float32, Usage, error) { + return nil, Usage{}, ErrNoEmbeddings +} diff --git a/Server/internal/ai/chat.go b/Server/internal/ai/chat.go new file mode 100644 index 0000000..cfd08e6 --- /dev/null +++ b/Server/internal/ai/chat.go @@ -0,0 +1,568 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "slices" + "sort" + "strings" + "time" + "unicode" + "unicode/utf8" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/directory" + "docwell/server/internal/store/pocketbase" +) + +// ---- Chat sessions ----------------------------------------------------------------- + +// Scopes a session can ask about. +const ( + ScopeWorkspace = "workspace" + ScopeSpace = "space" + ScopePage = "page" +) + +// Citation is a numbered source of an answer: a page (and block in it) or +// an extra file. +type Citation struct { + N int `json:"n"` + Page string `json:"page,omitempty"` + Block string `json:"block,omitempty"` + File string `json:"file,omitempty"` + Title string `json:"title"` + Snippet string `json:"snippet"` + text string +} + +// ChatMessage is one turn of a session. +type ChatMessage struct { + ID string `json:"id"` + Role string `json:"role"` + Content string `json:"content"` + Citations []Citation `json:"citations,omitempty"` + Error string `json:"error,omitempty"` + Created string `json:"created"` +} + +type sessionRecord struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + User string `json:"user"` + Title string `json:"title"` + Scope string `json:"scope"` + ScopeID string `json:"scope_id"` + Messages []ChatMessage `json:"messages"` + Created string `json:"created"` + Updated string `json:"updated"` +} + +// SessionSummary is a session in a list. +type SessionSummary struct { + ID string `json:"id"` + Title string `json:"title"` + Scope string `json:"scope"` + ScopeID string `json:"scopeId"` + Created string `json:"created"` + Updated string `json:"updated"` +} + +// Session is a session with its messages. +type Session struct { + SessionSummary + Workspace string `json:"workspace"` + Messages []ChatMessage `json:"messages"` +} + +func (r sessionRecord) summary() SessionSummary { + scope := r.Scope + if scope == "" { + scope = ScopeWorkspace + } + return SessionSummary{ID: r.ID, Title: r.Title, Scope: scope, ScopeID: r.ScopeID, Created: r.Created, Updated: r.Updated} +} + +func (r sessionRecord) view() Session { + msgs := r.Messages + if msgs == nil { + msgs = []ChatMessage{} + } + return Session{SessionSummary: r.summary(), Workspace: r.Workspace, Messages: msgs} +} + +// SessionInput creates or changes a session. +type SessionInput struct { + Title *string `json:"title"` + Scope *string `json:"scope"` + ScopeID *string `json:"scopeId"` +} + +const ( + maxSessions = 200 + maxMessages = 200 +) + +func newID() string { + b := make([]byte, 8) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func now() string { return time.Now().UTC().Format(time.RFC3339) } + +// checkScope makes sure c can read what a session asks about. +func (s *Service) checkScope(ctx context.Context, c access.Caller, wsID, scope, id string) error { + switch scope { + case ScopeWorkspace: + return nil + case ScopeSpace: + r, err := s.dir.Readable(ctx, c, wsID) + if err != nil { + return err + } + if _, ok := r.Spaces[id]; !ok { + return apperr.InvalidFields(map[string]string{"scopeId": "That space is not in this workspace."}) + } + return nil + case ScopePage: + p, err := s.dir.ReadPage(ctx, c, id) + if err != nil || p.Workspace != wsID { + return apperr.InvalidFields(map[string]string{"scopeId": "That page is not in this workspace."}) + } + return nil + } + return apperr.InvalidFields(map[string]string{"scope": "Scope must be workspace, space or page."}) +} + +// ListSessions lists c's sessions in a workspace, newest first. +func (s *Service) ListSessions(ctx context.Context, c access.Caller, wsID string) ([]SessionSummary, error) { + if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil { + return nil, err + } + res, err := pocketbase.List[sessionRecord](ctx, s.pb, "ai_sessions", pocketbase.ListOptions{ + PerPage: 100, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, c.ID), + Sort: "-updated", Fields: "id,title,scope,scope_id,created,updated", + }) + if err != nil { + return nil, err + } + out := make([]SessionSummary, 0, len(res.Items)) + for _, r := range res.Items { + out = append(out, r.summary()) + } + return out, nil +} + +// CreateSession starts a session. +func (s *Service) CreateSession(ctx context.Context, c access.Caller, wsID string, in SessionInput) (Session, error) { + if _, _, err := s.ready(ctx, c, wsID); err != nil { + return Session{}, err + } + scope, id := ScopeWorkspace, "" + if in.Scope != nil && *in.Scope != "" { + scope = *in.Scope + } + if in.ScopeID != nil { + id = *in.ScopeID + } + if scope == ScopeWorkspace { + id = "" + } + if err := s.checkScope(ctx, c, wsID, scope, id); err != nil { + return Session{}, err + } + title := "" + if in.Title != nil { + title = truncate(strings.TrimSpace(*in.Title), 200) + } + n, err := pocketbase.List[sessionRecord](ctx, s.pb, "ai_sessions", pocketbase.ListOptions{ + PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, c.ID), Fields: "id", + }) + if err != nil { + return Session{}, err + } + if n.TotalItems >= maxSessions { + return Session{}, apperr.Invalid("You have as many chats as allowed here; delete some first.") + } + rec, err := pocketbase.Create[sessionRecord](ctx, s.pb, "ai_sessions", map[string]any{ + "workspace": wsID, "user": c.ID, "title": title, "scope": scope, "scope_id": id, "messages": []ChatMessage{}, + }) + if err != nil { + return Session{}, err + } + return rec.view(), nil +} + +func (s *Service) sessionFor(ctx context.Context, c access.Caller, id string) (sessionRecord, error) { + if !validID(id) { + return sessionRecord{}, apperr.NotFound("chat not found") + } + rec, err := pocketbase.Get[sessionRecord](ctx, s.pb, "ai_sessions", id) + if err != nil { + if pocketbase.IsNotFound(err) { + return rec, apperr.NotFound("chat not found") + } + return rec, err + } + if rec.User != c.ID { + return rec, apperr.NotFound("chat not found") + } + if _, err := s.dir.WorkspaceRole(ctx, c, rec.Workspace); err != nil { + return rec, apperr.NotFound("chat not found") + } + return rec, nil +} + +// GetSession returns one of c's sessions with its messages. +func (s *Service) GetSession(ctx context.Context, c access.Caller, id string) (Session, error) { + rec, err := s.sessionFor(ctx, c, id) + return rec.view(), err +} + +// UpdateSession renames a session or changes what it asks about. +func (s *Service) UpdateSession(ctx context.Context, c access.Caller, id string, in SessionInput) (Session, error) { + rec, err := s.sessionFor(ctx, c, id) + if err != nil { + return Session{}, err + } + body := map[string]any{} + if in.Title != nil { + body["title"] = truncate(strings.TrimSpace(*in.Title), 200) + } + if in.Scope != nil { + scope, sid := *in.Scope, rec.ScopeID + if in.ScopeID != nil { + sid = *in.ScopeID + } + if scope == ScopeWorkspace { + sid = "" + } + if err := s.checkScope(ctx, c, rec.Workspace, scope, sid); err != nil { + return Session{}, err + } + body["scope"], body["scope_id"] = scope, sid + } + rec, err = pocketbase.Update[sessionRecord](ctx, s.pb, "ai_sessions", id, body) + return rec.view(), err +} + +// DeleteSession deletes one of c's sessions. +func (s *Service) DeleteSession(ctx context.Context, c access.Caller, id string) error { + if _, err := s.sessionFor(ctx, c, id); err != nil { + return err + } + return s.pb.Delete(ctx, "ai_sessions", id) +} + +// ForkSession copies a session up to and including message upTo ("" = all). +func (s *Service) ForkSession(ctx context.Context, c access.Caller, id, upTo string) (Session, error) { + rec, err := s.sessionFor(ctx, c, id) + if err != nil { + return Session{}, err + } + msgs := rec.Messages + if upTo != "" { + i := slices.IndexFunc(msgs, func(m ChatMessage) bool { return m.ID == upTo }) + if i < 0 { + return Session{}, apperr.InvalidFields(map[string]string{"message": "That message is not in this chat."}) + } + msgs = msgs[:i+1] + } + title := rec.Title + if title == "" { + title = "Chat" + } + fork, err := pocketbase.Create[sessionRecord](ctx, s.pb, "ai_sessions", map[string]any{ + "workspace": rec.Workspace, "user": c.ID, "title": truncate(title+" (fork)", 200), + "scope": rec.Scope, "scope_id": rec.ScopeID, "messages": msgs, + }) + return fork.view(), err +} + +// ---- Retrieval --------------------------------------------------------------------- + +const ( + maxSources = 8 + maxSourceChars = 2400 + maxPageChars = 24000 +) + +// retrieve finds the sources for a question in a scope, only from what c +// may read. It uses the embeddings when the workspace has them, else search. +func (s *Service) retrieve(ctx context.Context, c access.Caller, wsID, scope, scopeID, question string, st Settings, chain []profileRecord) ([]Citation, error) { + r, err := s.dir.Readable(ctx, c, wsID) + if err != nil { + return nil, err + } + ignored, err := s.ignoredSet(ctx, wsID, st.Ignored) + if err != nil { + return nil, err + } + var sources []Citation + add := func(cit Citation) { + cit.N = len(sources) + 1 + cit.text = truncate(cit.text, maxSourceChars) + cit.Snippet = truncate(strings.Join(strings.Fields(cit.text), " "), 200) + sources = append(sources, cit) + } + + if scope == ScopePage { + p, err := s.dir.ReadPage(ctx, c, scopeID) + if err != nil { + return nil, err + } + pieces := chunkDoc(p.Title, p.Doc) + total := 0 + for _, pc := range pieces { + total += utf8.RuneCountInString(pc.Text) + } + if total > maxPageChars { + pieces = rankPieces(pieces, question, maxSources) + } + for _, pc := range pieces { + add(Citation{Page: p.ID, Block: pc.Block, Title: p.Title, text: pc.Text}) + } + if len(pieces) == 0 { + add(Citation{Page: p.ID, Title: p.Title, text: "(This page is empty.)"}) + } + return sources, nil + } + + if prof, ok := embedProfile(chain); ok && st.Index { + meta, _ := s.store.Meta(wsID) + if meta.Model == prof.ID+":"+prof.EmbedModel { + p, err := s.provider(prof) + if err == nil { + vecs, usage, err := p.Embed(ctx, prof.EmbedModel, []string{question}) + s.record(prof, usage, err) + if err == nil && len(vecs) == 1 { + hits, err := s.store.Search(wsID, normalize(vecs[0]), maxSources, func(ch Chunk) bool { + if ch.File != "" { + return scope == ScopeWorkspace + } + if scope == ScopeSpace && ch.Space != scopeID { + return false + } + return !ignored[ch.Page] && r.Can(ch.Space, ch.Page) + }) + if err == nil && len(hits) > 0 { + for _, h := range hits { + add(Citation{Page: h.Page, Block: h.Block, File: h.File, Title: h.Title, text: h.Text}) + } + return sources, nil + } + } + } + } + } + + // No embeddings: the best search hits, and their best pieces. + q := directory.SearchQuery{Text: truncate(question, 190), Limit: 5} + if scope == ScopeSpace { + q.Space = scopeID + } + res, err := s.dir.Search(ctx, c, wsID, q) + if err != nil { + return nil, err + } + for _, h := range res.Items { + if ignored[h.ID] { + continue + } + p, err := s.dir.ReadPage(ctx, c, h.ID) + if err != nil { + continue + } + for _, pc := range rankPieces(chunkDoc(p.Title, p.Doc), question, 2) { + if len(sources) < maxSources { + add(Citation{Page: p.ID, Block: pc.Block, Title: p.Title, text: pc.Text}) + } + } + } + return sources, nil +} + +func words(s string) []string { + return strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) +} + +// rankPieces keeps the n pieces sharing the most words with the question, +// in document order. +func rankPieces(pieces []piece, question string, n int) []piece { + if len(pieces) <= n { + return pieces + } + q := map[string]bool{} + for _, w := range words(question) { + if utf8.RuneCountInString(w) > 2 { + q[w] = true + } + } + type scored struct{ i, score int } + all := make([]scored, len(pieces)) + for i, p := range pieces { + all[i].i = i + for _, w := range words(p.Text) { + if q[w] { + all[i].score++ + } + } + } + sort.SliceStable(all, func(a, b int) bool { return all[a].score > all[b].score }) + keep := all[:n] + sort.Slice(keep, func(a, b int) bool { return keep[a].i < keep[b].i }) + out := make([]piece, n) + for i, k := range keep { + out[i] = pieces[k.i] + } + return out +} + +// ---- Answering ------------------------------------------------------------------- + +const chatSystem = `You are the assistant built into Docwell, a team wiki. You answer questions about the user's workspace from the numbered sources that come with each question. + +- Base what you say about the workspace on the sources. After each statement that uses a source, cite it as [1], or [2][3] for several. +- If the sources do not answer the question, say so plainly, and only then add what you know in general, marked as such. +- Answer in the language of the question. Use Markdown. Be concise: lead with the answer, then the details that matter.` + +const historyTurns = 12 + +func sourcesBlock(sources []Citation) string { + if len(sources) == 0 { + return "Sources: none were found for this question.\n\n" + } + var b strings.Builder + b.WriteString("Sources:\n\n") + for _, src := range sources { + fmt.Fprintf(&b, "[%d] %s\n%s\n\n", src.N, src.Title, src.text) + } + return b.String() +} + +// Event is one server-sent event of a streamed answer. +type Event struct { + Name string + Data any +} + +// Ask adds a question to a session and streams the answer to emit: first +// "sources" (the citations), then "delta" pieces of text, then "done" with +// the stored message, or "error". +func (s *Service) Ask(ctx context.Context, c access.Caller, id, question string, emit func(Event)) error { + question = strings.TrimSpace(question) + if question == "" || utf8.RuneCountInString(question) > 8000 { + return apperr.InvalidFields(map[string]string{"content": "Ask a question of up to 8 000 characters."}) + } + rec, err := s.sessionFor(ctx, c, id) + if err != nil { + return err + } + if len(rec.Messages) >= maxMessages { + return apperr.Invalid("This chat is full; start a new one or fork it.") + } + st, chain, err := s.ready(ctx, c, rec.Workspace) + if err != nil { + return err + } + scope := rec.Scope + if scope == "" { + scope = ScopeWorkspace + } + sources, err := s.retrieve(ctx, c, rec.Workspace, scope, rec.ScopeID, question, st, chain) + if err != nil { + return err + } + emit(Event{Name: "sources", Data: map[string]any{"citations": nonNil(sources)}}) + + msgs := []Message{} + start := max(0, len(rec.Messages)-historyTurns) + for _, m := range rec.Messages[start:] { + if m.Content != "" && (m.Role == "user" || m.Role == "assistant") { + msgs = append(msgs, Message{Role: m.Role, Content: m.Content}) + } + } + msgs = append(msgs, Message{Role: "user", Content: sourcesBlock(sources) + "Question: " + question}) + + var answer strings.Builder + _, chatErr := s.chat(ctx, chain, ChatRequest{System: chatSystem, Messages: msgs, MaxTokens: 8000}, func(d string) { + answer.WriteString(d) + emit(Event{Name: "delta", Data: map[string]string{"text": d}}) + }) + + user := ChatMessage{ID: newID(), Role: "user", Content: question, Created: now()} + reply := ChatMessage{ID: newID(), Role: "assistant", Content: answer.String(), Citations: sources, Created: now()} + if chatErr != nil { + reply.Error = userError(chatErr) + } + body := map[string]any{"messages": append(rec.Messages, user, reply)} + if rec.Title == "" { + body["title"] = truncate(question, 60) + } + // Store the turn even when the client went away mid-answer. + saveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) + defer cancel() + if _, err := pocketbase.Update[sessionRecord](saveCtx, s.pb, "ai_sessions", rec.ID, body); err != nil { + return err + } + if chatErr != nil { + emit(Event{Name: "error", Data: map[string]string{"message": reply.Error}}) + return nil + } + emit(Event{Name: "done", Data: map[string]any{"user": user, "message": reply}}) + return nil +} + +func nonNil(c []Citation) []Citation { + if c == nil { + return []Citation{} + } + return c +} + +// userError is the message people see for a failed call. +func userError(err error) string { + if e, ok := apperr.As(err); ok { + return e.Message + } + switch { + case err == ErrRefused: + return "The model declined to answer this." + case strings.Contains(err.Error(), "context deadline exceeded"), strings.Contains(err.Error(), "context canceled"): + return "The answer took too long and was stopped." + } + return "The AI provider failed: " + truncate(err.Error(), 300) +} + +// Answer asks a one-off question without a session (MCP's ask tool). +func (s *Service) Answer(ctx context.Context, c access.Caller, wsID, scope, scopeID, question string) (string, []Citation, error) { + st, chain, err := s.ready(ctx, c, wsID) + if err != nil { + return "", nil, err + } + if scope == "" { + scope = ScopeWorkspace + } + if err := s.checkScope(ctx, c, wsID, scope, scopeID); err != nil { + return "", nil, err + } + sources, err := s.retrieve(ctx, c, wsID, scope, scopeID, question, st, chain) + if err != nil { + return "", nil, err + } + var answer strings.Builder + _, err = s.chat(ctx, chain, ChatRequest{ + System: chatSystem, MaxTokens: 8000, + Messages: []Message{{Role: "user", Content: sourcesBlock(sources) + "Question: " + question}}, + }, func(d string) { answer.WriteString(d) }) + if err != nil { + return "", nil, apperr.Invalid(userError(err)) + } + return answer.String(), nonNil(sources), nil +} diff --git a/Server/internal/ai/chunk.go b/Server/internal/ai/chunk.go new file mode 100644 index 0000000..5825242 --- /dev/null +++ b/Server/internal/ai/chunk.go @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "encoding/json" + "strings" + "unicode/utf8" + + "docwell/server/internal/convert" +) + +// chunkSize is the target length of one chunk in characters. +const chunkSize = 1200 + +// piece is a chunk before it has a vector: Text is shown as a source, +// Embed is what gets embedded (with the page title and heading for context). +type piece struct { + Block string + Text string + Embed string +} + +// blockText is a block's text with line breaks between its child blocks, +// so list items and table cells do not run together. +func blockText(n convert.Node) string { + if n.Type == "text" { + return n.Text + } + if n.Type == "hardBreak" { + return "\n" + } + inline := true + for _, c := range n.Content { + if c.Type != "text" && c.Type != "hardBreak" && c.Type != "mention" && c.Type != "inlineMath" { + inline = false + } + } + var parts []string + for _, c := range n.Content { + if t := blockText(c); t != "" { + parts = append(parts, t) + } + } + if n.Type == "mention" || n.Type == "pageLink" { + if l, ok := n.Attrs["label"].(string); ok { + return l + } + if l, ok := n.Attrs["title"].(string); ok { + return l + } + } + if inline { + return strings.Join(parts, "") + } + return strings.Join(parts, "\n") +} + +func blockID(n convert.Node) string { + id, _ := n.Attrs["blockId"].(string) + return id +} + +// chunkDoc cuts a page into pieces along its top-level blocks: a heading +// starts a new piece, and pieces stay near chunkSize. A piece remembers the +// first linkable block it covers, for citations. +func chunkDoc(title string, raw json.RawMessage) []piece { + doc, err := convert.Parse(raw) + if err != nil { + return nil + } + var out []piece + var buf strings.Builder + block, heading := "", "" + flush := func() { + text := strings.TrimSpace(buf.String()) + buf.Reset() + if text == "" { + return + } + for _, part := range splitLong(text, chunkSize*3/2) { + ctx := title + if heading != "" && heading != title { + ctx += " › " + heading + } + out = append(out, piece{Block: block, Text: part, Embed: ctx + "\n\n" + part}) + } + block = "" + } + for _, n := range doc.Content { + text := strings.TrimSpace(blockText(n)) + if n.Type == "heading" { + flush() + heading = text + } + if text == "" { + continue + } + if buf.Len() > 0 && utf8.RuneCountInString(buf.String())+utf8.RuneCountInString(text) > chunkSize { + flush() + } + if block == "" { + block = blockID(n) + } + buf.WriteString(text) + buf.WriteString("\n\n") + } + flush() + return out +} + +// chunkText cuts plain text (an extra file) into pieces at blank lines. +func chunkText(title, text string) []piece { + var out []piece + var buf strings.Builder + flush := func() { + t := strings.TrimSpace(buf.String()) + buf.Reset() + for _, part := range splitLong(t, chunkSize*3/2) { + out = append(out, piece{Text: part, Embed: title + "\n\n" + part}) + } + } + for _, para := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n\n") { + para = strings.TrimSpace(para) + if para == "" { + continue + } + if buf.Len() > 0 && utf8.RuneCountInString(buf.String())+utf8.RuneCountInString(para) > chunkSize { + flush() + } + buf.WriteString(para) + buf.WriteString("\n\n") + } + flush() + return out +} + +// splitLong breaks text longer than max runes at whitespace. +func splitLong(text string, max int) []string { + if text == "" { + return nil + } + var out []string + for utf8.RuneCountInString(text) > max { + runes := []rune(text) + cut := max + for i := max; i > max/2; i-- { + if runes[i] == '\n' || runes[i] == ' ' { + cut = i + break + } + } + out = append(out, strings.TrimSpace(string(runes[:cut]))) + text = strings.TrimSpace(string(runes[cut:])) + } + if text != "" { + out = append(out, text) + } + return out +} + +// truncate shortens s to at most n runes, with an ellipsis. +func truncate(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + return strings.TrimSpace(string([]rune(s)[:n])) + "…" +} diff --git a/Server/internal/ai/files.go b/Server/internal/ai/files.go new file mode 100644 index 0000000..ce159f2 --- /dev/null +++ b/Server/internal/ai/files.go @@ -0,0 +1,146 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "unicode/utf8" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/convert" + "docwell/server/internal/store/pocketbase" +) + +// ---- Extra files for retrieval ---------------------------------------------------- +// +// Workspace admins can add documents that are not pages (a handbook, a +// spec) to what chat retrieves. Only their text is kept. + +// MaxFileBytes caps one uploaded file. +const MaxFileBytes = 10 << 20 + +const maxFileText = 2_000_000 + +type fileRecord struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + Name string `json:"name"` + ContentText string `json:"content_text"` + Size float64 `json:"size"` + Updated string `json:"updated"` + Created string `json:"created"` +} + +// File is an extra document as admins see it. +type File struct { + ID string `json:"id"` + Name string `json:"name"` + Size int `json:"size"` + Chars int `json:"chars"` + Indexed bool `json:"indexed"` + Created string `json:"created"` +} + +// extractText reads the text of a supported file. +func extractText(name string, data []byte) (string, error) { + switch strings.ToLower(filepath.Ext(name)) { + case ".txt", ".md", ".markdown", ".csv", ".json", ".yaml", ".yml", ".xml", ".rst", ".org": + if !utf8.Valid(data) { + return "", apperr.Invalid("The file is not UTF-8 text.") + } + return string(data), nil + case ".html", ".htm": + doc, err := convert.FromHTML(string(data)) + if err != nil { + return "", apperr.Invalid("The HTML file could not be read.") + } + return convert.Markdown(doc, convert.Options{}), nil + case ".docx": + doc, _, err := convert.FromDOCX(data) + if err != nil { + return "", apperr.Invalid("The Word document could not be read.") + } + return convert.Markdown(doc, convert.Options{}), nil + } + return "", apperr.Invalid("Add text, Markdown, HTML or Word (.docx) files.") +} + +func (s *Service) fileView(ws string, r fileRecord) File { + h, _ := s.store.Hash(ws, "file/"+r.ID) + return File{ID: r.ID, Name: r.Name, Size: int(r.Size), Chars: utf8.RuneCountInString(r.ContentText), Indexed: h != "", Created: r.Created} +} + +// ListFiles lists a workspace's extra files (workspace admin). +func (s *Service) ListFiles(ctx context.Context, c access.Caller, wsID string) ([]File, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return nil, err + } + res, err := pocketbase.List[fileRecord](ctx, s.pb, "ai_files", pocketbase.ListOptions{ + PerPage: 500, Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "name", + }) + if err != nil { + return nil, err + } + out := make([]File, 0, len(res.Items)) + for _, r := range res.Items { + out = append(out, s.fileView(wsID, r)) + } + return out, nil +} + +// AddFile stores an extra file's text (workspace admin). +func (s *Service) AddFile(ctx context.Context, c access.Caller, wsID, name string, data []byte) (File, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return File{}, err + } + name = strings.TrimSpace(filepath.Base(name)) + if name == "" || name == "." || len(name) > 200 { + return File{}, apperr.Invalid("The file needs a name of up to 200 characters.") + } + if len(data) > MaxFileBytes { + return File{}, apperr.Invalid("Files can be up to 10 MB.") + } + text, err := extractText(name, data) + if err != nil { + return File{}, err + } + if strings.TrimSpace(text) == "" { + return File{}, apperr.Invalid("The file has no text.") + } + if utf8.RuneCountInString(text) > maxFileText { + text = string([]rune(text)[:maxFileText]) + } + rec, err := pocketbase.Create[fileRecord](ctx, s.pb, "ai_files", map[string]any{ + "workspace": wsID, "name": name, "content_text": text, "size": len(data), "created_by": c.ID, + }) + if err != nil { + return File{}, err + } + s.wake() + return s.fileView(wsID, rec), nil +} + +// DeleteFile removes an extra file and its vectors (workspace admin). +func (s *Service) DeleteFile(ctx context.Context, c access.Caller, id string) error { + if !validID(id) { + return apperr.NotFound("file not found") + } + rec, err := pocketbase.Get[fileRecord](ctx, s.pb, "ai_files", id) + if err != nil { + if pocketbase.IsNotFound(err) { + return apperr.NotFound("file not found") + } + return err + } + if err := s.canManage(ctx, c, rec.Workspace); err != nil { + return apperr.NotFound("file not found") + } + if err := s.pb.Delete(ctx, "ai_files", id); err != nil { + return err + } + return s.store.Drop(rec.Workspace, "file/"+id) +} diff --git a/Server/internal/ai/index.go b/Server/internal/ai/index.go new file mode 100644 index 0000000..7c15ed8 --- /dev/null +++ b/Server/internal/ai/index.go @@ -0,0 +1,472 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "slices" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- The embeddings indexer ------------------------------------------------------- +// +// Like the search index, it follows PocketBase: per indexed workspace it +// polls the pages whose "updated" moved past that workspace's checkpoint, +// re-embeds the ones whose text changed and drops the ones that went away. + +type indexState struct { + Running bool + LastRun time.Time + LastError string +} + +const embedBatch = 32 + +// Run keeps the index up to date until ctx ends. +func (s *Service) Run(ctx context.Context, every, sweepEvery time.Duration) { + tick := time.NewTicker(every) + defer tick.Stop() + lastSweep := time.Time{} + for { + run := func() error { return s.IndexPass(ctx, time.Since(lastSweep) >= sweepEvery) } + var err error + if s.track != nil { + err = s.track("ai.index", run) + } else { + err = run() + } + if err != nil && ctx.Err() == nil { + s.log.Warn("ai: indexing failed", "err", err) + } + if time.Since(lastSweep) >= sweepEvery { + lastSweep = time.Now() + } + select { + case <-ctx.Done(): + return + case <-tick.C: + case <-s.wakeCh: + } + } +} + +type wsRow struct { + ID string `json:"id"` + AISettings json.RawMessage `json:"ai_settings"` +} + +// IndexPass indexes every workspace that has embeddings on; sweep also +// removes sources that no longer exist. +func (s *Service) IndexPass(ctx context.Context, sweep bool) error { + s.passMu.Lock() + defer s.passMu.Unlock() + var rows []wsRow + for page := 1; ; page++ { + res, err := pocketbase.List[wsRow](ctx, s.pb, "workspaces", pocketbase.ListOptions{Page: page, PerPage: 500, Fields: "id,ai_settings"}) + if err != nil { + return err + } + rows = append(rows, res.Items...) + if page >= res.TotalPages || len(res.Items) == 0 { + break + } + } + live := map[string]bool{} + var errs []error + for _, w := range rows { + live[w.ID] = true + st := defaultSettings() + if len(w.AISettings) > 0 && string(w.AISettings) != "null" { + _ = json.Unmarshal(w.AISettings, &st) + } + if err := s.indexWorkspace(ctx, w.ID, st, sweep); err != nil { + errs = append(errs, fmt.Errorf("workspace %s: %w", w.ID, err)) + } + if ctx.Err() != nil { + return ctx.Err() + } + } + // Deleted workspaces leave their vectors behind otherwise. + stored, err := s.store.Workspaces() + if err != nil { + return err + } + for _, ws := range stored { + if !live[ws] { + _ = s.store.DropWorkspace(ws) + } + } + return errors.Join(errs...) +} + +func (s *Service) setState(ws string, fn func(*indexState)) { + s.mu.Lock() + defer s.mu.Unlock() + st := s.status[ws] + if st == nil { + st = &indexState{} + s.status[ws] = st + } + fn(st) +} + +type aiPage struct { + ID string `json:"id"` + Space string `json:"space"` + Parent string `json:"parent"` + Title string `json:"title"` + ContentJSON json.RawMessage `json:"content_json"` + IsTemplate bool `json:"is_template"` + DeletedAt string `json:"deleted_at"` + ArchivedAt string `json:"archived_at"` + Updated string `json:"updated"` +} + +// ignoredSet is the ignored pages and every page below them. +func (s *Service) ignoredSet(ctx context.Context, ws string, ignored []string) (map[string]bool, error) { + out := map[string]bool{} + if len(ignored) == 0 { + return out, nil + } + parent := map[string]string{} + for page := 1; ; page++ { + res, err := pocketbase.List[aiPage](ctx, s.pb, "pages", pocketbase.ListOptions{ + Page: page, PerPage: 1000, Filter: fmt.Sprintf("workspace = '%s'", ws), Fields: "id,parent", + }) + if err != nil { + return nil, err + } + for _, p := range res.Items { + parent[p.ID] = p.Parent + } + if page >= res.TotalPages || len(res.Items) == 0 { + break + } + } + for id := range parent { + for cur, depth := id, 0; cur != "" && depth < 1000; cur, depth = parent[cur], depth+1 { + if slices.Contains(ignored, cur) { + out[id] = true + break + } + } + } + return out, nil +} + +func (s *Service) indexWorkspace(ctx context.Context, ws string, st Settings, sweep bool) error { + chain, err := s.chain(ctx, ws, st) + if err != nil { + return err + } + prof, ok := embedProfile(chain) + meta, err := s.store.Meta(ws) + if err != nil { + return err + } + if !st.Enabled || !st.Index || !ok { + if meta.Model != "" { + return s.store.DropWorkspace(ws) + } + return nil + } + model := prof.ID + ":" + prof.EmbedModel + if meta.Model != model { + if err := s.store.DropWorkspace(ws); err != nil { + return err + } + meta = Meta{Model: model} + if err := s.store.SetMeta(ws, meta); err != nil { + return err + } + } + provider, err := s.provider(prof) + if err != nil { + s.setState(ws, func(x *indexState) { x.LastError = err.Error() }) + return nil + } + s.setState(ws, func(x *indexState) { x.Running = true }) + defer s.setState(ws, func(x *indexState) { x.Running = false; x.LastRun = time.Now() }) + + ignored, err := s.ignoredSet(ctx, ws, st.Ignored) + if err != nil { + return err + } + embed := func(texts []string) ([][]float32, error) { + var out [][]float32 + for i := 0; i < len(texts); i += embedBatch { + end := min(i+embedBatch, len(texts)) + vecs, usage, err := provider.Embed(ctx, prof.EmbedModel, texts[i:end]) + s.record(prof, usage, err) + if err != nil { + return nil, err + } + for _, v := range vecs { + out = append(out, normalize(v)) + } + } + return out, nil + } + + // Pages changed since the checkpoint. + for { + filter := fmt.Sprintf("workspace = '%s'", ws) + if meta.Checkpoint != "" { + filter += fmt.Sprintf(" && updated >= '%s'", meta.Checkpoint) + } + res, err := pocketbase.List[aiPage](ctx, s.pb, "pages", pocketbase.ListOptions{ + PerPage: 50, Filter: filter, Sort: "updated,id", + Fields: "id,space,parent,title,content_json,is_template,deleted_at,archived_at,updated", + }) + if err != nil { + return err + } + for _, p := range res.Items { + if err := s.indexPage(ws, p, ignored[p.ID], embed); err != nil { + s.setState(ws, func(x *indexState) { x.LastError = err.Error() }) + return nil // try again on the next pass, from this page + } + meta.Checkpoint = p.Updated + } + if err := s.store.SetMeta(ws, meta); err != nil { + return err + } + if len(res.Items) < 50 || ctx.Err() != nil { + break + } + // Every page of a full batch at the same instant: step past it. + if res.Items[0].Updated == res.Items[len(res.Items)-1].Updated { + t, err := time.Parse(pbTime, meta.Checkpoint) + if err == nil { + meta.Checkpoint = t.Add(time.Millisecond).Format(pbTime) + } + } + } + + // Extra files changed since the last pass. + files, err := pocketbase.List[fileRecord](ctx, s.pb, "ai_files", pocketbase.ListOptions{ + PerPage: 200, Filter: fmt.Sprintf("workspace = '%s' && updated >= '%s'", ws, meta.FilesAt), Sort: "updated", + }) + if err != nil { + return err + } + for _, f := range files.Items { + pieces := chunkText(f.Name, f.ContentText) + if err := s.putPieces(ws, "file/"+f.ID, hashPieces(f.Name, pieces), pieces, Chunk{File: f.ID, Title: f.Name}, embed); err != nil { + s.setState(ws, func(x *indexState) { x.LastError = err.Error() }) + return nil + } + meta.FilesAt = f.Updated + } + if err := s.store.SetMeta(ws, meta); err != nil { + return err + } + s.setState(ws, func(x *indexState) { x.LastError = "" }) + if sweep { + return s.sweep(ctx, ws, ignored) + } + return nil +} + +const pbTime = "2006-01-02 15:04:05.000Z" + +func hashPieces(title string, pieces []piece) string { + h := sha256.New() + h.Write([]byte(title)) + for _, p := range pieces { + h.Write([]byte{0}) + h.Write([]byte(p.Block)) + h.Write([]byte{0}) + h.Write([]byte(p.Embed)) + } + return hex.EncodeToString(h.Sum(nil)) +} + +func (s *Service) indexPage(ws string, p aiPage, ignored bool, embed func([]string) ([][]float32, error)) error { + source := "page/" + p.ID + if p.DeletedAt != "" || p.ArchivedAt != "" || p.IsTemplate || ignored { + return s.store.Drop(ws, source) + } + title := p.Title + if title == "" { + title = "Untitled" + } + pieces := chunkDoc(title, p.ContentJSON) + if len(pieces) == 0 { + // A page with a title only can still be found by its title. + pieces = []piece{{Text: title, Embed: title}} + } + return s.putPieces(ws, source, hashPieces(title, pieces), pieces, Chunk{Space: p.Space, Page: p.ID, Title: title}, embed) +} + +func (s *Service) putPieces(ws, source, hash string, pieces []piece, base Chunk, embed func([]string) ([][]float32, error)) error { + old, err := s.store.Hash(ws, source) + if err != nil || old == hash { + return err + } + texts := make([]string, len(pieces)) + for i, p := range pieces { + texts[i] = p.Embed + } + vecs, err := embed(texts) + if err != nil { + return err + } + chunks := make([]Chunk, len(pieces)) + for i, p := range pieces { + c := base + c.Block, c.Text, c.Vector = p.Block, p.Text, vecs[i] + chunks[i] = c + } + return s.store.Put(ws, source, hash, chunks) +} + +// sweep drops sources whose page or file is gone (deleted for good, or +// newly ignored). +func (s *Service) sweep(ctx context.Context, ws string, ignored map[string]bool) error { + live := map[string]bool{} + for page := 1; ; page++ { + res, err := pocketbase.List[aiPage](ctx, s.pb, "pages", pocketbase.ListOptions{ + Page: page, PerPage: 1000, Fields: "id", + Filter: fmt.Sprintf("workspace = '%s' && deleted_at = '' && archived_at = '' && is_template = false", ws), + }) + if err != nil { + return err + } + for _, p := range res.Items { + if !ignored[p.ID] { + live["page/"+p.ID] = true + } + } + if page >= res.TotalPages || len(res.Items) == 0 { + break + } + } + files, err := pocketbase.List[fileRecord](ctx, s.pb, "ai_files", pocketbase.ListOptions{ + PerPage: 500, Filter: fmt.Sprintf("workspace = '%s'", ws), Fields: "id", + }) + if err != nil { + return err + } + for _, f := range files.Items { + live["file/"+f.ID] = true + } + sources, err := s.store.Sources(ws) + if err != nil { + return err + } + for _, src := range sources { + if !live[src] { + if err := s.store.Drop(ws, src); err != nil { + return err + } + } + } + return nil +} + +// IndexStatus is a workspace's embeddings progress. +type IndexStatus struct { + Enabled bool `json:"enabled"` + // Profile and Model are what the vectors come from ("" when none fits). + Profile string `json:"profile"` + Model string `json:"model"` + Pages int `json:"pages"` + Indexed int `json:"indexed"` + Files int `json:"files"` + Chunks int `json:"chunks"` + Running bool `json:"running"` + LastRun string `json:"lastRun"` + LastError string `json:"lastError"` +} + +// IndexStatus reports a workspace's index (workspace admin). +func (s *Service) IndexStatus(ctx context.Context, c access.Caller, wsID string) (IndexStatus, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return IndexStatus{}, err + } + st, err := s.settings(ctx, wsID) + if err != nil { + return IndexStatus{}, err + } + out := IndexStatus{Enabled: st.Enabled && st.Index} + chain, err := s.chain(ctx, wsID, st) + if err != nil { + return out, err + } + if p, ok := embedProfile(chain); ok { + out.Profile, out.Model = p.Name, p.EmbedModel + } + // Pages that can be indexed: live ones that are not left out. + ignored, err := s.ignoredSet(ctx, wsID, st.Ignored) + if err != nil { + return out, err + } + filter := fmt.Sprintf("workspace = '%s' && deleted_at = '' && archived_at = '' && is_template = false", wsID) + if len(ignored) == 0 { + res, err := pocketbase.List[aiPage](ctx, s.pb, "pages", pocketbase.ListOptions{PerPage: 1, Fields: "id", Filter: filter}) + if err != nil { + return out, err + } + out.Pages = res.TotalItems + } else { + for page := 1; ; page++ { + res, err := pocketbase.List[aiPage](ctx, s.pb, "pages", pocketbase.ListOptions{Page: page, PerPage: 1000, Fields: "id", Filter: filter}) + if err != nil { + return out, err + } + for _, p := range res.Items { + if !ignored[p.ID] { + out.Pages++ + } + } + if page >= res.TotalPages || len(res.Items) == 0 { + break + } + } + } + if out.Indexed, out.Files, out.Chunks, err = s.store.Counts(wsID); err != nil { + return out, err + } + s.mu.Lock() + if x := s.status[wsID]; x != nil { + out.Running, out.LastError = x.Running, x.LastError + if !x.LastRun.IsZero() { + out.LastRun = x.LastRun.UTC().Format(time.RFC3339) + } + } + s.mu.Unlock() + return out, nil +} + +// RebuildIndex drops a workspace's vectors and indexes it again (workspace admin). +func (s *Service) RebuildIndex(ctx context.Context, c access.Caller, wsID string) error { + if err := s.canManage(ctx, c, wsID); err != nil { + return err + } + if err := s.store.DropWorkspace(wsID); err != nil { + return apperr.Conflict(err.Error()) + } + s.wake() + return nil +} + +// recheck makes the next pass walk every page of a workspace again (hashes +// keep unchanged pages from being embedded twice). +func (s *Service) recheck(wsID string) { + meta, err := s.store.Meta(wsID) + if err == nil && meta.Model != "" { + meta.Checkpoint = "" + _ = s.store.SetMeta(wsID, meta) + } + s.wake() +} diff --git a/Server/internal/ai/mcp.go b/Server/internal/ai/mcp.go new file mode 100644 index 0000000..c93b37d --- /dev/null +++ b/Server/internal/ai/mcp.go @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "encoding/json" + "fmt" + "slices" + "strings" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/directory" +) + +// ---- MCP server -------------------------------------------------------------------- +// +// POST /mcp speaks the Model Context Protocol over Streamable HTTP: one +// JSON-RPC 2.0 message (or batch) per request, answered with JSON. The +// caller is an API token's owner; write tokens also get the write tools. + +// MCPVersions are the protocol versions this server speaks, newest first. +var MCPVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"} + +type rpcRequest struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params,omitempty"` +} + +type rpcError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +type rpcResponse struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Result any `json:"result,omitempty"` + Error *rpcError `json:"error,omitempty"` +} + +type mcpTool struct { + Name string `json:"name"` + Title string `json:"title,omitempty"` + Description string `json:"description"` + InputSchema map[string]any `json:"inputSchema"` + Annotations map[string]any `json:"annotations,omitempty"` + write bool +} + +func schema(required []string, props map[string]any) map[string]any { + if required == nil { + required = []string{} + } + return map[string]any{"type": "object", "properties": props, "required": required, "additionalProperties": false} +} + +func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} } + +var readOnly = map[string]any{"readOnlyHint": true, "openWorldHint": false} + +var mcpTools = []mcpTool{ + { + Name: "list_workspaces", Title: "List workspaces", Annotations: readOnly, + Description: "Lists the Docwell workspaces you can open, with their ids.", + InputSchema: schema(nil, map[string]any{}), + }, + { + Name: "list_spaces", Title: "List spaces", Annotations: readOnly, + Description: "Lists the spaces of a workspace you can open, with their ids.", + InputSchema: schema([]string{"workspace"}, map[string]any{"workspace": str("Workspace id")}), + }, + { + Name: "list_pages", Title: "List pages", Annotations: readOnly, + Description: "Lists the page tree of a space (id, parent, title), or with only a workspace, its most recently changed pages.", + InputSchema: schema(nil, map[string]any{"workspace": str("Workspace id (recent pages)"), "space": str("Space id (the whole tree)")}), + }, + { + Name: "search", Title: "Search pages", Annotations: readOnly, + Description: "Full-text search over the pages of a workspace. Returns page ids, titles and snippets.", + InputSchema: schema([]string{"workspace", "query"}, map[string]any{ + "workspace": str("Workspace id"), "query": str("Words to look for"), "space": str("Optional space id to search in"), + "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 50, "description": "Most results (default 10)"}, + }), + }, + { + Name: "read_page", Title: "Read a page", Annotations: readOnly, + Description: "Returns a page's title and body as Markdown.", + InputSchema: schema([]string{"page"}, map[string]any{"page": str("Page id")}), + }, + { + Name: "ask", Title: "Ask the workspace", Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": true}, + Description: "Asks the workspace's AI a question; it answers from the pages you can read, with numbered sources. Needs AI set up in the workspace.", + InputSchema: schema([]string{"workspace", "question"}, map[string]any{ + "workspace": str("Workspace id"), "question": str("The question"), + "space": str("Optional space id to limit the sources"), "page": str("Optional page id to ask about"), + }), + }, + { + Name: "create_page", Title: "Create a page", write: true, + Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, + Description: "Creates a page in a space from Markdown and returns its id.", + InputSchema: schema([]string{"space", "title"}, map[string]any{ + "space": str("Space id"), "title": str("Page title"), "markdown": str("Page body as Markdown"), + "parent": str("Optional parent page id"), + }), + }, + { + Name: "update_page", Title: "Update a page", write: true, + Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": true, "openWorldHint": false}, + Description: "Replaces a page's body with Markdown, or appends Markdown to it (mode \"append\"). Page history keeps the previous version.", + InputSchema: schema([]string{"page", "markdown"}, map[string]any{ + "page": str("Page id"), "markdown": str("Markdown"), + "mode": map[string]any{"type": "string", "enum": []string{"replace", "append"}, "description": "replace (default) or append"}, + }), + }, +} + +// MCP answers one HTTP request body. It returns nil for a message that +// needs no answer (notifications), which the transport turns into 202. +// onWrite (optional) hears about every successful write tool call. +func (s *Service) MCP(ctx context.Context, c access.Caller, canWrite bool, body []byte, onWrite func(tool, page string)) ([]byte, error) { + ctx = context.WithValue(ctx, onWriteKey{}, onWrite) + trimmed := strings.TrimSpace(string(body)) + if strings.HasPrefix(trimmed, "[") { + var batch []rpcRequest + if err := json.Unmarshal(body, &batch); err != nil { + return json.Marshal(rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{-32700, "parse error"}}) + } + var out []rpcResponse + for _, req := range batch { + if res, ok := s.mcpOne(ctx, c, canWrite, req); ok { + out = append(out, res) + } + } + if len(out) == 0 { + return nil, nil + } + return json.Marshal(out) + } + var req rpcRequest + if err := json.Unmarshal(body, &req); err != nil { + return json.Marshal(rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{-32700, "parse error"}}) + } + res, ok := s.mcpOne(ctx, c, canWrite, req) + if !ok { + return nil, nil + } + return json.Marshal(res) +} + +func (s *Service) mcpOne(ctx context.Context, c access.Caller, canWrite bool, req rpcRequest) (rpcResponse, bool) { + if len(req.ID) == 0 { + return rpcResponse{}, false // a notification (initialized, cancelled …) + } + res := rpcResponse{JSONRPC: "2.0", ID: req.ID} + switch req.Method { + case "initialize": + var p struct { + ProtocolVersion string `json:"protocolVersion"` + } + _ = json.Unmarshal(req.Params, &p) + version := MCPVersions[0] + if slices.Contains(MCPVersions, p.ProtocolVersion) { + version = p.ProtocolVersion + } + instructions := "Docwell is a team wiki. Use list_workspaces first, then search or list_pages to find pages and read_page to read them." + if canWrite { + instructions += " create_page and update_page change pages as the token's owner." + } + res.Result = map[string]any{ + "protocolVersion": version, + "capabilities": map[string]any{"tools": map[string]any{"listChanged": false}}, + "serverInfo": map[string]string{"name": "docwell", "title": "Docwell", "version": "1"}, + "instructions": instructions, + } + case "ping": + res.Result = map[string]any{} + case "tools/list": + tools := []mcpTool{} + for _, t := range mcpTools { + if !t.write || canWrite { + tools = append(tools, t) + } + } + res.Result = map[string]any{"tools": tools} + case "tools/call": + var p struct { + Name string `json:"name"` + Arguments map[string]any `json:"arguments"` + } + if err := json.Unmarshal(req.Params, &p); err != nil { + res.Error = &rpcError{-32602, "invalid params"} + break + } + i := slices.IndexFunc(mcpTools, func(t mcpTool) bool { return t.Name == p.Name }) + if i < 0 || (mcpTools[i].write && !canWrite) { + res.Error = &rpcError{-32602, "unknown tool: " + p.Name} + break + } + text, err := s.callTool(ctx, c, p.Name, args(p.Arguments)) + if err != nil { + msg := err.Error() + if e, ok := apperr.As(err); ok { + msg = e.Message + for f, m := range e.Fields { + msg += fmt.Sprintf(" (%s: %s)", f, m) + } + } + res.Result = map[string]any{"content": []map[string]string{{"type": "text", "text": msg}}, "isError": true} + break + } + res.Result = map[string]any{"content": []map[string]string{{"type": "text", "text": text}}} + case "resources/list": + res.Result = map[string]any{"resources": []any{}} + case "prompts/list": + res.Result = map[string]any{"prompts": []any{}} + default: + res.Error = &rpcError{-32601, "method not found: " + req.Method} + } + return res, true +} + +type onWriteKey struct{} + +func wrote(ctx context.Context, tool, page string) { + if fn, _ := ctx.Value(onWriteKey{}).(func(tool, page string)); fn != nil { + fn(tool, page) + } +} + +type args map[string]any + +func (a args) str(k string) string { + v, _ := a[k].(string) + return strings.TrimSpace(v) +} + +func (a args) need(k string) (string, error) { + if v := a.str(k); v != "" { + return v, nil + } + return "", apperr.Invalid("missing argument: " + k) +} + +func toJSON(v any) (string, error) { + b, err := json.MarshalIndent(v, "", " ") + return string(b), err +} + +func (s *Service) callTool(ctx context.Context, c access.Caller, name string, a args) (string, error) { + switch name { + case "list_workspaces": + list, err := s.dir.ListWorkspaces(ctx, c) + if err != nil { + return "", err + } + type ws struct{ ID, Name, Role string } + out := []ws{} + for _, w := range list { + out = append(out, ws{w.ID, w.Name, w.Role}) + } + return toJSON(out) + case "list_spaces": + wsID, err := a.need("workspace") + if err != nil { + return "", err + } + list, err := s.dir.ListSpaces(ctx, c, wsID) + if err != nil { + return "", err + } + type sp struct{ ID, Name, Description, Role string } + out := []sp{} + for _, x := range list { + out = append(out, sp{x.ID, x.Name, x.Description, x.Role}) + } + return toJSON(out) + case "list_pages": + if space := a.str("space"); space != "" { + nodes, err := s.dir.ListPages(ctx, c, space) + if err != nil { + return "", err + } + type pg struct{ ID, Parent, Title string } + out := []pg{} + for _, n := range nodes { + out = append(out, pg{n.ID, n.Parent, n.Title}) + } + return toJSON(out) + } + wsID, err := a.need("workspace") + if err != nil { + return "", apperr.Invalid("give a space, or a workspace for its recent pages") + } + list, err := s.dir.RecentPages(ctx, c, wsID, "", 50) + if err != nil { + return "", err + } + return toJSON(list) + case "search": + wsID, err := a.need("workspace") + if err != nil { + return "", err + } + q, err := a.need("query") + if err != nil { + return "", err + } + limit := 10 + if f, ok := a["limit"].(float64); ok { + limit = min(max(int(f), 1), 50) + } + res, err := s.dir.Search(ctx, c, wsID, directory.SearchQuery{Text: q, Space: a.str("space"), Limit: limit}) + if err != nil { + return "", err + } + type hit struct { + Page string `json:"page"` + Title string `json:"title"` + Space string `json:"space"` + Snippet string `json:"snippet"` + Updated string `json:"updated"` + } + out := []hit{} + for _, h := range res.Items { + out = append(out, hit{h.ID, h.Title, h.SpaceName, h.Snippet, h.Updated}) + } + return toJSON(map[string]any{"total": res.Total, "results": out}) + case "read_page": + id, err := a.need("page") + if err != nil { + return "", err + } + p, err := s.dir.ReadPage(ctx, c, id) + if err != nil { + return "", err + } + return fmt.Sprintf("# %s\n\n\n\n%s", p.Title, p.ID, p.Space, p.Updated, p.Markdown), nil + case "ask": + wsID, err := a.need("workspace") + if err != nil { + return "", err + } + q, err := a.need("question") + if err != nil { + return "", err + } + scope, scopeID := ScopeWorkspace, "" + if p := a.str("page"); p != "" { + scope, scopeID = ScopePage, p + } else if sp := a.str("space"); sp != "" { + scope, scopeID = ScopeSpace, sp + } + answer, cites, err := s.Answer(ctx, c, wsID, scope, scopeID, q) + if err != nil { + return "", err + } + var b strings.Builder + b.WriteString(answer) + if len(cites) > 0 { + b.WriteString("\n\nSources:\n") + for _, ct := range cites { + ref := "page " + ct.Page + if ct.File != "" { + ref = "file" + } + fmt.Fprintf(&b, "[%d] %s (%s)\n", ct.N, ct.Title, ref) + } + } + return b.String(), nil + case "create_page": + space, err := a.need("space") + if err != nil { + return "", err + } + title, err := a.need("title") + if err != nil { + return "", err + } + p, err := s.dir.CreatePage(ctx, c, space, directory.CreatePageInput{Title: title, Parent: a.str("parent")}) + if err != nil { + return "", err + } + if md := a.str("markdown"); md != "" { + if _, err := s.dir.WriteMarkdown(ctx, c, p.ID, md, false); err != nil { + return "", err + } + } + wrote(ctx, name, p.ID) + return toJSON(map[string]string{"page": p.ID, "title": p.Title, "space": p.Space}) + case "update_page": + id, err := a.need("page") + if err != nil { + return "", err + } + md, err := a.need("markdown") + if err != nil { + return "", err + } + p, err := s.dir.WriteMarkdown(ctx, c, id, md, a.str("mode") == "append") + if err != nil { + return "", err + } + wrote(ctx, name, p.ID) + return toJSON(map[string]string{"page": p.ID, "title": p.Title, "updated": p.Updated}) + } + return "", apperr.Invalid("unknown tool") +} diff --git a/Server/internal/ai/profiles.go b/Server/internal/ai/profiles.go new file mode 100644 index 0000000..a4138f7 --- /dev/null +++ b/Server/internal/ai/profiles.go @@ -0,0 +1,571 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "slices" + "strings" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Secrets ------------------------------------------------------------------- + +// sealer encrypts provider keys with AES-256-GCM. +type sealer struct{ aead cipher.AEAD } + +func newSealer(secret string) *sealer { + key := sha256.Sum256([]byte("docwell-ai-keys:" + secret)) + block, _ := aes.NewCipher(key[:]) + aead, _ := cipher.NewGCM(block) + return &sealer{aead: aead} +} + +func (s *sealer) seal(plain string) string { + if plain == "" { + return "" + } + nonce := make([]byte, s.aead.NonceSize()) + _, _ = rand.Read(nonce) + return "v1:" + base64.StdEncoding.EncodeToString(s.aead.Seal(nonce, nonce, []byte(plain), nil)) +} + +var errUnreadableKey = errors.New("the stored API key cannot be decrypted (the server secret changed); enter the key again") + +func (s *sealer) open(sealed string) (string, error) { + if sealed == "" { + return "", nil + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(sealed, "v1:")) + n := s.aead.NonceSize() + if err != nil || len(raw) < n { + return "", errUnreadableKey + } + plain, err := s.aead.Open(nil, raw[:n], raw[n:], nil) + if err != nil { + return "", errUnreadableKey + } + return string(plain), nil +} + +// ---- Profiles -------------------------------------------------------------------- + +type profileRecord struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + Name string `json:"name"` + Kind string `json:"kind"` + BaseURL string `json:"base_url"` + APIKey string `json:"api_key"` + ChatModel string `json:"chat_model"` + EmbedModel string `json:"embed_model"` + Effort string `json:"effort"` + Enabled bool `json:"enabled"` + Position float64 `json:"position"` + Requests float64 `json:"requests"` + InputTokens float64 `json:"input_tokens"` + OutputTokens float64 `json:"output_tokens"` + LastUsed string `json:"last_used"` + LastError string `json:"last_error"` + Created string `json:"created"` +} + +// Profile is a provider configuration as admins see it, without the key. +type Profile struct { + ID string `json:"id"` + // Workspace is "" for an instance default. + Workspace string `json:"workspace"` + Name string `json:"name"` + Kind string `json:"kind"` + BaseURL string `json:"baseUrl"` + KeySet bool `json:"keySet"` + ChatModel string `json:"chatModel"` + EmbedModel string `json:"embedModel"` + Effort string `json:"effort"` + Enabled bool `json:"enabled"` + Position int `json:"position"` + Usage struct { + Requests int `json:"requests"` + InputTokens int `json:"inputTokens"` + OutputTokens int `json:"outputTokens"` + } `json:"usage"` + LastUsed string `json:"lastUsed"` + LastError string `json:"lastError"` + Created string `json:"created"` +} + +func (r profileRecord) view() Profile { + p := Profile{ + ID: r.ID, Workspace: r.Workspace, Name: r.Name, Kind: r.Kind, BaseURL: r.BaseURL, KeySet: r.APIKey != "", + ChatModel: r.ChatModel, EmbedModel: r.EmbedModel, Effort: r.Effort, Enabled: r.Enabled, + Position: int(r.Position), LastUsed: r.LastUsed, LastError: r.LastError, Created: r.Created, + } + p.Usage.Requests, p.Usage.InputTokens, p.Usage.OutputTokens = int(r.Requests), int(r.InputTokens), int(r.OutputTokens) + return p +} + +// ProfileInput creates or changes a profile. A nil APIKey keeps the stored +// key; "" removes it. +type ProfileInput struct { + Name *string `json:"name"` + Kind *string `json:"kind"` + BaseURL *string `json:"baseUrl"` + APIKey *string `json:"apiKey"` + ChatModel *string `json:"chatModel"` + EmbedModel *string `json:"embedModel"` + Effort *string `json:"effort"` + Enabled *bool `json:"enabled"` +} + +var efforts = []string{"", "low", "medium", "high", "xhigh", "max"} + +const maxProfiles = 20 + +func (in ProfileInput) body(s *sealer, create bool) (map[string]any, error) { + fields := map[string]string{} + body := map[string]any{} + str := func(p *string, key, field string, max int) { + if p == nil { + return + } + v := strings.TrimSpace(*p) + if len(v) > max { + fields[field] = fmt.Sprintf("Use at most %d characters.", max) + } + body[key] = v + } + str(in.Name, "name", "name", 80) + str(in.ChatModel, "chat_model", "chatModel", 200) + str(in.EmbedModel, "embed_model", "embedModel", 200) + if in.Name != nil && strings.TrimSpace(*in.Name) == "" { + fields["name"] = "Give the profile a name." + } + if create && in.Name == nil { + fields["name"] = "Give the profile a name." + } + if in.Kind != nil { + if !slices.Contains([]string{KindOpenAI, KindAnthropic, KindOllama}, *in.Kind) { + fields["kind"] = "Choose OpenAI-compatible, Anthropic or Ollama." + } + body["kind"] = *in.Kind + } else if create { + fields["kind"] = "Choose OpenAI-compatible, Anthropic or Ollama." + } + if in.BaseURL != nil { + v := strings.TrimRight(strings.TrimSpace(*in.BaseURL), "/") + if v != "" { + u, err := url.Parse(v) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + fields["baseUrl"] = "Enter an http:// or https:// address." + } + } + body["base_url"] = v + } + if in.Effort != nil { + if !slices.Contains(efforts, *in.Effort) { + fields["effort"] = "Effort must be low, medium, high, xhigh or max." + } + body["effort"] = *in.Effort + } + if in.APIKey != nil { + v := strings.TrimSpace(*in.APIKey) + if len(v) > 1000 { + fields["apiKey"] = "That key is too long." + } + body["api_key"] = s.seal(v) + } + if in.Enabled != nil { + body["enabled"] = *in.Enabled + } else if create { + body["enabled"] = true + } + if len(fields) > 0 { + return nil, apperr.InvalidFields(fields) + } + return body, nil +} + +// canManage checks that c may change the profiles of wsID ("" = instance). +func (s *Service) canManage(ctx context.Context, c access.Caller, wsID string) error { + if wsID == "" { + if !c.IsSuperadmin() { + return apperr.Forbidden("only superadmins manage the instance's AI profiles") + } + return nil + } + role, err := s.dir.WorkspaceRole(ctx, c, wsID) + if err != nil { + return err + } + if !access.AtLeast(role, access.WorkspaceAdmin) { + return apperr.Forbidden("workspace admin role required") + } + return nil +} + +func profileFilter(wsID string) string { + if wsID == "" { + return "workspace = ''" + } + return fmt.Sprintf("workspace = '%s'", wsID) +} + +func (s *Service) profileRecords(ctx context.Context, wsID string) ([]profileRecord, error) { + res, err := pocketbase.List[profileRecord](ctx, s.pb, "ai_profiles", pocketbase.ListOptions{ + PerPage: 200, Filter: profileFilter(wsID), Sort: "position,created", + }) + if err != nil { + return nil, err + } + return res.Items, nil +} + +// ListProfiles lists the profiles of a workspace ("" = the instance's). +func (s *Service) ListProfiles(ctx context.Context, c access.Caller, wsID string) ([]Profile, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return nil, err + } + recs, err := s.profileRecords(ctx, wsID) + if err != nil { + return nil, err + } + out := make([]Profile, 0, len(recs)) + for _, r := range recs { + out = append(out, r.view()) + } + return out, nil +} + +// CreateProfile adds a profile at the end of the list. +func (s *Service) CreateProfile(ctx context.Context, c access.Caller, wsID string, in ProfileInput) (Profile, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return Profile{}, err + } + body, err := in.body(s.keys, true) + if err != nil { + return Profile{}, err + } + recs, err := s.profileRecords(ctx, wsID) + if err != nil { + return Profile{}, err + } + if len(recs) >= maxProfiles { + return Profile{}, apperr.Invalid("This list has as many profiles as allowed.") + } + body["workspace"] = wsID + body["position"] = len(recs) + rec, err := pocketbase.Create[profileRecord](ctx, s.pb, "ai_profiles", body) + if err != nil { + return Profile{}, err + } + s.changed(wsID) + return rec.view(), nil +} + +func (s *Service) profileFor(ctx context.Context, c access.Caller, id string) (profileRecord, error) { + if !validID(id) { + return profileRecord{}, apperr.NotFound("profile not found") + } + rec, err := pocketbase.Get[profileRecord](ctx, s.pb, "ai_profiles", id) + if err != nil { + if pocketbase.IsNotFound(err) { + return rec, apperr.NotFound("profile not found") + } + return rec, err + } + if err := s.canManage(ctx, c, rec.Workspace); err != nil { + if rec.Workspace != "" { + return rec, apperr.NotFound("profile not found") + } + return rec, err + } + return rec, nil +} + +// UpdateProfile changes the fields that are set. +func (s *Service) UpdateProfile(ctx context.Context, c access.Caller, id string, in ProfileInput) (Profile, error) { + rec, err := s.profileFor(ctx, c, id) + if err != nil { + return Profile{}, err + } + body, err := in.body(s.keys, false) + if err != nil { + return Profile{}, err + } + body["last_error"] = "" + rec, err = pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", id, body) + if err != nil { + return Profile{}, err + } + s.changed(rec.Workspace) + return rec.view(), nil +} + +// DeleteProfile removes a profile. +func (s *Service) DeleteProfile(ctx context.Context, c access.Caller, id string) error { + rec, err := s.profileFor(ctx, c, id) + if err != nil { + return err + } + if err := s.pb.Delete(ctx, "ai_profiles", id); err != nil { + return err + } + s.changed(rec.Workspace) + return nil +} + +// OrderProfiles sets the order of a workspace's profiles (ids first to last). +func (s *Service) OrderProfiles(ctx context.Context, c access.Caller, wsID string, ids []string) ([]Profile, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return nil, err + } + recs, err := s.profileRecords(ctx, wsID) + if err != nil { + return nil, err + } + pos := map[string]int{} + for i, id := range ids { + pos[id] = i + } + for _, r := range recs { + p, ok := pos[r.ID] + if !ok { + p = len(ids) + int(r.Position) + } + if p != int(r.Position) { + if _, err := pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", r.ID, map[string]any{"position": p}); err != nil { + return nil, err + } + } + } + s.changed(wsID) + return s.ListProfiles(ctx, c, wsID) +} + +// TestResult is what a profile test found. +type TestResult struct { + OK bool `json:"ok"` + Chat string `json:"chat"` + Embeddings string `json:"embeddings"` + Dimensions int `json:"dimensions"` + LatencyMS int `json:"latencyMs"` + Error string `json:"error"` +} + +// TestProfile sends a tiny chat (and embedding) through a profile. +func (s *Service) TestProfile(ctx context.Context, c access.Caller, id string) (TestResult, error) { + rec, err := s.profileFor(ctx, c, id) + if err != nil { + return TestResult{}, err + } + ctx, cancel := context.WithTimeout(ctx, 60*time.Second) + defer cancel() + p, err := s.provider(rec) + if err != nil { + return TestResult{Error: err.Error()}, nil + } + res := TestResult{OK: true} + start := time.Now() + if rec.ChatModel != "" { + var out strings.Builder + usage, err := p.Chat(ctx, ChatRequest{ + Model: rec.ChatModel, Effort: rec.Effort, MaxTokens: 64, + Messages: []Message{{Role: "user", Content: "Reply with the single word: ready"}}, + }, func(d string) { out.WriteString(d) }) + s.record(rec, usage, err) + if err != nil { + res.OK, res.Error = false, err.Error() + } else { + res.Chat = strings.TrimSpace(out.String()) + } + } + if rec.EmbedModel != "" && res.OK { + vecs, usage, err := p.Embed(ctx, rec.EmbedModel, []string{"Docwell"}) + s.record(rec, usage, err) + if err != nil { + res.OK, res.Error = false, err.Error() + } else { + res.Embeddings, res.Dimensions = "ok", len(vecs[0]) + } + } + res.LatencyMS = int(time.Since(start).Milliseconds()) + return res, nil +} + +// provider builds the driver for a profile. Workspace profiles follow the +// webhook address rules; instance profiles may reach any address (a +// superadmin set them, and local models usually run next to the server). +func (s *Service) provider(rec profileRecord) (Provider, error) { + key, err := s.keys.open(rec.APIKey) + if err != nil { + return nil, err + } + client := s.guarded + if rec.Workspace == "" { + client = s.open + } + return NewProvider(rec.Kind, rec.BaseURL, key, client) +} + +// record adds a call's usage to a profile's counters, and its error. +func (s *Service) record(rec profileRecord, u Usage, callErr error) { + s.usageMu.Lock() + defer s.usageMu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + body := map[string]any{ + "requests+": 1, "input_tokens+": u.InputTokens, "output_tokens+": u.OutputTokens, + "last_used": time.Now().UTC().Format("2006-01-02 15:04:05.000Z"), "last_error": "", + } + if callErr != nil { + msg := callErr.Error() + if len(msg) > 480 { + msg = msg[:480] + } + body["last_error"] = msg + } + if _, err := pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", rec.ID, body); err != nil { + s.log.Warn("ai: recording usage", "profile", rec.ID, "err", err) + } +} + +// ---- Workspace settings ----------------------------------------------------------- + +// Settings is a workspace's AI switches. +type Settings struct { + Enabled bool `json:"enabled"` + UseInstanceProfiles bool `json:"useInstanceProfiles"` + Index bool `json:"index"` + Ignored []string `json:"ignored"` +} + +func defaultSettings() Settings { + return Settings{Enabled: true, UseInstanceProfiles: true, Ignored: []string{}} +} + +type workspaceAI struct { + ID string `json:"id"` + AISettings json.RawMessage `json:"ai_settings"` +} + +func (s *Service) settings(ctx context.Context, wsID string) (Settings, error) { + rec, err := pocketbase.Get[workspaceAI](ctx, s.pb, "workspaces", wsID) + if err != nil { + return Settings{}, err + } + out := defaultSettings() + if len(rec.AISettings) > 0 && string(rec.AISettings) != "null" { + _ = json.Unmarshal(rec.AISettings, &out) + } + if out.Ignored == nil { + out.Ignored = []string{} + } + return out, nil +} + +// GetSettings returns a workspace's AI settings (workspace admin). +func (s *Service) GetSettings(ctx context.Context, c access.Caller, wsID string) (Settings, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return Settings{}, err + } + return s.settings(ctx, wsID) +} + +// SaveSettings replaces a workspace's AI settings (workspace admin). +func (s *Service) SaveSettings(ctx context.Context, c access.Caller, wsID string, in Settings) (Settings, error) { + if err := s.canManage(ctx, c, wsID); err != nil { + return Settings{}, err + } + ignored := []string{} + for _, id := range in.Ignored { + if validID(id) && !slices.Contains(ignored, id) && len(ignored) < 2000 { + ignored = append(ignored, id) + } + } + in.Ignored = ignored + if _, err := pocketbase.Update[workspaceAI](ctx, s.pb, "workspaces", wsID, map[string]any{"ai_settings": in}); err != nil { + return Settings{}, err + } + s.recheck(wsID) + return in, nil +} + +// ---- Choosing profiles ---------------------------------------------------------- + +// chain is the profiles a workspace uses, in order: its own, then the +// instance's unless turned off. Disabled profiles are left out. +func (s *Service) chain(ctx context.Context, wsID string, st Settings) ([]profileRecord, error) { + own, err := s.profileRecords(ctx, wsID) + if err != nil { + return nil, err + } + all := own + if st.UseInstanceProfiles { + inst, err := s.profileRecords(ctx, "") + if err != nil { + return nil, err + } + all = append(all, inst...) + } + return slices.DeleteFunc(all, func(r profileRecord) bool { return !r.Enabled }), nil +} + +// embedProfile is the profile a workspace embeds with, or false. +func embedProfile(chain []profileRecord) (profileRecord, bool) { + for _, r := range chain { + if r.EmbedModel != "" { + return r, true + } + } + return profileRecord{}, false +} + +// errNoProfile is shown when a workspace has nothing to answer with. +var errNoProfile = apperr.Invalid("AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.") + +// chat runs a chat on the first profile of the chain that answers. It moves +// to the next one only while nothing was streamed yet. +func (s *Service) chat(ctx context.Context, chain []profileRecord, req ChatRequest, onDelta func(string)) (profileRecord, error) { + var lastErr error = errNoProfile + for _, rec := range chain { + if rec.ChatModel == "" { + continue + } + p, err := s.provider(rec) + if err != nil { + lastErr = err + continue + } + r := req + r.Model, r.Effort = rec.ChatModel, rec.Effort + if rec.Kind != KindAnthropic { + r.Effort = "" + } + streamed := false + usage, err := p.Chat(ctx, r, func(d string) { streamed = true; onDelta(d) }) + s.record(rec, usage, err) + if err == nil || streamed || errors.Is(err, ErrRefused) || ctx.Err() != nil { + return rec, err + } + s.log.Warn("ai: profile failed, trying the next", "profile", rec.ID, "err", err) + lastErr = err + } + return profileRecord{}, lastErr +} + +// changed wakes the indexer after a workspace's setup changed, so a new +// embedding model or a switched-on index is picked up at once. +func (s *Service) changed(string) { s.wake() } diff --git a/Server/internal/ai/provider.go b/Server/internal/ai/provider.go new file mode 100644 index 0000000..730264c --- /dev/null +++ b/Server/internal/ai/provider.go @@ -0,0 +1,391 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package ai is Docwell's AI layer (ADR-15): provider drivers, the BYOK +// profiles workspaces and the instance configure, the embeddings index, +// chat sessions with citations, writing actions and the MCP endpoint. +// +// Only the server talks to providers. Every request is checked against +// Docwell's permissions before anything is sent. +package ai + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" +) + +// Provider kinds. +const ( + KindOpenAI = "openai" + KindAnthropic = "anthropic" + KindOllama = "ollama" +) + +// Message is one chat turn: role "user" or "assistant". +type Message struct { + Role string + Content string +} + +// ChatRequest is a chat call. System is the system prompt. +type ChatRequest struct { + Model string + System string + Messages []Message + MaxTokens int + // Effort is the Anthropic effort level ("" leaves the model's default). + Effort string +} + +// Usage is what a call cost, as the provider reports it. +type Usage struct { + InputTokens int `json:"inputTokens"` + OutputTokens int `json:"outputTokens"` +} + +// Provider is one configured backend. +type Provider interface { + // Chat streams the answer to onDelta and returns the usage once done. + Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) + // Embed returns one vector per input text. + Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) +} + +// ErrNoEmbeddings is returned by providers that cannot embed text. +var ErrNoEmbeddings = errors.New("this provider has no embeddings API") + +// ErrRefused is returned when the model declined to answer. +var ErrRefused = errors.New("the model declined to answer this request") + +// ProviderError is an HTTP error from a provider, with its status. +type ProviderError struct { + Status int + Message string +} + +func (e *ProviderError) Error() string { + if e.Message == "" { + return fmt.Sprintf("provider answered %d", e.Status) + } + return fmt.Sprintf("provider answered %d: %s", e.Status, e.Message) +} + +// DefaultBaseURL is the address a kind uses when a profile leaves it empty. +func DefaultBaseURL(kind string) string { + switch kind { + case KindOpenAI: + return "https://api.openai.com/v1" + case KindAnthropic: + return "https://api.anthropic.com" + case KindOllama: + return "http://localhost:11434" + } + return "" +} + +// NewProvider builds the driver for a kind. client carries the address +// rules (see webhooks.Guard) and has no overall timeout, so answers can +// stream for as long as the context allows. +func NewProvider(kind, baseURL, apiKey string, client *http.Client) (Provider, error) { + if baseURL == "" { + baseURL = DefaultBaseURL(kind) + } + baseURL = strings.TrimRight(baseURL, "/") + switch kind { + case KindOpenAI: + return &openAI{base: baseURL, key: apiKey, http: client}, nil + case KindAnthropic: + return newAnthropic(baseURL, apiKey, client), nil + case KindOllama: + return &ollama{base: baseURL, key: apiKey, http: client}, nil + } + return nil, fmt.Errorf("unknown provider kind %q", kind) +} + +// postJSON sends body and returns the response, or a ProviderError for a +// status of 400 or more. +func postJSON(ctx context.Context, client *http.Client, url string, headers map[string]string, body any) (*http.Response, error) { + raw, err := json.Marshal(body) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + for k, v := range headers { + if v != "" { + req.Header.Set(k, v) + } + } + res, err := client.Do(req) + if err != nil { + return nil, err + } + if res.StatusCode >= 400 { + defer res.Body.Close() + return nil, readProviderError(res) + } + return res, nil +} + +// readProviderError pulls a message out of the usual error bodies: +// {"error": {"message": …}}, {"error": "…"} or plain text. +func readProviderError(res *http.Response) error { + raw, _ := io.ReadAll(io.LimitReader(res.Body, 4096)) + var body struct { + Error json.RawMessage `json:"error"` + } + msg := strings.TrimSpace(string(raw)) + if json.Unmarshal(raw, &body) == nil && len(body.Error) > 0 { + var nested struct { + Message string `json:"message"` + } + var flat string + if json.Unmarshal(body.Error, &nested) == nil && nested.Message != "" { + msg = nested.Message + } else if json.Unmarshal(body.Error, &flat) == nil && flat != "" { + msg = flat + } + } + if len(msg) > 300 { + msg = msg[:300] + } + return &ProviderError{Status: res.StatusCode, Message: msg} +} + +// ---- OpenAI-compatible -------------------------------------------------------- + +type openAI struct { + base string + key string + http *http.Client +} + +func (p *openAI) headers() map[string]string { + if p.key == "" { + return nil + } + return map[string]string{"Authorization": "Bearer " + p.key} +} + +func (p *openAI) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) { + msgs := []map[string]string{} + if req.System != "" { + msgs = append(msgs, map[string]string{"role": "system", "content": req.System}) + } + for _, m := range req.Messages { + msgs = append(msgs, map[string]string{"role": m.Role, "content": m.Content}) + } + body := map[string]any{ + "model": req.Model, "messages": msgs, "stream": true, + "stream_options": map[string]bool{"include_usage": true}, + } + if req.MaxTokens > 0 { + body["max_tokens"] = req.MaxTokens + } + res, err := postJSON(ctx, p.http, p.base+"/chat/completions", p.headers(), body) + if err != nil { + return Usage{}, err + } + defer res.Body.Close() + var usage Usage + err = readSSE(res.Body, func(data string) error { + if data == "[DONE]" { + return io.EOF + } + var chunk struct { + Choices []struct { + Delta struct { + Content string `json:"content"` + } `json:"delta"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + Usage *struct { + Prompt int `json:"prompt_tokens"` + Completion int `json:"completion_tokens"` + } `json:"usage"` + } + if err := json.Unmarshal([]byte(data), &chunk); err != nil { + return nil + } + for _, c := range chunk.Choices { + if c.Delta.Content != "" { + onDelta(c.Delta.Content) + } + if c.FinishReason == "content_filter" { + return ErrRefused + } + } + if chunk.Usage != nil { + usage = Usage{InputTokens: chunk.Usage.Prompt, OutputTokens: chunk.Usage.Completion} + } + return nil + }) + return usage, err +} + +func (p *openAI) Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) { + res, err := postJSON(ctx, p.http, p.base+"/embeddings", p.headers(), map[string]any{"model": model, "input": texts}) + if err != nil { + return nil, Usage{}, err + } + defer res.Body.Close() + var body struct { + Data []struct { + Index int `json:"index"` + Embedding []float32 `json:"embedding"` + } `json:"data"` + Usage struct { + Prompt int `json:"prompt_tokens"` + } `json:"usage"` + } + if err := json.NewDecoder(res.Body).Decode(&body); err != nil { + return nil, Usage{}, fmt.Errorf("embeddings: %w", err) + } + out := make([][]float32, len(texts)) + for i, d := range body.Data { + idx := d.Index + if idx < 0 || idx >= len(out) { + idx = i + } + if idx < len(out) { + out[idx] = d.Embedding + } + } + for _, v := range out { + if len(v) == 0 { + return nil, Usage{}, errors.New("embeddings: the provider returned fewer vectors than texts") + } + } + return out, Usage{InputTokens: body.Usage.Prompt}, nil +} + +// readSSE calls fn with the data of each server-sent event until the +// stream ends or fn returns an error (io.EOF ends it cleanly). +func readSSE(r io.Reader, fn func(data string) error) error { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64<<10), 4<<20) + var data strings.Builder + flush := func() error { + if data.Len() == 0 { + return nil + } + d := data.String() + data.Reset() + return fn(d) + } + for sc.Scan() { + line := sc.Text() + if line == "" { + if err := flush(); err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return err + } + continue + } + if v, ok := strings.CutPrefix(line, "data:"); ok { + if data.Len() > 0 { + data.WriteByte('\n') + } + data.WriteString(strings.TrimPrefix(v, " ")) + } + } + if err := sc.Err(); err != nil { + return err + } + if err := flush(); err != nil && !errors.Is(err, io.EOF) { + return err + } + return nil +} + +// ---- Ollama --------------------------------------------------------------------- + +type ollama struct { + base string + key string + http *http.Client +} + +func (p *ollama) headers() map[string]string { + if p.key == "" { + return nil + } + return map[string]string{"Authorization": "Bearer " + p.key} +} + +func (p *ollama) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) { + msgs := []map[string]string{} + if req.System != "" { + msgs = append(msgs, map[string]string{"role": "system", "content": req.System}) + } + for _, m := range req.Messages { + msgs = append(msgs, map[string]string{"role": m.Role, "content": m.Content}) + } + body := map[string]any{"model": req.Model, "messages": msgs, "stream": true} + if req.MaxTokens > 0 { + body["options"] = map[string]int{"num_predict": req.MaxTokens} + } + res, err := postJSON(ctx, p.http, p.base+"/api/chat", p.headers(), body) + if err != nil { + return Usage{}, err + } + defer res.Body.Close() + dec := json.NewDecoder(res.Body) + var usage Usage + for { + var chunk struct { + Message struct { + Content string `json:"content"` + } `json:"message"` + Done bool `json:"done"` + Error string `json:"error"` + PromptEval int `json:"prompt_eval_count"` + Eval int `json:"eval_count"` + } + if err := dec.Decode(&chunk); err != nil { + if errors.Is(err, io.EOF) { + return usage, nil + } + return usage, err + } + if chunk.Error != "" { + return usage, &ProviderError{Status: http.StatusBadGateway, Message: chunk.Error} + } + if chunk.Message.Content != "" { + onDelta(chunk.Message.Content) + } + if chunk.Done { + return Usage{InputTokens: chunk.PromptEval, OutputTokens: chunk.Eval}, nil + } + } +} + +func (p *ollama) Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) { + res, err := postJSON(ctx, p.http, p.base+"/api/embed", p.headers(), map[string]any{"model": model, "input": texts}) + if err != nil { + return nil, Usage{}, err + } + defer res.Body.Close() + var body struct { + Embeddings [][]float32 `json:"embeddings"` + PromptEval int `json:"prompt_eval_count"` + } + if err := json.NewDecoder(res.Body).Decode(&body); err != nil { + return nil, Usage{}, fmt.Errorf("embeddings: %w", err) + } + if len(body.Embeddings) != len(texts) { + return nil, Usage{}, errors.New("embeddings: the provider returned fewer vectors than texts") + } + return body.Embeddings, Usage{InputTokens: body.PromptEval}, nil +} diff --git a/Server/internal/ai/service.go b/Server/internal/ai/service.go new file mode 100644 index 0000000..e71a188 --- /dev/null +++ b/Server/internal/ai/service.go @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "log/slog" + "net" + "net/http" + "regexp" + "sync" + "syscall" + "time" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/directory" + "docwell/server/internal/store/pocketbase" + "docwell/server/internal/webhooks" +) + +// Options configure the service. +type Options struct { + // Secret encrypts provider keys (DOCWELL_SECRET_KEY, or a value derived + // from the PocketBase password). + Secret string + // DataDir holds the vector store (ai.db). + DataDir string + // AllowLocal lets workspace profiles reach loopback and private + // addresses, like webhooks. Instance profiles always may. + AllowLocal bool +} + +// Service is the AI layer. +type Service struct { + pb *pocketbase.Client + dir *directory.Service + keys *sealer + guarded *http.Client + open *http.Client + store *Store + log *slog.Logger + + usageMu sync.Mutex + passMu sync.Mutex // one indexing pass at a time + wakeCh chan struct{} + track func(name string, run func() error) error + + mu sync.Mutex + status map[string]*indexState // workspace → indexer progress +} + +// New opens the vector store and returns the service. +func New(pb *pocketbase.Client, dir *directory.Service, log *slog.Logger, o Options) (*Service, error) { + store, err := OpenStore(o.DataDir) + if err != nil { + return nil, err + } + return newService(pb, dir, log, o, store), nil +} + +func newService(pb *pocketbase.Client, dir *directory.Service, log *slog.Logger, o Options, store *Store) *Service { + transport := func(control func(network, address string, c syscall.RawConn) error) *http.Client { + d := &net.Dialer{Timeout: 15 * time.Second} + if control != nil { + d.Control = control + } + return &http.Client{Transport: &http.Transport{ + DialContext: d.DialContext, Proxy: http.ProxyFromEnvironment, + TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 5 * time.Minute, + MaxIdleConnsPerHost: 4, IdleConnTimeout: 90 * time.Second, + }} + } + return &Service{ + pb: pb, dir: dir, keys: newSealer(o.Secret), log: log, store: store, + guarded: transport(webhooks.Guard(o.AllowLocal)), + open: transport(nil), + wakeCh: make(chan struct{}, 1), + status: map[string]*indexState{}, + } +} + +// Close closes the vector store. +func (s *Service) Close() error { return s.store.Close() } + +// Track reports each indexing pass to fn (the admin panel's job list). +func (s *Service) Track(fn func(name string, run func() error) error) { s.track = fn } + +func (s *Service) wake() { + select { + case s.wakeCh <- struct{}{}: + default: + } +} + +var idPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +func validID(id string) bool { return idPattern.MatchString(id) } + +// ---- What a member sees -------------------------------------------------------- + +// Availability tells a workspace member what AI can do there. +type Availability struct { + // Chat is true when a profile with a chat model is set up and AI is on. + Chat bool `json:"chat"` + // Embeddings is true when the workspace is indexed for retrieval. + Embeddings bool `json:"embeddings"` + CanManage bool `json:"canManage"` +} + +// Available reports what AI offers in a workspace to c. +func (s *Service) Available(ctx context.Context, c access.Caller, wsID string) (Availability, error) { + role, err := s.dir.WorkspaceRole(ctx, c, wsID) + if err != nil { + return Availability{}, err + } + st, err := s.settings(ctx, wsID) + if err != nil { + return Availability{}, err + } + out := Availability{CanManage: access.AtLeast(role, access.WorkspaceAdmin)} + if !st.Enabled { + return out, nil + } + chain, err := s.chain(ctx, wsID, st) + if err != nil { + return out, err + } + for _, r := range chain { + if r.ChatModel != "" { + out.Chat = true + } + } + _, hasEmbed := embedProfile(chain) + out.Embeddings = st.Index && hasEmbed + return out, nil +} + +// ready loads what a chat or writing action in a workspace needs, checking +// that c is a member and AI is on. +func (s *Service) ready(ctx context.Context, c access.Caller, wsID string) (Settings, []profileRecord, error) { + if _, err := s.dir.WorkspaceRole(ctx, c, wsID); err != nil { + return Settings{}, nil, err + } + st, err := s.settings(ctx, wsID) + if err != nil { + return st, nil, err + } + if !st.Enabled { + return st, nil, apperr.Forbidden("AI is turned off in this workspace") + } + chain, err := s.chain(ctx, wsID, st) + if err != nil { + return st, nil, err + } + return st, chain, nil +} diff --git a/Server/internal/ai/store.go b/Server/internal/ai/store.go new file mode 100644 index 0000000..2e94935 --- /dev/null +++ b/Server/internal/ai/store.go @@ -0,0 +1,363 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "container/heap" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "math" + "os" + "path/filepath" + "strings" + "time" + + bolt "go.etcd.io/bbolt" +) + +// Store keeps embedding vectors per workspace in a bbolt file (ADR-15). It +// can always be thrown away and rebuilt from PocketBase. +// +// Layout: bucket "ws" → one bucket per workspace → "meta" (JSON), +// "docs" (source key → hash and chunk count) and "chunks" (source key + "/" + +// number → vector and metadata). A source key is "page/" or "file/". +type Store struct{ db *bolt.DB } + +// Chunk is one piece of a source with its vector. +type Chunk struct { + Source string `json:"-"` + Space string `json:"space,omitempty"` + Page string `json:"page,omitempty"` + File string `json:"file,omitempty"` + Block string `json:"block,omitempty"` + Title string `json:"title"` + Text string `json:"text"` + Vector []float32 `json:"-"` +} + +// Meta is a workspace's index state. +type Meta struct { + // Model is the profile and model the vectors come from (":"). + Model string `json:"model"` + Dims int `json:"dims"` + Checkpoint string `json:"checkpoint"` + FilesAt string `json:"filesAt"` +} + +var ( + bucketWS = []byte("ws") + bucketMeta = []byte("meta") + bucketDocs = []byte("docs") + bucketChunks = []byte("chunks") + keyMeta = []byte("meta") +) + +// OpenStore opens (or creates) dir/ai.db. +func OpenStore(dir string) (*Store, error) { + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, err + } + path := filepath.Join(dir, "ai.db") + db, err := bolt.Open(path, 0o600, &bolt.Options{Timeout: 5 * time.Second}) + if err != nil { + return nil, fmt.Errorf("ai store %s: %w", path, err) + } + if err := db.Update(func(tx *bolt.Tx) error { + _, err := tx.CreateBucketIfNotExists(bucketWS) + return err + }); err != nil { + _ = db.Close() + return nil, err + } + return &Store{db: db}, nil +} + +func (s *Store) Close() error { return s.db.Close() } + +func wsBucket(tx *bolt.Tx, ws string, create bool) (*bolt.Bucket, error) { + root := tx.Bucket(bucketWS) + if !create { + return root.Bucket([]byte(ws)), nil + } + b, err := root.CreateBucketIfNotExists([]byte(ws)) + if err != nil { + return nil, err + } + for _, name := range [][]byte{bucketMeta, bucketDocs, bucketChunks} { + if _, err := b.CreateBucketIfNotExists(name); err != nil { + return nil, err + } + } + return b, nil +} + +// Meta returns a workspace's index state (zero when it has none). +func (s *Store) Meta(ws string) (Meta, error) { + var m Meta + err := s.db.View(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + if raw := b.Bucket(bucketMeta).Get(keyMeta); raw != nil { + return json.Unmarshal(raw, &m) + } + return nil + }) + return m, err +} + +// SetMeta saves a workspace's index state. +func (s *Store) SetMeta(ws string, m Meta) error { + raw, _ := json.Marshal(m) + return s.db.Update(func(tx *bolt.Tx) error { + b, err := wsBucket(tx, ws, true) + if err != nil { + return err + } + return b.Bucket(bucketMeta).Put(keyMeta, raw) + }) +} + +// DropWorkspace forgets a workspace's vectors and state. +func (s *Store) DropWorkspace(ws string) error { + return s.db.Update(func(tx *bolt.Tx) error { + err := tx.Bucket(bucketWS).DeleteBucket([]byte(ws)) + if errors.Is(err, bolt.ErrBucketNotFound) { + return nil + } + return err + }) +} + +// Workspaces lists the workspaces the store has state for. +func (s *Store) Workspaces() ([]string, error) { + var out []string + err := s.db.View(func(tx *bolt.Tx) error { + return tx.Bucket(bucketWS).ForEachBucket(func(k []byte) error { + out = append(out, string(k)) + return nil + }) + }) + return out, err +} + +type docEntry struct { + Hash string `json:"hash"` + Chunks int `json:"chunks"` +} + +// Hash returns the hash a source was last indexed with ("" when it was not). +func (s *Store) Hash(ws, source string) (string, error) { + var d docEntry + err := s.db.View(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + if raw := b.Bucket(bucketDocs).Get([]byte(source)); raw != nil { + return json.Unmarshal(raw, &d) + } + return nil + }) + return d.Hash, err +} + +// Sources lists the indexed source keys of a workspace. +func (s *Store) Sources(ws string) ([]string, error) { + var out []string + err := s.db.View(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + return b.Bucket(bucketDocs).ForEach(func(k, _ []byte) error { + out = append(out, string(k)) + return nil + }) + }) + return out, err +} + +// Counts is how many sources and chunks a workspace has indexed. +func (s *Store) Counts(ws string) (pages, files, chunks int, err error) { + err = s.db.View(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + err := b.Bucket(bucketDocs).ForEach(func(k, v []byte) error { + if strings.HasPrefix(string(k), "file/") { + files++ + } else { + pages++ + } + return nil + }) + chunks = b.Bucket(bucketChunks).Stats().KeyN + return err + }) + return pages, files, chunks, err +} + +// Put replaces the chunks of one source. +func (s *Store) Put(ws, source, hash string, chunks []Chunk) error { + return s.db.Update(func(tx *bolt.Tx) error { + b, err := wsBucket(tx, ws, true) + if err != nil { + return err + } + if err := dropChunks(b, source); err != nil { + return err + } + cb := b.Bucket(bucketChunks) + for i, c := range chunks { + if err := cb.Put(chunkKey(source, i), encodeChunk(c)); err != nil { + return err + } + } + raw, _ := json.Marshal(docEntry{Hash: hash, Chunks: len(chunks)}) + return b.Bucket(bucketDocs).Put([]byte(source), raw) + }) +} + +// Drop removes a source. +func (s *Store) Drop(ws, source string) error { + return s.db.Update(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + if err := dropChunks(b, source); err != nil { + return err + } + return b.Bucket(bucketDocs).Delete([]byte(source)) + }) +} + +func chunkKey(source string, n int) []byte { return fmt.Appendf(nil, "%s/%05d", source, n) } + +func dropChunks(b *bolt.Bucket, source string) error { + c := b.Bucket(bucketChunks).Cursor() + prefix := []byte(source + "/") + var keys [][]byte + for k, _ := c.Seek(prefix); k != nil && strings.HasPrefix(string(k), string(prefix)); k, _ = c.Next() { + keys = append(keys, append([]byte(nil), k...)) + } + for _, k := range keys { + if err := b.Bucket(bucketChunks).Delete(k); err != nil { + return err + } + } + return nil +} + +// encodeChunk is: uint32 dims, dims × float32 (little endian), JSON metadata. +func encodeChunk(c Chunk) []byte { + meta, _ := json.Marshal(c) + out := make([]byte, 4+4*len(c.Vector), 4+4*len(c.Vector)+len(meta)) + binary.LittleEndian.PutUint32(out, uint32(len(c.Vector))) + for i, f := range c.Vector { + binary.LittleEndian.PutUint32(out[4+4*i:], math.Float32bits(f)) + } + return append(out, meta...) +} + +// dot scores a stored chunk against q without decoding its metadata. +func dot(raw []byte, q []float32) (float32, bool) { + if len(raw) < 4 { + return 0, false + } + n := int(binary.LittleEndian.Uint32(raw)) + if n != len(q) || len(raw) < 4+4*n { + return 0, false + } + var sum float32 + for i := range n { + sum += math.Float32frombits(binary.LittleEndian.Uint32(raw[4+4*i:])) * q[i] + } + return sum, true +} + +func decodeMeta(raw []byte) (Chunk, error) { + n := int(binary.LittleEndian.Uint32(raw)) + var c Chunk + err := json.Unmarshal(raw[4+4*n:], &c) + return c, err +} + +// normalize scales v to unit length in place (cosine = dot product). +func normalize(v []float32) []float32 { + var sum float64 + for _, f := range v { + sum += float64(f) * float64(f) + } + if sum == 0 { + return v + } + inv := float32(1 / math.Sqrt(sum)) + for i := range v { + v[i] *= inv + } + return v +} + +// Scored is a chunk with its similarity to the query. +type Scored struct { + Chunk + Score float32 `json:"score"` +} + +type minHeap []Scored + +func (h minHeap) Len() int { return len(h) } +func (h minHeap) Less(i, j int) bool { return h[i].Score < h[j].Score } +func (h minHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *minHeap) Push(x any) { *h = append(*h, x.(Scored)) } +func (h *minHeap) Pop() any { + old := *h + x := old[len(old)-1] + *h = old[:len(old)-1] + return x +} + +// Search returns the k chunks of ws most similar to q (normalised) that +// allow accepts, best first. Metadata is decoded only for chunks that would +// make the list. +func (s *Store) Search(ws string, q []float32, k int, allow func(Chunk) bool) ([]Scored, error) { + h := &minHeap{} + err := s.db.View(func(tx *bolt.Tx) error { + b, _ := wsBucket(tx, ws, false) + if b == nil { + return nil + } + return b.Bucket(bucketChunks).ForEach(func(key, raw []byte) error { + score, ok := dot(raw, q) + if !ok || (h.Len() >= k && score <= (*h)[0].Score) { + return nil + } + c, err := decodeMeta(raw) + if err != nil { + return nil + } + if parts := strings.SplitN(string(key), "/", 3); len(parts) == 3 { + c.Source = parts[0] + "/" + parts[1] + } + if allow != nil && !allow(c) { + return nil + } + heap.Push(h, Scored{Chunk: c, Score: score}) + if h.Len() > k { + heap.Pop(h) + } + return nil + }) + }) + out := make([]Scored, h.Len()) + for i := len(out) - 1; i >= 0; i-- { + out[i] = heap.Pop(h).(Scored) + } + return out, err +} diff --git a/Server/internal/ai/write.go b/Server/internal/ai/write.go new file mode 100644 index 0000000..dcd7118 --- /dev/null +++ b/Server/internal/ai/write.go @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package ai + +import ( + "context" + "strings" + "unicode/utf8" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" +) + +// ---- Writing actions on a selection -------------------------------------------------- + +// WriteInput is a writing action. Text is the selection; Before is the text +// in front of it (for "continue"); Language is the target of "translate"; +// Instruction is the request of "custom". +type WriteInput struct { + Action string `json:"action"` + Text string `json:"text"` + Before string `json:"before"` + Language string `json:"language"` + Instruction string `json:"instruction"` +} + +const writeSystem = `You are a writing assistant inside Docwell, a team wiki. You get a piece of a page and a task. Reply with the resulting text only, in Markdown, ready to put into the page: no preamble, no quotes around it, no remarks about what you changed. Keep the meaning, facts, names, links and formatting (lists, headings, emphasis) unless the task asks otherwise. Unless told to translate, write in the language of the text.` + +var writeTasks = map[string]string{ + "rewrite": "Rewrite the text so it reads clearly and naturally.", + "summarize": "Summarise the text in a few sentences or a short list of the key points.", + "translate": "Translate the text into %s.", + "continue": "Continue writing after the text, in the same voice and format. Reply with the continuation only.", + "shorter": "Make the text shorter, keeping what matters.", + "longer": "Expand the text with more detail and explanation, without inventing facts.", + "fix": "Fix spelling, grammar and punctuation. Change nothing else.", + "custom": "%s", +} + +// Write streams the result of a writing action to onDelta. +func (s *Service) Write(ctx context.Context, c access.Caller, wsID string, in WriteInput, onDelta func(string)) error { + task, ok := writeTasks[in.Action] + if !ok { + return apperr.InvalidFields(map[string]string{"action": "Unknown writing action."}) + } + text := strings.TrimSpace(in.Text) + if text == "" && in.Action != "continue" { + return apperr.InvalidFields(map[string]string{"text": "Select some text first."}) + } + if utf8.RuneCountInString(text) > 20000 { + return apperr.InvalidFields(map[string]string{"text": "Select at most 20 000 characters."}) + } + switch in.Action { + case "translate": + lang := strings.TrimSpace(in.Language) + if lang == "" || len(lang) > 60 { + return apperr.InvalidFields(map[string]string{"language": "Choose a language."}) + } + task = strings.Replace(task, "%s", lang, 1) + case "custom": + ins := strings.TrimSpace(in.Instruction) + if ins == "" || utf8.RuneCountInString(ins) > 2000 { + return apperr.InvalidFields(map[string]string{"instruction": "Say what to do, in up to 2 000 characters."}) + } + task = ins + } + _, chain, err := s.ready(ctx, c, wsID) + if err != nil { + return err + } + var prompt strings.Builder + prompt.WriteString("Task: " + task + "\n\n") + if in.Action == "continue" { + before := in.Before + if utf8.RuneCountInString(before) > 6000 { + r := []rune(before) + before = string(r[len(r)-6000:]) + } + prompt.WriteString("Text so far:\n\n" + strings.TrimSpace(before+"\n"+text) + "\n") + } else { + prompt.WriteString("Text:\n\n" + text + "\n") + } + _, err = s.chat(ctx, chain, ChatRequest{ + System: writeSystem, MaxTokens: 8000, + Messages: []Message{{Role: "user", Content: prompt.String()}}, + }, onDelta) + if err != nil { + if _, ok := apperr.As(err); ok { + return err + } + return apperr.Invalid(userError(err)) + } + return nil +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index a59585e..982ac36 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -27,6 +27,132 @@ func (e AdminStatsScope) Valid() bool { } } +// Defines values for AiMessageRole. +const ( + AiMessageRoleAssistant AiMessageRole = "assistant" + AiMessageRoleUser AiMessageRole = "user" +) + +// Valid indicates whether the value is a known member of the AiMessageRole enum. +func (e AiMessageRole) Valid() bool { + switch e { + case AiMessageRoleAssistant: + return true + case AiMessageRoleUser: + return true + default: + return false + } +} + +// Defines values for AiProfileInputEffort. +const ( + AiProfileInputEffortEmpty AiProfileInputEffort = "" + AiProfileInputEffortHigh AiProfileInputEffort = "high" + AiProfileInputEffortLow AiProfileInputEffort = "low" + AiProfileInputEffortMax AiProfileInputEffort = "max" + AiProfileInputEffortMedium AiProfileInputEffort = "medium" + AiProfileInputEffortXhigh AiProfileInputEffort = "xhigh" +) + +// Valid indicates whether the value is a known member of the AiProfileInputEffort enum. +func (e AiProfileInputEffort) Valid() bool { + switch e { + case AiProfileInputEffortEmpty: + return true + case AiProfileInputEffortHigh: + return true + case AiProfileInputEffortLow: + return true + case AiProfileInputEffortMax: + return true + case AiProfileInputEffortMedium: + return true + case AiProfileInputEffortXhigh: + return true + default: + return false + } +} + +// Defines values for AiProviderKind. +const ( + Anthropic AiProviderKind = "anthropic" + Ollama AiProviderKind = "ollama" + Openai AiProviderKind = "openai" +) + +// Valid indicates whether the value is a known member of the AiProviderKind enum. +func (e AiProviderKind) Valid() bool { + switch e { + case Anthropic: + return true + case Ollama: + return true + case Openai: + return true + default: + return false + } +} + +// Defines values for AiScope. +const ( + AiScopePage AiScope = "page" + AiScopeSpace AiScope = "space" + AiScopeWorkspace AiScope = "workspace" +) + +// Valid indicates whether the value is a known member of the AiScope enum. +func (e AiScope) Valid() bool { + switch e { + case AiScopePage: + return true + case AiScopeSpace: + return true + case AiScopeWorkspace: + return true + default: + return false + } +} + +// Defines values for AiWriteAction. +const ( + Continue AiWriteAction = "continue" + Custom AiWriteAction = "custom" + Fix AiWriteAction = "fix" + Longer AiWriteAction = "longer" + Rewrite AiWriteAction = "rewrite" + Shorter AiWriteAction = "shorter" + Summarize AiWriteAction = "summarize" + Translate AiWriteAction = "translate" +) + +// Valid indicates whether the value is a known member of the AiWriteAction enum. +func (e AiWriteAction) Valid() bool { + switch e { + case Continue: + return true + case Custom: + return true + case Fix: + return true + case Longer: + return true + case Rewrite: + return true + case Shorter: + return true + case Summarize: + return true + case Translate: + return true + default: + return false + } +} + // Defines values for ApiTokenScope. const ( ApiTokenScopeRead ApiTokenScope = "read" @@ -766,6 +892,220 @@ type AdminStats struct { // AdminStatsScope defines model for AdminStats.Scope. type AdminStatsScope string +// AiAvailability defines model for AiAvailability. +type AiAvailability struct { + // CanManage The caller may change the workspace's AI settings + CanManage bool `json:"canManage"` + + // Chat A profile with a chat model is set up and AI is on + Chat bool `json:"chat"` + + // Embeddings The workspace is indexed for retrieval + Embeddings bool `json:"embeddings"` +} + +// AiCitation defines model for AiCitation. +type AiCitation struct { + // Block The cited block (link with #b-) + Block *string `json:"block,omitempty"` + + // File An extra file instead of a page + File *string `json:"file,omitempty"` + + // N The number the answer cites as [n] + N int `json:"n"` + Page *string `json:"page,omitempty"` + Snippet string `json:"snippet"` + Title string `json:"title"` +} + +// AiFile defines model for AiFile. +type AiFile struct { + Chars int `json:"chars"` + Created string `json:"created"` + Id string `json:"id"` + Indexed bool `json:"indexed"` + Name string `json:"name"` + Size int `json:"size"` +} + +// AiForkInput defines model for AiForkInput. +type AiForkInput struct { + // Message The last message to copy; empty copies all + Message *string `json:"message,omitempty"` +} + +// AiIndexStatus defines model for AiIndexStatus. +type AiIndexStatus struct { + Chunks int `json:"chunks"` + Enabled bool `json:"enabled"` + Files int `json:"files"` + Indexed int `json:"indexed"` + LastError string `json:"lastError"` + LastRun string `json:"lastRun"` + Model string `json:"model"` + + // Pages Pages that can be indexed + Pages int `json:"pages"` + + // Profile The profile vectors come from; empty when none has an embedding model + Profile string `json:"profile"` + Running bool `json:"running"` +} + +// AiMessage defines model for AiMessage. +type AiMessage struct { + Citations *[]AiCitation `json:"citations,omitempty"` + + // Content Markdown + Content string `json:"content"` + Created string `json:"created"` + + // Error Why the answer stopped + Error *string `json:"error,omitempty"` + Id string `json:"id"` + Role AiMessageRole `json:"role"` +} + +// AiMessageRole defines model for AiMessage.Role. +type AiMessageRole string + +// AiProfile defines model for AiProfile. +type AiProfile struct { + // BaseUrl Empty for the kind's default address + BaseUrl string `json:"baseUrl"` + ChatModel string `json:"chatModel"` + Created string `json:"created"` + + // Effort Anthropic effort level + Effort string `json:"effort"` + + // EmbedModel Empty when the profile is not used for embeddings + EmbedModel string `json:"embedModel"` + Enabled bool `json:"enabled"` + Id string `json:"id"` + + // KeySet An API key is stored (keys are never returned) + KeySet bool `json:"keySet"` + + // Kind openai is any OpenAI-compatible API + Kind AiProviderKind `json:"kind"` + LastError string `json:"lastError"` + LastUsed string `json:"lastUsed"` + Name string `json:"name"` + Position int `json:"position"` + Usage struct { + InputTokens int `json:"inputTokens"` + OutputTokens int `json:"outputTokens"` + Requests int `json:"requests"` + } `json:"usage"` + + // Workspace Empty for an instance default + Workspace string `json:"workspace"` +} + +// AiProfileInput Creating needs name and kind; updating changes the fields that are set +type AiProfileInput struct { + // ApiKey Write-only; an empty string removes the key + ApiKey *string `json:"apiKey,omitempty"` + BaseUrl *string `json:"baseUrl,omitempty"` + ChatModel *string `json:"chatModel,omitempty"` + Effort *AiProfileInputEffort `json:"effort,omitempty"` + EmbedModel *string `json:"embedModel,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + + // Kind openai is any OpenAI-compatible API + Kind *AiProviderKind `json:"kind,omitempty"` + Name *string `json:"name,omitempty"` +} + +// AiProfileInputEffort defines model for AiProfileInput.Effort. +type AiProfileInputEffort string + +// AiProviderKind openai is any OpenAI-compatible API +type AiProviderKind string + +// AiScope defines model for AiScope. +type AiScope string + +// AiSession defines model for AiSession. +type AiSession struct { + Created string `json:"created"` + Id string `json:"id"` + Messages []AiMessage `json:"messages"` + Scope AiScope `json:"scope"` + + // ScopeId The space or page; empty for the workspace + ScopeId string `json:"scopeId"` + Title string `json:"title"` + Updated string `json:"updated"` + Workspace string `json:"workspace"` +} + +// AiSessionInput defines model for AiSessionInput. +type AiSessionInput struct { + Scope *AiScope `json:"scope,omitempty"` + ScopeId *string `json:"scopeId,omitempty"` + Title *string `json:"title,omitempty"` +} + +// AiSessionSummary defines model for AiSessionSummary. +type AiSessionSummary struct { + Created string `json:"created"` + Id string `json:"id"` + Scope AiScope `json:"scope"` + + // ScopeId The space or page; empty for the workspace + ScopeId string `json:"scopeId"` + Title string `json:"title"` + Updated string `json:"updated"` +} + +// AiSettings defines model for AiSettings. +type AiSettings struct { + Enabled bool `json:"enabled"` + + // Ignored Pages (with their subpages) that are neither indexed nor retrieved + Ignored []string `json:"ignored"` + + // Index Embed pages for retrieval (sends every page to the embedding provider) + Index bool `json:"index"` + + // UseInstanceProfiles After its own profiles + UseInstanceProfiles bool `json:"useInstanceProfiles"` +} + +// AiTestResult defines model for AiTestResult. +type AiTestResult struct { + // Chat The model's reply + Chat string `json:"chat"` + Dimensions int `json:"dimensions"` + Embeddings string `json:"embeddings"` + Error string `json:"error"` + LatencyMs int `json:"latencyMs"` + Ok bool `json:"ok"` +} + +// AiWriteAction defines model for AiWriteAction. +type AiWriteAction string + +// AiWriteInput defines model for AiWriteInput. +type AiWriteInput struct { + Action AiWriteAction `json:"action"` + + // Before Text in front of the selection (continue) + Before *string `json:"before,omitempty"` + + // Instruction What to do (custom) + Instruction *string `json:"instruction,omitempty"` + + // Language Target language (translate) + Language *string `json:"language,omitempty"` + + // Text The selection + Text string `json:"text"` +} + // ApiToken defines model for ApiToken. type ApiToken struct { Created string `json:"created"` @@ -1060,6 +1400,11 @@ type GroupRequest struct { Name *string `json:"name,omitempty"` } +// IdList defines model for IdList. +type IdList struct { + Ids []string `json:"ids"` +} + // InstanceSettings defines model for InstanceSettings. type InstanceSettings struct { Auth AuthSettings `json:"auth"` @@ -1958,6 +2303,11 @@ type SendTestEmailJSONBody struct { To openapi_types.Email `json:"to"` } +// AskAiJSONBody defines parameters for AskAi. +type AskAiJSONBody struct { + Content string `json:"content"` +} + // AcceptInviteJSONBody defines parameters for AcceptInvite. type AcceptInviteJSONBody struct { Name *string `json:"name,omitempty"` @@ -2267,6 +2617,11 @@ type UpdateWorkspaceJSONBody struct { Name *string `json:"name,omitempty"` } +// AddAiFileMultipartBody defines parameters for AddAiFile. +type AddAiFileMultipartBody struct { + File openapi_types.File `json:"file"` +} + // ListDocsParams defines parameters for ListDocs. type ListDocsParams struct { // Space Only pages in this space @@ -2347,12 +2702,33 @@ type CreateSpaceJSONBody struct { Visibility *SpaceVisibility `json:"visibility,omitempty"` } +// McpJSONBody defines parameters for Mcp. +type McpJSONBody map[string]interface{} + +// CreateInstanceAiProfileJSONRequestBody defines body for CreateInstanceAiProfile for application/json ContentType. +type CreateInstanceAiProfileJSONRequestBody = AiProfileInput + +// OrderInstanceAiProfilesJSONRequestBody defines body for OrderInstanceAiProfiles for application/json ContentType. +type OrderInstanceAiProfilesJSONRequestBody = IdList + // UpdateInstanceSettingsJSONRequestBody defines body for UpdateInstanceSettings for application/json ContentType. type UpdateInstanceSettingsJSONRequestBody = InstanceSettingsUpdate // SendTestEmailJSONRequestBody defines body for SendTestEmail for application/json ContentType. type SendTestEmailJSONRequestBody SendTestEmailJSONBody +// UpdateAiProfileJSONRequestBody defines body for UpdateAiProfile for application/json ContentType. +type UpdateAiProfileJSONRequestBody = AiProfileInput + +// UpdateAiSessionJSONRequestBody defines body for UpdateAiSession for application/json ContentType. +type UpdateAiSessionJSONRequestBody = AiSessionInput + +// ForkAiSessionJSONRequestBody defines body for ForkAiSession for application/json ContentType. +type ForkAiSessionJSONRequestBody = AiForkInput + +// AskAiJSONRequestBody defines body for AskAi for application/json ContentType. +type AskAiJSONRequestBody AskAiJSONBody + // AcceptInviteJSONRequestBody defines body for AcceptInvite for application/json ContentType. type AcceptInviteJSONRequestBody AcceptInviteJSONBody @@ -2506,6 +2882,24 @@ type CreateWorkspaceJSONRequestBody CreateWorkspaceJSONBody // UpdateWorkspaceJSONRequestBody defines body for UpdateWorkspace for application/json ContentType. type UpdateWorkspaceJSONRequestBody UpdateWorkspaceJSONBody +// AddAiFileMultipartRequestBody defines body for AddAiFile for multipart/form-data ContentType. +type AddAiFileMultipartRequestBody AddAiFileMultipartBody + +// CreateAiProfileJSONRequestBody defines body for CreateAiProfile for application/json ContentType. +type CreateAiProfileJSONRequestBody = AiProfileInput + +// OrderAiProfilesJSONRequestBody defines body for OrderAiProfiles for application/json ContentType. +type OrderAiProfilesJSONRequestBody = IdList + +// CreateAiSessionJSONRequestBody defines body for CreateAiSession for application/json ContentType. +type CreateAiSessionJSONRequestBody = AiSessionInput + +// SaveAiSettingsJSONRequestBody defines body for SaveAiSettings for application/json ContentType. +type SaveAiSettingsJSONRequestBody = AiSettings + +// AiWriteJSONRequestBody defines body for AiWrite for application/json ContentType. +type AiWriteJSONRequestBody = AiWriteInput + // CreateCollectionJSONRequestBody defines body for CreateCollection for application/json ContentType. type CreateCollectionJSONRequestBody = CollectionInput @@ -2532,3 +2926,6 @@ type CreateTagJSONRequestBody = TagInput // CreateWebhookJSONRequestBody defines body for CreateWebhook for application/json ContentType. type CreateWebhookJSONRequestBody = WebhookInput + +// McpJSONRequestBody defines body for Mcp for application/json ContentType. +type McpJSONRequestBody McpJSONBody diff --git a/Server/internal/config/config.go b/Server/internal/config/config.go index 36846f3..0aeb37d 100644 --- a/Server/internal/config/config.go +++ b/Server/internal/config/config.go @@ -32,12 +32,15 @@ type Config struct { AdminPassword string AdminName string - PocketBaseURL string + PocketBaseURL string PocketBaseEmail string PocketBasePassword string - // DataDir holds docwell-server's own files (the search index). + // DataDir holds docwell-server's own files (the search index, AI vectors). DataDir string + // SecretKey encrypts stored AI provider keys; empty derives one from the + // PocketBase password. + SecretKey string // MaxUploadMB caps one attachment. MaxUploadMB int @@ -105,6 +108,7 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) { AdminPassword: get("DOCWELL_ADMIN_PASSWORD", ""), AdminName: get("DOCWELL_ADMIN_NAME", ""), DataDir: get("DOCWELL_DATA_DIR", "./data"), + SecretKey: get("DOCWELL_SECRET_KEY", ""), ShutdownTimeout: 15 * time.Second, WebhooksAllowLocal: get("DOCWELL_WEBHOOKS_ALLOW_LOCAL", "false") == "true", } diff --git a/Server/internal/directory/ai.go b/Server/internal/directory/ai.go new file mode 100644 index 0000000..4d91b59 --- /dev/null +++ b/Server/internal/directory/ai.go @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "encoding/json" + "fmt" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/convert" + "docwell/server/internal/store/pocketbase" +) + +// ---- What the AI layer (ADR-15) needs from the directory ---------------------- + +// WorkspaceRole is c's effective role in a workspace; a workspace c cannot +// open is not found. +func (s *Service) WorkspaceRole(ctx context.Context, c access.Caller, wsID string) (string, error) { + _, role, err := s.workspaceFor(ctx, c, wsID) + return role, err +} + +// Readable answers which pages of one workspace a caller may read. It is +// built once per request, so filtering many retrieval hits stays cheap. +type Readable struct { + Workspace string + // Spaces are the spaces the caller can open, by id, with their names. + Spaces map[string]string + rules map[string]pageRules +} + +// Can reports whether the caller may read page in space. +func (r *Readable) Can(space, page string) bool { + rules, ok := r.rules[space] + return ok && rules.role(page) != "" +} + +// Readable loads the caller's reading rights in a workspace. +func (s *Service) Readable(ctx context.Context, c access.Caller, wsID string) (*Readable, error) { + spaces, err := s.ListSpaces(ctx, c, wsID) + if err != nil { + return nil, err + } + r := &Readable{Workspace: wsID, Spaces: map[string]string{}, rules: map[string]pageRules{}} + for _, sp := range spaces { + _, rules, err := s.spaceRules(ctx, c, sp.ID) + if err != nil { + return nil, err + } + r.Spaces[sp.ID], r.rules[sp.ID] = sp.Name, rules + } + return r, nil +} + +// PageText is a page as the AI layer reads it. +type PageText struct { + ID string `json:"id"` + Workspace string `json:"workspace"` + Space string `json:"space"` + Parent string `json:"parent"` + Title string `json:"title"` + Icon string `json:"icon"` + Updated string `json:"updated"` + // Markdown is the page body; Doc is the same as Tiptap JSON. + Markdown string `json:"markdown"` + Doc json.RawMessage `json:"-"` + CanEdit bool `json:"canEdit"` +} + +// ReadPage returns a page c may read, with its body as Markdown. +func (s *Service) ReadPage(ctx context.Context, c access.Caller, id string) (PageText, error) { + if !validID(id) { + return PageText{}, apperr.NotFound("page not found") + } + p, a, err := s.pageFor(ctx, c, id) + if err != nil { + return PageText{}, err + } + if p.DeletedAt != "" { + return PageText{}, apperr.NotFound("page not found") + } + doc, err := s.docs.Content(ctx, p.ID) + if err != nil { + return PageText{}, err + } + node, err := convert.Parse(doc) + if err != nil { + return PageText{}, err + } + return PageText{ + ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon, + Updated: p.Updated, Markdown: convert.Markdown(node, convert.Options{}), Doc: doc, + CanEdit: access.SpaceAtLeast(a.role, access.SpaceEditor) && p.ArchivedAt == "", + }, nil +} + +// PageSummary is one page in a listing for the AI layer. +type PageSummary struct { + ID string `json:"id"` + Space string `json:"space"` + Title string `json:"title"` + Updated string `json:"updated"` +} + +// RecentPages lists the pages of a workspace c may read, most recently +// changed first (a space narrows it). +func (s *Service) RecentPages(ctx context.Context, c access.Caller, wsID, space string, limit int) ([]PageSummary, error) { + r, err := s.Readable(ctx, c, wsID) + if err != nil { + return nil, err + } + filter := fmt.Sprintf("workspace = '%s' && deleted_at = '' && archived_at = ''", wsID) + if space != "" { + if _, ok := r.Spaces[space]; !ok { + return []PageSummary{}, nil + } + filter += fmt.Sprintf(" && space = '%s'", filterValue(space)) + } + out := []PageSummary{} + for page := 1; len(out) < limit; page++ { + res, err := pocketbase.List[pageRecord](ctx, s.pb, "pages", pocketbase.ListOptions{ + Page: page, PerPage: 200, Filter: filter, Sort: "-updated", Fields: "id,space,title,updated", + }) + if err != nil { + return nil, err + } + for _, p := range res.Items { + if r.Can(p.Space, p.ID) && len(out) < limit { + out = append(out, PageSummary{ID: p.ID, Space: p.Space, Title: p.Title, Updated: p.Updated}) + } + } + if page >= res.TotalPages || len(res.Items) == 0 { + break + } + } + return out, nil +} + +// WriteMarkdown replaces a page's body with Markdown, or (appendTo) adds it +// at the end (editor). Open editors receive the change live. +func (s *Service) WriteMarkdown(ctx context.Context, c access.Caller, id, md string, appendTo bool) (PageText, error) { + p, err := s.editablePage(ctx, c, id) + if err != nil { + return PageText{}, err + } + add, err := convert.FromMarkdown(md) + if err != nil { + return PageText{}, apperr.Invalid("The Markdown could not be read.") + } + doc := add + if appendTo { + raw, err := s.docs.Content(ctx, p.ID) + if err != nil { + return PageText{}, err + } + if doc, err = convert.Parse(raw); err != nil { + return PageText{}, err + } + doc.Content = append(doc.Content, add.Content...) + } + raw, err := json.Marshal(doc) + if err != nil { + return PageText{}, err + } + if len(raw) > maxContentBytes { + return PageText{}, apperr.Invalid("The page is too large to save.") + } + if err := s.docs.Replace(ctx, p.ID, c.ID, raw, "before-replace"); err != nil { + return PageText{}, err + } + return s.ReadPage(ctx, c, p.ID) +} diff --git a/Server/internal/httpapi/ai.go b/Server/internal/httpapi/ai.go new file mode 100644 index 0000000..5f4511d --- /dev/null +++ b/Server/internal/httpapi/ai.go @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "docwell/server/internal/access" + "docwell/server/internal/ai" + "docwell/server/internal/apperr" + "docwell/server/internal/audit" + "docwell/server/internal/auth" +) + +// AIService is the AI layer (ADR-15). +type AIService interface { + Available(ctx context.Context, c access.Caller, wsID string) (ai.Availability, error) + GetSettings(ctx context.Context, c access.Caller, wsID string) (ai.Settings, error) + SaveSettings(ctx context.Context, c access.Caller, wsID string, in ai.Settings) (ai.Settings, error) + + ListProfiles(ctx context.Context, c access.Caller, wsID string) ([]ai.Profile, error) + CreateProfile(ctx context.Context, c access.Caller, wsID string, in ai.ProfileInput) (ai.Profile, error) + UpdateProfile(ctx context.Context, c access.Caller, id string, in ai.ProfileInput) (ai.Profile, error) + DeleteProfile(ctx context.Context, c access.Caller, id string) error + OrderProfiles(ctx context.Context, c access.Caller, wsID string, ids []string) ([]ai.Profile, error) + TestProfile(ctx context.Context, c access.Caller, id string) (ai.TestResult, error) + + IndexStatus(ctx context.Context, c access.Caller, wsID string) (ai.IndexStatus, error) + RebuildIndex(ctx context.Context, c access.Caller, wsID string) error + ListFiles(ctx context.Context, c access.Caller, wsID string) ([]ai.File, error) + AddFile(ctx context.Context, c access.Caller, wsID, name string, data []byte) (ai.File, error) + DeleteFile(ctx context.Context, c access.Caller, id string) error + + ListSessions(ctx context.Context, c access.Caller, wsID string) ([]ai.SessionSummary, error) + CreateSession(ctx context.Context, c access.Caller, wsID string, in ai.SessionInput) (ai.Session, error) + GetSession(ctx context.Context, c access.Caller, id string) (ai.Session, error) + UpdateSession(ctx context.Context, c access.Caller, id string, in ai.SessionInput) (ai.Session, error) + DeleteSession(ctx context.Context, c access.Caller, id string) error + ForkSession(ctx context.Context, c access.Caller, id, upTo string) (ai.Session, error) + Ask(ctx context.Context, c access.Caller, id, question string, emit func(ai.Event)) error + Write(ctx context.Context, c access.Caller, wsID string, in ai.WriteInput, onDelta func(string)) error + + MCP(ctx context.Context, c access.Caller, canWrite bool, body []byte, onWrite func(tool, page string)) ([]byte, error) +} + +var errNoAI = apperr.NotFound("AI is not available on this server") + +// withAI answers 404 when the server runs without the AI layer. +func (a *api) withAI(next http.HandlerFunc) http.HandlerFunc { + return a.requireUser(func(w http.ResponseWriter, r *http.Request) { + if a.ai == nil { + a.writeError(w, errNoAI) + return + } + next(w, r) + }) +} + +// sse streams server-sent events. Errors before the first event are sent +// as plain JSON errors, so clients can show them like any other. +type sse struct { + w http.ResponseWriter + rc *http.ResponseController + started bool +} + +func newSSE(w http.ResponseWriter) *sse { return &sse{w: w, rc: http.NewResponseController(w)} } + +func (s *sse) send(event string, data any) { + if !s.started { + h := s.w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-cache") + h.Set("X-Accel-Buffering", "no") // nginx: do not buffer the stream + s.w.WriteHeader(http.StatusOK) + s.started = true + } + raw, _ := json.Marshal(data) + fmt.Fprintf(s.w, "event: %s\ndata: %s\n\n", event, raw) + _ = s.rc.Flush() +} + +func (a *api) aiRoutes(mux *routeMux) { + ws := func(path string) string { return "/api/v1/workspaces/{id}/ai" + path } + + mux.HandleFunc("GET "+ws(""), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.Available(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("GET "+ws("/settings"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.GetSettings(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("PUT "+ws("/settings"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.Settings + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.SaveSettings(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, v, err) + })) + + // Profiles: a workspace's, and the instance's (superadmins). + mux.HandleFunc("GET "+ws("/profiles"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.ListProfiles(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("POST "+ws("/profiles"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.ProfileInput + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.CreateProfile(r.Context(), caller(r), r.PathValue("id"), in) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("PUT "+ws("/profiles/order"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in struct { + IDs []string `json:"ids"` + } + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.OrderProfiles(r.Context(), caller(r), r.PathValue("id"), in.IDs) + a.respond(w, v, err) + })) + mux.HandleFunc("GET /api/v1/admin/ai/profiles", a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.ListProfiles(r.Context(), caller(r), "") + a.respond(w, v, err) + })) + mux.HandleFunc("POST /api/v1/admin/ai/profiles", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.ProfileInput + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.CreateProfile(r.Context(), caller(r), "", in) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("PUT /api/v1/admin/ai/profiles/order", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in struct { + IDs []string `json:"ids"` + } + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.OrderProfiles(r.Context(), caller(r), "", in.IDs) + a.respond(w, v, err) + })) + mux.HandleFunc("PATCH /api/v1/ai/profiles/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.ProfileInput + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.UpdateProfile(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, v, err) + })) + mux.HandleFunc("DELETE /api/v1/ai/profiles/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.ai.DeleteProfile(r.Context(), caller(r), r.PathValue("id"))) + })) + mux.HandleFunc("POST /api/v1/ai/profiles/{id}/test", a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.TestProfile(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + + // Embeddings index and extra files. + mux.HandleFunc("GET "+ws("/index"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.IndexStatus(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("POST "+ws("/index/rebuild"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.ai.RebuildIndex(r.Context(), caller(r), r.PathValue("id"))) + })) + mux.HandleFunc("GET "+ws("/files"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.ListFiles(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("POST "+ws("/files"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, ai.MaxFileBytes+1<<20) + if err := r.ParseMultipartForm(ai.MaxFileBytes); err != nil { + a.writeError(w, apperr.Invalid("Files can be up to 10 MB.")) + return + } + f, h, err := r.FormFile("file") + if err != nil { + a.writeError(w, apperr.InvalidFields(map[string]string{"file": "Choose a file."})) + return + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, ai.MaxFileBytes+1)) + if err != nil { + a.writeError(w, err) + return + } + v, err := a.ai.AddFile(r.Context(), caller(r), r.PathValue("id"), h.Filename, data) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("DELETE /api/v1/ai/files/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.ai.DeleteFile(r.Context(), caller(r), r.PathValue("id"))) + })) + + // Chat sessions. + mux.HandleFunc("GET "+ws("/sessions"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.ListSessions(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("POST "+ws("/sessions"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.SessionInput + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.CreateSession(r.Context(), caller(r), r.PathValue("id"), in) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("GET /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + v, err := a.ai.GetSession(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, v, err) + })) + mux.HandleFunc("PATCH /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.SessionInput + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.UpdateSession(r.Context(), caller(r), r.PathValue("id"), in) + a.respond(w, v, err) + })) + mux.HandleFunc("DELETE /api/v1/ai/sessions/{id}", a.withAI(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.ai.DeleteSession(r.Context(), caller(r), r.PathValue("id"))) + })) + mux.HandleFunc("POST /api/v1/ai/sessions/{id}/fork", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in struct { + Message string `json:"message"` + } + if !a.decode(w, r, &in) { + return + } + v, err := a.ai.ForkSession(r.Context(), caller(r), r.PathValue("id"), in.Message) + a.respondStatus(w, http.StatusCreated, v, err) + })) + mux.HandleFunc("POST /api/v1/ai/sessions/{id}/messages", a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in struct { + Content string `json:"content"` + } + if !a.decode(w, r, &in) { + return + } + out := newSSE(w) + err := a.ai.Ask(r.Context(), caller(r), r.PathValue("id"), in.Content, func(e ai.Event) { out.send(e.Name, e.Data) }) + a.streamError(w, out, err) + })) + + // Writing actions. + mux.HandleFunc("POST "+ws("/write"), a.withAI(func(w http.ResponseWriter, r *http.Request) { + var in ai.WriteInput + if !a.decodeMax(w, r, &in, 4<<20) { + return + } + out := newSSE(w) + err := a.ai.Write(r.Context(), caller(r), r.PathValue("id"), in, func(d string) { out.send("delta", map[string]string{"text": d}) }) + if err == nil { + out.send("done", map[string]any{}) + } + a.streamError(w, out, err) + })) +} + +// streamError reports err as JSON before a stream started, else as an +// "error" event. +func (a *api) streamError(w http.ResponseWriter, out *sse, err error) { + if err == nil { + return + } + if !out.started { + a.writeError(w, err) + return + } + msg := "Something went wrong." + if e, ok := apperr.As(err); ok { + msg = e.Message + } else if r := err.Error(); r != "" && !strings.Contains(r, "context canceled") { + a.log.Warn("ai stream failed", "err", err) + } + out.send("error", map[string]string{"message": msg}) +} + +// mcpRoute serves the MCP endpoint. Its clients send API tokens (or +// session tokens); a write token also gets the write tools. +func (a *api) mcpRoute(mux *routeMux) { + mux.HandleFunc("POST /mcp", func(w http.ResponseWriter, r *http.Request) { + if a.ai == nil { + a.writeError(w, errNoAI) + return + } + token := auth.BearerToken(r) + var u auth.User + var err error + canWrite := true + if strings.HasPrefix(token, auth.TokenPrefix) { + var scope string + u, scope, err = a.auth.VerifyAPIToken(r.Context(), token) + canWrite = scope == auth.ScopeWrite + } else { + u, err = a.auth.Verify(r.Context(), token) + } + if err != nil { + w.Header().Set("WWW-Authenticate", `Bearer realm="docwell", error="invalid_token"`) + a.writeError(w, err) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4<<20)) + if err != nil { + writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too_large"}) + return + } + onWrite := func(tool, page string) { + if a.audit != nil { + a.audit.Record(audit.Entry{ + Action: "mcp." + tool, ActorID: u.ID, ActorEmail: u.Email, Org: u.Organization, + TargetType: "page", TargetID: page, Status: http.StatusOK, + IP: audit.ClientIP(r), UserAgent: r.UserAgent(), + }) + } + } + out, err := a.ai.MCP(r.Context(), u.Caller(), canWrite, body, onWrite) + if err != nil { + a.writeError(w, err) + return + } + if out == nil { + w.WriteHeader(http.StatusAccepted) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(out) + }) +} diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index 233c0ff..389c755 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -68,6 +68,7 @@ type api struct { collab CollabHub previews LinkPreviewer push PushService + ai AIService log *slog.Logger } @@ -222,6 +223,7 @@ func (a *api) routes(mux *routeMux) { a.webhookRoutes(mux) a.commentRoutes(mux) a.adminRoutes(mux) + a.aiRoutes(mux) } func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool { diff --git a/Server/internal/httpapi/router.go b/Server/internal/httpapi/router.go index 283ef9b..b7556e5 100644 --- a/Server/internal/httpapi/router.go +++ b/Server/internal/httpapi/router.go @@ -40,6 +40,8 @@ type Deps struct { Previews LinkPreviewer // Audit records changes and serves the audit log; nil turns both off. Audit AuditService + // AI serves chat, writing actions, profiles and MCP; nil turns them off. + AI AIService Admin http.Handler Log *slog.Logger } @@ -76,9 +78,13 @@ func newMux(d Deps) *routeMux { if d.Push != nil { a.push = d.Push } + if d.AI != nil { + a.ai = d.AI + } a.routes(mux) a.fileRoutes(mux, max(d.MaxUpload, 1<<20)) a.collabRoute(mux, d.CORSOrigins) + a.mcpRoute(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) diff --git a/Server/internal/httpapi/security.go b/Server/internal/httpapi/security.go index 10a8af7..d158f57 100644 --- a/Server/internal/httpapi/security.go +++ b/Server/internal/httpapi/security.go @@ -39,6 +39,13 @@ var unaudited = map[string]bool{ "POST /api/v1/files/token": true, "PUT /api/v1/pages/{id}/favorite": true, "POST /api/v1/comments/{id}/reactions": true, + // Questions and writing help change no page; their sessions are private. + "POST /api/v1/ai/sessions/{id}/messages": true, + "POST /api/v1/workspaces/{id}/ai/write": true, + "POST /api/v1/workspaces/{id}/ai/sessions": true, + "POST /api/v1/ai/sessions/{id}/fork": true, + "PATCH /api/v1/ai/sessions/{id}": true, + "DELETE /api/v1/ai/sessions/{id}": true, } // routeEntry describes a successful change request: the route (without the diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json index 983f526..3c56eba 100644 --- a/Server/internal/pbschema/schema.json +++ b/Server/internal/pbschema/schema.json @@ -491,6 +491,17 @@ "values": [ "edgeless" ] + }, + { + "help": "", + "hidden": false, + "id": "json4204996261", + "maxSize": 200000, + "name": "ai_settings", + "presentable": false, + "required": false, + "system": false, + "type": "json" } ], "id": "pbc_2170078043", @@ -4509,5 +4520,523 @@ "type": "base", "updateRule": null, "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": false, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1579384326", + "max": 80, + "min": 0, + "name": "name", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "select1002749145", + "maxSelect": 1, + "name": "kind", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": [ + "openai", + "anthropic", + "ollama" + ] + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text2651864036", + "max": 500, + "min": 0, + "name": "base_url", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text3373460893", + "max": 2000, + "min": 0, + "name": "api_key", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text3605569346", + "max": 200, + "min": 0, + "name": "chat_model", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text387273915", + "max": 200, + "min": 0, + "name": "embed_model", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text3895342900", + "max": 20, + "min": 0, + "name": "effort", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "bool1358543748", + "name": "enabled", + "presentable": false, + "required": false, + "system": false, + "type": "bool" + }, + { + "help": "", + "hidden": false, + "id": "number1177347317", + "max": null, + "min": null, + "name": "position", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "help": "", + "hidden": false, + "id": "number2072368721", + "max": null, + "min": null, + "name": "requests", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "help": "", + "hidden": false, + "id": "number1726912723", + "max": null, + "min": null, + "name": "input_tokens", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "help": "", + "hidden": false, + "id": "number2122787687", + "max": null, + "min": null, + "name": "output_tokens", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "help": "", + "hidden": false, + "id": "date4016875332", + "max": "", + "min": "", + "name": "last_used", + "presentable": false, + "required": false, + "system": false, + "type": "date" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1066830442", + "max": 500, + "min": 0, + "name": "last_error", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate3332085495", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_1680285732", + "indexes": [ + "CREATE INDEX idx_ai_profiles_ws ON ai_profiles (workspace, position)" + ], + "listRule": null, + "name": "ai_profiles", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "cascadeDelete": true, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation2375276105", + "maxSelect": 1, + "minSelect": 0, + "name": "user", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text724990059", + "max": 200, + "min": 0, + "name": "title", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "select11490771", + "maxSelect": 1, + "name": "scope", + "presentable": false, + "required": false, + "system": false, + "type": "select", + "values": [ + "workspace", + "space", + "page" + ] + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1747671345", + "max": 15, + "min": 0, + "name": "scope_id", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "json3674349206", + "maxSize": 5000000, + "name": "messages", + "presentable": false, + "required": false, + "system": false, + "type": "json" + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate3332085495", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_1970747399", + "indexes": [ + "CREATE INDEX idx_ai_sessions_user ON ai_sessions (user, workspace, updated)" + ], + "listRule": null, + "name": "ai_sessions", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null + }, + { + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "help": "", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_2170078043", + "help": "", + "hidden": false, + "id": "relation2375286809", + "maxSelect": 1, + "minSelect": 0, + "name": "workspace", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text1579384326", + "max": 200, + "min": 0, + "name": "name", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "help": "", + "hidden": false, + "id": "text4142483970", + "max": 2000000, + "min": 0, + "name": "content_text", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "help": "", + "hidden": false, + "id": "number4156564586", + "max": null, + "min": null, + "name": "size", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "cascadeDelete": false, + "collectionId": "_pb_users_auth_", + "help": "", + "hidden": false, + "id": "relation3725765462", + "maxSelect": 1, + "minSelect": 0, + "name": "created_by", + "presentable": false, + "required": false, + "system": false, + "type": "relation" + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate3332085495", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_449585925", + "indexes": [ + "CREATE INDEX idx_ai_files_ws ON ai_files (workspace)" + ], + "listRule": null, + "name": "ai_files", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": null } ] diff --git a/Web-App/frontend/package.json b/Web-App/frontend/package.json index b16a9cd..0189602 100644 --- a/Web-App/frontend/package.json +++ b/Web-App/frontend/package.json @@ -19,6 +19,8 @@ "@docwell/api-client": "*", "@docwell/editor": "*", "@docwell/ui": "*", + "dompurify": "^3.4.17", + "marked": "^16.4.2", "pinia": "^4.1.0", "vue": "^3.5.44", "vue-i18n": "^11.4.16", diff --git a/Web-App/frontend/src/components/AppLayout.vue b/Web-App/frontend/src/components/AppLayout.vue index 0692a2a..e0d3c96 100644 --- a/Web-App/frontend/src/components/AppLayout.vue +++ b/Web-App/frontend/src/components/AppLayout.vue @@ -16,6 +16,8 @@ import { useNotificationsStore } from "../stores/notifications"; import { useOrganizeStore } from "../stores/organize"; import { useSpacesStore } from "../stores/spaces"; import { atLeast, useWorkspacesStore } from "../stores/workspaces"; +import AiPanel from "./ai/AiPanel.vue"; +import { aiPanelOpen, useAiAvailability } from "../composables/useAi"; import PageTreeNode from "./PageTreeNode.vue"; import SearchPalette from "./SearchPalette.vue"; import ServerStatus from "./ServerStatus.vue"; @@ -46,6 +48,15 @@ function showError(e: unknown) { } onMounted(() => workspaces.load().catch(showError)); + +// The AI chat beside the views (ADR-15), offered where a workspace has AI or +// its admin can set it up. +const aiAvail = useAiAvailability(() => workspaces.current?.id); +const aiOffered = computed(() => !!aiAvail.value && (aiAvail.value.chat || aiAvail.value.canManage)); +const aiPageTitle = computed(() => { + const { space, page } = spaces.active; + return page ? (spaces.trees[space]?.find((n) => n.id === page)?.title ?? "") : ""; +}); onMounted(() => notifications.start()); onBeforeUnmount(() => notifications.stop()); watch( @@ -66,7 +77,10 @@ watch( // Ctrl+/ (Cmd+/ on macOS) folds the sidebar, as in other editors; Ctrl+K // searches. (Back and forward are in App.vue.) function onKey(e: KeyboardEvent) { - if ((e.ctrlKey || e.metaKey) && e.key === "/") { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "j" && !e.shiftKey && !e.altKey && aiOffered.value) { + e.preventDefault(); + aiPanelOpen.value = !aiPanelOpen.value; + } else if ((e.ctrlKey || e.metaKey) && e.key === "/") { e.preventDefault(); sidebar.toggle(); } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k" && !e.shiftKey && !e.altKey) { @@ -520,6 +534,18 @@ function signOut() { @click="sidebar.toggle()" />
+
@@ -556,6 +582,18 @@ function signOut() {
+
+ +
diff --git a/Web-App/frontend/src/components/ai/AiPanel.vue b/Web-App/frontend/src/components/ai/AiPanel.vue new file mode 100644 index 0000000..d732fcd --- /dev/null +++ b/Web-App/frontend/src/components/ai/AiPanel.vue @@ -0,0 +1,465 @@ + + + +