Add AI chat, writing actions, workspace embeddings and an MCP server

Phase E of the AFFiNE parity plan (ADR-15):

- internal/ai: OpenAI-compatible, Anthropic (official Go SDK) and Ollama
  drivers; BYOK profiles per workspace and for the instance, with keys
  encrypted by DOCWELL_SECRET_KEY, failover order, a test call and usage
  counters.
- Embeddings: an indexer that follows PocketBase like the search index,
  chunks pages along their blocks and keeps vectors in a bbolt file in
  the data dir (no cgo); progress, ignored pages and extra files.
- Chat sessions scoped to a page, space or workspace, streamed as
  server-sent events, with citations to pages and blocks, fork and
  history; retrieval only from pages the asker can read.
- Writing actions (rewrite, fix, shorter, longer, summarise, translate,
  continue, custom) in the editor's selection toolbar.
- POST /mcp: MCP over Streamable HTTP with personal API tokens; read
  tokens search and read pages, write tokens also create and update them.
- Web app chat panel (Ctrl+J), workspace AI settings, an admin AI page,
  OpenAPI, generated clients, migration and translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-15 21:58:22 +01:00
1 parent 05a6334f26
commit 78b7710090
64 files changed
+10692 -13

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// 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);
},
);
+18
View File
@@ -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://<server>/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*.
+3 -2
View File
@@ -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
+13
View File
@@ -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,
+15
View File
@@ -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
+24 -1
View File
@@ -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<Uint8Array>({
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" },
]);
});
});
+129
View File
@@ -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<Uint8Array>): AsyncGenerator<AiStreamEvent> {
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<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
@@ -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<AiStreamEvent> {
const headers: Record<string, string> = { 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<T>(path: string, form: FormData): Promise<T> {
const headers: Record<string, string> = { Accept: "application/json" };
@@ -237,6 +313,59 @@ export function createClient(opts: ClientOptions) {
revokeToken: (id: string) => request<void>("DELETE", `/api/v1/me/tokens/${encodeURIComponent(id)}`),
},
/** AI chat, writing actions and their setup (ADR-15). */
ai: {
available: (workspace: string) => request<AiAvailability>("GET", `/api/v1/workspaces/${enc(workspace)}/ai`),
settings: (workspace: string) => request<AiSettings>("GET", `/api/v1/workspaces/${enc(workspace)}/ai/settings`),
saveSettings: (workspace: string, input: AiSettings) =>
request<AiSettings>("PUT", `/api/v1/workspaces/${enc(workspace)}/ai/settings`, input),
/** A workspace's profiles; pass "" for the instance defaults (superadmins). */
profiles: (workspace: string) =>
request<AiProfile[]>(
"GET",
workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles` : "/api/v1/admin/ai/profiles",
),
createProfile: (workspace: string, input: AiProfileInput) =>
post<AiProfile>(
workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles` : "/api/v1/admin/ai/profiles",
input,
),
orderProfiles: (workspace: string, ids: string[]) =>
request<AiProfile[]>(
"PUT",
workspace ? `/api/v1/workspaces/${enc(workspace)}/ai/profiles/order` : "/api/v1/admin/ai/profiles/order",
{ ids },
),
updateProfile: (id: string, input: AiProfileInput) =>
request<AiProfile>("PATCH", `/api/v1/ai/profiles/${enc(id)}`, input),
deleteProfile: (id: string) => request<void>("DELETE", `/api/v1/ai/profiles/${enc(id)}`),
testProfile: (id: string) => post<AiTestResult>(`/api/v1/ai/profiles/${enc(id)}/test`),
index: (workspace: string) => request<AiIndexStatus>("GET", `/api/v1/workspaces/${enc(workspace)}/ai/index`),
rebuildIndex: (workspace: string) => post<void>(`/api/v1/workspaces/${enc(workspace)}/ai/index/rebuild`),
files: (workspace: string) => request<AiFile[]>("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<AiFile>(`/api/v1/workspaces/${enc(workspace)}/ai/files`, form);
},
deleteFile: (id: string) => request<void>("DELETE", `/api/v1/ai/files/${enc(id)}`),
sessions: (workspace: string) =>
request<AiSessionSummary[]>("GET", `/api/v1/workspaces/${enc(workspace)}/ai/sessions`),
createSession: (workspace: string, input: AiSessionInput) =>
post<AiSession>(`/api/v1/workspaces/${enc(workspace)}/ai/sessions`, input),
session: (id: string) => request<AiSession>("GET", `/api/v1/ai/sessions/${enc(id)}`),
updateSession: (id: string, input: AiSessionInput) =>
request<AiSession>("PATCH", `/api/v1/ai/sessions/${enc(id)}`, input),
deleteSession: (id: string) => request<void>("DELETE", `/api/v1/ai/sessions/${enc(id)}`),
forkSession: (id: string, message = "") => post<AiSession>(`/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<Webhook[]>("GET", `/api/v1/workspaces/${encodeURIComponent(workspace)}/webhooks`),
File diff suppressed because it is too large. Load diff
+211 -2
View File
@@ -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<Tool[]>(() => {
},
},
];
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<AiAction>("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 });
<DwIcon :name="alignIcons[a] ?? 'align-left'" :size="16" />
</button>
</div>
<div
v-if="editor.isEditable && ai && panel === 'ai'"
class="flex w-80 max-w-[90vw] flex-col gap-1 border-t border-line px-1 pt-1.5 pb-0.5 text-ui-sm"
data-testid="ai-panel"
>
<template v-if="!aiStarted">
<button
v-for="a in aiQuick"
:key="a"
type="button"
class="flex h-7 cursor-pointer items-center rounded-sm px-2 text-left text-ink hover:bg-surface-hover"
:data-testid="`ai-${a}`"
@mousedown.prevent
@click="runAi(a)"
>
{{ labels.ai[a] }}
</button>
<div class="flex items-center gap-1 px-1">
<span class="flex-1 px-1 text-ink">{{ labels.ai.translate }}</span>
<select v-model="aiLanguage" class="dw-input h-control-sm w-32" :aria-label="labels.ai.language">
<option v-for="(l, i) in ai.languages" :key="l" :value="i === 0 ? '' : l">{{ l }}</option>
</select>
<button
type="button"
class="h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
data-testid="ai-translate"
@mousedown.prevent
@click="runAi('translate')"
>
{{ labels.ai.run }}
</button>
</div>
<form class="flex items-center gap-1 px-1 pb-0.5" @submit.prevent="runAi('custom')">
<input
v-model="aiInstruction"
type="text"
maxlength="2000"
class="dw-input h-control-sm min-w-0 flex-1"
:placeholder="labels.ai.customPlaceholder"
:aria-label="labels.ai.custom"
data-testid="ai-instruction"
/>
<button
type="submit"
class="grid size-7 place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink disabled:opacity-50"
:aria-label="labels.ai.run"
:title="labels.ai.run"
:disabled="!aiInstruction.trim()"
>
<DwIcon name="send" :size="16" />
</button>
</form>
</template>
<template v-else>
<div
class="max-h-64 overflow-y-auto rounded-sm bg-surface px-2 py-1.5 whitespace-pre-wrap text-ink"
aria-live="polite"
data-testid="ai-result"
>
{{ aiText || (aiBusy ? labels.ai.working : "") }}
</div>
<p v-if="aiError" class="px-1 text-danger" role="alert">{{ aiError }}</p>
<div class="flex flex-wrap items-center gap-1">
<button
v-if="aiBusy"
type="button"
class="h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
@mousedown.prevent
@click="stopAi"
>
{{ labels.ai.stop }}
</button>
<template v-else>
<button
v-if="aiText.trim() && aiLast !== 'continue'"
type="button"
class="h-7 rounded-sm bg-primary px-2 font-semibold text-on-primary hover:opacity-90"
data-testid="ai-replace"
@mousedown.prevent
@click="applyAi('replace')"
>
{{ labels.ai.replace }}
</button>
<button
v-if="aiText.trim()"
type="button"
class="h-7 rounded-sm px-2 font-semibold hover:opacity-90"
:class="
aiLast === 'continue'
? 'bg-primary text-on-primary'
: 'text-ink-muted hover:bg-surface-hover hover:text-ink'
"
data-testid="ai-insert"
@mousedown.prevent
@click="applyAi('below')"
>
{{ labels.ai.insertBelow }}
</button>
<button
type="button"
class="h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
@mousedown.prevent
@click="runAi(aiLast)"
>
{{ labels.ai.retry }}
</button>
<button
type="button"
class="ml-auto h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
data-testid="ai-discard"
@mousedown.prevent
@click="resetAi"
>
{{ labels.ai.discard }}
</button>
</template>
</div>
</template>
</div>
</BubbleMenu>
<BubbleMenu
v-if="editor"
+37
View File
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/** The writing actions the selection toolbar offers. */
export const aiActions = [
"rewrite",
"fix",
"shorter",
"longer",
"summarize",
"continue",
"translate",
"custom",
] as const;
export type AiAction = (typeof aiActions)[number];
/** What the editor sends for a writing action. */
export interface AiWriteRequest {
action: AiAction;
/** The selected text. */
text: string;
/** Text in front of the selection, for "continue". */
before: string;
language?: string;
instruction?: string;
}
/**
* The host's AI. run streams the result (Markdown) to onText until it
* resolves; it rejects with an Error whose message is shown. toHTML turns
* the Markdown into HTML the editor can insert.
*/
export interface AiHost {
run(req: AiWriteRequest, onText: (text: string) => void, signal: AbortSignal): Promise<void>;
toHTML(markdown: string): string;
/** Languages offered for "translate" (names in the reader's language). */
languages: string[];
}
+1
View File
@@ -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 {
+43
View File
@@ -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",
+8
View File
@@ -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;
+751
View File
@@ -4159,3 +4159,754 @@ class PageUser {
Map<String, dynamic> toJson() => {'id': id, 'name': name};
}
class IdList {
const IdList({required this.ids});
factory IdList.fromJson(Map<String, dynamic> json) =>
IdList(ids: (json['ids'] as List).map((e) => e as String).toList());
final List<String> ids;
Map<String, dynamic> toJson() => {'ids': ids.map((e) => e).toList()};
}
class AiAvailability {
const AiAvailability({
required this.chat,
required this.embeddings,
required this.canManage,
});
factory AiAvailability.fromJson(Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String> ignored;
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic>),
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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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-`<block>`)
final String? block;
/// An extra file instead of a page
final String? file;
final String title;
final String snippet;
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic>))
.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<AiCitation>? citations;
/// Why the answer stopped
final String? error;
final String created;
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic>))
.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<AiMessage> messages;
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> toJson() => {
'title': ?title,
'scope': ?scope?.toJson(),
'scopeId': ?scopeId,
};
}
class AiForkInput {
const AiForkInput({this.message});
factory AiForkInput.fromJson(Map<String, dynamic> json) => AiForkInput(
message: json['message'] == null ? null : json['message'] as String,
);
/// The last message to copy; empty copies all
final String? message;
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> toJson() => {
'action': action.toJson(),
'text': text,
'before': ?before,
'language': ?language,
'instruction': ?instruction,
};
}
+4
View File
@@ -337,6 +337,10 @@ class _Generator {
'switch',
'in',
'is',
'continue',
'break',
'return',
'case',
};
static String _ident(String s) {
+1
View File
@@ -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") },
]
: []),
+41 -1
View File
@@ -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."
}
}
+41 -1
View File
@@ -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."
}
}
+41 -1
View File
@@ -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."
}
}
+41 -1
View File
@@ -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."
}
}
+41 -1
View File
@@ -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."
}
}
+1
View File
@@ -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") },
{
+244
View File
@@ -0,0 +1,244 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { AiProfile, AiProfileInput, AiProviderKind, AiTestResult } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { api, errorMessage } from "../session";
// The instance's default AI providers (ADR-15): workspaces use them after
// their own, unless a workspace turns that off.
const { t, locale } = useI18n();
const KINDS: AiProviderKind[] = ["openai", "anthropic", "ollama"];
const DEFAULT_CHAT: Record<AiProviderKind, string> = { openai: "", anthropic: "claude-opus-5-5", ollama: "" };
const profiles = ref<AiProfile[]>([]);
const error = ref("");
const busy = ref(false);
const editing = ref<string | null>(null);
const tested = ref<Record<string, AiTestResult>>({});
const keyTouched = ref(false);
const form = reactive({
name: "",
kind: "openai" as AiProviderKind,
baseUrl: "",
apiKey: "",
chatModel: "",
embedModel: "",
effort: "",
});
async function run(action: () => Promise<unknown>) {
busy.value = true;
error.value = "";
try {
await action();
} catch (e) {
error.value = errorMessage(e);
} finally {
busy.value = false;
}
}
const load = () =>
run(async () => {
profiles.value = await api.ai.profiles("");
});
onMounted(load);
function startNew() {
Object.assign(form, { name: "", kind: "openai", baseUrl: "", apiKey: "", chatModel: "", embedModel: "", effort: "" });
keyTouched.value = false;
editing.value = "new";
}
function startEdit(p: AiProfile) {
Object.assign(form, { ...p, apiKey: "" });
keyTouched.value = false;
editing.value = p.id;
}
function setKind(kind: AiProviderKind) {
if (form.chatModel === DEFAULT_CHAT[form.kind]) form.chatModel = DEFAULT_CHAT[kind];
if (kind === "anthropic") form.embedModel = "";
else form.effort = "";
form.kind = kind;
}
const save = () =>
run(async () => {
const input: AiProfileInput = {
name: form.name.trim(),
kind: form.kind,
baseUrl: form.baseUrl.trim(),
chatModel: form.chatModel.trim(),
embedModel: form.embedModel.trim(),
effort: form.effort as AiProfileInput["effort"],
};
if (editing.value === "new" || keyTouched.value) input.apiKey = form.apiKey.trim();
if (editing.value === "new") await api.ai.createProfile("", input);
else if (editing.value) await api.ai.updateProfile(editing.value, input);
editing.value = null;
profiles.value = await api.ai.profiles("");
});
const toggle = (p: AiProfile) =>
run(async () => {
await api.ai.updateProfile(p.id, { enabled: !p.enabled });
profiles.value = await api.ai.profiles("");
});
const remove = (p: AiProfile) =>
run(async () => {
if (!window.confirm(t("ai.deleteConfirm", { name: p.name }))) return;
await api.ai.deleteProfile(p.id);
profiles.value = await api.ai.profiles("");
});
const move = (p: AiProfile, by: -1 | 1) =>
run(async () => {
const ids = profiles.value.map((x) => x.id);
const i = ids.indexOf(p.id);
const j = i + by;
if (j < 0 || j >= ids.length) return;
[ids[i], ids[j]] = [ids[j]!, ids[i]!];
profiles.value = await api.ai.orderProfiles("", ids);
});
const test = (p: AiProfile) =>
run(async () => {
tested.value = { ...tested.value, [p.id]: await api.ai.testProfile(p.id) };
profiles.value = await api.ai.profiles("");
});
const fmt = computed(() => new Intl.NumberFormat(locale.value, { notation: "compact" }));
const total = computed(() =>
profiles.value.reduce(
(s, p) => ({ in: s.in + p.usage.inputTokens, out: s.out + p.usage.outputTokens, req: s.req + p.usage.requests }),
{ in: 0, out: 0, req: 0 },
),
);
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("ai.title") }}</h1>
<p class="mt-1 max-w-2xl text-ink-muted">{{ $t("ai.hint") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout size="ui" class="mt-4 max-w-2xl">{{ $t("ai.keyNote") }}</DwCallout>
<section class="mt-6 max-w-3xl dw-card">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<h2 class="text-ui-lg">{{ $t("ai.profiles") }}</h2>
<p class="text-ui-sm text-ink-muted">
{{
$t("ai.total", {
requests: fmt.format(total.req),
input: fmt.format(total.in),
output: fmt.format(total.out),
})
}}
</p>
</div>
<ol class="mt-3 divide-y divide-line">
<li v-for="(p, i) in profiles" :key="p.id" class="space-y-2 py-3" data-testid="admin-ai-profile">
<div class="flex flex-wrap items-center gap-2">
<span class="w-5 text-ui-sm font-semibold text-ink-muted">{{ i + 1 }}</span>
<div class="min-w-0 flex-1">
<p class="font-medium" :class="{ 'text-ink-muted line-through': !p.enabled }">{{ p.name }}</p>
<p class="text-ui-sm text-ink-muted">
{{ $t(`ai.kinds.${p.kind}`) }}
<template v-if="p.chatModel"> · {{ p.chatModel }}</template>
<template v-if="p.embedModel"> · {{ $t("ai.embeddings") }}: {{ p.embedModel }}</template>
· {{ p.keySet ? $t("ai.keySet") : $t("ai.noKey") }}
</p>
<p class="text-ui-xs text-ink-faint">
{{
$t("ai.usage", {
requests: fmt.format(p.usage.requests),
input: fmt.format(p.usage.inputTokens),
output: fmt.format(p.usage.outputTokens),
})
}}
</p>
</div>
<div class="flex flex-wrap items-center gap-2 text-ui-sm">
<button class="dw-link" :disabled="busy || i === 0" @click="move(p, -1)">↑</button>
<button class="dw-link" :disabled="busy || i === profiles.length - 1" @click="move(p, 1)">↓</button>
<button class="dw-link" :disabled="busy" @click="test(p)">{{ $t("ai.test") }}</button>
<button class="dw-link" :disabled="busy" @click="startEdit(p)">{{ $t("common.edit") }}</button>
<button class="dw-link" :disabled="busy" @click="toggle(p)">
{{ p.enabled ? $t("ai.disable") : $t("ai.enable") }}
</button>
<button class="text-danger hover:underline" :disabled="busy" @click="remove(p)">
{{ $t("common.delete") }}
</button>
</div>
</div>
<DwCallout v-if="tested[p.id]" :tone="tested[p.id]!.ok ? 'success' : 'danger'" size="ui">
{{ tested[p.id]!.ok ? $t("ai.testOk", { ms: tested[p.id]!.latencyMs }) : tested[p.id]!.error }}
</DwCallout>
<p v-else-if="p.lastError" class="text-ui-sm text-danger">{{ $t("ai.lastError", { error: p.lastError }) }}</p>
</li>
<li v-if="!profiles.length" class="py-3 text-ink-muted">{{ $t("ai.none") }}</li>
</ol>
<form v-if="editing" class="mt-4 grid gap-4 border-t border-line pt-4 sm:grid-cols-2" @submit.prevent="save">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.kind") }}</span>
<select
:value="form.kind"
class="dw-input"
@change="setKind(($event.target as HTMLSelectElement).value as AiProviderKind)"
>
<option v-for="k in KINDS" :key="k" :value="k">{{ $t(`ai.kinds.${k}`) }}</option>
</select>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.name") }}</span>
<input v-model="form.name" required maxlength="80" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">{{ $t("ai.baseUrl") }}</span>
<input v-model="form.baseUrl" class="dw-input" :placeholder="$t(`ai.baseUrlDefault.${form.kind}`)" />
</label>
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">{{ $t("ai.apiKey") }}</span>
<input
v-model="form.apiKey"
type="password"
autocomplete="new-password"
class="dw-input"
:placeholder="editing !== 'new' ? $t('common.unchanged') : ''"
@input="keyTouched = true"
/>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.chatModel") }}</span>
<input v-model="form.chatModel" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.embedModel") }}</span>
<input v-model="form.embedModel" class="dw-input" :disabled="form.kind === 'anthropic'" />
</label>
<label v-if="form.kind === 'anthropic'" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.effort") }}</span>
<select v-model="form.effort" class="dw-input">
<option value="">{{ $t("ai.effortDefault") }}</option>
<option v-for="e in ['low', 'medium', 'high', 'xhigh', 'max']" :key="e" :value="e">{{ e }}</option>
</select>
</label>
<div class="flex gap-2 sm:col-span-2">
<DwButton type="submit" variant="primary" :disabled="busy || !form.name.trim()">{{
$t("common.save")
}}</DwButton>
<DwButton variant="secondary" :disabled="busy" @click="editing = null">{{ $t("common.cancel") }}</DwButton>
</div>
</form>
<DwButton v-else class="mt-4" size="sm" icon="plus" @click="startNew">{{ $t("ai.add") }}</DwButton>
</section>
<section class="mt-6 max-w-3xl dw-card">
<h2 class="text-ui-lg">{{ $t("ai.mcpTitle") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("ai.mcpHint") }}</p>
</section>
</template>
+17
View File
@@ -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,
}),
+17
View File
@@ -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
+37
View File
@@ -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=
+249
View File
@@ -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")
}
}
+121
View File
@@ -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
}
+568
View File
@@ -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
}
+168
View File
@@ -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])) + "…"
}
+146
View File
@@ -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)
}
+472
View File
@@ -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()
}
+412
View File
@@ -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<!-- page %s, space %s, updated %s -->\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")
}
+571
View File
@@ -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() }
+391
View File
@@ -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
}
+157
View File
@@ -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
}
+363
View File
@@ -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/<id>" or "file/<id>".
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 ("<profile>:<model>").
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
}
+94
View File
@@ -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<text>\n" + strings.TrimSpace(before+"\n"+text) + "\n</text>")
} else {
prompt.WriteString("Text:\n<text>\n" + text + "\n</text>")
}
_, 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
}
+397
View File
@@ -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>)
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
+6 -2
View File
@@ -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",
}
+174
View File
@@ -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)
}
+339
View File
@@ -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)
})
}
+2
View File
@@ -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 {
+6
View File
@@ -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"})
+7
View File
@@ -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
+529
View File
@@ -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
}
]
+2
View File
@@ -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",
+39 -1
View File
@@ -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()"
/>
<div id="app-header" class="flex min-w-0 flex-1 items-center gap-2" />
<DwButton
v-if="aiOffered"
variant="ghost"
size="sm"
icon="sparkles"
:class="{ '!text-primary': aiPanelOpen }"
:aria-label="$t('ai.title')"
:aria-pressed="aiPanelOpen"
:title="`${$t('ai.title')} (Ctrl J)`"
data-testid="ai-toggle"
@click="aiPanelOpen = !aiPanelOpen"
/>
</header>
<div class="flex min-h-0 flex-1">
<div class="min-w-0 flex-1 overflow-y-auto">
@@ -556,6 +582,18 @@ function signOut() {
<PageView :id="split.page.value" :key="split.page.value" pane="split" @error="showError" />
</div>
</section>
<div
v-if="aiPanelOpen && aiOffered && workspaces.current"
class="fixed inset-0 z-40 flex flex-col bg-surface md:static md:z-auto md:w-[22rem] md:shrink-0 md:border-l md:border-line lg:w-[26rem]"
>
<AiPanel
:workspace="workspaces.current.id"
:space="spaces.active.space || undefined"
:page="spaces.active.page || undefined"
:page-title="aiPageTitle"
@close="aiPanelOpen = false"
/>
</div>
</div>
</main>
</div>
@@ -0,0 +1,465 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import {
ApiError,
type AiCitation,
type AiMessage,
type AiScope,
type AiSession,
type AiSessionSummary,
} from "@docwell/api-client";
import { blockHash, pagePath } from "@docwell/editor";
import { DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { useApi } from "../../api";
import { aiErrorText, useAiAvailability } from "../../composables/useAi";
import { renderMarkdown } from "../../lib/markdown";
// The AI chat beside the page: sessions about the workspace, a space or the
// open page, with answers citing the pages they come from (ADR-15).
const props = defineProps<{ workspace: string; space?: string; page?: string; pageTitle?: string }>();
const emit = defineEmits<{ close: [] }>();
const api = useApi();
const router = useRouter();
const { t } = useI18n();
const avail = useAiAvailability(() => props.workspace);
const sessions = ref<AiSessionSummary[]>([]);
const session = ref<AiSession | null>(null);
const question = ref("");
const error = ref("");
const busy = ref(false);
// The answer being streamed: its sources and text so far.
const pending = ref<{ question: string; text: string; citations: AiCitation[] } | null>(null);
let abort: AbortController | null = null;
const list = ref<HTMLElement | null>(null);
const input = ref<HTMLTextAreaElement | null>(null);
const scope = ref<AiScope>(props.page ? "page" : "workspace");
const scopeId = computed(
() => (scope.value === "page" ? props.page : scope.value === "space" ? props.space : "") ?? "",
);
const scopes = computed(() => {
const out: { id: AiScope; label: string }[] = [];
if (props.page) out.push({ id: "page", label: t("ai.scope.page") });
if (props.space) out.push({ id: "space", label: t("ai.scope.space") });
out.push({ id: "workspace", label: t("ai.scope.workspace") });
return out;
});
function fail(e: unknown) {
error.value = e instanceof ApiError ? aiErrorText(e) || t("ai.failed") : t("ai.failed");
}
async function loadSessions() {
sessions.value = await api.ai.sessions(props.workspace);
}
async function open(id: string) {
error.value = "";
session.value = await api.ai.session(id);
scope.value = session.value.scope;
await scrollDown();
}
function newChat() {
stop();
session.value = null;
error.value = "";
scope.value = props.page ? "page" : props.space && scope.value === "space" ? "space" : "workspace";
void nextTick(() => input.value?.focus());
}
watch(
() => [props.workspace, avail.value?.chat] as const,
async ([, chat]) => {
session.value = null;
sessions.value = [];
if (chat) await loadSessions().catch(fail);
},
{ immediate: true },
);
// A fresh chat follows the page being looked at.
watch(
() => props.page,
(p) => {
if (!session.value?.messages.length) scope.value = p ? "page" : scope.value === "page" ? "workspace" : scope.value;
},
);
async function changeScope(next: AiScope) {
scope.value = next;
const s = session.value;
if (!s) return;
if (s.messages.length) {
newChat();
scope.value = next;
return;
}
session.value = await api.ai.updateSession(s.id, { scope: next, scopeId: scopeId.value }).catch((e) => {
fail(e);
return s;
});
}
async function scrollDown() {
await nextTick();
list.value?.scrollTo({ top: list.value.scrollHeight });
}
async function send() {
const q = question.value.trim();
if (!q || busy.value) return;
error.value = "";
busy.value = true;
try {
if (!session.value) {
session.value = await api.ai.createSession(props.workspace, { scope: scope.value, scopeId: scopeId.value });
}
const s = session.value;
question.value = "";
pending.value = { question: q, text: "", citations: [] };
await scrollDown();
abort = new AbortController();
for await (const ev of api.ai.ask(s.id, q, abort.signal)) {
const data = ev.data as {
citations?: AiCitation[];
text?: string;
message?: AiMessage | string;
user?: AiMessage;
};
if (ev.event === "sources") pending.value.citations = data.citations ?? [];
else if (ev.event === "delta") {
pending.value.text += data.text ?? "";
void scrollDown();
} else if (ev.event === "done" || ev.event === "error") {
if (ev.event === "error") error.value = String(data.message ?? t("ai.failed"));
break;
}
}
} catch (e) {
if (!abort?.signal.aborted) fail(e);
} finally {
abort = null;
pending.value = null;
busy.value = false;
// The server stored the turn (also when stopped part way); show it as stored.
if (session.value) {
await open(session.value.id).catch(() => {});
await loadSessions().catch(() => {});
}
}
}
function stop() {
abort?.abort();
}
onBeforeUnmount(stop);
function onKey(e: KeyboardEvent) {
if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
e.preventDefault();
void send();
}
}
async function remove() {
const s = session.value;
if (!s || !window.confirm(t("ai.deleteConfirm"))) return;
await api.ai.deleteSession(s.id).catch(fail);
session.value = null;
await loadSessions().catch(fail);
}
async function fork(m: AiMessage) {
const s = session.value;
if (!s) return;
try {
session.value = await api.ai.forkSession(s.id, m.id);
await loadSessions();
} catch (e) {
fail(e);
}
}
const copied = ref("");
async function copy(m: AiMessage) {
try {
await navigator.clipboard.writeText(m.content);
copied.value = m.id;
setTimeout(() => (copied.value = ""), 1500);
} catch {
// clipboard blocked: nothing to do
}
}
const citationHref = (c: AiCitation) => (c.page ? pagePath(c.page) + (c.block ? blockHash(c.block) : "") : "");
// Clicks on [n] in an answer open that source.
function onAnswerClick(e: MouseEvent, citations: AiCitation[] | undefined) {
const a = (e.target as HTMLElement).closest("a");
if (!a) return;
const n = a.dataset.cite;
if (n) {
e.preventDefault();
const c = citations?.find((x) => String(x.n) === n);
if (c && citationHref(c)) void router.push(citationHref(c));
return;
}
// Other links: same-app paths stay in the app, the rest open in a tab.
const href = a.getAttribute("href") ?? "";
e.preventDefault();
if (href.startsWith("/")) void router.push(href);
else if (/^https?:/i.test(href)) window.open(href, "_blank", "noopener");
}
/** The sources an answer cites, in citation order (all of them when it cites none). */
function cited(m: { content?: string; text?: string; citations?: AiCitation[] }) {
const all = m.citations ?? [];
const text = m.content ?? m.text ?? "";
const used = new Set([...text.matchAll(/\[(\d{1,2})\]/g)].map((x) => Number(x[1])));
const out = all.filter((c) => used.has(c.n));
return out.length ? out : [];
}
const scopeLabel = computed(() => scopes.value.find((s) => s.id === scope.value)?.label ?? "");
</script>
<template>
<aside class="flex h-full w-full flex-col bg-surface" :aria-label="$t('ai.title')" data-testid="ai-panel">
<header class="flex h-10 shrink-0 items-center gap-1 border-b border-line px-2">
<DwIcon name="sparkles" :size="16" class="text-primary" />
<select
v-if="sessions.length"
:value="session?.id ?? ''"
class="dw-input h-control-sm min-w-0 flex-1"
:aria-label="$t('ai.history')"
data-testid="ai-sessions"
@change="
($event.target as HTMLSelectElement).value ? open(($event.target as HTMLSelectElement).value) : newChat()
"
>
<option value="">{{ $t("ai.newChat") }}</option>
<option v-for="s in sessions" :key="s.id" :value="s.id">{{ s.title || $t("ai.untitled") }}</option>
</select>
<span v-else class="flex-1 truncate font-semibold">{{ $t("ai.title") }}</span>
<DwButton
variant="ghost"
size="sm"
icon="plus"
:aria-label="$t('ai.newChat')"
:title="$t('ai.newChat')"
data-testid="ai-new"
@click="newChat"
/>
<DwButton
v-if="session"
variant="ghost"
size="sm"
icon="trash"
:aria-label="$t('ai.delete')"
:title="$t('ai.delete')"
@click="remove"
/>
<DwButton
variant="ghost"
size="sm"
icon="close"
:aria-label="$t('ai.close')"
:title="`${$t('ai.close')} (Ctrl J)`"
data-testid="ai-close"
@click="emit('close')"
/>
</header>
<div v-if="avail && !avail.chat" class="space-y-3 p-4 text-ui-md text-ink-muted" data-testid="ai-unavailable">
<p>{{ $t("ai.notSetUp") }}</p>
<RouterLink
v-if="avail.canManage"
:to="{ name: 'workspace-settings', params: { id: workspace }, hash: '#ai' }"
class="dw-link"
>
{{ $t("ai.setUp") }}
</RouterLink>
<p v-else>{{ $t("ai.askAdmin") }}</p>
</div>
<template v-else-if="avail">
<div ref="list" class="min-h-0 flex-1 space-y-4 overflow-y-auto px-3 py-3" data-testid="ai-messages">
<div v-if="!session?.messages.length && !pending" class="mt-6 space-y-2 text-center text-ui-md text-ink-muted">
<DwIcon name="sparkles" :size="28" class="mx-auto text-ink-faint" />
<p>{{ $t(`ai.intro.${scope}`, { title: pageTitle || $t("home.untitled") }) }}</p>
<p v-if="!avail.embeddings && scope !== 'page'" class="text-ui-sm text-ink-faint">
{{ $t("ai.searchOnly") }}
</p>
</div>
<template v-for="m in session?.messages ?? []" :key="m.id">
<div v-if="m.role === 'user'" class="ml-8 rounded-md bg-surface-sunken px-3 py-2 whitespace-pre-wrap">
{{ m.content }}
</div>
<div v-else class="group space-y-2" data-testid="ai-answer">
<!-- eslint-disable vue/no-v-html -- sanitised by renderMarkdown -->
<div
class="dw-ai-answer"
@click="onAnswerClick($event, m.citations)"
v-html="renderMarkdown(m.content, true)"
/>
<!-- eslint-enable vue/no-v-html -->
<p v-if="m.error" class="text-ui-sm text-danger">{{ m.error }}</p>
<ol v-if="cited(m).length" class="space-y-1 text-ui-sm" :aria-label="$t('ai.sources')">
<li v-for="c in cited(m)" :key="c.n" class="flex gap-2">
<span class="w-5 shrink-0 text-right font-semibold text-ink-muted">{{ c.n }}</span>
<RouterLink v-if="c.page" :to="citationHref(c)" class="min-w-0 dw-link truncate" :title="c.snippet">
{{ c.title || $t("home.untitled") }}
</RouterLink>
<span v-else class="min-w-0 truncate" :title="c.snippet">
<DwIcon name="paperclip" :size="12" class="inline" /> {{ c.title }}
</span>
</li>
</ol>
<div class="flex gap-1 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">
<button class="dw-link text-ui-xs" @click="copy(m)">
{{ copied === m.id ? $t("ai.copied") : $t("ai.copy") }}
</button>
<span class="text-ink-faint">·</span>
<button class="dw-link text-ui-xs" data-testid="ai-fork" @click="fork(m)">{{ $t("ai.fork") }}</button>
</div>
</div>
</template>
<template v-if="pending">
<div class="ml-8 rounded-md bg-surface-sunken px-3 py-2 whitespace-pre-wrap">{{ pending.question }}</div>
<div class="space-y-2" aria-live="polite">
<!-- eslint-disable-next-line vue/no-v-html -- sanitised by renderMarkdown -->
<div v-if="pending.text" class="dw-ai-answer" v-html="renderMarkdown(pending.text, true)" />
<p v-else class="text-ink-muted">
{{ pending.citations.length ? $t("ai.thinking") : $t("ai.searching") }}
</p>
</div>
</template>
</div>
<DwCallout v-if="error" tone="danger" size="ui" class="mx-3 mb-2" role="alert">{{ error }}</DwCallout>
<form class="shrink-0 space-y-2 border-t border-line p-2" @submit.prevent="send">
<div class="flex flex-wrap items-center gap-1 text-ui-xs" role="radiogroup" :aria-label="$t('ai.scope.label')">
<span class="text-ink-muted">{{ $t("ai.scope.label") }}</span>
<button
v-for="s in scopes"
:key="s.id"
type="button"
role="radio"
:aria-checked="scope === s.id"
class="rounded-full border px-2 py-0.5"
:class="
scope === s.id ? 'border-primary bg-primary/10 text-ink' : 'border-line text-ink-muted hover:text-ink'
"
:data-testid="`ai-scope-${s.id}`"
@click="changeScope(s.id)"
>
{{ s.label }}
</button>
</div>
<div class="flex items-end gap-1">
<textarea
ref="input"
v-model="question"
rows="2"
maxlength="8000"
class="dw-input max-h-40 min-h-control w-full resize-y py-1.5"
:placeholder="$t('ai.placeholder', { scope: scopeLabel.toLowerCase() })"
:aria-label="$t('ai.placeholder', { scope: scopeLabel.toLowerCase() })"
data-testid="ai-input"
@keydown="onKey"
/>
<DwButton v-if="busy" variant="secondary" :aria-label="$t('ai.stop')" :title="$t('ai.stop')" @click="stop">
{{ $t("ai.stop") }}
</DwButton>
<DwButton
v-else
type="submit"
variant="primary"
icon="send"
:disabled="!question.trim()"
:aria-label="$t('ai.send')"
:title="$t('ai.send')"
data-testid="ai-send"
/>
</div>
</form>
</template>
</aside>
</template>
<style scoped>
.dw-ai-answer {
line-height: 1.55;
overflow-wrap: anywhere;
}
.dw-ai-answer :deep(p),
.dw-ai-answer :deep(ul),
.dw-ai-answer :deep(ol),
.dw-ai-answer :deep(pre),
.dw-ai-answer :deep(blockquote) {
margin: 0 0 0.6em;
}
.dw-ai-answer :deep(ul) {
list-style: disc;
padding-left: 1.25em;
}
.dw-ai-answer :deep(ol) {
list-style: decimal;
padding-left: 1.25em;
}
.dw-ai-answer :deep(h1),
.dw-ai-answer :deep(h2),
.dw-ai-answer :deep(h3) {
margin: 0.8em 0 0.4em;
font-weight: 600;
}
.dw-ai-answer :deep(code) {
font-family: var(--font-mono, monospace);
font-size: 0.9em;
background: var(--color-surface-sunken);
border-radius: 3px;
padding: 0 0.25em;
}
.dw-ai-answer :deep(pre) {
overflow-x: auto;
background: var(--color-surface-sunken);
border-radius: 4px;
padding: 0.5em 0.75em;
}
.dw-ai-answer :deep(pre code) {
background: none;
padding: 0;
}
.dw-ai-answer :deep(a) {
color: var(--color-primary);
text-decoration: underline;
}
.dw-ai-answer :deep(a.dw-cite) {
display: inline-grid;
place-items: center;
min-width: 1.2em;
height: 1.2em;
margin: 0 0.1em;
border-radius: 999px;
background: var(--color-surface-sunken);
font-size: 0.72em;
font-weight: 600;
text-decoration: none;
vertical-align: super;
}
.dw-ai-answer :deep(table) {
border-collapse: collapse;
margin: 0 0 0.6em;
}
.dw-ai-answer :deep(th),
.dw-ai-answer :deep(td) {
border: 1px solid var(--color-line);
padding: 0.2em 0.5em;
}
</style>
@@ -0,0 +1,300 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { AiProfile, AiProfileInput, AiProviderKind, AiTestResult } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../../api";
import { useFormErrors } from "../../composables/useFormErrors";
// AI provider profiles (BYOK) of a workspace, in the order they are tried.
const props = defineProps<{ workspace: string }>();
const emit = defineEmits<{ changed: [] }>();
const api = useApi();
const { locale } = useI18n();
const errors = useFormErrors();
const KINDS: AiProviderKind[] = ["openai", "anthropic", "ollama"];
const DEFAULTS: Record<AiProviderKind, { base: string; chat: string; embed: string }> = {
openai: { base: "https://api.openai.com/v1", chat: "", embed: "" },
anthropic: { base: "https://api.anthropic.com", chat: "claude-opus-5-5", embed: "" },
ollama: { base: "http://localhost:11434", chat: "", embed: "nomic-embed-text" },
};
const profiles = ref<AiProfile[]>([]);
const busy = ref(false);
const editing = ref<string | null>(null); // a profile id, "new", or null
const tested = ref<Record<string, AiTestResult>>({});
const form = ref({
name: "",
kind: "openai" as AiProviderKind,
baseUrl: "",
apiKey: "",
chatModel: "",
embedModel: "",
effort: "",
});
const keyTouched = ref(false);
async function load() {
profiles.value = await api.ai.profiles(props.workspace);
}
onMounted(() => load().catch(errors.show));
async function run(action: () => Promise<unknown>) {
busy.value = true;
errors.reset();
try {
await action();
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
function startNew() {
const d = DEFAULTS.openai;
form.value = {
name: "",
kind: "openai",
baseUrl: "",
apiKey: "",
chatModel: d.chat,
embedModel: d.embed,
effort: "",
};
keyTouched.value = false;
editing.value = "new";
}
function setKind(kind: AiProviderKind) {
const old = DEFAULTS[form.value.kind];
const d = DEFAULTS[kind];
// Swap in the new kind's suggestions where the old ones were untouched.
if (form.value.chatModel === old.chat) form.value.chatModel = d.chat;
if (form.value.embedModel === old.embed) form.value.embedModel = d.embed;
if (kind !== "anthropic") form.value.effort = "";
form.value.kind = kind;
}
function startEdit(p: AiProfile) {
form.value = {
name: p.name,
kind: p.kind,
baseUrl: p.baseUrl,
apiKey: "",
chatModel: p.chatModel,
embedModel: p.embedModel,
effort: p.effort,
};
keyTouched.value = false;
editing.value = p.id;
}
const input = (): AiProfileInput => {
const f = form.value;
const out: AiProfileInput = {
name: f.name.trim(),
kind: f.kind,
baseUrl: f.baseUrl.trim(),
chatModel: f.chatModel.trim(),
embedModel: f.embedModel.trim(),
effort: f.effort as AiProfileInput["effort"],
};
if (editing.value === "new" || keyTouched.value) out.apiKey = f.apiKey.trim();
return out;
};
const save = () =>
run(async () => {
if (editing.value === "new") await api.ai.createProfile(props.workspace, input());
else if (editing.value) await api.ai.updateProfile(editing.value, input());
editing.value = null;
await load();
emit("changed");
});
const toggle = (p: AiProfile) =>
run(async () => {
await api.ai.updateProfile(p.id, { enabled: !p.enabled });
await load();
emit("changed");
});
const remove = (p: AiProfile) =>
run(async () => {
if (!window.confirm(`${p.name}?`)) return;
await api.ai.deleteProfile(p.id);
await load();
emit("changed");
});
const move = (p: AiProfile, by: -1 | 1) =>
run(async () => {
const ids = profiles.value.map((x) => x.id);
const i = ids.indexOf(p.id);
const j = i + by;
if (j < 0 || j >= ids.length) return;
[ids[i], ids[j]] = [ids[j]!, ids[i]!];
profiles.value = await api.ai.orderProfiles(props.workspace, ids);
emit("changed");
});
const test = (p: AiProfile) =>
run(async () => {
tested.value = { ...tested.value, [p.id]: await api.ai.testProfile(p.id) };
await load();
});
const fmt = computed(() => new Intl.NumberFormat(locale.value, { notation: "compact" }));
</script>
<template>
<div class="space-y-3" data-testid="ai-profiles">
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<ol class="divide-y divide-line rounded-md border border-line">
<li v-for="(p, i) in profiles" :key="p.id" class="space-y-2 p-3" data-testid="ai-profile">
<div class="flex flex-wrap items-center gap-2">
<span class="w-5 text-ui-sm font-semibold text-ink-muted">{{ i + 1 }}</span>
<div class="min-w-0 flex-1">
<p class="truncate font-medium" :class="{ 'text-ink-muted line-through': !p.enabled }">{{ p.name }}</p>
<p class="truncate text-ui-sm text-ink-muted">
{{ $t(`ai.kinds.${p.kind}`) }}
<template v-if="p.chatModel"> · {{ $t("ai.chat") }}: {{ p.chatModel }}</template>
<template v-if="p.embedModel"> · {{ $t("ai.embeddings") }}: {{ p.embedModel }}</template>
· {{ p.keySet ? $t("ai.keySet") : $t("ai.noKey") }}
</p>
<p class="text-ui-xs text-ink-faint">
{{
$t("ai.usage", {
requests: fmt.format(p.usage.requests),
input: fmt.format(p.usage.inputTokens),
output: fmt.format(p.usage.outputTokens),
})
}}
</p>
</div>
<div class="flex items-center gap-1">
<DwButton
variant="ghost"
size="sm"
icon="arrow-up"
:aria-label="$t('ai.moveUp')"
:disabled="busy || i === 0"
@click="move(p, -1)"
/>
<DwButton
variant="ghost"
size="sm"
icon="arrow-down"
:aria-label="$t('ai.moveDown')"
:disabled="busy || i === profiles.length - 1"
@click="move(p, 1)"
/>
<button class="dw-link text-ui-sm" :disabled="busy" data-testid="ai-test" @click="test(p)">
{{ $t("ai.test") }}
</button>
<button class="dw-link text-ui-sm" :disabled="busy" @click="startEdit(p)">{{ $t("ai.edit") }}</button>
<button class="dw-link text-ui-sm" :disabled="busy" @click="toggle(p)">
{{ p.enabled ? $t("ai.disable") : $t("ai.enable") }}
</button>
<button class="text-ui-sm text-danger hover:underline" :disabled="busy" @click="remove(p)">
{{ $t("workspace.remove") }}
</button>
</div>
</div>
<DwCallout
v-if="tested[p.id]"
:tone="tested[p.id]!.ok ? 'success' : 'danger'"
size="ui"
data-testid="ai-test-result"
>
<template v-if="tested[p.id]!.ok">
{{ $t("ai.testOk", { ms: tested[p.id]!.latencyMs }) }}
<template v-if="tested[p.id]!.chat"> “{{ tested[p.id]!.chat }}”</template>
<template v-if="tested[p.id]!.dimensions">
· {{ $t("ai.dimensions", { n: tested[p.id]!.dimensions }) }}</template
>
</template>
<template v-else>{{ tested[p.id]!.error }}</template>
</DwCallout>
<p v-else-if="p.lastError" class="text-ui-sm text-danger">{{ $t("ai.lastError", { error: p.lastError }) }}</p>
</li>
<li v-if="!profiles.length" class="p-3 text-ui-md text-ink-muted">{{ $t("ai.noProfiles") }}</li>
</ol>
<form
v-if="editing"
class="space-y-3 rounded-md border border-line p-3"
data-testid="ai-profile-form"
@submit.prevent="save"
>
<div class="grid gap-3 sm:grid-cols-2">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.kind") }}</span>
<select
:value="form.kind"
class="dw-input"
data-testid="ai-kind"
@change="setKind(($event.target as HTMLSelectElement).value as AiProviderKind)"
>
<option v-for="k in KINDS" :key="k" :value="k">{{ $t(`ai.kinds.${k}`) }}</option>
</select>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.name") }}</span>
<input v-model="form.name" required maxlength="80" class="dw-input" data-testid="ai-name" />
<span v-if="errors.fields.value.name" class="text-ui-sm text-danger">{{ errors.fields.value.name }}</span>
</label>
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">{{ $t("ai.baseUrl") }}</span>
<input v-model="form.baseUrl" class="dw-input" :placeholder="DEFAULTS[form.kind].base" />
<span class="text-ui-xs text-ink-muted">{{ $t(`ai.baseUrlHint.${form.kind}`) }}</span>
<span v-if="errors.fields.value.baseUrl" class="text-ui-sm text-danger">{{
errors.fields.value.baseUrl
}}</span>
</label>
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">{{ $t("ai.apiKey") }}</span>
<input
v-model="form.apiKey"
type="password"
autocomplete="off"
class="dw-input"
:placeholder="editing !== 'new' ? $t('ai.keepKey') : form.kind === 'ollama' ? $t('ai.optional') : ''"
data-testid="ai-key"
@input="keyTouched = true"
/>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.chatModel") }}</span>
<input v-model="form.chatModel" class="dw-input" data-testid="ai-chat-model" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.embedModel") }}</span>
<input
v-model="form.embedModel"
class="dw-input"
:disabled="form.kind === 'anthropic'"
:placeholder="form.kind === 'anthropic' ? $t('ai.noEmbeddings') : $t('ai.optional')"
/>
</label>
<label v-if="form.kind === 'anthropic'" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("ai.effort") }}</span>
<select v-model="form.effort" class="dw-input">
<option value="">{{ $t("ai.effortDefault") }}</option>
<option v-for="e in ['low', 'medium', 'high', 'xhigh', 'max']" :key="e" :value="e">{{ e }}</option>
</select>
</label>
</div>
<div class="flex gap-2">
<DwButton type="submit" variant="primary" :disabled="busy || !form.name.trim()" data-testid="ai-save">{{
$t("common.save")
}}</DwButton>
<DwButton variant="secondary" :disabled="busy" @click="editing = null">{{ $t("ai.cancel") }}</DwButton>
</div>
</form>
<DwButton v-else size="sm" icon="plus" data-testid="ai-add" @click="startNew">{{ $t("ai.addProfile") }}</DwButton>
</div>
</template>
@@ -0,0 +1,303 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { AiFile, AiIndexStatus, AiSettings, SearchHit } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../../api";
import { refreshAi } from "../../composables/useAi";
import { useFormErrors } from "../../composables/useFormErrors";
import AiProfiles from "./AiProfiles.vue";
// A workspace's AI setup (workspace admins): switches, providers, the
// embeddings index, extra files and pages left out (ADR-15).
const props = defineProps<{ workspace: string }>();
const api = useApi();
const { locale, t } = useI18n();
const errors = useFormErrors();
const settings = ref<AiSettings | null>(null);
const index = ref<AiIndexStatus | null>(null);
const files = ref<AiFile[]>([]);
const ignoredTitles = ref<Record<string, string>>({});
const busy = ref(false);
const unavailable = ref(false);
const query = ref("");
const hits = ref<SearchHit[]>([]);
async function loadIndex() {
index.value = await api.ai.index(props.workspace);
}
async function load() {
try {
settings.value = await api.ai.settings(props.workspace);
} catch (e) {
unavailable.value = true;
errors.show(e);
return;
}
await Promise.all([loadIndex(), api.ai.files(props.workspace).then((f) => (files.value = f))]);
for (const id of settings.value.ignored) void title(id);
}
onMounted(() => load().catch(errors.show));
// While the index is filling, check on it every few seconds.
let timer: ReturnType<typeof setInterval> | undefined;
watch(
() => !!index.value?.enabled && (index.value.running || index.value.indexed < index.value.pages),
(filling) => {
clearInterval(timer);
if (filling) timer = setInterval(() => void loadIndex().catch(() => {}), 4000);
},
);
onBeforeUnmount(() => clearInterval(timer));
async function title(id: string) {
if (ignoredTitles.value[id] !== undefined) return;
ignoredTitles.value[id] = "";
try {
ignoredTitles.value[id] = (await api.pages.get(id)).title;
} catch {
ignoredTitles.value[id] = id;
}
}
async function run(action: () => Promise<unknown>) {
busy.value = true;
errors.reset();
try {
await action();
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
const save = (patch: Partial<AiSettings>) =>
run(async () => {
if (!settings.value) return;
settings.value = await api.ai.saveSettings(props.workspace, { ...settings.value, ...patch });
refreshAi(props.workspace);
await loadIndex();
});
function changed() {
refreshAi(props.workspace);
void loadIndex().catch(errors.show);
}
const rebuild = () =>
run(async () => {
if (!window.confirm(t("ai.rebuildConfirm"))) return;
await api.ai.rebuildIndex(props.workspace);
await loadIndex();
});
const upload = (e: Event) =>
run(async () => {
const el = e.target as HTMLInputElement;
for (const f of Array.from(el.files ?? [])) await api.ai.addFile(props.workspace, f, f.name);
el.value = "";
files.value = await api.ai.files(props.workspace);
});
const removeFile = (f: AiFile) =>
run(async () => {
await api.ai.deleteFile(f.id);
files.value = await api.ai.files(props.workspace);
});
let searchTimer: ReturnType<typeof setTimeout> | undefined;
watch(query, (q) => {
clearTimeout(searchTimer);
if (!q.trim()) {
hits.value = [];
return;
}
searchTimer = setTimeout(async () => {
try {
hits.value = (await api.workspaces.search(props.workspace, q, 8)).items.filter((h) => !h.record);
} catch {
hits.value = [];
}
}, 250);
});
const ignore = (h: SearchHit) => {
if (!settings.value || settings.value.ignored.includes(h.id)) return;
ignoredTitles.value[h.id] = h.title;
query.value = "";
void save({ ignored: [...settings.value.ignored, h.id] });
};
const unignore = (id: string) => settings.value && save({ ignored: settings.value.ignored.filter((x) => x !== id) });
const progress = computed(() => {
const i = index.value;
return i && i.pages ? Math.min(100, Math.round((i.indexed / i.pages) * 100)) : 0;
});
const size = (n: number) =>
new Intl.NumberFormat(locale.value, { style: "unit", unit: "kilobyte", maximumFractionDigits: 0 }).format(n / 1024);
</script>
<template>
<section id="ai" class="dw-card space-y-4" data-testid="workspace-ai">
<div>
<h2 class="text-ui-lg">{{ $t("ai.settingsTitle") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("ai.settingsHint") }}</p>
</div>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<template v-if="settings && !unavailable">
<div class="space-y-2">
<label class="flex items-start gap-2 text-ui-md">
<input
type="checkbox"
:checked="settings.enabled"
:disabled="busy"
class="mt-1"
data-testid="ai-enabled"
@change="save({ enabled: !settings.enabled })"
/>
<span>
<span class="font-semibold">{{ $t("ai.enabled") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("ai.enabledHint") }}</span>
</span>
</label>
<label class="flex items-start gap-2 text-ui-md">
<input
type="checkbox"
:checked="settings.useInstanceProfiles"
:disabled="busy"
class="mt-1"
@change="save({ useInstanceProfiles: !settings.useInstanceProfiles })"
/>
<span>
<span class="font-semibold">{{ $t("ai.useInstance") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("ai.useInstanceHint") }}</span>
</span>
</label>
</div>
<div>
<h3 class="text-ui-md font-semibold">{{ $t("ai.profiles") }}</h3>
<p class="mb-2 text-ui-sm text-ink-muted">{{ $t("ai.profilesHint") }}</p>
<AiProfiles :workspace="workspace" @changed="changed" />
</div>
<div class="space-y-2">
<h3 class="text-ui-md font-semibold">{{ $t("ai.indexTitle") }}</h3>
<label class="flex items-start gap-2 text-ui-md">
<input
type="checkbox"
:checked="settings.index"
:disabled="busy"
class="mt-1"
data-testid="ai-index"
@change="save({ index: !settings.index })"
/>
<span>
<span class="font-semibold">{{ $t("ai.index") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("ai.indexHint") }}</span>
</span>
</label>
<template v-if="index && settings.index">
<p v-if="!index.profile" class="text-ui-sm text-warning">{{ $t("ai.noEmbedProfile") }}</p>
<template v-else>
<div
class="h-2 overflow-hidden rounded-full bg-surface-sunken"
role="progressbar"
:aria-valuenow="progress"
aria-valuemin="0"
aria-valuemax="100"
:aria-label="$t('ai.indexTitle')"
>
<div class="h-full bg-primary transition-[width]" :style="{ width: `${progress}%` }" />
</div>
<p class="text-ui-sm text-ink-muted" data-testid="ai-index-status">
{{
$t("ai.indexStatus", {
indexed: index.indexed,
pages: index.pages,
chunks: index.chunks,
model: index.model,
profile: index.profile,
})
}}
<template v-if="index.running"> · {{ $t("ai.indexing") }}</template>
</p>
<p v-if="index.lastError" class="text-ui-sm text-danger">
{{ $t("ai.lastError", { error: index.lastError }) }}
</p>
<DwButton size="sm" variant="secondary" :disabled="busy" @click="rebuild">{{ $t("ai.rebuild") }}</DwButton>
</template>
</template>
</div>
<div class="space-y-2">
<h3 class="text-ui-md font-semibold">{{ $t("ai.ignoredTitle") }}</h3>
<p class="text-ui-sm text-ink-muted">{{ $t("ai.ignoredHint") }}</p>
<ul v-if="settings.ignored.length" class="flex flex-wrap gap-1.5">
<li
v-for="id in settings.ignored"
:key="id"
class="flex items-center gap-1 rounded-full border border-line px-2 py-0.5 text-ui-sm"
>
{{ ignoredTitles[id] || "…" }}
<button class="text-ink-muted hover:text-danger" :aria-label="$t('workspace.remove')" @click="unignore(id)">
×
</button>
</li>
</ul>
<div class="relative max-w-md">
<input
v-model="query"
type="search"
class="dw-input w-full"
:placeholder="$t('ai.ignoreSearch')"
:aria-label="$t('ai.ignoreSearch')"
/>
<ul
v-if="hits.length"
class="absolute z-10 mt-1 w-full rounded-md border border-line bg-surface-raised p-1 shadow-menu"
>
<li v-for="h in hits" :key="h.id">
<button class="w-full truncate rounded-sm px-2 py-1 text-left hover:bg-surface-hover" @click="ignore(h)">
{{ h.icon }} {{ h.title || $t("home.untitled") }}
<span class="text-ui-xs text-ink-muted">· {{ h.spaceName }}</span>
</button>
</li>
</ul>
</div>
</div>
<div class="space-y-2">
<h3 class="text-ui-md font-semibold">{{ $t("ai.filesTitle") }}</h3>
<p class="text-ui-sm text-ink-muted">{{ $t("ai.filesHint") }}</p>
<ul v-if="files.length" class="divide-y divide-line">
<li v-for="f in files" :key="f.id" class="flex items-center gap-2 py-1.5 text-ui-md">
<span class="min-w-0 flex-1 truncate">{{ f.name }}</span>
<span class="text-ui-xs text-ink-muted"
>{{ size(f.size) }} · {{ f.indexed ? $t("ai.fileIndexed") : $t("ai.fileWaiting") }}</span
>
<button class="text-ui-sm text-danger hover:underline" :disabled="busy" @click="removeFile(f)">
{{ $t("workspace.remove") }}
</button>
</li>
</ul>
<label class="inline-flex cursor-pointer items-center gap-2 dw-link text-ui-md">
<input
type="file"
multiple
accept=".txt,.md,.markdown,.html,.htm,.docx,.csv,.json"
class="sr-only"
:disabled="busy"
@change="upload"
/>
{{ $t("ai.addFiles") }}
</label>
</div>
</template>
</section>
</template>
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { ApiError, type AiAvailability } from "@docwell/api-client";
import type { AiHost } from "@docwell/editor";
import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { markdownToEditorHTML } from "../lib/markdown";
// What AI offers per workspace, loaded once per workspace and session.
const availability = reactive<Record<string, AiAvailability | undefined>>({});
const loading = new Map<string, Promise<void>>();
function readOpen(): boolean {
try {
return localStorage.getItem("docwell.aiPanel") === "1";
} catch {
return false;
}
}
/** Whether the AI chat panel is open (remembered per browser). */
export const aiPanelOpen = ref(readOpen());
watch(aiPanelOpen, (open) => {
try {
localStorage.setItem("docwell.aiPanel", open ? "1" : "0");
} catch {
// private mode: keep it for this tab only
}
});
/** Forgets what was loaded for a workspace, e.g. after its AI settings changed. */
export function refreshAi(workspace: string) {
delete availability[workspace];
loading.delete(workspace);
}
/** What AI offers in a workspace; undefined until loaded, or when the server has no AI. */
export function useAiAvailability(workspace: () => string | undefined) {
const api = useApi();
watch(
workspace,
(id) => {
if (!id || availability[id] || loading.has(id)) return;
loading.set(
id,
api.ai
.available(id)
.then((a) => void (availability[id] = a))
.catch((e) => {
// A server without AI answers 404; treat it as "no AI".
if (e instanceof ApiError) availability[id] = { chat: false, embeddings: false, canManage: false };
}),
);
},
{ immediate: true },
);
return computed(() => {
const id = workspace();
return id ? availability[id] : undefined;
});
}
/** The server's words for a failed AI call. */
export function aiErrorText(e: ApiError): string {
return e.serverMessage || Object.values(e.fields)[0] || "";
}
const translateTo = ["en", "de", "fr", "es", "pl", "it", "pt", "nl", "uk", "cs", "sv", "ja", "zh", "ko"];
/** The editor's AI writing host for a workspace, when AI is set up there. */
export function useAiWriter(workspace: () => string | undefined) {
const api = useApi();
const { locale, t } = useI18n();
const avail = useAiAvailability(workspace);
return computed<AiHost | undefined>(() => {
const ws = workspace();
if (!ws || !avail.value?.chat) return undefined;
let names: Intl.DisplayNames | undefined;
try {
names = new Intl.DisplayNames([locale.value], { type: "language" });
} catch {
names = undefined;
}
// The reader's language first, then the rest.
const own = locale.value.split("-")[0] ?? "en";
const codes = [own, ...translateTo.filter((c) => c !== own)];
return {
languages: codes.map((c) => names?.of(c) ?? c),
toHTML: markdownToEditorHTML,
async run(req, onText, signal) {
try {
for await (const ev of api.ai.write(ws, req, signal)) {
const data = ev.data as { text?: string; message?: string };
if (ev.event === "delta" && data.text) onText(data.text);
else if (ev.event === "error") throw new Error(data.message || t("ai.failed"));
}
} catch (e) {
throw e instanceof ApiError ? new Error(aiErrorText(e) || t("ai.failed")) : e;
}
},
};
});
}
@@ -40,6 +40,7 @@ export function useEditorLabels() {
dates: group("dates", "dates"),
database: group("database", "database"),
edgeless: group("edgeless", "edgeless"),
ai: group("ai", "ai"),
}));
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { describe, expect, it } from "vitest";
import { markdownToEditorHTML, renderMarkdown } from "./markdown";
describe("renderMarkdown", () => {
it("links citations outside code and strips scripts", () => {
const html = renderMarkdown("Use the **form** [1][2].\n\n`a[3]`\n\n<script>alert(1)</script>", true);
expect(html).toContain('<a href="#cite-1" class="dw-cite" data-cite="1">1</a>');
expect(html).toContain('data-cite="2"');
expect(html).toContain("<code>a[3]</code>");
expect(html).not.toContain("<script");
});
it("leaves citations alone without the flag", () => {
expect(renderMarkdown("x [1]")).toContain("x [1]");
});
it("makes editor HTML from lists and headings", () => {
const html = markdownToEditorHTML("## Title\n\n- one\n- two\n");
expect(html).toContain("<h2>Title</h2>");
expect(html).toContain("<li>one</li>");
});
});
+26
View File
@@ -0,0 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import DOMPurify from "dompurify";
import { marked } from "marked";
/**
* Markdown from an AI answer as safe HTML. Citations like [1] become
* links (#cite-1) the chat panel turns into page links.
*/
export function renderMarkdown(md: string, citations = false): string {
let html = marked.parse(md, { async: false, gfm: true, breaks: false }) as string;
if (citations) {
// Outside code: [n] → a citation link.
html = html.replace(
/(<code[\s\S]*?<\/code>)|\[(\d{1,2})\]/g,
(all, code: string | undefined, n: string | undefined) =>
code ? code : `<a href="#cite-${n}" class="dw-cite" data-cite="${n}">${n}</a>`,
);
}
return DOMPurify.sanitize(html, { ADD_ATTR: ["data-cite", "target"] });
}
/** Markdown as HTML for inserting into the editor (no citation links). */
export function markdownToEditorHTML(md: string): string {
return DOMPurify.sanitize(marked.parse(md.trim(), { async: false, gfm: true }) as string);
}
+117
View File
@@ -931,6 +931,27 @@
"colorInk": "Standard",
"colorPaper": "Papier",
"colorNone": "Keine"
},
"ai": {
"button": "KI fragen",
"rewrite": "Text verbessern",
"summarize": "Zusammenfassen",
"translate": "Übersetzen",
"continue": "Weiterschreiben",
"shorter": "Kürzer machen",
"longer": "Länger machen",
"fix": "Rechtschreibung und Grammatik korrigieren",
"custom": "KI bitten, …",
"customPlaceholder": "Sag der KI, was sie mit der Auswahl tun soll",
"language": "Sprache",
"run": "Los",
"working": "Schreibt …",
"replace": "Auswahl ersetzen",
"insertBelow": "Darunter einfügen",
"discard": "Verwerfen",
"stop": "Stopp",
"retry": "Noch einmal",
"failed": "Die KI konnte das nicht fertigstellen."
}
},
"comments": {
@@ -1300,5 +1321,101 @@
"exportSvg": "Als SVG exportieren",
"defaultEdgeless": "Für alle als Tafel öffnen",
"defaultPage": "Für alle als Seite öffnen"
},
"ai": {
"title": "KI-Chat",
"history": "Frühere Chats",
"newChat": "Neuer Chat",
"untitled": "Chat ohne Titel",
"delete": "Diesen Chat löschen",
"deleteConfirm": "Diesen Chat löschen?",
"close": "KI-Chat schließen",
"notSetUp": "In diesem Arbeitsbereich ist noch keine KI eingerichtet.",
"setUp": "KI in den Einstellungen des Arbeitsbereichs einrichten",
"askAdmin": "Bitte eine Admin-Person des Arbeitsbereichs, einen KI-Anbieter hinzuzufügen.",
"intro": {
"page": "Fragen zu „{title}“: Zusammenfassungen, Antworten und Aufgaben aus dieser Seite.",
"space": "Fragen zu den Seiten dieses Bereichs. Antworten verlinken ihre Quellen.",
"workspace": "Fragen zu allem in diesem Arbeitsbereich. Antworten verlinken ihre Quellen."
},
"searchOnly": "Dieser Arbeitsbereich ist nicht für KI indiziert; Antworten stützen sich auf Suchtreffer.",
"sources": "Quellen",
"copy": "Kopieren",
"copied": "Kopiert",
"fork": "In neuem Chat fortsetzen",
"thinking": "Schreibt die Antwort …",
"searching": "Durchsucht die Seiten …",
"failed": "Die KI konnte nicht antworten.",
"stop": "Stopp",
"send": "Senden",
"placeholder": "Frage zum {scope} …",
"scope": {
"label": "Über",
"page": "Seite",
"space": "Bereich",
"workspace": "Arbeitsbereich"
},
"settingsTitle": "KI",
"settingsHint": "Chat, Schreibhilfe und Suche nach Bedeutung mit dem KI-Anbieter deiner Wahl. Es wird nichts an einen Anbieter gesendet, bevor hier oder von der Server-Administration einer hinzugefügt wurde.",
"enabled": "KI in diesem Arbeitsbereich einschalten",
"enabledHint": "Mitglieder bekommen den KI-Chat und die Schreibaktionen.",
"useInstance": "KI-Anbieter des Servers verwenden",
"useInstanceHint": "Nach den Anbietern unten auch die der Server-Administration versuchen.",
"profiles": "Anbieter",
"profilesHint": "Von oben nach unten versucht; fällt einer aus, antwortet der nächste. Schlüssel werden verschlüsselt gespeichert und nie wieder angezeigt.",
"indexTitle": "Suche nach Bedeutung",
"index": "Seiten für KI indizieren",
"indexHint": "Sendet den Text jeder Seite an den Embedding-Anbieter, damit der Chat Seiten nach Bedeutung findet. Ohne das nutzt der Chat die Stichwortsuche.",
"noEmbedProfile": "Kein Anbieter hat ein Embedding-Modell; trage bei einem eines ein, um Seiten zu indizieren.",
"indexStatus": "{indexed} von {pages} Seiten indiziert, {chunks} Abschnitte, mit {model} ({profile})",
"indexing": "wird gerade indiziert",
"rebuild": "Neu indizieren",
"rebuildConfirm": "Index verwerfen und alle Seiten neu einbetten?",
"lastError": "Letzter Fehler: {error}",
"ignoredTitle": "Ausgelassene Seiten",
"ignoredHint": "Diese Seiten und ihre Unterseiten werden weder indiziert noch in Antworten verwendet.",
"ignoreSearch": "Seite zum Auslassen suchen",
"filesTitle": "Zusätzliche Dokumente",
"filesHint": "Text-, Markdown-, HTML- oder Word-Dateien, die der Chat als Quellen nutzen kann (je bis 10 MB).",
"fileIndexed": "indiziert",
"fileWaiting": "wartet auf den Index",
"addFiles": "Dateien hinzufügen …",
"kinds": {
"openai": "OpenAI-kompatibel",
"anthropic": "Anthropic",
"ollama": "Ollama"
},
"chat": "Chat",
"embeddings": "Embeddings",
"keySet": "Schlüssel gespeichert",
"noKey": "kein Schlüssel",
"usage": "{requests} Anfragen, {input} Tokens hinein, {output} heraus",
"moveUp": "Nach oben",
"moveDown": "Nach unten",
"test": "Testen",
"edit": "Bearbeiten",
"disable": "Ausschalten",
"enable": "Einschalten",
"testOk": "Funktioniert ({ms} ms).",
"dimensions": "{n} Dimensionen",
"noProfiles": "Noch keine Anbieter.",
"kind": "Anbieter",
"name": "Name",
"baseUrl": "Adresse",
"baseUrlHint": {
"openai": "OpenAI oder eine kompatible API: Azure, OpenRouter, LiteLLM, vLLM, LocalAI …",
"anthropic": "Leer lassen für die API von Anthropic.",
"ollama": "Wo Ollama läuft, aus Sicht des Servers."
},
"apiKey": "API-Schlüssel",
"keepKey": "Leer lassen, um den gespeicherten Schlüssel zu behalten",
"optional": "Optional",
"chatModel": "Chat-Modell",
"embedModel": "Embedding-Modell",
"noEmbeddings": "Anthropic hat keine Embeddings",
"effort": "Aufwand",
"effortDefault": "Standard des Modells",
"addProfile": "Anbieter hinzufügen",
"cancel": "Abbrechen"
}
}
+117
View File
@@ -931,6 +931,27 @@
"colorInk": "Default",
"colorPaper": "Paper",
"colorNone": "None"
},
"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."
}
},
"comments": {
@@ -1300,5 +1321,101 @@
"exportSvg": "Export as SVG",
"defaultEdgeless": "Open as canvas for everyone",
"defaultPage": "Open as page for everyone"
},
"ai": {
"title": "AI chat",
"history": "Earlier chats",
"newChat": "New chat",
"untitled": "Untitled chat",
"delete": "Delete this chat",
"deleteConfirm": "Delete this chat?",
"close": "Close AI chat",
"notSetUp": "AI is not set up in this workspace yet.",
"setUp": "Set up AI in the workspace settings",
"askAdmin": "Ask a workspace admin to add an AI provider.",
"intro": {
"page": "Ask about “{title}”: summaries, answers and to-dos from this page.",
"space": "Ask about the pages of this space. Answers link to their sources.",
"workspace": "Ask about anything in this workspace. Answers link to their sources."
},
"searchOnly": "This workspace is not indexed for AI, so answers draw on search results.",
"sources": "Sources",
"copy": "Copy",
"copied": "Copied",
"fork": "Continue in a new chat",
"thinking": "Writing the answer…",
"searching": "Looking through the pages…",
"failed": "The AI could not answer.",
"stop": "Stop",
"send": "Send",
"placeholder": "Ask about the {scope}…",
"scope": {
"label": "About",
"page": "Page",
"space": "Space",
"workspace": "Workspace"
},
"settingsTitle": "AI",
"settingsHint": "Chat, writing help and search by meaning, with the AI provider you choose. Nothing is sent to a provider until one is added here or by the server's admin.",
"enabled": "Turn AI on in this workspace",
"enabledHint": "Members get the AI chat and writing actions.",
"useInstance": "Use the server's AI providers",
"useInstanceHint": "After the providers below, also try the ones the server's admin set up.",
"profiles": "Providers",
"profilesHint": "Tried from the top; when one fails, the next one answers. Keys are stored encrypted and never shown again.",
"indexTitle": "Search by meaning",
"index": "Index pages for AI",
"indexHint": "Sends the text of every page to the embedding provider, so the chat finds pages by meaning. Without it, the chat uses keyword search.",
"noEmbedProfile": "No provider has an embedding model; add one to a provider to index pages.",
"indexStatus": "{indexed} of {pages} pages indexed, {chunks} pieces, with {model} ({profile})",
"indexing": "indexing now",
"rebuild": "Index again",
"rebuildConfirm": "Drop the index and embed every page again?",
"lastError": "Last error: {error}",
"ignoredTitle": "Pages left out",
"ignoredHint": "These pages and their subpages are not indexed or used in answers.",
"ignoreSearch": "Find a page to leave out",
"filesTitle": "Extra documents",
"filesHint": "Text, Markdown, HTML or Word files the chat can use as sources (up to 10 MB each).",
"fileIndexed": "indexed",
"fileWaiting": "waiting for the index",
"addFiles": "Add files…",
"kinds": {
"openai": "OpenAI-compatible",
"anthropic": "Anthropic",
"ollama": "Ollama"
},
"chat": "chat",
"embeddings": "embeddings",
"keySet": "key stored",
"noKey": "no key",
"usage": "{requests} requests, {input} tokens in, {output} out",
"moveUp": "Move up",
"moveDown": "Move down",
"test": "Test",
"edit": "Edit",
"disable": "Turn off",
"enable": "Turn on",
"testOk": "Works ({ms} ms).",
"dimensions": "{n} dimensions",
"noProfiles": "No providers yet.",
"kind": "Provider",
"name": "Name",
"baseUrl": "Address",
"baseUrlHint": {
"openai": "OpenAI, or any compatible API: Azure, OpenRouter, LiteLLM, vLLM, LocalAI…",
"anthropic": "Leave empty for Anthropic's API.",
"ollama": "Where Ollama runs, as the server sees it."
},
"apiKey": "API key",
"keepKey": "Leave empty to keep the stored key",
"optional": "Optional",
"chatModel": "Chat model",
"embedModel": "Embedding model",
"noEmbeddings": "Anthropic has no embeddings",
"effort": "Effort",
"effortDefault": "Model default",
"addProfile": "Add a provider",
"cancel": "Cancel"
}
}
+117
View File
@@ -931,6 +931,27 @@
"colorInk": "Predeterminado",
"colorPaper": "Papel",
"colorNone": "Ninguno"
},
"ai": {
"button": "Preguntar a la IA",
"rewrite": "Mejorar el texto",
"summarize": "Resumir",
"translate": "Traducir",
"continue": "Seguir escribiendo",
"shorter": "Acortar",
"longer": "Alargar",
"fix": "Corregir ortografía y gramática",
"custom": "Pedir a la IA que…",
"customPlaceholder": "Dile a la IA qué hacer con la selección",
"language": "Idioma",
"run": "Ir",
"working": "Escribiendo…",
"replace": "Reemplazar la selección",
"insertBelow": "Insertar debajo",
"discard": "Descartar",
"stop": "Detener",
"retry": "Reintentar",
"failed": "La IA no pudo terminar."
}
},
"comments": {
@@ -1300,5 +1321,101 @@
"exportSvg": "Exportar como SVG",
"defaultEdgeless": "Abrir como lienzo para todos",
"defaultPage": "Abrir como página para todos"
},
"ai": {
"title": "Chat de IA",
"history": "Chats anteriores",
"newChat": "Chat nuevo",
"untitled": "Chat sin título",
"delete": "Eliminar este chat",
"deleteConfirm": "¿Eliminar este chat?",
"close": "Cerrar el chat de IA",
"notSetUp": "La IA aún no está configurada en este espacio de trabajo.",
"setUp": "Configurar la IA en los ajustes del espacio de trabajo",
"askAdmin": "Pide a un administrador del espacio de trabajo que añada un proveedor de IA.",
"intro": {
"page": "Pregunta sobre «{title}»: resúmenes, respuestas y tareas de esta página.",
"space": "Pregunta sobre las páginas de este espacio. Las respuestas enlazan sus fuentes.",
"workspace": "Pregunta sobre cualquier cosa de este espacio de trabajo. Las respuestas enlazan sus fuentes."
},
"searchOnly": "Este espacio de trabajo no está indexado para la IA, así que las respuestas usan la búsqueda.",
"sources": "Fuentes",
"copy": "Copiar",
"copied": "Copiado",
"fork": "Seguir en un chat nuevo",
"thinking": "Escribiendo la respuesta…",
"searching": "Buscando en las páginas…",
"failed": "La IA no pudo responder.",
"stop": "Detener",
"send": "Enviar",
"placeholder": "Pregunta sobre: {scope}…",
"scope": {
"label": "Sobre",
"page": "Página",
"space": "Espacio",
"workspace": "Espacio de trabajo"
},
"settingsTitle": "IA",
"settingsHint": "Chat, ayuda para escribir y búsqueda por significado, con el proveedor de IA que elijas. No se envía nada a ningún proveedor hasta que se añada uno aquí o lo haga la administración del servidor.",
"enabled": "Activar la IA en este espacio de trabajo",
"enabledHint": "Los miembros tienen el chat de IA y las acciones de escritura.",
"useInstance": "Usar los proveedores de IA del servidor",
"useInstanceHint": "Después de los proveedores de abajo, probar también los de la administración del servidor.",
"profiles": "Proveedores",
"profilesHint": "Se prueban de arriba abajo; si uno falla, responde el siguiente. Las claves se guardan cifradas y no se vuelven a mostrar.",
"indexTitle": "Búsqueda por significado",
"index": "Indexar las páginas para la IA",
"indexHint": "Envía el texto de cada página al proveedor de embeddings para que el chat encuentre páginas por su significado. Sin esto, el chat usa la búsqueda por palabras.",
"noEmbedProfile": "Ningún proveedor tiene modelo de embeddings; añade uno a un proveedor para indexar páginas.",
"indexStatus": "{indexed} de {pages} páginas indexadas, {chunks} fragmentos, con {model} ({profile})",
"indexing": "indexando ahora",
"rebuild": "Volver a indexar",
"rebuildConfirm": "¿Borrar el índice e indexar de nuevo todas las páginas?",
"lastError": "Último error: {error}",
"ignoredTitle": "Páginas excluidas",
"ignoredHint": "Estas páginas y sus subpáginas no se indexan ni se usan en las respuestas.",
"ignoreSearch": "Buscar una página para excluir",
"filesTitle": "Documentos adicionales",
"filesHint": "Archivos de texto, Markdown, HTML o Word que el chat puede usar como fuentes (hasta 10 MB cada uno).",
"fileIndexed": "indexado",
"fileWaiting": "esperando al índice",
"addFiles": "Añadir archivos…",
"kinds": {
"openai": "Compatible con OpenAI",
"anthropic": "Anthropic",
"ollama": "Ollama"
},
"chat": "chat",
"embeddings": "embeddings",
"keySet": "clave guardada",
"noKey": "sin clave",
"usage": "{requests} solicitudes, {input} tokens de entrada, {output} de salida",
"moveUp": "Subir",
"moveDown": "Bajar",
"test": "Probar",
"edit": "Editar",
"disable": "Desactivar",
"enable": "Activar",
"testOk": "Funciona ({ms} ms).",
"dimensions": "{n} dimensiones",
"noProfiles": "Aún no hay proveedores.",
"kind": "Proveedor",
"name": "Nombre",
"baseUrl": "Dirección",
"baseUrlHint": {
"openai": "OpenAI o cualquier API compatible: Azure, OpenRouter, LiteLLM, vLLM, LocalAI…",
"anthropic": "Déjalo vacío para la API de Anthropic.",
"ollama": "Dónde se ejecuta Ollama, visto desde el servidor."
},
"apiKey": "Clave de API",
"keepKey": "Déjalo vacío para conservar la clave guardada",
"optional": "Opcional",
"chatModel": "Modelo de chat",
"embedModel": "Modelo de embeddings",
"noEmbeddings": "Anthropic no tiene embeddings",
"effort": "Esfuerzo",
"effortDefault": "El del modelo",
"addProfile": "Añadir un proveedor",
"cancel": "Cancelar"
}
}
+117
View File
@@ -931,6 +931,27 @@
"colorInk": "Par défaut",
"colorPaper": "Papier",
"colorNone": "Aucune"
},
"ai": {
"button": "Demander à l’IA",
"rewrite": "Améliorer le texte",
"summarize": "Résumer",
"translate": "Traduire",
"continue": "Continuer la rédaction",
"shorter": "Raccourcir",
"longer": "Développer",
"fix": "Corriger l’orthographe et la grammaire",
"custom": "Demander à l’IA de…",
"customPlaceholder": "Dites à l’IA quoi faire de la sélection",
"language": "Langue",
"run": "OK",
"working": "Rédaction…",
"replace": "Remplacer la sélection",
"insertBelow": "Insérer en dessous",
"discard": "Abandonner",
"stop": "Arrêter",
"retry": "Réessayer",
"failed": "L’IA n’a pas pu terminer."
}
},
"comments": {
@@ -1300,5 +1321,101 @@
"exportSvg": "Exporter en SVG",
"defaultEdgeless": "Ouvrir en tableau pour tous",
"defaultPage": "Ouvrir en page pour tous"
},
"ai": {
"title": "Chat IA",
"history": "Chats précédents",
"newChat": "Nouveau chat",
"untitled": "Chat sans titre",
"delete": "Supprimer ce chat",
"deleteConfirm": "Supprimer ce chat ?",
"close": "Fermer le chat IA",
"notSetUp": "L’IA n’est pas encore configurée dans cet espace de travail.",
"setUp": "Configurer l’IA dans les paramètres de l’espace de travail",
"askAdmin": "Demandez à un administrateur de l’espace de travail d’ajouter un fournisseur d’IA.",
"intro": {
"page": "Posez vos questions sur « {title} » : résumés, réponses et tâches tirés de cette page.",
"space": "Posez vos questions sur les pages de cet espace. Les réponses renvoient à leurs sources.",
"workspace": "Posez vos questions sur tout cet espace de travail. Les réponses renvoient à leurs sources."
},
"searchOnly": "Cet espace de travail n’est pas indexé pour l’IA : les réponses s’appuient sur la recherche.",
"sources": "Sources",
"copy": "Copier",
"copied": "Copié",
"fork": "Continuer dans un nouveau chat",
"thinking": "Rédaction de la réponse…",
"searching": "Parcours des pages…",
"failed": "L’IA n’a pas pu répondre.",
"stop": "Arrêter",
"send": "Envoyer",
"placeholder": "Question sur : {scope}…",
"scope": {
"label": "Sur",
"page": "Page",
"space": "Espace",
"workspace": "Espace de travail"
},
"settingsTitle": "IA",
"settingsHint": "Chat, aide à la rédaction et recherche par le sens, avec le fournisseur d’IA de votre choix. Rien n’est envoyé à un fournisseur tant qu’aucun n’est ajouté ici ou par l’administration du serveur.",
"enabled": "Activer l’IA dans cet espace de travail",
"enabledHint": "Les membres ont le chat IA et les actions de rédaction.",
"useInstance": "Utiliser les fournisseurs d’IA du serveur",
"useInstanceHint": "Après les fournisseurs ci-dessous, essayer aussi ceux de l’administration du serveur.",
"profiles": "Fournisseurs",
"profilesHint": "Essayés de haut en bas ; si l’un échoue, le suivant répond. Les clés sont chiffrées et ne sont plus jamais affichées.",
"indexTitle": "Recherche par le sens",
"index": "Indexer les pages pour l’IA",
"indexHint": "Envoie le texte de chaque page au fournisseur d’embeddings, pour que le chat trouve les pages par leur sens. Sans cela, le chat utilise la recherche par mots-clés.",
"noEmbedProfile": "Aucun fournisseur n’a de modèle d’embeddings ; ajoutez-en un à un fournisseur pour indexer les pages.",
"indexStatus": "{indexed} pages sur {pages} indexées, {chunks} extraits, avec {model} ({profile})",
"indexing": "indexation en cours",
"rebuild": "Réindexer",
"rebuildConfirm": "Supprimer l’index et réindexer toutes les pages ?",
"lastError": "Dernière erreur : {error}",
"ignoredTitle": "Pages exclues",
"ignoredHint": "Ces pages et leurs sous-pages ne sont ni indexées ni utilisées dans les réponses.",
"ignoreSearch": "Chercher une page à exclure",
"filesTitle": "Documents supplémentaires",
"filesHint": "Fichiers texte, Markdown, HTML ou Word que le chat peut citer (10 Mo chacun au plus).",
"fileIndexed": "indexé",
"fileWaiting": "en attente de l’index",
"addFiles": "Ajouter des fichiers…",
"kinds": {
"openai": "Compatible OpenAI",
"anthropic": "Anthropic",
"ollama": "Ollama"
},
"chat": "chat",
"embeddings": "embeddings",
"keySet": "clé enregistrée",
"noKey": "aucune clé",
"usage": "{requests} requêtes, {input} jetons en entrée, {output} en sortie",
"moveUp": "Monter",
"moveDown": "Descendre",
"test": "Tester",
"edit": "Modifier",
"disable": "Désactiver",
"enable": "Activer",
"testOk": "Fonctionne ({ms} ms).",
"dimensions": "{n} dimensions",
"noProfiles": "Aucun fournisseur pour l’instant.",
"kind": "Fournisseur",
"name": "Nom",
"baseUrl": "Adresse",
"baseUrlHint": {
"openai": "OpenAI, ou toute API compatible : Azure, OpenRouter, LiteLLM, vLLM, LocalAI…",
"anthropic": "Laisser vide pour l’API d’Anthropic.",
"ollama": "Où tourne Ollama, vu depuis le serveur."
},
"apiKey": "Clé d’API",
"keepKey": "Laisser vide pour garder la clé enregistrée",
"optional": "Facultatif",
"chatModel": "Modèle de chat",
"embedModel": "Modèle d’embeddings",
"noEmbeddings": "Anthropic n’a pas d’embeddings",
"effort": "Effort",
"effortDefault": "Valeur du modèle",
"addProfile": "Ajouter un fournisseur",
"cancel": "Annuler"
}
}
+117
View File
@@ -931,6 +931,27 @@
"colorInk": "Domyślny",
"colorPaper": "Papier",
"colorNone": "Brak"
},
"ai": {
"button": "Zapytaj AI",
"rewrite": "Popraw styl",
"summarize": "Podsumuj",
"translate": "Przetłumacz",
"continue": "Pisz dalej",
"shorter": "Skróć",
"longer": "Rozwiń",
"fix": "Popraw pisownię i gramatykę",
"custom": "Poproś AI, aby…",
"customPlaceholder": "Napisz, co AI ma zrobić z zaznaczeniem",
"language": "Język",
"run": "Dalej",
"working": "Pisze…",
"replace": "Zastąp zaznaczenie",
"insertBelow": "Wstaw poniżej",
"discard": "Odrzuć",
"stop": "Zatrzymaj",
"retry": "Spróbuj ponownie",
"failed": "AI nie dokończyło zadania."
}
},
"comments": {
@@ -1300,5 +1321,101 @@
"exportSvg": "Eksportuj jako SVG",
"defaultEdgeless": "Otwieraj jako tablicę dla wszystkich",
"defaultPage": "Otwieraj jako stronę dla wszystkich"
},
"ai": {
"title": "Czat AI",
"history": "Wcześniejsze czaty",
"newChat": "Nowy czat",
"untitled": "Czat bez tytułu",
"delete": "Usuń ten czat",
"deleteConfirm": "Usunąć ten czat?",
"close": "Zamknij czat AI",
"notSetUp": "AI nie jest jeszcze skonfigurowane w tym obszarze roboczym.",
"setUp": "Skonfiguruj AI w ustawieniach obszaru roboczego",
"askAdmin": "Poproś administratora obszaru roboczego o dodanie dostawcy AI.",
"intro": {
"page": "Pytaj o „{title}”: podsumowania, odpowiedzi i zadania z tej strony.",
"space": "Pytaj o strony tej przestrzeni. Odpowiedzi linkują do źródeł.",
"workspace": "Pytaj o wszystko w tym obszarze roboczym. Odpowiedzi linkują do źródeł."
},
"searchOnly": "Ten obszar roboczy nie jest zaindeksowany dla AI, więc odpowiedzi opierają się na wyszukiwaniu.",
"sources": "Źródła",
"copy": "Kopiuj",
"copied": "Skopiowano",
"fork": "Kontynuuj w nowym czacie",
"thinking": "Pisze odpowiedź…",
"searching": "Przegląda strony…",
"failed": "AI nie mogło odpowiedzieć.",
"stop": "Zatrzymaj",
"send": "Wyślij",
"placeholder": "Zapytaj o: {scope}…",
"scope": {
"label": "Dotyczy",
"page": "Strona",
"space": "Przestrzeń",
"workspace": "Obszar roboczy"
},
"settingsTitle": "AI",
"settingsHint": "Czat, pomoc w pisaniu i wyszukiwanie po znaczeniu, z wybranym dostawcą AI. Nic nie trafia do dostawcy, dopóki nie zostanie dodany tutaj lub przez administratora serwera.",
"enabled": "Włącz AI w tym obszarze roboczym",
"enabledHint": "Członkowie dostają czat AI i akcje pisania.",
"useInstance": "Używaj dostawców AI serwera",
"useInstanceHint": "Po dostawcach poniżej próbuj też tych skonfigurowanych przez administratora serwera.",
"profiles": "Dostawcy",
"profilesHint": "Próbowani od góry; gdy jeden zawiedzie, odpowiada następny. Klucze są szyfrowane i nigdy więcej nie są pokazywane.",
"indexTitle": "Wyszukiwanie po znaczeniu",
"index": "Indeksuj strony dla AI",
"indexHint": "Wysyła tekst każdej strony do dostawcy embeddingów, żeby czat znajdował strony po znaczeniu. Bez tego czat korzysta z wyszukiwania słów.",
"noEmbedProfile": "Żaden dostawca nie ma modelu embeddingów; dodaj go do któregoś, aby indeksować strony.",
"indexStatus": "Zaindeksowano {indexed} z {pages} stron, {chunks} fragmentów, modelem {model} ({profile})",
"indexing": "trwa indeksowanie",
"rebuild": "Indeksuj ponownie",
"rebuildConfirm": "Usunąć indeks i zaindeksować wszystkie strony od nowa?",
"lastError": "Ostatni błąd: {error}",
"ignoredTitle": "Pominięte strony",
"ignoredHint": "Te strony i ich podstrony nie są indeksowane ani używane w odpowiedziach.",
"ignoreSearch": "Znajdź stronę do pominięcia",
"filesTitle": "Dodatkowe dokumenty",
"filesHint": "Pliki tekstowe, Markdown, HTML lub Word, z których czat może korzystać jako źródeł (do 10 MB każdy).",
"fileIndexed": "zaindeksowany",
"fileWaiting": "czeka na indeks",
"addFiles": "Dodaj pliki…",
"kinds": {
"openai": "Zgodny z OpenAI",
"anthropic": "Anthropic",
"ollama": "Ollama"
},
"chat": "czat",
"embeddings": "embeddingi",
"keySet": "klucz zapisany",
"noKey": "brak klucza",
"usage": "Zapytania: {requests}, tokeny wejściowe: {input}, wyjściowe: {output}",
"moveUp": "W górę",
"moveDown": "W dół",
"test": "Testuj",
"edit": "Edytuj",
"disable": "Wyłącz",
"enable": "Włącz",
"testOk": "Działa ({ms} ms).",
"dimensions": "Wymiary: {n}",
"noProfiles": "Brak dostawców.",
"kind": "Dostawca",
"name": "Nazwa",
"baseUrl": "Adres",
"baseUrlHint": {
"openai": "OpenAI lub dowolne zgodne API: Azure, OpenRouter, LiteLLM, vLLM, LocalAI…",
"anthropic": "Zostaw puste dla API Anthropic.",
"ollama": "Gdzie działa Ollama, widziane z serwera."
},
"apiKey": "Klucz API",
"keepKey": "Zostaw puste, aby zachować zapisany klucz",
"optional": "Opcjonalnie",
"chatModel": "Model czatu",
"embedModel": "Model embeddingów",
"noEmbeddings": "Anthropic nie ma embeddingów",
"effort": "Wysiłek",
"effortDefault": "Domyślny modelu",
"addProfile": "Dodaj dostawcę",
"cancel": "Anuluj"
}
}
@@ -27,6 +27,7 @@ import PageComments from "../../components/PageComments.vue";
import PageList from "../../components/PageList.vue";
import PageProperties from "../../components/PageProperties.vue";
import ShareDialog from "../../components/ShareDialog.vue";
import { useAiWriter } from "../../composables/useAi";
import { useEditorLabels, useMentions, usePageLinks } from "../../composables/useEditorHosts";
import { useFileHost } from "../../composables/useFiles";
import { useSplit } from "../../composables/useSplit";
@@ -77,6 +78,7 @@ const busy = ref(false);
const historyOpen = ref(false);
const shareOpen = ref(false);
const labels = useEditorLabels();
const aiWriter = useAiWriter(() => page.value?.workspace);
const mentions = useMentions(() => page.value?.workspace);
const pageLinks = usePageLinks(
() => page.value?.workspace,
@@ -958,6 +960,7 @@ const purge = () =>
:synced-pages="syncedPages"
:record-page="main ? recordPage : undefined"
:code-line-numbers="prefs.codeLineNumbers"
:ai="aiWriter"
:user="me"
:editable="editable"
:placeholder="editable ? $t('page.placeholder') : ''"
@@ -1,5 +1,6 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import WorkspaceAI from "../../components/ai/WorkspaceAI.vue";
import type { Invite, PageMode, Workspace, WorkspaceMember, WorkspaceRole } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
@@ -256,6 +257,7 @@ async function removeWorkspace() {
<WorkspaceProperties :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceTags :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceWebhooks v-if="canManage" :workspace="ws.id" />
<WorkspaceAI v-if="canManage" :workspace="ws.id" />
<section v-if="atLeast(myRole, 'owner')" class="dw-card">
<h2 class="text-ui-lg">{{ $t("org.dangerTitle") }}</h2>
+610
View File
@@ -3027,6 +3027,458 @@ paths:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getWorkspaceAi
tags: [ai]
summary: What AI offers in the workspace to the caller (member)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiAvailability" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/settings:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getAiSettings
tags: [ai]
summary: The workspace's AI switches (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSettings" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
put:
operationId: saveAiSettings
tags: [ai]
summary: Replace the workspace's AI switches (workspace admin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiSettings" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSettings" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/profiles:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listAiProfiles
tags: [ai]
summary: The workspace's AI provider profiles, in order (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiProfile" } }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createAiProfile
tags: [ai]
summary: 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.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfileInput" }
responses:
"201":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfile" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/profiles/order:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
put:
operationId: orderAiProfiles
tags: [ai]
summary: Set the order of the workspace's profiles (workspace admin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/IdList" }
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiProfile" } }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/admin/ai/profiles:
get:
operationId: listInstanceAiProfiles
tags: [admin]
summary: The instance's default AI profiles (superadmin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiProfile" } }
"403": { $ref: "#/components/responses/Error" }
post:
operationId: createInstanceAiProfile
tags: [admin]
summary: Add an instance default profile (superadmin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfileInput" }
responses:
"201":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfile" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
/api/v1/admin/ai/profiles/order:
put:
operationId: orderInstanceAiProfiles
tags: [admin]
summary: Set the order of the instance's profiles (superadmin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/IdList" }
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiProfile" } }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
/api/v1/ai/profiles/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
patch:
operationId: updateAiProfile
tags: [ai]
summary: Change a profile; a missing apiKey keeps the stored one (workspace admin, or superadmin for instance profiles)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfileInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiProfile" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteAiProfile
tags: [ai]
summary: Remove a profile
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/ai/profiles/{id}/test:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: testAiProfile
tags: [ai]
summary: Send a one-word chat (and a one-line embedding) through a profile
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiTestResult" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/index:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getAiIndex
tags: [ai]
summary: Embeddings progress of the workspace (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiIndexStatus" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/index/rebuild:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: rebuildAiIndex
tags: [ai]
summary: Drop the workspace's vectors and embed every page again (workspace admin)
security: [{ bearer: [] }]
responses:
"204": { description: Started }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/files:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listAiFiles
tags: [ai]
summary: Extra documents chat retrieves from (workspace admin)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiFile" } }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: addAiFile
tags: [ai]
summary: Add a text, Markdown, HTML or Word file (up to 10 MB) for retrieval (workspace admin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file]
properties:
file: { type: string, format: binary }
responses:
"201":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiFile" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/ai/files/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
delete:
operationId: deleteAiFile
tags: [ai]
summary: Remove an extra file and its vectors (workspace admin)
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/sessions:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listAiSessions
tags: [ai]
summary: The caller's AI chats in the workspace, newest first
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/AiSessionSummary" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createAiSession
tags: [ai]
summary: Start an AI chat about the workspace, a space or a page
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiSessionInput" }
responses:
"201":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSession" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/ai/sessions/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getAiSession
tags: [ai]
summary: One of the caller's chats with its messages
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSession" }
"404": { $ref: "#/components/responses/Error" }
patch:
operationId: updateAiSession
tags: [ai]
summary: Rename a chat or change what it asks about
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiSessionInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSession" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteAiSession
tags: [ai]
summary: Delete a chat
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"404": { $ref: "#/components/responses/Error" }
/api/v1/ai/sessions/{id}/fork:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: forkAiSession
tags: [ai]
summary: Copy a chat up to a message (all of it without one)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiForkInput" }
responses:
"201":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/AiSession" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/ai/sessions/{id}/messages:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: askAi
tags: [ai]
summary: Ask a question in a chat; the answer streams as server-sent events
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { type: object, required: [content], properties: { content: { type: string, maxLength: 8000 } } }
responses:
"200":
description: >-
Events: sources ({citations: AiCitation[]}), delta ({text}), then done ({user: AiMessage, message: AiMessage}) or error ({message}). Errors before the stream starts are JSON.
content:
text/event-stream:
schema: { type: string }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/ai/write:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: aiWrite
tags: [ai]
summary: Run a writing action on a piece of text; the result (Markdown) streams as server-sent events
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/AiWriteInput" }
responses:
"200":
description: >-
Events: delta ({text}), then done ({}) or error ({message}). Errors before the stream starts are JSON.
content:
text/event-stream:
schema: { type: string }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/mcp:
post:
operationId: mcp
tags: [ai]
summary: 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.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { type: object, additionalProperties: true }
responses:
"200":
description: The JSON-RPC response
content:
application/json:
schema: { type: object, additionalProperties: true }
"202": { description: A notification was received }
"401": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearer:
@@ -4025,3 +4477,161 @@ components:
properties:
id: { type: string }
name: { type: string, description: Empty when the account is gone }
IdList:
type: object
required: [ids]
properties:
ids: { type: array, items: { type: string }, maxItems: 200 }
AiAvailability:
type: object
required: [chat, embeddings, canManage]
properties:
chat: { type: boolean, description: A profile with a chat model is set up and AI is on }
embeddings: { type: boolean, description: The workspace is indexed for retrieval }
canManage: { type: boolean, description: The caller may change the workspace's AI settings }
AiSettings:
type: object
required: [enabled, useInstanceProfiles, index, ignored]
properties:
enabled: { type: boolean }
useInstanceProfiles: { type: boolean, description: After its own profiles, the workspace uses the instance's }
index: { type: boolean, description: Embed pages for retrieval (sends every page to the embedding provider) }
ignored: { type: array, items: { type: string }, description: Pages (with their subpages) that are neither indexed nor retrieved }
AiProviderKind:
type: string
enum: [openai, anthropic, ollama]
description: openai is any OpenAI-compatible API
AiProfile:
type: object
required: [id, workspace, name, kind, baseUrl, keySet, chatModel, embedModel, effort, enabled, position, usage, lastUsed, lastError, created]
properties:
id: { type: string }
workspace: { type: string, description: Empty for an instance default }
name: { type: string }
kind: { $ref: "#/components/schemas/AiProviderKind" }
baseUrl: { type: string, description: Empty for the kind's default address }
keySet: { type: boolean, description: An API key is stored (keys are never returned) }
chatModel: { type: string }
embedModel: { type: string, description: Empty when the profile is not used for embeddings }
effort: { type: string, description: Anthropic effort level, empty for the model's default }
enabled: { type: boolean }
position: { type: integer }
usage:
type: object
required: [requests, inputTokens, outputTokens]
properties:
requests: { type: integer }
inputTokens: { type: integer }
outputTokens: { type: integer }
lastUsed: { type: string }
lastError: { type: string }
created: { type: string }
AiProfileInput:
type: object
description: Creating needs name and kind; updating changes the fields that are set
properties:
name: { type: string, maxLength: 80 }
kind: { $ref: "#/components/schemas/AiProviderKind" }
baseUrl: { type: string }
apiKey: { type: string, description: "Write-only; an empty string removes the key" }
chatModel: { type: string }
embedModel: { type: string }
effort: { type: string, enum: ["", low, medium, high, xhigh, max] }
enabled: { type: boolean }
AiTestResult:
type: object
required: [ok, chat, embeddings, dimensions, latencyMs, error]
properties:
ok: { type: boolean }
chat: { type: string, description: The model's reply }
embeddings: { type: string }
dimensions: { type: integer }
latencyMs: { type: integer }
error: { type: string }
AiIndexStatus:
type: object
required: [enabled, profile, model, pages, indexed, files, chunks, running, lastRun, lastError]
properties:
enabled: { type: boolean }
profile: { type: string, description: The profile vectors come from; empty when none has an embedding model }
model: { type: string }
pages: { type: integer, description: Pages that can be indexed }
indexed: { type: integer }
files: { type: integer }
chunks: { type: integer }
running: { type: boolean }
lastRun: { type: string }
lastError: { type: string }
AiFile:
type: object
required: [id, name, size, chars, indexed, created]
properties:
id: { type: string }
name: { type: string }
size: { type: integer }
chars: { type: integer }
indexed: { type: boolean }
created: { type: string }
AiScope:
type: string
enum: [workspace, space, page]
AiSessionSummary:
type: object
required: [id, title, scope, scopeId, created, updated]
properties:
id: { type: string }
title: { type: string }
scope: { $ref: "#/components/schemas/AiScope" }
scopeId: { type: string, description: The space or page; empty for the workspace }
created: { type: string }
updated: { type: string }
AiCitation:
type: object
required: [n, title, snippet]
properties:
n: { type: integer, description: "The number the answer cites as [n]" }
page: { type: string }
block: { type: string, description: "The cited block (link with #b-<block>)" }
file: { type: string, description: An extra file instead of a page }
title: { type: string }
snippet: { type: string }
AiMessage:
type: object
required: [id, role, content, created]
properties:
id: { type: string }
role: { type: string, enum: [user, assistant] }
content: { type: string, description: Markdown }
citations: { type: array, items: { $ref: "#/components/schemas/AiCitation" } }
error: { type: string, description: Why the answer stopped }
created: { type: string }
AiSession:
allOf:
- { $ref: "#/components/schemas/AiSessionSummary" }
- type: object
required: [workspace, messages]
properties:
workspace: { type: string }
messages: { type: array, items: { $ref: "#/components/schemas/AiMessage" } }
AiSessionInput:
type: object
properties:
title: { type: string, maxLength: 200 }
scope: { $ref: "#/components/schemas/AiScope" }
scopeId: { type: string }
AiForkInput:
type: object
properties:
message: { type: string, description: The last message to copy; empty copies all }
AiWriteAction:
type: string
enum: [rewrite, summarize, translate, continue, shorter, longer, fix, custom]
AiWriteInput:
type: object
required: [action, text]
properties:
action: { $ref: "#/components/schemas/AiWriteAction" }
text: { type: string, maxLength: 20000, description: The selection }
before: { type: string, description: Text in front of the selection (continue) }
language: { type: string, description: Target language (translate) }
instruction: { type: string, maxLength: 2000, description: What to do (custom) }
+2
View File
@@ -11665,6 +11665,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",