@databricks/appkit 0.82.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/CLAUDE.md +21 -1
  2. package/dist/agents/databricks.d.ts +15 -3
  3. package/dist/agents/databricks.d.ts.map +1 -1
  4. package/dist/agents/databricks.js +25 -8
  5. package/dist/agents/databricks.js.map +1 -1
  6. package/dist/appkit/package.js +1 -1
  7. package/dist/beta.d.ts +2 -2
  8. package/dist/cache/index.d.ts.map +1 -1
  9. package/dist/cache/index.js +6 -1
  10. package/dist/cache/index.js.map +1 -1
  11. package/dist/cli/commands/agent/eval.js +1 -1
  12. package/dist/cli/commands/generate-types.js +1 -1
  13. package/dist/cli/commands/plugin/sync/sync.js +28 -15
  14. package/dist/cli/commands/plugin/sync/sync.js.map +1 -1
  15. package/dist/cli/commands/registry/add.js +3 -11
  16. package/dist/cli/commands/registry/add.js.map +1 -1
  17. package/dist/cli/commands/registry/config-writer.js +1 -1
  18. package/dist/connectors/lakebase/index.js +1 -1
  19. package/dist/connectors/lakebase/routing-pool.d.ts +1 -1
  20. package/dist/connectors/lakebase/routing-pool.d.ts.map +1 -1
  21. package/dist/connectors/lakebase/routing-pool.js +6 -12
  22. package/dist/connectors/lakebase/routing-pool.js.map +1 -1
  23. package/dist/context/caller-context.d.ts +25 -0
  24. package/dist/context/caller-context.d.ts.map +1 -0
  25. package/dist/context/caller-context.js +21 -0
  26. package/dist/context/caller-context.js.map +1 -0
  27. package/dist/context/deprecation.js +14 -0
  28. package/dist/context/deprecation.js.map +1 -0
  29. package/dist/context/execution-context.d.ts +40 -4
  30. package/dist/context/execution-context.d.ts.map +1 -1
  31. package/dist/context/execution-context.js +87 -33
  32. package/dist/context/execution-context.js.map +1 -1
  33. package/dist/context/index.d.ts +3 -2
  34. package/dist/context/index.js +3 -1
  35. package/dist/context/request-scope.d.ts +2 -0
  36. package/dist/context/request-scope.js +39 -0
  37. package/dist/context/request-scope.js.map +1 -0
  38. package/dist/context/resource-capabilities.js +59 -0
  39. package/dist/context/resource-capabilities.js.map +1 -0
  40. package/dist/context/scoped-api.js +104 -0
  41. package/dist/context/scoped-api.js.map +1 -0
  42. package/dist/context/service-context.d.ts +18 -12
  43. package/dist/context/service-context.d.ts.map +1 -1
  44. package/dist/context/service-context.js +45 -55
  45. package/dist/context/service-context.js.map +1 -1
  46. package/dist/context/user-context.d.ts +16 -22
  47. package/dist/context/user-context.d.ts.map +1 -1
  48. package/dist/context/user-context.js +57 -3
  49. package/dist/context/user-context.js.map +1 -1
  50. package/dist/core/agent/load-agents.d.ts.map +1 -1
  51. package/dist/core/agent/load-agents.js +5 -2
  52. package/dist/core/agent/load-agents.js.map +1 -1
  53. package/dist/core/agent/run-agent.d.ts +19 -6
  54. package/dist/core/agent/run-agent.d.ts.map +1 -1
  55. package/dist/core/agent/run-agent.js +53 -17
  56. package/dist/core/agent/run-agent.js.map +1 -1
  57. package/dist/core/agent/types.d.ts +18 -1
  58. package/dist/core/agent/types.d.ts.map +1 -1
  59. package/dist/core/agent/types.js.map +1 -1
  60. package/dist/core/appkit.d.ts +4 -3
  61. package/dist/core/appkit.d.ts.map +1 -1
  62. package/dist/core/appkit.js +34 -11
  63. package/dist/core/appkit.js.map +1 -1
  64. package/dist/core/plugin-context.d.ts +14 -15
  65. package/dist/core/plugin-context.d.ts.map +1 -1
  66. package/dist/core/plugin-context.js +24 -14
  67. package/dist/core/plugin-context.js.map +1 -1
  68. package/dist/errors/base.d.ts +2 -2
  69. package/dist/errors/base.js +2 -2
  70. package/dist/errors/base.js.map +1 -1
  71. package/dist/errors/identity-expired.d.ts +14 -0
  72. package/dist/errors/identity-expired.d.ts.map +1 -0
  73. package/dist/errors/identity-expired.js +33 -0
  74. package/dist/errors/identity-expired.js.map +1 -0
  75. package/dist/errors/index.js +1 -0
  76. package/dist/index.d.ts +12 -6
  77. package/dist/index.js +7 -2
  78. package/dist/logging/logger.js +1 -1
  79. package/dist/plugin/execution-result.d.ts +4 -1
  80. package/dist/plugin/execution-result.d.ts.map +1 -1
  81. package/dist/plugin/interceptors/telemetry.js +6 -4
  82. package/dist/plugin/interceptors/telemetry.js.map +1 -1
  83. package/dist/plugin/plugin.d.ts +14 -22
  84. package/dist/plugin/plugin.d.ts.map +1 -1
  85. package/dist/plugin/plugin.js +42 -123
  86. package/dist/plugin/plugin.js.map +1 -1
  87. package/dist/plugins/agents/agents.d.ts +13 -1
  88. package/dist/plugins/agents/agents.d.ts.map +1 -1
  89. package/dist/plugins/agents/agents.js +65 -15
  90. package/dist/plugins/agents/agents.js.map +1 -1
  91. package/dist/plugins/agents/auth-mode.js +42 -0
  92. package/dist/plugins/agents/auth-mode.js.map +1 -0
  93. package/dist/plugins/agents/index.d.ts +1 -1
  94. package/dist/plugins/agents/mlflow.js +11 -3
  95. package/dist/plugins/agents/mlflow.js.map +1 -1
  96. package/dist/plugins/agents/tool-dispatch.js +9 -1
  97. package/dist/plugins/agents/tool-dispatch.js.map +1 -1
  98. package/dist/plugins/ai-search/ai-search.d.ts +1 -1
  99. package/dist/plugins/ai-search/ai-search.d.ts.map +1 -1
  100. package/dist/plugins/ai-search/ai-search.js +4 -4
  101. package/dist/plugins/ai-search/ai-search.js.map +1 -1
  102. package/dist/plugins/analytics/analytics.d.ts +3 -3
  103. package/dist/plugins/analytics/analytics.d.ts.map +1 -1
  104. package/dist/plugins/analytics/analytics.js +9 -7
  105. package/dist/plugins/analytics/analytics.js.map +1 -1
  106. package/dist/plugins/database/crud/contract.js +2 -2
  107. package/dist/plugins/database/crud/contract.js.map +1 -1
  108. package/dist/plugins/database/database.d.ts +1 -1
  109. package/dist/plugins/files/plugin.d.ts +21 -15
  110. package/dist/plugins/files/plugin.d.ts.map +1 -1
  111. package/dist/plugins/files/plugin.js +50 -29
  112. package/dist/plugins/files/plugin.js.map +1 -1
  113. package/dist/plugins/genie/genie.d.ts +10 -1
  114. package/dist/plugins/genie/genie.d.ts.map +1 -1
  115. package/dist/plugins/genie/genie.js +12 -3
  116. package/dist/plugins/genie/genie.js.map +1 -1
  117. package/dist/plugins/genie/manifest.js +1 -0
  118. package/dist/plugins/jobs/plugin.d.ts +1 -1
  119. package/dist/plugins/jobs/plugin.js +2 -2
  120. package/dist/plugins/jobs/plugin.js.map +1 -1
  121. package/dist/plugins/lakebase/lakebase.d.ts +11 -18
  122. package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
  123. package/dist/plugins/lakebase/lakebase.js +16 -21
  124. package/dist/plugins/lakebase/lakebase.js.map +1 -1
  125. package/dist/plugins/server/client-config-sanitizer.js +1 -4
  126. package/dist/plugins/server/client-config-sanitizer.js.map +1 -1
  127. package/dist/plugins/server/dev-obo-middleware.js +60 -0
  128. package/dist/plugins/server/dev-obo-middleware.js.map +1 -0
  129. package/dist/plugins/server/index.d.ts +1 -1
  130. package/dist/plugins/server/index.d.ts.map +1 -1
  131. package/dist/plugins/server/index.js +3 -0
  132. package/dist/plugins/server/index.js.map +1 -1
  133. package/dist/plugins/serving/manifest.js +1 -0
  134. package/dist/plugins/serving/serving.d.ts +1 -1
  135. package/dist/plugins/serving/serving.js +6 -6
  136. package/dist/plugins/serving/serving.js.map +1 -1
  137. package/dist/resources/index.d.ts +1 -0
  138. package/dist/resources/index.js +3 -0
  139. package/dist/resources/warehouse.d.ts +16 -0
  140. package/dist/resources/warehouse.d.ts.map +1 -0
  141. package/dist/resources/warehouse.js +93 -0
  142. package/dist/resources/warehouse.js.map +1 -0
  143. package/dist/schemas/manifest.d.ts +44 -1
  144. package/dist/schemas/manifest.d.ts.map +1 -1
  145. package/dist/schemas/manifest.js +122 -3
  146. package/dist/schemas/manifest.js.map +1 -1
  147. package/dist/shared/src/dev-obo.js +86 -0
  148. package/dist/shared/src/dev-obo.js.map +1 -0
  149. package/dist/shared/src/index.d.ts +1 -1
  150. package/dist/shared/src/plugin.d.ts +12 -1
  151. package/dist/shared/src/plugin.d.ts.map +1 -1
  152. package/dist/shared/src/schemas/manifest.d.ts +17 -0
  153. package/dist/shared/src/schemas/manifest.d.ts.map +1 -1
  154. package/dist/shared/src/schemas/manifest.js +53 -3
  155. package/dist/shared/src/schemas/manifest.js.map +1 -1
  156. package/dist/stream/stream-manager.d.ts.map +1 -1
  157. package/dist/stream/stream-manager.js +5 -2
  158. package/dist/stream/stream-manager.js.map +1 -1
  159. package/dist/telemetry/execution-span-processor.js +21 -0
  160. package/dist/telemetry/execution-span-processor.js.map +1 -0
  161. package/dist/telemetry/telemetry-manager.js +2 -1
  162. package/dist/telemetry/telemetry-manager.js.map +1 -1
  163. package/dist/testing/create-test-app.d.ts +2 -2
  164. package/dist/testing/create-test-app.js +2 -2
  165. package/dist/testing/create-test-app.js.map +1 -1
  166. package/dist/testing/fixtures.d.ts +3 -2
  167. package/dist/testing/fixtures.d.ts.map +1 -1
  168. package/dist/testing/fixtures.js +21 -14
  169. package/dist/testing/fixtures.js.map +1 -1
  170. package/dist/testing/reset-singletons.js +1 -1
  171. package/dist/testing/test-plugin-context.d.ts +3 -12
  172. package/dist/testing/test-plugin-context.d.ts.map +1 -1
  173. package/dist/testing/test-plugin-context.js +24 -16
  174. package/dist/testing/test-plugin-context.js.map +1 -1
  175. package/dist/utils/is-plain-object.js +11 -0
  176. package/dist/utils/is-plain-object.js.map +1 -0
  177. package/docs/api/appkit/Class.AppKitError.md +2 -1
  178. package/docs/api/appkit/Class.AuthenticationError.md +1 -1
  179. package/docs/api/appkit/Class.ConfigurationError.md +1 -1
  180. package/docs/api/appkit/Class.ConnectionError.md +1 -1
  181. package/docs/api/appkit/Class.DatabaseValidationError.md +1 -1
  182. package/docs/api/appkit/Class.ExecutionError.md +1 -1
  183. package/docs/api/appkit/Class.IdentityExpiredError.md +190 -0
  184. package/docs/api/appkit/Class.InitializationError.md +1 -1
  185. package/docs/api/appkit/Class.Plugin.md +9 -13
  186. package/docs/api/appkit/Class.ServerError.md +1 -1
  187. package/docs/api/appkit/Class.ServiceContext.md +169 -0
  188. package/docs/api/appkit/Class.TunnelError.md +1 -1
  189. package/docs/api/appkit/Class.ValidationError.md +1 -1
  190. package/docs/api/appkit/Function.createApp.md +12 -12
  191. package/docs/api/appkit/Function.getCallerContext.md +12 -0
  192. package/docs/api/appkit/Function.getCurrentActorId.md +12 -0
  193. package/docs/api/appkit/Function.getCurrentPrincipalKey.md +12 -0
  194. package/docs/api/appkit/Function.getCurrentUserId.md +14 -0
  195. package/docs/api/appkit/Function.getExecutionContext.md +5 -3
  196. package/docs/api/appkit/Function.getUserContext.md +16 -0
  197. package/docs/api/appkit/Function.getWarehouseId.md +20 -0
  198. package/docs/api/appkit/Function.isInUserContext.md +12 -0
  199. package/docs/api/appkit/Function.isUserContext.md +20 -0
  200. package/docs/api/appkit/Function.runAgent.md +1 -1
  201. package/docs/api/appkit/Function.runInCallerContext.md +27 -0
  202. package/docs/api/appkit/Function.runInUserContext.md +29 -0
  203. package/docs/api/appkit/Interface.AgentDefinition.md +11 -0
  204. package/docs/api/appkit/Interface.AgentsPluginConfig.md +11 -0
  205. package/docs/api/appkit/Interface.CallerContext.md +54 -0
  206. package/docs/api/appkit/Interface.IndexConfig.md +1 -1
  207. package/docs/api/appkit/Interface.PluginManifest.md +33 -2
  208. package/docs/api/appkit/Interface.RegisteredAgent.md +11 -0
  209. package/docs/api/appkit/Interface.RunAgentInput.md +45 -1
  210. package/docs/api/appkit/TypeAlias.AgentAuth.md +8 -0
  211. package/docs/api/appkit/TypeAlias.AppKitApi.md +35 -0
  212. package/docs/api/appkit/TypeAlias.CallerPrincipal.md +13 -0
  213. package/docs/api/appkit/TypeAlias.ExecutionContext.md +9 -0
  214. package/docs/api/appkit/TypeAlias.ExecutionResult.md +65 -0
  215. package/docs/api/appkit/TypeAlias.ScopedPluginMap.md +12 -0
  216. package/docs/api/appkit/TypeAlias.UserContext.md +109 -0
  217. package/docs/api/appkit/TypeAlias.UserScopedApp.md +39 -0
  218. package/docs/api/appkit.md +20 -0
  219. package/docs/plugins/agents.md +45 -0
  220. package/docs/plugins/analytics.md +8 -0
  221. package/docs/plugins/execution-context.md +101 -50
  222. package/docs/plugins/lakebase.md +6 -82
  223. package/llms.txt +21 -1
  224. package/package.json +1 -1
  225. package/sbom.cdx.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"analytics.js","names":["manifest"],"sources":["../../../src/plugins/analytics/analytics.ts"],"sourcesContent":["import type express from \"express\";\nimport {\n type AgentToolDefinition,\n type AnalyticsSseMessage,\n type IAppRouter,\n makeResultMessage,\n type PluginExecuteConfig,\n type SQLTypeMarker,\n type StreamExecutionSettings,\n type ToolProvider,\n} from \"shared\";\nimport { z } from \"zod\";\n\nimport { SQLWarehouseConnector } from \"../../connectors\";\nimport {\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n type WarehouseStatusUpdate,\n} from \"../../connectors/sql-warehouse/client\";\nimport { getWarehouseId, getWorkspaceClient } from \"../../context\";\nimport { buildToolkitEntries } from \"../../core/agent/build-toolkit\";\nimport {\n defineTool,\n executeFromRegistry,\n toolsFromRegistry,\n} from \"../../core/agent/tools/define-tool\";\nimport { assertReadOnlySql } from \"../../core/agent/tools/sql-policy\";\nimport { AppKitError, ExecutionError } from \"../../errors\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } from \"../../registry\";\nimport type { WorkspaceClient } from \"../../workspace-client\";\nimport { queryDefaults } from \"./defaults\";\nimport manifest from \"./manifest.json\";\nimport {\n buildMetricSql,\n composeMetricCacheKey,\n deriveMetricExecutorKey,\n loadMetricMetadata,\n loadMetricRegistry,\n METRIC_METADATA_FILE,\n selectMetricMetadata,\n validateMetricRequest,\n} from \"./metric\";\nimport { QueryProcessor } from \"./query\";\nimport {\n type ArrowCapability,\n deliverArrowBytes,\n deliverJsonResult,\n type QueryExecutor,\n} from \"./result-delivery\";\nimport {\n type AnalyticsQueryResponse,\n type AnalyticsStreamMessage,\n type IAnalyticsConfig,\n type IAnalyticsQueryRequest,\n type MetricRegistration,\n normalizeAnalyticsFormat,\n type WarehouseStatus,\n} from \"./types\";\n\nconst logger = createLogger(\"analytics\");\n\n/**\n * Bridges a callback-emitting async function into an async iterable.\n *\n * `start(emit)` runs concurrently; every value passed to `emit` is yielded\n * in order. The iterable completes when `start`'s promise resolves and\n * re-throws (after draining) if it rejects. Lets a callback-based progress\n * API (e.g. SQL warehouse readiness) be consumed with `for await`.\n */\nasync function* streamCallbacks<T>(\n start: (emit: (value: T) => void) => Promise<void>,\n): AsyncGenerator<T, void, unknown> {\n const queue: T[] = [];\n let wake: (() => void) | null = null;\n let settled = false;\n let error: unknown = null;\n\n const notify = (): void => {\n wake?.();\n wake = null;\n };\n\n // The .then(_, err => ...) chain converts a rejection into a resolved\n // promise; the consumer surfaces `error` after draining the queue.\n void start((value) => {\n queue.push(value);\n notify();\n }).then(\n () => {\n settled = true;\n notify();\n },\n (err) => {\n error = err;\n settled = true;\n notify();\n },\n );\n\n while (!settled || queue.length > 0) {\n while (queue.length > 0) yield queue.shift() as T;\n if (settled) break;\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n if (error) throw error;\n}\n\nexport class AnalyticsPlugin extends Plugin implements ToolProvider {\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = defineManifest<\"analytics\">(manifest);\n\n protected static description = \"Analytics plugin for data analysis\";\n declare protected config: IAnalyticsConfig;\n\n // analytics services\n private SQLClient: SQLWarehouseConnector;\n private queryProcessor: QueryProcessor;\n\n /**\n * In-process memo of which arrow delivery mode each warehouse supports\n * (keyed by warehouse id). A standard warehouse rejects `INLINE+ARROW_STREAM`\n * on every query, so once learned we skip that doomed probe; Reyden stays\n * `\"inline\"`. Capability is a property of the warehouse, not the user, so it\n * is not user-scoped. Bounded by the number of distinct warehouses a process\n * talks to (effectively one).\n */\n private _arrowCapability = new Map<string, ArrowCapability>();\n\n constructor(config: IAnalyticsConfig) {\n super(config);\n this.config = config;\n this.queryProcessor = new QueryProcessor();\n\n this.SQLClient = new SQLWarehouseConnector({\n timeout: config.timeout,\n telemetry: config.telemetry,\n });\n }\n\n injectRoutes(router: IAppRouter) {\n this.route<AnalyticsQueryResponse>(router, {\n name: \"query\",\n method: \"post\",\n path: \"/query/:query_key\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleQueryRoute(req, res);\n },\n });\n\n // Metric-view route. Registered parallel to `/query`\n // measures a registered UC Metric View over the same SSE envelope.\n this.route(router, {\n name: \"metric\",\n method: \"post\",\n path: \"/metric/:key\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleMetricRoute(req, res);\n },\n });\n\n // Column-names fallback for very wide Arrow schemas whose names don't fit\n // in the `X-Appkit-Arrow-Columns` response header.\n // The client hits this with the statement id from `X-Appkit-Arrow-Columns-Ref`.\n this.route(router, {\n name: \"arrow-columns\",\n method: \"get\",\n path: \"/columns/:statementId\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleColumnsRoute(req, res);\n },\n });\n }\n\n /**\n * Column-names fallback endpoint. Re-derives the real column names from the\n * statement's result manifest (stateless — no server cache), for the client\n * to relabel a positional Arrow schema when the names were too large for the\n * response header.\n */\n async _handleColumnsRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { statementId } = req.params;\n const columns = await this._resolveColumnNames(req, statementId);\n if (columns && columns.length > 0) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.json({ columns });\n return;\n }\n res.status(404).json({\n error: \"Column names unavailable\",\n plugin: this.name,\n });\n }\n\n /**\n * Resolve a statement's real column names, trying the user's identity first\n * (required for `.obo.sql` statements, which the service principal cannot\n * `getStatement`) then falling back to the service principal (for\n * SP-executed statements). Returns undefined if neither identity can read it,\n * so the client falls back to the raw positional Arrow schema names.\n */\n private async _resolveColumnNames(\n req: express.Request,\n statementId: string,\n ): Promise<string[] | undefined> {\n const attempts: Array<() => Promise<string[] | undefined>> = [\n () => this.asUser(req)._getColumnNames(statementId),\n () => this._getColumnNames(statementId),\n ];\n for (const attempt of attempts) {\n try {\n const columns = await attempt();\n if (columns && columns.length > 0) return columns;\n } catch (error) {\n logger.debug(\n \"Arrow column-names lookup attempt failed for %s: %O\",\n statementId,\n error,\n );\n }\n }\n return undefined;\n }\n\n /**\n * Fetch column names in the current execution context. Proxied by `asUser`,\n * so `getWorkspaceClient()` resolves to the user's client when invoked via\n * `this.asUser(req)` and the service principal's otherwise.\n */\n async _getColumnNames(statementId: string): Promise<string[] | undefined> {\n return this.SQLClient.getColumnNames(getWorkspaceClient(), statementId);\n }\n\n /**\n * Handle SQL query execution requests.\n * When called via asUser(req), uses the user's Databricks credentials.\n */\n async _handleQueryRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { query_key } = req.params;\n const { parameters, format: rawFormat = \"JSON_ARRAY\" } =\n req.body as IAnalyticsQueryRequest;\n\n if (\n rawFormat !== \"JSON_ARRAY\" &&\n rawFormat !== \"ARROW_STREAM\" &&\n rawFormat !== \"JSON\" &&\n rawFormat !== \"ARROW\"\n ) {\n res.status(400).json({\n error: `Invalid format: ${String(rawFormat)}. Expected \"JSON_ARRAY\" or \"ARROW_STREAM\".`,\n });\n return;\n }\n\n const format = normalizeAnalyticsFormat(rawFormat);\n\n // Request-scoped logging with WideEvent tracking\n logger.debug(req, \"Executing query: %s (format=%s)\", query_key, format);\n\n const event = logger.event(req);\n event?.setComponent(\"analytics\", \"executeQuery\").setContext(\"analytics\", {\n query_key,\n format,\n parameter_count: parameters ? Object.keys(parameters).length : 0,\n plugin: this.name,\n });\n\n if (!query_key) {\n res.status(400).json({ error: \"query_key is required\" });\n return;\n }\n\n const queryResult = await this.app.getAppQuery(\n query_key,\n req,\n this.devFileReader,\n );\n\n if (!queryResult) {\n res.status(404).json({ error: \"Query not found\" });\n return;\n }\n\n const { query, isAsUser } = queryResult;\n\n // ARROW_STREAM streams the raw Arrow IPC bytes back as the HTTP response\n // body — no SSE, no server-side stash, no second /arrow-result request.\n // INLINE attachments are piped straight through (the bytes are already in\n // hand from executeStatement); a warehouse that refuses INLINE falls back\n // to EXTERNAL_LINKS and streams those chunks. JSON keeps the SSE path\n // below (it carries warehouse-readiness progress + cached rows).\n if (format === \"ARROW_STREAM\") {\n await this._handleArrowStreamQuery(\n req,\n res,\n query_key,\n query,\n isAsUser,\n parameters,\n );\n return;\n }\n\n // get execution context - user-scoped if .obo.sql, otherwise service principal\n const executor = isAsUser ? this.asUser(req) : this;\n const executorKey = isAsUser ? this.resolveUserId(req) : \"global\";\n\n const hashedQuery = this.queryProcessor.hashQuery(query);\n\n const cacheConfig = {\n ...queryDefaults.cache,\n cacheKey: [\n \"analytics:query\",\n query_key,\n JSON.stringify(parameters),\n format,\n hashedQuery,\n executorKey,\n ],\n };\n\n // Cache/retry/timeout are scoped to the SQL execution itself (inner\n // `execute`) so the warehouse-readiness phase isn't subject to retries\n // and the generator value never leaks into the cache.\n const sqlConfig: PluginExecuteConfig = {\n ...queryDefaults,\n cache: cacheConfig,\n };\n\n // Outer stream: no cache/retry — `executeStream` would otherwise wrap the\n // generator factory and cache the generator object itself. Telemetry +\n // user-scoped trace context still apply.\n const streamExecutionSettings: StreamExecutionSettings = {\n default: {\n cache: { enabled: false },\n retry: { enabled: false },\n },\n };\n\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStartWarehouse = this.config.autoStartWarehouse ?? true;\n\n const self = this;\n\n await executor.executeStream(\n res,\n async function* (\n signal,\n ): AsyncGenerator<AnalyticsStreamMessage, void, unknown> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n // Stream warehouse-readiness updates as SSE events, then run SQL.\n const readinessUpdates = streamCallbacks<WarehouseStatusUpdate>(\n (emit) =>\n self.SQLClient.ensureWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart: autoStartWarehouse,\n onStatus: emit,\n },\n ),\n );\n for await (const update of readinessUpdates) {\n yield {\n type: \"warehouse_status\",\n status: {\n state: update.state as WarehouseStatus[\"state\"],\n elapsedMs: update.elapsedMs,\n },\n };\n }\n\n // `execute()` reduces a thrown error to `{ status, message }`,\n // dropping the rich fields (`errorCode`, `clientMessage`) the\n // fallback's `ExecutionError`s carry. Capture the original here so\n // we can re-throw it intact — the SSE error path\n // (`StreamManager`) reads `errorCode`/`clientMessage` off it.\n let originalError: unknown;\n const sqlResult = await executor.execute(\n async (sig) => {\n try {\n const processedParams =\n await self.queryProcessor.processQueryParams(query, parameters);\n // JSON_ARRAY path: tries INLINE + JSON_ARRAY and, if the\n // warehouse only accepts ARROW_STREAM for INLINE, retries as\n // ARROW_STREAM and decodes server-side — returning the SSE\n // `result` message with plain rows. (ARROW_STREAM requests are\n // handled earlier via `_handleArrowStreamQuery`.)\n return await self._executeJsonArrayPath(\n executor,\n query,\n processedParams,\n sig,\n );\n } catch (err) {\n originalError = err;\n throw err;\n }\n },\n { default: sqlConfig },\n executorKey,\n );\n\n if (!sqlResult.ok) {\n const msg = sqlResult.message;\n const lower = msg.toLowerCase();\n if (\n lower.includes(\"operation was aborted\") ||\n lower.includes(\"the request was aborted\") ||\n lower.includes(\"statement was canceled\")\n ) {\n const err = new DOMException(\n lower.includes(\"canceled\") ? msg : \"The operation was aborted.\",\n \"AbortError\",\n );\n throw err;\n }\n // Re-throw the original error so its structured `errorCode` (e.g.\n // RESULT_TOO_LARGE_FOR_JSON_FALLBACK) and sanitized `clientMessage`\n // survive to the SSE error payload. Fall back to a generic\n // statement failure only if the original wasn't an AppKitError.\n if (originalError instanceof AppKitError) {\n throw originalError;\n }\n const inner = msg.startsWith(\"Statement failed: \")\n ? msg.slice(\"Statement failed: \".length)\n : msg;\n throw ExecutionError.statementFailed(inner);\n }\n\n yield sqlResult.data as AnalyticsStreamMessage;\n },\n streamExecutionSettings,\n executorKey,\n );\n }\n\n /**\n * Handle metric-view execution requests (`POST /api/analytics/metric/:key`).\n *\n * Mirrors {@link _handleQueryRoute}'s JSON SSE path: the outer\n * `executeStream` disables cache/retry and streams warehouse-readiness\n * (`warehouse_status`) events, then the inner `execute` builds the metric SQL\n * and delivers rows through {@link deliverJsonResult} as a `result` message.\n * The `originalError` re-throw discipline preserves each error's structured\n * `errorCode`/`clientMessage` for the SSE error payload.\n *\n * Lane dispatch is driven by the registration: an SP-lane metric runs as the\n * app service principal (shared cache); an OBO-lane metric runs\n * on-behalf-of the requesting user via `asUser(req)` (per-user cache keyed by\n * a hash of the user identity).\n */\n async _handleMetricRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { key } = req.params;\n\n logger.debug(req, \"Executing metric: %s\", key);\n\n const event = logger.event(req);\n event?.setComponent(\"analytics\", \"executeMetric\").setContext(\"analytics\", {\n metric_key: key,\n plugin: this.name,\n });\n\n if (!key) {\n res.status(400).json({ error: \"metric key is required\" });\n return;\n }\n\n // Resolve the registry from disk: read + parse `definitions.json` once per\n // request (no memoization). Reads through the plugin's shared `this.app`\n // (the base `Plugin`'s `AppManager`) from `config/metric-views/` under the\n // process cwd, so this is dev-tunnel aware and inherits the traversal\n // guard — the same mechanism as the sibling `.sql` query path.\n let registry: Record<string, MetricRegistration>;\n try {\n registry = await loadMetricRegistry(this.app, req, this.devFileReader);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn(req, \"Failed to load metric registry: %s\", reason);\n event?.setContext(\"analytics\", {\n metric_registry_load_error: reason,\n });\n res.status(503).json({\n error: \"Metric registry not available\",\n code: \"METRIC_REGISTRY_LOAD_FAILED\",\n });\n return;\n }\n\n // Own-property lookup: never resolve `key` to an inherited `Object.prototype` member.\n const registration = Object.hasOwn(registry, key)\n ? registry[key]\n : undefined;\n if (!registration) {\n // Don't echo the user-supplied `key` back in the public response.\n event?.setContext(\"analytics\", { unknown_metric_key: key });\n res.status(404).json({ error: \"Metric not found\" });\n return;\n }\n\n // Validate the body on the canonical error path.\n // `validateMetricRequest` throws a `ValidationError` (400) whose message names only field paths, never raw values.\n let request: ReturnType<typeof validateMetricRequest>;\n try {\n request = validateMetricRequest(req.body ?? {});\n } catch (err) {\n if (err instanceof AppKitError) {\n res.status(err.statusCode).json({ error: err.message, code: err.code });\n return;\n }\n event?.setContext(\"analytics\", {\n unexpected_error: err instanceof Error ? err.message : String(err),\n metric_key: key,\n });\n logger.warn(\n req,\n \"Unexpected throw during metric request validation for %s: %s\",\n key,\n err instanceof Error ? err.message : String(err),\n );\n res.status(400).json({ error: \"Invalid request body\" });\n return;\n }\n\n // Lane dispatch. The lane comes from the registration (the entry's\n // `executor` in definitions.json), NOT a URL segment or `.obo.sql`\n // filename: an OBO-lane metric runs on-behalf-of the requesting user\n // (per-user cache via `asUser(req)`), an SP-lane metric as the app service\n // principal (shared cache).\n let executor: AnalyticsPlugin;\n let executorKey: string;\n try {\n const isObo = registration.lane === \"obo\";\n executor = isObo ? this.asUser(req) : this;\n executorKey = deriveMetricExecutorKey({\n lane: registration.lane,\n userIdentity: isObo ? this.resolveUserId(req) : undefined,\n });\n } catch (err) {\n if (err instanceof AppKitError) {\n res.status(err.statusCode).json({ error: err.message, code: err.code });\n return;\n }\n throw err;\n }\n\n const injectedMetadata = this.config.metricViewsMetadata;\n const allMetadata =\n injectedMetadata ??\n (await loadMetricMetadata(this.app, req, this.devFileReader));\n\n if (allMetadata !== undefined && !Object.hasOwn(allMetadata, key)) {\n if (injectedMetadata !== undefined) {\n logger.warn(\n req,\n \"No display metadata for metric key %s in the injected metricViewsMetadata\",\n key,\n );\n } else {\n logger.warn(\n req,\n \"No display metadata for metric key %s — regenerate types to refresh %s\",\n key,\n METRIC_METADATA_FILE,\n );\n }\n }\n\n // Computed here, outside the cached execute below, so a cache hit still\n // serves the current metadata. Absent config → `undefined` → the `result`\n // message omits the field (envelope-identical to `/query`).\n const metadata = selectMetricMetadata(\n allMetadata,\n key,\n request.measures,\n request.dimensions,\n );\n\n // Cache key. Composed over the canonicalized args (sorted measures/\n // dimensions, stable-sorted predicates, grain, timeDimension, limit, orderBy) plus\n // the `executorKey` — `\"sp\"` shares the cache across all users, a per-user\n // identity hash isolates OBO callers.\n const cacheConfig = {\n ...queryDefaults.cache,\n cacheKey: composeMetricCacheKey({\n metricKey: key,\n source: registration.source,\n measures: request.measures,\n dimensions: request.dimensions,\n timeGrain: request.timeGrain,\n timeDimension: request.timeDimension,\n filter: request.filter,\n format: \"JSON_ARRAY\",\n executorKey,\n limit: request.limit,\n orderBy: request.orderBy,\n }),\n };\n\n // Cache/retry/timeout scoped to the SQL execution itself (inner `execute`)\n // so the warehouse-readiness phase isn't retried and the generator value\n // never leaks into the cache.\n const sqlConfig: PluginExecuteConfig = {\n ...queryDefaults,\n cache: cacheConfig,\n };\n\n // Outer stream: no cache/retry — `executeStream` would otherwise wrap the\n // generator factory and cache the generator object itself. Telemetry +\n // trace context still apply.\n const streamExecutionSettings: StreamExecutionSettings = {\n default: {\n cache: { enabled: false },\n retry: { enabled: false },\n },\n };\n\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStartWarehouse = this.config.autoStartWarehouse ?? true;\n\n const self = this;\n\n await executor.executeStream(\n res,\n async function* (\n signal,\n ): AsyncGenerator<AnalyticsStreamMessage, void, unknown> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n // Stream warehouse-readiness updates as SSE events, then run SQL.\n const readinessUpdates = streamCallbacks<WarehouseStatusUpdate>(\n (emit) =>\n self.SQLClient.ensureWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart: autoStartWarehouse,\n onStatus: emit,\n },\n ),\n );\n for await (const update of readinessUpdates) {\n yield {\n type: \"warehouse_status\",\n status: {\n state: update.state as WarehouseStatus[\"state\"],\n elapsedMs: update.elapsedMs,\n },\n };\n }\n\n // `execute()` reduces a thrown error to `{ status, message }`,\n // dropping the rich fields (`errorCode`, `clientMessage`). Capture the\n // original here so we can re-throw it intact — the SSE error path\n // (`StreamManager`) reads `errorCode`/`clientMessage` off it.\n let originalError: unknown;\n const sqlResult = await executor.execute(\n async (sig) => {\n try {\n const { statement, parameters } = buildMetricSql(\n registration,\n request,\n );\n const processedParams =\n await self.queryProcessor.processQueryParams(\n statement,\n Object.keys(parameters).length > 0 ? parameters : undefined,\n );\n // Reuse the query route's JSON delivery: INLINE JSON_ARRAY with\n // an ARROW_STREAM-inline fallback, returning plain rows in a\n // `result` message — byte-identical envelope to `/query`.\n return await self._executeJsonArrayPath(\n executor,\n statement,\n processedParams,\n sig,\n );\n } catch (err) {\n originalError = err;\n throw err;\n }\n },\n { default: sqlConfig },\n executorKey,\n );\n\n if (!sqlResult.ok) {\n const msg = sqlResult.message;\n const lower = msg.toLowerCase();\n if (\n lower.includes(\"operation was aborted\") ||\n lower.includes(\"the request was aborted\") ||\n lower.includes(\"statement was canceled\")\n ) {\n const err = new DOMException(\n lower.includes(\"canceled\") ? msg : \"The operation was aborted.\",\n \"AbortError\",\n );\n throw err;\n }\n // Re-throw the original error so its structured `errorCode` and\n // sanitized `clientMessage` survive to the SSE error payload. Fall\n // back to a generic statement failure only if it wasn't an\n // AppKitError.\n if (originalError instanceof AppKitError) {\n throw originalError;\n }\n const inner = msg.startsWith(\"Statement failed: \")\n ? msg.slice(\"Statement failed: \".length)\n : msg;\n throw ExecutionError.statementFailed(inner);\n }\n\n // Stamp the metadata onto the (possibly cached) result message; the\n // cached message never carries it.\n const resultMessage = sqlResult.data as AnalyticsSseMessage;\n yield (\n metadata !== undefined\n ? { ...resultMessage, metadata }\n : resultMessage\n ) as AnalyticsStreamMessage;\n },\n streamExecutionSettings,\n executorKey,\n );\n }\n\n /**\n * JSON_ARRAY SSE path. Delegates the disposition/format fallback to\n * {@link deliverJsonResult} (INLINE JSON_ARRAY → on `needs-arrow-inline`,\n * INLINE ARROW_STREAM decoded to rows) and wraps the rows in a `result`\n * message. External links are never used for the JSON fallback.\n */\n private async _executeJsonArrayPath(\n executor: AnalyticsPlugin,\n query: string,\n processedParams:\n | Record<string, SQLTypeMarker | null | undefined>\n | undefined,\n signal?: AbortSignal,\n ): Promise<AnalyticsSseMessage> {\n const result = await deliverJsonResult(\n executor,\n query,\n processedParams,\n signal,\n );\n return makeResultMessage(result.data, {\n status: result.status,\n statement_id: result.statement_id,\n });\n }\n\n /**\n * Attach the real column names so the client can relabel the positional\n * Arrow schema (Databricks encodes ARROW_STREAM columns as col_0, …).\n *\n * Small schemas ride `X-Appkit-Arrow-Columns` directly. A very wide schema\n * whose URL-encoded names would blow the HTTP header size limit instead\n * advertises the statement id in `X-Appkit-Arrow-Columns-Ref`, and the\n * client fetches the names from `GET /columns/:statementId`.\n */\n private _setArrowColumnsHeader(\n res: express.Response,\n columnsRef: { columnNames?: string[]; statementId?: string },\n ): void {\n const names = columnsRef.columnNames;\n if (!names || names.length === 0) return;\n\n const encoded = encodeURIComponent(JSON.stringify(names));\n if (encoded.length <= MAX_ARROW_COLUMNS_HEADER_BYTES) {\n res.setHeader(\"X-Appkit-Arrow-Columns\", encoded);\n return;\n }\n if (columnsRef.statementId) {\n res.setHeader(\"X-Appkit-Arrow-Columns-Ref\", columnsRef.statementId);\n } else {\n logger.warn(\n \"Arrow column names exceed the header limit and no statement id is available for the fallback endpoint; client will fall back to the raw schema names\",\n );\n }\n }\n\n /**\n * ARROW_STREAM query handler: stream the raw Arrow IPC bytes back as the\n * HTTP response body — no SSE, no server-side stash, no second\n * `/arrow-result` request.\n *\n * The first chunk is pulled before headers are sent so a failure still\n * yields a clean JSON error; once bytes are in flight a mid-stream failure\n * can only abort the socket. Warehouse readiness is awaited (no SSE\n * progress on this path) — a no-op for a warm warehouse, a blocking wait\n * on a cold start. Runs under the user's context for `.obo.sql` queries.\n */\n private async _handleArrowStreamQuery(\n req: express.Request,\n res: express.Response,\n query_key: string,\n query: string,\n isAsUser: boolean,\n parameters: IAnalyticsQueryRequest[\"parameters\"],\n ): Promise<void> {\n const executor = isAsUser ? this.asUser(req) : this;\n const executorKey = isAsUser ? this.resolveUserId(req) : \"global\";\n const abortController = new AbortController();\n const onClose = () => abortController.abort();\n res.on(\"close\", onClose);\n const signal = abortController.signal;\n\n // Fail-fast: bound the wait for the first byte (warehouse readiness +\n // execute + first chunk) so a stuck/overloaded warehouse returns a clear\n // 503 instead of hanging until the client gives up. Cleared once the\n // first chunk arrives — a legitimately long stream is never interrupted.\n const firstByteTimeoutMs =\n this.config.arrowFirstByteTimeoutMs ??\n DEFAULT_ARROW_FIRST_BYTE_TIMEOUT_MS;\n let timedOut = false;\n const failFast = setTimeout(() => {\n timedOut = true;\n abortController.abort();\n }, firstByteTimeoutMs);\n\n try {\n // Run warehouse readiness in the SAME identity context as the query:\n // for `.obo.sql`, `executor` is the `asUser(req)` proxy, so\n // `getWorkspaceClient()` inside resolves to the user's client (matching\n // the SSE path). Calling it bare here would auto-start the warehouse as\n // the service principal even for OBO requests.\n await executor._ensureArrowWarehouseReady(signal);\n\n const processedParams = await this.queryProcessor.processQueryParams(\n query,\n parameters,\n );\n\n const warehouseId = await getWarehouseId();\n\n // Populated by `deliverArrowBytes` from the result manifest before the\n // first chunk is yielded, so the header below carries the real names.\n const columnsRef: { columnNames?: string[]; statementId?: string } = {};\n const bytes = deliverArrowBytes(\n // Wrap the executor so the INLINE attempt runs through the interceptor\n // chain (cache + retry), matching the JSON path. Only inline attachments\n // are cached; EXTERNAL_LINKS carry expiring pre-signed URLs and are\n // never cached (see `_arrowCachingExecutor`).\n this._arrowCachingExecutor(\n executor,\n query_key,\n query,\n parameters,\n executorKey,\n ),\n this.SQLClient,\n query,\n processedParams,\n columnsRef,\n signal,\n {\n // Skip the doomed INLINE probe on a warehouse already known to need\n // EXTERNAL_LINKS; remember the resolved mode for next time.\n capabilityHint: this._arrowCapability.get(warehouseId),\n onCapabilityResolved: (capability) =>\n this._arrowCapability.set(warehouseId, capability),\n },\n );\n const first = await bytes.next();\n // First byte in hand — stop the fail-fast clock.\n clearTimeout(failFast);\n\n res.setHeader(\"Content-Type\", \"application/vnd.apache.arrow.stream\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n this._setArrowColumnsHeader(res, columnsRef);\n\n if (!first.done) {\n await writeChunk(res, first.value);\n for await (const buf of bytes) {\n await writeChunk(res, buf);\n }\n }\n res.end();\n } catch (error) {\n clearTimeout(failFast);\n // Fail-fast timeout: the warehouse never produced a first byte. This also\n // aborts the signal, so it must be handled before the generic\n // `signal.aborted` branch below. Headers aren't sent yet (we time out\n // before the first chunk), so a clean 503 is still possible.\n if (timedOut) {\n logger.warn(\n \"Arrow query timed out before first byte after %dms\",\n firstByteTimeoutMs,\n );\n res.status(503).json({\n error:\n \"The SQL warehouse is starting or overloaded and did not respond in time. Please retry.\",\n errorCode: \"WAREHOUSE_UNAVAILABLE\",\n plugin: this.name,\n });\n return;\n }\n // Client disconnect / unmount aborts the signal (see `onClose`). That's\n // routine UI behavior, not a server error — tear down quietly whether it\n // fires before or after headers. Checked before the headersSent branch so\n // a mid-stream disconnect doesn't spam ERROR logs / alerting.\n if (signal.aborted) {\n if (res.headersSent) res.destroy();\n else res.end();\n return;\n }\n if (res.headersSent) {\n logger.error(\"Arrow query stream failed mid-flight: %O\", error);\n res.destroy(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n logger.error(\"Arrow query error: %O\", error);\n // Do not echo upstream / SDK error text — it can include statement\n // fragments and correlation ids. Keep the structured code so the\n // client can branch (e.g. RESULT_TOO_LARGE_FOR_JSON_FALLBACK,\n // ARROW_DELIVERY_UNSUPPORTED).\n const errorCode =\n error instanceof ExecutionError ? error.errorCode : undefined;\n res.status(500).json({\n // `clientMessage` is the sanitized, actionable text (e.g. \"Re-run with\n // JSON_ARRAY\" for ARROW_DELIVERY_UNSUPPORTED); it never carries raw\n // warehouse/SDK strings. Fall back to a generic message otherwise.\n error:\n error instanceof AppKitError\n ? error.clientMessage\n : \"Unable to execute query\",\n errorCode,\n plugin: this.name,\n });\n } finally {\n res.off(\"close\", onClose);\n }\n }\n\n /**\n * Await SQL warehouse readiness for the direct-binary Arrow path. There is no\n * SSE progress channel here — readiness is simply awaited, bounded by the\n * caller's abort signal / fail-fast timeout. Invoked via the request executor\n * (`asUser(req)` for `.obo.sql`) so `getWorkspaceClient()` resolves in the\n * correct identity context rather than defaulting to the service principal.\n */\n async _ensureArrowWarehouseReady(signal: AbortSignal): Promise<void> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStart = this.config.autoStartWarehouse ?? true;\n await this.SQLClient.ensureWarehouseRunning(workspaceClient, warehouseId, {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart,\n onStatus: () => {},\n });\n }\n\n /**\n * Wrap an executor so the `INLINE + ARROW_STREAM` attempt is served from\n * (and populates) the same per-user TTL cache the JSON path uses — otherwise\n * every arrow chart render is a fresh warehouse execution, unlike its JSON\n * twin. Caching is deliberately scoped to inline attachments:\n *\n * - INLINE results carry a bounded (<=25 MiB) base64 `attachment` with the\n * same lifecycle as cached JSON rows — safe to cache.\n * - EXTERNAL_LINKS results carry short-lived pre-signed URLs that expire in\n * minutes; caching them would serve dead links, so those pass through\n * uncached (only the tiny link metadata would be cached anyway).\n *\n * Uses `this.cache.getOrExecute` directly rather than `this.execute()`\n * because `execute()` reduces a thrown error to `{ ok:false, message }`,\n * dropping the `errorCode` the capability fallback classifies on. The cache\n * re-throws `AppKitError`s intact and never caches a rejection, so the\n * INLINE→EXTERNAL_LINKS fallback still sees the structured rejection.\n */\n private _arrowCachingExecutor(\n executor: AnalyticsPlugin,\n query_key: string,\n query: string,\n parameters: IAnalyticsQueryRequest[\"parameters\"],\n executorKey: string,\n ): QueryExecutor {\n const hashedQuery = this.queryProcessor.hashQuery(query);\n const cache = this.cache;\n const ttl = queryDefaults.cache?.ttl;\n return {\n query: (q, params, formatParameters, signal) => {\n // Only the inline-arrow attempt is cacheable — EXTERNAL_LINKS carry\n // short-lived pre-signed URLs, so those pass straight through.\n if (\n formatParameters.disposition !== \"INLINE\" ||\n formatParameters.format !== \"ARROW_STREAM\"\n ) {\n return executor.query(q, params, formatParameters, signal);\n }\n // On a standard warehouse this throws a capability rejection — the\n // cache never stores a rejection, so the fallback still sees the\n // structured error. On Reyden it returns a bounded (<=25 MiB)\n // attachment that caches like the JSON path's rows. The shared signal\n // dedupes concurrent renders (e.g. React StrictMode double-mount).\n return cache.getOrExecute(\n [\n \"analytics:query:arrow\",\n query_key,\n JSON.stringify(parameters),\n hashedQuery,\n executorKey,\n ],\n (sharedSignal) =>\n executor.query(q, params, formatParameters, sharedSignal ?? signal),\n executorKey,\n { ttl, callerSignal: signal },\n );\n },\n };\n }\n\n /**\n * Execute a SQL query using the current execution context.\n *\n * When called directly: uses service principal credentials.\n * When called via asUser(req).query(...): uses user's credentials.\n *\n * @example\n * ```typescript\n * // Service principal execution\n * const result = await analytics.query(\"SELECT * FROM table\")\n *\n * // User context execution (in route handler)\n * const result = await this.asUser(req).query(\"SELECT * FROM table\")\n * ```\n */\n async query(\n query: string,\n parameters?: Record<string, SQLTypeMarker | null | undefined>,\n formatParameters?: Record<string, any>,\n signal?: AbortSignal,\n ): Promise<any> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n const { statement, parameters: sqlParameters } =\n this.queryProcessor.convertToSQLParameters(query, parameters);\n\n const response = await this.SQLClient.executeStatement(\n workspaceClient,\n {\n statement,\n warehouse_id: warehouseId,\n parameters: sqlParameters,\n ...formatParameters,\n },\n signal,\n );\n\n return response.result;\n }\n\n async shutdown(): Promise<void> {\n this.streamManager.abortAll();\n }\n\n private tools = {\n query: defineTool({\n description:\n \"Execute a read-only SQL query against the Databricks SQL warehouse. Only SELECT, WITH, SHOW, EXPLAIN, and DESCRIBE statements are accepted; writes are rejected. Returns the query results as JSON.\",\n schema: z.object({\n query: z\n .string()\n .describe(\n \"The SQL query to execute. Must be a SELECT, WITH, SHOW, EXPLAIN, or DESCRIBE statement.\",\n ),\n }),\n annotations: {\n effect: \"read\",\n requiresUserContext: true,\n },\n autoInheritable: true,\n execute: (args, signal) => {\n assertReadOnlySql(args.query);\n return this.query(args.query, undefined, undefined, signal);\n },\n }),\n };\n\n getAgentTools(): AgentToolDefinition[] {\n return toolsFromRegistry(this.tools);\n }\n\n async executeAgentTool(\n name: string,\n args: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n return executeFromRegistry(this.tools, name, args, signal);\n }\n\n /**\n * Returns the plugin's tools as a keyed record of `ToolkitEntry` markers.\n * Called by the agents plugin (via `resolveToolkitFromProvider`) to spread\n * a filtered, renamed view of the plugin's tools into an agent's tool\n * index. Inside the function form of `AgentDefinition.tools`, callers\n * reach this method via `plugins.analytics.toolkit(opts)`.\n */\n toolkit(opts?: import(\"../../core/agent/types\").ToolkitOptions) {\n return buildToolkitEntries(this.name, this.tools, opts);\n }\n\n /**\n * Returns the public exports for the analytics plugin.\n * Note: `asUser()` is automatically added by AppKit.\n */\n exports() {\n return {\n /**\n * Execute a SQL query using service principal credentials.\n */\n query: this.query,\n };\n }\n}\n\n/**\n * Write one chunk to the response honoring backpressure: if the socket\n * buffer is full (`res.write` returns false), wait for `drain` before\n * resolving so a slow client can't balloon Node's internal write queue and\n * defeat the constant-memory goal of streaming.\n *\n * @internal exported for unit testing the backpressure/disconnect behavior.\n */\nexport function writeChunk(\n res: express.Response,\n bytes: Uint8Array,\n): Promise<void> {\n const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n // If the socket is already gone, `res.write` won't return true and the\n // `drain`/`close`/`error` events have already fired — so the promise below\n // would never settle, wedging the for-await loop and the upstream reader.\n // Reject up front instead.\n if (res.destroyed || res.writableEnded) {\n return Promise.reject(\n new DOMException(\"The response stream closed\", \"AbortError\"),\n );\n }\n if (res.write(buf)) return Promise.resolve();\n // Backpressured: resolve on `drain`, but also settle on `close`/`error`. A\n // client that disconnects mid-backpressure never emits `drain` on the\n // destroyed socket, so waiting on `drain` alone would wedge this promise —\n // and with it the awaiting for-await loop and the upstream Arrow reader —\n // forever. Rejecting instead unwinds the stream so its `finally` can cancel\n // the reader.\n return new Promise<void>((resolve, reject) => {\n const cleanup = () => {\n res.off(\"drain\", onDrain);\n res.off(\"close\", onClose);\n res.off(\"error\", onClose);\n };\n const onDrain = () => {\n cleanup();\n resolve();\n };\n const onClose = () => {\n cleanup();\n reject(new DOMException(\"The response stream closed\", \"AbortError\"));\n };\n res.once(\"drain\", onDrain);\n res.once(\"close\", onClose);\n res.once(\"error\", onClose);\n });\n}\n\n/**\n * Fail-fast ceiling on the wait for the first Arrow byte (warehouse\n * readiness + execute + first chunk). Past this a stuck/overloaded warehouse\n * yields a clear 503 instead of hanging. Override per plugin via\n * `arrowFirstByteTimeoutMs`.\n */\nconst DEFAULT_ARROW_FIRST_BYTE_TIMEOUT_MS = 120_000;\n\n/**\n * Byte ceiling for the `X-Appkit-Arrow-Columns` header value. Beyond this (a\n * very wide schema) the names are served via the `/columns/:statementId`\n * fallback endpoint instead of the header. Kept well under the common ~8 KiB\n * per-header limit.\n */\nconst MAX_ARROW_COLUMNS_HEADER_BYTES = 6000;\n\n/**\n * @internal\n */\nexport const analytics = toPlugin(AnalyticsPlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAM,SAAS,aAAa,YAAY;;;;;;;;;AAUxC,gBAAgB,gBACd,OACkC;CAClC,MAAM,QAAa,EAAE;CACrB,IAAI,OAA4B;CAChC,IAAI,UAAU;CACd,IAAI,QAAiB;CAErB,MAAM,eAAqB;AACzB,UAAQ;AACR,SAAO;;AAKT,CAAK,OAAO,UAAU;AACpB,QAAM,KAAK,MAAM;AACjB,UAAQ;GACR,CAAC,WACK;AACJ,YAAU;AACV,UAAQ;KAET,QAAQ;AACP,UAAQ;AACR,YAAU;AACV,UAAQ;GAEX;AAED,QAAO,CAAC,WAAW,MAAM,SAAS,GAAG;AACnC,SAAO,MAAM,SA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AAW;AACzB,qBAAkB,KAAK,MAAM;AAC7B,UAAO,KAAK,MAAM,KAAK,OAAO,QAAW,QAAW,OAAO;;EAE9D,CAAC,EACH;CAED,gBAAuC;AACrC,SAAO,kBAAkB,KAAK,MAAM;;CAGtC,MAAM,iBACJ,MACA,MACA,QACkB;AAClB,SAAO,oBAAoB,KAAK,OAAO,MAAM,MAAM,OAAO;;;;;;;;;CAU5D,QAAQ,MAAwD;AAC9D,SAAO,oBAAoB,KAAK,MAAM,KAAK,OAAO,KAAK;;;;;;CAOzD,UAAU;AACR,SAAO,EAIL,OAAO,KAAK,OACb;;;;;;;;;;;AAYL,SAAgB,WACd,KACA,OACe;CACf,MAAM,MAAM,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,WAAW;AAKzE,KAAI,IAAI,aAAa,IAAI,cACvB,QAAO,QAAQ,OACb,IAAI,aAAa,8BAA8B,aAAa,CAC7D;AAEH,KAAI,IAAI,MAAM,IAAI,CAAE,QAAO,QAAQ,SAAS;AAO5C,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,gBAAgB;AACpB,OAAI,IAAI,SAAS,QAAQ;AACzB,OAAI,IAAI,SAAS,QAAQ;AACzB,OAAI,IAAI,SAAS,QAAQ;;EAE3B,MAAM,gBAAgB;AACpB,YAAS;AACT,YAAS;;EAEX,MAAM,gBAAgB;AACpB,YAAS;AACT,UAAO,IAAI,aAAa,8BAA8B,aAAa,CAAC;;AAEtE,MAAI,KAAK,SAAS,QAAQ;AAC1B,MAAI,KAAK,SAAS,QAAQ;AAC1B,MAAI,KAAK,SAAS,QAAQ;GAC1B;;;;;;;;AASJ,MAAM,sCAAsC;;;;;;;AAQ5C,MAAM,iCAAiC;;;;AAKvC,MAAa,YAAY,SAAS,gBAAgB"}
1
+ {"version":3,"file":"analytics.js","names":["manifest"],"sources":["../../../src/plugins/analytics/analytics.ts"],"sourcesContent":["import type express from \"express\";\nimport {\n type AgentToolDefinition,\n type AnalyticsSseMessage,\n type IAppRouter,\n makeResultMessage,\n type PluginExecuteConfig,\n type SQLTypeMarker,\n type StreamExecutionSettings,\n type ToolProvider,\n} from \"shared\";\nimport { z } from \"zod\";\n\nimport { SQLWarehouseConnector } from \"../../connectors\";\nimport {\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n type WarehouseStatusUpdate,\n} from \"../../connectors/sql-warehouse/client\";\nimport { getWorkspaceClient } from \"../../context\";\nimport { buildToolkitEntries } from \"../../core/agent/build-toolkit\";\nimport {\n defineTool,\n executeFromRegistry,\n toolsFromRegistry,\n} from \"../../core/agent/tools/define-tool\";\nimport { assertReadOnlySql } from \"../../core/agent/tools/sql-policy\";\nimport { AppKitError, ExecutionError } from \"../../errors\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } from \"../../registry\";\nimport { getWarehouseId } from \"../../resources\";\nimport type { WorkspaceClient } from \"../../workspace-client\";\nimport { queryDefaults } from \"./defaults\";\nimport manifest from \"./manifest.json\";\nimport {\n buildMetricSql,\n composeMetricCacheKey,\n deriveMetricExecutorKey,\n loadMetricMetadata,\n loadMetricRegistry,\n METRIC_METADATA_FILE,\n selectMetricMetadata,\n validateMetricRequest,\n} from \"./metric\";\nimport { QueryProcessor } from \"./query\";\nimport {\n type ArrowCapability,\n deliverArrowBytes,\n deliverJsonResult,\n type QueryExecutor,\n} from \"./result-delivery\";\nimport {\n type AnalyticsQueryResponse,\n type AnalyticsStreamMessage,\n type IAnalyticsConfig,\n type IAnalyticsQueryRequest,\n type MetricRegistration,\n normalizeAnalyticsFormat,\n type WarehouseStatus,\n} from \"./types\";\n\nconst logger = createLogger(\"analytics\");\n\n/**\n * Bridges a callback-emitting async function into an async iterable.\n *\n * `start(emit)` runs concurrently; every value passed to `emit` is yielded\n * in order. The iterable completes when `start`'s promise resolves and\n * re-throws (after draining) if it rejects. Lets a callback-based progress\n * API (e.g. SQL warehouse readiness) be consumed with `for await`.\n */\nasync function* streamCallbacks<T>(\n start: (emit: (value: T) => void) => Promise<void>,\n): AsyncGenerator<T, void, unknown> {\n const queue: T[] = [];\n let wake: (() => void) | null = null;\n let settled = false;\n let error: unknown = null;\n\n const notify = (): void => {\n wake?.();\n wake = null;\n };\n\n // The .then(_, err => ...) chain converts a rejection into a resolved\n // promise; the consumer surfaces `error` after draining the queue.\n void start((value) => {\n queue.push(value);\n notify();\n }).then(\n () => {\n settled = true;\n notify();\n },\n (err) => {\n error = err;\n settled = true;\n notify();\n },\n );\n\n while (!settled || queue.length > 0) {\n while (queue.length > 0) yield queue.shift() as T;\n if (settled) break;\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n if (error) throw error;\n}\n\nexport class AnalyticsPlugin extends Plugin implements ToolProvider {\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = defineManifest<\"analytics\">(manifest);\n\n protected static description = \"Analytics plugin for data analysis\";\n declare protected config: IAnalyticsConfig;\n\n // analytics services\n private SQLClient: SQLWarehouseConnector;\n private queryProcessor: QueryProcessor;\n\n /**\n * In-process memo of which arrow delivery mode each warehouse supports\n * (keyed by warehouse id). A standard warehouse rejects `INLINE+ARROW_STREAM`\n * on every query, so once learned we skip that doomed probe; Reyden stays\n * `\"inline\"`. Capability is a property of the warehouse, not the user, so it\n * is not user-scoped. Bounded by the number of distinct warehouses a process\n * talks to (effectively one).\n */\n private _arrowCapability = new Map<string, ArrowCapability>();\n\n constructor(config: IAnalyticsConfig) {\n super(config);\n this.config = config;\n this.queryProcessor = new QueryProcessor();\n\n this.SQLClient = new SQLWarehouseConnector({\n timeout: config.timeout,\n telemetry: config.telemetry,\n });\n }\n\n injectRoutes(router: IAppRouter) {\n this.route<AnalyticsQueryResponse>(router, {\n name: \"query\",\n method: \"post\",\n path: \"/query/:query_key\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleQueryRoute(req, res);\n },\n });\n\n // Metric-view route. Registered parallel to `/query`\n // measures a registered UC Metric View over the same SSE envelope.\n this.route(router, {\n name: \"metric\",\n method: \"post\",\n path: \"/metric/:key\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleMetricRoute(req, res);\n },\n });\n\n // Column-names fallback for very wide Arrow schemas whose names don't fit\n // in the `X-Appkit-Arrow-Columns` response header.\n // The client hits this with the statement id from `X-Appkit-Arrow-Columns-Ref`.\n this.route(router, {\n name: \"arrow-columns\",\n method: \"get\",\n path: \"/columns/:statementId\",\n handler: async (req: express.Request, res: express.Response) => {\n await this._handleColumnsRoute(req, res);\n },\n });\n }\n\n /**\n * Column-names fallback endpoint. Re-derives the real column names from the\n * statement's result manifest (stateless — no server cache), for the client\n * to relabel a positional Arrow schema when the names were too large for the\n * response header.\n */\n async _handleColumnsRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { statementId } = req.params;\n const columns = await this._resolveColumnNames(req, statementId);\n if (columns && columns.length > 0) {\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.json({ columns });\n return;\n }\n res.status(404).json({\n error: \"Column names unavailable\",\n plugin: this.name,\n });\n }\n\n /**\n * Resolve a statement's real column names, trying the user's identity first\n * (required for `.obo.sql` statements, which the service principal cannot\n * `getStatement`) then falling back to the service principal (for\n * SP-executed statements). Returns undefined if neither identity can read it,\n * so the client falls back to the raw positional Arrow schema names.\n */\n private async _resolveColumnNames(\n req: express.Request,\n statementId: string,\n ): Promise<string[] | undefined> {\n const attempts: Array<() => Promise<string[] | undefined>> = [\n () => this._asUserScoped(req)._getColumnNames(statementId),\n () => this._getColumnNames(statementId),\n ];\n for (const attempt of attempts) {\n try {\n const columns = await attempt();\n if (columns && columns.length > 0) return columns;\n } catch (error) {\n logger.debug(\n \"Arrow column-names lookup attempt failed for %s: %O\",\n statementId,\n error,\n );\n }\n }\n return undefined;\n }\n\n /**\n * Fetch column names in the current execution context. Proxied by `asUser`,\n * so `getWorkspaceClient()` resolves to the user's client when invoked via\n * `asUser(req)` and the service principal's otherwise.\n */\n async _getColumnNames(statementId: string): Promise<string[] | undefined> {\n return this.SQLClient.getColumnNames(getWorkspaceClient(), statementId);\n }\n\n /**\n * Handle SQL query execution requests.\n * When called via asUser(req), uses the user's Databricks credentials.\n */\n async _handleQueryRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { query_key } = req.params;\n const { parameters, format: rawFormat = \"JSON_ARRAY\" } =\n req.body as IAnalyticsQueryRequest;\n\n if (\n rawFormat !== \"JSON_ARRAY\" &&\n rawFormat !== \"ARROW_STREAM\" &&\n rawFormat !== \"JSON\" &&\n rawFormat !== \"ARROW\"\n ) {\n res.status(400).json({\n error: `Invalid format: ${String(rawFormat)}. Expected \"JSON_ARRAY\" or \"ARROW_STREAM\".`,\n });\n return;\n }\n\n const format = normalizeAnalyticsFormat(rawFormat);\n\n // Request-scoped logging with WideEvent tracking\n logger.debug(req, \"Executing query: %s (format=%s)\", query_key, format);\n\n const event = logger.event(req);\n event?.setComponent(\"analytics\", \"executeQuery\").setContext(\"analytics\", {\n query_key,\n format,\n parameter_count: parameters ? Object.keys(parameters).length : 0,\n plugin: this.name,\n });\n\n if (!query_key) {\n res.status(400).json({ error: \"query_key is required\" });\n return;\n }\n\n const queryResult = await this.app.getAppQuery(\n query_key,\n req,\n this.devFileReader,\n );\n\n if (!queryResult) {\n res.status(404).json({ error: \"Query not found\" });\n return;\n }\n\n const { query, isAsUser } = queryResult;\n\n // ARROW_STREAM streams the raw Arrow IPC bytes back as the HTTP response\n // body — no SSE, no server-side stash, no second /arrow-result request.\n // INLINE attachments are piped straight through (the bytes are already in\n // hand from executeStatement); a warehouse that refuses INLINE falls back\n // to EXTERNAL_LINKS and streams those chunks. JSON keeps the SSE path\n // below (it carries warehouse-readiness progress + cached rows).\n if (format === \"ARROW_STREAM\") {\n await this._handleArrowStreamQuery(\n req,\n res,\n query_key,\n query,\n isAsUser,\n parameters,\n );\n return;\n }\n\n // get execution context - user-scoped if .obo.sql, otherwise service principal\n const executor = isAsUser ? this._asUserScoped(req) : this;\n const executorKey = isAsUser ? this.resolveUserId(req) : \"global\";\n\n const hashedQuery = this.queryProcessor.hashQuery(query);\n\n const cacheConfig = {\n ...queryDefaults.cache,\n cacheKey: [\n \"analytics:query\",\n query_key,\n JSON.stringify(parameters),\n format,\n hashedQuery,\n executorKey,\n ],\n };\n\n // Cache/retry/timeout are scoped to the SQL execution itself (inner\n // `execute`) so the warehouse-readiness phase isn't subject to retries\n // and the generator value never leaks into the cache.\n const sqlConfig: PluginExecuteConfig = {\n ...queryDefaults,\n cache: cacheConfig,\n };\n\n // Outer stream: no cache/retry — `executeStream` would otherwise wrap the\n // generator factory and cache the generator object itself. Telemetry +\n // user-scoped trace context still apply.\n const streamExecutionSettings: StreamExecutionSettings = {\n default: {\n cache: { enabled: false },\n retry: { enabled: false },\n },\n };\n\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStartWarehouse = this.config.autoStartWarehouse ?? true;\n\n const self = this;\n\n await executor.executeStream(\n res,\n async function* (\n signal,\n ): AsyncGenerator<AnalyticsStreamMessage, void, unknown> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n // Stream warehouse-readiness updates as SSE events, then run SQL.\n const readinessUpdates = streamCallbacks<WarehouseStatusUpdate>(\n (emit) =>\n self.SQLClient.ensureWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart: autoStartWarehouse,\n onStatus: emit,\n },\n ),\n );\n for await (const update of readinessUpdates) {\n yield {\n type: \"warehouse_status\",\n status: {\n state: update.state as WarehouseStatus[\"state\"],\n elapsedMs: update.elapsedMs,\n },\n };\n }\n\n // `execute()` reduces a thrown error to `{ status, message }`,\n // dropping the rich fields (`errorCode`, `clientMessage`) the\n // fallback's `ExecutionError`s carry. Capture the original here so\n // we can re-throw it intact — the SSE error path\n // (`StreamManager`) reads `errorCode`/`clientMessage` off it.\n let originalError: unknown;\n const sqlResult = await executor.execute(\n async (sig) => {\n try {\n const processedParams =\n await self.queryProcessor.processQueryParams(query, parameters);\n // JSON_ARRAY path: tries INLINE + JSON_ARRAY and, if the\n // warehouse only accepts ARROW_STREAM for INLINE, retries as\n // ARROW_STREAM and decodes server-side — returning the SSE\n // `result` message with plain rows. (ARROW_STREAM requests are\n // handled earlier via `_handleArrowStreamQuery`.)\n return await self._executeJsonArrayPath(\n executor,\n query,\n processedParams,\n sig,\n );\n } catch (err) {\n originalError = err;\n throw err;\n }\n },\n { default: sqlConfig },\n executorKey,\n );\n\n if (!sqlResult.ok) {\n const msg = sqlResult.message;\n const lower = msg.toLowerCase();\n if (\n lower.includes(\"operation was aborted\") ||\n lower.includes(\"the request was aborted\") ||\n lower.includes(\"statement was canceled\")\n ) {\n const err = new DOMException(\n lower.includes(\"canceled\") ? msg : \"The operation was aborted.\",\n \"AbortError\",\n );\n throw err;\n }\n // Re-throw the original error so its structured `errorCode` (e.g.\n // RESULT_TOO_LARGE_FOR_JSON_FALLBACK) and sanitized `clientMessage`\n // survive to the SSE error payload. Fall back to a generic\n // statement failure only if the original wasn't an AppKitError.\n if (originalError instanceof AppKitError) {\n throw originalError;\n }\n const inner = msg.startsWith(\"Statement failed: \")\n ? msg.slice(\"Statement failed: \".length)\n : msg;\n throw ExecutionError.statementFailed(inner);\n }\n\n yield sqlResult.data as AnalyticsStreamMessage;\n },\n streamExecutionSettings,\n executorKey,\n );\n }\n\n /**\n * Handle metric-view execution requests (`POST /api/analytics/metric/:key`).\n *\n * Mirrors {@link _handleQueryRoute}'s JSON SSE path: the outer\n * `executeStream` disables cache/retry and streams warehouse-readiness\n * (`warehouse_status`) events, then the inner `execute` builds the metric SQL\n * and delivers rows through {@link deliverJsonResult} as a `result` message.\n * The `originalError` re-throw discipline preserves each error's structured\n * `errorCode`/`clientMessage` for the SSE error payload.\n *\n * Lane dispatch is driven by the registration: an SP-lane metric runs as the\n * app service principal (shared cache); an OBO-lane metric runs\n * on-behalf-of the requesting user via `asUser(req)` (per-user cache keyed by\n * a hash of the user identity).\n */\n async _handleMetricRoute(\n req: express.Request,\n res: express.Response,\n ): Promise<void> {\n const { key } = req.params;\n\n logger.debug(req, \"Executing metric: %s\", key);\n\n const event = logger.event(req);\n event?.setComponent(\"analytics\", \"executeMetric\").setContext(\"analytics\", {\n metric_key: key,\n plugin: this.name,\n });\n\n if (!key) {\n res.status(400).json({ error: \"metric key is required\" });\n return;\n }\n\n // Resolve the registry from disk: read + parse `definitions.json` once per\n // request (no memoization). Reads through the plugin's shared `this.app`\n // (the base `Plugin`'s `AppManager`) from `config/metric-views/` under the\n // process cwd, so this is dev-tunnel aware and inherits the traversal\n // guard — the same mechanism as the sibling `.sql` query path.\n let registry: Record<string, MetricRegistration>;\n try {\n registry = await loadMetricRegistry(this.app, req, this.devFileReader);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n logger.warn(req, \"Failed to load metric registry: %s\", reason);\n event?.setContext(\"analytics\", {\n metric_registry_load_error: reason,\n });\n res.status(503).json({\n error: \"Metric registry not available\",\n code: \"METRIC_REGISTRY_LOAD_FAILED\",\n });\n return;\n }\n\n // Own-property lookup: never resolve `key` to an inherited `Object.prototype` member.\n const registration = Object.hasOwn(registry, key)\n ? registry[key]\n : undefined;\n if (!registration) {\n // Don't echo the user-supplied `key` back in the public response.\n event?.setContext(\"analytics\", { unknown_metric_key: key });\n res.status(404).json({ error: \"Metric not found\" });\n return;\n }\n\n // Validate the body on the canonical error path.\n // `validateMetricRequest` throws a `ValidationError` (400) whose message names only field paths, never raw values.\n let request: ReturnType<typeof validateMetricRequest>;\n try {\n request = validateMetricRequest(req.body ?? {});\n } catch (err) {\n if (err instanceof AppKitError) {\n res.status(err.statusCode).json({ error: err.message, code: err.code });\n return;\n }\n event?.setContext(\"analytics\", {\n unexpected_error: err instanceof Error ? err.message : String(err),\n metric_key: key,\n });\n logger.warn(\n req,\n \"Unexpected throw during metric request validation for %s: %s\",\n key,\n err instanceof Error ? err.message : String(err),\n );\n res.status(400).json({ error: \"Invalid request body\" });\n return;\n }\n\n // Lane dispatch. The lane comes from the registration (the entry's\n // `executor` in definitions.json), NOT a URL segment or `.obo.sql`\n // filename: an OBO-lane metric runs on-behalf-of the requesting user\n // (per-user cache via `asUser(req)`), an SP-lane metric as the app service\n // principal (shared cache).\n let executor: AnalyticsPlugin;\n let executorKey: string;\n try {\n const isObo = registration.lane === \"obo\";\n executor = isObo ? this._asUserScoped(req) : this;\n executorKey = deriveMetricExecutorKey({\n lane: registration.lane,\n userIdentity: isObo ? this.resolveUserId(req) : undefined,\n });\n } catch (err) {\n if (err instanceof AppKitError) {\n res.status(err.statusCode).json({ error: err.message, code: err.code });\n return;\n }\n throw err;\n }\n\n const injectedMetadata = this.config.metricViewsMetadata;\n const allMetadata =\n injectedMetadata ??\n (await loadMetricMetadata(this.app, req, this.devFileReader));\n\n if (allMetadata !== undefined && !Object.hasOwn(allMetadata, key)) {\n if (injectedMetadata !== undefined) {\n logger.warn(\n req,\n \"No display metadata for metric key %s in the injected metricViewsMetadata\",\n key,\n );\n } else {\n logger.warn(\n req,\n \"No display metadata for metric key %s — regenerate types to refresh %s\",\n key,\n METRIC_METADATA_FILE,\n );\n }\n }\n\n // Computed here, outside the cached execute below, so a cache hit still\n // serves the current metadata. Absent config → `undefined` → the `result`\n // message omits the field (envelope-identical to `/query`).\n const metadata = selectMetricMetadata(\n allMetadata,\n key,\n request.measures,\n request.dimensions,\n );\n\n // Cache key. Composed over the canonicalized args (sorted measures/\n // dimensions, stable-sorted predicates, grain, timeDimension, limit, orderBy) plus\n // the `executorKey` — `\"sp\"` shares the cache across all users, a per-user\n // identity hash isolates OBO callers.\n const cacheConfig = {\n ...queryDefaults.cache,\n cacheKey: composeMetricCacheKey({\n metricKey: key,\n source: registration.source,\n measures: request.measures,\n dimensions: request.dimensions,\n timeGrain: request.timeGrain,\n timeDimension: request.timeDimension,\n filter: request.filter,\n format: \"JSON_ARRAY\",\n executorKey,\n limit: request.limit,\n orderBy: request.orderBy,\n }),\n };\n\n // Cache/retry/timeout scoped to the SQL execution itself (inner `execute`)\n // so the warehouse-readiness phase isn't retried and the generator value\n // never leaks into the cache.\n const sqlConfig: PluginExecuteConfig = {\n ...queryDefaults,\n cache: cacheConfig,\n };\n\n // Outer stream: no cache/retry — `executeStream` would otherwise wrap the\n // generator factory and cache the generator object itself. Telemetry +\n // trace context still apply.\n const streamExecutionSettings: StreamExecutionSettings = {\n default: {\n cache: { enabled: false },\n retry: { enabled: false },\n },\n };\n\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStartWarehouse = this.config.autoStartWarehouse ?? true;\n\n const self = this;\n\n await executor.executeStream(\n res,\n async function* (\n signal,\n ): AsyncGenerator<AnalyticsStreamMessage, void, unknown> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n // Stream warehouse-readiness updates as SSE events, then run SQL.\n const readinessUpdates = streamCallbacks<WarehouseStatusUpdate>(\n (emit) =>\n self.SQLClient.ensureWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart: autoStartWarehouse,\n onStatus: emit,\n },\n ),\n );\n for await (const update of readinessUpdates) {\n yield {\n type: \"warehouse_status\",\n status: {\n state: update.state as WarehouseStatus[\"state\"],\n elapsedMs: update.elapsedMs,\n },\n };\n }\n\n // `execute()` reduces a thrown error to `{ status, message }`,\n // dropping the rich fields (`errorCode`, `clientMessage`). Capture the\n // original here so we can re-throw it intact — the SSE error path\n // (`StreamManager`) reads `errorCode`/`clientMessage` off it.\n let originalError: unknown;\n const sqlResult = await executor.execute(\n async (sig) => {\n try {\n const { statement, parameters } = buildMetricSql(\n registration,\n request,\n );\n const processedParams =\n await self.queryProcessor.processQueryParams(\n statement,\n Object.keys(parameters).length > 0 ? parameters : undefined,\n );\n // Reuse the query route's JSON delivery: INLINE JSON_ARRAY with\n // an ARROW_STREAM-inline fallback, returning plain rows in a\n // `result` message — byte-identical envelope to `/query`.\n return await self._executeJsonArrayPath(\n executor,\n statement,\n processedParams,\n sig,\n );\n } catch (err) {\n originalError = err;\n throw err;\n }\n },\n { default: sqlConfig },\n executorKey,\n );\n\n if (!sqlResult.ok) {\n const msg = sqlResult.message;\n const lower = msg.toLowerCase();\n if (\n lower.includes(\"operation was aborted\") ||\n lower.includes(\"the request was aborted\") ||\n lower.includes(\"statement was canceled\")\n ) {\n const err = new DOMException(\n lower.includes(\"canceled\") ? msg : \"The operation was aborted.\",\n \"AbortError\",\n );\n throw err;\n }\n // Re-throw the original error so its structured `errorCode` and\n // sanitized `clientMessage` survive to the SSE error payload. Fall\n // back to a generic statement failure only if it wasn't an\n // AppKitError.\n if (originalError instanceof AppKitError) {\n throw originalError;\n }\n const inner = msg.startsWith(\"Statement failed: \")\n ? msg.slice(\"Statement failed: \".length)\n : msg;\n throw ExecutionError.statementFailed(inner);\n }\n\n // Stamp the metadata onto the (possibly cached) result message; the\n // cached message never carries it.\n const resultMessage = sqlResult.data as AnalyticsSseMessage;\n yield (\n metadata !== undefined\n ? { ...resultMessage, metadata }\n : resultMessage\n ) as AnalyticsStreamMessage;\n },\n streamExecutionSettings,\n executorKey,\n );\n }\n\n /**\n * JSON_ARRAY SSE path. Delegates the disposition/format fallback to\n * {@link deliverJsonResult} (INLINE JSON_ARRAY → on `needs-arrow-inline`,\n * INLINE ARROW_STREAM decoded to rows) and wraps the rows in a `result`\n * message. External links are never used for the JSON fallback.\n */\n private async _executeJsonArrayPath(\n executor: AnalyticsPlugin,\n query: string,\n processedParams:\n | Record<string, SQLTypeMarker | null | undefined>\n | undefined,\n signal?: AbortSignal,\n ): Promise<AnalyticsSseMessage> {\n const result = await deliverJsonResult(\n executor,\n query,\n processedParams,\n signal,\n );\n return makeResultMessage(result.data, {\n status: result.status,\n statement_id: result.statement_id,\n });\n }\n\n /**\n * Attach the real column names so the client can relabel the positional\n * Arrow schema (Databricks encodes ARROW_STREAM columns as col_0, …).\n *\n * Small schemas ride `X-Appkit-Arrow-Columns` directly. A very wide schema\n * whose URL-encoded names would blow the HTTP header size limit instead\n * advertises the statement id in `X-Appkit-Arrow-Columns-Ref`, and the\n * client fetches the names from `GET /columns/:statementId`.\n */\n private _setArrowColumnsHeader(\n res: express.Response,\n columnsRef: { columnNames?: string[]; statementId?: string },\n ): void {\n const names = columnsRef.columnNames;\n if (!names || names.length === 0) return;\n\n const encoded = encodeURIComponent(JSON.stringify(names));\n if (encoded.length <= MAX_ARROW_COLUMNS_HEADER_BYTES) {\n res.setHeader(\"X-Appkit-Arrow-Columns\", encoded);\n return;\n }\n if (columnsRef.statementId) {\n res.setHeader(\"X-Appkit-Arrow-Columns-Ref\", columnsRef.statementId);\n } else {\n logger.warn(\n \"Arrow column names exceed the header limit and no statement id is available for the fallback endpoint; client will fall back to the raw schema names\",\n );\n }\n }\n\n /**\n * ARROW_STREAM query handler: stream the raw Arrow IPC bytes back as the\n * HTTP response body — no SSE, no server-side stash, no second\n * `/arrow-result` request.\n *\n * The first chunk is pulled before headers are sent so a failure still\n * yields a clean JSON error; once bytes are in flight a mid-stream failure\n * can only abort the socket. Warehouse readiness is awaited (no SSE\n * progress on this path) — a no-op for a warm warehouse, a blocking wait\n * on a cold start. Runs under the user's context for `.obo.sql` queries.\n */\n private async _handleArrowStreamQuery(\n req: express.Request,\n res: express.Response,\n query_key: string,\n query: string,\n isAsUser: boolean,\n parameters: IAnalyticsQueryRequest[\"parameters\"],\n ): Promise<void> {\n const executor = isAsUser ? this._asUserScoped(req) : this;\n const executorKey = isAsUser ? this.resolveUserId(req) : \"global\";\n const abortController = new AbortController();\n const onClose = () => abortController.abort();\n res.on(\"close\", onClose);\n const signal = abortController.signal;\n\n // Fail-fast: bound the wait for the first byte (warehouse readiness +\n // execute + first chunk) so a stuck/overloaded warehouse returns a clear\n // 503 instead of hanging until the client gives up. Cleared once the\n // first chunk arrives — a legitimately long stream is never interrupted.\n const firstByteTimeoutMs =\n this.config.arrowFirstByteTimeoutMs ??\n DEFAULT_ARROW_FIRST_BYTE_TIMEOUT_MS;\n let timedOut = false;\n const failFast = setTimeout(() => {\n timedOut = true;\n abortController.abort();\n }, firstByteTimeoutMs);\n\n try {\n // Run warehouse readiness in the SAME identity context as the query:\n // for `.obo.sql`, `executor` is the `asUser(req)` proxy, so\n // `getWorkspaceClient()` inside resolves to the user's client (matching\n // the SSE path). Calling it bare here would auto-start the warehouse as\n // the service principal even for OBO requests.\n await executor._ensureArrowWarehouseReady(signal);\n\n const processedParams = await this.queryProcessor.processQueryParams(\n query,\n parameters,\n );\n\n const warehouseId = await getWarehouseId();\n\n // Populated by `deliverArrowBytes` from the result manifest before the\n // first chunk is yielded, so the header below carries the real names.\n const columnsRef: { columnNames?: string[]; statementId?: string } = {};\n const bytes = deliverArrowBytes(\n // Wrap the executor so the INLINE attempt runs through the interceptor\n // chain (cache + retry), matching the JSON path. Only inline attachments\n // are cached; EXTERNAL_LINKS carry expiring pre-signed URLs and are\n // never cached (see `_arrowCachingExecutor`).\n this._arrowCachingExecutor(\n executor,\n query_key,\n query,\n parameters,\n executorKey,\n ),\n this.SQLClient,\n query,\n processedParams,\n columnsRef,\n signal,\n {\n // Skip the doomed INLINE probe on a warehouse already known to need\n // EXTERNAL_LINKS; remember the resolved mode for next time.\n capabilityHint: this._arrowCapability.get(warehouseId),\n onCapabilityResolved: (capability) =>\n this._arrowCapability.set(warehouseId, capability),\n },\n );\n const first = await bytes.next();\n // First byte in hand — stop the fail-fast clock.\n clearTimeout(failFast);\n\n res.setHeader(\"Content-Type\", \"application/vnd.apache.arrow.stream\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n this._setArrowColumnsHeader(res, columnsRef);\n\n if (!first.done) {\n await writeChunk(res, first.value);\n for await (const buf of bytes) {\n await writeChunk(res, buf);\n }\n }\n res.end();\n } catch (error) {\n clearTimeout(failFast);\n // Fail-fast timeout: the warehouse never produced a first byte. This also\n // aborts the signal, so it must be handled before the generic\n // `signal.aborted` branch below. Headers aren't sent yet (we time out\n // before the first chunk), so a clean 503 is still possible.\n if (timedOut) {\n logger.warn(\n \"Arrow query timed out before first byte after %dms\",\n firstByteTimeoutMs,\n );\n res.status(503).json({\n error:\n \"The SQL warehouse is starting or overloaded and did not respond in time. Please retry.\",\n errorCode: \"WAREHOUSE_UNAVAILABLE\",\n plugin: this.name,\n });\n return;\n }\n // Client disconnect / unmount aborts the signal (see `onClose`). That's\n // routine UI behavior, not a server error — tear down quietly whether it\n // fires before or after headers. Checked before the headersSent branch so\n // a mid-stream disconnect doesn't spam ERROR logs / alerting.\n if (signal.aborted) {\n if (res.headersSent) res.destroy();\n else res.end();\n return;\n }\n if (res.headersSent) {\n logger.error(\"Arrow query stream failed mid-flight: %O\", error);\n res.destroy(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n logger.error(\"Arrow query error: %O\", error);\n // Do not echo upstream / SDK error text — it can include statement\n // fragments and correlation ids. Keep the structured code so the\n // client can branch (e.g. RESULT_TOO_LARGE_FOR_JSON_FALLBACK,\n // ARROW_DELIVERY_UNSUPPORTED).\n const errorCode =\n error instanceof ExecutionError ? error.errorCode : undefined;\n res.status(500).json({\n // `clientMessage` is the sanitized, actionable text (e.g. \"Re-run with\n // JSON_ARRAY\" for ARROW_DELIVERY_UNSUPPORTED); it never carries raw\n // warehouse/SDK strings. Fall back to a generic message otherwise.\n error:\n error instanceof AppKitError\n ? error.clientMessage\n : \"Unable to execute query\",\n errorCode,\n plugin: this.name,\n });\n } finally {\n res.off(\"close\", onClose);\n }\n }\n\n /**\n * Await SQL warehouse readiness for the direct-binary Arrow path. There is no\n * SSE progress channel here — readiness is simply awaited, bounded by the\n * caller's abort signal / fail-fast timeout. Invoked via the request executor\n * (`asUser(req)` for `.obo.sql`) so `getWorkspaceClient()` resolves in the\n * correct identity context rather than defaulting to the service principal.\n */\n async _ensureArrowWarehouseReady(signal: AbortSignal): Promise<void> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n const startupTimeoutMs =\n this.config.warehouseStartupTimeoutMs ??\n DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS;\n const autoStart = this.config.autoStartWarehouse ?? true;\n await this.SQLClient.ensureWarehouseRunning(workspaceClient, warehouseId, {\n signal,\n timeoutMs: startupTimeoutMs,\n autoStart,\n onStatus: () => {},\n });\n }\n\n /**\n * Wrap an executor so the `INLINE + ARROW_STREAM` attempt is served from\n * (and populates) the same per-user TTL cache the JSON path uses — otherwise\n * every arrow chart render is a fresh warehouse execution, unlike its JSON\n * twin. Caching is deliberately scoped to inline attachments:\n *\n * - INLINE results carry a bounded (<=25 MiB) base64 `attachment` with the\n * same lifecycle as cached JSON rows — safe to cache.\n * - EXTERNAL_LINKS results carry short-lived pre-signed URLs that expire in\n * minutes; caching them would serve dead links, so those pass through\n * uncached (only the tiny link metadata would be cached anyway).\n *\n * Uses `this.cache.getOrExecute` directly rather than `this.execute()`\n * because `execute()` reduces a thrown error to `{ ok:false, message }`,\n * dropping the `errorCode` the capability fallback classifies on. The cache\n * re-throws `AppKitError`s intact and never caches a rejection, so the\n * INLINE→EXTERNAL_LINKS fallback still sees the structured rejection.\n */\n private _arrowCachingExecutor(\n executor: AnalyticsPlugin,\n query_key: string,\n query: string,\n parameters: IAnalyticsQueryRequest[\"parameters\"],\n executorKey: string,\n ): QueryExecutor {\n const hashedQuery = this.queryProcessor.hashQuery(query);\n const cache = this.cache;\n const ttl = queryDefaults.cache?.ttl;\n return {\n query: (q, params, formatParameters, signal) => {\n // Only the inline-arrow attempt is cacheable — EXTERNAL_LINKS carry\n // short-lived pre-signed URLs, so those pass straight through.\n if (\n formatParameters.disposition !== \"INLINE\" ||\n formatParameters.format !== \"ARROW_STREAM\"\n ) {\n return executor.query(q, params, formatParameters, signal);\n }\n // On a standard warehouse this throws a capability rejection — the\n // cache never stores a rejection, so the fallback still sees the\n // structured error. On Reyden it returns a bounded (<=25 MiB)\n // attachment that caches like the JSON path's rows. The shared signal\n // dedupes concurrent renders (e.g. React StrictMode double-mount).\n return cache.getOrExecute(\n [\n \"analytics:query:arrow\",\n query_key,\n JSON.stringify(parameters),\n hashedQuery,\n executorKey,\n ],\n (sharedSignal) =>\n executor.query(q, params, formatParameters, sharedSignal ?? signal),\n executorKey,\n { ttl, callerSignal: signal },\n );\n },\n };\n }\n\n /**\n * Execute a SQL query using the current execution context.\n *\n * When called directly: uses service principal credentials.\n * When called via asUser(req).query(...): uses user's credentials.\n *\n * @example\n * ```typescript\n * // Service principal execution\n * const result = await analytics.query(\"SELECT * FROM table\")\n *\n * // User context execution (in route handler)\n * const result = await appkit.asUser(req).analytics.query(\"SELECT * FROM table\")\n * ```\n */\n async query(\n query: string,\n parameters?: Record<string, SQLTypeMarker | null | undefined>,\n formatParameters?: Record<string, any>,\n signal?: AbortSignal,\n ): Promise<any> {\n const workspaceClient = getWorkspaceClient();\n const warehouseId = await getWarehouseId();\n\n const { statement, parameters: sqlParameters } =\n this.queryProcessor.convertToSQLParameters(query, parameters);\n\n const response = await this.SQLClient.executeStatement(\n workspaceClient,\n {\n statement,\n warehouse_id: warehouseId,\n parameters: sqlParameters,\n ...formatParameters,\n },\n signal,\n );\n\n return response.result;\n }\n\n async shutdown(): Promise<void> {\n this.streamManager.abortAll();\n }\n\n private tools = {\n query: defineTool({\n description:\n \"Execute a read-only SQL query against the Databricks SQL warehouse. Only SELECT, WITH, SHOW, EXPLAIN, and DESCRIBE statements are accepted; writes are rejected. Returns the query results as JSON.\",\n schema: z.object({\n query: z\n .string()\n .describe(\n \"The SQL query to execute. Must be a SELECT, WITH, SHOW, EXPLAIN, or DESCRIBE statement.\",\n ),\n }),\n annotations: {\n effect: \"read\",\n requiresUserContext: true,\n },\n autoInheritable: true,\n execute: (args, signal) => {\n assertReadOnlySql(args.query);\n return this.query(args.query, undefined, undefined, signal);\n },\n }),\n };\n\n getAgentTools(): AgentToolDefinition[] {\n return toolsFromRegistry(this.tools);\n }\n\n async executeAgentTool(\n name: string,\n args: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n return executeFromRegistry(this.tools, name, args, signal);\n }\n\n /**\n * Returns the plugin's tools as a keyed record of `ToolkitEntry` markers.\n * Called by the agents plugin (via `resolveToolkitFromProvider`) to spread\n * a filtered, renamed view of the plugin's tools into an agent's tool\n * index. Inside the function form of `AgentDefinition.tools`, callers\n * reach this method via `plugins.analytics.toolkit(opts)`.\n */\n toolkit(opts?: import(\"../../core/agent/types\").ToolkitOptions) {\n return buildToolkitEntries(this.name, this.tools, opts);\n }\n\n /**\n * Returns the public exports for the analytics plugin.\n * Note: `asUser()` is automatically added by AppKit.\n */\n exports() {\n return {\n /**\n * Execute a SQL query using service principal credentials.\n */\n query: this.query,\n };\n }\n}\n\n/**\n * Write one chunk to the response honoring backpressure: if the socket\n * buffer is full (`res.write` returns false), wait for `drain` before\n * resolving so a slow client can't balloon Node's internal write queue and\n * defeat the constant-memory goal of streaming.\n *\n * @internal exported for unit testing the backpressure/disconnect behavior.\n */\nexport function writeChunk(\n res: express.Response,\n bytes: Uint8Array,\n): Promise<void> {\n const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n // If the socket is already gone, `res.write` won't return true and the\n // `drain`/`close`/`error` events have already fired — so the promise below\n // would never settle, wedging the for-await loop and the upstream reader.\n // Reject up front instead.\n if (res.destroyed || res.writableEnded) {\n return Promise.reject(\n new DOMException(\"The response stream closed\", \"AbortError\"),\n );\n }\n if (res.write(buf)) return Promise.resolve();\n // Backpressured: resolve on `drain`, but also settle on `close`/`error`. A\n // client that disconnects mid-backpressure never emits `drain` on the\n // destroyed socket, so waiting on `drain` alone would wedge this promise —\n // and with it the awaiting for-await loop and the upstream Arrow reader —\n // forever. Rejecting instead unwinds the stream so its `finally` can cancel\n // the reader.\n return new Promise<void>((resolve, reject) => {\n const cleanup = () => {\n res.off(\"drain\", onDrain);\n res.off(\"close\", onClose);\n res.off(\"error\", onClose);\n };\n const onDrain = () => {\n cleanup();\n resolve();\n };\n const onClose = () => {\n cleanup();\n reject(new DOMException(\"The response stream closed\", \"AbortError\"));\n };\n res.once(\"drain\", onDrain);\n res.once(\"close\", onClose);\n res.once(\"error\", onClose);\n });\n}\n\n/**\n * Fail-fast ceiling on the wait for the first Arrow byte (warehouse\n * readiness + execute + first chunk). Past this a stuck/overloaded warehouse\n * yields a clear 503 instead of hanging. Override per plugin via\n * `arrowFirstByteTimeoutMs`.\n */\nconst DEFAULT_ARROW_FIRST_BYTE_TIMEOUT_MS = 120_000;\n\n/**\n * Byte ceiling for the `X-Appkit-Arrow-Columns` header value. Beyond this (a\n * very wide schema) the names are served via the `/columns/:statementId`\n * fallback endpoint instead of the header. Kept well under the common ~8 KiB\n * per-header limit.\n */\nconst MAX_ARROW_COLUMNS_HEADER_BYTES = 6000;\n\n/**\n * @internal\n */\nexport const analytics = toPlugin(AnalyticsPlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,SAAS,aAAa,YAAY;;;;;;;;;AAUxC,gBAAgB,gBACd,OACkC;CAClC,MAAM,QAAa,EAAE;CACrB,IAAI,OAA4B;CAChC,IAAI,UAAU;CACd,IAAI,QAAiB;CAErB,MAAM,eAAqB;AACzB,UAAQ;AACR,SAAO;;AAKT,CAAK,OAAO,UAAU;AACpB,QAAM,KAAK,MAAM;AACjB,UAAQ;GACR,CAAC,WACK;AACJ,YAAU;AACV,UAAQ;KAET,QAAQ;AACP,UAAQ;AACR,YAAU;AACV,UAAQ;GAEX;AAED,QAAO,CAAC,WAAW,MAAM,SAAS,GAAG;AACnC,SAAO,MAAM,SAAS,EAAG,OAAM,MAAM,OAAO;AAC5C,MAAI,QAAS;AACb,QAAM,IAAI,SAAe,YAAY;AACnC,UAAO;IACP;;AAEJ,KAAI,MAAO,OAAM;;AAGnB,IAAa,kBAAb,cAAqC,OAA+B;;CAElE,OAAO,WAAW,eAA4BA,iBAAS;CAEvD,OAAiB,cAAc;CAI/B,AAAQ;CACR,AA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AAO;;;;;;;;;CAU5D,QAAQ,MAAwD;AAC9D,SAAO,oBAAoB,KAAK,MAAM,KAAK,OAAO,KAAK;;;;;;CAOzD,UAAU;AACR,SAAO,EAIL,OAAO,KAAK,OACb;;;;;;;;;;;AAYL,SAAgB,WACd,KACA,OACe;CACf,MAAM,MAAM,OAAO,KAAK,MAAM,QAAQ,MAAM,YAAY,MAAM,WAAW;AAKzE,KAAI,IAAI,aAAa,IAAI,cACvB,QAAO,QAAQ,OACb,IAAI,aAAa,8BAA8B,aAAa,CAC7D;AAEH,KAAI,IAAI,MAAM,IAAI,CAAE,QAAO,QAAQ,SAAS;AAO5C,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,gBAAgB;AACpB,OAAI,IAAI,SAAS,QAAQ;AACzB,OAAI,IAAI,SAAS,QAAQ;AACzB,OAAI,IAAI,SAAS,QAAQ;;EAE3B,MAAM,gBAAgB;AACpB,YAAS;AACT,YAAS;;EAEX,MAAM,gBAAgB;AACpB,YAAS;AACT,UAAO,IAAI,aAAa,8BAA8B,aAAa,CAAC;;AAEtE,MAAI,KAAK,SAAS,QAAQ;AAC1B,MAAI,KAAK,SAAS,QAAQ;AAC1B,MAAI,KAAK,SAAS,QAAQ;GAC1B;;;;;;;;AASJ,MAAM,sCAAsC;;;;;;;AAQ5C,MAAM,iCAAiC;;;;AAKvC,MAAa,YAAY,SAAS,gBAAgB"}
@@ -1,3 +1,4 @@
1
+ import { isPlainObject as isPlainObject$1 } from "../../../utils/is-plain-object.js";
1
2
  import { filterOperatorsForKind } from "../../../database/schema-builder/types.js";
2
3
  import { DatabasePluginError } from "../../../database/errors.js";
3
4
  import { MAX_SERIALIZED_DEPTH, MAX_SERIALIZED_NODES } from "../defaults.js";
@@ -7,8 +8,7 @@ import { compileColumn } from "./codecs.js";
7
8
  /** A bare object literal; a `Date`, class instance, or `Map` is not JSON. */
8
9
  function isPlainObject(value) {
9
10
  if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
10
- const prototype = Object.getPrototypeOf(value);
11
- return prototype === Object.prototype || prototype === null;
11
+ return isPlainObject$1(value);
12
12
  }
13
13
  /** A serializer that breaks its contract is trusted code failing, not input. */
14
14
  function serializerFault() {
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","names":[],"sources":["../../../../src/plugins/database/crud/contract.ts"],"sourcesContent":["import { DatabasePluginError } from \"../../../database/errors\";\nimport type { Row } from \"../../../database/runtime\";\nimport type { AppKitTable } from \"../../../database/schema-builder\";\nimport { filterOperatorsForKind } from \"../../../database/schema-builder/types\";\nimport { MAX_SERIALIZED_DEPTH, MAX_SERIALIZED_NODES } from \"../defaults\";\nimport { type CompiledColumn, compileColumn, type JsonValue } from \"./codecs\";\n\n/** One relation edge wired to the contract of its target table. */\nexport interface CrudRelation {\n readonly cardinality: \"toOne\" | \"toMany\";\n readonly target: CrudTable;\n}\n\n/** Private HTTP contract compiled once for one exposed table. */\nexport interface CrudTable {\n readonly name: string;\n readonly primaryKey?: CompiledColumn;\n readonly columns: ReadonlyMap<string, CompiledColumn>;\n /** Public columns a request may project. */\n readonly selectable: ReadonlySet<string>;\n /** Public columns a request may filter or order by. */\n readonly queryable: ReadonlySet<string>;\n /** Public columns a create body may set, including a caller-chosen key. */\n readonly creatable: ReadonlySet<string>;\n /** Public columns an update body may set; a key or a stamp is never one. */\n readonly updatable: ReadonlySet<string>;\n readonly relations: ReadonlyMap<string, CrudRelation>;\n projectPublicRow(row: Row): JsonValue;\n sanitizeSerializedRow(row: unknown): JsonValue;\n}\n\ntype MutableCrudTable = Omit<CrudTable, \"relations\"> & {\n readonly relations: Map<string, CrudRelation>;\n};\n\ninterface SanitizeState {\n nodes: number;\n readonly ancestors: Set<object>;\n}\n\n/** A bare object literal; a `Date`, class instance, or `Map` is not JSON. */\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** A serializer that breaks its contract is trusted code failing, not input. */\nfunction serializerFault(): never {\n throw new DatabasePluginError(\"INTERNAL\", \"read\");\n}\n\n/** Charge one value against the output budget before descending into it. */\nfunction countNode(depth: number, state: SanitizeState): void {\n state.nodes += 1;\n if (state.nodes > MAX_SERIALIZED_NODES || depth > MAX_SERIALIZED_DEPTH) {\n serializerFault();\n }\n}\n\n/** Walk a container while its ancestors are tracked, so a cycle cannot pass. */\nfunction enterObject<T>(\n value: object,\n state: SanitizeState,\n visit: () => T,\n): T {\n if (state.ancestors.has(value)) serializerFault();\n state.ancestors.add(value);\n try {\n return visit();\n } finally {\n state.ancestors.delete(value);\n }\n}\n\n/** Accept a serializer's own added value only where it is already JSON. */\nfunction sanitizeJson(\n value: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n countNode(depth, state);\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) serializerFault();\n return value;\n }\n if (Array.isArray(value)) {\n return enterObject(value, state, () =>\n value.map((item) => sanitizeJson(item, depth + 1, state)),\n );\n }\n if (!isPlainObject(value)) serializerFault();\n return enterObject(value, state, () => {\n // A null prototype keeps `__proto__` an ordinary key instead of a setter.\n const out: Record<string, JsonValue> = Object.create(null);\n for (const [key, child] of Object.entries(value)) {\n if (child === undefined) continue;\n out[key] = sanitizeJson(child, depth + 1, state);\n }\n return out;\n });\n}\n\n/** Keep an included row under its own table's policy, one row or many. */\nfunction sanitizeRelation(\n target: CrudTable,\n value: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n if (value === null) return null;\n if (!Array.isArray(value)) return sanitizeRow(target, value, depth, state);\n countNode(depth, state);\n return enterObject(value, state, () =>\n value.map((row) => sanitizeRow(target, row, depth + 1, state)),\n );\n}\n\n/** Re-apply the private-column policy wherever the output stays contracted. */\nfunction sanitizeRow(\n table: CrudTable,\n row: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n countNode(depth, state);\n if (!isPlainObject(row)) serializerFault();\n return enterObject(row, state, () => {\n const out: Record<string, JsonValue> = {};\n for (const [key, child] of Object.entries(row)) {\n if (child === undefined) continue;\n if (table.columns.get(key)?.meta.isPrivate) continue;\n const relation = table.relations.get(key);\n out[key] = relation\n ? sanitizeRelation(relation.target, child, depth + 1, state)\n : sanitizeJson(child, depth + 1, state);\n }\n return out;\n });\n}\n\n/** The budget a caller's own JSON has to fit, same as the one going back out. */\nexport function boundedJson(value: unknown): JsonValue {\n return sanitizeJson(value, 0, { nodes: 0, ancestors: new Set() });\n}\n\n/** Project an included row through its own table; absent to-one reads null. */\nfunction projectRelation(target: CrudTable, value: unknown): JsonValue {\n if (value === null || value === undefined) return null;\n return Array.isArray(value)\n ? value.map((row) => target.projectPublicRow(row as Row))\n : target.projectPublicRow(value as Row);\n}\n\n/** Build the public JSON for one driver row, dropping anything uncontracted. */\nfunction projectRow(table: CrudTable, row: Row): JsonValue {\n const out: Record<string, JsonValue> = {};\n for (const [key, value] of Object.entries(row)) {\n const column = table.columns.get(key);\n if (column) {\n // Whatever the driver returned, only public contracted columns ship.\n if (!column.meta.isPrivate) out[key] = column.encode(value);\n continue;\n }\n const relation = table.relations.get(key);\n if (relation) out[key] = projectRelation(relation.target, value);\n }\n return out;\n}\n\n/** Compile one table's allowlists and codecs from its finalized metadata. */\nfunction compileTable(table: AppKitTable): MutableCrudTable {\n const columns = new Map<string, CompiledColumn>();\n const selectable = new Set<string>();\n const queryable = new Set<string>();\n const creatable = new Set<string>();\n const updatable = new Set<string>();\n let primaryKey: CompiledColumn | undefined;\n\n for (const meta of Object.values(table.$columns)) {\n const column = compileColumn(meta);\n columns.set(meta.columnName, column);\n // A private key must not power `GET /:table/:id`: per-id probing would\n // answer 200 or 404 on an identifier the schema hides, so over HTTP the\n // table is keyless — no detail route, and lists must name their own order.\n if (meta.primaryKey && !meta.isPrivate) primaryKey = column;\n if (meta.isPrivate) continue;\n selectable.add(meta.columnName);\n if (filterOperatorsForKind(meta.kind).length > 0) {\n queryable.add(meta.columnName);\n }\n // Database-generated identities belong to the server, never the caller.\n if (meta.serverGenerated || (meta.primaryKey && meta.defaultRandom))\n continue;\n creatable.add(meta.columnName);\n // Rewriting a key would move a row out from under every existing reference,\n // and rewriting a database-materialized stamp would rewrite history.\n if (meta.primaryKey || meta.defaultNow || meta.defaultRandom) continue;\n updatable.add(meta.columnName);\n }\n\n const compiled: MutableCrudTable = {\n name: table.$name,\n primaryKey,\n columns,\n selectable,\n queryable,\n creatable,\n updatable,\n relations: new Map(),\n projectPublicRow: (row) => projectRow(compiled, row),\n sanitizeSerializedRow: (row) =>\n sanitizeRow(compiled, row, 0, { nodes: 0, ancestors: new Set() }),\n };\n return compiled;\n}\n\n/**\n * Compile the HTTP contract for every exposed table and wire the relations\n * they share. A relation whose target is not exposed stays unreachable, so\n * enabling one table never widens another table's public surface.\n */\nexport function compileCrudTables(\n tables: Record<string, AppKitTable>,\n): Map<string, CrudTable> {\n const compiled = new Map<string, MutableCrudTable>();\n for (const table of Object.values(tables)) {\n compiled.set(table.$name, compileTable(table));\n }\n for (const table of Object.values(tables)) {\n const entry = compiled.get(table.$name);\n for (const relation of table.$relations) {\n const target = compiled.get(relation.targetTable);\n if (!entry || !target) continue;\n entry.relations.set(relation.name, {\n cardinality: relation.cardinality,\n target,\n });\n }\n }\n return compiled as Map<string, CrudTable>;\n}\n"],"mappings":";;;;;;;AAyCA,SAAgB,cACd,OACkC;AAClC,KAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CACrE,QAAO;CAET,MAAM,YAAY,OAAO,eAAe,MAAM;AAC9C,QAAO,cAAc,OAAO,aAAa,cAAc;;;AAIzD,SAAS,kBAAyB;AAChC,OAAM,IAAI,oBAAoB,YAAY,OAAO;;;AAInD,SAAS,UAAU,OAAe,OAA4B;AAC5D,OAAM,SAAS;AACf,KAAI,MAAM,QAAQ,wBAAwB,QAAQ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AAO,MAAM,SAAS,EAAE;EAChD,MAAM,SAAS,cAAc,KAAK;AAClC,UAAQ,IAAI,KAAK,YAAY,OAAO;AAIpC,MAAI,KAAK,cAAc,CAAC,KAAK,UAAW,cAAa;AACrD,MAAI,KAAK,UAAW;AACpB,aAAW,IAAI,KAAK,WAAW;AAC/B,MAAI,uBAAuB,KAAK,KAAK,CAAC,SAAS,EAC7C,WAAU,IAAI,KAAK,WAAW;AAGhC,MAAI,KAAK,mBAAoB,KAAK,cAAc,KAAK,cACnD;AACF,YAAU,IAAI,KAAK,WAAW;AAG9B,MAAI,KAAK,cAAc,KAAK,cAAc,KAAK,cAAe;AAC9D,YAAU,IAAI,KAAK,WAAW;;CAGhC,MAAM,WAA6B;EACjC,MAAM,MAAM;EACZ;EACA;EACA;EACA;EACA;EACA;EACA,2BAAW,IAAI,KAAK;EACpB,mBAAmB,QAAQ,WAAW,UAAU,IAAI;EACpD,wBAAwB,QACtB,YAAY,UAAU,KAAK,GAAG;GAAE,OAAO;GAAG,2BAAW,IAAI,KAAK;GAAE,CAAC;EACpE;AACD,QAAO;;;;;;;AAQT,SAAgB,kBACd,QACwB;CACxB,MAAM,2BAAW,IAAI,KAA+B;AACpD,MAAK,MAAM,SAAS,OAAO,OAAO,OAAO,CACvC,UAAS,IAAI,MAAM,OAAO,aAAa,MAAM,CAAC;AAEhD,MAAK,MAAM,SAAS,OAAO,OAAO,OAAO,EAAE;EACzC,MAAM,QAAQ,SAAS,IAAI,MAAM,MAAM;AACvC,OAAK,MAAM,YAAY,MAAM,YAAY;GACvC,MAAM,SAAS,SAAS,IAAI,SAAS,YAAY;AACjD,OAAI,CAAC,SAAS,CAAC,OAAQ;AACvB,SAAM,UAAU,IAAI,SAAS,MAAM;IACjC,aAAa,SAAS;IACtB;IACD,CAAC;;;AAGN,QAAO"}
1
+ {"version":3,"file":"contract.js","names":["hasPlainObjectPrototype"],"sources":["../../../../src/plugins/database/crud/contract.ts"],"sourcesContent":["import { DatabasePluginError } from \"../../../database/errors\";\nimport type { Row } from \"../../../database/runtime\";\nimport type { AppKitTable } from \"../../../database/schema-builder\";\nimport { filterOperatorsForKind } from \"../../../database/schema-builder/types\";\nimport { isPlainObject as hasPlainObjectPrototype } from \"../../../utils/is-plain-object\";\nimport { MAX_SERIALIZED_DEPTH, MAX_SERIALIZED_NODES } from \"../defaults\";\nimport { type CompiledColumn, compileColumn, type JsonValue } from \"./codecs\";\n\n/** One relation edge wired to the contract of its target table. */\nexport interface CrudRelation {\n readonly cardinality: \"toOne\" | \"toMany\";\n readonly target: CrudTable;\n}\n\n/** Private HTTP contract compiled once for one exposed table. */\nexport interface CrudTable {\n readonly name: string;\n readonly primaryKey?: CompiledColumn;\n readonly columns: ReadonlyMap<string, CompiledColumn>;\n /** Public columns a request may project. */\n readonly selectable: ReadonlySet<string>;\n /** Public columns a request may filter or order by. */\n readonly queryable: ReadonlySet<string>;\n /** Public columns a create body may set, including a caller-chosen key. */\n readonly creatable: ReadonlySet<string>;\n /** Public columns an update body may set; a key or a stamp is never one. */\n readonly updatable: ReadonlySet<string>;\n readonly relations: ReadonlyMap<string, CrudRelation>;\n projectPublicRow(row: Row): JsonValue;\n sanitizeSerializedRow(row: unknown): JsonValue;\n}\n\ntype MutableCrudTable = Omit<CrudTable, \"relations\"> & {\n readonly relations: Map<string, CrudRelation>;\n};\n\ninterface SanitizeState {\n nodes: number;\n readonly ancestors: Set<object>;\n}\n\n/** A bare object literal; a `Date`, class instance, or `Map` is not JSON. */\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n return hasPlainObjectPrototype(value);\n}\n\n/** A serializer that breaks its contract is trusted code failing, not input. */\nfunction serializerFault(): never {\n throw new DatabasePluginError(\"INTERNAL\", \"read\");\n}\n\n/** Charge one value against the output budget before descending into it. */\nfunction countNode(depth: number, state: SanitizeState): void {\n state.nodes += 1;\n if (state.nodes > MAX_SERIALIZED_NODES || depth > MAX_SERIALIZED_DEPTH) {\n serializerFault();\n }\n}\n\n/** Walk a container while its ancestors are tracked, so a cycle cannot pass. */\nfunction enterObject<T>(\n value: object,\n state: SanitizeState,\n visit: () => T,\n): T {\n if (state.ancestors.has(value)) serializerFault();\n state.ancestors.add(value);\n try {\n return visit();\n } finally {\n state.ancestors.delete(value);\n }\n}\n\n/** Accept a serializer's own added value only where it is already JSON. */\nfunction sanitizeJson(\n value: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n countNode(depth, state);\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) serializerFault();\n return value;\n }\n if (Array.isArray(value)) {\n return enterObject(value, state, () =>\n value.map((item) => sanitizeJson(item, depth + 1, state)),\n );\n }\n if (!isPlainObject(value)) serializerFault();\n return enterObject(value, state, () => {\n // A null prototype keeps `__proto__` an ordinary key instead of a setter.\n const out: Record<string, JsonValue> = Object.create(null);\n for (const [key, child] of Object.entries(value)) {\n if (child === undefined) continue;\n out[key] = sanitizeJson(child, depth + 1, state);\n }\n return out;\n });\n}\n\n/** Keep an included row under its own table's policy, one row or many. */\nfunction sanitizeRelation(\n target: CrudTable,\n value: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n if (value === null) return null;\n if (!Array.isArray(value)) return sanitizeRow(target, value, depth, state);\n countNode(depth, state);\n return enterObject(value, state, () =>\n value.map((row) => sanitizeRow(target, row, depth + 1, state)),\n );\n}\n\n/** Re-apply the private-column policy wherever the output stays contracted. */\nfunction sanitizeRow(\n table: CrudTable,\n row: unknown,\n depth: number,\n state: SanitizeState,\n): JsonValue {\n countNode(depth, state);\n if (!isPlainObject(row)) serializerFault();\n return enterObject(row, state, () => {\n const out: Record<string, JsonValue> = {};\n for (const [key, child] of Object.entries(row)) {\n if (child === undefined) continue;\n if (table.columns.get(key)?.meta.isPrivate) continue;\n const relation = table.relations.get(key);\n out[key] = relation\n ? sanitizeRelation(relation.target, child, depth + 1, state)\n : sanitizeJson(child, depth + 1, state);\n }\n return out;\n });\n}\n\n/** The budget a caller's own JSON has to fit, same as the one going back out. */\nexport function boundedJson(value: unknown): JsonValue {\n return sanitizeJson(value, 0, { nodes: 0, ancestors: new Set() });\n}\n\n/** Project an included row through its own table; absent to-one reads null. */\nfunction projectRelation(target: CrudTable, value: unknown): JsonValue {\n if (value === null || value === undefined) return null;\n return Array.isArray(value)\n ? value.map((row) => target.projectPublicRow(row as Row))\n : target.projectPublicRow(value as Row);\n}\n\n/** Build the public JSON for one driver row, dropping anything uncontracted. */\nfunction projectRow(table: CrudTable, row: Row): JsonValue {\n const out: Record<string, JsonValue> = {};\n for (const [key, value] of Object.entries(row)) {\n const column = table.columns.get(key);\n if (column) {\n // Whatever the driver returned, only public contracted columns ship.\n if (!column.meta.isPrivate) out[key] = column.encode(value);\n continue;\n }\n const relation = table.relations.get(key);\n if (relation) out[key] = projectRelation(relation.target, value);\n }\n return out;\n}\n\n/** Compile one table's allowlists and codecs from its finalized metadata. */\nfunction compileTable(table: AppKitTable): MutableCrudTable {\n const columns = new Map<string, CompiledColumn>();\n const selectable = new Set<string>();\n const queryable = new Set<string>();\n const creatable = new Set<string>();\n const updatable = new Set<string>();\n let primaryKey: CompiledColumn | undefined;\n\n for (const meta of Object.values(table.$columns)) {\n const column = compileColumn(meta);\n columns.set(meta.columnName, column);\n // A private key must not power `GET /:table/:id`: per-id probing would\n // answer 200 or 404 on an identifier the schema hides, so over HTTP the\n // table is keyless — no detail route, and lists must name their own order.\n if (meta.primaryKey && !meta.isPrivate) primaryKey = column;\n if (meta.isPrivate) continue;\n selectable.add(meta.columnName);\n if (filterOperatorsForKind(meta.kind).length > 0) {\n queryable.add(meta.columnName);\n }\n // Database-generated identities belong to the server, never the caller.\n if (meta.serverGenerated || (meta.primaryKey && meta.defaultRandom))\n continue;\n creatable.add(meta.columnName);\n // Rewriting a key would move a row out from under every existing reference,\n // and rewriting a database-materialized stamp would rewrite history.\n if (meta.primaryKey || meta.defaultNow || meta.defaultRandom) continue;\n updatable.add(meta.columnName);\n }\n\n const compiled: MutableCrudTable = {\n name: table.$name,\n primaryKey,\n columns,\n selectable,\n queryable,\n creatable,\n updatable,\n relations: new Map(),\n projectPublicRow: (row) => projectRow(compiled, row),\n sanitizeSerializedRow: (row) =>\n sanitizeRow(compiled, row, 0, { nodes: 0, ancestors: new Set() }),\n };\n return compiled;\n}\n\n/**\n * Compile the HTTP contract for every exposed table and wire the relations\n * they share. A relation whose target is not exposed stays unreachable, so\n * enabling one table never widens another table's public surface.\n */\nexport function compileCrudTables(\n tables: Record<string, AppKitTable>,\n): Map<string, CrudTable> {\n const compiled = new Map<string, MutableCrudTable>();\n for (const table of Object.values(tables)) {\n compiled.set(table.$name, compileTable(table));\n }\n for (const table of Object.values(tables)) {\n const entry = compiled.get(table.$name);\n for (const relation of table.$relations) {\n const target = compiled.get(relation.targetTable);\n if (!entry || !target) continue;\n entry.relations.set(relation.name, {\n cardinality: relation.cardinality,\n target,\n });\n }\n }\n return compiled as Map<string, CrudTable>;\n}\n"],"mappings":";;;;;;;;AA0CA,SAAgB,cACd,OACkC;AAClC,KAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CACrE,QAAO;AAET,QAAOA,gBAAwB,MAAM;;;AAIvC,SAAS,kBAAyB;AAChC,OAAM,IAAI,oBAAoB,YAAY,OAAO;;;AAInD,SAAS,UAAU,OAAe,OAA4B;AAC5D,OAAM,SAAS;AACf,KAAI,MAAM,QAAQ,wBAAwB,QAAQ,qBAChD,kBAAiB;;;AAKrB,SAAS,YACP,OACA,OACA,OACG;AACH,KAAI,MAAM,UAAU,IAAI,MAAM,CAAE,kBAAiB;AACjD,OAAM,UAAU,IAAI,MAAM;AAC1B,KAAI;AACF,SAAO,OAAO;WACN;AACR,QAAM,UAAU,OAAO,MAAM;;;;AAKjC,SAAS,aACP,OACA,OACA,OACW;AACX,WAAU,OAAO,MAAM;A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I,KAAK,WAAW;AAGhC,MAAI,KAAK,mBAAoB,KAAK,cAAc,KAAK,cACnD;AACF,YAAU,IAAI,KAAK,WAAW;AAG9B,MAAI,KAAK,cAAc,KAAK,cAAc,KAAK,cAAe;AAC9D,YAAU,IAAI,KAAK,WAAW;;CAGhC,MAAM,WAA6B;EACjC,MAAM,MAAM;EACZ;EACA;EACA;EACA;EACA;EACA;EACA,2BAAW,IAAI,KAAK;EACpB,mBAAmB,QAAQ,WAAW,UAAU,IAAI;EACpD,wBAAwB,QACtB,YAAY,UAAU,KAAK,GAAG;GAAE,OAAO;GAAG,2BAAW,IAAI,KAAK;GAAE,CAAC;EACpE;AACD,QAAO;;;;;;;AAQT,SAAgB,kBACd,QACwB;CACxB,MAAM,2BAAW,IAAI,KAA+B;AACpD,MAAK,MAAM,SAAS,OAAO,OAAO,OAAO,CACvC,UAAS,IAAI,MAAM,OAAO,aAAa,MAAM,CAAC;AAEhD,MAAK,MAAM,SAAS,OAAO,OAAO,OAAO,EAAE;EACzC,MAAM,QAAQ,SAAS,IAAI,MAAM,MAAM;AACvC,OAAK,MAAM,YAAY,MAAM,YAAY;GACvC,MAAM,SAAS,SAAS,IAAI,SAAS,YAAY;AACjD,OAAI,CAAC,SAAS,CAAC,OAAQ;AACvB,SAAM,UAAU,IAAI,SAAS,MAAM;IACjC,aAAa,SAAS;IACtB;IACD,CAAC;;;AAGN,QAAO"}
@@ -1,9 +1,9 @@
1
1
  import { BasePluginConfig, PluginConstructor } from "../../shared/src/plugin.js";
2
2
  import "../../shared/src/index.js";
3
3
  import { Schema } from "../../database/schema-builder/types.js";
4
+ import { PluginManifest } from "../../registry/types.js";
4
5
  import { Plugin } from "../../plugin/plugin.js";
5
6
  import "../../plugin/index.js";
6
- import { PluginManifest } from "../../registry/types.js";
7
7
  import "../../registry/index.js";
8
8
  import { DatabaseExports } from "./entity-types.js";
9
9
  import { DefaultDatabaseSchema, IDatabaseConfig } from "./types.js";
@@ -2,10 +2,10 @@ import { AgentToolDefinition, ToolProvider } from "../../shared/src/agent.js";
2
2
  import { IAppRouter, ToPlugin } from "../../shared/src/plugin.js";
3
3
  import "../../shared/src/index.js";
4
4
  import { ToolkitEntry, ToolkitOptions } from "../../core/agent/types.js";
5
+ import { PluginManifest, ResourceRequirement } from "../../registry/types.js";
5
6
  import { Plugin } from "../../plugin/plugin.js";
6
7
  import "../../plugin/index.js";
7
8
  import { FilePolicy, FilePolicyUser } from "./policy.js";
8
- import { PluginManifest, ResourceRequirement } from "../../registry/types.js";
9
9
  import "../../registry/index.js";
10
10
  import { FilesExport, IFilesConfig, VolumeAPI, VolumeConfig } from "./types.js";
11
11
  import "../../index.js";
@@ -69,7 +69,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
69
69
  * return a policy user explicitly marked `isServicePrincipal: true`, so
70
70
  * even in dev a `usersOnly`-style policy that gates on
71
71
  * `!user.isServicePrincipal` cannot be tricked. The matching SDK execution
72
- * path also falls through to the SP client (no `runInUserContext` wrap),
72
+ * path also falls through to the SP client (no `runInCallerContext` wrap),
73
73
  * so the policy user and the SDK identity stay aligned.
74
74
  */
75
75
  private _extractUser;
@@ -104,7 +104,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
104
104
  * NOTE: This method only selects which identity the *policy* sees. The
105
105
  * matching SDK execution identity is selected separately by
106
106
  * `_resolveAuthForRequest` and applied via `_runWithAuth` /
107
- * `runInUserContext` in each handler. The two selections are designed to
107
+ * `runInCallerContext` in each handler. The two selections are designed to
108
108
  * converge on the same identity per the policy-user matrix in the docs —
109
109
  * see `docs/docs/plugins/files.md#policy-user-matrix`.
110
110
  */
@@ -159,7 +159,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
159
159
  *
160
160
  * On OBO volumes the read cache is disabled (see `_readSettings`), so
161
161
  * invalidation is a no-op here for `mode === "on-behalf-of-user"`. The
162
- * cache layer is keyed by `getCurrentUserId()`, so user A's writes can
162
+ * cache layer is keyed by `getCurrentPrincipalId()`, so user A's writes can
163
163
  * only invalidate user A's cache entry — user B would otherwise see stale
164
164
  * data for the same volume/path until TTL. Disabling the cache on OBO
165
165
  * trades read performance for correctness; the alternative is a
@@ -197,7 +197,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
197
197
  private _handleDelete;
198
198
  private _resolveAuth;
199
199
  /**
200
- * Build a `UserContext` from request headers when both
200
+ * Build a `CallerContext` from request headers when both
201
201
  * `x-forwarded-access-token` and `x-forwarded-user` are present, otherwise
202
202
  * return `null`. Used by OBO route handlers to wrap SDK calls in the
203
203
  * end-user's identity. A `null` result means "fall back to the service
@@ -209,7 +209,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
209
209
  /**
210
210
  * Build the telemetry attribute hash for the `files.auth_mode` span
211
211
  * attribute. The value reflects what operationally happened — i.e.
212
- * whether `runInUserContext` actually wrapped the SDK call:
212
+ * whether `runInCallerContext` actually wrapped the SDK call:
213
213
  * - HTTP route on OBO volume + valid token → `"on-behalf-of-user"`.
214
214
  * - HTTP route on OBO volume + dev-fallback (no token) →
215
215
  * `"service-principal"` (the route falls through to the SP client).
@@ -221,12 +221,12 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
221
221
  private _authModeAttributes;
222
222
  /**
223
223
  * One-shot resolver for HTTP route handlers. Builds the request's
224
- * `UserContext` AT MOST ONCE (when the volume is OBO and the headers are
224
+ * `CallerContext` AT MOST ONCE (when the volume is OBO and the headers are
225
225
  * present) and returns both the operationally-effective auth mode and the
226
- * pre-built `UserContext`.
226
+ * pre-built `CallerContext`.
227
227
  *
228
228
  * Handlers thread the `userCtx` into `_runWithAuth(userCtx, fn)` to avoid
229
- * a second `ServiceContext.createUserContext()` allocation — that call
229
+ * a second `ServiceContext.createCallerContext()` allocation. That call
230
230
  * builds a fresh `WorkspaceClient` per invocation, so doing it twice per
231
231
  * request was pure throwaway overhead.
232
232
  */
@@ -234,11 +234,11 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
234
234
  /**
235
235
  * Run `fn` under the correct execution context.
236
236
  * - `userCtx` is `null`: invokes `fn` directly so the service-principal
237
- * `WorkspaceClient` and `getCurrentUserId()` are used — identical
237
+ * `WorkspaceClient` and `getCurrentPrincipalId()` are used, identical
238
238
  * behavior to pre-OBO releases. This covers both SP volumes and the
239
239
  * OBO dev-fallback path (where headers were missing).
240
- * - `userCtx` is a `UserContext`: wraps `fn` in `runInUserContext(userCtx)`,
241
- * so SDK calls execute as the end user and `getCurrentUserId()` (and
240
+ * - `userCtx` is a `CallerContext`: wraps `fn` in `runInCallerContext(userCtx)`,
241
+ * so SDK calls execute as the end user and `getCurrentPrincipalId()` (and
242
242
  * therefore cache keys) resolve to the user's ID.
243
243
  *
244
244
  * The caller is responsible for building `userCtx` exactly once per
@@ -272,13 +272,19 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
272
272
  * additional parent span is opened, so each call produces exactly one
273
273
  * `files.<operation>` span instead of two.
274
274
  */
275
+ /**
276
+ * Like `_wrapVolumeAPIWithSPSpan`, but picks `files.auth_mode` from the
277
+ * active scope at call time: "on-behalf-of-user" inside a caller scope
278
+ * (for example `appkit.asUser(req)`), "service-principal" otherwise.
279
+ */
280
+ private _wrapVolumeAPIWithScopeSpan;
275
281
  private _wrapVolumeAPIWithSPSpan;
276
282
  /**
277
283
  * Wrap each `VolumeAPI` method so its execution runs inside
278
- * `runInUserContext(userCtx, ...)`. Used by `VolumeHandle.asUser(req)` to
284
+ * `runInCallerContext(userCtx, ...)`. Used by `VolumeHandle.asUser(req)` to
279
285
  * force the SDK identity to the end user regardless of the volume's
280
286
  * `auth` setting. The policy check baked into each method (via
281
- * `createVolumeAPI`) runs inside the same scope, so `getCurrentUserId()`
287
+ * `createVolumeAPI`) runs inside the same scope, so `getCurrentPrincipalId()`
282
288
  * and any cache `userKey` derived from it also resolve to the user.
283
289
  *
284
290
  * Each wrapped invocation tags the connector's span with
@@ -318,7 +324,7 @@ declare class FilesPlugin extends Plugin implements ToolProvider {
318
324
  * through the HTTP routes run as the end user; for programmatic calls
319
325
  * outside a route, use `asUser(req)` to opt into per-user execution.
320
326
  * `asUser(req)` is a hard override at the SDK level: it forces every
321
- * subsequent call to execute as the end user inside `runInUserContext`,
327
+ * subsequent call to execute as the end user inside `runInCallerContext`,
322
328
  * regardless of the volume's `auth` setting. Policies control per-user
323
329
  * access in either mode.
324
330
  *
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","names":[],"sources":["../../../src/plugins/files/plugin.ts"],"mappings":";;;;;;;;;;;;;;cAmEa,WAAA,SAAoB,MAAA,YAAkB,YAAA;EACjD,IAAA;;SAGO,QAAA,EAJgB,cAAA;EAAA,iBAKN,WAAA;EAAA,UACC,MAAA,EAAQ,YAAA;EAAA,QAElB,gBAAA;EAAA,QACA,aAAA;EAAA,QACA,UAAA;EAAA,QACA,KAAA;EAXe;;;;;EAAA,OAkBhB,eAAA,CAAgB,MAAA,EAAQ,YAAA,GAAe,MAAA,SAAe,YAAA;EAAf;;;;;;;;;;;;;;;;;;;;;;;;;EAAA,OA4CvC,uBAAA,CAAwB,MAAA,EAAQ,YAAA,GAAe,mBAAA;EAxDpC;;;;;;;;;;;;;;;;;;EAAA,QA+FV,YAAA;;;;;;;;;;;UAgCA,eAAA;EA+YA;;;;EAAA,QAvXM,YAAA;EA+kBA;;;;;;;;;;;;;;;;;;;EAAA,QAhiBA,cAAA;cAwDF,MAAA,EAAQ,YAAA;EAiDpB,YAAA,CAAa,MAAA,EAAQ,UAAA;EAgrClB;;;;EAAA,QAljCK,cAAA;EAqtCU;;;;;;;;;;;;;EAAA,QArrCV,cAAA;EA+uCR;;;;EAAA,QA5tCQ,YAAA;EAAA,QAQA,aAAA;EAAA,QAyBA,cAAA;EAAA,QAaA,iBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAmDM,oBAAA;EAAA,QAiFN,eAAA;EAAA,QAuCA,gBAAA;EAAA,QAOM,WAAA;EAAA,QAsCA,WAAA;EAAA,QAoFA,eAAA;EAAA,QAWA,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