From 174d262a516ea767fb3a8f722ee96b6bc86505ed Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:01:00 +0000 Subject: [PATCH 1/3] fix(appkit): skip block comments in SQL params, dedupe and quote typegen keys - `:name` inside `/* ... */` is no longer read as a parameter or replaced during DESCRIBE. - Typegen keeps `x.obo.sql` when `x.sql` also exists, matching the runtime, and warns instead of emitting the key twice. - Query keys that aren't valid identifiers (e.g. `my-query`) are quoted in the generated declarations. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- .../src/type-generator/query-registry.ts | 21 ++++++- .../src/type-generator/render-query-types.ts | 7 ++- .../tests/generate-queries.test.ts | 59 +++++++++---------- .../tests/query-registry.test.ts | 15 +++++ .../tests/render-query-types.test.ts | 23 ++++++++ packages/appkit/src/utils/sql-parameters.ts | 7 ++- .../src/utils/tests/sql-parameters.test.ts | 7 +++ 7 files changed, 102 insertions(+), 37 deletions(-) create mode 100644 packages/appkit/src/type-generator/tests/render-query-types.test.ts diff --git a/packages/appkit/src/type-generator/query-registry.ts b/packages/appkit/src/type-generator/query-registry.ts index cff25109b..7e818f2f1 100644 --- a/packages/appkit/src/type-generator/query-registry.ts +++ b/packages/appkit/src/type-generator/query-registry.ts @@ -477,7 +477,13 @@ export function inferParameterTypes( for (const pattern of NUMERIC_PATTERNS) { for (const match of sql.matchAll(pattern)) { - if (!isInsideProtectedRange(match.index, protectedRanges)) { + if ( + !isInsideProtectedRange(match.index, protectedRanges) && + !isInsideProtectedRange( + match.index + match[0].length - 1, + protectedRanges, + ) + ) { inferred[match[1]] = "NUMERIC"; } } @@ -538,7 +544,18 @@ export async function generateQueriesFromDescribe( : loadCache(), ]); - const queryFiles = allFiles.filter((file) => file.endsWith(".sql")); + const files = new Set(allFiles); + const queryFiles = allFiles.filter((file) => { + if (!file.endsWith(".sql")) return false; + const oboFile = `${file.slice(0, -4)}.obo.sql`; + if (!file.endsWith(".obo.sql") && files.has(oboFile)) { + logger.warn( + `Both ${oboFile} and ${file} found for query ${file.slice(0, -4)}. Using ${oboFile}.`, + ); + return false; + } + return true; + }); logger.debug("Found %d SQL queries", queryFiles.length); const client = createTypegenWorkspaceClient(); diff --git a/packages/appkit/src/type-generator/render-query-types.ts b/packages/appkit/src/type-generator/render-query-types.ts index a05fbf852..b6e65da23 100644 --- a/packages/appkit/src/type-generator/render-query-types.ts +++ b/packages/appkit/src/type-generator/render-query-types.ts @@ -15,7 +15,12 @@ export function generateQueryTypeDeclarations( .split("\n") .map((line, i) => (i === 0 ? line : ` ${line}`)) .join("\n"); - return ` ${name}: ${indentedType}`; + const key = /^[$_\p{ID_Start}][$\p{ID_Continue}\p{Join_Control}]*$/u.test( + name, + ) + ? name + : JSON.stringify(name); + return ` ${key}: ${indentedType}`; }) .join(";\n"); diff --git a/packages/appkit/src/type-generator/tests/generate-queries.test.ts b/packages/appkit/src/type-generator/tests/generate-queries.test.ts index b836a0112..fa91ccef8 100644 --- a/packages/appkit/src/type-generator/tests/generate-queries.test.ts +++ b/packages/appkit/src/type-generator/tests/generate-queries.test.ts @@ -675,39 +675,36 @@ describe("generateQueriesFromDescribe", () => { expect(lastSavedQueries()).not.toHaveProperty("users"); }); - test("PENDING reuses a prior good cached type when the SQL hash matches", async () => { - // `users.sql` and `users.obo.sql` normalize to the same query name and hold - // identical SQL (same hash). With concurrency=1 the first DESCRIBE SUCCEEDS - // and its batch commits a good cached type; the second batch comes back - // non-terminal (warehouse not ready) and must reuse that freshly-cached good - // type rather than overwrite it with unknown. - const sql = "SELECT id FROM users"; - mocks.readdir.mockResolvedValue(["users.sql", "users.obo.sql"]); - mocks.readFile.mockResolvedValue(sql); - mocks.executeStatement - .mockResolvedValueOnce(succeededResult([["id", "INT", null]])) - .mockResolvedValueOnce({ - statementId: "stmt-pending", - status: { state: "RUNNING" }, - }); + test.each([ + ["users.sql", "users.obo.sql"], + ["users.obo.sql", "users.sql"], + ])("prefers the OBO query for directory order %s, %s", async (...files) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + mocks.readdir.mockResolvedValue(files); + mocks.readFile.mockResolvedValue("SELECT obo_id FROM users"); + mocks.executeStatement.mockResolvedValueOnce( + succeededResult([["obo_id", "INT", null]]), + ); - const { schemas, syntaxErrors, fatalErrors } = await describeQueries( - "/queries", - "wh-123", - { - concurrency: 1, - }, - ); + const { schemas } = await describeQueries("/queries", "wh-123"); - expect(schemas).toHaveLength(2); - // both entries resolve to the good type — the PENDING one reuses the cache - expect(schemas[0].type).toContain("id: number"); - expect(schemas[1].type).toContain("id: number"); - expect(schemas[1].type).not.toContain("result: unknown"); - expect(syntaxErrors).toEqual([]); - expect(fatalErrors).toEqual([]); - // the good cached type persists; PENDING never overwrites it with unknown - expect(lastSavedQueries()?.users.type).toContain("id: number"); + expect(mocks.readFile).toHaveBeenCalledOnce(); + expect(mocks.readFile).toHaveBeenCalledWith( + "/queries/users.obo.sql", + "utf8", + ); + expect(mocks.executeStatement).toHaveBeenCalledOnce(); + expect(schemas).toHaveLength(1); + expect(schemas[0].name).toBe("users"); + expect(schemas[0].type).toContain("obo_id: number"); + expect(warn).toHaveBeenCalledWith( + "[appkit:type-generator:query-registry]", + "Both users.obo.sql and users.sql found for query users. Using users.obo.sql.", + ); + } finally { + warn.mockRestore(); + } }); test("syntax error (FAILED) is recorded in syntaxErrors and not cached", async () => { diff --git a/packages/appkit/src/type-generator/tests/query-registry.test.ts b/packages/appkit/src/type-generator/tests/query-registry.test.ts index 00d78e5fb..36e2edc4b 100644 --- a/packages/appkit/src/type-generator/tests/query-registry.test.ts +++ b/packages/appkit/src/type-generator/tests/query-registry.test.ts @@ -578,6 +578,11 @@ describe("inferParameterTypes", () => { expect(result.fake).toBeUndefined(); }); + test("does not treat a block comment opener as an arithmetic operator", () => { + expect(inferParameterTypes("SELECT :value /* :hidden */")).toEqual({}); + expect(inferParameterTypes("SELECT :value -- :hidden")).toEqual({}); + }); + test("handles multiple params in one query with mixed contexts", () => { const sql = "SELECT * FROM t WHERE name = :name LIMIT :count OFFSET :skip"; const result = inferParameterTypes(sql); @@ -892,6 +897,16 @@ describe("substituteParametersForDescribe (IDENTIFIER support, #383)", () => { ); }); + test("leaves block comment placeholders untouched while substituting later parameters", () => { + const sql = "SELECT /* :hidden\n:also_hidden */ :visible, '/* :literal'"; + expect(substituteParametersForDescribe(sql)).toBe( + "SELECT /* :hidden\n:also_hidden */ '', '/* :literal'", + ); + expect(substituteParametersForDescribe("SELECT :visible /* :hidden")).toBe( + "SELECT '' /* :hidden", + ); + }); + test("does not substitute placeholders inside string literals", () => { const sql = "SELECT ':target_catalog' AS lit, :target_catalog AS p"; const sql2 = ["-- @param target_catalog STRING = main", sql].join("\n"); diff --git a/packages/appkit/src/type-generator/tests/render-query-types.test.ts b/packages/appkit/src/type-generator/tests/render-query-types.test.ts new file mode 100644 index 000000000..266617968 --- /dev/null +++ b/packages/appkit/src/type-generator/tests/render-query-types.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "vitest"; + +import { generateQueryTypeDeclarations } from "../render-query-types"; + +describe("generateQueryTypeDeclarations", () => { + test("quotes invalid identifiers and preserves valid identifiers", () => { + const output = generateQueryTypeDeclarations([ + { name: "my-query", type: "string" }, + { name: "normal_name", type: "number" }, + { name: "$valid", type: "boolean" }, + { name: "café", type: "unknown" }, + { name: 'a"b', type: "null" }, + { name: "123", type: "never" }, + ]); + + expect(output).toContain(' "my-query": string;'); + expect(output).toContain(" normal_name: number;"); + expect(output).toContain(" $valid: boolean;"); + expect(output).toContain(" café: unknown;"); + expect(output).toContain(' "a\\\"b": null;'); + expect(output).toContain(' "123": never;'); + }); +}); diff --git a/packages/appkit/src/utils/sql-parameters.ts b/packages/appkit/src/utils/sql-parameters.ts index 023f1336f..e678a1263 100644 --- a/packages/appkit/src/utils/sql-parameters.ts +++ b/packages/appkit/src/utils/sql-parameters.ts @@ -1,10 +1,11 @@ /** * Spans where `:name` isn't a parameter: '...' and "..." literals, `...` - * identifiers and `--` comments (not block comments). The first branch to - * match wins, so `"HH:mm'T'"` is one span. + * identifiers, `--` comments and block comments. The first branch to match + * wins, so `"HH:mm'T'"` is one span. */ +// shortcut: nested block comments aren't supported, use a SQL parser if needed. const PROTECTED_RANGE_RE = - /'(?:[^'\\]|\\.|'')*'|"(?:[^"\\]|\\.|"")*"|`(?:[^`]|``)*`|--[^\n]*/g; + /'(?:[^'\\]|\\.|'')*'|"(?:[^"\\]|\\.|"")*"|`(?:[^`]|``)*`|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/g; /** Start/end offsets of every span in {@link PROTECTED_RANGE_RE}. */ export function getProtectedRanges(sql: string): Array<[number, number]> { diff --git a/packages/appkit/src/utils/tests/sql-parameters.test.ts b/packages/appkit/src/utils/tests/sql-parameters.test.ts index f1bdfd572..0bb7dc6d1 100644 --- a/packages/appkit/src/utils/tests/sql-parameters.test.ts +++ b/packages/appkit/src/utils/tests/sql-parameters.test.ts @@ -19,11 +19,18 @@ describe("extractParameters", () => { ['"" escape', `SELECT "say ""hi"" at 10:30" AS t, :a`], ["backtick identifier", "SELECT `col:name` AS t, :a"], ["line comment", "SELECT 1 -- run at 10:30 :not_me\n, :a"], + ["single-line block comment", "SELECT /* :not_me */ :a"], + ["multi-line block comment", "SELECT /* :not_me\n :nor_me */ :a"], + ["block comment opener inside string", "SELECT '/* :not_me' AS t, :a"], [":: cast", "SELECT x::int AS t, :a"], ])("%s", (_, sql) => { expect(extractParameters(sql)).toEqual(["a"]); }); + test("unterminated block comments protect the rest of the SQL", () => { + expect(extractParameters("SELECT :a /* :not_me\n :nor_me")).toEqual(["a"]); + }); + test("parameters next to literals still count", () => { expect( extractParameters( From a17f8aada1233b5ca8a02a2185e13a1620ff310b Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:01:13 +0000 Subject: [PATCH 2/3] feat(appkit): expose named analytics queries as agent tools `plugins.analytics.queries({ only })` turns each `config/queries/*.sql` file into a `query.` tool in the `toolkit()` entry shape, so agents (and the upcoming MCP plugin) can use them. - `-- @description` and `-- @param name TYPE [description]` comments are read at runtime and give the tool its description and JSON Schema; every parameter is required and untyped ones are strings. - `.sql` tools run as the app even inside a caller scope; `.obo.sql` tools run as the caller and are refused without one (except the existing dev fallback). - Every query tool is `effect: "read"`; files that fail the read-only SQL check are refused. Results are capped at 100 rows with a note. - New `analytics.runQuery(name, params?, signal?)` runs a named query in process and returns its rows. The HTTP route's JSON path and the tools share its execution core, cache keys unchanged. - Docs: "Named queries as tools" in the analytics plugin page. Co-authored-by: Isaac Signed-off-by: mario.cadenas --- docs/docs/api/appkit/TypeAlias.Plugins.md | 37 ++- docs/docs/api/appkit/index.md | 2 +- docs/docs/plugins/agents.md | 12 + docs/docs/plugins/analytics.md | 48 +++ packages/appkit/src/core/agent/index.ts | 1 + packages/appkit/src/core/agent/run-agent.ts | 3 + .../src/core/agent/tests/run-agent.test.ts | 39 +++ packages/appkit/src/core/agent/types.ts | 15 +- .../appkit/src/plugins/analytics/analytics.ts | 279 +++++++++++++----- .../src/plugins/analytics/query-tools.ts | 163 ++++++++++ .../plugins/analytics/tests/analytics.test.ts | 190 ++++++++++++ .../analytics/tests/query-tools.test.ts | 249 ++++++++++++++++ 12 files changed, 953 insertions(+), 85 deletions(-) create mode 100644 packages/appkit/src/plugins/analytics/query-tools.ts create mode 100644 packages/appkit/src/plugins/analytics/tests/query-tools.test.ts diff --git a/docs/docs/api/appkit/TypeAlias.Plugins.md b/docs/docs/api/appkit/TypeAlias.Plugins.md index e70ed4bcc..c7dcc521e 100644 --- a/docs/docs/api/appkit/TypeAlias.Plugins.md +++ b/docs/docs/api/appkit/TypeAlias.Plugins.md @@ -1,18 +1,52 @@ # Type Alias: Plugins ```ts -type Plugins = Record; +type Plugins = Record & { + analytics: PluginToolkitProvider & { + queries: Record; + }; +}; ``` Plugin map passed to the function form of [AgentDefinition.tools](Interface.AgentDefinition.md#tools). Each entry exposes a `.toolkit(opts?)` method that returns a record of [ToolkitEntry](Interface.ToolkitEntry.md) markers ready to be spread into a tool record. +`analytics` also exposes `.queries(opts?)`, one `query.` tool per +named SQL file in `config/queries/`. AppKit does not statically know which plugins the surrounding `createApp` will register, so this is a plain string-keyed record. Refer to plugins by the name used in `createApp({ plugins: [...] })`; unknown names resolve to `undefined` at runtime. +## Type Declaration + +### analytics + +```ts +analytics: PluginToolkitProvider & { + queries: Record; +}; +``` + +#### Type Declaration + +##### queries() + +```ts +queries(opts?: QueryToolsOptions): Record; +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts?` | `QueryToolsOptions` | + +###### Returns + +`Record`\<`string`, [`ToolkitEntry`](Interface.ToolkitEntry.md)\> + ## Example ```ts @@ -23,6 +57,7 @@ const support = createAgent({ get_weather: tool({ ... }), ...plugins.analytics.toolkit(), ...plugins.files.toolkit({ only: ["uploads.read"] }), + ...plugins.analytics.queries({ only: ["top_customers"] }), }; }, }); diff --git a/docs/docs/api/appkit/index.md b/docs/docs/api/appkit/index.md index 90f64e67c..e60543dd8 100644 --- a/docs/docs/api/appkit/index.md +++ b/docs/docs/api/appkit/index.md @@ -170,7 +170,7 @@ surface with `@databricks/appkit/beta`. Not meant for application imports. | [OperationWireInput](TypeAlias.OperationWireInput.md) | The JSON a caller sends to an operation; a bigint travels as a string or safe integer. | | [OperationWireOutput](TypeAlias.OperationWireOutput.md) | The JSON a successful call answers with; without an output schema there is none. | | [PluginData](TypeAlias.PluginData.md) | Tuple of plugin class, config, and name. Created by `toPlugin()` and passed to `createApp()`. | -| [Plugins](TypeAlias.Plugins.md) | Plugin map passed to the function form of [AgentDefinition.tools](Interface.AgentDefinition.md#tools). Each entry exposes a `.toolkit(opts?)` method that returns a record of [ToolkitEntry](Interface.ToolkitEntry.md) markers ready to be spread into a tool record. | +| [Plugins](TypeAlias.Plugins.md) | Plugin map passed to the function form of [AgentDefinition.tools](Interface.AgentDefinition.md#tools). Each entry exposes a `.toolkit(opts?)` method that returns a record of [ToolkitEntry](Interface.ToolkitEntry.md) markers ready to be spread into a tool record. `analytics` also exposes `.queries(opts?)`, one `query.` tool per named SQL file in `config/queries/`. | | [Policy](TypeAlias.Policy.md) | A reusable authorization rule, with or without a resource lookup. | | [PolicyDecision](TypeAlias.PolicyDecision.md) | Only literal `true` admits. False and an explicit denial refuse. | | [ResolvedToolEntry](TypeAlias.ResolvedToolEntry.md) | Internal tool-index entry after a tool record has been resolved to a dispatchable form. | diff --git a/docs/docs/plugins/agents.md b/docs/docs/plugins/agents.md index db2adbadc..af7c72d06 100644 --- a/docs/docs/plugins/agents.md +++ b/docs/docs/plugins/agents.md @@ -176,6 +176,18 @@ Some examples further down still pass agents inline via this map for snippet bre | `prefix` | `{ prefix: "" }` | Drop the `${pluginName}.` prefix | | `rename` | `{ rename: { query: "q" } }` | Remap specific local names | +Named analytics SQL files can also be exposed as individual tools, separately +from the raw SQL toolkit: + +```ts +tools: (plugins) => ({ + ...plugins.analytics.queries({ only: ["top_customers"] }), +}), +``` + +See [Named queries as tools](./analytics.md#named-queries-as-tools) for identity, +parameter, and read-only rules. + For plugins that don't expose a `.toolkit()` method (e.g., third-party `ToolProvider` plugins authored with plain `toPlugin`), the runtime falls back to walking `getAgentTools()` and synthesizing namespaced keys (`${pluginName}.${localName}`). The fallback respects `only` / `except` / `rename` / `prefix` the same way. If a referenced plugin is not registered in `createApp({ plugins })`, the agents plugin throws at setup with an `Available: …` listing so you can fix the wiring before the first request. diff --git a/docs/docs/plugins/analytics.md b/docs/docs/plugins/analytics.md index 577f6a0c9..7c3ff0b5a 100644 --- a/docs/docs/plugins/analytics.md +++ b/docs/docs/plugins/analytics.md @@ -114,6 +114,54 @@ type-based placeholder, so a sample value can never break out of the WHERE workspace_id = :workspaceId ``` +## Named queries as tools + +Expose named queries explicitly in an agent. `queries()` returns keys such as +`query.top_customers`; it does not include the raw SQL tool from `toolkit()`. + +```ts +const agent = createAgent({ + instructions: "Answer questions about customers.", + tools: (plugins) => ({ + ...plugins.analytics.queries({ only: ["top_customers"] }), + }), +}); +``` + +Write descriptions for the model in the SQL file: + +```sql +-- @description Find customers with the most orders. +-- @param min_orders INT Minimum number of orders +-- @param region STRING Region to search +SELECT customer, count(*) AS orders FROM sales +WHERE region = :region AND workspace_id = :workspaceId +GROUP BY customer HAVING count(*) >= :min_orders +``` + +Multiple `@description` lines are joined. Without one, AppKit warns and uses a +generic description. Only actual `:name` markers become required inputs; +untyped inputs are strings. `workspaceId` is injected by the server and is not +exposed to the model. A `-- @param x TYPE = sample` line supplies a typegen +sample, not a tool-parameter description. See [sample values](#sample-values-for-type-generation). + +`.sql` tools always run as the app service principal, even within a user +request. `.obo.sql` tools run as the caller and require caller credentials +(except for the existing local-development fallback). If both variants exist, +the OBO file wins. Only expose app-identity queries to agents whose users may +see the data available to the app. The same conservative read-only SQL check +used by the raw analytics tool applies; an invalid explicit selection fails at +startup, while an invalid query discovered without `only` is skipped with a +warning. The classifier checks statement prefixes; it does not guarantee that +functions or CTEs have no side effects. Use warehouse permissions to enforce +read-only access. Tool lists are built at startup, so restart after adding or +changing queries. Results contain `rows` and `rowCount`; results over 100 rows are +truncated with a note. This limit applies after fetching, not at the warehouse. + +For application code, `appkit.analytics.runQuery(name, parameters?, signal?)` +returns uncapped rows and accepts the usual SQL type markers. It follows the +same app/caller identity rules. + ## HTTP endpoints The analytics plugin exposes these endpoints (mounted under `/api/analytics`): diff --git a/packages/appkit/src/core/agent/index.ts b/packages/appkit/src/core/agent/index.ts index d184e13ae..282d7623d 100644 --- a/packages/appkit/src/core/agent/index.ts +++ b/packages/appkit/src/core/agent/index.ts @@ -48,6 +48,7 @@ export { type Plugins, type PluginToolkitProvider, type PromptContext, + type QueryToolsOptions, type RegisteredAgent, type ResolvedToolEntry, type ToolkitEntry, diff --git a/packages/appkit/src/core/agent/run-agent.ts b/packages/appkit/src/core/agent/run-agent.ts index efea6f6f8..b4d510c2b 100644 --- a/packages/appkit/src/core/agent/run-agent.ts +++ b/packages/appkit/src/core/agent/run-agent.ts @@ -515,6 +515,9 @@ function buildStandalonePluginsMap( if (!provider) continue; // initStandalonePlugins should have set this out[data.name] = { toolkit: (opts) => resolveToolkitFromProvider(data.name, provider, opts), + ...("queries" in provider && typeof provider.queries === "function" + ? { queries: provider.queries.bind(provider) } + : {}), }; } return createPluginsProxy(out, "runAgent: tools(plugins)"); diff --git a/packages/appkit/src/core/agent/tests/run-agent.test.ts b/packages/appkit/src/core/agent/tests/run-agent.test.ts index efaa0356b..5af69516d 100644 --- a/packages/appkit/src/core/agent/tests/run-agent.test.ts +++ b/packages/appkit/src/core/agent/tests/run-agent.test.ts @@ -143,6 +143,45 @@ describe("runAgent", () => { expect(pingExec).toHaveBeenCalled(); }); + test("standalone passes analytics queries through to tools callback", async () => { + const queries = vi.fn(function (this: { name: string }, opts: unknown) { + expect(this.name).toBe("analytics"); + expect(opts).toEqual({ only: ["sales"] }); + return {}; + }); + class FakeAnalytics implements ToolProvider { + static manifest = { name: "analytics" }; + static DEFAULT_CONFIG = {}; + name = "analytics"; + constructor(public config: unknown) {} + getAgentTools(): AgentToolDefinition[] { + return []; + } + async executeAgentTool() { + return undefined; + } + queries = queries; + } + const def = createAgent({ + instructions: "x", + model: scriptedAdapter([]), + tools: (plugins) => ({ + ...plugins.analytics.queries({ only: ["sales"] }), + }), + }); + await runAgent(def, { + messages: "hi", + plugins: [ + { + plugin: FakeAnalytics as unknown as PluginConstructor, + config: {}, + name: "analytics", + }, + ], + }); + expect(queries).toHaveBeenCalledOnce(); + }); + test("function-form throws with guidance when a referenced plugin is missing", async () => { const adapter: AgentAdapter = { async *run(_input, _context) { diff --git a/packages/appkit/src/core/agent/types.ts b/packages/appkit/src/core/agent/types.ts index 0fe15c043..f2f800111 100644 --- a/packages/appkit/src/core/agent/types.ts +++ b/packages/appkit/src/core/agent/types.ts @@ -67,10 +67,18 @@ export interface PluginToolkitProvider { toolkit(opts?: ToolkitOptions): Record; } +/** Options for `plugins.analytics.queries()`. */ +export interface QueryToolsOptions { + /** Query names to expose; defaults to all named queries. */ + only?: string[]; +} + /** * Plugin map passed to the function form of {@link AgentDefinition.tools}. * Each entry exposes a `.toolkit(opts?)` method that returns a record of * {@link ToolkitEntry} markers ready to be spread into a tool record. + * `analytics` also exposes `.queries(opts?)`, one `query.` tool per + * named SQL file in `config/queries/`. * * AppKit does not statically know which plugins the surrounding * `createApp` will register, so this is a plain string-keyed record. @@ -86,12 +94,17 @@ export interface PluginToolkitProvider { * get_weather: tool({ ... }), * ...plugins.analytics.toolkit(), * ...plugins.files.toolkit({ only: ["uploads.read"] }), + * ...plugins.analytics.queries({ only: ["top_customers"] }), * }; * }, * }); * ``` */ -export type Plugins = Record; +export type Plugins = Record & { + analytics: PluginToolkitProvider & { + queries(opts?: QueryToolsOptions): Record; + }; +}; /** * Context passed to `baseSystemPrompt` callbacks. diff --git a/packages/appkit/src/plugins/analytics/analytics.ts b/packages/appkit/src/plugins/analytics/analytics.ts index 6ac837575..c7bbe3d2f 100644 --- a/packages/appkit/src/plugins/analytics/analytics.ts +++ b/packages/appkit/src/plugins/analytics/analytics.ts @@ -2,6 +2,7 @@ import type express from "express"; import { type AgentToolDefinition, type AnalyticsSseMessage, + type AnalyticsResultMessage, type IAppRouter, makeResultMessage, type PluginExecuteConfig, @@ -16,16 +17,24 @@ import { DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS, type WarehouseStatusUpdate, } from "../../connectors/sql-warehouse/client"; -import { getWorkspaceClient } from "../../context"; +import { + getCallerContext, + getCurrentPrincipalKey, + getWorkspaceClient, +} from "../../context"; +import { runOutsideCallerScope } from "../../context/execution-context"; +import { isDevOboFallback } from "../../context/request-scope"; import { buildToolkitEntries } from "../../core/agent/build-toolkit"; import { defineTool, executeFromRegistry, + type ToolRegistry, toolsFromRegistry, } from "../../core/agent/tools/define-tool"; import { assertReadOnlySql } from "../../core/agent/tools/sql-policy"; import { AppKitError, + AuthenticationError, ExecutionError, IdentityExpiredError, } from "../../errors"; @@ -46,6 +55,7 @@ import { validateMetricRequest, } from "./metric"; import { QueryProcessor } from "./query"; +import { buildQueryTools } from "./query-tools"; import { ArrowCapabilityMemo, type ArrowDeliveryOut, @@ -123,6 +133,7 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { // analytics services private SQLClient: SQLWarehouseConnector; private queryProcessor: QueryProcessor; + private queryTools: ToolRegistry = {}; /** * In-process memo of which arrow delivery mode each warehouse supports @@ -318,28 +329,6 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { const executor = isAsUser ? this._asUserScoped(req) : this; const executorKey = isAsUser ? this.resolveUserId(req) : "global"; - const hashedQuery = this.queryProcessor.hashQuery(query); - - const cacheConfig = { - ...queryDefaults.cache, - cacheKey: [ - "analytics:query", - query_key, - JSON.stringify(parameters), - format, - hashedQuery, - executorKey, - ], - }; - - // Cache/retry/timeout are scoped to the SQL execution itself (inner - // `execute`) so the warehouse-readiness phase isn't subject to retries - // and the generator value never leaks into the cache. - const sqlConfig: PluginExecuteConfig = { - ...queryDefaults, - cache: cacheConfig, - }; - // Outer stream: no cache/retry — `executeStream` would otherwise wrap the // generator factory and cache the generator object itself. Telemetry + // user-scoped trace context still apply. @@ -389,71 +378,115 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { }; } - // `execute()` reduces a thrown error to `{ status, message }`, - // dropping the rich fields (`errorCode`, `clientMessage`) the - // fallback's `ExecutionError`s carry. Capture the original here so - // we can re-throw it intact — the SSE error path - // (`StreamManager`) reads `errorCode`/`clientMessage` off it. - let originalError: unknown; - const sqlResult = await executor.execute( - async (sig) => { - try { - const processedParams = - await self.queryProcessor.processQueryParams(query, parameters); - // JSON_ARRAY path: tries INLINE + JSON_ARRAY and, if the - // warehouse only accepts ARROW_STREAM for INLINE, retries as - // ARROW_STREAM and decodes server-side — returning the SSE - // `result` message with plain rows. (ARROW_STREAM requests are - // handled earlier via `_handleArrowStreamQuery`.) Numeric and - // BOOLEAN cells are coerced to match the generated query types. - return await self._executeJsonArrayPath( - executor, - query, - processedParams, - sig, - { coerceScalars: true }, - ); - } catch (err) { - originalError = err; - throw err; - } - }, - { default: sqlConfig }, + yield await self._executeNamedQueryJson( + executor, + query_key, + query, + parameters, executorKey, + format, ); + }, + streamExecutionSettings, + executorKey, + ); + } - if (!sqlResult.ok) { - const msg = sqlResult.message; - const lower = msg.toLowerCase(); - if ( - lower.includes("operation was aborted") || - lower.includes("the request was aborted") || - lower.includes("statement was canceled") - ) { - const err = new DOMException( - lower.includes("canceled") ? msg : "The operation was aborted.", - "AbortError", - ); - throw err; - } - // Re-throw the original error so its structured `errorCode` (e.g. - // RESULT_TOO_LARGE_FOR_JSON_FALLBACK) and sanitized `clientMessage` - // survive to the SSE error payload. Fall back to a generic - // statement failure only if the original wasn't an AppKitError. - if (originalError instanceof AppKitError) { - throw originalError; - } - const inner = msg.startsWith("Statement failed: ") - ? msg.slice("Statement failed: ".length) - : msg; - throw ExecutionError.statementFailed(inner); - } + private async _executeNamedQueryJson( + executor: AnalyticsPlugin, + queryKey: string, + query: string, + parameters: Record | undefined, + executorKey: string, + format: string, + signal?: AbortSignal, + ): Promise { + const hashedQuery = this.queryProcessor.hashQuery(query); + + const cacheConfig = { + ...queryDefaults.cache, + cacheKey: [ + "analytics:query", + queryKey, + JSON.stringify(parameters), + format, + hashedQuery, + executorKey, + ], + }; + + // Cache/retry/timeout are scoped to the SQL execution itself (inner + // `execute`) so the warehouse-readiness phase isn't subject to retries + // and the generator value never leaks into the cache. + const sqlConfig: PluginExecuteConfig = { + ...queryDefaults, + cache: cacheConfig, + }; - yield sqlResult.data as AnalyticsStreamMessage; + // `execute()` reduces a thrown error to `{ status, message }`, + // dropping the rich fields (`errorCode`, `clientMessage`) the + // fallback's `ExecutionError`s carry. Capture the original here so + // we can re-throw it intact — the SSE error path + // (`StreamManager`) reads `errorCode`/`clientMessage` off it. + let originalError: unknown; + const sqlResult = await executor.execute( + async (sig) => { + try { + const processedParams = await this.queryProcessor.processQueryParams( + query, + parameters, + ); + // JSON_ARRAY path: tries INLINE + JSON_ARRAY and, if the + // warehouse only accepts ARROW_STREAM for INLINE, retries as + // ARROW_STREAM and decodes server-side — returning the SSE + // `result` message with plain rows. (ARROW_STREAM requests are + // handled earlier via `_handleArrowStreamQuery`.) Numeric and + // BOOLEAN cells are coerced to match the generated query types. + // shortcut: a caller abort can cancel shared cache work; pass caller signals into Plugin.execute when supported. + return await this._executeJsonArrayPath( + executor, + query, + processedParams, + signal && sig ? AbortSignal.any([signal, sig]) : (signal ?? sig), + { coerceScalars: true }, + ); + } catch (err) { + originalError = err; + throw err; + } }, - streamExecutionSettings, + { default: sqlConfig }, executorKey, ); + + if (!sqlResult.ok) { + const msg = sqlResult.message; + const lower = msg.toLowerCase(); + if ( + lower.includes("operation was aborted") || + lower.includes("the request was aborted") || + lower.includes("statement was canceled") + ) { + const err = new DOMException( + lower.includes("canceled") ? msg : "The operation was aborted.", + "AbortError", + ); + throw err; + } + // Re-throw the original error so its structured `errorCode` (e.g. + // RESULT_TOO_LARGE_FOR_JSON_FALLBACK) and sanitized `clientMessage` + // survive to the SSE error payload. Fall back to a generic + // statement failure only if the original wasn't an AppKitError. + if (originalError instanceof AppKitError) { + throw originalError; + } + const inner = msg.startsWith("Statement failed: ") + ? msg.slice("Statement failed: ".length) + : msg; + throw ExecutionError.statementFailed(inner); + } + + return sqlResult.data as AnalyticsResultMessage; } /** @@ -1081,6 +1114,82 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { return response.result; } + /** Run a named analytics query as the app or, for .obo.sql, the caller. */ + async runQuery( + queryKey: string, + parameters?: Record, + signal?: AbortSignal, + ): Promise[]> { + return this._runQuery(queryKey, parameters, signal); + } + + private async _runQuery( + queryKey: string, + parameters: Record | undefined, + signal: AbortSignal | undefined, + expected?: { query: string; isAsUser: boolean }, + ): Promise[]> { + signal?.throwIfAborted(); + const result = await this.app.getAppQuery(queryKey); + if (!result) throw new Error(`Query not found: ${queryKey}`); + if (expected) { + if ( + result.query !== expected.query || + result.isAsUser !== expected.isAsUser + ) { + throw new Error( + `Query ${queryKey} changed after tools were built; restart the app`, + ); + } + assertReadOnlySql(result.query); + } + const execute = async () => { + if (result.isAsUser && !getCallerContext() && !isDevOboFallback()) { + throw AuthenticationError.missingToken("user token"); + } + const executorKey = result.isAsUser ? getCurrentPrincipalKey() : "global"; + await this.SQLClient.ensureWarehouseRunning( + getWorkspaceClient(), + await getWarehouseId(), + { + signal, + timeoutMs: + this.config.warehouseStartupTimeoutMs ?? + DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS, + autoStart: this.config.autoStartWarehouse ?? true, + onStatus: () => {}, + }, + ); + signal?.throwIfAborted(); + const message = await this._executeNamedQueryJson( + this, + queryKey, + result.query, + parameters, + executorKey, + "JSON_ARRAY", + signal, + ); + return message.data ?? []; + }; + return result.isAsUser ? execute() : runOutsideCallerScope(execute); + } + + /** Expose selected read-only named queries as agent tools. */ + queries(opts?: import("../../core/agent/types").QueryToolsOptions) { + const registry = buildQueryTools( + this.app.queriesDir, + opts, + (name, params, signal, expected) => + this._runQuery(name, params, signal, expected), + ); + for (const [name, entry] of Object.entries(registry)) { + registry[name] = this.queryTools[name] ?? entry; + this.queryTools[name] = registry[name]; + } + return buildToolkitEntries(this.name, registry, { prefix: "" }); + } + async shutdown(): Promise { this.streamManager.abortAll(); } @@ -1117,7 +1226,12 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { args: unknown, signal?: AbortSignal, ): Promise { - return executeFromRegistry(this.tools, name, args, signal); + return executeFromRegistry( + name.startsWith("query.") ? this.queryTools : this.tools, + name, + args, + signal, + ); } /** @@ -1141,6 +1255,7 @@ export class AnalyticsPlugin extends Plugin implements ToolProvider { * Execute a SQL query using service principal credentials. */ query: this.query, + runQuery: this.runQuery, }; } } diff --git a/packages/appkit/src/plugins/analytics/query-tools.ts b/packages/appkit/src/plugins/analytics/query-tools.ts new file mode 100644 index 000000000..0c8dea9d0 --- /dev/null +++ b/packages/appkit/src/plugins/analytics/query-tools.ts @@ -0,0 +1,163 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { sql, type SQLTypeMarker } from "shared"; +import { z } from "zod"; + +import { + defineTool, + type ToolRegistry, +} from "../../core/agent/tools/define-tool"; +import { assertReadOnlySql } from "../../core/agent/tools/sql-policy"; +import type { QueryToolsOptions } from "../../core/agent/types"; +import { createLogger } from "../../logging/logger"; +import { extractParameters } from "../../utils/sql-parameters"; + +const logger = createLogger("analytics"); +const paramLine = + /^[ \t]*--[ \t]*@param[ \t]+(\w+)[ \t]+(STRING|NUMERIC|DECIMAL|BIGINT|TINYINT|SMALLINT|INT|FLOAT|DOUBLE|BOOLEAN|DATE|TIMESTAMP_NTZ|TIMESTAMP|BINARY)\b([^\r\n]*)/gim; + +export function buildQueryTools( + directory: string, + options: QueryToolsOptions | undefined, + run: ( + name: string, + params: Record, + signal: AbortSignal | undefined, + expected: { query: string; isAsUser: boolean }, + ) => Promise[]>, +): ToolRegistry { + let files: string[]; + try { + files = readdirSync(directory); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + files = []; + } + const names = new Set( + files.flatMap((file) => { + const match = /^([a-zA-Z0-9_-]+)(?:\.obo)?\.sql$/.exec(file); + return match ? [match[1]] : []; + }), + ); + for (const name of options?.only ?? []) { + if (!names.has(name)) throw new Error(`Query not found: ${name}`); + } + const registry: ToolRegistry = {}; + for (const name of options?.only ?? names) { + const obo = files.includes(`${name}.obo.sql`); + if (obo && files.includes(`${name}.sql`)) { + logger.warn( + `Both ${name}.obo.sql and ${name}.sql found for query ${name}. Using ${name}.obo.sql.`, + ); + } + const query = readFileSync( + join(directory, `${name}${obo ? ".obo" : ""}.sql`), + "utf8", + ); + try { + assertReadOnlySql(query); + } catch (error) { + if (options?.only) throw error; + logger.warn(`Skipping query ${name}: ${(error as Error).message}`); + continue; + } + const descriptions = [ + ...query.matchAll(/^[ \t]*--[ \t]*@description[ \t]+([^\r\n]+)/gim), + ] + .map((match) => match[1].trim()) + .filter(Boolean); + if (!descriptions.length) logger.warn(`Query ${name} has no @description.`); + const annotations = new Map< + string, + { type: string; description?: string } + >(); + for (const match of query.matchAll(paramLine)) { + const rest = match[3].trim(); + annotations.set(match[1], { + type: match[2].toUpperCase(), + description: rest && !rest.startsWith("=") ? rest : undefined, + }); + } + const parameters = extractParameters(query); + // shortcut: Zod drops __proto__ during object parsing; upgrade when it preserves this key. + if (parameters.includes("__proto__")) { + const message = `Query ${name} uses unsupported parameter __proto__`; + if (options?.only) throw new Error(message); + logger.warn(`Skipping ${message}`); + continue; + } + const types = new Map(); + const shape: Record = {}; + for (const param of parameters) { + if (param === "workspaceId") continue; + const { type = "STRING", description } = annotations.get(param) ?? {}; + types.set(param, type); + let schema: z.ZodType; + if (["INT", "BIGINT", "TINYINT", "SMALLINT"].includes(type)) + schema = z.number().int(); + else if (["NUMERIC", "DECIMAL", "FLOAT", "DOUBLE"].includes(type)) + schema = z.number(); + else if (type === "BOOLEAN") schema = z.boolean(); + else if (type === "DATE") schema = z.iso.date(); + else if (type === "TIMESTAMP" || type === "TIMESTAMP_NTZ") + schema = z + .string() + .regex( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})?$/, + ); + else schema = z.string(); + const hint = + type === "BINARY" + ? `${description ? `${description} ` : ""}Hex-encoded string.` + : description; + shape[param] = hint ? schema.describe(hint) : schema; + } + registry[`query.${name}`] = defineTool({ + description: + descriptions.join(" ") || `Run the "${name}" analytics query.`, + schema: z.object(shape), + annotations: obo + ? { effect: "read", requiresUserContext: true } + : { effect: "read" }, + execute: async (args, signal) => { + const params: Record = {}; + let field = ""; + try { + for (const [key, type] of types) { + field = key; + const value = args[key]; + if (type === "BIGINT") params[key] = sql.bigint(value as number); + else if (["INT", "TINYINT", "SMALLINT"].includes(type)) + params[key] = sql.int(value as number); + else if (["NUMERIC", "DECIMAL"].includes(type)) + params[key] = sql.numeric(value as number); + else if (["FLOAT", "DOUBLE"].includes(type)) + params[key] = sql.double(value as number); + else if (type === "BOOLEAN") + params[key] = sql.boolean(value as boolean); + else if (type === "DATE") params[key] = sql.date(value as string); + else if (type === "TIMESTAMP" || type === "TIMESTAMP_NTZ") + params[key] = sql.timestamp(value as string); + else if (type === "BINARY") + params[key] = sql.binary(value as string); + else params[key] = sql.string(value as string); + } + } catch (error) { + return `Invalid arguments for query.${name}: ${field}: ${error instanceof Error ? error.message : String(error)}`; + } + const rows = await run(name, params, signal, { query, isAsUser: obo }); + // shortcut: rows are capped after fetching; push a row limit to the warehouse for large results. + return rows.length > 100 + ? { + rows: rows.slice(0, 100), + rowCount: rows.length, + truncated: true, + note: `Showing the first 100 of ${rows.length} rows; narrow the query with its parameters to see the rest.`, + } + : { rows, rowCount: rows.length }; + }, + }); + } + return registry; +} diff --git a/packages/appkit/src/plugins/analytics/tests/analytics.test.ts b/packages/appkit/src/plugins/analytics/tests/analytics.test.ts index 12ced8c8a..8e424ea87 100644 --- a/packages/appkit/src/plugins/analytics/tests/analytics.test.ts +++ b/packages/appkit/src/plugins/analytics/tests/analytics.test.ts @@ -1,3 +1,9 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { context as otelContext } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; import { createMockRequest, createMockResponse, @@ -22,7 +28,9 @@ import { sql } from "shared"; import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; import { runInCallerContext } from "../../../context"; +import { createRequestScope } from "../../../context/request-scope"; import { ServiceContext } from "../../../context/service-context"; +import { PluginContext } from "../../../core/plugin-context"; import { IdentityExpiredError } from "../../../errors"; import { createMockWorkspaceClient } from "../../../testing"; import { useTestCache } from "../../../testing/test-cache"; @@ -59,6 +67,188 @@ describe("Analytics Plugin", () => { expect(plugin.name).toBe("analytics"); }); + describe("named queries", () => { + let dir: string; + let plugin: AnalyticsPlugin; + let execute: ReturnType; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "analytics-named-")); + plugin = new AnalyticsPlugin(config); + Object.defineProperty((plugin as any).app, "_queriesDir", { value: dir }); + (plugin as any).SQLClient.ensureWarehouseRunning = vi + .fn() + .mockResolvedValue(undefined); + execute = vi.fn().mockImplementation((client) => + Promise.resolve({ + result: { + data: [ + { + client: + client === serviceContextMock.serviceContext.client + ? "app" + : "caller", + }, + ], + }, + }), + ); + (plugin as any).SQLClient.executeStatement = execute; + }); + afterEach(() => rmSync(dir, { recursive: true, force: true })); + const caller = (id: string) => ({ + principal: { type: "user" as const, userId: id }, + client: createMockWorkspaceClient(), + workspaceId: Promise.resolve("workspace"), + }); + + test("runs app queries outside caller scope and OBO queries in caller scope with isolated caches", async () => { + writeFileSync(join(dir, "app.sql"), "SELECT 1"); + writeFileSync(join(dir, "user.obo.sql"), "SELECT 1"); + const first = caller("first"), + second = caller("second"); + expect( + await runInCallerContext(first, () => plugin.runQuery("app")), + ).toEqual([{ client: "app" }]); + expect( + await runInCallerContext(first, () => plugin.runQuery("user")), + ).toEqual([{ client: "caller" }]); + expect( + await runInCallerContext(second, () => plugin.runQuery("user")), + ).toEqual([{ client: "caller" }]); + expect( + await runInCallerContext(first, () => plugin.runQuery("user")), + ).toEqual([{ client: "caller" }]); + expect(execute).toHaveBeenCalledTimes(3); + expect(execute.mock.calls.map((call) => call[0])).toEqual([ + serviceContextMock.serviceContext.client, + first.client, + second.client, + ]); + await expect(plugin.runQuery("user")).rejects.toThrow(/token/i); + await expect(plugin.runQuery("missing")).rejects.toThrow(/missing/i); + expect(plugin.exports().runQuery).toBe(plugin.runQuery); + }); + + test("allows the development OBO fallback", async () => { + writeFileSync(join(dir, "user.obo.sql"), "SELECT 1"); + const manager = new AsyncLocalStorageContextManager().enable(); + otelContext.setGlobalContextManager(manager); + vi.stubEnv("NODE_ENV", "development"); + try { + const scope = createRequestScope( + createMockRequest() as unknown as express.Request, + ); + expect(await scope.run(() => plugin.runQuery("user"))).toEqual([ + { client: "app" }, + ]); + } finally { + otelContext.disable(); + manager.disable(); + vi.unstubAllEnvs(); + } + }); + + test("dispatches query tools through request-created caller scopes", async () => { + writeFileSync(join(dir, "app.sql"), "-- @description app\nSELECT 1"); + writeFileSync( + join(dir, "user.obo.sql"), + "-- @description user\nSELECT 1", + ); + plugin.queries(); + const context = new PluginContext(); + context.registerToolProvider("analytics", plugin); + const req = createMockRequest({ + headers: { + "x-forwarded-access-token": "token", + "x-forwarded-user": "user-a", + }, + }) as unknown as express.Request; + expect( + await context.executeTool(req, "analytics", "query.app", {}), + ).toEqual({ rows: [{ client: "app" }], rowCount: 1 }); + expect( + await context.executeTool(req, "analytics", "query.user", {}), + ).toEqual({ rows: [{ client: "caller" }], rowCount: 1 }); + expect(execute.mock.calls[0][0]).toBe( + serviceContextMock.serviceContext.client, + ); + expect(execute.mock.calls[1][0]).toBe( + serviceContextMock.createUserContextSpy.mock.results[1].value.client, + ); + }); + + test("forwards abort signals to warehouse readiness and SQL", async () => { + writeFileSync(join(dir, "signal.sql"), "SELECT 1"); + const controller = new AbortController(); + await plugin.runQuery("signal", {}, controller.signal); + expect( + (plugin as any).SQLClient.ensureWarehouseRunning, + ).toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({ signal: controller.signal }), + ); + const sqlSignal = execute.mock.calls[0][2] as AbortSignal; + expect(sqlSignal.aborted).toBe(false); + controller.abort(); + expect(sqlSignal.aborted).toBe(true); + await expect( + plugin.runQuery("signal", {}, controller.signal), + ).rejects.toMatchObject({ name: "AbortError" }); + }); + + test("merges selections for dispatch, validates and passes markers to warehouse", async () => { + writeFileSync( + join(dir, "a.sql"), + "-- @description A\n-- @param n INT Number\n-- @param region STRING Region\n-- @param flag BOOLEAN Flag\n-- @param amount DOUBLE Amount\nSELECT :n, :region, :flag, :amount, :workspaceId", + ); + writeFileSync(join(dir, "b.sql"), "-- @description B\nSELECT 2"); + expect(Object.keys(plugin.queries({ only: ["a"] }))).toEqual(["query.a"]); + expect(Object.keys(plugin.queries({ only: ["b"] }))).toEqual(["query.b"]); + expect(await plugin.executeAgentTool("query.a", {})).toMatch( + /Invalid arguments/, + ); + expect(execute).not.toHaveBeenCalled(); + expect( + await plugin.executeAgentTool("query.a", { + n: 4, + region: "west", + flag: true, + amount: 2.5, + }), + ).toEqual({ + rows: [{ client: "app" }], + rowCount: 1, + }); + expect(execute).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + parameters: [ + { name: "n", value: "4", type: "INT" }, + { name: "region", value: "west", type: "STRING" }, + { name: "flag", value: "true", type: "BOOLEAN" }, + { name: "amount", value: "2.5", type: "DOUBLE" }, + { name: "workspaceId", value: "test-workspace-id", type: "STRING" }, + ], + }), + expect.any(AbortSignal), + ); + expect(await plugin.executeAgentTool("query.b", {})).toEqual({ + rows: [{ client: "app" }], + rowCount: 1, + }); + writeFileSync(join(dir, "b.sql"), "-- @description Changed\nSELECT 3"); + expect(plugin.queries({ only: ["b"] })["query.b"].def.description).toBe( + "B", + ); + await expect(plugin.executeAgentTool("query.b", {})).rejects.toThrow( + /changed/, + ); + writeFileSync(join(dir, "b.sql"), "DELETE FROM t"); + await expect(plugin.executeAgentTool("query.b", {})).rejects.toThrow(); + }); + }); + describe("injectRoutes", () => { test("should register the query and metric POST routes", () => { const plugin = new AnalyticsPlugin(config); diff --git a/packages/appkit/src/plugins/analytics/tests/query-tools.test.ts b/packages/appkit/src/plugins/analytics/tests/query-tools.test.ts new file mode 100644 index 000000000..fb3c0d67e --- /dev/null +++ b/packages/appkit/src/plugins/analytics/tests/query-tools.test.ts @@ -0,0 +1,249 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { buildToolkitEntries } from "../../../core/agent/build-toolkit"; +import { executeFromRegistry } from "../../../core/agent/tools/define-tool"; +import { buildQueryTools } from "../query-tools"; + +describe("named query tools", () => { + let dir: string; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "query-tools-")); + }); + afterEach(() => { + rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); + }); + const write = (name: string, sql: string) => + writeFileSync(join(dir, name), sql); + + test("parses descriptions, required schemas, and SQL markers", async () => { + write( + "top.sql", + `-- @description Find sales +-- @description in a region +-- @param region STRING The region +-- @param count INT Minimum count +-- @param big BIGINT Big number +-- @param small SMALLINT +-- @param tiny TINYINT +-- @param amount DECIMAL Total +-- @param numeric NUMERIC +-- @param rate FLOAT +-- @param ratio DOUBLE +-- @param active BOOLEAN Active only +-- @param day DATE A day +-- @param at TIMESTAMP An instant +-- @param local TIMESTAMP_NTZ Local instant +-- @param data BINARY Hex data +-- @param sample STRING = example words +-- @param unused STRING ignored +SELECT :region, :count, :big, :small, :tiny, :amount, :numeric, :rate, :ratio, :active, :day, :at, :local, :data, :sample, :plain, :workspaceId /* :hidden */`, + ); + const run = vi.fn().mockResolvedValue([{ a: 1 }]); + const registry = buildQueryTools(dir, undefined, run); + const entry = buildToolkitEntries("analytics", registry, { prefix: "" })[ + "query.top" + ]; + expect(entry).toMatchObject({ + pluginName: "analytics", + localName: "query.top", + def: { description: "Find sales in a region" }, + annotations: { effect: "read" }, + }); + const schema = entry.def.parameters as any; + expect(schema.required).toEqual([ + "region", + "count", + "big", + "small", + "tiny", + "amount", + "numeric", + "rate", + "ratio", + "active", + "day", + "at", + "local", + "data", + "sample", + "plain", + ]); + expect(schema.properties).toMatchObject({ + region: { type: "string", description: "The region" }, + count: { type: "integer" }, + amount: { type: "number" }, + active: { type: "boolean" }, + day: { type: "string", format: "date" }, + at: { type: "string", pattern: expect.any(String) }, + data: { type: "string", description: "Hex data Hex-encoded string." }, + sample: { type: "string" }, + plain: { type: "string" }, + }); + expect(schema.properties.sample.description).toBeUndefined(); + const args = { + region: "US", + count: 3, + big: 4, + small: 5, + tiny: 6, + amount: 1.5, + numeric: 2.5, + rate: 0.5, + ratio: 0.25, + active: true, + day: "2024-01-01", + at: "2024-01-01T00:00:00Z", + local: "2024-01-01T00:00:00", + data: "00ff", + sample: "x", + plain: "y", + }; + expect(await executeFromRegistry(registry, "query.top", args)).toEqual({ + rows: [{ a: 1 }], + rowCount: 1, + }); + expect(run).toHaveBeenCalledWith( + "top", + expect.objectContaining({ + region: { __sql_type: "STRING", value: "US" }, + count: { __sql_type: "INT", value: "3" }, + big: { __sql_type: "BIGINT", value: "4" }, + amount: { __sql_type: "NUMERIC", value: "1.5" }, + rate: { __sql_type: "DOUBLE", value: "0.5" }, + active: { __sql_type: "BOOLEAN", value: "true" }, + data: { __sql_type: "STRING", value: "00FF" }, + }), + undefined, + expect.objectContaining({ isAsUser: false }), + ); + expect(await executeFromRegistry(registry, "query.top", {})).toMatch( + /Invalid arguments/i, + ); + expect(run).toHaveBeenCalledTimes(1); + }); + + test("returns correctable errors for invalid marker values without running the query", async () => { + write( + "values.sql", + `-- @description Input values +-- @param at TIMESTAMP An instant +-- @param local TIMESTAMP_NTZ A local instant +-- @param bytes BINARY +-- @param count INT +-- @param big BIGINT +SELECT :at, :local, :bytes, :count, :big`, + ); + const run = vi.fn().mockResolvedValue([]); + const registry = buildQueryTools(dir, undefined, run); + const entry = buildToolkitEntries("analytics", registry, { prefix: "" })[ + "query.values" + ]; + const schema = entry.def.parameters as any; + expect(schema.properties.bytes.description).toBe("Hex-encoded string."); + const timestampPattern = new RegExp(schema.properties.at.pattern); + expect(timestampPattern.test("2024-01-01T12:00")).toBe(false); + expect(timestampPattern.test("2024-01-01T12:00:00.123456789+01:00")).toBe( + true, + ); + const valid = { + at: "2024-01-01T12:00:00Z", + local: "2024-01-01T12:00:00", + bytes: "00ff", + count: 1, + big: 2, + }; + for (const [field, value] of [ + ["at", "2024-01-01T12:00"], + ["local", "2024-01-01T12:00"], + ["bytes", "not hex"], + ["count", 2147483648], + ["big", Number.MAX_SAFE_INTEGER + 1], + ] as const) { + expect( + await executeFromRegistry(registry, "query.values", { + ...valid, + [field]: value, + }), + ).toMatch(new RegExp(`^Invalid arguments for query\\.values: ${field}:`)); + } + expect( + await executeFromRegistry(registry, "query.values", { + ...valid, + bytes: "not hex", + }), + ).toBe( + "Invalid arguments for query.values: bytes: sql.binary() expects Uint8Array, ArrayBuffer, or hex string, got invalid hex: not hex", + ); + expect( + await executeFromRegistry(registry, "query.values", { + ...valid, + count: 2147483648, + }), + ).toContain( + "Invalid arguments for query.values: count: sql.int() value 2147483648 is outside INT (32-bit signed) range", + ); + expect(run).not.toHaveBeenCalled(); + run.mockRejectedValueOnce(new Error("warehouse unavailable")); + await expect( + executeFromRegistry(registry, "query.values", valid), + ).rejects.toThrow("warehouse unavailable"); + }); + + test("selects OBO, warns for missing descriptions and skips unsafe SQL", () => { + write("a.sql", "SELECT 1"); + write("a.obo.sql", "SELECT 2"); + write("bad.sql", "DELETE FROM t"); + write("invalid.name.sql", "SELECT 3"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const registry = buildQueryTools(dir, undefined, vi.fn()); + expect(Object.keys(registry)).toEqual(["query.a"]); + expect(registry["query.a"].description).toBe( + 'Run the "a" analytics query.', + ); + expect(registry["query.a"].annotations).toEqual({ + effect: "read", + requiresUserContext: true, + }); + expect(warn.mock.calls.flat().join(" ")).toContain("no @description"); + expect(warn.mock.calls.flat().join(" ")).toContain( + "Both a.obo.sql and a.sql", + ); + expect(warn.mock.calls.flat().join(" ")).toContain("Skipping query bad"); + expect(() => buildQueryTools(dir, { only: ["bad"] }, vi.fn())).toThrow(); + expect(() => buildQueryTools(dir, { only: ["missing"] }, vi.fn())).toThrow( + /missing/, + ); + expect(Object.keys(buildQueryTools(dir, { only: [] }, vi.fn()))).toEqual( + [], + ); + }); + + test("fails closed for parameter names Zod cannot preserve", () => { + write("unsupported.sql", "SELECT :__proto__"); + expect(Object.keys(buildQueryTools(dir, undefined, vi.fn()))).toEqual([]); + expect(() => + buildQueryTools(dir, { only: ["unsupported"] }, vi.fn()), + ).toThrow(/__proto__/); + }); + + test("caps rows and explains truncation", async () => { + write("many.sql", "-- @description Lots of rows\nSELECT 1"); + const rows = Array.from({ length: 101 }, (_, n) => ({ n })); + const registry = buildQueryTools( + dir, + undefined, + vi.fn().mockResolvedValue(rows), + ); + expect(await executeFromRegistry(registry, "query.many", {})).toEqual({ + rows: rows.slice(0, 100), + rowCount: 101, + truncated: true, + note: "Showing the first 100 of 101 rows; narrow the query with its parameters to see the rest.", + }); + }); +}); From a635fd2c4e46d4ba254b044ed3d3f91de97644da Mon Sep 17 00:00:00 2001 From: "mario.cadenas" Date: Thu, 3 Dec 2026 10:07:10 +0000 Subject: [PATCH 3/3] chore: re-run the check now that pnpm is on the check shell's PATH Co-authored-by: Isaac Signed-off-by: mario.cadenas