@databricks/appkit 0.83.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.
- package/CLAUDE.md +15 -1
- package/dist/agents/databricks.d.ts +15 -3
- package/dist/agents/databricks.d.ts.map +1 -1
- package/dist/agents/databricks.js +25 -8
- package/dist/agents/databricks.js.map +1 -1
- package/dist/appkit/package.js +1 -1
- package/dist/beta.d.ts +2 -2
- package/dist/cache/index.d.ts.map +1 -1
- package/dist/cache/index.js +6 -1
- package/dist/cache/index.js.map +1 -1
- package/dist/cli/commands/agent/eval.js +1 -1
- package/dist/cli/commands/generate-types.js +1 -1
- package/dist/cli/commands/plugin/sync/sync.js +28 -15
- package/dist/cli/commands/plugin/sync/sync.js.map +1 -1
- package/dist/cli/commands/registry/add.js +3 -11
- package/dist/cli/commands/registry/add.js.map +1 -1
- package/dist/cli/commands/registry/config-writer.js +1 -1
- package/dist/connectors/lakebase/routing-pool.d.ts.map +1 -1
- package/dist/connectors/lakebase/routing-pool.js +4 -10
- package/dist/connectors/lakebase/routing-pool.js.map +1 -1
- package/dist/context/caller-context.d.ts +4 -1
- package/dist/context/caller-context.d.ts.map +1 -1
- package/dist/context/caller-context.js.map +1 -1
- package/dist/context/execution-context.d.ts +29 -1
- package/dist/context/execution-context.d.ts.map +1 -1
- package/dist/context/execution-context.js +60 -8
- package/dist/context/execution-context.js.map +1 -1
- package/dist/context/index.d.ts +2 -2
- package/dist/context/index.js +2 -1
- package/dist/context/request-scope.d.ts +2 -0
- package/dist/context/request-scope.js +39 -0
- package/dist/context/request-scope.js.map +1 -0
- package/dist/context/resource-capabilities.js +59 -0
- package/dist/context/resource-capabilities.js.map +1 -0
- package/dist/context/scoped-api.js +104 -0
- package/dist/context/scoped-api.js.map +1 -0
- package/dist/context/service-context.d.ts.map +1 -1
- package/dist/context/service-context.js +1 -1
- package/dist/context/service-context.js.map +1 -1
- package/dist/context/user-context.d.ts +16 -19
- package/dist/context/user-context.d.ts.map +1 -1
- package/dist/context/user-context.js +30 -3
- package/dist/context/user-context.js.map +1 -1
- package/dist/core/agent/load-agents.d.ts.map +1 -1
- package/dist/core/agent/load-agents.js +5 -2
- package/dist/core/agent/load-agents.js.map +1 -1
- package/dist/core/agent/run-agent.d.ts +19 -6
- package/dist/core/agent/run-agent.d.ts.map +1 -1
- package/dist/core/agent/run-agent.js +53 -17
- package/dist/core/agent/run-agent.js.map +1 -1
- package/dist/core/agent/types.d.ts +18 -1
- package/dist/core/agent/types.d.ts.map +1 -1
- package/dist/core/agent/types.js.map +1 -1
- package/dist/core/appkit.d.ts +4 -3
- package/dist/core/appkit.d.ts.map +1 -1
- package/dist/core/appkit.js +30 -9
- package/dist/core/appkit.js.map +1 -1
- package/dist/core/plugin-context.d.ts +14 -15
- package/dist/core/plugin-context.d.ts.map +1 -1
- package/dist/core/plugin-context.js +24 -14
- package/dist/core/plugin-context.js.map +1 -1
- package/dist/errors/base.d.ts +2 -2
- package/dist/errors/base.js +2 -2
- package/dist/errors/base.js.map +1 -1
- package/dist/errors/identity-expired.d.ts +14 -0
- package/dist/errors/identity-expired.d.ts.map +1 -0
- package/dist/errors/identity-expired.js +33 -0
- package/dist/errors/identity-expired.js.map +1 -0
- package/dist/errors/index.js +1 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +5 -2
- package/dist/logging/logger.js +1 -1
- package/dist/plugin/execution-result.d.ts +4 -1
- package/dist/plugin/execution-result.d.ts.map +1 -1
- package/dist/plugin/interceptors/telemetry.js +6 -4
- package/dist/plugin/interceptors/telemetry.js.map +1 -1
- package/dist/plugin/plugin.d.ts +13 -21
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +41 -122
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/plugins/agents/agents.d.ts +12 -0
- package/dist/plugins/agents/agents.d.ts.map +1 -1
- package/dist/plugins/agents/agents.js +65 -15
- package/dist/plugins/agents/agents.js.map +1 -1
- package/dist/plugins/agents/auth-mode.js +42 -0
- package/dist/plugins/agents/auth-mode.js.map +1 -0
- package/dist/plugins/agents/index.d.ts +1 -1
- package/dist/plugins/agents/mlflow.js +11 -3
- package/dist/plugins/agents/mlflow.js.map +1 -1
- package/dist/plugins/agents/tool-dispatch.js +9 -1
- package/dist/plugins/agents/tool-dispatch.js.map +1 -1
- package/dist/plugins/ai-search/ai-search.d.ts.map +1 -1
- package/dist/plugins/ai-search/ai-search.js +4 -4
- package/dist/plugins/ai-search/ai-search.js.map +1 -1
- package/dist/plugins/analytics/analytics.d.ts +2 -2
- package/dist/plugins/analytics/analytics.js +6 -6
- package/dist/plugins/analytics/analytics.js.map +1 -1
- package/dist/plugins/database/crud/contract.js +2 -2
- package/dist/plugins/database/crud/contract.js.map +1 -1
- package/dist/plugins/files/plugin.d.ts +10 -4
- package/dist/plugins/files/plugin.d.ts.map +1 -1
- package/dist/plugins/files/plugin.js +34 -13
- package/dist/plugins/files/plugin.js.map +1 -1
- package/dist/plugins/genie/genie.d.ts +9 -0
- package/dist/plugins/genie/genie.d.ts.map +1 -1
- package/dist/plugins/genie/genie.js +12 -3
- package/dist/plugins/genie/genie.js.map +1 -1
- package/dist/plugins/genie/manifest.js +1 -0
- package/dist/plugins/jobs/plugin.js +2 -2
- package/dist/plugins/jobs/plugin.js.map +1 -1
- package/dist/plugins/lakebase/lakebase.d.ts +10 -17
- package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
- package/dist/plugins/lakebase/lakebase.js +12 -17
- package/dist/plugins/lakebase/lakebase.js.map +1 -1
- package/dist/plugins/server/client-config-sanitizer.js +1 -4
- package/dist/plugins/server/client-config-sanitizer.js.map +1 -1
- package/dist/plugins/server/dev-obo-middleware.js +60 -0
- package/dist/plugins/server/dev-obo-middleware.js.map +1 -0
- package/dist/plugins/server/index.d.ts.map +1 -1
- package/dist/plugins/server/index.js +5 -2
- package/dist/plugins/server/index.js.map +1 -1
- package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js +3 -3
- package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
- package/dist/plugins/server/static-server.js +3 -3
- package/dist/plugins/server/static-server.js.map +1 -1
- package/dist/plugins/server/utils.js +3 -3
- package/dist/plugins/server/utils.js.map +1 -1
- package/dist/plugins/server/vite-dev-server.js +4 -4
- package/dist/plugins/server/vite-dev-server.js.map +1 -1
- package/dist/plugins/serving/manifest.js +1 -0
- package/dist/plugins/serving/serving.js +6 -6
- package/dist/plugins/serving/serving.js.map +1 -1
- package/dist/schemas/manifest.d.ts +35 -1
- package/dist/schemas/manifest.d.ts.map +1 -1
- package/dist/schemas/manifest.js +112 -4
- package/dist/schemas/manifest.js.map +1 -1
- package/dist/shared/src/dev-obo.js +86 -0
- package/dist/shared/src/dev-obo.js.map +1 -0
- package/dist/shared/src/index.d.ts +1 -1
- package/dist/shared/src/plugin.d.ts +12 -1
- package/dist/shared/src/plugin.d.ts.map +1 -1
- package/dist/shared/src/schemas/manifest.d.ts +41 -33
- package/dist/shared/src/schemas/manifest.d.ts.map +1 -1
- package/dist/shared/src/schemas/manifest.js +43 -4
- package/dist/shared/src/schemas/manifest.js.map +1 -1
- package/dist/stream/stream-manager.d.ts.map +1 -1
- package/dist/stream/stream-manager.js +5 -2
- package/dist/stream/stream-manager.js.map +1 -1
- package/dist/telemetry/execution-span-processor.js +21 -0
- package/dist/telemetry/execution-span-processor.js.map +1 -0
- package/dist/telemetry/telemetry-manager.js +2 -1
- package/dist/telemetry/telemetry-manager.js.map +1 -1
- package/dist/testing/create-test-app.d.ts +2 -2
- package/dist/testing/create-test-app.js.map +1 -1
- package/dist/testing/test-plugin-context.d.ts +3 -12
- package/dist/testing/test-plugin-context.d.ts.map +1 -1
- package/dist/testing/test-plugin-context.js +24 -16
- package/dist/testing/test-plugin-context.js.map +1 -1
- package/dist/type-generator/database/generate.js +3 -3
- package/dist/type-generator/database/generate.js.map +1 -1
- package/dist/type-generator/migration.js +2 -2
- package/dist/type-generator/migration.js.map +1 -1
- package/dist/type-generator/serving/server-file-extractor.js +3 -3
- package/dist/type-generator/serving/server-file-extractor.js.map +1 -1
- package/dist/utils/is-plain-object.js +11 -0
- package/dist/utils/is-plain-object.js.map +1 -0
- package/docs/api/appkit/Class.AppKitError.md +2 -1
- package/docs/api/appkit/Class.AuthenticationError.md +1 -1
- package/docs/api/appkit/Class.ConfigurationError.md +1 -1
- package/docs/api/appkit/Class.ConnectionError.md +1 -1
- package/docs/api/appkit/Class.DatabaseValidationError.md +1 -1
- package/docs/api/appkit/Class.ExecutionError.md +1 -1
- package/docs/api/appkit/Class.IdentityExpiredError.md +190 -0
- package/docs/api/appkit/Class.InitializationError.md +1 -1
- package/docs/api/appkit/Class.Plugin.md +8 -12
- package/docs/api/appkit/Class.ServerError.md +1 -1
- package/docs/api/appkit/Class.ServiceContext.md +169 -0
- package/docs/api/appkit/Class.TunnelError.md +1 -1
- package/docs/api/appkit/Class.ValidationError.md +1 -1
- package/docs/api/appkit/Function.createApp.md +12 -12
- package/docs/api/appkit/Function.getCallerContext.md +12 -0
- package/docs/api/appkit/Function.getCurrentUserId.md +14 -0
- package/docs/api/appkit/Function.getExecutionContext.md +1 -1
- package/docs/api/appkit/Function.getUserContext.md +16 -0
- package/docs/api/appkit/Function.isInUserContext.md +12 -0
- package/docs/api/appkit/Function.isUserContext.md +20 -0
- package/docs/api/appkit/Function.runAgent.md +1 -1
- package/docs/api/appkit/Function.runInCallerContext.md +27 -0
- package/docs/api/appkit/Function.runInUserContext.md +29 -0
- package/docs/api/appkit/Interface.AgentDefinition.md +11 -0
- package/docs/api/appkit/Interface.AgentsPluginConfig.md +11 -0
- package/docs/api/appkit/Interface.CallerContext.md +13 -0
- package/docs/api/appkit/Interface.IndexConfig.md +1 -1
- package/docs/api/appkit/Interface.PluginManifest.md +9 -1
- package/docs/api/appkit/Interface.RegisteredAgent.md +11 -0
- package/docs/api/appkit/Interface.RunAgentInput.md +45 -1
- package/docs/api/appkit/TypeAlias.AgentAuth.md +8 -0
- package/docs/api/appkit/TypeAlias.AppKitApi.md +35 -0
- package/docs/api/appkit/TypeAlias.ExecutionContext.md +4 -1
- package/docs/api/appkit/TypeAlias.ExecutionResult.md +65 -0
- package/docs/api/appkit/TypeAlias.ScopedPluginMap.md +12 -0
- package/docs/api/appkit/TypeAlias.UserContext.md +109 -0
- package/docs/api/appkit/TypeAlias.UserScopedApp.md +39 -0
- package/docs/api/appkit.md +14 -0
- package/docs/plugins/agents.md +45 -0
- package/docs/plugins/execution-context.md +101 -50
- package/docs/plugins/lakebase.md +6 -82
- package/llms.txt +15 -1
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getCurrentPrincipalId, isInUserContext, normalizeIdentityError } from "../../context/execution-context.js";
|
|
2
2
|
import { SpanStatusCode } from "../../telemetry/index.js";
|
|
3
|
-
import { isDevOboFallback } from "
|
|
3
|
+
import { isDevOboFallback } from "../../context/request-scope.js";
|
|
4
|
+
import "../plugin.js";
|
|
4
5
|
|
|
5
6
|
//#region src/plugin/interceptors/telemetry.ts
|
|
6
7
|
var TelemetryInterceptor = class {
|
|
@@ -29,12 +30,13 @@ var TelemetryInterceptor = class {
|
|
|
29
30
|
}
|
|
30
31
|
try {
|
|
31
32
|
span.setAttribute("execution.context", isInUserContext() ? "user" : "service");
|
|
32
|
-
span.setAttribute("caller.id",
|
|
33
|
+
span.setAttribute("caller.id", getCurrentPrincipalId());
|
|
33
34
|
if (isDevOboFallback()) span.setAttribute("execution.obo_dev_fallback", true);
|
|
34
35
|
const result = await fn();
|
|
35
36
|
if (!isAborted) span.setStatus({ code: SpanStatusCode.OK });
|
|
36
37
|
return result;
|
|
37
|
-
} catch (
|
|
38
|
+
} catch (caught) {
|
|
39
|
+
const error = normalizeIdentityError(caught);
|
|
38
40
|
if (!isAborted) {
|
|
39
41
|
span.recordException(error);
|
|
40
42
|
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry.js","names":[],"sources":["../../../src/plugin/interceptors/telemetry.ts"],"sourcesContent":["import type { TelemetryConfig } from \"shared\";\n\nimport {\n
|
|
1
|
+
{"version":3,"file":"telemetry.js","names":[],"sources":["../../../src/plugin/interceptors/telemetry.ts"],"sourcesContent":["import type { TelemetryConfig } from \"shared\";\n\nimport {\n getCurrentPrincipalId,\n isInUserContext,\n normalizeIdentityError,\n} from \"../../context/execution-context\";\nimport type { ITelemetry, Span } from \"../../telemetry\";\nimport { SpanStatusCode } from \"../../telemetry\";\nimport { isDevOboFallback } from \"../plugin\";\nimport type { ExecutionInterceptor, InterceptorContext } from \"./types\";\n\nexport class TelemetryInterceptor implements ExecutionInterceptor {\n constructor(\n private telemetry: ITelemetry,\n private config?: TelemetryConfig,\n ) {}\n\n async intercept<T>(\n fn: () => Promise<T>,\n context: InterceptorContext,\n ): Promise<T> {\n const spanName = this.config?.spanName || \"plugin.execute\";\n\n // abort operation if signal is aborted\n if (context.signal?.aborted) {\n throw new Error(\"Operation aborted before execution\");\n }\n\n return this.telemetry.startActiveSpan(\n spanName,\n { attributes: this.config?.attributes },\n async (span: Span) => {\n let abortHandler: (() => void) | undefined;\n let isAborted = false;\n\n if (context.signal) {\n abortHandler = () => {\n // abort span if not recording\n if (!span.isRecording()) return;\n isAborted = true;\n span.setAttribute(\"cancelled\", true);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: \"Operation cancelled by client\",\n });\n span.end();\n };\n context.signal.addEventListener(\"abort\", abortHandler, {\n once: true,\n });\n }\n\n try {\n span.setAttribute(\n \"execution.context\",\n isInUserContext() ? \"user\" : \"service\",\n );\n span.setAttribute(\"caller.id\", getCurrentPrincipalId());\n if (isDevOboFallback()) {\n span.setAttribute(\"execution.obo_dev_fallback\", true);\n }\n\n const result = await fn();\n if (!isAborted) {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n return result;\n } catch (caught) {\n const error = normalizeIdentityError(caught);\n if (!isAborted) {\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n throw error;\n } finally {\n if (abortHandler && context.signal) {\n context.signal.removeEventListener(\"abort\", abortHandler);\n }\n if (!isAborted) {\n span.end();\n }\n }\n },\n );\n }\n}\n"],"mappings":";;;;;;AAYA,IAAa,uBAAb,MAAkE;CAChE,YACE,AAAQ,WACR,AAAQ,QACR;EAFQ;EACA;;CAGV,MAAM,UACJ,IACA,SACY;EACZ,MAAM,WAAW,KAAK,QAAQ,YAAY;AAG1C,MAAI,QAAQ,QAAQ,QAClB,OAAM,IAAI,MAAM,qCAAqC;AAGvD,SAAO,KAAK,UAAU,gBACpB,UACA,EAAE,YAAY,KAAK,QAAQ,YAAY,EACvC,OAAO,SAAe;GACpB,IAAI;GACJ,IAAI,YAAY;AAEhB,OAAI,QAAQ,QAAQ;AAClB,yBAAqB;AAEnB,SAAI,CAAC,KAAK,aAAa,CAAE;AACzB,iBAAY;AACZ,UAAK,aAAa,aAAa,KAAK;AACpC,UAAK,UAAU;MACb,MAAM,eAAe;MACrB,SAAS;MACV,CAAC;AACF,UAAK,KAAK;;AAEZ,YAAQ,OAAO,iBAAiB,SAAS,cAAc,EACrD,MAAM,MACP,CAAC;;AAGJ,OAAI;AACF,SAAK,aACH,qBACA,iBAAiB,GAAG,SAAS,UAC9B;AACD,SAAK,aAAa,aAAa,uBAAuB,CAAC;AACvD,QAAI,kBAAkB,CACpB,MAAK,aAAa,8BAA8B,KAAK;IAGvD,MAAM,SAAS,MAAM,IAAI;AACzB,QAAI,CAAC,UACH,MAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;AAE7C,WAAO;YACA,QAAQ;IACf,MAAM,QAAQ,uBAAuB,OAAO;AAC5C,QAAI,CAAC,WAAW;AACd,UAAK,gBAAgB,MAAe;AACpC,UAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;;AAEhD,UAAM;aACE;AACR,QAAI,gBAAgB,QAAQ,OAC1B,SAAQ,OAAO,oBAAoB,SAAS,aAAa;AAE3D,QAAI,CAAC,UACH,MAAK,KAAK;;IAIjB"}
|
package/dist/plugin/plugin.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { PluginContext } from "../core/plugin-context.js";
|
|
|
10
10
|
import { StreamManager } from "../stream/stream-manager.js";
|
|
11
11
|
import "../stream/index.js";
|
|
12
12
|
import { DevFileReader } from "./dev-reader.js";
|
|
13
|
+
import "../context/request-scope.js";
|
|
13
14
|
import express from "express";
|
|
14
15
|
|
|
15
16
|
//#region src/plugin/plugin.d.ts
|
|
@@ -221,31 +222,21 @@ declare abstract class Plugin<TConfig extends BasePluginConfig = BasePluginConfi
|
|
|
221
222
|
* @throws AuthenticationError in production when no user header is present.
|
|
222
223
|
*/
|
|
223
224
|
protected resolveUserId(req: express.Request): string;
|
|
224
|
-
/**
|
|
225
|
-
* Execute operations using the user's identity from the request.
|
|
226
|
-
* Returns a proxy of this plugin where all method calls execute
|
|
227
|
-
* with the user's Databricks credentials instead of the service principal.
|
|
228
|
-
*
|
|
229
|
-
* @param req - The Express request containing the user token in headers
|
|
230
|
-
* @returns A proxied plugin instance that executes as the user
|
|
231
|
-
* @throws AuthenticationError if user token is not available in request headers (production only).
|
|
232
|
-
* In development mode (`NODE_ENV=development`), skips user impersonation instead of throwing.
|
|
233
|
-
*/
|
|
225
|
+
/** @deprecated Use appkit.asUser(req) to scope the whole app. */
|
|
234
226
|
asUser(req: express.Request): this;
|
|
235
227
|
/**
|
|
236
|
-
*
|
|
237
|
-
*
|
|
228
|
+
* User-scoped executor for the plugin's own on-behalf-of routing (for
|
|
229
|
+
* example `.obo.sql` lanes), using the same caller context as the
|
|
230
|
+
* app-level `appkit.asUser(req)`.
|
|
238
231
|
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
232
|
+
* Unlike the deprecated public `asUser(req)`, this does not emit a
|
|
233
|
+
* deprecation warning and does not opt out of the app-only resource
|
|
234
|
+
* guards, so internal routing matches current on-behalf-of semantics
|
|
235
|
+
* rather than the retained legacy behavior.
|
|
242
236
|
*
|
|
243
|
-
*
|
|
244
|
-
* exports object never re-enter the proxy's `get` trap. Wrapping them
|
|
245
|
-
* here is the only way to make the user context follow function
|
|
246
|
-
* references back out of the plugin.
|
|
237
|
+
* @internal
|
|
247
238
|
*/
|
|
248
|
-
|
|
239
|
+
protected _asUserScoped(req: express.Request): this;
|
|
249
240
|
protected executeStream<T>(res: IAppResponse, fn: StreamExecuteHandler<T>, options: StreamExecutionSettings, userKey?: string): Promise<void>;
|
|
250
241
|
/**
|
|
251
242
|
* Execute a function with the plugin's interceptor chain.
|
|
@@ -254,7 +245,8 @@ declare abstract class Plugin<TConfig extends BasePluginConfig = BasePluginConfi
|
|
|
254
245
|
* - `{ ok: true, data: T }` on success
|
|
255
246
|
* - `{ ok: false, status: number, message: string }` on failure
|
|
256
247
|
*
|
|
257
|
-
*
|
|
248
|
+
* Caller credential expiration retains the failure result and additionally
|
|
249
|
+
* exposes a typed error, preserving existing result-based callers.
|
|
258
250
|
*/
|
|
259
251
|
protected execute<T>(fn: (signal?: AbortSignal) => Promise<T>, options: PluginExecutionSettings, userKey?: string): Promise<ExecutionResult<T>>;
|
|
260
252
|
protected registerEndpoint(name: string, path: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../src/plugin/plugin.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../src/plugin/plugin.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwJA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBAAsB,MAAA,iBACJ,gBAAA,GAAmB,gBAAA,aACxB,UAAA;EAAA,UA4BW,MAAA,EAAQ,OAAA;EAAA,UA3BpB,OAAA;EAAA,UACA,KAAA,EAAQ,YAAA;EAAA,UACR,GAAA,EA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A,YAAA,CACR,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAChB,MAAA,EAAQ,WAAA;EAAA,QAeF,qBAAA;EAAA,QAaA,kBAAA;EAAA,QAqCM,wBAAA;EAAA,QAqBN,iBAAA;AAAA"}
|
package/dist/plugin/plugin.js
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
import { camelToKebab } from "../shared/src/naming.js";
|
|
2
2
|
import { AppKitError } from "../errors/base.js";
|
|
3
3
|
import { AuthenticationError } from "../errors/authentication.js";
|
|
4
|
+
import { IdentityExpiredError } from "../errors/identity-expired.js";
|
|
4
5
|
import "../errors/index.js";
|
|
5
6
|
import { createLogger } from "../logging/logger.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
7
|
+
import { warnContextDeprecation } from "../context/deprecation.js";
|
|
8
|
+
import { getCurrentPrincipalId, normalizeIdentityError } from "../context/execution-context.js";
|
|
9
|
+
import { isPlainObject } from "../utils/is-plain-object.js";
|
|
10
|
+
import { scopePlugin } from "../context/scoped-api.js";
|
|
11
|
+
import { assertPluginExecution, getPluginResourceTypes } from "../context/resource-capabilities.js";
|
|
8
12
|
import { normalizeTelemetryOptions } from "../telemetry/config.js";
|
|
9
13
|
import { TelemetryManager } from "../telemetry/telemetry-manager.js";
|
|
10
14
|
import "../telemetry/index.js";
|
|
11
15
|
import { deepMerge } from "../utils/merge.js";
|
|
12
16
|
import { CacheManager } from "../cache/index.js";
|
|
13
17
|
import "../context/index.js";
|
|
18
|
+
import { createRequestScope, isDevOboFallback } from "../context/request-scope.js";
|
|
14
19
|
import { AppManager } from "../app/index.js";
|
|
15
20
|
import { StreamManager } from "../stream/stream-manager.js";
|
|
16
21
|
import "../stream/index.js";
|
|
@@ -20,55 +25,11 @@ import { CacheInterceptor } from "./interceptors/cache.js";
|
|
|
20
25
|
import { RetryInterceptor } from "./interceptors/retry.js";
|
|
21
26
|
import { TelemetryInterceptor } from "./interceptors/telemetry.js";
|
|
22
27
|
import { TimeoutInterceptor } from "./interceptors/timeout.js";
|
|
23
|
-
import { context
|
|
28
|
+
import { context } from "@opentelemetry/api";
|
|
24
29
|
|
|
25
30
|
//#region src/plugin/plugin.ts
|
|
26
31
|
const logger = createLogger("plugin");
|
|
27
32
|
/**
|
|
28
|
-
* OTel context key for marking OBO dev mode fallback.
|
|
29
|
-
* Set when asUser() is called in development mode without a user token.
|
|
30
|
-
*/
|
|
31
|
-
const DEV_OBO_FALLBACK_KEY = createContextKey("appkit.devOboFallback");
|
|
32
|
-
/**
|
|
33
|
-
* Returns true if `value` is a plain object literal (not an array, Date,
|
|
34
|
-
* class instance, etc.). Used to decide whether to recurse into nested
|
|
35
|
-
* export shapes when wrapping functions.
|
|
36
|
-
*
|
|
37
|
-
* @internal exported so the AppKit core can reuse the same predicate for
|
|
38
|
-
* its `bindExportMethods` walk; not part of the public package surface.
|
|
39
|
-
*/
|
|
40
|
-
function isPlainObject(value) {
|
|
41
|
-
if (typeof value !== "object" || value === null) return false;
|
|
42
|
-
const proto = Object.getPrototypeOf(value);
|
|
43
|
-
return proto === Object.prototype || proto === null;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Returns a deep copy of `exports` where every function has been replaced
|
|
47
|
-
* with `wrap(fn)`, walking into nested plain objects.
|
|
48
|
-
*
|
|
49
|
-
* Used by the asUser proxy to make the user context follow function
|
|
50
|
-
* references that escape the proxy via `exports()`. The original input is
|
|
51
|
-
* not mutated, so plugins that memoize `exports()` are safe — each call
|
|
52
|
-
* through the proxy yields an independent, freshly wrapped view.
|
|
53
|
-
*/
|
|
54
|
-
function wrapExportFunctions(exports, wrap) {
|
|
55
|
-
const result = {};
|
|
56
|
-
for (const key of Object.keys(exports)) {
|
|
57
|
-
const val = exports[key];
|
|
58
|
-
if (typeof val === "function") result[key] = wrap(val);
|
|
59
|
-
else if (isPlainObject(val)) result[key] = wrapExportFunctions(val, wrap);
|
|
60
|
-
else result[key] = val;
|
|
61
|
-
}
|
|
62
|
-
return result;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* Returns true if the current execution is an OBO dev mode fallback
|
|
66
|
-
* (asUser() was called but fell back to service principal due to missing token).
|
|
67
|
-
*/
|
|
68
|
-
function isDevOboFallback() {
|
|
69
|
-
return context.active().getValue(DEV_OBO_FALLBACK_KEY) === true;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
33
|
* Narrow an unknown thrown value to an Error that carries a numeric
|
|
73
34
|
* `statusCode` property (e.g. `ApiError` from `@databricks/sdk-experimental`).
|
|
74
35
|
*/
|
|
@@ -76,23 +37,6 @@ function hasHttpStatusCode(error) {
|
|
|
76
37
|
return error instanceof Error && "statusCode" in error && typeof error.statusCode === "number";
|
|
77
38
|
}
|
|
78
39
|
/**
|
|
79
|
-
* Methods that should not be proxied by asUser().
|
|
80
|
-
* These are lifecycle/internal methods that don't make sense
|
|
81
|
-
* to execute in a user context.
|
|
82
|
-
*/
|
|
83
|
-
const EXCLUDED_FROM_PROXY = new Set([
|
|
84
|
-
"setup",
|
|
85
|
-
"shutdown",
|
|
86
|
-
"attachContext",
|
|
87
|
-
"injectRoutes",
|
|
88
|
-
"getEndpoints",
|
|
89
|
-
"getSkipBodyParsingPaths",
|
|
90
|
-
"abortActiveOperations",
|
|
91
|
-
"clientConfig",
|
|
92
|
-
"asUser",
|
|
93
|
-
"constructor"
|
|
94
|
-
]);
|
|
95
|
-
/**
|
|
96
40
|
* Base abstract class for creating AppKit plugins.
|
|
97
41
|
*
|
|
98
42
|
* All plugins must declare a static `manifest` property with their metadata
|
|
@@ -329,72 +273,39 @@ var Plugin = class {
|
|
|
329
273
|
resolveUserId(req) {
|
|
330
274
|
const userId = req.header("x-forwarded-user")?.trim();
|
|
331
275
|
if (userId) return userId;
|
|
332
|
-
if (process.env.NODE_ENV === "development") return
|
|
276
|
+
if (process.env.NODE_ENV === "development") return getCurrentPrincipalId();
|
|
333
277
|
throw AuthenticationError.missingUserId();
|
|
334
278
|
}
|
|
335
|
-
/**
|
|
336
|
-
* Execute operations using the user's identity from the request.
|
|
337
|
-
* Returns a proxy of this plugin where all method calls execute
|
|
338
|
-
* with the user's Databricks credentials instead of the service principal.
|
|
339
|
-
*
|
|
340
|
-
* @param req - The Express request containing the user token in headers
|
|
341
|
-
* @returns A proxied plugin instance that executes as the user
|
|
342
|
-
* @throws AuthenticationError if user token is not available in request headers (production only).
|
|
343
|
-
* In development mode (`NODE_ENV=development`), skips user impersonation instead of throwing.
|
|
344
|
-
*/
|
|
279
|
+
/** @deprecated Use appkit.asUser(req) to scope the whole app. */
|
|
345
280
|
asUser(req) {
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
const isDev = process.env.NODE_ENV === "development";
|
|
350
|
-
if (!token && isDev) {
|
|
351
|
-
logger.warn("asUser() called without user token in development mode. Skipping user impersonation.");
|
|
352
|
-
return this._createAsUserProxy((fn) => (...args) => {
|
|
353
|
-
const ctx = context.active().setValue(DEV_OBO_FALLBACK_KEY, true);
|
|
354
|
-
return context.with(ctx, () => fn(...args));
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
if (!token) throw AuthenticationError.missingToken("user token");
|
|
358
|
-
if (!userId && !isDev) throw AuthenticationError.missingUserId();
|
|
359
|
-
const effectiveUserId = userId || "dev-user";
|
|
360
|
-
const userContext = ServiceContext.createCallerContext(token, effectiveUserId, void 0, userEmail ?? void 0);
|
|
361
|
-
return this._createAsUserProxy((fn) => (...args) => runInCallerContext(userContext, () => fn(...args)));
|
|
281
|
+
warnContextDeprecation("Plugin.asUser", "appkit.asUser(req)");
|
|
282
|
+
assertPluginExecution(this);
|
|
283
|
+
return scopePlugin(this, createRequestScope(req, getPluginResourceTypes(this), { legacy: true }));
|
|
362
284
|
}
|
|
363
285
|
/**
|
|
364
|
-
*
|
|
365
|
-
*
|
|
286
|
+
* User-scoped executor for the plugin's own on-behalf-of routing (for
|
|
287
|
+
* example `.obo.sql` lanes), using the same caller context as the
|
|
288
|
+
* app-level `appkit.asUser(req)`.
|
|
366
289
|
*
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
290
|
+
* Unlike the deprecated public `asUser(req)`, this does not emit a
|
|
291
|
+
* deprecation warning and does not opt out of the app-only resource
|
|
292
|
+
* guards, so internal routing matches current on-behalf-of semantics
|
|
293
|
+
* rather than the retained legacy behavior.
|
|
370
294
|
*
|
|
371
|
-
*
|
|
372
|
-
* exports object never re-enter the proxy's `get` trap. Wrapping them
|
|
373
|
-
* here is the only way to make the user context follow function
|
|
374
|
-
* references back out of the plugin.
|
|
295
|
+
* @internal
|
|
375
296
|
*/
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
if (typeof value !== "function") return value;
|
|
380
|
-
if (typeof prop === "string" && EXCLUDED_FROM_PROXY.has(prop)) return value;
|
|
381
|
-
if (prop === "exports") return () => {
|
|
382
|
-
const raw = value.call(target);
|
|
383
|
-
if (raw == null) return {};
|
|
384
|
-
if (typeof raw === "function") return raw;
|
|
385
|
-
if (isPlainObject(raw)) return wrapExportFunctions(raw, (fn) => wrapCall(fn.bind(target)));
|
|
386
|
-
return raw;
|
|
387
|
-
};
|
|
388
|
-
return wrapCall(value.bind(target));
|
|
389
|
-
} });
|
|
297
|
+
_asUserScoped(req) {
|
|
298
|
+
assertPluginExecution(this);
|
|
299
|
+
return scopePlugin(this, createRequestScope(req, getPluginResourceTypes(this)));
|
|
390
300
|
}
|
|
391
301
|
async executeStream(res, fn, options, userKey) {
|
|
302
|
+
assertPluginExecution(this);
|
|
392
303
|
const { stream: streamConfig, default: defaultConfig, user: userConfig } = options;
|
|
393
304
|
const executeConfig = this._buildExecutionConfig({
|
|
394
305
|
default: defaultConfig,
|
|
395
306
|
user: userConfig
|
|
396
307
|
});
|
|
397
|
-
const effectiveUserKey = userKey ??
|
|
308
|
+
const effectiveUserKey = userKey ?? getCurrentPrincipalId();
|
|
398
309
|
const self = this;
|
|
399
310
|
const parentOtelContext = context.active();
|
|
400
311
|
const asyncWrapperFn = async function* (streamSignal) {
|
|
@@ -408,8 +319,12 @@ var Plugin = class {
|
|
|
408
319
|
return await fn(context$1.signal);
|
|
409
320
|
};
|
|
410
321
|
const result = await context.with(parentOtelContext, () => self._executeWithInterceptors(wrappedFn, interceptors, context$1));
|
|
411
|
-
|
|
412
|
-
|
|
322
|
+
try {
|
|
323
|
+
if (self._checkIfGenerator(result)) yield* result;
|
|
324
|
+
else yield result;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw normalizeIdentityError(error);
|
|
327
|
+
}
|
|
413
328
|
};
|
|
414
329
|
await this.streamManager.stream(res, asyncWrapperFn, streamConfig, effectiveUserKey);
|
|
415
330
|
}
|
|
@@ -420,12 +335,14 @@ var Plugin = class {
|
|
|
420
335
|
* - `{ ok: true, data: T }` on success
|
|
421
336
|
* - `{ ok: false, status: number, message: string }` on failure
|
|
422
337
|
*
|
|
423
|
-
*
|
|
338
|
+
* Caller credential expiration retains the failure result and additionally
|
|
339
|
+
* exposes a typed error, preserving existing result-based callers.
|
|
424
340
|
*/
|
|
425
341
|
async execute(fn, options, userKey) {
|
|
342
|
+
assertPluginExecution(this);
|
|
426
343
|
const executeConfig = this._buildExecutionConfig(options);
|
|
427
344
|
const interceptors = this._buildInterceptors(executeConfig);
|
|
428
|
-
const effectiveUserKey = userKey ??
|
|
345
|
+
const effectiveUserKey = userKey ?? getCurrentPrincipalId();
|
|
429
346
|
const context = {
|
|
430
347
|
metadata: /* @__PURE__ */ new Map(),
|
|
431
348
|
userKey: effectiveUserKey
|
|
@@ -435,7 +352,8 @@ var Plugin = class {
|
|
|
435
352
|
ok: true,
|
|
436
353
|
data: await this._executeWithInterceptors(fn, interceptors, context)
|
|
437
354
|
};
|
|
438
|
-
} catch (
|
|
355
|
+
} catch (caught) {
|
|
356
|
+
const error = normalizeIdentityError(caught);
|
|
439
357
|
logger.error("Plugin execution failed", {
|
|
440
358
|
error,
|
|
441
359
|
plugin: this.name
|
|
@@ -443,7 +361,8 @@ var Plugin = class {
|
|
|
443
361
|
if (error instanceof AppKitError) return {
|
|
444
362
|
ok: false,
|
|
445
363
|
status: error.statusCode,
|
|
446
|
-
message: error.message
|
|
364
|
+
message: error.message,
|
|
365
|
+
...error instanceof IdentityExpiredError ? { error } : {}
|
|
447
366
|
};
|
|
448
367
|
if (hasHttpStatusCode(error)) {
|
|
449
368
|
const isDev = process.env.NODE_ENV !== "production";
|
|
@@ -498,5 +417,5 @@ var Plugin = class {
|
|
|
498
417
|
};
|
|
499
418
|
|
|
500
419
|
//#endregion
|
|
501
|
-
export { Plugin
|
|
420
|
+
export { Plugin };
|
|
502
421
|
//# sourceMappingURL=plugin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":["otelContext","context"],"sources":["../../src/plugin/plugin.ts"],"sourcesContent":["import { createContextKey, context as otelContext } from \"@opentelemetry/api\";\nimport type express from \"express\";\nimport type {\n BasePlugin,\n BasePluginConfig,\n IAppResponse,\n PluginEndpointMap,\n PluginExecuteConfig,\n PluginExecutionSettings,\n PluginPhase,\n RouteConfig,\n StreamExecuteHandler,\n StreamExecutionSettings,\n} from \"shared\";\nimport { camelToKebab } from \"shared\";\n\nimport { AppManager } from \"../app\";\nimport { CacheManager } from \"../cache\";\nimport {\n getCurrentUserId,\n runInCallerContext,\n ServiceContext,\n} from \"../context\";\nimport type { PluginContext } from \"../core/plugin-context\";\nimport { AppKitError, AuthenticationError } from \"../errors\";\nimport { createLogger } from \"../logging/logger\";\nimport { StreamManager } from \"../stream\";\nimport {\n type ITelemetry,\n normalizeTelemetryOptions,\n TelemetryManager,\n} from \"../telemetry\";\nimport { deepMerge } from \"../utils\";\nimport { forwardAsyncErrors } from \"../utils/safe-handler\";\nimport { DevFileReader } from \"./dev-reader\";\nimport type { ExecutionResult } from \"./execution-result\";\nimport { CacheInterceptor } from \"./interceptors/cache\";\nimport { RetryInterceptor } from \"./interceptors/retry\";\nimport { TelemetryInterceptor } from \"./interceptors/telemetry\";\nimport { TimeoutInterceptor } from \"./interceptors/timeout\";\nimport type {\n ExecutionInterceptor,\n InterceptorContext,\n} from \"./interceptors/types\";\n\nconst logger = createLogger(\"plugin\");\n\n/**\n * OTel context key for marking OBO dev mode fallback.\n * Set when asUser() is called in development mode without a user token.\n */\nconst DEV_OBO_FALLBACK_KEY = createContextKey(\"appkit.devOboFallback\");\n\n/**\n * Returns true if `value` is a plain object literal (not an array, Date,\n * class instance, etc.). Used to decide whether to recurse into nested\n * export shapes when wrapping functions.\n *\n * @internal exported so the AppKit core can reuse the same predicate for\n * its `bindExportMethods` walk; not part of the public package surface.\n */\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Returns a deep copy of `exports` where every function has been replaced\n * with `wrap(fn)`, walking into nested plain objects.\n *\n * Used by the asUser proxy to make the user context follow function\n * references that escape the proxy via `exports()`. The original input is\n * not mutated, so plugins that memoize `exports()` are safe — each call\n * through the proxy yields an independent, freshly wrapped view.\n */\nfunction wrapExportFunctions(\n exports: Record<string, unknown>,\n wrap: (fn: (...a: unknown[]) => unknown) => (...a: unknown[]) => unknown,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(exports)) {\n const val = exports[key];\n if (typeof val === \"function\") {\n result[key] = wrap(val as (...a: unknown[]) => unknown);\n } else if (isPlainObject(val)) {\n result[key] = wrapExportFunctions(val, wrap);\n } else {\n result[key] = val;\n }\n }\n return result;\n}\n\n/**\n * Returns true if the current execution is an OBO dev mode fallback\n * (asUser() was called but fell back to service principal due to missing token).\n */\nexport function isDevOboFallback(): boolean {\n return otelContext.active().getValue(DEV_OBO_FALLBACK_KEY) === true;\n}\n\n/**\n * Narrow an unknown thrown value to an Error that carries a numeric\n * `statusCode` property (e.g. `ApiError` from `@databricks/sdk-experimental`).\n */\nfunction hasHttpStatusCode(\n error: unknown,\n): error is Error & { statusCode: number } {\n return (\n error instanceof Error &&\n \"statusCode\" in error &&\n typeof (error as Record<string, unknown>).statusCode === \"number\"\n );\n}\n\n/**\n * Methods that should not be proxied by asUser().\n * These are lifecycle/internal methods that don't make sense\n * to execute in a user context.\n */\nconst EXCLUDED_FROM_PROXY = new Set([\n // Lifecycle methods\n \"setup\",\n \"shutdown\",\n \"attachContext\",\n \"injectRoutes\",\n \"getEndpoints\",\n \"getSkipBodyParsingPaths\",\n \"abortActiveOperations\",\n \"clientConfig\",\n // asUser itself - prevent chaining like .asUser().asUser()\n \"asUser\",\n // Internal methods\n \"constructor\",\n]);\n\n/**\n * Base abstract class for creating AppKit plugins.\n *\n * All plugins must declare a static `manifest` property with their metadata\n * and resource requirements. The manifest defines:\n * - `required` resources: Always needed for the plugin to function\n * - `optional` resources: May be needed depending on plugin configuration\n *\n * ## Static vs Runtime Resource Requirements\n *\n * The manifest is static and doesn't know the plugin's runtime configuration.\n * For resources that become required based on config options, plugins can\n * implement a static `getResourceRequirements(config)` method.\n *\n * At runtime, this method is called with the actual config to determine\n * which \"optional\" resources should be treated as \"required\".\n *\n * @example Basic plugin with static requirements\n * ```typescript\n * import { Plugin, toPlugin, PluginManifest, ResourceType } from '@databricks/appkit';\n *\n * const myManifest: PluginManifest = {\n * name: 'myPlugin',\n * displayName: 'My Plugin',\n * description: 'Does something awesome',\n * resources: {\n * required: [\n * { type: ResourceType.SQL_WAREHOUSE, alias: 'warehouse', ... }\n * ],\n * optional: []\n * }\n * };\n *\n * class MyPlugin extends Plugin<MyConfig> {\n * static manifest = myManifest;\n * }\n * ```\n *\n * @example Plugin with config-dependent resources\n * ```typescript\n * interface MyConfig extends BasePluginConfig {\n * enableCaching?: boolean;\n * }\n *\n * const myManifest: PluginManifest = {\n * name: 'myPlugin',\n * resources: {\n * required: [\n * { type: ResourceType.SQL_WAREHOUSE, alias: 'warehouse', ... }\n * ],\n * optional: [\n * // Database is optional in the static manifest\n * { type: ResourceType.DATABASE, alias: 'cache', description: 'Required if caching enabled', ... }\n * ]\n * }\n * };\n *\n * class MyPlugin extends Plugin<MyConfig> {\n * static manifest = myManifest<\"myPlugin\">;\n *\n * // Runtime method: converts optional resources to required based on config\n * static getResourceRequirements(config: MyConfig) {\n * const resources = [];\n * if (config.enableCaching) {\n * // When caching is enabled, Database becomes required\n * resources.push({\n * type: ResourceType.DATABASE,\n * alias: 'cache',\n * resourceKey: 'database',\n * description: 'Cache storage for query results',\n * permission: 'CAN_CONNECT_AND_CREATE',\n * fields: {\n * instance_name: { env: 'DATABRICKS_CACHE_INSTANCE' },\n * database_name: { env: 'DATABRICKS_CACHE_DB' },\n * },\n * required: true // Mark as required at runtime\n * });\n * }\n * return resources;\n * }\n * }\n * ```\n */\nexport abstract class Plugin<\n TConfig extends BasePluginConfig = BasePluginConfig,\n> implements BasePlugin {\n protected isReady = false;\n protected cache!: CacheManager;\n protected app: AppManager;\n protected devFileReader: DevFileReader;\n protected streamManager: StreamManager;\n protected telemetry!: ITelemetry;\n protected context?: PluginContext;\n\n /** Registered endpoints for this plugin */\n private registeredEndpoints: PluginEndpointMap = {};\n\n /** Paths that opt out of JSON body parsing (e.g. file upload routes) */\n private skipBodyParsingPaths: Set<string> = new Set();\n\n /**\n * Plugin initialization phase.\n * - 'core': Initialized first (e.g., config plugins)\n * - 'normal': Initialized second (most plugins)\n * - 'deferred': Initialized last (e.g., server plugin)\n */\n static phase: PluginPhase = \"normal\";\n\n /**\n * Plugin name identifier.\n */\n name: string;\n\n constructor(protected config: TConfig) {\n this.name =\n config.name ??\n (this.constructor as { manifest?: { name: string } }).manifest?.name ??\n \"plugin\";\n this.streamManager = new StreamManager(config.streamConfig);\n this.app = new AppManager();\n this.devFileReader = DevFileReader.getInstance();\n this.context = (config as Record<string, unknown>).context as\n | PluginContext\n | undefined;\n\n // Eagerly bind telemetry + cache if the core services have already been\n // initialized (normal createApp path, or tests that mock CacheManager).\n // If they haven't, we leave these undefined and rely on `attachContext`\n // being called later — this lets factories eagerly construct plugin\n // instances at module top-level before `createApp` has run.\n this.tryAttachContext();\n }\n\n private tryAttachContext(): void {\n try {\n this.cache = CacheManager.getInstanceSync();\n } catch {\n return;\n }\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n this.config.telemetry,\n );\n this.isReady = true;\n }\n\n /**\n * Binds runtime dependencies (telemetry provider, cache, plugin context) to\n * this plugin. Called by `AppKit._createApp` after construction and before\n * `setup()`. Idempotent: safe to call if the constructor already bound them\n * eagerly. Kept separate so factories can eagerly construct plugin instances\n * without running this before `TelemetryManager.initialize()` /\n * `CacheManager.getInstance()` have run.\n */\n attachContext(\n deps: {\n context?: unknown;\n telemetryConfig?: BasePluginConfig[\"telemetry\"];\n } = {},\n ): void {\n if (!this.cache) {\n this.cache = CacheManager.getInstanceSync();\n }\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n deps.telemetryConfig ?? this.config.telemetry,\n );\n if (deps.context !== undefined) {\n this.context = deps.context as PluginContext;\n }\n this.isReady = true;\n }\n\n injectRoutes(_: express.Router) {\n return;\n }\n\n async setup() {}\n\n getEndpoints(): PluginEndpointMap {\n return this.registeredEndpoints;\n }\n\n getSkipBodyParsingPaths(): ReadonlySet<string> {\n return this.skipBodyParsingPaths;\n }\n\n abortActiveOperations(): void {\n this.streamManager.abortAll();\n }\n\n /**\n * Returns the public exports for this plugin.\n * Override this to define a custom public API.\n * By default, returns an empty object.\n *\n * The returned object becomes the plugin's public API on the AppKit instance\n * (e.g. `appkit.myPlugin.method()`). AppKit automatically binds method context\n * and adds `asUser(req)` for user-scoped execution.\n *\n * @example\n * ```ts\n * class MyPlugin extends Plugin {\n * private getData() { return []; }\n *\n * exports() {\n * return { getData: this.getData };\n * }\n * }\n *\n * // After registration:\n * const appkit = await createApp({ plugins: [myPlugin()] });\n * appkit.myPlugin.getData();\n * ```\n */\n exports(): unknown {\n return {};\n }\n\n /**\n * Returns startup config to expose to the client.\n * Override this to surface server-side values that are safe to publish to the\n * frontend, such as feature flags, resource IDs, or other app boot settings.\n *\n * This runs once when the server starts, so it should not depend on\n * request-scoped or user-specific state.\n *\n * String values that match non-public environment variables are redacted\n * unless you intentionally expose them via a matching `PUBLIC_APPKIT_` env var.\n *\n * Values must be JSON-serializable plain data (no functions, Dates, classes,\n * Maps, Sets, BigInts, or circular references).\n * By default returns an empty object (plugin contributes nothing to client config).\n *\n * On the client, read the config with the `usePluginClientConfig` hook\n * (React) or the `getPluginClientConfig` function (vanilla JS), both\n * from `@databricks/appkit-ui`.\n *\n * @example\n * ```ts\n * // Server — plugin definition\n * class MyPlugin extends Plugin<MyConfig> {\n * clientConfig() {\n * return {\n * warehouseId: this.config.warehouseId,\n * features: { darkMode: true },\n * };\n * }\n * }\n *\n * // Client — React component\n * import { usePluginClientConfig } from \"@databricks/appkit-ui/react\";\n *\n * interface MyPluginConfig { warehouseId: string; features: { darkMode: boolean } }\n *\n * const config = usePluginClientConfig<MyPluginConfig>(\"myPlugin\");\n * config.warehouseId; // \"abc-123\"\n *\n * // Client — vanilla JS\n * import { getPluginClientConfig } from \"@databricks/appkit-ui/js\";\n *\n * const config = getPluginClientConfig<MyPluginConfig>(\"myPlugin\");\n * ```\n */\n clientConfig(): Record<string, unknown> {\n return {};\n }\n\n /**\n * Resolve the effective user ID from a request.\n *\n * Returns the `x-forwarded-user` header when present. In development mode\n * (`NODE_ENV=development`) falls back to the current context user ID so\n * that callers outside an active `runInCallerContext` scope still get a\n * consistent value.\n *\n * @throws AuthenticationError in production when no user header is present.\n */\n protected resolveUserId(req: express.Request): string {\n const userId = req.header(\"x-forwarded-user\")?.trim();\n if (userId) return userId;\n if (process.env.NODE_ENV === \"development\") return getCurrentUserId();\n throw AuthenticationError.missingUserId();\n }\n\n /**\n * Execute operations using the user's identity from the request.\n * Returns a proxy of this plugin where all method calls execute\n * with the user's Databricks credentials instead of the service principal.\n *\n * @param req - The Express request containing the user token in headers\n * @returns A proxied plugin instance that executes as the user\n * @throws AuthenticationError if user token is not available in request headers (production only).\n * In development mode (`NODE_ENV=development`), skips user impersonation instead of throwing.\n */\n asUser(req: express.Request): this {\n const token = req.header(\"x-forwarded-access-token\")?.trim();\n const userId = req.header(\"x-forwarded-user\")?.trim();\n const userEmail = req.header(\"x-forwarded-email\");\n const isDev = process.env.NODE_ENV === \"development\";\n\n // In local development, skip user impersonation since there's no user\n // token available. Mark execution as OBO dev fallback via OTel context\n // so telemetry can distinguish intended OBO calls from regular SP calls.\n if (!token && isDev) {\n logger.warn(\n \"asUser() called without user token in development mode. Skipping user impersonation.\",\n );\n\n return this._createAsUserProxy((fn) => (...args) => {\n const ctx = otelContext.active().setValue(DEV_OBO_FALLBACK_KEY, true);\n return otelContext.with(ctx, () => fn(...args));\n });\n }\n\n if (!token) {\n throw AuthenticationError.missingToken(\"user token\");\n }\n\n if (!userId && !isDev) {\n throw AuthenticationError.missingUserId();\n }\n\n const effectiveUserId = userId || \"dev-user\";\n\n const userContext = ServiceContext.createCallerContext(\n token,\n effectiveUserId,\n undefined,\n userEmail ?? undefined,\n );\n\n return this._createAsUserProxy(\n (fn) =>\n (...args) =>\n runInCallerContext(userContext, () => fn(...args)),\n );\n }\n\n /**\n * Creates a proxy of `this` where every method call — and every function\n * in the result of `exports()` — runs inside `wrapCall`.\n *\n * `wrapCall` decides the per-call scope. Two strategies are used today:\n * - real OBO: fn => (...args) => runInCallerContext(userContext, () => fn(...args))\n * - dev fallback: fn => (...args) => otelContext.with(DEV_OBO_FALLBACK_KEY=true, () => fn(...args))\n *\n * `exports` is intercepted because methods captured in the returned\n * exports object never re-enter the proxy's `get` trap. Wrapping them\n * here is the only way to make the user context follow function\n * references back out of the plugin.\n */\n private _createAsUserProxy(\n wrapCall: (\n fn: (...a: unknown[]) => unknown,\n ) => (...a: unknown[]) => unknown,\n ): this {\n return new Proxy(this, {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") return value;\n if (typeof prop === \"string\" && EXCLUDED_FROM_PROXY.has(prop))\n return value;\n\n if (prop === \"exports\") {\n return () => {\n const raw = (value as () => unknown).call(target);\n if (raw == null) return {};\n // Callable exports (e.g. files, jobs) manage per-call asUser\n // themselves; leave them untouched.\n if (typeof raw === \"function\") return raw;\n if (isPlainObject(raw)) {\n return wrapExportFunctions(raw, (fn) =>\n wrapCall(fn.bind(target)),\n );\n }\n return raw;\n };\n }\n\n const fn = (value as (...a: unknown[]) => unknown).bind(target);\n return wrapCall(fn);\n },\n }) as this;\n }\n\n // streaming execution with interceptors\n protected async executeStream<T>(\n res: IAppResponse,\n fn: StreamExecuteHandler<T>,\n options: StreamExecutionSettings,\n userKey?: string,\n ) {\n // destructure options\n const {\n stream: streamConfig,\n default: defaultConfig,\n user: userConfig,\n } = options;\n\n // build execution options\n const executeConfig = this._buildExecutionConfig({\n default: defaultConfig,\n user: userConfig,\n });\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const self = this;\n // capture the active OTel context (HTTP span) before entering the async generator,\n // where it would otherwise be lost across the async boundary\n const parentOtelContext = otelContext.active();\n\n // wrapper function to ensure it returns a generator\n const asyncWrapperFn = async function* (streamSignal?: AbortSignal) {\n // build execution context\n const context: InterceptorContext = {\n signal: streamSignal,\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n // build interceptors\n const interceptors = self._buildInterceptors(executeConfig);\n\n // wrap the function to ensure it returns a promise\n const wrappedFn = async () => {\n const result = await fn(context.signal);\n return result;\n };\n\n // execute the function with interceptors, restoring the parent OTel context\n // so telemetry spans are linked as children of the HTTP request span\n const result = await otelContext.with(parentOtelContext, () =>\n self._executeWithInterceptors(\n wrappedFn as (signal?: AbortSignal) => Promise<T>,\n interceptors,\n context,\n ),\n );\n\n // check if result is a generator\n if (self._checkIfGenerator(result)) {\n yield* result;\n } else {\n yield result;\n }\n };\n\n // stream the result to the client. The effective user key is forwarded\n // to the stream manager so that reconnections to existing streamIds are\n // bound to the original creator (prevents cross-user stream takeover via\n // guessed/leaked IDs).\n await this.streamManager.stream(\n res,\n asyncWrapperFn,\n streamConfig,\n effectiveUserKey,\n );\n }\n\n /**\n * Execute a function with the plugin's interceptor chain.\n *\n * Returns an {@link ExecutionResult} discriminated union:\n * - `{ ok: true, data: T }` on success\n * - `{ ok: false, status: number, message: string }` on failure\n *\n * Errors are never thrown — the method is production-safe.\n */\n protected async execute<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: PluginExecutionSettings,\n userKey?: string,\n ): Promise<ExecutionResult<T>> {\n const executeConfig = this._buildExecutionConfig(options);\n\n const interceptors = this._buildInterceptors(executeConfig);\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const context: InterceptorContext = {\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n try {\n const data = await this._executeWithInterceptors(\n fn,\n interceptors,\n context,\n );\n return { ok: true, data };\n } catch (error) {\n logger.error(\"Plugin execution failed\", { error, plugin: this.name });\n\n if (error instanceof AppKitError) {\n return {\n ok: false,\n status: error.statusCode,\n message: error.message,\n };\n }\n\n if (hasHttpStatusCode(error)) {\n const isDev = process.env.NODE_ENV !== \"production\";\n const isClientError = error.statusCode >= 400 && error.statusCode < 500;\n return {\n ok: false,\n status: error.statusCode,\n message: isDev || isClientError ? error.message : \"Server error\",\n };\n }\n\n const isDev = process.env.NODE_ENV !== \"production\";\n return {\n ok: false,\n status: 500,\n message:\n isDev && error instanceof Error ? error.message : \"Server error\",\n };\n }\n }\n\n protected registerEndpoint(name: string, path: string): void {\n this.registeredEndpoints[name] = path;\n }\n\n protected route<_TResponse>(\n router: express.Router,\n config: RouteConfig,\n ): void {\n const { name, method, path, handler } = config;\n\n router[method](path, forwardAsyncErrors(handler));\n\n const fullPath = `/api/${camelToKebab(this.name)}${path}`;\n this.registerEndpoint(name, fullPath);\n\n if (config.skipBodyParsing) {\n this.skipBodyParsingPaths.add(fullPath);\n }\n }\n\n // build execution options by merging defaults, plugin config, and user overrides\n private _buildExecutionConfig(\n options: PluginExecutionSettings,\n ): PluginExecuteConfig {\n const { default: methodDefaults, user: userOverride } = options;\n\n // Merge: method defaults <- plugin config <- user override (highest priority)\n return deepMerge(\n deepMerge(methodDefaults, this.config),\n userOverride ?? {},\n ) as PluginExecuteConfig;\n }\n\n // build interceptors based on execute options\n private _buildInterceptors(\n options: PluginExecuteConfig,\n ): ExecutionInterceptor[] {\n const interceptors: ExecutionInterceptor[] = [];\n\n // order matters: telemetry → timeout → retry → cache (innermost to outermost)\n\n const telemetryConfig = normalizeTelemetryOptions(this.config.telemetry);\n if (\n telemetryConfig.traces &&\n (options.telemetryInterceptor?.enabled ?? true)\n ) {\n interceptors.push(\n new TelemetryInterceptor(this.telemetry, options.telemetryInterceptor),\n );\n }\n\n if (options.timeout && options.timeout > 0) {\n interceptors.push(new TimeoutInterceptor(options.timeout));\n }\n\n if (\n options.retry?.enabled &&\n options.retry.attempts &&\n options.retry.attempts > 1\n ) {\n interceptors.push(new RetryInterceptor(options.retry));\n }\n\n if (options.cache?.enabled && options.cache.cacheKey?.length) {\n interceptors.push(new CacheInterceptor(this.cache, options.cache));\n }\n\n return interceptors;\n }\n\n // execute method wrapped with interceptors\n private async _executeWithInterceptors<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n interceptors: ExecutionInterceptor[],\n context: InterceptorContext,\n ): Promise<T> {\n // no interceptors, execute directly\n if (interceptors.length === 0) {\n return fn(context.signal);\n }\n // build nested execution chain from interceptors\n let wrappedFn = () => fn(context.signal);\n\n // wrap each interceptor around the previous function\n for (const interceptor of interceptors) {\n const previousFn = wrappedFn;\n wrappedFn = () => interceptor.intercept(previousFn, context);\n }\n\n return wrappedFn();\n }\n\n private _checkIfGenerator(\n result: any,\n ): result is AsyncGenerator<any, void, unknown> {\n return (\n result && typeof result === \"object\" && Symbol.asyncIterator in result\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,SAAS,aAAa,SAAS;;;;;AAMrC,MAAM,uBAAuB,iBAAiB,wBAAwB;;;;;;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,SACE,UAAU,OAAO,WAAW,YAAY,OAAO,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"plugin.js","names":["otelContext","context"],"sources":["../../src/plugin/plugin.ts"],"sourcesContent":["import { context as otelContext } from \"@opentelemetry/api\";\nimport type express from \"express\";\nimport type {\n BasePlugin,\n BasePluginConfig,\n IAppResponse,\n PluginEndpointMap,\n PluginExecuteConfig,\n PluginExecutionSettings,\n PluginPhase,\n RouteConfig,\n StreamExecuteHandler,\n StreamExecutionSettings,\n} from \"shared\";\nimport { camelToKebab } from \"shared\";\n\nimport { AppManager } from \"../app\";\nimport { CacheManager } from \"../cache\";\nimport { getCurrentPrincipalId } from \"../context\";\nimport { warnContextDeprecation } from \"../context/deprecation\";\nimport { normalizeIdentityError } from \"../context/execution-context\";\nimport { createRequestScope } from \"../context/request-scope\";\nimport {\n assertPluginExecution,\n getPluginResourceTypes,\n} from \"../context/resource-capabilities\";\nimport { scopePlugin } from \"../context/scoped-api\";\nimport type { PluginContext } from \"../core/plugin-context\";\nimport { AppKitError, AuthenticationError } from \"../errors\";\nimport { IdentityExpiredError } from \"../errors/identity-expired\";\nimport { createLogger } from \"../logging/logger\";\nimport { StreamManager } from \"../stream\";\nimport {\n type ITelemetry,\n normalizeTelemetryOptions,\n TelemetryManager,\n} from \"../telemetry\";\nimport { deepMerge } from \"../utils\";\nimport { forwardAsyncErrors } from \"../utils/safe-handler\";\nimport { DevFileReader } from \"./dev-reader\";\nimport type { ExecutionResult } from \"./execution-result\";\nimport { CacheInterceptor } from \"./interceptors/cache\";\nimport { RetryInterceptor } from \"./interceptors/retry\";\nimport { TelemetryInterceptor } from \"./interceptors/telemetry\";\nimport { TimeoutInterceptor } from \"./interceptors/timeout\";\nimport type {\n ExecutionInterceptor,\n InterceptorContext,\n} from \"./interceptors/types\";\n\nconst logger = createLogger(\"plugin\");\n\nexport { isPlainObject } from \"../utils/is-plain-object\";\nexport { isDevOboFallback } from \"../context/request-scope\";\n\n/**\n * Narrow an unknown thrown value to an Error that carries a numeric\n * `statusCode` property (e.g. `ApiError` from `@databricks/sdk-experimental`).\n */\nfunction hasHttpStatusCode(\n error: unknown,\n): error is Error & { statusCode: number } {\n return (\n error instanceof Error &&\n \"statusCode\" in error &&\n typeof (error as Record<string, unknown>).statusCode === \"number\"\n );\n}\n\n/**\n * Base abstract class for creating AppKit plugins.\n *\n * All plugins must declare a static `manifest` property with their metadata\n * and resource requirements. The manifest defines:\n * - `required` resources: Always needed for the plugin to function\n * - `optional` resources: May be needed depending on plugin configuration\n *\n * ## Static vs Runtime Resource Requirements\n *\n * The manifest is static and doesn't know the plugin's runtime configuration.\n * For resources that become required based on config options, plugins can\n * implement a static `getResourceRequirements(config)` method.\n *\n * At runtime, this method is called with the actual config to determine\n * which \"optional\" resources should be treated as \"required\".\n *\n * @example Basic plugin with static requirements\n * ```typescript\n * import { Plugin, toPlugin, PluginManifest, ResourceType } from '@databricks/appkit';\n *\n * const myManifest: PluginManifest = {\n * name: 'myPlugin',\n * displayName: 'My Plugin',\n * description: 'Does something awesome',\n * resources: {\n * required: [\n * { type: ResourceType.SQL_WAREHOUSE, alias: 'warehouse', ... }\n * ],\n * optional: []\n * }\n * };\n *\n * class MyPlugin extends Plugin<MyConfig> {\n * static manifest = myManifest;\n * }\n * ```\n *\n * @example Plugin with config-dependent resources\n * ```typescript\n * interface MyConfig extends BasePluginConfig {\n * enableCaching?: boolean;\n * }\n *\n * const myManifest: PluginManifest = {\n * name: 'myPlugin',\n * resources: {\n * required: [\n * { type: ResourceType.SQL_WAREHOUSE, alias: 'warehouse', ... }\n * ],\n * optional: [\n * // Database is optional in the static manifest\n * { type: ResourceType.DATABASE, alias: 'cache', description: 'Required if caching enabled', ... }\n * ]\n * }\n * };\n *\n * class MyPlugin extends Plugin<MyConfig> {\n * static manifest = myManifest<\"myPlugin\">;\n *\n * // Runtime method: converts optional resources to required based on config\n * static getResourceRequirements(config: MyConfig) {\n * const resources = [];\n * if (config.enableCaching) {\n * // When caching is enabled, Database becomes required\n * resources.push({\n * type: ResourceType.DATABASE,\n * alias: 'cache',\n * resourceKey: 'database',\n * description: 'Cache storage for query results',\n * permission: 'CAN_CONNECT_AND_CREATE',\n * fields: {\n * instance_name: { env: 'DATABRICKS_CACHE_INSTANCE' },\n * database_name: { env: 'DATABRICKS_CACHE_DB' },\n * },\n * required: true // Mark as required at runtime\n * });\n * }\n * return resources;\n * }\n * }\n * ```\n */\nexport abstract class Plugin<\n TConfig extends BasePluginConfig = BasePluginConfig,\n> implements BasePlugin {\n protected isReady = false;\n protected cache!: CacheManager;\n protected app: AppManager;\n protected devFileReader: DevFileReader;\n protected streamManager: StreamManager;\n protected telemetry!: ITelemetry;\n protected context?: PluginContext;\n\n /** Registered endpoints for this plugin */\n private registeredEndpoints: PluginEndpointMap = {};\n\n /** Paths that opt out of JSON body parsing (e.g. file upload routes) */\n private skipBodyParsingPaths: Set<string> = new Set();\n\n /**\n * Plugin initialization phase.\n * - 'core': Initialized first (e.g., config plugins)\n * - 'normal': Initialized second (most plugins)\n * - 'deferred': Initialized last (e.g., server plugin)\n */\n static phase: PluginPhase = \"normal\";\n\n /**\n * Plugin name identifier.\n */\n name: string;\n\n constructor(protected config: TConfig) {\n this.name =\n config.name ??\n (this.constructor as { manifest?: { name: string } }).manifest?.name ??\n \"plugin\";\n this.streamManager = new StreamManager(config.streamConfig);\n this.app = new AppManager();\n this.devFileReader = DevFileReader.getInstance();\n this.context = (config as Record<string, unknown>).context as\n | PluginContext\n | undefined;\n\n // Eagerly bind telemetry + cache if the core services have already been\n // initialized (normal createApp path, or tests that mock CacheManager).\n // If they haven't, we leave these undefined and rely on `attachContext`\n // being called later — this lets factories eagerly construct plugin\n // instances at module top-level before `createApp` has run.\n this.tryAttachContext();\n }\n\n private tryAttachContext(): void {\n try {\n this.cache = CacheManager.getInstanceSync();\n } catch {\n return;\n }\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n this.config.telemetry,\n );\n this.isReady = true;\n }\n\n /**\n * Binds runtime dependencies (telemetry provider, cache, plugin context) to\n * this plugin. Called by `AppKit._createApp` after construction and before\n * `setup()`. Idempotent: safe to call if the constructor already bound them\n * eagerly. Kept separate so factories can eagerly construct plugin instances\n * without running this before `TelemetryManager.initialize()` /\n * `CacheManager.getInstance()` have run.\n */\n attachContext(\n deps: {\n context?: unknown;\n telemetryConfig?: BasePluginConfig[\"telemetry\"];\n } = {},\n ): void {\n if (!this.cache) {\n this.cache = CacheManager.getInstanceSync();\n }\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n deps.telemetryConfig ?? this.config.telemetry,\n );\n if (deps.context !== undefined) {\n this.context = deps.context as PluginContext;\n }\n this.isReady = true;\n }\n\n injectRoutes(_: express.Router) {\n return;\n }\n\n async setup() {}\n\n getEndpoints(): PluginEndpointMap {\n return this.registeredEndpoints;\n }\n\n getSkipBodyParsingPaths(): ReadonlySet<string> {\n return this.skipBodyParsingPaths;\n }\n\n abortActiveOperations(): void {\n this.streamManager.abortAll();\n }\n\n /**\n * Returns the public exports for this plugin.\n * Override this to define a custom public API.\n * By default, returns an empty object.\n *\n * The returned object becomes the plugin's public API on the AppKit instance\n * (e.g. `appkit.myPlugin.method()`). AppKit automatically binds method context\n * and adds `asUser(req)` for user-scoped execution.\n *\n * @example\n * ```ts\n * class MyPlugin extends Plugin {\n * private getData() { return []; }\n *\n * exports() {\n * return { getData: this.getData };\n * }\n * }\n *\n * // After registration:\n * const appkit = await createApp({ plugins: [myPlugin()] });\n * appkit.myPlugin.getData();\n * ```\n */\n exports(): unknown {\n return {};\n }\n\n /**\n * Returns startup config to expose to the client.\n * Override this to surface server-side values that are safe to publish to the\n * frontend, such as feature flags, resource IDs, or other app boot settings.\n *\n * This runs once when the server starts, so it should not depend on\n * request-scoped or user-specific state.\n *\n * String values that match non-public environment variables are redacted\n * unless you intentionally expose them via a matching `PUBLIC_APPKIT_` env var.\n *\n * Values must be JSON-serializable plain data (no functions, Dates, classes,\n * Maps, Sets, BigInts, or circular references).\n * By default returns an empty object (plugin contributes nothing to client config).\n *\n * On the client, read the config with the `usePluginClientConfig` hook\n * (React) or the `getPluginClientConfig` function (vanilla JS), both\n * from `@databricks/appkit-ui`.\n *\n * @example\n * ```ts\n * // Server — plugin definition\n * class MyPlugin extends Plugin<MyConfig> {\n * clientConfig() {\n * return {\n * warehouseId: this.config.warehouseId,\n * features: { darkMode: true },\n * };\n * }\n * }\n *\n * // Client — React component\n * import { usePluginClientConfig } from \"@databricks/appkit-ui/react\";\n *\n * interface MyPluginConfig { warehouseId: string; features: { darkMode: boolean } }\n *\n * const config = usePluginClientConfig<MyPluginConfig>(\"myPlugin\");\n * config.warehouseId; // \"abc-123\"\n *\n * // Client — vanilla JS\n * import { getPluginClientConfig } from \"@databricks/appkit-ui/js\";\n *\n * const config = getPluginClientConfig<MyPluginConfig>(\"myPlugin\");\n * ```\n */\n clientConfig(): Record<string, unknown> {\n return {};\n }\n\n /**\n * Resolve the effective user ID from a request.\n *\n * Returns the `x-forwarded-user` header when present. In development mode\n * (`NODE_ENV=development`) falls back to the current context user ID so\n * that callers outside an active `runInCallerContext` scope still get a\n * consistent value.\n *\n * @throws AuthenticationError in production when no user header is present.\n */\n protected resolveUserId(req: express.Request): string {\n const userId = req.header(\"x-forwarded-user\")?.trim();\n if (userId) return userId;\n if (process.env.NODE_ENV === \"development\") return getCurrentPrincipalId();\n throw AuthenticationError.missingUserId();\n }\n\n /** @deprecated Use appkit.asUser(req) to scope the whole app. */\n asUser(req: express.Request): this {\n warnContextDeprecation(\"Plugin.asUser\", \"appkit.asUser(req)\");\n assertPluginExecution(this);\n return scopePlugin(\n this,\n createRequestScope(req, getPluginResourceTypes(this), { legacy: true }),\n );\n }\n\n /**\n * User-scoped executor for the plugin's own on-behalf-of routing (for\n * example `.obo.sql` lanes), using the same caller context as the\n * app-level `appkit.asUser(req)`.\n *\n * Unlike the deprecated public `asUser(req)`, this does not emit a\n * deprecation warning and does not opt out of the app-only resource\n * guards, so internal routing matches current on-behalf-of semantics\n * rather than the retained legacy behavior.\n *\n * @internal\n */\n protected _asUserScoped(req: express.Request): this {\n assertPluginExecution(this);\n return scopePlugin(\n this,\n createRequestScope(req, getPluginResourceTypes(this)),\n );\n }\n\n // streaming execution with interceptors\n protected async executeStream<T>(\n res: IAppResponse,\n fn: StreamExecuteHandler<T>,\n options: StreamExecutionSettings,\n userKey?: string,\n ) {\n assertPluginExecution(this);\n // destructure options\n const {\n stream: streamConfig,\n default: defaultConfig,\n user: userConfig,\n } = options;\n\n // build execution options\n const executeConfig = this._buildExecutionConfig({\n default: defaultConfig,\n user: userConfig,\n });\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentPrincipalId();\n\n const self = this;\n // capture the active OTel context (HTTP span) before entering the async generator,\n // where it would otherwise be lost across the async boundary\n const parentOtelContext = otelContext.active();\n\n // wrapper function to ensure it returns a generator\n const asyncWrapperFn = async function* (streamSignal?: AbortSignal) {\n // build execution context\n const context: InterceptorContext = {\n signal: streamSignal,\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n // build interceptors\n const interceptors = self._buildInterceptors(executeConfig);\n\n // wrap the function to ensure it returns a promise\n const wrappedFn = async () => {\n const result = await fn(context.signal);\n return result;\n };\n\n // execute the function with interceptors, restoring the parent OTel context\n // so telemetry spans are linked as children of the HTTP request span\n const result = await otelContext.with(parentOtelContext, () =>\n self._executeWithInterceptors(\n wrappedFn as (signal?: AbortSignal) => Promise<T>,\n interceptors,\n context,\n ),\n );\n\n // check if result is a generator\n try {\n if (self._checkIfGenerator(result)) {\n yield* result;\n } else {\n yield result;\n }\n } catch (error) {\n throw normalizeIdentityError(error);\n }\n };\n\n // stream the result to the client. The effective user key is forwarded\n // to the stream manager so that reconnections to existing streamIds are\n // bound to the original creator (prevents cross-user stream takeover via\n // guessed/leaked IDs).\n await this.streamManager.stream(\n res,\n asyncWrapperFn,\n streamConfig,\n effectiveUserKey,\n );\n }\n\n /**\n * Execute a function with the plugin's interceptor chain.\n *\n * Returns an {@link ExecutionResult} discriminated union:\n * - `{ ok: true, data: T }` on success\n * - `{ ok: false, status: number, message: string }` on failure\n *\n * Caller credential expiration retains the failure result and additionally\n * exposes a typed error, preserving existing result-based callers.\n */\n protected async execute<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: PluginExecutionSettings,\n userKey?: string,\n ): Promise<ExecutionResult<T>> {\n assertPluginExecution(this);\n const executeConfig = this._buildExecutionConfig(options);\n\n const interceptors = this._buildInterceptors(executeConfig);\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentPrincipalId();\n\n const context: InterceptorContext = {\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n try {\n const data = await this._executeWithInterceptors(\n fn,\n interceptors,\n context,\n );\n return { ok: true, data };\n } catch (caught) {\n const error = normalizeIdentityError(caught);\n logger.error(\"Plugin execution failed\", { error, plugin: this.name });\n\n if (error instanceof AppKitError) {\n return {\n ok: false,\n status: error.statusCode,\n message: error.message,\n ...(error instanceof IdentityExpiredError ? { error } : {}),\n };\n }\n\n if (hasHttpStatusCode(error)) {\n const isDev = process.env.NODE_ENV !== \"production\";\n const isClientError = error.statusCode >= 400 && error.statusCode < 500;\n return {\n ok: false,\n status: error.statusCode,\n message: isDev || isClientError ? error.message : \"Server error\",\n };\n }\n\n const isDev = process.env.NODE_ENV !== \"production\";\n return {\n ok: false,\n status: 500,\n message:\n isDev && error instanceof Error ? error.message : \"Server error\",\n };\n }\n }\n\n protected registerEndpoint(name: string, path: string): void {\n this.registeredEndpoints[name] = path;\n }\n\n protected route<_TResponse>(\n router: express.Router,\n config: RouteConfig,\n ): void {\n const { name, method, path, handler } = config;\n\n router[method](path, forwardAsyncErrors(handler));\n\n const fullPath = `/api/${camelToKebab(this.name)}${path}`;\n this.registerEndpoint(name, fullPath);\n\n if (config.skipBodyParsing) {\n this.skipBodyParsingPaths.add(fullPath);\n }\n }\n\n // build execution options by merging defaults, plugin config, and user overrides\n private _buildExecutionConfig(\n options: PluginExecutionSettings,\n ): PluginExecuteConfig {\n const { default: methodDefaults, user: userOverride } = options;\n\n // Merge: method defaults <- plugin config <- user override (highest priority)\n return deepMerge(\n deepMerge(methodDefaults, this.config),\n userOverride ?? {},\n ) as PluginExecuteConfig;\n }\n\n // build interceptors based on execute options\n private _buildInterceptors(\n options: PluginExecuteConfig,\n ): ExecutionInterceptor[] {\n const interceptors: ExecutionInterceptor[] = [];\n\n // order matters: telemetry → timeout → retry → cache (innermost to outermost)\n\n const telemetryConfig = normalizeTelemetryOptions(this.config.telemetry);\n if (\n telemetryConfig.traces &&\n (options.telemetryInterceptor?.enabled ?? true)\n ) {\n interceptors.push(\n new TelemetryInterceptor(this.telemetry, options.telemetryInterceptor),\n );\n }\n\n if (options.timeout && options.timeout > 0) {\n interceptors.push(new TimeoutInterceptor(options.timeout));\n }\n\n if (\n options.retry?.enabled &&\n options.retry.attempts &&\n options.retry.attempts > 1\n ) {\n interceptors.push(new RetryInterceptor(options.retry));\n }\n\n if (options.cache?.enabled && options.cache.cacheKey?.length) {\n interceptors.push(new CacheInterceptor(this.cache, options.cache));\n }\n\n return interceptors;\n }\n\n // execute method wrapped with interceptors\n private async _executeWithInterceptors<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n interceptors: ExecutionInterceptor[],\n context: InterceptorContext,\n ): Promise<T> {\n // no interceptors, execute directly\n if (interceptors.length === 0) {\n return fn(context.signal);\n }\n // build nested execution chain from interceptors\n let wrappedFn = () => fn(context.signal);\n\n // wrap each interceptor around the previous function\n for (const interceptor of interceptors) {\n const previousFn = wrappedFn;\n wrappedFn = () => interceptor.intercept(previousFn, context);\n }\n\n return wrappedFn();\n }\n\n private _checkIfGenerator(\n result: any,\n ): result is AsyncGenerator<any, void, unknown> {\n return (\n result && typeof result === \"object\" && Symbol.asyncIterator in result\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,SAAS,aAAa,SAAS;;;;;AASrC,SAAS,kBACP,OACyC;AACzC,QACE,iBA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,gBACT,MAAK,qBAAqB,IAAI,SAAS;;CAK3C,AAAQ,sBACN,SACqB;EACrB,MAAM,EAAE,SAAS,gBAAgB,MAAM,iBAAiB;AAGxD,SAAO,UACL,UAAU,gBAAgB,KAAK,OAAO,EACtC,gBAAgB,EAAE,CACnB;;CAIH,AAAQ,mBACN,SACwB;EACxB,MAAM,eAAuC,EAAE;AAK/C,MADwB,0BAA0B,KAAK,OAAO,UAAU,CAEtD,WACf,QAAQ,sBAAsB,WAAW,MAE1C,cAAa,KACX,IAAI,qBAAqB,KAAK,WAAW,QAAQ,qBAAqB,CACvE;AAGH,MAAI,QAAQ,WAAW,QAAQ,UAAU,EACvC,cAAa,KAAK,IAAI,mBAAmB,QAAQ,QAAQ,CAAC;AAG5D,MACE,QAAQ,OAAO,WACf,QAAQ,MAAM,YACd,QAAQ,MAAM,WAAW,EAEzB,cAAa,KAAK,IAAI,iBAAiB,QAAQ,MAAM,CAAC;AAGxD,MAAI,QAAQ,OAAO,WAAW,QAAQ,MAAM,UAAU,OACpD,cAAa,KAAK,IAAI,iBAAiB,KAAK,OAAO,QAAQ,MAAM,CAAC;AAGpE,SAAO;;CAIT,MAAc,yBACZ,IACA,cACA,SACY;AAEZ,MAAI,aAAa,WAAW,EAC1B,QAAO,GAAG,QAAQ,OAAO;EAG3B,IAAI,kBAAkB,GAAG,QAAQ,OAAO;AAGxC,OAAK,MAAM,eAAe,cAAc;GACtC,MAAM,aAAa;AACnB,qBAAkB,YAAY,UAAU,YAAY,QAAQ;;AAG9D,SAAO,WAAW;;CAGpB,AAAQ,kBACN,QAC8C;AAC9C,SACE,UAAU,OAAO,WAAW,YAAY,OAAO,iBAAiB"}
|
|
@@ -173,6 +173,18 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
173
173
|
* does not provide. See {@link collectApprovalRequiredToolNames}.
|
|
174
174
|
*/
|
|
175
175
|
private _handleInvoke;
|
|
176
|
+
/**
|
|
177
|
+
* Fail closed for an on-behalf-of-user agent: without a forwarded user token
|
|
178
|
+
* the request is rejected with 401 before any model or tool call, in
|
|
179
|
+
* production and in development. Other agents are unaffected.
|
|
180
|
+
*/
|
|
181
|
+
private allowsCaller;
|
|
182
|
+
/**
|
|
183
|
+
* Run an on-behalf-of-user agent inside the request's user scope, so the
|
|
184
|
+
* model call, hand-rolled tools, and sub-agents all act as the user. Other
|
|
185
|
+
* agents run exactly as before.
|
|
186
|
+
*/
|
|
187
|
+
private runInAgentScope;
|
|
176
188
|
private _streamAgent;
|
|
177
189
|
/**
|
|
178
190
|
* Non-streaming counterpart to {@link _streamAgent} used by `/invocations`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;cAmHa,YAAA,SAAqB,MAAA,YAAkB,YAAA;EAAA,OAC3C,QAAA,EADiB,cAAA;EAAA,OAEjB,KAAA,EAAO,WAAA;EAAA,UAEI,MAAA,EAAQ,kBAAA;EAAA,QAElB,MAAA;EAAA,QACA,gBAAA;;AAPV;;;UAYU,OAAA;EAAA,QACA,SAAA;EAAA,QACA,WAAA;EAAA,QACA,YAAA;EAqFG;EAAA,QAnFH,0BAAA;EAqxBS;EAAA,QAnxBT,6BAAA;cAEI,MAAA,EAAQ,kBAAA;EA+1BJ;;;;;;;;;;EAp3B8C;;;;;EAAA,QAyDtD,YAAA;EAAA,QAEA,oBAAA;EAAA,YAKI,sBAAA,CAAA;EA5DM;EAAA,YAsEN,cAAA,CAAA;EApEJ;EAAA,QA8EA,gBAAA;EAAA,QAIA,WAAA;EAAA,QAQA,aAAA;EAIF,KAAA,CAAA,GAAK,OAAA;EArFH;;;;;;EA0GF,MAAA,CAAA,GAAU,OAAA;EA9DR;;;;;EAAA,QAwFM,kBAAA;EA/CR;;;;;EAAA,QA4JE,mBAAA;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