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

@@ -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);