diff --git a/AGENTS.md b/AGENTS.md index e1778a6d..17842914 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -236,6 +236,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa - **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`). - **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing. - **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket). +- **Extension bundles:** each of the four extension settings pages (MCP servers, tools, skills, knowledgebases) exports the rows picked there as one JSON file (`cobble-extensions` v1, `{format, version, exported_at, app_version, items}`, one item per row: `{kind, key, config, redacted, env_keys, notes, documents?}`) and imports one again beside its "New ..." button. `src/functions/backend/db/extension-bundles/` holds the plain-data core (`exportExtensions({kind, ids})`, `previewExtensionImport({bundle, kind})`, `applyExtensionImport({bundle, kind, decisions, user_id})`; the three routes under `api/admin/extensions/` are thin wrappers, super admin only, so a chat path can reuse them later). Preview matches by natural identity (mcp and skill slug, tool name, knowledgebase name lowercased) and calls each item `new`, `same`, `conflict` (with the differing fields) or `invalid`; nothing is written until the super admin picks skip/add/overwrite/copy per item, and one bad item never fails the batch. **A bundle carries settings, never keys or reach:** `{{env.KEY}}` templates stay, literal `headers`/`env` values are left out and named in `redacted` (missing keys are listed for Settings > Environment), and no grant or `all_bots` travels, so every imported row starts unattached. Knowledgebase documents travel as their text (never bytes; ingest re-embeds them), and nothing is synced on import, so a new MCP server says "Not connected yet: Refresh". - **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces). ### Token usage diff --git a/src/data/app-data.ts b/src/data/app-data.ts index 0220da88..e9f89ff4 100644 --- a/src/data/app-data.ts +++ b/src/data/app-data.ts @@ -922,6 +922,17 @@ export const AppData = { ExtensionResearchMinChars: 40, ExtensionResearchMaxChars: 6000, ExtensionResearchSourcesMax: 10, + /** + * Extension bundles (Settings > MCP servers, Tools, Skills, + * Knowledgebases): the most items one imported file may hold, and the + * most documents one knowledgebase item carries. + */ + ExtensionBundleMaxItems: 500, + ExtensionBundleMaxDocuments: 2000, + /** + * The biggest bundle the import modal reads, before parsing. + */ + ExtensionBundleMaxBytes: 25_000_000, /** * `search_computers`: how long the command may run on each computer, * and how much of each computer's output the bot reads. diff --git a/src/functions/backend/db/extension-bundles/apply-extension-import.ts b/src/functions/backend/db/extension-bundles/apply-extension-import.ts new file mode 100644 index 00000000..fcdc3091 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/apply-extension-import.ts @@ -0,0 +1,252 @@ +import type { SaveCustomToolRequest, SaveMcpServerRequest, SaveSkillRequest } from "@/src/schemas/extension-schema"; +import type { SaveKnowledgebaseRequest } from "@/src/schemas/knowledgebase-schema"; +import type { + ExtensionBundle, + ExtensionBundleItem, + ExtensionBundleKind, + ExtensionImportAction, + ExtensionImportApplyPayload, + ExtensionImportDecision, + ExtensionImportOutcome, +} from "@/src/types"; +import mcpServerSlug from "@/src/utils/mcp-server-slug"; +import safeErrorMessage from "@/src/utils/safe-error-message"; +import grabMcpsOverview from "../extensions/grab-mcps-overview"; +import grabSkillsOverview from "../extensions/grab-skills-overview"; +import grabToolsOverview from "../extensions/grab-tools-overview"; +import saveCustomTool from "../extensions/save-custom-tool"; +import saveMcpServer from "../extensions/save-mcp-server"; +import saveSkill from "../extensions/save-skill"; +import grabKnowledgebasesOverview from "../knowledgebases/grab-knowledgebases-overview"; +import recordKnowledgebaseDocument from "../knowledgebases/record-knowledgebase-document"; +import saveKnowledgebase from "../knowledgebases/save-knowledgebase"; +import extensionItemSchema from "./extension-item-schemas"; +import grabExistingExtensionItems from "./grab-existing-extension-items"; +import matchExtensionItem, { type ExistingExtensionItem } from "./match-extension-item"; +import normalizeExtensionConfig from "./normalize-extension-config"; +import uniqueCopyName from "./unique-copy-name"; + +type Params = { + bundle: ExtensionBundle; + kind: ExtensionBundleKind; + /** + * What the user chose per item, by its place in the bundle. Anything + * left out gets its default: add a new one, leave a matching one alone. + */ + decisions: ExtensionImportDecision[]; + user_id: number; +}; + +/** + * Writes what the preview promised, one item at a time. An item that can't + * be read or saved is reported and the rest still go in; nothing here ever + * touches access, a connection or a document's bytes. + */ +export default async function applyExtensionImport({ bundle, kind, decisions, user_id }: Params): Promise { + const existing = await grabExistingExtensionItems({ kind }); + const chosen = new Map(decisions.map((decision) => [decision.index, decision.action])); + const outcomes: ExtensionImportOutcome[] = []; + + for (const [index, item] of bundle.items.entries()) { + if (item.kind != kind) continue; + + outcomes.push( + await importItem({ + index, + item, + action: chosen.get(index) ?? "add", + existing, + user_id, + }), + ); + } + + if (kind == "mcp") return { kind, outcomes, overview: await grabMcpsOverview({ user_id }) }; + if (kind == "tool") return { kind, outcomes, overview: await grabToolsOverview({ user_id }) }; + if (kind == "skill") return { kind, outcomes, overview: await grabSkillsOverview({ user_id }) }; + + return { kind, outcomes, overview: await grabKnowledgebasesOverview({ user_id }) }; +} + +type ImportItemParams = { + index: number; + item: ExtensionBundleItem; + action: ExtensionImportAction; + existing: ExistingExtensionItem[]; + user_id: number; +}; + +async function importItem({ index, item, action, existing, user_id }: ImportItemParams): Promise { + const name = typeof item.config.name == "string" ? item.config.name : item.key; + + if (action == "skip") return { index, name, action, ok: true, msg: "Left alone." }; + + const config = normalizeExtensionConfig({ kind: item.kind, config: item.config }); + + const parsed = extensionItemSchema({ kind: item.kind }).safeParse(config); + + if (!parsed.success) { + return { index, name, action, ok: false, msg: parsed.error.issues[0]?.message || "The item can't be read." }; + } + + const match = matchExtensionItem({ key: item.key, config, existing }); + const replace = action == "overwrite" && match.existing_id; + /** An overwrite changes settings, never who reaches the row. */ + const keep_all_bots = !!existing.find((row) => row.id == match.existing_id)?.all_bots; + const better = action == "copy" && !!match.existing_id; + const taken = existing.map((row) => String(row.config.name ?? row.key)); + + try { + if (item.kind == "mcp") { + const config = parsed.data as SaveMcpServerRequest; + const data: SaveMcpServerRequest = { + ...config, + mcp_server_id: replace ? (match.existing_id as number) : undefined, + name: better ? uniqueCopyName({ name, taken, style: "words", max_length: 80 }) : name, + all_bots: replace ? keep_all_bots : false, + }; + + const id = await saveMcpServer({ user_id, data }); + remember({ existing, id, replace, key: data.name == config.name ? item.key : mcpServerSlug({ name: data.name }), config: data, all_bots: data.all_bots }); + + return done({ index, action, name, better, copy_name: better ? data.name : "" }); + } + + if (item.kind == "tool") { + const config = parsed.data as SaveCustomToolRequest; + const data: SaveCustomToolRequest = { + ...config, + custom_tool_id: replace ? (match.existing_id as number) : undefined, + name: better ? uniqueCopyName({ name, taken, style: "snake", max_length: 64 }) : name, + all_bots: replace ? keep_all_bots : false, + }; + + const id = await saveCustomTool({ user_id, data }); + remember({ existing, id, replace, key: data.name, config: data, all_bots: data.all_bots }); + + return done({ index, action, name, better, copy_name: better ? data.name : "" }); + } + + if (item.kind == "skill") { + const config = parsed.data as SaveSkillRequest; + const slugs = existing.map((row) => String(row.config.slug ?? row.key)); + const data: SaveSkillRequest = { + ...config, + skill_id: replace ? (match.existing_id as number) : undefined, + name: better ? uniqueCopyName({ name, taken, style: "words", max_length: 80 }) : name, + slug: better + ? uniqueCopyName({ name: config.slug, taken: slugs, style: "dash", max_length: 64 }) + : config.slug, + all_bots: replace ? keep_all_bots : false, + }; + + const id = await saveSkill({ user_id, data }); + remember({ existing, id, replace, key: data.slug, config: data, all_bots: data.all_bots }); + + return done({ index, action, name, better, copy_name: better ? data.name : "" }); + } + + const config = parsed.data as SaveKnowledgebaseRequest; + const data: SaveKnowledgebaseRequest = { + ...config, + knowledgebase_id: replace ? (match.existing_id as number) : undefined, + name: better ? uniqueCopyName({ name, taken, style: "words", max_length: 80 }) : name, + all_bots: replace ? keep_all_bots : false, + }; + + const id = await saveKnowledgebase({ user_id, data }); + remember({ existing, id, replace, key: data.name.toLowerCase(), config: data, all_bots: data.all_bots }); + + const documents = await addDocuments({ item, knowledgebase_id: id, user_id }); + const outcome = done({ index, action, name, better, copy_name: better ? data.name : "" }); + + return { ...outcome, msg: `${outcome.msg}${documents}` }; + } catch (error) { + return { index, name, action, ok: false, msg: safeErrorMessage({ error }) }; + } +} + +type DoneParams = { + index: number; + action: ExtensionImportAction; + name: string; + better: boolean; + copy_name: string; +}; + +function done({ index, action, name, better, copy_name }: DoneParams): ExtensionImportOutcome { + if (action == "overwrite") return { index, name, action, ok: true, msg: `Replaced the settings of ${name}.` }; + if (better) return { index, name, action, ok: true, msg: `Added as ${copy_name}.` }; + + return { index, name, action, ok: true, msg: "Added." }; +} + +type RememberParams = { + existing: ExistingExtensionItem[]; + id: number; + replace: number | false | null; + key: string; + config: unknown; + all_bots: boolean; +}; + +/** + * Keeps the list being compared against current, so a file holding the same + * key twice can't add two identical rows. + */ +function remember({ existing, id, replace, key, config, all_bots }: RememberParams) { + const shape = config as Record; + + if (replace) { + const row = existing.find((candidate) => candidate.id == replace); + + if (row) { + row.key = key; + row.config = shape; + row.all_bots = all_bots; + } + + return; + } + + existing.push({ id, key, config: shape, all_bots }); +} + +type AddDocumentsParams = { + item: ExtensionBundleItem; + knowledgebase_id: number; + user_id: number; +}; + +/** + * A knowledgebase's text, document by document. What lands is what a bot + * reads; the passages and vectors are made again by the ingest worker. + */ +async function addDocuments({ item, knowledgebase_id, user_id }: AddDocumentsParams): Promise { + if (!item.documents.length) return ""; + + let added = 0; + let first_problem = ""; + + for (const document of item.documents) { + try { + await recordKnowledgebaseDocument({ + user_id, + knowledgebase_id, + name: document.name, + source: "text", + content: document.text, + mime_type: document.mime_type || "text/markdown", + size: Buffer.byteLength(document.text, "utf8"), + }); + + added++; + } catch (error) { + first_problem ||= safeErrorMessage({ error }); + } + } + + const counted = `${added} of ${item.documents.length} ${item.documents.length == 1 ? "document" : "documents"} added.`; + + return ` ${counted}${first_problem ? ` ${first_problem}` : ""}`; +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/export-extensions.ts b/src/functions/backend/db/extension-bundles/export-extensions.ts new file mode 100644 index 00000000..ba8a9b31 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/export-extensions.ts @@ -0,0 +1,37 @@ +import type { ExtensionBundle, ExtensionBundleKind } from "@/src/types"; +import runningVersion from "@/src/utils/running-version"; +import exportKnowledgebases from "./export-knowledgebases"; +import exportMcps from "./export-mcps"; +import exportSkills from "./export-skills"; +import exportTools from "./export-tools"; + +type Params = { + kind: ExtensionBundleKind; + /** + * The rows picked on the page, or none for every one. + */ + ids: number[]; +}; + +/** + * One page's extensions as a file another install can import: a single + * JSON document with the format's name and version in it, so a bundle of + * every kind is the same shape later. + */ +export default async function exportExtensions({ kind, ids }: Params): Promise { + const entries = await (kind == "mcp" + ? exportMcps({ ids }) + : kind == "tool" + ? exportTools({ ids }) + : kind == "skill" + ? exportSkills({ ids }) + : exportKnowledgebases({ ids })); + + return { + format: "cobble-extensions", + version: 1, + exported_at: Date.now(), + app_version: runningVersion({ env: process.env }).version || "", + items: entries.map((entry) => entry.item), + }; +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/export-knowledgebases.ts b/src/functions/backend/db/extension-bundles/export-knowledgebases.ts new file mode 100644 index 00000000..f5e02e12 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/export-knowledgebases.ts @@ -0,0 +1,107 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASES } from "@/db/types/db"; +import { AppData } from "@/src/data/app-data"; +import type { ExtensionBundleDocument } from "@/src/types"; +import grabKnowledgebaseDocumentText from "../knowledgebases/grab-knowledgebase-document-text"; +import parseKnowledgebaseRow from "../knowledgebases/parse-knowledgebase-row"; +import type { ExtensionBundleEntry } from "./extension-bundle-entry"; + +type Params = { + /** + * The rows picked, or none for every one. + */ + ids: number[]; +}; + +type DocumentRow = { + id: number; + name: string; + source: string; + media_id: number | null; + content: string | null; + mime_type: string; +}; + +/** + * Knowledgebases as a bundle carries them: the name and how it's + * described, and each document's text. Never a file's bytes and never the + * passages they were cut into: an import reads them again with its own + * embedding model, and a bot only ever reads text. + */ +export default async function exportKnowledgebases({ ids }: Params): Promise { + const rows = await BunSQLite.sql({ + sql: `SELECT * FROM knowledgebases ORDER BY name COLLATE NOCASE ASC, id ASC`, + }); + + const wanted = ids.length ? new Set(ids.map(Number)) : null; + const entries: ExtensionBundleEntry[] = []; + + for (const row of rows.payload || []) { + const knowledgebase = parseKnowledgebaseRow({ row }); + + if (wanted && !wanted.has(knowledgebase.id)) continue; + + const documents = await BunSQLite.sql({ + sql: `SELECT id, name, source, media_id, content, mime_type FROM knowledgebase_documents + WHERE knowledgebase_id = ? ORDER BY name COLLATE NOCASE ASC, id ASC`, + values: [knowledgebase.id], + }); + + const carried: ExtensionBundleDocument[] = []; + let empty = 0; + let cut = 0; + + for (const document of documents.payload || []) { + const text = await grabKnowledgebaseDocumentText({ document }); + + if (!text.trim()) { + empty++; + continue; + } + + if (text.length > AppData.KnowledgebaseTextMaxChars) cut++; + + carried.push({ + name: document.name || `Document ${document.id}`, + mime_type: "text/markdown", + text: text.slice(0, AppData.KnowledgebaseTextMaxChars), + }); + } + + const notes: string[] = []; + + if (empty) { + notes.push( + `${empty} ${empty == 1 ? "document" : "documents"} held no text to carry, so ${ + empty == 1 ? "it was" : "they were" + } left out.`, + ); + } + + if (cut) { + notes.push( + `${cut} ${cut == 1 ? "document was" : "documents were"} cut to ${AppData.KnowledgebaseTextMaxChars} characters.`, + ); + } + + entries.push({ + id: knowledgebase.id, + item: { + kind: "knowledgebase", + key: knowledgebase.name.toLowerCase(), + config: { + name: knowledgebase.name, + description: knowledgebase.description, + enabled: knowledgebase.enabled, + all_bots: false, + }, + redacted: [], + env_keys: [], + notes, + documents: carried, + }, + }); + } + + return entries; +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/export-mcps.ts b/src/functions/backend/db/extension-bundles/export-mcps.ts new file mode 100644 index 00000000..0ec6ba39 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/export-mcps.ts @@ -0,0 +1,65 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { BUN_SQLITE_COBBLE_MCP_SERVERS } from "@/db/types/db"; +import type { SaveMcpServerRequest } from "@/src/schemas/extension-schema"; +import extensionEnvUses from "@/src/utils/extension-env-uses"; +import redactTemplateMap from "@/src/utils/redact-template-map"; +import parseMcpServerRow from "../extensions/parse-mcp-server-row"; +import type { ExtensionBundleEntry } from "./extension-bundle-entry"; + +type Params = { + /** + * The rows picked, or none for every one. + */ + ids: number[]; +}; + +/** + * MCP servers as a bundle carries them: how each is reached, with its own + * header and env values left behind (listed in `redacted`, so the import + * says which), and never who it's attached to. + */ +export default async function exportMcps({ ids }: Params): Promise { + const rows = await BunSQLite.sql({ + sql: `SELECT * FROM mcp_servers ORDER BY name COLLATE NOCASE ASC, id ASC`, + }); + + const wanted = ids.length ? new Set(ids.map(Number)) : null; + + return (rows.payload || []) + .map((row) => parseMcpServerRow({ row })) + .filter((server) => !wanted || wanted.has(server.id)) + .map((server) => { + const remote = server.transport == "remote"; + const headers = redactTemplateMap({ values: remote ? server.headers : {}, label: "header" }); + const env = redactTemplateMap({ values: remote ? {} : server.env, label: "env" }); + + const config: SaveMcpServerRequest = { + name: server.name, + description: server.description, + transport: server.transport, + url: remote ? server.url : "", + headers: headers.values, + auth_scheme: remote ? server.auth_scheme : "none", + auth_header: remote ? server.auth_header : "", + command: remote ? "" : server.command, + setup_command: remote ? "" : server.setup_command, + env: env.values, + excluded_tools: server.excluded_tools, + enabled: server.enabled, + all_bots: false, + }; + + return { + id: server.id, + item: { + kind: "mcp", + key: server.slug || server.name, + config, + redacted: [...headers.redacted, ...env.redacted], + env_keys: [...new Set(extensionEnvUses({ kind: "mcp", data: config }).sends.map((use) => use.key))], + notes: [], + documents: [], + }, + }; + }); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/export-skills.ts b/src/functions/backend/db/extension-bundles/export-skills.ts new file mode 100644 index 00000000..469fa3ff --- /dev/null +++ b/src/functions/backend/db/extension-bundles/export-skills.ts @@ -0,0 +1,51 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { BUN_SQLITE_COBBLE_SKILLS } from "@/db/types/db"; +import type { SaveSkillRequest } from "@/src/schemas/extension-schema"; +import parseSkillRow from "../extensions/parse-skill-row"; +import type { ExtensionBundleEntry } from "./extension-bundle-entry"; + +type Params = { + /** + * The rows picked, or none for every one. + */ + ids: number[]; +}; + +/** + * Skills as a bundle carries them: the whole runbook and the line saying + * when to load it. + */ +export default async function exportSkills({ ids }: Params): Promise { + const rows = await BunSQLite.sql({ + sql: `SELECT * FROM skills ORDER BY name COLLATE NOCASE ASC, id ASC`, + }); + + const wanted = ids.length ? new Set(ids.map(Number)) : null; + + return (rows.payload || []) + .map((row) => parseSkillRow({ row })) + .filter((skill) => !wanted || wanted.has(skill.id)) + .map((skill) => { + const config: SaveSkillRequest = { + name: skill.name, + slug: skill.slug, + description: skill.description, + body: skill.body, + enabled: skill.enabled, + all_bots: false, + }; + + return { + id: skill.id, + item: { + kind: "skill", + key: skill.slug || skill.name, + config, + redacted: [], + env_keys: [], + notes: [], + documents: [], + }, + }; + }); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/export-tools.ts b/src/functions/backend/db/extension-bundles/export-tools.ts new file mode 100644 index 00000000..9158ff30 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/export-tools.ts @@ -0,0 +1,94 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { BUN_SQLITE_COBBLE_CUSTOM_TOOLS } from "@/db/types/db"; +import type { SaveCustomToolRequest } from "@/src/schemas/extension-schema"; +import extensionEnvUses from "@/src/utils/extension-env-uses"; +import redactTemplateMap from "@/src/utils/redact-template-map"; +import parseCustomToolRow from "../extensions/parse-custom-tool-row"; +import type { ExtensionBundleEntry } from "./extension-bundle-entry"; + +type Params = { + /** + * The rows picked, or none for every one. + */ + ids: number[]; +}; + +/** + * Custom tools as a bundle carries them: what each runs, with the headers + * of an http tool left behind when they hold a key rather than an env + * template. A body, a script and a prompt are the user's own text and go + * as they are. + */ +export default async function exportTools({ ids }: Params): Promise { + const rows = await BunSQLite.sql({ + sql: `SELECT * FROM custom_tools ORDER BY name COLLATE NOCASE ASC, id ASC`, + }); + + const wanted = ids.length ? new Set(ids.map(Number)) : null; + + return (rows.payload || []) + .map((row) => { + const tool = parseCustomToolRow({ row }); + const base = { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + enabled: tool.enabled, + all_bots: false, + }; + + if (tool.kind == "http") { + const headers = redactTemplateMap({ values: tool.config.headers || {}, label: "header" }); + const config: SaveCustomToolRequest = { + ...base, + kind: "http", + config: { + method: tool.config.method, + url: tool.config.url, + headers: headers.values, + body: tool.config.body || "", + timeout_ms: tool.config.timeout_ms, + }, + }; + + return { + id: tool.id, + item: { + kind: "tool" as const, + key: tool.name, + config, + redacted: headers.redacted, + env_keys: [...new Set(extensionEnvUses({ kind: "tool", data: config }).sends.map((use) => use.key))], + notes: [], + documents: [], + }, + }; + } + + const config: SaveCustomToolRequest = + tool.kind == "script" + ? { + ...base, + kind: "script", + config: { + language: tool.config.language, + code: tool.config.code, + timeout_ms: tool.config.timeout_ms, + }, + } + : { ...base, kind: "prompt", config: { prompt: tool.config.prompt } }; + + return { + id: tool.id, + item: { + kind: "tool" as const, + key: tool.name, + config, + redacted: [], + env_keys: [], + notes: [], + documents: [], + }, + }; + }); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/extension-bundle-entry.ts b/src/functions/backend/db/extension-bundles/extension-bundle-entry.ts new file mode 100644 index 00000000..e9a59384 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/extension-bundle-entry.ts @@ -0,0 +1,10 @@ +import type { ExtensionBundleItem } from "@/src/types"; + +/** + * An exported item with the row it came from: the bundle itself carries no + * ids, but the import needs them to say which row a match is. + */ +export type ExtensionBundleEntry = { + id: number; + item: ExtensionBundleItem; +}; \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/extension-item-schemas.ts b/src/functions/backend/db/extension-bundles/extension-item-schemas.ts new file mode 100644 index 00000000..43e9b5ac --- /dev/null +++ b/src/functions/backend/db/extension-bundles/extension-item-schemas.ts @@ -0,0 +1,23 @@ +import { SaveKnowledgebaseRequestSchema } from "@/src/schemas/knowledgebase-schema"; +import { + SaveCustomToolRequestSchema, + SaveMcpServerRequestSchema, + SaveSkillRequestSchema, +} from "@/src/schemas/extension-schema"; +import type { ExtensionBundleKind } from "@/src/types"; + +/** + * The schema a bundle's item of this kind is read with: the same one the + * row's own form saves through, so an import can never write a row the + * form would refuse. + */ +const Schemas = { + mcp: SaveMcpServerRequestSchema, + tool: SaveCustomToolRequestSchema, + skill: SaveSkillRequestSchema, + knowledgebase: SaveKnowledgebaseRequestSchema, +}; + +export default function extensionItemSchema({ kind }: { kind: ExtensionBundleKind }) { + return Schemas[kind]; +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/grab-existing-extension-items.ts b/src/functions/backend/db/extension-bundles/grab-existing-extension-items.ts new file mode 100644 index 00000000..b5627237 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/grab-existing-extension-items.ts @@ -0,0 +1,72 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { ExtensionBundleKind } from "@/src/types"; +import exportKnowledgebases from "./export-knowledgebases"; +import exportMcps from "./export-mcps"; +import exportSkills from "./export-skills"; +import exportTools from "./export-tools"; +import type { ExistingExtensionItem } from "./match-extension-item"; + +type Params = { + kind: ExtensionBundleKind; +}; + +type DocumentRow = { + knowledgebase_id: number; + name: string; + size: number; +}; + +type AccessRow = { + id: number; + all_bots: number; +}; + +const Tables: Record = { + mcp: "mcp_servers", + tool: "custom_tools", + skill: "skills", + knowledgebase: "knowledgebases", +}; + +/** + * The rows already here, in the shape a bundle carries them, so the import + * compares like with like: the same builder the export uses, so a value + * left out of a file is left out of this side too. + */ +export default async function grabExistingExtensionItems({ kind }: Params): Promise { + const entries = await (kind == "mcp" + ? exportMcps({ ids: [] }) + : kind == "tool" + ? exportTools({ ids: [] }) + : kind == "skill" + ? exportSkills({ ids: [] }) + : exportKnowledgebases({ ids: [] })); + + const access = await BunSQLite.sql({ + sql: `SELECT id, all_bots FROM ${Tables[kind]}`, + }); + + const every_bot = new Set( + (access.payload || []).filter((row) => Number(row.all_bots)).map((row) => Number(row.id)), + ); + + const items: ExistingExtensionItem[] = entries.map((entry) => ({ + id: entry.id, + key: entry.item.key, + config: entry.item.config as Record, + all_bots: every_bot.has(entry.id), + })); + + if (kind != "knowledgebase") return items; + + const rows = await BunSQLite.sql({ + sql: `SELECT knowledgebase_id, name, size FROM knowledgebase_documents`, + }); + + return items.map((item) => ({ + ...item, + documents: (rows.payload || []) + .filter((row) => Number(row.knowledgebase_id) == item.id) + .map((row) => ({ name: row.name || "", size: Number(row.size) || 0 })), + })); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/match-extension-item.test.ts b/src/functions/backend/db/extension-bundles/match-extension-item.test.ts new file mode 100644 index 00000000..98d9b7cb --- /dev/null +++ b/src/functions/backend/db/extension-bundles/match-extension-item.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, test } from "bun:test"; +import matchExtensionItem, { type ExistingExtensionItem } from "./match-extension-item"; + +const existing: ExistingExtensionItem[] = [ + { + id: 7, + key: "github", + config: { name: "GitHub", transport: "remote", url: "https://example.test/mcp", headers: { a: "b" } }, + }, + { + id: 9, + key: "weekly-seo-report", + config: { name: "Weekly SEO report", body: "# Do it" }, + }, +]; + +describe("matchExtensionItem", () => { + test("an item with no row here is new", () => { + expect(matchExtensionItem({ key: "linear", config: { name: "Linear" }, existing })).toEqual({ + status: "new", + existing_id: null, + differing: [], + }); + }); + + test("an identical config is the same row", () => { + expect( + matchExtensionItem({ + key: "github", + config: { name: "GitHub", transport: "remote", url: "https://example.test/mcp", headers: { a: "b" } }, + existing, + }), + ).toEqual({ status: "same", existing_id: 7, differing: [] }); + }); + + test("key order inside a config doesn't matter", () => { + expect( + matchExtensionItem({ + key: "github", + config: { headers: { a: "b" }, url: "https://example.test/mcp", transport: "remote", name: "GitHub" }, + existing, + }).status, + ).toBe("same"); + }); + + test("a changed config conflicts, naming the fields that differ", () => { + const match = matchExtensionItem({ + key: "github", + config: { name: "GitHub", transport: "remote", url: "https://other.test/mcp", headers: { a: "b" } }, + existing, + }); + + expect(match.status).toBe("conflict"); + expect(match.existing_id).toBe(7); + expect(match.differing).toEqual(["url"]); + }); + + test("a field only one side has counts as differing", () => { + expect( + matchExtensionItem({ key: "weekly-seo-report", config: { name: "Weekly SEO report", body: "# Do it", enabled: false }, existing }) + .differing, + ).toEqual(["enabled"]); + }); + + test("the fields a bundle never carries are ignored on both sides", () => { + expect( + matchExtensionItem({ + key: "github", + config: { + name: "GitHub", + transport: "remote", + url: "https://example.test/mcp", + headers: { a: "b" }, + all_bots: false, + mcp_server_id: 3, + }, + existing, + }).status, + ).toBe("same"); + }); + + test("nested arrays are compared by content, not by reference", () => { + expect( + matchExtensionItem({ + key: "github", + config: { + name: "GitHub", + transport: "remote", + url: "https://example.test/mcp", + headers: { a: "b" }, + excluded_tools: ["x", "y"], + }, + existing: [ + { + id: 7, + key: "github", + config: { + name: "GitHub", + transport: "remote", + url: "https://example.test/mcp", + headers: { a: "b" }, + excluded_tools: ["x", "y"], + }, + }, + ], + }).status, + ).toBe("same"); + }); +}); \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/match-extension-item.ts b/src/functions/backend/db/extension-bundles/match-extension-item.ts new file mode 100644 index 00000000..d6821f6c --- /dev/null +++ b/src/functions/backend/db/extension-bundles/match-extension-item.ts @@ -0,0 +1,98 @@ +/** + * What a knowledgebase's existing documents look like, by name and size: + * enough to tell one that changed from one that didn't, without reading + * every document back. + */ +export type ExtensionDocumentFingerprint = { + name: string; + size: number; +}; + +/** + * A row already here, as the import compares a bundle's item against it. + */ +export type ExistingExtensionItem = { + id: number; + key: string; + config: Record; + /** + * Whether the row reaches every bot: an overwrite keeps it, since an + * import changes settings and never access. + */ + all_bots?: boolean; + documents?: ExtensionDocumentFingerprint[]; +}; + +export type ExtensionMatchStatus = "new" | "same" | "conflict"; + +export type ExtensionMatch = { + status: ExtensionMatchStatus; + existing_id: number | null; + /** + * The config's top-level fields that differ, named, so the preview can + * say what an overwrite would change. + */ + differing: string[]; +}; + +type Params = { + key: string; + config: Record; + existing: ExistingExtensionItem[]; +}; + +/** + * Fields a bundle never carries, so comparing them would only ever see the + * importing install's own values. + */ +const IgnoredFields = ["all_bots", "mcp_server_id", "custom_tool_id", "skill_id", "knowledgebase_id"]; + +/** + * Whether an item is one this install doesn't have, one it has exactly, or + * one it has with different settings. The item's key is its natural + * identity: a server's or skill's slug, a tool's name, a knowledgebase's + * name lowercased. + */ +export default function matchExtensionItem({ key, config, existing }: Params): ExtensionMatch { + const match = existing.find((row) => row.key == key); + + if (!match) return { status: "new", existing_id: null, differing: [] }; + + const here = comparable({ config }); + const there = comparable({ config: match.config }); + const fields = new Set([...Object.keys(here), ...Object.keys(there)]); + const differing = [...fields] + .filter((field) => JSON.stringify(here[field]) !== JSON.stringify(there[field])) + .sort(); + + return { + status: differing.length ? "conflict" : "same", + existing_id: match.id, + differing, + }; +} + +/** + * A config with the fields a bundle never carries taken out and every + * object's keys sorted, so two equal configs serialize the same however + * they were written. + */ +function comparable({ config }: { config: Record }): Record { + return sorted( + Object.fromEntries(Object.entries(config).filter(([field]) => !IgnoredFields.includes(field))), + ) as Record; +} + +function sorted(value: unknown): unknown { + if (Array.isArray(value)) return value.map(sorted); + + if (value && typeof value == "object") { + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, sorted((value as Record)[key])]), + ); + } + + return value; +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/missing-env-keys.ts b/src/functions/backend/db/extension-bundles/missing-env-keys.ts new file mode 100644 index 00000000..9634b44d --- /dev/null +++ b/src/functions/backend/db/extension-bundles/missing-env-keys.ts @@ -0,0 +1,21 @@ +import grabProposalEnvs from "../extension-proposals/grab-proposal-envs"; + +type Params = { + keys: string[]; +}; + +/** + * The keys a bundle's templates need that nothing in this install fills: + * an import brings `{{env.KEY}}` with the server, never the value, so a + * key saved nowhere (or only for one bot) leaves the server unable to run + * until it's added. + */ +export default async function missingEnvKeys({ keys }: Params): Promise { + if (!keys.length) return []; + + const envs = await grabProposalEnvs({ + sends: [...new Set(keys)].map((key) => ({ key, where: "" })), + }); + + return envs.filter((env) => !env.saved_in.includes("general")).map((env) => env.key); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/normalize-extension-config.test.ts b/src/functions/backend/db/extension-bundles/normalize-extension-config.test.ts new file mode 100644 index 00000000..6edb0f8a --- /dev/null +++ b/src/functions/backend/db/extension-bundles/normalize-extension-config.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import normalizeExtensionConfig from "./normalize-extension-config"; + +const argumentsText = `{"type":"object","properties":{"topic":{"type":"string"}}}`; + +describe("normalizeExtensionConfig", () => { + test("reads a tool's arguments from the JSON text of the object", () => { + const config = normalizeExtensionConfig({ kind: "tool", config: { name: "search", parameters: argumentsText } }); + + expect(config.parameters).toEqual({ type: "object", properties: { topic: { type: "string" } } }); + }); + + test("leaves arguments that are already an object alone", () => { + const parameters = { type: "object", properties: {} }; + + expect(normalizeExtensionConfig({ kind: "tool", config: { parameters } }).parameters).toBe(parameters); + }); + + test("leaves text that isn't a JSON object alone, so the schema says what's wrong", () => { + expect(normalizeExtensionConfig({ kind: "tool", config: { parameters: "not json" } }).parameters).toBe("not json"); + expect(normalizeExtensionConfig({ kind: "tool", config: { parameters: "[1,2]" } }).parameters).toBe("[1,2]"); + }); + + test("never touches another kind", () => { + const config = { name: "Cold Email", body: "text" }; + + expect(normalizeExtensionConfig({ kind: "skill", config })).toBe(config); + }); +}); \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/normalize-extension-config.ts b/src/functions/backend/db/extension-bundles/normalize-extension-config.ts new file mode 100644 index 00000000..85566c59 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/normalize-extension-config.ts @@ -0,0 +1,25 @@ +import type { ExtensionBundleKind } from "@/src/types"; + +type Params = { + kind: ExtensionBundleKind; + config: Record; +}; + +/** + * A bundle's config as the row's own form would have it. A tool's arguments + * are an object, but a bundle written by hand, or pulled straight out of a + * database, can carry them as the JSON text of that object. + */ +export default function normalizeExtensionConfig({ kind, config }: Params): Record { + if (kind != "tool" || typeof config.parameters != "string") return config; + + try { + const parameters: unknown = JSON.parse(config.parameters); + + if (!parameters || typeof parameters != "object" || Array.isArray(parameters)) return config; + + return { ...config, parameters }; + } catch { + return config; + } +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/preview-extension-import.ts b/src/functions/backend/db/extension-bundles/preview-extension-import.ts new file mode 100644 index 00000000..a5196115 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/preview-extension-import.ts @@ -0,0 +1,158 @@ +import type { + ExtensionBundle, + ExtensionBundleItem, + ExtensionBundleKind, + ExtensionImportPreview, + ExtensionImportPreviewItem, + ExtensionImportStatus, +} from "@/src/types"; +import hasEnvTemplate from "@/src/utils/has-env-template"; +import extensionItemSchema from "./extension-item-schemas"; +import grabExistingExtensionItems from "./grab-existing-extension-items"; +import matchExtensionItem, { type ExistingExtensionItem } from "./match-extension-item"; +import missingEnvKeys from "./missing-env-keys"; +import normalizeExtensionConfig from "./normalize-extension-config"; + +type Params = { + bundle: ExtensionBundle; + kind: ExtensionBundleKind; +}; + +/** + * What importing this file's items of one kind would do, item by item: + * which is new here, which is already here exactly, which is here with + * different settings, and which can't be read at all. Nothing is written. + */ +export default async function previewExtensionImport({ bundle, kind }: Params): Promise { + const existing = await grabExistingExtensionItems({ kind }); + const counts: Record = { new: 0, same: 0, conflict: 0, invalid: 0 }; + const items: ExtensionImportPreviewItem[] = []; + + for (const [index, item] of bundle.items.entries()) { + if (item.kind != kind) continue; + + const preview = await previewItem({ index, item, existing }); + + counts[preview.status]++; + items.push(preview); + } + + return { + kind, + exported_at: bundle.exported_at, + app_version: bundle.app_version, + counts, + items, + other_kinds: bundle.items.filter((item) => item.kind != kind).length, + }; +} + +type PreviewItemParams = { + index: number; + item: ExtensionBundleItem; + existing: ExistingExtensionItem[]; +}; + +async function previewItem({ index, item, existing }: PreviewItemParams): Promise { + const base: ExtensionImportPreviewItem = { + index, + kind: item.kind, + key: item.key, + name: typeof item.config.name == "string" ? item.config.name : item.key, + status: "new", + existing_id: null, + differing: [], + problem: "", + warnings: [...item.notes], + redacted: item.redacted, + env_keys: item.env_keys, + document_count: item.documents.length, + copy_only: false, + }; + + const config = normalizeExtensionConfig({ kind: item.kind, config: item.config }); + + const parsed = extensionItemSchema({ kind: item.kind }).safeParse(config); + + if (!parsed.success) { + const issue = parsed.error.issues[0]; + + return { + ...base, + status: "invalid", + problem: issue + ? issue.path.length + ? `${issue.path.join(".")}: ${issue.message}` + : issue.message + : "The item can't be read.", + }; + } + + if (parsed.data.name) base.name = parsed.data.name; + + const match = matchExtensionItem({ key: item.key, config, existing }); + const warnings = [...base.warnings]; + + if (item.kind == "knowledgebase" && match.status == "same" && item.documents.length) { + const row = existing.find((candidate) => candidate.id == match.existing_id); + const here = fingerprints(row?.documents || []); + const there = fingerprints(item.documents.map((document) => ({ name: document.name, size: Buffer.byteLength(document.text, "utf8") }))); + + if (here != there) { + match.status = "conflict"; + match.differing = ["documents"]; + warnings.push("Its documents here are different, and an overwrite adds the file's beside them."); + } + } + + const same_name = item.kind == "knowledgebase" ? existing.filter((row) => row.key == item.key).length : 0; + + if (same_name > 1) { + warnings.push(`${same_name} knowledgebases here already have this name, so it can only be imported as a copy.`); + } + + if (item.kind == "mcp") { + const url = typeof config.url == "string" ? config.url : ""; + const other = url && !hasEnvTemplate({ values: [url] }) + ? existing.find((row) => row.key != item.key && row.config.url === url) + : undefined; + + if (other) warnings.push(`${String(other.config.name || other.key)} already uses this URL.`); + } + + if (item.kind == "tool") { + const other = existing.find((row) => row.key != item.key && row.key.toLowerCase() == item.key.toLowerCase()); + + if (other) warnings.push(`A tool named ${other.key} is already here; names are case-sensitive.`); + } + + const missing = await missingEnvKeys({ keys: item.env_keys }); + + if (missing.length) { + warnings.push(`Keys to add in Settings > Environment: ${missing.join(", ")}.`); + } + + if (item.redacted.length) { + warnings.push(`Left out of the file: ${item.redacted.join(", ")}. Add them on the row after importing.`); + } + + return { + ...base, + status: same_name > 1 ? "conflict" : match.status, + existing_id: match.existing_id, + differing: match.differing, + warnings, + copy_only: same_name > 1, + }; +} + +/** + * Documents as one comparable line: names and sizes in order, so two sets + * with the same documents read the same however they were added. + */ +function fingerprints(documents: { name: string; size: number }[]): string { + return documents + .map((document) => `${document.name}:${document.size}`) + .sort() + .join("|"); +} \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/unique-copy-name.test.ts b/src/functions/backend/db/extension-bundles/unique-copy-name.test.ts new file mode 100644 index 00000000..d84e280b --- /dev/null +++ b/src/functions/backend/db/extension-bundles/unique-copy-name.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "bun:test"; +import uniqueCopyName from "./unique-copy-name"; + +describe("uniqueCopyName", () => { + test("a display name gets the worded marker", () => { + expect(uniqueCopyName({ name: "GitHub", taken: [], style: "words" })).toBe("GitHub (imported)"); + }); + + test("a taken marker counts up", () => { + expect(uniqueCopyName({ name: "GitHub", taken: ["GitHub (imported)"], style: "words" })).toBe( + "GitHub (imported 2)", + ); + }); + + test("a tool name stays snake_case", () => { + expect(uniqueCopyName({ name: "fetch_page", taken: [], style: "snake" })).toBe("fetch_page_imported"); + expect(uniqueCopyName({ name: "fetch_page", taken: ["fetch_page_imported"], style: "snake" })).toBe( + "fetch_page_imported_2", + ); + }); + + test("a slug stays lowercase with hyphens", () => { + expect(uniqueCopyName({ name: "weekly-seo-report", taken: [], style: "dash" })).toBe( + "weekly-seo-report-imported", + ); + }); + + test("a long name is cut to make room, never past the limit", () => { + const copy = uniqueCopyName({ name: "a".repeat(64), taken: [], style: "dash", max_length: 64 }); + + expect(copy.length).toBe(64); + expect(copy.endsWith("-imported")).toBe(true); + }); +}); \ No newline at end of file diff --git a/src/functions/backend/db/extension-bundles/unique-copy-name.ts b/src/functions/backend/db/extension-bundles/unique-copy-name.ts new file mode 100644 index 00000000..912f1d22 --- /dev/null +++ b/src/functions/backend/db/extension-bundles/unique-copy-name.ts @@ -0,0 +1,35 @@ +type Params = { + name: string; + /** + * Every name of this kind already here, so the copy gets one nobody has. + */ + taken: string[]; + /** + * How the marker reads: `Name (imported)`, `name_imported` or + * `name-imported`. + */ + style: "words" | "snake" | "dash"; + /** + * What the name can't pass, e.g. a slug's 64 characters: the base is + * cut to make room for the marker. + */ + max_length?: number; +}; + +/** + * A name for a copy of an imported item, so it can sit beside the row it + * would otherwise replace. + */ +export default function uniqueCopyName({ name, taken, style, max_length = 200 }: Params): string { + for (let n = 1; n < 100; n++) { + const marker = n == 1 ? "" : ` ${n}`; + const suffix = + style == "words" ? ` (imported${marker})` : style == "snake" ? `_imported${n == 1 ? "" : `_${n}`}` : `-imported${n == 1 ? "" : `-${n}`}`; + const base = name.slice(0, Math.max(1, max_length - suffix.length)); + const copy = `${base}${suffix}`; + + if (!taken.includes(copy)) return copy; + } + + return `${name.slice(0, Math.max(1, max_length - 11))}-imported-x`; +} \ No newline at end of file diff --git a/src/pages/admin/settings/(functions)/download-json-bundle.ts b/src/pages/admin/settings/(functions)/download-json-bundle.ts new file mode 100644 index 00000000..d4909fbb --- /dev/null +++ b/src/pages/admin/settings/(functions)/download-json-bundle.ts @@ -0,0 +1,39 @@ +import type { ExtensionBundle, ExtensionBundleKind } from "@/src/types"; + +const KindNames = { + mcp: "mcp-servers", + tool: "tools", + skill: "skills", + knowledgebase: "knowledgebases", +}; + +/** + * How long the object URL is kept, so the browser has read it before it + * is let go: revoking it as the click returns can cancel the save. + */ +const UrlKeepMs = 10_000; + +type Params = { + bundle: ExtensionBundle; + kind: ExtensionBundleKind; +}; + +/** + * Saves a bundle the browser already has as a JSON file, named for the + * page and the day it was exported so two exports don't overwrite each + * other. + */ +export default function downloadJsonBundle({ bundle, kind }: Params) { + const day = new Date().toISOString().slice(0, 10); + const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + + link.href = url; + link.download = `cobble-${KindNames[kind]}-${day}.json`; + link.rel = "noopener"; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), UrlKeepMs); +} \ No newline at end of file diff --git a/src/pages/admin/settings/(functions)/read-bundle-file.ts b/src/pages/admin/settings/(functions)/read-bundle-file.ts new file mode 100644 index 00000000..4fdf0b6f --- /dev/null +++ b/src/pages/admin/settings/(functions)/read-bundle-file.ts @@ -0,0 +1,41 @@ +import { AppData } from "@/src/data/app-data"; +import { ExtensionBundleSchema } from "@/src/schemas/extension-bundle-schema"; +import type { ExtensionBundle } from "@/src/types"; + +type Params = { + file: File; +}; + +type Result = { + bundle?: ExtensionBundle; + problem?: string; +}; + +/** + * A bundle file as the modal reads it: JSON of this format, no bigger than + * a paste of every extension could be, with the shape checked here so a + * preview is never asked to read a file that isn't one. + */ +export default async function readBundleFile({ file }: Params): Promise { + if (file.size > AppData.ExtensionBundleMaxBytes) { + return { problem: `That file is over ${Math.round(AppData.ExtensionBundleMaxBytes / 1_000_000)} MB.` }; + } + + let value: unknown; + + try { + value = JSON.parse(await file.text()); + } catch { + return { problem: "That file isn't JSON." }; + } + + const parsed = ExtensionBundleSchema.safeParse(value); + + if (!parsed.success) { + return { + problem: `That isn't a bundle this app exports: ${parsed.error.issues[0]?.message || "unexpected shape"}.`, + }; + } + + return { bundle: parsed.data as ExtensionBundle }; +} \ No newline at end of file diff --git a/src/pages/admin/settings/(hooks)/use-extension-selection.ts b/src/pages/admin/settings/(hooks)/use-extension-selection.ts new file mode 100644 index 00000000..6679224b --- /dev/null +++ b/src/pages/admin/settings/(hooks)/use-extension-selection.ts @@ -0,0 +1,18 @@ +import { useState } from "react"; + +/** + * Which rows of a settings list a bundle export would take: ids picked with + * the boxes beside each row, all of them, or none. + */ +export default function useExtensionSelection() { + const [selected, setSelected] = useState([]); + + return { + selected, + has: ({ id }: { id: number }) => selected.includes(id), + toggle: ({ id, checked }: { id: number; checked: boolean }) => + setSelected((prev) => (checked ? [...new Set([...prev, id])] : prev.filter((candidate) => candidate != id))), + all: ({ ids }: { ids: number[] }) => setSelected(ids), + clear: () => setSelected([]), + }; +} \ No newline at end of file diff --git a/src/pages/admin/settings/(partials)/extension-bundle-bar.tsx b/src/pages/admin/settings/(partials)/extension-bundle-bar.tsx new file mode 100644 index 00000000..13bb87e4 --- /dev/null +++ b/src/pages/admin/settings/(partials)/extension-bundle-bar.tsx @@ -0,0 +1,116 @@ +import { useState } from "react"; +import Button from "@moduletrace/twui/layout/Button"; +import Row from "@moduletrace/twui/layout/Row"; +import Span from "@moduletrace/twui/layout/Span"; +import { Download } from "lucide-react"; +import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api"; +import type { ExtensionBundle, ExtensionBundleKind } from "@/src/types"; +import downloadJsonBundle from "../(functions)/download-json-bundle"; + +type Props = { + kind: ExtensionBundleKind; + /** + * What the page calls its rows, one and many, e.g. "MCP server" and + * "MCP servers". + */ + one: string; + label: string; + ids: number[]; + selected: number[]; + onSelectAll: () => void; + onClear: () => void; + onExported: (msg: string) => void; + onError: (msg: string) => void; +}; + +/** + * The line above a settings list while its rows can be picked: how many + * are picked, Select all and Clear, and Export, which saves exactly those + * as a JSON file another install can import. + */ +export default function ExtensionBundleBar({ + kind, + one, + label, + ids, + selected, + onSelectAll, + onClear, + onExported, + onError, +}: Props) { + const [busy, setBusy] = useState(false); + /** A row another action deleted is no longer picked, whatever the hook still holds. */ + const picked = selected.filter((id) => ids.includes(id)); + const all = ids.length > 0 && picked.length == ids.length; + + const export_bundle = async () => { + if (busy || !picked.length) return; + + setBusy(true); + const res = await postAdminApi({ + path: "extensions/export-bundle", + body: { kind, ids: picked }, + }); + setBusy(false); + + if (!res.success || !res.singleRes) { + onError(res.msg || "That didn't work."); + return; + } + + downloadJsonBundle({ bundle: res.singleRes, kind }); + onExported(res.msg || "Exported."); + }; + + return ( + + + {picked.length + ? `${picked.length} of ${ids.length} picked` + : `${ids.length} ${ids.length == 1 ? one : label}, none picked`} + + + {all ? null : ( + + )} + {picked.length ? ( + + ) : null} + + + + ); +} \ No newline at end of file diff --git a/src/pages/admin/settings/(partials)/import-bundle-modal.tsx b/src/pages/admin/settings/(partials)/import-bundle-modal.tsx new file mode 100644 index 00000000..41968682 --- /dev/null +++ b/src/pages/admin/settings/(partials)/import-bundle-modal.tsx @@ -0,0 +1,234 @@ +import { useState } from "react"; +import FileUpload from "@moduletrace/twui/form/FileUpload"; +import Button from "@moduletrace/twui/layout/Button"; +import Row from "@moduletrace/twui/layout/Row"; +import Span from "@moduletrace/twui/layout/Span"; +import Stack from "@moduletrace/twui/layout/Stack"; +import { Check, CircleAlert, Upload } from "lucide-react"; +import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell"; +import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api"; +import type { + ExtensionBundle, + ExtensionBundleKind, + ExtensionImportAction, + ExtensionImportApplyPayload, + ExtensionImportOutcome, + ExtensionImportPreview, +} from "@/src/types"; +import readBundleFile from "../(functions)/read-bundle-file"; +import ImportPreviewRow from "./import-preview-row"; +import SettingsStatus from "./settings-status"; + +type Props = { + kind: ExtensionBundleKind; + /** + * What the page calls its rows, e.g. "MCP servers". + */ + label: string; + onImported: (payload: ExtensionImportApplyPayload, msg: string) => void; + onClose: () => void; +}; + +type Status = { error?: boolean; success?: boolean; msg?: string }; + +/** + * Importing a bundle the page's own export made: pick the file, read what + * it holds and what this install already has, choose per item, then write. + * Only this page's kind goes in; the rest is left for its own page. + */ +export default function ImportBundleModal({ kind, label, onImported, onClose }: Props) { + const [bundle, setBundle] = useState(); + const [preview, setPreview] = useState(); + const [actions, setActions] = useState>({}); + const [outcomes, setOutcomes] = useState(); + const [status, setStatus] = useState(); + const [busy, setBusy] = useState(false); + + const read = async ({ file }: { file?: File }) => { + if (!file || busy) return; + + setBusy(true); + setStatus(undefined); + + const read_file = await readBundleFile({ file }); + + if (!read_file.bundle) { + setBusy(false); + setStatus({ error: true, msg: read_file.problem || "That file can't be read." }); + return; + } + + const res = await postAdminApi({ + path: "extensions/preview-import", + body: { bundle: read_file.bundle, kind }, + }); + + setBusy(false); + + if (!res.singleRes) { + setStatus({ error: true, msg: res.msg || "That file can't be read." }); + return; + } + + setBundle(read_file.bundle); + setPreview(res.singleRes); + setActions( + Object.fromEntries( + res.singleRes.items.map((item) => [item.index, item.status == "new" ? "add" : "skip"] as const), + ), + ); + setStatus(res.success ? undefined : { error: false, success: false, msg: res.msg }); + }; + + const apply = async () => { + if (!bundle || !preview || busy) return; + + setBusy(true); + const res = await postAdminApi({ + path: "extensions/apply-import", + body: { + bundle, + kind, + decisions: Object.entries(actions).map(([index, action]) => ({ index: Number(index), action })), + }, + }); + setBusy(false); + + if (!res.success || !res.singleRes) { + setStatus({ error: true, msg: res.msg || "That didn't work." }); + return; + } + + setOutcomes(res.singleRes.outcomes); + onImported(res.singleRes, res.msg || "Imported."); + }; + + const title = outcomes ? "Imported" : preview ? `What would come in from this file` : `Import ${label}`; + + return ( + { + if (!open) onClose(); + }} + title={title} + description={ + outcomes + ? undefined + : preview + ? "Nothing has been written yet. Pick what to do with each item, then import." + : `A JSON file exported from another install's ${label} settings page. It brings settings, never keys or who gets them.` + } + > + + {outcomes ? ( + <> + + {outcomes.map((outcome) => ( + + {outcome.ok ? ( + + ) : ( + + )} + + + {outcome.name} + + {outcome.msg} + + + ))} + + + + ) : preview ? ( + <> + {summary({ preview })} + + {preview.items.map((item) => ( + + setActions((prev) => ({ ...prev, [item.index]: action })) + } + /> + ))} + + + + + + + ) : ( + <> + read({ file: file_data?.file })} + /> + {busy ? ( + + + Reading the file... + + ) : null} + + )} + + + + ); +} + +function summary({ preview }: { preview: ExtensionImportPreview }) { + const parts = [ + preview.counts.new ? `${preview.counts.new} new` : "", + preview.counts.same ? `${preview.counts.same} already here` : "", + preview.counts.conflict ? `${preview.counts.conflict} different here` : "", + preview.counts.invalid ? `${preview.counts.invalid} can't be read` : "", + ].filter(Boolean); + + const others = preview.other_kinds + ? ` The file also holds ${preview.other_kinds} ${preview.other_kinds == 1 ? "item" : "items"} for other pages.` + : ""; + + return `${parts.length ? parts.join(", ") : "Nothing"} in this file.${others}`; +} \ No newline at end of file diff --git a/src/pages/admin/settings/(partials)/import-preview-row.tsx b/src/pages/admin/settings/(partials)/import-preview-row.tsx new file mode 100644 index 00000000..ccfb7acd --- /dev/null +++ b/src/pages/admin/settings/(partials)/import-preview-row.tsx @@ -0,0 +1,88 @@ +import Select from "@moduletrace/twui/form/Select"; +import Span from "@moduletrace/twui/layout/Span"; +import Stack from "@moduletrace/twui/layout/Stack"; +import { BookOpen, Library, Plug, Wrench } from "lucide-react"; +import IconTile from "@/src/components/general/icon-tile"; +import type { ExtensionImportAction, ExtensionImportPreviewItem, ExtensionBundleKind } from "@/src/types"; +import SettingsListRow from "./settings-list-row"; + +type Props = { + item: ExtensionImportPreviewItem; + action: ExtensionImportAction; + onAction: (action: ExtensionImportAction) => void; +}; + +const Icons: Record = { + mcp: Plug, + tool: Wrench, + skill: BookOpen, + knowledgebase: Library, +}; + +const StatusLabels = { + new: "New here", + same: "Already here", + conflict: "Different here", + invalid: "Can't be read", +}; + +/** + * One item of a bundle as the import would treat it: what it is, whether + * this install has it already, what an overwrite would change, and the + * choice of what to do with it. + */ +export default function ImportPreviewRow({ item, action, onAction }: Props) { + const options = [ + { value: "add", title: "Import" }, + { value: "overwrite", title: "Overwrite" }, + { value: "copy", title: "Import a copy" }, + { value: "skip", title: "Skip" }, + ].filter((option) => + item.status == "new" + ? ["add", "skip"].includes(option.value) + : item.copy_only + ? ["copy", "skip"].includes(option.value) + : ["overwrite", "copy", "skip"].includes(option.value), + ); + + const lines = [ + item.differing.length ? `Differs: ${item.differing.join(", ")}` : "", + item.key != item.name ? `Key: ${item.key}` : "", + item.env_keys.length ? `Env keys: ${item.env_keys.join(", ")}` : "", + item.document_count ? `${item.document_count} ${item.document_count == 1 ? "document" : "documents"}` : "", + ...item.warnings, + ].filter(Boolean); + + return ( + + } + title={item.name} + badge={item.status == "same" ? undefined : StatusLabels[item.status]} + subtitle={item.status == "invalid" ? item.problem : undefined} + > + {item.status == "invalid" ? null : ( +