feat(ai): add plugin recommendations and agent context

This commit is contained in:
二丫讲梵 authored and t8y2 committed 2026-09-27 12:04:09 +08:00
1 parent 1b6017b9c5
commit e6edd02bbe
43 files changed
+1210 -118

No files matched your search

+8 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import * as api from "@/lib/backend/api";
import { AGENT_ACTIONS, ASK_ACTIONS, buildAgentRequest, isValidActionForMode, type AiAction, type AiContext } from "@/lib/ai/ai";
import { AGENT_ACTIONS, ASK_ACTIONS, buildAgentRequest, buildSystemPrompt, isValidActionForMode, type AiAction, type AiContext } from "@/lib/ai/ai";
import { INTENT_CLASSIFY_MAX_TEXT_CHARS, actionForIntent, classifyIntentByLlm, intentCandidatesForMode, parseClassifierAction, requestsExplicitExecution, routeIntent, routeIntentByRules, type AiIntent, type AiIntentRouteInput } from "@/lib/ai/aiIntentRouter";
import type { AiConfig } from "@/stores/settingsStore";
@@ -428,6 +428,13 @@ describe("routeIntent (two-stage entry point)", () => {
});
describe("'auto' never reaches the transport layer", () => {
it("builds plugin Agent prompts that require live tools", () => {
const request = buildAgentRequest({ config, action: "general", mode: "agent", instruction: "检查当前集群", context: context({ databaseType: "plugin", connectionName: "orb", database: "" }) });
expect(request.messages[request.messages.length - 1]?.content).toBe("检查当前集群");
expect(buildSystemPrompt("general", context({ databaseType: "plugin", connectionName: "orb", database: "" }), "agent")).toContain("live data");
expect(buildSystemPrompt("general", context({ databaseType: "plugin", connectionName: "orb", database: "" }), "agent")).not.toContain("返回 SQL");
});
it("keeps the concrete action tables free of 'auto'", () => {
expect(ASK_ACTIONS).not.toContain("auto");
expect(AGENT_ACTIONS).not.toContain("auto");
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { buildPluginAiRequest, createPluginAiConversation, pluginContextFromMessages, streamPluginAiConversation } from "../aiPluginConversation";
import { buildPluginAiRequest, createPluginAiConversation, pluginComposerConnectionLabel, pluginContextConnectionId, pluginContextFromMessages, streamPluginAiConversation } from "../aiPluginConversation";
import type { AiConfig } from "@/types/ai";
import type { AgentEvent } from "@/lib/backend/tauri";
@@ -7,6 +7,19 @@ const identity = { id: "market", name: "Market Watch" };
const input = () => ({ title: "AAPL", prompt: "Analyse risks", context: { quotes: [{ symbol: "AAPL", price: 100, currency: "USD" }], snapshotId: "snap-1" } });
describe("plugin conversations in DBX AI", () => {
it("keeps the composer label on the connection instead of the recommendation title", () => {
const context = createPluginAiConversation(identity, input()).context;
expect(pluginComposerConnectionLabel(context, "orb", "Saved connection")).toBe("orb");
expect(pluginComposerConnectionLabel(context, undefined, "Saved connection")).toBe("Saved connection");
expect(pluginComposerConnectionLabel(context)).toBe("Market Watch");
});
it("reads an optional connection id from the plugin snapshot without requiring it", () => {
const context = createPluginAiConversation(identity, { ...input(), context: { connectionId: "conn-orb" } }).context;
expect(pluginContextConnectionId(context)).toBe("conn-orb");
expect(pluginContextConnectionId(createPluginAiConversation(identity, input()).context)).toBeUndefined();
});
it("binds the host identity and freezes a data snapshot without auto-sending by default", () => {
const request = input();
const opened = createPluginAiConversation(identity, { ...request, pluginId: "other-plugin", pluginName: "spoof" });
@@ -16,6 +29,16 @@ describe("plugin conversations in DBX AI", () => {
expect(opened).not.toHaveProperty("apiKey");
});
it("keeps legacy opens in snapshot Ask mode and accepts explicit Agent mode", () => {
const legacy = createPluginAiConversation(identity, input());
expect(legacy.mode).toBeUndefined();
expect(legacy.context.mode).toBeUndefined();
const live = createPluginAiConversation(identity, { ...input(), mode: "agent" });
expect(live.mode).toBe("agent");
expect(live.context.mode).toBe("agent");
expect(() => createPluginAiConversation(identity, { ...input(), mode: "invalid" })).toThrow();
});
it.each([{ title: "" }, { prompt: "" }, { context: [] }, { send: "true" }, { context: { callback: () => {} } }, { context: { big: "x".repeat(2 * 1024 * 1024) } }])("rejects malformed or oversized requests", (override) => {
expect(() => createPluginAiConversation(identity, { ...input(), ...override })).toThrow();
});
+17
View File
@@ -286,6 +286,9 @@ export async function runAgentStream(input: AiRequestInput, history: api.AiMessa
}
export function buildUserPrompt(action: AiAction, context: AiContext, instruction: string, isZh: boolean): string {
if (context.databaseType === "plugin") {
return instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
}
const userRequest = instruction.trim() || (isZh ? "(无额外说明)" : "(No extra instruction provided.)");
const attachedTextData = formatAttachedTextData(context, isZh);
if (isVectorDbType(context.databaseType) || context.databaseType === "redis") {
@@ -325,6 +328,20 @@ function attachmentSafetyInstruction(isZh: boolean): string {
}
export function buildSystemPrompt(action: AiAction, context: AiContext, mode: AiAssistantMode = "ask", custom?: CustomPromptContext): string {
if (context.databaseType === "plugin") {
const isZh = isChineseLocale(currentLocale());
return [
isZh ? "你是 DBX 中连接插件的实时 Agent。" : "You are DBX's live Agent for a connected plugin.",
isZh
? "必须优先调用当前插件提供的工具获取实时数据,再基于工具结果回答。不要把历史上下文快照当作当前状态,也不要在没有工具结果时声称已经查询过资源。"
: "Always call the connected plugin's tools first to obtain live data. Do not treat historical context snapshots as current state or claim that a resource was queried without tool results.",
isZh ? "工具调用遵循工具定义和现有确认策略;如果没有可用工具,明确告知用户当前连接未提供实时查询能力。" : "Follow the tool definitions and the existing approval policy. If no tool is available, tell the user that this connection does not provide live query capability.",
...buildCustomInstructionLines(custom, isZh),
`Connection: ${context.connectionName}`,
]
.filter(Boolean)
.join("\n\n");
}
if (isVectorDbType(context.databaseType)) {
return buildVectorSystemPrompt(context, mode, custom);
}
@@ -1,6 +1,6 @@
import type { InjectionKey } from "vue";
import { snapshotPluginWorkbenchContext } from "@/lib/plugins/pluginData";
import type { AiConfig } from "@/types/ai";
import type { AiAssistantMode, AiConfig } from "@/types/ai";
import type { AiCompletionRequest, AiMessage, AiStreamChunk, AgentEvent } from "@/lib/backend/tauri";
/** Data owned by a conversation, independent of the currently selected DBX tab. */
@@ -10,12 +10,16 @@ export interface AiPluginContext {
title: string;
capturedAt: string;
data: Record<string, unknown>;
/** Persisted so reopening a live recommendation conversation keeps Agent mode. */
mode?: AiAssistantMode;
}
export interface AiPluginConversationRequest {
context: AiPluginContext;
prompt: string;
send: boolean;
/** Legacy plugin calls stay on snapshot Ask mode unless they opt into live Agent mode. */
mode?: AiAssistantMode;
}
export const OPEN_PLUGIN_AI_CONVERSATION: InjectionKey<(request: AiPluginConversationRequest) => Promise<void>> = Symbol("open-plugin-ai-conversation");
@@ -27,6 +31,7 @@ export function createPluginAiConversation(plugin: { id: string; name: string },
if (typeof input.prompt !== "string" || !input.prompt.trim() || input.prompt.length > 32000) throw new Error("AI conversation prompt must contain 1–32000 characters");
if (!input.context || typeof input.context !== "object" || Array.isArray(input.context)) throw new Error("AI conversation context must be an object");
if (input.send !== undefined && typeof input.send !== "boolean") throw new Error("AI conversation send must be a boolean");
if (input.mode !== undefined && input.mode !== "ask" && input.mode !== "agent") throw new Error("AI conversation mode must be ask or agent");
return {
context: {
pluginId: plugin.id,
@@ -34,9 +39,11 @@ export function createPluginAiConversation(plugin: { id: string; name: string },
title: input.title.trim(),
capturedAt: new Date().toISOString(),
data: snapshotPluginWorkbenchContext(input.context as Record<string, unknown>),
...(input.mode === undefined ? {} : { mode: input.mode }),
},
prompt: input.prompt.trim(),
send: input.send === true,
...(input.mode === undefined ? {} : { mode: input.mode }),
};
}
@@ -48,6 +55,25 @@ export function pluginContextText(context: AiPluginContext): string {
return `${context.pluginName} · ${context.title}\n${context.capturedAt}\n\n${JSON.stringify(context.data, null, 2)}`;
}
/** A plugin may include the DBX connection id in its snapshot context. */
export function pluginContextConnectionId(context: AiPluginContext): string | undefined {
const value = context.data.connectionId;
return typeof value === "string" && value.trim() ? value : undefined;
}
/**
* Label shown in the AI composer for a plugin-backed conversation.
*
* The plugin title describes the request and can change for every
* recommendation. The composer is bound to a connection instead, so prefer
* the resolved connection name and use the persisted name for conversations
* whose connection was removed. Older plugin conversations may have neither,
* in which case the plugin name is the safest available fallback.
*/
export function pluginComposerConnectionLabel(context: AiPluginContext, boundConnectionName?: string, persistedConnectionName?: string): string {
return boundConnectionName?.trim() || persistedConnectionName?.trim() || context.pluginName;
}
export function buildPluginAiRequest(config: AiConfig, context: AiPluginContext, messages: AiMessage[], instructions?: string[]): AiCompletionRequest {
return {
config,
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import { interpolatePluginAiRecommendation, isValidPluginAiRecommendationTemplate, resolvePluginAiRecommendationUpdate, resolvePluginAiRecommendations, selectPluginAiRecommendations } from "./pluginAiRecommendations";
import type { PluginAiRecommendation } from "@/types/pluginAiRecommendations";
const item = (overrides: Partial<PluginAiRecommendation> = {}): PluginAiRecommendation => ({
id: "health",
label: "Check {{resource.name}}",
prompt: "Analyze {{resource.kind}}/{{resource.name}}",
...overrides,
});
describe("plugin AI recommendations", () => {
it("rejects malformed placeholders", () => {
expect(isValidPluginAiRecommendationTemplate("Inspect {{resource.name}}")).toBe(true);
expect(isValidPluginAiRecommendationTemplate("Inspect {{resource..name}}")).toBe(false);
expect(isValidPluginAiRecommendationTemplate("Inspect {{resource.name")).toBe(false);
expect(isValidPluginAiRecommendationTemplate("Inspect resource.name}}")).toBe(false);
expect(isValidPluginAiRecommendationTemplate('Render JSON {"name": "{{resource.name}}"}')).toBe(true);
expect(isValidPluginAiRecommendationTemplate("Inspect {{resource.name}} and {{resource.kind}}")).toBe(true);
});
it("interpolates nested context paths in label and prompt", () => {
expect(interpolatePluginAiRecommendation(item(), { resource: { kind: "deployment", name: "whoami" } })).toEqual({
id: "health",
label: "Check whoami",
prompt: "Analyze deployment/whoami",
});
});
it("filters a recommendation when a placeholder is unresolved", () => {
expect(resolvePluginAiRecommendations([item()], { resource: { kind: "deployment" } })).toEqual([]);
expect(resolvePluginAiRecommendations([item({ label: "Static", prompt: "No placeholders" })], {})).toHaveLength(1);
});
it("does not traverse inherited or forbidden context properties", () => {
const context = Object.create({ resource: { name: "inherited" } }) as Record<string, unknown>;
expect(resolvePluginAiRecommendations([item()], context)).toEqual([]);
expect(resolvePluginAiRecommendations([item({ label: "{{constructor}}", prompt: "safe" })], {})).toEqual([]);
});
it("orders by order while keeping declaration order for ties and caps at five", () => {
const items = Array.from({ length: 7 }, (_, index) => item({ id: `item-${index}`, label: `Item ${index}`, prompt: `Prompt ${index}`, order: index === 6 ? -1 : 1 }));
expect(resolvePluginAiRecommendations(items, {}).map(({ id }) => id)).toEqual(["item-6", "item-0", "item-1", "item-2", "item-3"]);
});
it("does not mutate input recommendations", () => {
const defaults = [item({ label: "{{resource.name}}", prompt: "Ask {{resource.name}}" })];
const output = resolvePluginAiRecommendations(defaults, { resource: { name: "db" } });
expect(output[0]).not.toBe(defaults[0]);
expect(defaults[0].label).toBe("{{resource.name}}");
});
it("uses runtime recommendations as an override, including an explicit empty list", () => {
const defaults = [item({ id: "default", label: "Default", prompt: "Default" })];
expect(selectPluginAiRecommendations(defaults, undefined)).toBe(defaults);
expect(selectPluginAiRecommendations(defaults, [])).toEqual([]);
expect(resolvePluginAiRecommendationUpdate(defaults, { context: {}, items: [] })).toEqual([]);
});
it("uses runtime context and falls back to the supplied context when no update exists", () => {
const defaults = [item()];
expect(resolvePluginAiRecommendationUpdate(defaults, undefined, { resource: { kind: "table", name: "users" } })[0]?.prompt).toBe("Analyze table/users");
expect(resolvePluginAiRecommendationUpdate(defaults, { context: { resource: { kind: "pod", name: "api" } }, items: [item()] })[0]?.prompt).toBe("Analyze pod/api");
});
});
@@ -0,0 +1,115 @@
import { MAX_PLUGIN_AI_RECOMMENDATIONS, type PluginAiRecommendation, type PluginAiRecommendationContext, type PluginAiRecommendationUpdate } from "@/types/pluginAiRecommendations";
export { MAX_PLUGIN_AI_RECOMMENDATIONS, type PluginAiRecommendation, type PluginAiRecommendationContext, type PluginAiRecommendationUpdate };
const PLACEHOLDER = /\{\{\s*([A-Za-z_$][A-Za-z0-9_$]*(?:\.(?:[A-Za-z_$][A-Za-z0-9_$]*|[0-9]+))*)\s*\}\}/g;
const PLACEHOLDER_PATH = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.(?:[A-Za-z_$][A-Za-z0-9_$]*|[0-9]+))*$/;
const FORBIDDEN_PATH_SEGMENTS = new Set(["__proto__", "prototype", "constructor"]);
/** Validate that every brace pair uses the supported context placeholder syntax. */
export function isValidPluginAiRecommendationTemplate(value: string): boolean {
let offset = 0;
while (offset < value.length) {
const open = value.indexOf("{{", offset);
const close = value.indexOf("}}", offset);
const next = open < 0 ? close : close < 0 ? open : Math.min(open, close);
if (next < 0) return true;
if (value.startsWith("}}", next)) return false;
const end = value.indexOf("}}", next + 2);
if (end < 0) return false;
const path = value.slice(next + 2, end).trim();
if (!PLACEHOLDER_PATH.test(path) || FORBIDDEN_PATH_SEGMENTS.has(path) || path.split(".").some((segment) => FORBIDDEN_PATH_SEGMENTS.has(segment))) return false;
offset = end + 2;
}
return true;
}
/**
* Resolve a dotted context path without traversing inherited properties.
* This keeps plugin supplied templates from reading prototype members.
*/
function readContextPath(context: unknown, path: string): unknown {
let current: unknown = context;
for (const segment of path.split(".")) {
if (FORBIDDEN_PATH_SEGMENTS.has(segment) || (typeof current !== "object" && typeof current !== "function") || current === null) return undefined;
if (!Object.prototype.hasOwnProperty.call(current, segment)) return undefined;
current = (current as Record<string, unknown>)[segment];
}
return current;
}
/** Convert a context leaf to safe human-readable template text. */
function contextValueText(value: unknown): string | undefined {
if (value === null || value === undefined) return undefined;
if (typeof value === "string") return value.trim() ? value : undefined;
if (typeof value === "number") return Number.isFinite(value) ? String(value) : undefined;
if (typeof value === "boolean" || typeof value === "bigint") return String(value);
return undefined;
}
/**
* Interpolate one recommendation. If any placeholder cannot be resolved, the
* item is omitted (`null`) so an unfinished prompt is never shown to users.
*/
export function interpolatePluginAiRecommendation(item: PluginAiRecommendation, context: PluginAiRecommendationContext): PluginAiRecommendation | null {
if (!isValidRecommendation(item)) return null;
let unresolved = false;
const interpolate = (text: string): string =>
text.replace(PLACEHOLDER, (_match, path: string) => {
const value = contextValueText(readContextPath(context, path));
if (value === undefined) {
unresolved = true;
return "";
}
return value;
});
const label = interpolate(item.label);
const prompt = interpolate(item.prompt);
if (unresolved || !label.trim() || !prompt.trim()) return null;
return {
id: item.id.trim(),
label,
prompt,
...(item.order === undefined ? {} : { order: item.order }),
};
}
/**
* Resolve, order, and cap a list of recommendations for a context.
* The input is never mutated and the result contains fresh objects.
*/
export function resolvePluginAiRecommendations(items: readonly PluginAiRecommendation[] | undefined, context: PluginAiRecommendationContext = {}): PluginAiRecommendation[] {
const resolved = (items ?? [])
.map((item) => interpolatePluginAiRecommendation(item, context))
.filter((item): item is PluginAiRecommendation => item !== null)
.map((item, index) => ({ item, index }));
resolved.sort((left, right) => (left.item.order ?? 0) - (right.item.order ?? 0) || left.index - right.index);
return resolved.slice(0, MAX_PLUGIN_AI_RECOMMENDATIONS).map(({ item }) => item);
}
/**
* Select the effective list. An omitted runtime list keeps manifest defaults;
* an explicitly supplied list (including `[]`) replaces them.
*/
export function selectPluginAiRecommendations(defaults: readonly PluginAiRecommendation[] | undefined, runtime: readonly PluginAiRecommendation[] | undefined): readonly PluginAiRecommendation[] {
return runtime === undefined ? (defaults ?? []) : runtime;
}
/** Resolve a declaration plus an optional runtime update in one pure step. */
export function resolvePluginAiRecommendationUpdate(defaults: readonly PluginAiRecommendation[] | undefined, runtime: PluginAiRecommendationUpdate | undefined, fallbackContext: PluginAiRecommendationContext = {}): PluginAiRecommendation[] {
const items = selectPluginAiRecommendations(defaults, runtime?.items);
return resolvePluginAiRecommendations(items, runtime?.context ?? fallbackContext);
}
function isValidRecommendation(item: PluginAiRecommendation): boolean {
if (!item || typeof item !== "object") return false;
if (typeof item.id !== "string" || !item.id.trim()) return false;
if (typeof item.label !== "string" || !item.label.trim()) return false;
if (typeof item.prompt !== "string" || !item.prompt.trim()) return false;
if (!isValidPluginAiRecommendationTemplate(item.label) || !isValidPluginAiRecommendationTemplate(item.prompt)) return false;
return item.order === undefined || (typeof item.order === "number" && Number.isFinite(item.order));
}
+81
View File
@@ -141,6 +141,87 @@ describe("PluginHostBridge", () => {
expect(messages[0].capabilities.ai).toBe(false);
});
it("does not publish recommendation defaults without the host.ai permission", () => {
const updates: unknown[] = [];
const target = { postMessage: vi.fn() } as unknown as Window;
const contribution = {
...workbench,
ai: { recommendations: [{ id: "health", label: "Health", prompt: "Check health" }] },
} as PluginWorkbenchContribution;
new PluginHostBridge(plugin([], [contribution]), contribution, { workbenchId: "wb-1" }, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
setAiRecommendations: (update) => updates.push(update),
});
expect(updates).toHaveLength(0);
});
it("publishes manifest and runtime AI recommendations per workbench instance", async () => {
const messages: any[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const updates: any[] = [];
const contribution = {
...workbench,
ai: { recommendations: [{ id: "health", label: "Inspect {{resource.name}}", prompt: "Check {{resource.name}}", order: 1 }] },
} as PluginWorkbenchContribution;
const bridge = new PluginHostBridge(plugin(["host.ai"], [contribution]), contribution, { workbenchId: "wb-1", connectionId: "conn-1", resource: { name: "orders" } }, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
openAiConversation: vi.fn().mockResolvedValue(undefined),
setAiRecommendations: (update) => updates.push(update),
});
expect(updates[0]).toMatchObject({ workbenchId: "wb-1", items: [{ label: "Inspect orders", prompt: "Check orders" }] });
bridge.handleWindowMessage({
source: target,
data: {
source: "dbx-plugin",
version: 1,
type: "request",
id: "set",
method: "host.ai.setRecommendations",
params: { context: { connectionId: "other-connection", resource: { name: "customers" } }, items: [{ id: "custom", label: "Review {{resource.name}}", prompt: "Review {{resource.name}}" }] },
},
} as MessageEvent);
await vi.waitFor(() => expect(messages.some((message) => message.id === "set" && message.result === null)).toBe(true));
expect(updates[updates.length - 1]).toMatchObject({
pluginId: "sample",
pluginName: "Sample",
workbenchId: "wb-1",
context: { connectionId: "conn-1", resource: { name: "customers" } },
items: [{ label: "Review customers", prompt: "Review customers" }],
});
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "clear", method: "host.ai.clearRecommendations", params: {} },
} as MessageEvent);
await vi.waitFor(() => expect(messages.some((message) => message.id === "clear" && message.result === null)).toBe(true));
expect(updates[updates.length - 1]).toMatchObject({ workbenchId: "wb-1", items: [] });
});
it("rejects malformed runtime recommendation placeholders", async () => {
const messages: any[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(plugin(["host.ai"]), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
openAiConversation: vi.fn().mockResolvedValue(undefined),
setAiRecommendations: vi.fn(),
});
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "bad", method: "host.ai.setRecommendations", params: { context: {}, items: [{ id: "bad", label: "Inspect {{resource..name}}", prompt: "Check" }] } },
} as MessageEvent);
await vi.waitFor(() => expect(messages[0]?.error).toContain("invalid placeholder"));
});
it("binds backend calls to the owning plugin identity", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
@@ -2,6 +2,8 @@ import type { InstalledPlugin, PluginBinaryEvent, PluginEvent, PluginUiAssetPayl
import { clonePluginData, snapshotPluginWorkbenchContext } from "./pluginData";
import { MAX_PLUGIN_PLAN_SQL_CHARS, MAX_PLUGIN_PLAN_TIMEOUT_MS, PLUGIN_PLAN_PERMISSION, type PluginPlanCapabilities, type PluginPlanRequest, type PluginPlanResult } from "@/types/pluginPlan";
import { createPluginAiConversation, type AiPluginConversationRequest } from "@/lib/ai/aiPluginConversation";
import { isValidPluginAiRecommendationTemplate, resolvePluginAiRecommendationUpdate, type PluginAiRecommendationContext, type PluginAiRecommendationUpdate } from "@/lib/plugins/pluginAiRecommendations";
import type { PluginAiRecommendation } from "@/types/pluginAiRecommendations";
import { MAX_PLUGIN_SCHEMA_METADATA_NAME_CHARS, PLUGIN_SCHEMA_METADATA_CAPABILITY, PLUGIN_SCHEMA_METADATA_PERMISSION, type PluginTableContext, type PluginTableMetadata } from "@/types/pluginSchemaMetadata";
import { MAX_PLUGIN_DATA_MAX_ROWS, MAX_PLUGIN_DATA_NAME_CHARS, MAX_PLUGIN_DATA_SQL_CHARS, MAX_PLUGIN_DATA_TIMEOUT_MS, PLUGIN_DATA_ACCESS_NOT_GRANTED, PLUGIN_DATA_CAPABILITY, PLUGIN_DATA_READ_PERMISSION, type PluginDataQueryRequest, type PluginDataQueryResult } from "@/types/pluginData";
@@ -152,6 +154,7 @@ export interface PluginHostBridgeApi {
sendBinary(pluginId: string, channel: string, dataBase64: string): Promise<void>;
readAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload>;
openAiConversation?(request: AiPluginConversationRequest): Promise<void>;
setAiRecommendations?(update: PluginAiRecommendationHostUpdate): void;
openWorkbench?(pluginId: string, contributionId: string, context?: PluginWorkbenchContext, options?: { forceNew?: boolean }): Promise<void> | void;
openFilesystem?(pluginId: string, providerId: string, context?: PluginWorkbenchContext): Promise<void> | void;
/** Explicit user-triggered reconnect of an owned plugin connection (full flow, interactive password prompt allowed). */
@@ -236,6 +239,15 @@ export interface PluginHostBridgeApi {
storageDelete?(pluginId: string, key: string): Promise<void>;
}
export interface PluginAiRecommendationHostUpdate {
pluginId: string;
pluginName: string;
contributionId: string;
workbenchId: string;
context: PluginAiRecommendationContext;
items: readonly PluginAiRecommendation[];
}
interface PluginRequestMessage {
source: typeof PLUGIN_MESSAGE_SOURCE;
version: typeof BRIDGE_VERSION;
@@ -265,6 +277,7 @@ export class PluginHostBridge {
/** One consent prompt per connection at a time; concurrent queries share it. */
private pendingDataAccess = new Map<string, Promise<void>>();
private inFlightDataQueries = 0;
private runtimeAiRecommendations: PluginAiRecommendationUpdate | null | undefined;
/** Bounded audit trail of this session's clipboard read attempts (oldest first). */
get clipboardAudit(): readonly PluginClipboardAuditEntry[] {
@@ -286,6 +299,7 @@ export class PluginHostBridge {
this.context = snapshotPluginWorkbenchContext(context);
this.locale = locale;
this.theme = theme ? clonePluginData(theme) : undefined;
this.publishAiRecommendations();
}
handleWindowMessage(event: MessageEvent): boolean {
@@ -360,6 +374,7 @@ export class PluginHostBridge {
this.downloads.clear();
for (const token of this.mediaTokens) void this.api.closeMedia?.(this.plugin.manifest.id, token).catch(() => undefined);
this.mediaTokens.clear();
this.publishAiRecommendations({ context: {}, items: [] });
}
private disposed = false;
@@ -419,6 +434,7 @@ export class PluginHostBridge {
[PLUGIN_DATA_CAPABILITY]: !!this.api.queryData && !!this.api.hasDataGrant && !!this.api.confirmDataAccess && !!this.api.grantDataAccess,
storage: !!this.api.storageGet && !!this.api.storageSet && !!this.api.storageDelete,
ai: !!this.api.openAiConversation,
aiRecommendations: !!this.api.openAiConversation && !!this.api.setAiRecommendations,
// Additive with the same "absence means unsupported" contract: an older
// host omits these, and a web host has neither.
clipboardWrite: !!this.api.copyText,
@@ -437,9 +453,42 @@ export class PluginHostBridge {
*/
updateContext(context: PluginWorkbenchContext): void {
this.context = snapshotPluginWorkbenchContext(context);
this.runtimeAiRecommendations = undefined;
this.publishAiRecommendations();
this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "context", context: snapshotPluginWorkbenchContext(this.context) });
}
private publishAiRecommendations(override?: PluginAiRecommendationUpdate): void {
if (!this.hasPermission("host.ai") || !this.api.openAiConversation || !this.api.setAiRecommendations) return;
const workbenchId = typeof this.context.workbenchId === "string" ? this.context.workbenchId : "";
const contribution = this.contribution.type === "workbench" ? this.contribution : undefined;
const defaults = contribution?.ai?.recommendations;
const runtime = override ?? this.runtimeAiRecommendations;
// Runtime updates usually contain only the resource-specific fields used by
// placeholders. Keep host-owned routing fields authoritative so clicking a
// recommendation remains bound to this workbench's connection even when the
// plugin does not repeat connectionId in every update.
const runtimeContext = runtime
? snapshotPluginWorkbenchContext({
...runtime.context,
...(this.context.connectionId === undefined ? {} : { connectionId: this.context.connectionId }),
...(this.context.database === undefined ? {} : { database: this.context.database }),
...(this.context.schema === undefined ? {} : { schema: this.context.schema }),
...(this.context.workbenchId === undefined ? {} : { workbenchId: this.context.workbenchId }),
})
: this.context;
const effectiveRuntime = runtime === null ? { context: {}, items: [] } : runtime ? { ...runtime, context: runtimeContext } : undefined;
const items = resolvePluginAiRecommendationUpdate(defaults, effectiveRuntime, this.context);
this.api.setAiRecommendations({
pluginId: this.plugin.manifest.id,
pluginName: this.plugin.manifest.name,
contributionId: this.contribution.id,
workbenchId,
context: runtime ? runtimeContext : this.context,
items,
});
}
/** Notify the plugin UI about a locale change without a reload. */
updateLocale(locale: string): void {
this.locale = locale;
@@ -515,6 +564,21 @@ export class PluginHostBridge {
await this.api.openAiConversation(request);
return null;
}
if (method === "host.ai.setRecommendations") {
this.requirePermission("host.ai");
if (!this.api.openAiConversation || !this.api.setAiRecommendations) throw new Error("DBX AI recommendations are unavailable");
const update = requirePluginAiRecommendationUpdate(params);
this.runtimeAiRecommendations = update;
this.publishAiRecommendations();
return null;
}
if (method === "host.ai.clearRecommendations") {
this.requirePermission("host.ai");
if (!this.api.openAiConversation || !this.api.setAiRecommendations) throw new Error("DBX AI recommendations are unavailable");
this.runtimeAiRecommendations = { context: {}, items: [] };
this.publishAiRecommendations();
return null;
}
if (method === "backend.invoke") {
const input = requireRecord(params, "backend.invoke params");
const backendMethod = requireProtocolName(input.method, "backend method");
@@ -1087,7 +1151,11 @@ export function pluginSdkSource(initialTheme?: PluginBridgeTheme): string {
downloadFile: (options) => request('host.downloadFile', options),
cancelDownload: (downloadId) => request('host.cancelDownload', { downloadId }),
request,
ai: Object.freeze({ openConversation: (options) => request('host.ai.openConversation', options) }),
ai: Object.freeze({
openConversation: (options) => request('host.ai.openConversation', options),
setRecommendations: (update) => request('host.ai.setRecommendations', update),
clearRecommendations: () => request('host.ai.clearRecommendations'),
}),
invoke: (method, params, options = {}) => request('backend.invoke', { method, params, timeoutMs: options.timeoutMs }),
stream,
notify: (method, params) => request('backend.notify', { method, params }),
@@ -1385,6 +1453,29 @@ function requireHandleId(value: unknown): string {
return value;
}
function requirePluginAiRecommendationUpdate(value: unknown): PluginAiRecommendationUpdate {
const input = requireRecord(value, "AI recommendation update");
if (!isRecord(input.context)) throw new Error("AI recommendation context must be an object");
if (!Array.isArray(input.items)) throw new Error("AI recommendation items must be an array");
if (input.items.length > 5) throw new Error("At most 5 AI recommendations may be registered");
const context = snapshotPluginWorkbenchContext(input.context) as PluginAiRecommendationContext;
const items = input.items.map((candidate, index) => {
if (!isRecord(candidate)) throw new Error(`AI recommendation ${index} must be an object`);
if (typeof candidate.id !== "string" || !candidate.id.trim()) throw new Error(`AI recommendation ${index} requires id`);
if (typeof candidate.label !== "string" || !candidate.label.trim() || candidate.label.length > 200) throw new Error(`AI recommendation ${index} label is invalid`);
if (typeof candidate.prompt !== "string" || !candidate.prompt.trim() || candidate.prompt.length > 32000) throw new Error(`AI recommendation ${index} prompt is invalid`);
if (!isValidPluginAiRecommendationTemplate(candidate.label) || !isValidPluginAiRecommendationTemplate(candidate.prompt)) throw new Error(`AI recommendation ${index} contains an invalid placeholder`);
if (candidate.order !== undefined && (typeof candidate.order !== "number" || !Number.isFinite(candidate.order))) throw new Error(`AI recommendation ${index} order is invalid`);
return {
id: candidate.id.trim(),
label: candidate.label.trim(),
prompt: candidate.prompt.trim(),
...(candidate.order === undefined ? {} : { order: candidate.order }),
};
});
return { context, items };
}
function requireOffset(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error("offset is invalid");
return Math.floor(value);