Export and import extensions as one bundle
Each of the four extension settings pages picks rows with a checkbox
and exports them as one JSON file, or imports such a file from another
install beside New. An import is previewed against what is already here
(item by item: new, already here, different, unreadable) and only then
applied, each item skipped, added, overwritten or added as a copy.
Keys never travel: {{env.KEY}} templates are kept while literal header
and env values are left out and named, so the preview can say which
keys to add. Access grants and all_bots stay behind, knowledgebase
documents travel as text, and nothing is connected on import.
The core takes and returns plain data so a chat path can reuse it later.
The rows' actions also move into a three-dot menu, and the list's
checkbox is pinned so a long title can no longer squeeze it.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<ExtensionImportApplyPayload> {
|
||||
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<ExtensionImportOutcome> {
|
||||
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<string, unknown>;
|
||||
|
||||
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<string> {
|
||||
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}` : ""}`;
|
||||
}
|
||||
@@ -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<ExtensionBundle> {
|
||||
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),
|
||||
};
|
||||
}
|
||||
@@ -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<ExtensionBundleEntry[]> {
|
||||
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_KNOWLEDGEBASES>({
|
||||
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<DocumentRow>({
|
||||
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;
|
||||
}
|
||||
@@ -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<ExtensionBundleEntry[]> {
|
||||
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_MCP_SERVERS>({
|
||||
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: [],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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<ExtensionBundleEntry[]> {
|
||||
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_SKILLS>({
|
||||
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: [],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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<ExtensionBundleEntry[]> {
|
||||
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_CUSTOM_TOOLS>({
|
||||
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: [],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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<ExtensionBundleKind, string> = {
|
||||
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<ExistingExtensionItem[]> {
|
||||
const entries = await (kind == "mcp"
|
||||
? exportMcps({ ids: [] })
|
||||
: kind == "tool"
|
||||
? exportTools({ ids: [] })
|
||||
: kind == "skill"
|
||||
? exportSkills({ ids: [] })
|
||||
: exportKnowledgebases({ ids: [] }));
|
||||
|
||||
const access = await BunSQLite.sql<AccessRow>({
|
||||
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<string, unknown>,
|
||||
all_bots: every_bot.has(entry.id),
|
||||
}));
|
||||
|
||||
if (kind != "knowledgebase") return items;
|
||||
|
||||
const rows = await BunSQLite.sql<DocumentRow>({
|
||||
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 })),
|
||||
}));
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>;
|
||||
/**
|
||||
* 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<string, unknown>;
|
||||
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<string, unknown> }): Record<string, unknown> {
|
||||
return sorted(
|
||||
Object.fromEntries(Object.entries(config).filter(([field]) => !IgnoredFields.includes(field))),
|
||||
) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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<string, unknown>)[key])]),
|
||||
);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -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<string[]> {
|
||||
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);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { ExtensionBundleKind } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
kind: ExtensionBundleKind;
|
||||
config: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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<string, unknown> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<ExtensionImportPreview> {
|
||||
const existing = await grabExistingExtensionItems({ kind });
|
||||
const counts: Record<ExtensionImportStatus, number> = { 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<ExtensionImportPreviewItem> {
|
||||
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("|");
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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`;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<Result> {
|
||||
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 };
|
||||
}
|
||||
@@ -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<number[]>([]);
|
||||
|
||||
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([]),
|
||||
};
|
||||
}
|
||||
@@ -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<ExtensionBundle>({
|
||||
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 (
|
||||
<Row className="w-full flex-wrap items-center gap-2! border-0 border-b border-solid border-hairline pb-2">
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{picked.length
|
||||
? `${picked.length} of ${ids.length} picked`
|
||||
: `${ids.length} ${ids.length == 1 ? one : label}, none picked`}
|
||||
</Span>
|
||||
<Row className="ml-auto flex-nowrap items-center gap-1!">
|
||||
{all ? null : (
|
||||
<Button
|
||||
title="Pick all"
|
||||
type="button"
|
||||
color="gray"
|
||||
variant="ghost"
|
||||
size="smaller"
|
||||
disabled={!ids.length || busy}
|
||||
onClick={onSelectAll}
|
||||
>
|
||||
Select all
|
||||
</Button>
|
||||
)}
|
||||
{picked.length ? (
|
||||
<Button
|
||||
title="Pick none"
|
||||
type="button"
|
||||
color="gray"
|
||||
variant="ghost"
|
||||
size="smaller"
|
||||
disabled={busy}
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
title="Export the picked ones"
|
||||
type="button"
|
||||
color="gray"
|
||||
variant="outlined"
|
||||
size="small"
|
||||
beforeIcon={<Download size={14} aria-hidden />}
|
||||
loading={busy}
|
||||
disabled={busy || !picked.length}
|
||||
onClick={export_bundle}
|
||||
>
|
||||
Export
|
||||
</Button>
|
||||
</Row>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -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<ExtensionBundle>();
|
||||
const [preview, setPreview] = useState<ExtensionImportPreview>();
|
||||
const [actions, setActions] = useState<Record<number, ExtensionImportAction>>({});
|
||||
const [outcomes, setOutcomes] = useState<ExtensionImportOutcome[]>();
|
||||
const [status, setStatus] = useState<Status>();
|
||||
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<ExtensionImportPreview>({
|
||||
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<ExtensionImportApplyPayload>({
|
||||
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 (
|
||||
<AddModalShell
|
||||
open
|
||||
setOpen={(open) => {
|
||||
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.`
|
||||
}
|
||||
>
|
||||
<Stack className="w-full gap-3! items-stretch pt-2">
|
||||
{outcomes ? (
|
||||
<>
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
{outcomes.map((outcome) => (
|
||||
<Row key={outcome.index} className="w-full items-start gap-2! flex-nowrap">
|
||||
{outcome.ok ? (
|
||||
<Check size={14} aria-hidden className="shrink-0 mt-0.5 text-ink-secondary" />
|
||||
) : (
|
||||
<CircleAlert size={14} aria-hidden className="shrink-0 mt-0.5 text-ink" />
|
||||
)}
|
||||
<Stack className="grow min-w-0 gap-0!">
|
||||
<Span className="text-[13px] leading-[18px] font-bold text-ink truncate w-full">
|
||||
{outcome.name}
|
||||
</Span>
|
||||
<Span className="text-xs leading-4 text-ink-secondary">{outcome.msg}</Span>
|
||||
</Stack>
|
||||
</Row>
|
||||
))}
|
||||
</Stack>
|
||||
<Button
|
||||
title="Close"
|
||||
type="button"
|
||||
color="gray"
|
||||
variant="outlined"
|
||||
size="small"
|
||||
onClick={onClose}
|
||||
className="self-end"
|
||||
>
|
||||
Close
|
||||
</Button>
|
||||
</>
|
||||
) : preview ? (
|
||||
<>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">{summary({ preview })}</Span>
|
||||
<Stack className="w-full gap-0! items-stretch max-h-[46vh] overflow-y-auto">
|
||||
{preview.items.map((item) => (
|
||||
<ImportPreviewRow
|
||||
key={item.index}
|
||||
item={item}
|
||||
action={actions[item.index] || "skip"}
|
||||
onAction={(action) =>
|
||||
setActions((prev) => ({ ...prev, [item.index]: action }))
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
<Row className="w-full justify-end gap-2! flex-nowrap">
|
||||
<Button
|
||||
title="Pick another file"
|
||||
type="button"
|
||||
color="gray"
|
||||
variant="ghost"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
setPreview(undefined);
|
||||
setBundle(undefined);
|
||||
setStatus(undefined);
|
||||
}}
|
||||
>
|
||||
Pick another file
|
||||
</Button>
|
||||
<Button
|
||||
title="Import what's chosen"
|
||||
type="button"
|
||||
color="primary"
|
||||
variant="normal"
|
||||
size="small"
|
||||
loading={busy}
|
||||
disabled={busy}
|
||||
onClick={apply}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
</Row>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FileUpload
|
||||
label={`A file of ${label} (.json)`}
|
||||
className="h-[160px]"
|
||||
fileInputProps={{ accept: ".json,application/json" }}
|
||||
changeHandler={(file_data) => read({ file: file_data?.file })}
|
||||
/>
|
||||
{busy ? (
|
||||
<Row className="w-full items-center gap-2!">
|
||||
<Upload size={14} aria-hidden className="text-ink-secondary" />
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">Reading the file...</Span>
|
||||
</Row>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
<SettingsStatus status={status} />
|
||||
</Stack>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
|
||||
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}`;
|
||||
}
|
||||
@@ -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<ExtensionBundleKind, typeof Plug> = {
|
||||
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 (
|
||||
<Stack className="w-full gap-1! items-stretch border-0 border-b border-solid border-hairline last:border-b-0 pb-2">
|
||||
<SettingsListRow
|
||||
avatar={<IconTile Icon={Icons[item.kind]} />}
|
||||
title={item.name}
|
||||
badge={item.status == "same" ? undefined : StatusLabels[item.status]}
|
||||
subtitle={item.status == "invalid" ? item.problem : undefined}
|
||||
>
|
||||
{item.status == "invalid" ? null : (
|
||||
<Select
|
||||
label="What to do"
|
||||
showLabel={false}
|
||||
title={`What to do with ${item.name}`}
|
||||
options={options}
|
||||
value={action}
|
||||
changeHandler={(value) => onAction(value as ExtensionImportAction)}
|
||||
wrapperProps={{ className: "w-[9.5rem]" }}
|
||||
input_props={{ className: "h-8! text-xs!" }}
|
||||
/>
|
||||
)}
|
||||
</SettingsListRow>
|
||||
{lines.length ? (
|
||||
<Stack className="gap-0! pl-11 pr-3">
|
||||
{lines.map((line) => (
|
||||
<Span key={line} className="text-xs leading-4 text-ink-secondary">
|
||||
{line}
|
||||
</Span>
|
||||
))}
|
||||
</Stack>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import Link from "@moduletrace/twui/layout/Link";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
|
||||
type Props = {
|
||||
avatar: ReactNode;
|
||||
@@ -25,6 +26,12 @@ type Props = {
|
||||
*/
|
||||
title_icon?: ReactNode;
|
||||
subtitle?: string;
|
||||
/**
|
||||
* Whether it is picked, for a list whose rows can be picked for an
|
||||
* export. Giving `onSelected` is what shows the box.
|
||||
*/
|
||||
selected?: boolean;
|
||||
onSelected?: (checked: boolean) => void;
|
||||
/**
|
||||
* Its actions, at the end of the row.
|
||||
*/
|
||||
@@ -35,7 +42,18 @@ type Props = {
|
||||
* One row of a settings list: an avatar, a title and one line about it,
|
||||
* then what can be done with it.
|
||||
*/
|
||||
export default function SettingsListRow({ avatar, title, href, onOpen, badge, title_icon, subtitle, children }: Props) {
|
||||
export default function SettingsListRow({
|
||||
avatar,
|
||||
title,
|
||||
href,
|
||||
onOpen,
|
||||
badge,
|
||||
title_icon,
|
||||
subtitle,
|
||||
selected,
|
||||
onSelected,
|
||||
children,
|
||||
}: Props) {
|
||||
const title_content = (
|
||||
<Span className="block text-sm font-bold leading-5 text-ink truncate w-full">
|
||||
{title}
|
||||
@@ -46,6 +64,19 @@ export default function SettingsListRow({ avatar, title, href, onOpen, badge, ti
|
||||
|
||||
return (
|
||||
<Row className="w-full min-h-14 gap-3! flex-nowrap items-center px-3 py-2">
|
||||
{onSelected ? (
|
||||
<Checkbox
|
||||
noLabel
|
||||
title={`Pick ${title}`}
|
||||
checked={!!selected}
|
||||
/**
|
||||
* The box's own root may not shrink: the title's
|
||||
* `truncate` would squeeze it into the avatar.
|
||||
*/
|
||||
wrapperWrapperProps={{ className: "shrink-0" }}
|
||||
clickDispatchHandler={(checked) => onSelected(checked)}
|
||||
/>
|
||||
) : null}
|
||||
{avatar}
|
||||
<Stack className="grow min-w-0 gap-0!">
|
||||
{href ? (
|
||||
|
||||
@@ -26,6 +26,11 @@ type Props = {
|
||||
embedding_model: string | null;
|
||||
onChanged: (overview: KnowledgebasesOverviewPayload, msg: string) => void;
|
||||
onError: (msg: string) => void;
|
||||
/**
|
||||
* Whether it is picked for an export.
|
||||
*/
|
||||
selected?: boolean;
|
||||
onSelected?: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -34,7 +39,7 @@ type Props = {
|
||||
* documents, who gets it, and for a super admin editing, retrying the
|
||||
* ones that failed, reading every document again, and deleting it.
|
||||
*/
|
||||
export default function KnowledgebaseRow({ knowledgebase, targets, embedding_model, onChanged, onError }: Props) {
|
||||
export default function KnowledgebaseRow({ selected, onSelected, knowledgebase, targets, embedding_model, onChanged, onError }: Props) {
|
||||
const [open, setOpen] = useState<"documents" | "edit" | "access">();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
@@ -72,6 +77,8 @@ export default function KnowledgebaseRow({ knowledgebase, targets, embedding_mod
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<SettingsListRow
|
||||
selected={selected}
|
||||
onSelected={onSelected}
|
||||
avatar={<IconTile Icon={Library} />}
|
||||
title={knowledgebase.name}
|
||||
badge={knowledgebase.enabled ? undefined : "Off"}
|
||||
|
||||
+62
-16
@@ -1,12 +1,16 @@
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Plus } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { Plus, Upload } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { KnowledgebasesOverviewPayload } from "@/src/types";
|
||||
import type { ExtensionImportApplyPayload, KnowledgebasesOverviewPayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import ExtensionBundleBar from "../../(partials)/extension-bundle-bar";
|
||||
import ImportBundleModal from "../../(partials)/import-bundle-modal";
|
||||
import useExtensionSelection from "../../(hooks)/use-extension-selection";
|
||||
import EmbeddingModelNote from "../(partials)/embedding-model-note";
|
||||
import KnowledgebaseModal from "../(partials)/knowledgebase-modal";
|
||||
import KnowledgebaseRow from "../(partials)/knowledgebase-row";
|
||||
@@ -31,6 +35,8 @@ export default function KnowledgebasesSettingsSection() {
|
||||
* Remounts the rows when the data changes under them.
|
||||
*/
|
||||
const [version, setVersion] = useState(0);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const selection = useExtensionSelection();
|
||||
|
||||
const reading = Boolean(overview?.knowledgebases.some((knowledgebase) => knowledgebase.pending_count));
|
||||
|
||||
@@ -59,6 +65,7 @@ export default function KnowledgebasesSettingsSection() {
|
||||
setVersion((prev) => prev + 1);
|
||||
};
|
||||
const failed = (msg: string) => setStatus({ error: true, msg });
|
||||
const ids = overview.knowledgebases.map((row) => row.id);
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
@@ -75,10 +82,35 @@ export default function KnowledgebasesSettingsSection() {
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : null}
|
||||
{overview.can_edit ? (
|
||||
<ExtensionBundleBar
|
||||
kind="knowledgebase"
|
||||
one="knowledgebase"
|
||||
label="knowledgebases"
|
||||
ids={ids}
|
||||
selected={selection.selected}
|
||||
onSelectAll={() => selection.all({ ids })}
|
||||
onClear={selection.clear}
|
||||
onExported={(msg) => setStatus({ success: true, msg })}
|
||||
onError={failed}
|
||||
/>
|
||||
) : null}
|
||||
{importing ? (
|
||||
<ImportBundleModal
|
||||
kind="knowledgebase"
|
||||
label="knowledgebases"
|
||||
onImported={(payload: ExtensionImportApplyPayload, msg) => {
|
||||
if (payload.kind === "knowledgebase") changed(payload.overview, msg);
|
||||
}}
|
||||
onClose={() => setImporting(false)}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsList is_empty={!overview.knowledgebases.length} empty="No knowledgebases yet.">
|
||||
{overview.knowledgebases.map((knowledgebase) => (
|
||||
<KnowledgebaseRow
|
||||
key={`${knowledgebase.id}-${version}`}
|
||||
selected={overview.can_edit ? selection.has({ id: knowledgebase.id }) : undefined}
|
||||
onSelected={overview.can_edit ? (checked) => selection.toggle({ id: knowledgebase.id, checked }) : undefined}
|
||||
knowledgebase={knowledgebase}
|
||||
targets={overview}
|
||||
embedding_model={overview.embedding_model}
|
||||
@@ -87,21 +119,35 @@ export default function KnowledgebasesSettingsSection() {
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{overview.can_edit && !adding ? (
|
||||
<Button
|
||||
title="Add a knowledgebase"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="self-start gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New knowledgebase
|
||||
</Button>
|
||||
{overview.can_edit && !adding && !importing ? (
|
||||
<Row className="flex-wrap items-center gap-2! self-start">
|
||||
<Button
|
||||
title="Add a knowledgebase"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New knowledgebase
|
||||
</Button>
|
||||
<Button
|
||||
title="Import knowledgebases from a file"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setImporting(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Upload size={14} aria-hidden />
|
||||
Import
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Plug } from "lucide-react";
|
||||
import { Pencil, Plug, RefreshCw, Trash2, Users } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import { McpTransports } from "@/src/dict/mcp-dict";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
@@ -8,7 +8,9 @@ import type { ExtensionTargets, McpServersOverviewPayload, PublicMcpServer } fro
|
||||
import ExtensionStatusLine from "../../(partials)/extension-status-line";
|
||||
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import checkedAgo from "../../(utils)/checked-ago";
|
||||
import extensionAccessLabel from "../../(utils)/extension-access-label";
|
||||
import updatedAgo from "../../(utils)/updated-ago";
|
||||
@@ -19,14 +21,20 @@ type Props = {
|
||||
targets: ExtensionTargets;
|
||||
onChanged: (overview: McpServersOverviewPayload, msg: string) => void;
|
||||
onError: (msg: string) => void;
|
||||
/**
|
||||
* Whether it is picked for an export.
|
||||
*/
|
||||
selected?: boolean;
|
||||
onSelected?: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One MCP server: how it's reached and who gets it, and under it whether
|
||||
* it connected (when it was last checked, and why it failed). Edit and
|
||||
* Access open in a modal.
|
||||
* it connected (when it was last checked, and why it failed). Its actions
|
||||
* live in the three-dot menu: edit, who gets it, refreshing its tools and
|
||||
* deleting it.
|
||||
*/
|
||||
export default function McpServerRow({ server, targets, onChanged, onError }: Props) {
|
||||
export default function McpServerRow({ selected, onSelected, server, targets, onChanged, onError }: Props) {
|
||||
const [open, setOpen] = useState<"edit" | "access">();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
@@ -58,6 +66,8 @@ export default function McpServerRow({ server, targets, onChanged, onError }: Pr
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<SettingsListRow
|
||||
selected={selected}
|
||||
onSelected={onSelected}
|
||||
avatar={<IconTile Icon={Plug} />}
|
||||
title={server.name}
|
||||
badge={server.enabled ? undefined : "Off"}
|
||||
@@ -69,42 +79,38 @@ export default function McpServerRow({ server, targets, onChanged, onError }: Pr
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction
|
||||
title={`Edit ${server.name}`}
|
||||
label="Edit"
|
||||
disabled={busy}
|
||||
onClick={() => setOpen(open == "edit" ? undefined : "edit")}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowAction
|
||||
title={`Choose who gets ${server.name}`}
|
||||
label="Access"
|
||||
disabled={busy}
|
||||
onClick={() => setOpen(open == "access" ? undefined : "access")}
|
||||
/>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction
|
||||
title={`List ${server.name}'s tools again`}
|
||||
label={busy ? "Connecting…" : "Refresh"}
|
||||
disabled={busy || !server.enabled}
|
||||
onClick={() => post({ path: "mcps/sync-mcp", body: { mcp_server_id: server.id } })}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction
|
||||
title={`Delete ${server.name}`}
|
||||
label="Delete"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "mcps/delete-mcp",
|
||||
body: { mcp_server_id: server.id },
|
||||
confirm: `Delete ${server.name}? Bots lose its tools at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowMenu title={`${server.name} menu`} disabled={busy}>
|
||||
<SettingsRowMenuPanel>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={RefreshCw}
|
||||
title="Refresh"
|
||||
description="List its tools again."
|
||||
disabled={!server.enabled}
|
||||
loading={busy}
|
||||
onClick={() => post({ path: "mcps/sync-mcp", body: { mcp_server_id: server.id } })}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Delete"
|
||||
description="Delete it. Bots lose its tools at once."
|
||||
onClick={() =>
|
||||
post({
|
||||
path: "mcps/delete-mcp",
|
||||
body: { mcp_server_id: server.id },
|
||||
confirm: `Delete ${server.name}? Bots lose its tools at once.`,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
<ExtensionStatusLine state={server.status} {...status} />
|
||||
{open == "edit" ? (
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Plus } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { Plus, Upload } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { McpServersOverviewPayload } from "@/src/types";
|
||||
import type { McpServersOverviewPayload, ExtensionImportApplyPayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import ExtensionBundleBar from "../../(partials)/extension-bundle-bar";
|
||||
import ImportBundleModal from "../../(partials)/import-bundle-modal";
|
||||
import useExtensionSelection from "../../(hooks)/use-extension-selection";
|
||||
import McpServerModal from "../(partials)/mcp-server-modal";
|
||||
import McpServerRow from "../(partials)/mcp-server-row";
|
||||
|
||||
@@ -24,6 +28,8 @@ export default function McpsSettingsSection() {
|
||||
* Remounts the rows when the data changes under them.
|
||||
*/
|
||||
const [version, setVersion] = useState(0);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const selection = useExtensionSelection();
|
||||
|
||||
if (!overview) return null;
|
||||
|
||||
@@ -33,6 +39,7 @@ export default function McpsSettingsSection() {
|
||||
setVersion((prev) => prev + 1);
|
||||
};
|
||||
const failed = (msg: string) => setStatus({ error: true, msg });
|
||||
const ids = overview.servers.map((row) => row.id);
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
@@ -48,10 +55,35 @@ export default function McpsSettingsSection() {
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : null}
|
||||
{overview.can_edit ? (
|
||||
<ExtensionBundleBar
|
||||
kind="mcp"
|
||||
one="MCP server"
|
||||
label="MCP servers"
|
||||
ids={ids}
|
||||
selected={selection.selected}
|
||||
onSelectAll={() => selection.all({ ids })}
|
||||
onClear={selection.clear}
|
||||
onExported={(msg) => setStatus({ success: true, msg })}
|
||||
onError={failed}
|
||||
/>
|
||||
) : null}
|
||||
{importing ? (
|
||||
<ImportBundleModal
|
||||
kind="mcp"
|
||||
label="MCP servers"
|
||||
onImported={(payload: ExtensionImportApplyPayload, msg) => {
|
||||
if (payload.kind === "mcp") changed(payload.overview, msg);
|
||||
}}
|
||||
onClose={() => setImporting(false)}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsList is_empty={!overview.servers.length} empty="No MCP servers yet.">
|
||||
{overview.servers.map((server) => (
|
||||
<McpServerRow
|
||||
key={`${server.id}-${version}`}
|
||||
selected={overview.can_edit ? selection.has({ id: server.id }) : undefined}
|
||||
onSelected={overview.can_edit ? (checked) => selection.toggle({ id: server.id, checked }) : undefined}
|
||||
server={server}
|
||||
targets={overview}
|
||||
onChanged={changed}
|
||||
@@ -59,19 +91,33 @@ export default function McpsSettingsSection() {
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{overview.can_edit && !adding ? (
|
||||
<Button
|
||||
title="Add an MCP server"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="self-start gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New MCP server
|
||||
</Button>
|
||||
{overview.can_edit && !adding && !importing ? (
|
||||
<Row className="flex-wrap items-center gap-2! self-start">
|
||||
<Button
|
||||
title="Add an MCP server"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New MCP server
|
||||
</Button>
|
||||
<Button
|
||||
title="Import MCP servers from a file"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setImporting(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Upload size={14} aria-hidden />
|
||||
Import
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</SettingsGroup>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { BookOpen } from "lucide-react";
|
||||
import { BookOpen, Pencil, Trash2, Users } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import type { ExtensionTargets, PublicSkill, SkillLimitsOverview, SkillsOverviewPayload } from "@/src/types";
|
||||
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import extensionAccessLabel from "../../(utils)/extension-access-label";
|
||||
import updatedAgo from "../../(utils)/updated-ago";
|
||||
import SkillModal from "./skill-modal";
|
||||
@@ -17,13 +19,18 @@ type Props = {
|
||||
limits: SkillLimitsOverview;
|
||||
onChanged: (overview: SkillsOverviewPayload, msg: string) => void;
|
||||
onError: (msg: string) => void;
|
||||
/**
|
||||
* Whether it is picked for an export.
|
||||
*/
|
||||
selected?: boolean;
|
||||
onSelected?: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One skill: its slug and when it applies, and who gets it. Edit and Access
|
||||
* open in a modal.
|
||||
* One skill: its slug and when it applies, and who gets it. Its actions
|
||||
* live in the three-dot menu: edit, who gets it and deleting it.
|
||||
*/
|
||||
export default function SkillRow({ skill, targets, limits, onChanged, onError }: Props) {
|
||||
export default function SkillRow({ selected, onSelected, skill, targets, limits, onChanged, onError }: Props) {
|
||||
const [open, setOpen] = useState<"edit" | "access">();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
@@ -49,6 +56,8 @@ export default function SkillRow({ skill, targets, limits, onChanged, onError }:
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<SettingsListRow
|
||||
selected={selected}
|
||||
onSelected={onSelected}
|
||||
avatar={<IconTile Icon={BookOpen} />}
|
||||
title={skill.name}
|
||||
badge={skill.enabled ? undefined : "Off"}
|
||||
@@ -61,23 +70,22 @@ export default function SkillRow({ skill, targets, limits, onChanged, onError }:
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction
|
||||
title={`Edit ${skill.name}`}
|
||||
label="Edit"
|
||||
disabled={busy}
|
||||
onClick={() => setOpen(open == "edit" ? undefined : "edit")}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsRowAction
|
||||
title={`Choose who gets ${skill.name}`}
|
||||
label="Access"
|
||||
disabled={busy}
|
||||
onClick={() => setOpen(open == "access" ? undefined : "access")}
|
||||
/>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction title={`Delete ${skill.name}`} label="Delete" disabled={busy} onClick={remove} />
|
||||
) : null}
|
||||
<SettingsRowMenu title={`${skill.name} menu`} disabled={busy}>
|
||||
<SettingsRowMenuPanel>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Delete"
|
||||
description="Delete it. Bots lose it at once."
|
||||
onClick={remove}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
{open == "edit" ? (
|
||||
<SkillModal skill={skill} limits={limits} onSaved={saved} onCancel={() => setOpen(undefined)} />
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Plus } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { Plus, Upload } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { SkillsOverviewPayload } from "@/src/types";
|
||||
import type { ExtensionImportApplyPayload, SkillsOverviewPayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import ExtensionBundleBar from "../../(partials)/extension-bundle-bar";
|
||||
import ImportBundleModal from "../../(partials)/import-bundle-modal";
|
||||
import useExtensionSelection from "../../(hooks)/use-extension-selection";
|
||||
import SkillModal from "../(partials)/skill-modal";
|
||||
import SkillRow from "../(partials)/skill-row";
|
||||
|
||||
@@ -24,6 +28,8 @@ export default function SkillsSettingsSection() {
|
||||
* Remounts the rows when the data changes under them.
|
||||
*/
|
||||
const [version, setVersion] = useState(0);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const selection = useExtensionSelection();
|
||||
|
||||
if (!overview) return null;
|
||||
|
||||
@@ -33,6 +39,7 @@ export default function SkillsSettingsSection() {
|
||||
setVersion((prev) => prev + 1);
|
||||
};
|
||||
const failed = (msg: string) => setStatus({ error: true, msg });
|
||||
const ids = overview.skills.map((row) => row.id);
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
@@ -49,10 +56,35 @@ export default function SkillsSettingsSection() {
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : null}
|
||||
{overview.can_edit ? (
|
||||
<ExtensionBundleBar
|
||||
kind="skill"
|
||||
one="skill"
|
||||
label="skills"
|
||||
ids={ids}
|
||||
selected={selection.selected}
|
||||
onSelectAll={() => selection.all({ ids })}
|
||||
onClear={selection.clear}
|
||||
onExported={(msg) => setStatus({ success: true, msg })}
|
||||
onError={failed}
|
||||
/>
|
||||
) : null}
|
||||
{importing ? (
|
||||
<ImportBundleModal
|
||||
kind="skill"
|
||||
label="skills"
|
||||
onImported={(payload: ExtensionImportApplyPayload, msg) => {
|
||||
if (payload.kind === "skill") changed(payload.overview, msg);
|
||||
}}
|
||||
onClose={() => setImporting(false)}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsList is_empty={!overview.skills.length} empty="No skills yet.">
|
||||
{overview.skills.map((skill) => (
|
||||
<SkillRow
|
||||
key={`${skill.id}-${version}`}
|
||||
selected={overview.can_edit ? selection.has({ id: skill.id }) : undefined}
|
||||
onSelected={overview.can_edit ? (checked) => selection.toggle({ id: skill.id, checked }) : undefined}
|
||||
skill={skill}
|
||||
targets={overview}
|
||||
limits={overview.limits}
|
||||
@@ -61,21 +93,35 @@ export default function SkillsSettingsSection() {
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{overview.can_edit && !adding ? (
|
||||
<Button
|
||||
title="Add a skill"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="self-start gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New skill
|
||||
</Button>
|
||||
{overview.can_edit && !adding && !importing ? (
|
||||
<Row className="flex-wrap items-center gap-2! self-start">
|
||||
<Button
|
||||
title="Add a skill"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New skill
|
||||
</Button>
|
||||
<Button
|
||||
title="Import skills from a file"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setImporting(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Upload size={14} aria-hidden />
|
||||
Import
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { Wrench } from "lucide-react";
|
||||
import { Pencil, Play, Trash2, Users, Wrench } from "lucide-react";
|
||||
import IconTile from "@/src/components/general/icon-tile";
|
||||
import { CustomToolKinds } from "@/src/dict/custom-tool-dict";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
@@ -8,7 +8,9 @@ import type { CustomToolsOverviewPayload, ExtensionTargets, PublicCustomTool } f
|
||||
import ExtensionStatusLine from "../../(partials)/extension-status-line";
|
||||
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
|
||||
import SettingsListRow from "../../(partials)/settings-list-row";
|
||||
import SettingsRowAction from "../../(partials)/settings-row-action";
|
||||
import SettingsRowMenu from "../../(partials)/settings-row-menu";
|
||||
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
|
||||
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
|
||||
import checkedAgo from "../../(utils)/checked-ago";
|
||||
import extensionAccessLabel from "../../(utils)/extension-access-label";
|
||||
import updatedAgo from "../../(utils)/updated-ago";
|
||||
@@ -24,19 +26,22 @@ type Props = {
|
||||
*/
|
||||
onRefreshed: (overview: CustomToolsOverviewPayload) => void;
|
||||
onError: (msg: string) => void;
|
||||
/**
|
||||
* Whether it is picked for an export.
|
||||
*/
|
||||
selected?: boolean;
|
||||
onSelected?: (checked: boolean) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One custom tool: its name, kind and who gets it, and under it how its
|
||||
* last run went (a bot's call or a try). Edit, Access and Try open in a
|
||||
* modal.
|
||||
* last run went (a bot's call or a try). Its actions live in the three-dot
|
||||
* menu: edit, who gets it, trying it and deleting it.
|
||||
*/
|
||||
export default function CustomToolRow({ tool, targets, onChanged, onRefreshed, onError }: Props) {
|
||||
export default function CustomToolRow({ selected, onSelected, tool, targets, onChanged, onRefreshed, onError }: Props) {
|
||||
const [open, setOpen] = useState<"edit" | "access" | "try">();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const toggle = (panel: "edit" | "access" | "try") => setOpen(open == panel ? undefined : panel);
|
||||
|
||||
const saved = (overview: CustomToolsOverviewPayload, msg: string) => {
|
||||
setOpen(undefined);
|
||||
onChanged(overview, msg);
|
||||
@@ -67,6 +72,8 @@ export default function CustomToolRow({ tool, targets, onChanged, onRefreshed, o
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch border-0 border-b border-solid border-hairline last:border-b-0">
|
||||
<SettingsListRow
|
||||
selected={selected}
|
||||
onSelected={onSelected}
|
||||
avatar={<IconTile Icon={Wrench} />}
|
||||
title={tool.name}
|
||||
badge={tool.enabled ? undefined : "Off"}
|
||||
@@ -79,21 +86,30 @@ export default function CustomToolRow({ tool, targets, onChanged, onRefreshed, o
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction title={`Edit ${tool.name}`} label="Edit" disabled={busy} onClick={() => toggle("edit")} />
|
||||
) : null}
|
||||
<SettingsRowAction
|
||||
title={`Choose who gets ${tool.name}`}
|
||||
label="Access"
|
||||
disabled={busy}
|
||||
onClick={() => toggle("access")}
|
||||
/>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction title={`Try ${tool.name}`} label="Try" disabled={busy} onClick={() => toggle("try")} />
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowAction title={`Delete ${tool.name}`} label="Delete" disabled={busy} onClick={remove} />
|
||||
) : null}
|
||||
<SettingsRowMenu title={`${tool.name} menu`} disabled={busy}>
|
||||
<SettingsRowMenuPanel>
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
|
||||
) : null}
|
||||
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Play}
|
||||
title="Try"
|
||||
description="Run it once to check it works."
|
||||
onClick={() => setOpen("try")}
|
||||
/>
|
||||
) : null}
|
||||
{targets.can_edit ? (
|
||||
<SettingsRowMenuItem
|
||||
icon={Trash2}
|
||||
title="Delete"
|
||||
description="Delete it. Bots lose it at once."
|
||||
onClick={remove}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsRowMenuPanel>
|
||||
</SettingsRowMenu>
|
||||
</SettingsListRow>
|
||||
<ExtensionStatusLine state={tool.status} {...status} />
|
||||
{open == "edit" ? (
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useContext, useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { Plus } from "lucide-react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import { Plus, Upload } from "lucide-react";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import type { CustomToolsOverviewPayload } from "@/src/types";
|
||||
import type { CustomToolsOverviewPayload, ExtensionImportApplyPayload } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import SettingsList from "../../(partials)/settings-list";
|
||||
import SettingsStatus from "../../(partials)/settings-status";
|
||||
import ExtensionBundleBar from "../../(partials)/extension-bundle-bar";
|
||||
import ImportBundleModal from "../../(partials)/import-bundle-modal";
|
||||
import useExtensionSelection from "../../(hooks)/use-extension-selection";
|
||||
import CustomToolModal from "../(partials)/custom-tool-modal";
|
||||
import CustomToolRow from "../(partials)/custom-tool-row";
|
||||
|
||||
@@ -24,6 +28,8 @@ export default function ToolsSettingsSection() {
|
||||
* Remounts the rows when the data changes under them.
|
||||
*/
|
||||
const [version, setVersion] = useState(0);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const selection = useExtensionSelection();
|
||||
|
||||
if (!overview) return null;
|
||||
|
||||
@@ -33,6 +39,7 @@ export default function ToolsSettingsSection() {
|
||||
setVersion((prev) => prev + 1);
|
||||
};
|
||||
const failed = (msg: string) => setStatus({ error: true, msg });
|
||||
const ids = overview.tools.map((row) => row.id);
|
||||
|
||||
return (
|
||||
<SettingsGroup
|
||||
@@ -48,10 +55,35 @@ export default function ToolsSettingsSection() {
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : null}
|
||||
{overview.can_edit ? (
|
||||
<ExtensionBundleBar
|
||||
kind="tool"
|
||||
one="tool"
|
||||
label="tools"
|
||||
ids={ids}
|
||||
selected={selection.selected}
|
||||
onSelectAll={() => selection.all({ ids })}
|
||||
onClear={selection.clear}
|
||||
onExported={(msg) => setStatus({ success: true, msg })}
|
||||
onError={failed}
|
||||
/>
|
||||
) : null}
|
||||
{importing ? (
|
||||
<ImportBundleModal
|
||||
kind="tool"
|
||||
label="tools"
|
||||
onImported={(payload: ExtensionImportApplyPayload, msg) => {
|
||||
if (payload.kind === "tool") changed(payload.overview, msg);
|
||||
}}
|
||||
onClose={() => setImporting(false)}
|
||||
/>
|
||||
) : null}
|
||||
<SettingsList is_empty={!overview.tools.length} empty="No tools yet.">
|
||||
{overview.tools.map((tool) => (
|
||||
<CustomToolRow
|
||||
key={`${tool.id}-${version}`}
|
||||
selected={overview.can_edit ? selection.has({ id: tool.id }) : undefined}
|
||||
onSelected={overview.can_edit ? (checked) => selection.toggle({ id: tool.id, checked }) : undefined}
|
||||
tool={tool}
|
||||
targets={overview}
|
||||
onChanged={changed}
|
||||
@@ -60,21 +92,35 @@ export default function ToolsSettingsSection() {
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{overview.can_edit && !adding ? (
|
||||
<Button
|
||||
title="Add a tool"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="self-start gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New tool
|
||||
</Button>
|
||||
{overview.can_edit && !adding && !importing ? (
|
||||
<Row className="flex-wrap items-center gap-2! self-start">
|
||||
<Button
|
||||
title="Add a tool"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setAdding(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Plus size={14} aria-hidden />
|
||||
New tool
|
||||
</Button>
|
||||
<Button
|
||||
title="Import tools from a file"
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setImporting(true)}
|
||||
className="gap-1!"
|
||||
>
|
||||
<Upload size={14} aria-hidden />
|
||||
Import
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import applyExtensionImport from "@/src/functions/backend/db/extension-bundles/apply-extension-import";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { ApplyExtensionImportRequestSchema } from "@/src/schemas/extension-bundle-schema";
|
||||
import type { ExtensionImportApplyPayload } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler, BunextServerRouteConfig } from "@moduletrace/bunext/types";
|
||||
|
||||
export const config: BunextServerRouteConfig = {
|
||||
max_request_body_mb: 200,
|
||||
};
|
||||
|
||||
/**
|
||||
* Super admin only: writes a bundle's items of one kind, as the preview
|
||||
* showed, and answers with what each did and the page's list again.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<ExtensionImportApplyPayload>> = async ({
|
||||
req,
|
||||
body,
|
||||
}) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
throw new AppError(`Only a super admin can do that.`);
|
||||
}
|
||||
|
||||
const data = parseWithSchema({ schema: ApplyExtensionImportRequestSchema, data: body });
|
||||
const payload = await applyExtensionImport({
|
||||
bundle: data.bundle,
|
||||
kind: data.kind,
|
||||
decisions: data.decisions,
|
||||
user_id: user.id,
|
||||
});
|
||||
|
||||
const added = payload.outcomes.filter((outcome) => outcome.ok && outcome.action != "skip").length;
|
||||
const failed = payload.outcomes.filter((outcome) => !outcome.ok).length;
|
||||
|
||||
await logEvent({
|
||||
title: "Extensions imported",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} imported ${added} ${data.kind} item${added == 1 ? "" : "s"}${
|
||||
failed ? `, ${failed} of them failing` : ""
|
||||
}.`,
|
||||
metadata: { kind: data.kind, added, failed },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: failed
|
||||
? `${added} imported, ${failed} not.`
|
||||
: `${added} ${added == 1 ? "item" : "items"} imported.`,
|
||||
singleRes: payload,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import exportExtensions from "@/src/functions/backend/db/extension-bundles/export-extensions";
|
||||
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
|
||||
import { ExportExtensionBundleRequestSchema } from "@/src/schemas/extension-bundle-schema";
|
||||
import type { ExtensionBundle } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
const Labels = {
|
||||
mcp: ["MCP server", "MCP servers"],
|
||||
tool: ["tool", "tools"],
|
||||
skill: ["skill", "skills"],
|
||||
knowledgebase: ["knowledgebase", "knowledgebases"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Super admin only: one page's extensions (the ones picked, or all of them)
|
||||
* as a JSON bundle another install can import. Never a key: a server's own
|
||||
* header and env values stay behind and the bundle says which.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<ExtensionBundle>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
throw new AppError(`Only a super admin can do that.`);
|
||||
}
|
||||
|
||||
const data = parseWithSchema({ schema: ExportExtensionBundleRequestSchema, data: body });
|
||||
const bundle = await exportExtensions({ kind: data.kind, ids: data.ids });
|
||||
const [one, many] = Labels[data.kind];
|
||||
const redacted = bundle.items.reduce((total, item) => total + item.redacted.length, 0);
|
||||
|
||||
await logEvent({
|
||||
title: "Extensions exported",
|
||||
category: "system",
|
||||
user_id: user.id,
|
||||
plain_text: `User #${user.id} exported ${bundle.items.length} ${bundle.items.length == 1 ? one : many}${
|
||||
redacted ? `, leaving ${redacted} ${redacted == 1 ? "value" : "values"} behind` : ""
|
||||
}.`,
|
||||
metadata: { kind: data.kind, items: bundle.items.length, redacted },
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: `${bundle.items.length} ${bundle.items.length == 1 ? one : many} exported.`,
|
||||
singleRes: bundle,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
|
||||
import previewExtensionImport from "@/src/functions/backend/db/extension-bundles/preview-extension-import";
|
||||
import { PreviewExtensionImportRequestSchema } from "@/src/schemas/extension-bundle-schema";
|
||||
import type { ExtensionImportPreview } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler, BunextServerRouteConfig } from "@moduletrace/bunext/types";
|
||||
|
||||
export const config: BunextServerRouteConfig = {
|
||||
max_request_body_mb: 200,
|
||||
};
|
||||
|
||||
/**
|
||||
* Super admin only: what importing a bundle's items of one kind would do,
|
||||
* item by item. Reads only.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<ExtensionImportPreview>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const user = await grabSuperAdminUser({ req });
|
||||
|
||||
if (!user?.id) {
|
||||
throw new AppError(`Only a super admin can do that.`);
|
||||
}
|
||||
|
||||
const data = parseWithSchema({ schema: PreviewExtensionImportRequestSchema, data: body });
|
||||
const preview = await previewExtensionImport({ bundle: data.bundle, kind: data.kind });
|
||||
|
||||
return {
|
||||
success: preview.items.length > 0,
|
||||
msg: preview.items.length
|
||||
? ""
|
||||
: preview.other_kinds
|
||||
? `This file holds none of these; its ${preview.other_kinds} items belong to other pages.`
|
||||
: `This file holds nothing to import.`,
|
||||
singleRes: preview,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* The kinds one bundle holds, in the order a file lists them.
|
||||
*/
|
||||
export const ExtensionBundleKinds = ["mcp", "tool", "skill", "knowledgebase"] as const;
|
||||
|
||||
/**
|
||||
* A knowledgebase document as a bundle carries it: what it says, never its
|
||||
* bytes. A bot reads only text, and the passages a text is cut into belong
|
||||
* to the install that embedded them, so an import reads them again.
|
||||
*/
|
||||
export const ExtensionBundleDocumentSchema = z.object({
|
||||
name: z.string().trim().min(1).max(200),
|
||||
mime_type: z.string().trim().max(200).default("text/markdown"),
|
||||
text: z.string().max(AppData.KnowledgebaseTextMaxChars),
|
||||
});
|
||||
|
||||
/**
|
||||
* One MCP server, tool, skill or knowledgebase: its natural key (what two
|
||||
* installs call the same thing), the configuration a save takes, what the
|
||||
* export left behind, and a knowledgebase's documents.
|
||||
*/
|
||||
export const ExtensionBundleItemSchema = z.object({
|
||||
kind: z.enum(ExtensionBundleKinds),
|
||||
key: z.string().trim().min(1).max(200),
|
||||
config: z.record(z.string(), z.unknown()),
|
||||
/**
|
||||
* Values the export left behind, named, e.g. "header Authorization".
|
||||
*/
|
||||
redacted: z.array(z.string().max(200)).max(500).default([]),
|
||||
/**
|
||||
* The keys a run needs (`{{env.KEY}}`), for the import to check.
|
||||
*/
|
||||
env_keys: z.array(z.string().max(200)).max(500).default([]),
|
||||
/**
|
||||
* What the export had to leave out or cut, said in the preview.
|
||||
*/
|
||||
notes: z.array(z.string().max(300)).max(20).default([]),
|
||||
documents: z.array(ExtensionBundleDocumentSchema).max(AppData.ExtensionBundleMaxDocuments).default([]),
|
||||
});
|
||||
|
||||
/**
|
||||
* A file of extensions taken from one install for another: what it is, the
|
||||
* version of the format, and the items themselves.
|
||||
*/
|
||||
export const ExtensionBundleSchema = z.object({
|
||||
format: z.literal("cobble-extensions"),
|
||||
version: z.literal(1),
|
||||
exported_at: z.number().int().nonnegative().default(0),
|
||||
app_version: z.string().trim().max(40).default(""),
|
||||
items: z.array(ExtensionBundleItemSchema).max(AppData.ExtensionBundleMaxItems),
|
||||
});
|
||||
|
||||
/**
|
||||
* Sending a bundle to be compared with what the install has.
|
||||
*/
|
||||
export const PreviewExtensionImportRequestSchema = z.object({
|
||||
bundle: ExtensionBundleSchema,
|
||||
/**
|
||||
* The page it's imported from: only its own kind is previewed.
|
||||
*/
|
||||
kind: z.enum(ExtensionBundleKinds),
|
||||
});
|
||||
|
||||
/**
|
||||
* Importing it: the bundle, and what to do with each item.
|
||||
*/
|
||||
export const ApplyExtensionImportRequestSchema = PreviewExtensionImportRequestSchema.extend({
|
||||
decisions: z
|
||||
.array(
|
||||
z.object({
|
||||
index: z.number().int().nonnegative(),
|
||||
action: z.enum(["skip", "add", "overwrite", "copy"]),
|
||||
}),
|
||||
)
|
||||
.max(AppData.ExtensionBundleMaxItems)
|
||||
.default([]),
|
||||
});
|
||||
|
||||
/**
|
||||
* Exporting from one page: the kind, and the rows picked (all when empty).
|
||||
*/
|
||||
export const ExportExtensionBundleRequestSchema = z.object({
|
||||
kind: z.enum(ExtensionBundleKinds),
|
||||
ids: z.array(z.coerce.number().int().positive()).max(AppData.ExtensionBundleMaxItems).default([]),
|
||||
});
|
||||
|
||||
export type ExtensionBundleRequest = z.infer<typeof ExtensionBundleSchema>;
|
||||
export type PreviewExtensionImportRequest = z.infer<typeof PreviewExtensionImportRequestSchema>;
|
||||
export type ApplyExtensionImportRequest = z.infer<typeof ApplyExtensionImportRequestSchema>;
|
||||
export type ExportExtensionBundleRequest = z.infer<typeof ExportExtensionBundleRequestSchema>;
|
||||
@@ -1782,6 +1782,130 @@ export type CustomToolsOverviewPayload = ExtensionTargets & {
|
||||
tools: PublicCustomTool[];
|
||||
};
|
||||
|
||||
/**
|
||||
* An extension bundle: what one install exports for another (Settings >
|
||||
* MCP servers, Tools, Skills, Knowledgebases). Its `config` is the shape a
|
||||
* save already takes, so nothing is written that the forms couldn't.
|
||||
*/
|
||||
export type ExtensionBundleKind = "mcp" | "tool" | "skill" | "knowledgebase";
|
||||
|
||||
export type ExtensionBundleDocument = {
|
||||
name: string;
|
||||
mime_type: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type ExtensionBundleItem = {
|
||||
kind: ExtensionBundleKind;
|
||||
/**
|
||||
* What two installs call the same thing: an MCP server's slug, a tool's
|
||||
* or a knowledgebase's name, a skill's slug.
|
||||
*/
|
||||
key: string;
|
||||
config: Record<string, unknown>;
|
||||
/**
|
||||
* Values the export left behind, named: a server's own keys.
|
||||
*/
|
||||
redacted: string[];
|
||||
/**
|
||||
* The env keys the item's templates ask for.
|
||||
*/
|
||||
env_keys: string[];
|
||||
/**
|
||||
* What the export had to leave out or cut.
|
||||
*/
|
||||
notes: string[];
|
||||
documents: ExtensionBundleDocument[];
|
||||
};
|
||||
|
||||
export type ExtensionBundle = {
|
||||
format: "cobble-extensions";
|
||||
version: 1;
|
||||
exported_at: number;
|
||||
app_version: string;
|
||||
items: ExtensionBundleItem[];
|
||||
};
|
||||
|
||||
/**
|
||||
* What an imported item is, against what the install already has: the same
|
||||
* thing and the same settings, the same thing changed, nothing like it, or
|
||||
* a file that can't be read.
|
||||
*/
|
||||
export type ExtensionImportStatus = "new" | "same" | "conflict" | "invalid";
|
||||
|
||||
export type ExtensionImportPreviewItem = {
|
||||
/**
|
||||
* Where it sits in the bundle, which is how it's picked again when the
|
||||
* import is confirmed.
|
||||
*/
|
||||
index: number;
|
||||
kind: ExtensionBundleKind;
|
||||
key: string;
|
||||
name: string;
|
||||
status: ExtensionImportStatus;
|
||||
/**
|
||||
* The row with this key, when there is one.
|
||||
*/
|
||||
existing_id: number | null;
|
||||
/**
|
||||
* For a conflict: the settings that differ.
|
||||
*/
|
||||
differing: string[];
|
||||
/**
|
||||
* For one that can't be imported: why.
|
||||
*/
|
||||
problem: string;
|
||||
warnings: string[];
|
||||
redacted: string[];
|
||||
env_keys: string[];
|
||||
document_count: number;
|
||||
/**
|
||||
* Several rows here already have this name, so it can only go in as a
|
||||
* copy.
|
||||
*/
|
||||
copy_only: boolean;
|
||||
};
|
||||
|
||||
export type ExtensionImportPreview = {
|
||||
kind: ExtensionBundleKind;
|
||||
exported_at: number;
|
||||
app_version: string;
|
||||
counts: Record<ExtensionImportStatus, number>;
|
||||
items: ExtensionImportPreviewItem[];
|
||||
/**
|
||||
* Items of other kinds the file holds: imported from their own pages.
|
||||
*/
|
||||
other_kinds: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* What to do with one previewed item: leave it, add it, replace the row it
|
||||
* matched, or add it beside it under a new name.
|
||||
*/
|
||||
export type ExtensionImportAction = "skip" | "add" | "overwrite" | "copy";
|
||||
|
||||
export type ExtensionImportDecision = {
|
||||
index: number;
|
||||
action: ExtensionImportAction;
|
||||
};
|
||||
|
||||
export type ExtensionImportOutcome = {
|
||||
index: number;
|
||||
name: string;
|
||||
action: ExtensionImportAction;
|
||||
ok: boolean;
|
||||
msg: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* What an import did, and the page's list again, for the kind it came from.
|
||||
*/
|
||||
export type ExtensionImportApplyPayload =
|
||||
| { kind: "mcp"; outcomes: ExtensionImportOutcome[]; overview: McpServersOverviewPayload }
|
||||
| { kind: "tool"; outcomes: ExtensionImportOutcome[]; overview: CustomToolsOverviewPayload }
|
||||
| { kind: "skill"; outcomes: ExtensionImportOutcome[]; overview: SkillsOverviewPayload }
|
||||
| { kind: "knowledgebase"; outcomes: ExtensionImportOutcome[]; overview: KnowledgebasesOverviewPayload };
|
||||
|
||||
/**
|
||||
* What testing an MCP server's form returned: its tools, or why it didn't
|
||||
* connect.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import redactTemplateMap from "./redact-template-map";
|
||||
|
||||
describe("redactTemplateMap", () => {
|
||||
it("keeps templates and names every literal value it left behind", () => {
|
||||
const res = redactTemplateMap({
|
||||
values: { Authorization: "Bearer sk-live", "X-Trace": "{{env.TRACE}}" },
|
||||
label: "header",
|
||||
});
|
||||
|
||||
expect(res).toEqual({
|
||||
values: { "X-Trace": "{{env.TRACE}}" },
|
||||
redacted: ["header Authorization"],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a template that only ends in one", () => {
|
||||
const res = redactTemplateMap({ values: { Authorization: "Bearer {{env.GITHUB_TOKEN}}" }, label: "header" });
|
||||
|
||||
expect(res).toEqual({ values: { Authorization: "Bearer {{env.GITHUB_TOKEN}}" }, redacted: [] });
|
||||
});
|
||||
|
||||
it("keeps an empty value: there is nothing to hide", () => {
|
||||
expect(redactTemplateMap({ values: { Accept: "" }, label: "header" })).toEqual({
|
||||
values: { Accept: "" },
|
||||
redacted: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a template however it is spaced or cased", () => {
|
||||
const res = redactTemplateMap({ values: { KEY: "{{ ENV . key }}" }, label: "env" });
|
||||
|
||||
expect(res.redacted).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import hasEnvTemplate from "./has-env-template";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* Header or env names to their values, as a row stores them.
|
||||
*/
|
||||
values: Record<string, string>;
|
||||
/**
|
||||
* What these are, for the line that names each one left out: "header",
|
||||
* "env".
|
||||
*/
|
||||
label: string;
|
||||
};
|
||||
|
||||
type Result = {
|
||||
/**
|
||||
* The entries a bundle carries: every one written as an env template
|
||||
* (`{{env.KEY}}`), which travels as it is, and any left empty.
|
||||
*/
|
||||
values: Record<string, string>;
|
||||
/**
|
||||
* The ones left out, named, e.g. "header Authorization".
|
||||
*/
|
||||
redacted: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* # Redact Template Map
|
||||
* A server's headers or env are the only places a key can be written out
|
||||
* instead of templated. A bundle carries the templates and leaves every
|
||||
* literal value behind, saying which, so an imported server is never
|
||||
* handed someone else's key (and a file on a disk holds none).
|
||||
*/
|
||||
export default function redactTemplateMap({ values, label }: Params): Result {
|
||||
const kept: Record<string, string> = {};
|
||||
const redacted: string[] = [];
|
||||
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value && !hasEnvTemplate({ values: [value] })) {
|
||||
redacted.push(`${label} ${key}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
kept[key] = value;
|
||||
}
|
||||
|
||||
return { values: kept, redacted };
|
||||
}
|
||||
Reference in New Issue
Block a user