@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.
- package/CLAUDE.md +21 -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/index.js +1 -1
- package/dist/connectors/lakebase/routing-pool.d.ts +1 -1
- package/dist/connectors/lakebase/routing-pool.d.ts.map +1 -1
- package/dist/connectors/lakebase/routing-pool.js +6 -12
- package/dist/connectors/lakebase/routing-pool.js.map +1 -1
- package/dist/context/caller-context.d.ts +25 -0
- package/dist/context/caller-context.d.ts.map +1 -0
- package/dist/context/caller-context.js +21 -0
- package/dist/context/caller-context.js.map +1 -0
- package/dist/context/deprecation.js +14 -0
- package/dist/context/deprecation.js.map +1 -0
- package/dist/context/execution-context.d.ts +40 -4
- package/dist/context/execution-context.d.ts.map +1 -1
- package/dist/context/execution-context.js +87 -33
- package/dist/context/execution-context.js.map +1 -1
- package/dist/context/index.d.ts +3 -2
- package/dist/context/index.js +3 -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 +18 -12
- package/dist/context/service-context.d.ts.map +1 -1
- package/dist/context/service-context.js +45 -55
- package/dist/context/service-context.js.map +1 -1
- package/dist/context/user-context.d.ts +16 -22
- package/dist/context/user-context.d.ts.map +1 -1
- package/dist/context/user-context.js +57 -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 +34 -11
- 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 +12 -6
- package/dist/index.js +7 -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 +14 -22
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +42 -123
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/plugins/agents/agents.d.ts +13 -1
- 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 +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 +3 -3
- package/dist/plugins/analytics/analytics.d.ts.map +1 -1
- package/dist/plugins/analytics/analytics.js +9 -7
- 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/database/database.d.ts +1 -1
- package/dist/plugins/files/plugin.d.ts +21 -15
- package/dist/plugins/files/plugin.d.ts.map +1 -1
- package/dist/plugins/files/plugin.js +50 -29
- package/dist/plugins/files/plugin.js.map +1 -1
- package/dist/plugins/genie/genie.d.ts +10 -1
- 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.d.ts +1 -1
- package/dist/plugins/jobs/plugin.js +2 -2
- package/dist/plugins/jobs/plugin.js.map +1 -1
- package/dist/plugins/lakebase/lakebase.d.ts +11 -18
- package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
- package/dist/plugins/lakebase/lakebase.js +16 -21
- 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 +1 -1
- package/dist/plugins/server/index.d.ts.map +1 -1
- package/dist/plugins/server/index.js +3 -0
- package/dist/plugins/server/index.js.map +1 -1
- package/dist/plugins/serving/manifest.js +1 -0
- package/dist/plugins/serving/serving.d.ts +1 -1
- package/dist/plugins/serving/serving.js +6 -6
- package/dist/plugins/serving/serving.js.map +1 -1
- package/dist/resources/index.d.ts +1 -0
- package/dist/resources/index.js +3 -0
- package/dist/resources/warehouse.d.ts +16 -0
- package/dist/resources/warehouse.d.ts.map +1 -0
- package/dist/resources/warehouse.js +93 -0
- package/dist/resources/warehouse.js.map +1 -0
- package/dist/schemas/manifest.d.ts +44 -1
- package/dist/schemas/manifest.d.ts.map +1 -1
- package/dist/schemas/manifest.js +122 -3
- 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 +17 -0
- package/dist/shared/src/schemas/manifest.d.ts.map +1 -1
- package/dist/shared/src/schemas/manifest.js +53 -3
- 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 +2 -2
- package/dist/testing/create-test-app.js.map +1 -1
- package/dist/testing/fixtures.d.ts +3 -2
- package/dist/testing/fixtures.d.ts.map +1 -1
- package/dist/testing/fixtures.js +21 -14
- package/dist/testing/fixtures.js.map +1 -1
- package/dist/testing/reset-singletons.js +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/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 +9 -13
- 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.getCurrentActorId.md +12 -0
- package/docs/api/appkit/Function.getCurrentPrincipalKey.md +12 -0
- package/docs/api/appkit/Function.getCurrentUserId.md +14 -0
- package/docs/api/appkit/Function.getExecutionContext.md +5 -3
- package/docs/api/appkit/Function.getUserContext.md +16 -0
- package/docs/api/appkit/Function.getWarehouseId.md +20 -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 +54 -0
- package/docs/api/appkit/Interface.IndexConfig.md +1 -1
- package/docs/api/appkit/Interface.PluginManifest.md +33 -2
- 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.CallerPrincipal.md +13 -0
- package/docs/api/appkit/TypeAlias.ExecutionContext.md +9 -0
- 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 +20 -0
- package/docs/plugins/agents.md +45 -0
- package/docs/plugins/analytics.md +8 -0
- package/docs/plugins/execution-context.md +101 -50
- package/docs/plugins/lakebase.md +6 -82
- package/llms.txt +21 -1
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -1,32 +1,26 @@
|
|
|
1
1
|
import { ServiceContextState } from "./service-context.js";
|
|
2
|
+
import { CallerContext, ExecutionContext } from "./caller-context.js";
|
|
2
3
|
|
|
3
4
|
//#region src/context/user-context.d.ts
|
|
4
5
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
6
|
+
* @deprecated Use CallerContext and its principal field. Kept for callers
|
|
7
|
+
* that construct the legacy shape or read its flat identity fields.
|
|
7
8
|
*/
|
|
8
|
-
|
|
9
|
-
/** WorkspaceClient authenticated as the user */
|
|
10
|
-
|
|
11
|
-
/** The user's
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
userEmail?: string;
|
|
17
|
-
/** Truncated SHA-256 hash of the user's OBO token, used to detect token rotation */
|
|
18
|
-
tokenFingerprint?: string;
|
|
19
|
-
/** Promise that resolves to the warehouse ID (inherited from service context, only present when a plugin requires `SQL_WAREHOUSE` resource) */
|
|
20
|
-
warehouseId?: Promise<string>;
|
|
21
|
-
/** Promise that resolves to the workspace ID (inherited from service context) */
|
|
22
|
-
workspaceId: Promise<string>;
|
|
23
|
-
/** Flag indicating this is a user context */
|
|
9
|
+
type UserContext = {
|
|
10
|
+
/** WorkspaceClient authenticated as the user */client: ServiceContextState["client"]; /** The user's ID (from request headers) */
|
|
11
|
+
userId: string; /** The user's name (from request headers) */
|
|
12
|
+
userName?: string; /** The user's email (from `x-forwarded-email` header) */
|
|
13
|
+
userEmail?: string; /** Truncated SHA-256 hash of the user's OBO token, used to detect token rotation */
|
|
14
|
+
tokenFingerprint?: string; /** @deprecated Use getWarehouseId() from @databricks/appkit. */
|
|
15
|
+
warehouseId?: Promise<string>; /** Promise that resolves to the workspace ID (inherited from service context) */
|
|
16
|
+
workspaceId: Promise<string>; /** Flag indicating this is a user context */
|
|
24
17
|
isUserContext: true;
|
|
25
|
-
}
|
|
18
|
+
};
|
|
26
19
|
/**
|
|
27
|
-
*
|
|
20
|
+
* @deprecated Use isCallerContext. Active caller contexts retain the legacy
|
|
21
|
+
* identity accessors for callers narrowed by this guard.
|
|
28
22
|
*/
|
|
29
|
-
|
|
23
|
+
declare function isUserContext(ctx: ExecutionContext | UserContext): ctx is UserContext & Partial<CallerContext>;
|
|
30
24
|
//#endregion
|
|
31
|
-
export {
|
|
25
|
+
export { UserContext, isUserContext };
|
|
32
26
|
//# sourceMappingURL=user-context.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-context.d.ts","names":[],"sources":["../../src/context/user-context.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"user-context.d.ts","names":[],"sources":["../../src/context/user-context.ts"],"mappings":";;;;;AAiBA;;;KAAY,WAAA;EAYI,gDAVd,MAAA,EAAQ,mBAAA,YAYY;EAVpB,MAAA,UAFA;EAIA,QAAA,WAFA;EAIA,SAAA;EAEA,gBAAA,WAEA;EAAA,WAAA,GAAc,OAAA,UAEd;EAAA,WAAA,EAAa,OAAA,UAEb;EAAA,aAAA;AAAA;;;;;iBAkGc,aAAA,CACd,GAAA,EAAK,gBAAA,GAAmB,WAAA,GACvB,GAAA,IAAO,WAAA,GAAc,OAAA,CAAQ,aAAA"}
|
|
@@ -1,11 +1,65 @@
|
|
|
1
|
+
import { isCallerContext, snapshotCallerContext } from "./caller-context.js";
|
|
2
|
+
import { warnContextDeprecation } from "./deprecation.js";
|
|
3
|
+
|
|
1
4
|
//#region src/context/user-context.ts
|
|
5
|
+
const immutableCallers = /* @__PURE__ */ new WeakSet();
|
|
6
|
+
function legacyIdentityContext(ctx) {
|
|
7
|
+
if (immutableCallers.has(ctx)) return ctx;
|
|
8
|
+
const caller = snapshotCallerContext(ctx);
|
|
9
|
+
const { principal } = caller;
|
|
10
|
+
const snapshot = Object.freeze({
|
|
11
|
+
...caller,
|
|
12
|
+
get userId() {
|
|
13
|
+
warnContextDeprecation("UserContext.userId", "CallerContext.principal.userId");
|
|
14
|
+
return principal.userId;
|
|
15
|
+
},
|
|
16
|
+
get userName() {
|
|
17
|
+
warnContextDeprecation("UserContext.userName", "CallerContext.principal.userName");
|
|
18
|
+
return principal.userName;
|
|
19
|
+
},
|
|
20
|
+
get userEmail() {
|
|
21
|
+
warnContextDeprecation("UserContext.userEmail", "CallerContext.principal.userEmail");
|
|
22
|
+
return principal.userEmail;
|
|
23
|
+
},
|
|
24
|
+
get isUserContext() {
|
|
25
|
+
warnContextDeprecation("UserContext.isUserContext", "CallerContext.principal.type");
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
immutableCallers.add(snapshot);
|
|
30
|
+
return snapshot;
|
|
31
|
+
}
|
|
32
|
+
/** Expose the old resource field only through the deprecated context APIs. */
|
|
33
|
+
function legacyUserContext(ctx, resolveWarehouseId) {
|
|
34
|
+
return Object.freeze(Object.defineProperties({ get warehouseId() {
|
|
35
|
+
warnContextDeprecation("UserContext.warehouseId", "getWarehouseId() from @databricks/appkit");
|
|
36
|
+
return resolveWarehouseId();
|
|
37
|
+
} }, Object.getOwnPropertyDescriptors(legacyIdentityContext(ctx))));
|
|
38
|
+
}
|
|
39
|
+
/** Normalize legacy inputs before opening a caller scope. */
|
|
40
|
+
function toCallerContext(ctx) {
|
|
41
|
+
if ("principal" in ctx) return ctx;
|
|
42
|
+
return {
|
|
43
|
+
client: ctx.client,
|
|
44
|
+
principal: {
|
|
45
|
+
type: "user",
|
|
46
|
+
userId: ctx.userId,
|
|
47
|
+
userName: ctx.userName,
|
|
48
|
+
userEmail: ctx.userEmail
|
|
49
|
+
},
|
|
50
|
+
tokenFingerprint: ctx.tokenFingerprint,
|
|
51
|
+
workspaceId: ctx.workspaceId
|
|
52
|
+
};
|
|
53
|
+
}
|
|
2
54
|
/**
|
|
3
|
-
*
|
|
55
|
+
* @deprecated Use isCallerContext. Active caller contexts retain the legacy
|
|
56
|
+
* identity accessors for callers narrowed by this guard.
|
|
4
57
|
*/
|
|
5
58
|
function isUserContext(ctx) {
|
|
6
|
-
|
|
59
|
+
warnContextDeprecation("isUserContext", "isCallerContext");
|
|
60
|
+
return "principal" in ctx ? isCallerContext(ctx) : "isUserContext" in ctx && ctx.isUserContext === true;
|
|
7
61
|
}
|
|
8
62
|
|
|
9
63
|
//#endregion
|
|
10
|
-
export { isUserContext };
|
|
64
|
+
export { isUserContext, legacyUserContext, toCallerContext };
|
|
11
65
|
//# sourceMappingURL=user-context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user-context.js","names":[],"sources":["../../src/context/user-context.ts"],"sourcesContent":["import type { ServiceContextState } from \"./service-context\";\n\n/**\n *
|
|
1
|
+
{"version":3,"file":"user-context.js","names":[],"sources":["../../src/context/user-context.ts"],"sourcesContent":["import {\n type CallerContext,\n type ExecutionContext,\n isCallerContext,\n snapshotCallerContext,\n} from \"./caller-context\";\nimport { warnContextDeprecation } from \"./deprecation\";\nimport type { ServiceContextState } from \"./service-context\";\n\nexport type { ExecutionContext } from \"./caller-context\";\n\nconst immutableCallers = new WeakSet<object>();\n\n/**\n * @deprecated Use CallerContext and its principal field. Kept for callers\n * that construct the legacy shape or read its flat identity fields.\n */\nexport type UserContext = {\n /** WorkspaceClient authenticated as the user */\n client: ServiceContextState[\"client\"];\n /** The user's ID (from request headers) */\n userId: string;\n /** The user's name (from request headers) */\n userName?: string;\n /** The user's email (from `x-forwarded-email` header) */\n userEmail?: string;\n /** Truncated SHA-256 hash of the user's OBO token, used to detect token rotation */\n tokenFingerprint?: string;\n /** @deprecated Use getWarehouseId() from @databricks/appkit. */\n warehouseId?: Promise<string>;\n /** Promise that resolves to the workspace ID (inherited from service context) */\n workspaceId: Promise<string>;\n /** Flag indicating this is a user context */\n isUserContext: true;\n};\n\n/**\n * @deprecated Use snapshotCallerContext for identity-only snapshots.\n * Retains the legacy fields for existing callers.\n */\nexport function immutableCallerContext(\n ctx: CallerContext,\n): CallerContext & UserContext {\n warnContextDeprecation(\"immutableCallerContext\", \"snapshotCallerContext\");\n return legacyIdentityContext(ctx);\n}\n\nfunction legacyIdentityContext(\n ctx: CallerContext,\n): CallerContext & UserContext {\n if (immutableCallers.has(ctx)) return ctx as CallerContext & UserContext;\n const caller = snapshotCallerContext(ctx);\n const { principal } = caller;\n const snapshot = Object.freeze({\n ...caller,\n get userId() {\n warnContextDeprecation(\n \"UserContext.userId\",\n \"CallerContext.principal.userId\",\n );\n return principal.userId;\n },\n get userName() {\n warnContextDeprecation(\n \"UserContext.userName\",\n \"CallerContext.principal.userName\",\n );\n return principal.userName;\n },\n get userEmail() {\n warnContextDeprecation(\n \"UserContext.userEmail\",\n \"CallerContext.principal.userEmail\",\n );\n return principal.userEmail;\n },\n get isUserContext(): true {\n warnContextDeprecation(\n \"UserContext.isUserContext\",\n \"CallerContext.principal.type\",\n );\n return true;\n },\n });\n immutableCallers.add(snapshot);\n return snapshot;\n}\n\n/** Expose the old resource field only through the deprecated context APIs. */\nexport function legacyUserContext(\n ctx: CallerContext,\n resolveWarehouseId: () => Promise<string> | undefined,\n): CallerContext & UserContext {\n return Object.freeze(\n Object.defineProperties(\n {\n get warehouseId() {\n warnContextDeprecation(\n \"UserContext.warehouseId\",\n \"getWarehouseId() from @databricks/appkit\",\n );\n return resolveWarehouseId();\n },\n },\n Object.getOwnPropertyDescriptors(legacyIdentityContext(ctx)),\n ),\n ) as CallerContext & UserContext;\n}\n\n/** Normalize legacy inputs before opening a caller scope. */\nexport function toCallerContext(\n ctx: CallerContext | UserContext,\n): CallerContext {\n if (\"principal\" in ctx) return ctx;\n return {\n client: ctx.client,\n principal: {\n type: \"user\",\n userId: ctx.userId,\n userName: ctx.userName,\n userEmail: ctx.userEmail,\n },\n tokenFingerprint: ctx.tokenFingerprint,\n workspaceId: ctx.workspaceId,\n };\n}\n\n/**\n * @deprecated Use isCallerContext. Active caller contexts retain the legacy\n * identity accessors for callers narrowed by this guard.\n */\nexport function isUserContext(\n ctx: ExecutionContext | UserContext,\n): ctx is UserContext & Partial<CallerContext> {\n warnContextDeprecation(\"isUserContext\", \"isCallerContext\");\n return \"principal\" in ctx\n ? isCallerContext(ctx)\n : \"isUserContext\" in ctx && ctx.isUserContext === true;\n}\n"],"mappings":";;;;AAWA,MAAM,mCAAmB,IAAI,SAAiB;AAoC9C,SAAS,sBACP,KAC6B;AAC7B,KAAI,iBAAiB,IAAI,IAAI,CAAE,QAAO;CACtC,MAAM,SAAS,sBAAsB,IAAI;CACzC,MAAM,EAAE,cAAc;CACtB,MAAM,WAAW,OAAO,OAAO;EAC7B,GAAG;EACH,IAAI,SAAS;AACX,0BACE,sBACA,iCACD;AACD,UAAO,UAAU;;EAEnB,IAAI,WAAW;AACb,0BACE,wBACA,mCACD;AACD,UAAO,UAAU;;EAEnB,IAAI,YAAY;AACd,0BACE,yBACA,oCACD;AACD,UAAO,UAAU;;EAEnB,IAAI,gBAAsB;AACxB,0BACE,6BACA,+BACD;AACD,UAAO;;EAEV,CAAC;AACF,kBAAiB,IAAI,SAAS;AAC9B,QAAO;;;AAIT,SAAgB,kBACd,KACA,oBAC6B;AAC7B,QAAO,OAAO,OACZ,OAAO,iBACL,EACE,IAAI,cAAc;AAChB,yBACE,2BACA,2CACD;AACD,SAAO,oBAAoB;IAE9B,EACD,OAAO,0BAA0B,sBAAsB,IAAI,CAAC,CAC7D,CACF;;;AAIH,SAAgB,gBACd,KACe;AACf,KAAI,eAAe,IAAK,QAAO;AAC/B,QAAO;EACL,QAAQ,IAAI;EACZ,WAAW;GACT,MAAM;GACN,QAAQ,IAAI;GACZ,UAAU,IAAI;GACd,WAAW,IAAI;GAChB;EACD,kBAAkB,IAAI;EACtB,aAAa,IAAI;EAClB;;;;;;AAOH,SAAgB,cACd,KAC6C;AAC7C,wBAAuB,iBAAiB,kBAAkB;AAC1D,QAAO,eAAe,MAClB,gBAAgB,IAAI,GACpB,mBAAmB,OAAO,IAAI,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-agents.d.ts","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"load-agents.d.ts","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"mappings":";;;;;UAuBU,eAAA;EACR,OAAA,GAAU,IAAA,GAAO,cAAA,KAAmB,MAAA;AAAA;AAAA,UAGrB,WAAA;EAJQ;EAMvB,YAAA,GAAe,YAAA,GAAe,OAAA,CAAQ,YAAA;EALI;EAO1C,cAAA,GAAiB,MAAA,SAAe,SAAA;EAPf;;;;;AAGnB;EAWE,OAAA,GAAU,GAAA,SAAY,eAAA;;;;;;;;EAQtB,UAAA,GAAa,MAAA,SAAe,eAAA;AAAA;AAAA,UAGb,UAAA;EAHI;EAKnB,IAAA,EAAM,MAAA,SAAe,eAAA;EAtBrB;EAwBA,YAAA;AAAA;;;;;;iBAwEc,uBAAA,CAAwB,QAAA;;;;;;;;;iBAiClB,iBAAA,CACpB,QAAA,UACA,GAAA,EAAK,WAAA,GACJ,OAAA,CAAQ,eAAA;;;;;;;;;;;;;;;;;;;iBAgCW,iBAAA,CACpB,GAAA,UACA,GAAA,EAAK,WAAA,GACJ,OAAA,CAAQ,UAAA"}
|
|
@@ -32,7 +32,8 @@ const ALLOWED_KEYS = new Set([
|
|
|
32
32
|
"generationParams",
|
|
33
33
|
"default",
|
|
34
34
|
"baseSystemPrompt",
|
|
35
|
-
"ephemeral"
|
|
35
|
+
"ephemeral",
|
|
36
|
+
"auth"
|
|
36
37
|
]);
|
|
37
38
|
/**
|
|
38
39
|
* Loads a single markdown agent file and resolves its frontmatter against
|
|
@@ -254,6 +255,7 @@ function buildDefinition(name, raw, filePath, ctx) {
|
|
|
254
255
|
const fm = data ?? {};
|
|
255
256
|
const tools = resolveFrontmatterTools(name, fm, filePath, ctx);
|
|
256
257
|
const model = fm.model ?? fm.endpoint ?? ctx.defaultModel;
|
|
258
|
+
if (fm.auth !== void 0 && fm.auth !== "on-behalf-of-user") throw new Error(`Agent '${name}' (${filePath}) has invalid 'auth:' frontmatter: expected "on-behalf-of-user", got ${JSON.stringify(fm.auth)}.`);
|
|
257
259
|
let baseSystemPrompt;
|
|
258
260
|
if (fm.baseSystemPrompt === false) baseSystemPrompt = false;
|
|
259
261
|
else if (typeof fm.baseSystemPrompt === "string") baseSystemPrompt = fm.baseSystemPrompt;
|
|
@@ -267,7 +269,8 @@ function buildDefinition(name, raw, filePath, ctx) {
|
|
|
267
269
|
maxTokens: typeof fm.maxTokens === "number" ? fm.maxTokens : void 0,
|
|
268
270
|
generationParams: parseGenerationParams(fm.generationParams, filePath),
|
|
269
271
|
baseSystemPrompt,
|
|
270
|
-
ephemeral: typeof fm.ephemeral === "boolean" ? fm.ephemeral : void 0
|
|
272
|
+
ephemeral: typeof fm.ephemeral === "boolean" ? fm.ephemeral : void 0,
|
|
273
|
+
auth: fm.auth
|
|
271
274
|
};
|
|
272
275
|
}
|
|
273
276
|
function resolveFrontmatterTools(agentName, fm, filePath, ctx) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-agents.js","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"sourcesContent":["import type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport yaml from \"js-yaml\";\nimport type { AgentAdapter } from \"shared\";\n\nimport type { GenerationParams } from \"../../agents/databricks\";\nimport type {\n AgentDefinition,\n AgentTool,\n BaseSystemPromptOption,\n ToolkitEntry,\n ToolkitOptions,\n} from \"../../core/agent/types\";\nimport { isToolkitEntry } from \"../../core/agent/types\";\nimport { createLogger } from \"../../logging/logger\";\nimport { agentDirNames } from \"./agent-dirs\";\nimport { splitFrontmatter } from \"./frontmatter\";\n\nconst logger = createLogger(\"agents:loader\");\n\ninterface ToolkitProvider {\n toolkit: (opts?: ToolkitOptions) => Record<string, unknown>;\n}\n\nexport interface LoadContext {\n /** Default model when frontmatter has no `endpoint` and the def has no `model`. */\n defaultModel?: AgentAdapter | Promise<AgentAdapter> | string;\n /** Ambient tool library referenced by frontmatter `tools: [key1, key2]`. */\n availableTools?: Record<string, AgentTool>;\n /**\n * Registered plugin toolkits referenced by `plugin:NAME` entries in the\n * unified `tools:` frontmatter list. Keyed by plugin name; each value\n * exposes the same `toolkit(opts?)` surface as the `plugins` argument to\n * `tools(plugins) => Record<...>` in the code form.\n */\n plugins?: Map<string, ToolkitProvider>;\n /**\n * Code-defined agents contributed by `agents({ agents: { ... } })`. The\n * directory loader resolves `agents:` frontmatter references against\n * these alongside sibling markdown files, so a markdown parent can\n * delegate to a code-defined child. Code-defined names win on collision\n * with markdown names, matching the plugin's top-level merge precedence.\n */\n codeAgents?: Record<string, AgentDefinition>;\n}\n\nexport interface LoadResult {\n /** Agent definitions keyed by agent id (directory name under `dir`). */\n defs: Record<string, AgentDefinition>;\n /** First agent with `default: true` frontmatter (sorted id order), or `null`. */\n defaultAgent: string | null;\n}\n\ninterface Frontmatter {\n endpoint?: string;\n model?: string;\n /**\n * Unified tool list. Each entry is one of:\n *\n * - **`plugin:<name>`** (string) — pull every tool from the named plugin.\n * - **`plugin:<name>: [tool1, tool2]`** — pull only the listed tools\n * (shorthand for `{ only: [...] }`).\n * - **`plugin:<name>: { ...ToolkitOptions }`** — pass full\n * `prefix` / `only` / `except` / `rename` options.\n * - **`<key>`** (string, no `plugin:` prefix) — ambient tool name\n * resolved against the `agents({ tools: { ... } })` config.\n *\n * Mirrors the TS function form `tools(plugins) { ... }` where plugin\n * tools and inline tools live in the same record.\n */\n tools?: FrontmatterToolEntry[];\n /**\n * Other agent ids to expose as sub-agents. Each becomes an `agent-<id>`\n * tool at runtime. Resolution happens at directory-load time in\n * {@link loadAgentsFromDir}; the single-file {@link loadAgentFromFile} path\n * rejects non-empty values since there are no siblings to resolve against.\n */\n agents?: string[];\n /**\n * Names of global skills (from the shared `skills/` pool or a catalog\n * volume) to make visible to this agent. Per-agent skills under\n * `<id>/skills/` are always visible and need not be listed here. Ignored\n * when the plugin's `autoInheritSkills` makes every global skill visible.\n */\n skills?: string[];\n maxSteps?: number;\n maxTokens?: number;\n /**\n * Optional OpenAI-compatible generation params forwarded to the serving\n * request body (`temperature`, `top_p`, `stop`, `frequency_penalty`,\n * `presence_penalty`). Parsed defensively in {@link buildDefinition}.\n */\n generationParams?: Record<string, unknown>;\n default?: boolean;\n baseSystemPrompt?: false | string;\n ephemeral?: boolean;\n}\n\n/**\n * Each item in {@link Frontmatter.tools}. Strings are either ambient tool\n * names (no prefix) or bare plugin references (`plugin:NAME`). Objects are\n * single-key mappings whose key is `plugin:NAME` and whose value is either\n * an array of local tool names (sugar for `{ only: [...] }`) or a full\n * `ToolkitOptions` record.\n *\n * Named `FrontmatterToolEntry` to avoid colliding with the exported\n * `ToolEntry` from `tools/define-tool.ts` — that is the plugin-author API\n * surface (`defineTool({ ... }) : ToolEntry`); this is the frontmatter\n * parse type. They are unrelated and live in different layers.\n */\ntype FrontmatterToolEntry =\n | string\n | { [key: string]: ToolkitOptions | string[] };\n\nconst PLUGIN_PREFIX = \"plugin:\";\n\n/**\n * Derives the logical agent id from a markdown path. When the file is named\n * `agent.md`, the id is the parent directory name (folder-based layout);\n * otherwise the id is the file stem (e.g. legacy single-file paths).\n */\nexport function agentIdFromMarkdownPath(filePath: string): string {\n const normalized = path.normalize(filePath);\n const base = path.basename(normalized);\n const parent = path.basename(path.dirname(normalized));\n if (base === \"agent.md\" && parent && parent !== \".\" && parent !== \"..\") {\n return parent;\n }\n return path.basename(normalized, \".md\");\n}\n\nconst ALLOWED_KEYS = new Set([\n \"endpoint\",\n \"model\",\n \"tools\",\n \"agents\",\n \"skills\",\n \"maxSteps\",\n \"maxTokens\",\n \"generationParams\",\n \"default\",\n \"baseSystemPrompt\",\n \"ephemeral\",\n]);\n\n/**\n * Loads a single markdown agent file and resolves its frontmatter against\n * registered plugin toolkits + ambient tool library.\n *\n * Rejects non-empty `agents:` frontmatter because single-file loads have\n * no siblings to resolve sub-agent references against — callers must use\n * {@link loadAgentsFromDir} when markdown agents delegate to one another.\n */\nexport async function loadAgentFromFile(\n filePath: string,\n ctx: LoadContext,\n): Promise<AgentDefinition> {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const name = agentIdFromMarkdownPath(filePath);\n const { data } = parseFrontmatter(raw, filePath);\n if (Array.isArray(data?.agents) && data.agents.length > 0) {\n throw new Error(\n `Agent '${name}' (${filePath}) declares 'agents:' in frontmatter, ` +\n `which requires loadAgentsFromDir to resolve sibling references. ` +\n `Use loadAgentsFromDir, or wire sub-agents in code via createAgent({ agents: { ... } }).`,\n );\n }\n return buildDefinition(name, raw, filePath, ctx);\n}\n\n/**\n * Scans a directory for one subdirectory per agent, each containing\n * `agent.md` (frontmatter + body). Produces an `AgentDefinition` record keyed\n * by agent id (folder name). Throws on frontmatter errors or unresolved\n * references. Returns an empty map if the directory does not exist.\n *\n * Legacy top-level `*.md` files are rejected with an error — migrate each to\n * `<id>/agent.md` under a sibling folder named for the agent id.\n *\n * Runs in two passes so sub-agent references in frontmatter (`agents: [...]`)\n * can be resolved regardless of directory iteration order:\n *\n * 1. Build every agent's definition from its own `agent.md`.\n * 2. Walk `agents:` references and wire `def.agents = { child: childDef }`\n * by looking them up in the complete map. Dangling names and\n * self-references fail loudly; mutual delegation is allowed and bounded\n * at runtime by `limits.maxSubAgentDepth`.\n */\nexport async function loadAgentsFromDir(\n dir: string,\n ctx: LoadContext,\n): Promise<LoadResult> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { defs: {}, defaultAgent: null };\n }\n throw err;\n }\n const orphanMd = entries\n .filter((e) => e.isFile() && e.name.endsWith(\".md\"))\n .map((e) => e.name)\n .sort();\n\n if (orphanMd.length > 0) {\n const hint = orphanMd\n .map((f) => `${path.basename(f, \".md\")}/agent.md`)\n .join(\", \");\n throw new Error(\n `Agents directory contains unsupported top-level markdown file(s): ${orphanMd.join(\", \")}. ` +\n `Use one folder per agent with a fixed entry file, e.g. ${hint}.`,\n );\n }\n\n // A symlink to a file is filtered out below when reading agent.md (ENOTDIR).\n const agentIds = agentDirNames(entries);\n\n const defs: Record<string, AgentDefinition> = {};\n const subAgentRefs: Record<string, string[]> = {};\n let defaultAgent: string | null = null;\n\n // Pass 1: build every agent's definition; collect sub-agent refs.\n for (const id of agentIds) {\n const agentPath = path.join(dir, id, \"agent.md\");\n let raw: string;\n try {\n raw = await fs.readFile(agentPath, \"utf-8\");\n } catch (err) {\n // No agent.md → a code-agent folder (agent.ts) or an asset dir (skills/);\n // ENOTDIR → the entry is a symlink to a file, not an agent folder.\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") continue;\n throw err;\n }\n defs[id] = buildDefinition(id, raw, agentPath, ctx);\n const { data } = parseFrontmatter(raw, agentPath);\n if (data?.agents !== undefined) {\n subAgentRefs[id] = normalizeAgentsFrontmatter(data.agents, id, agentPath);\n }\n if (data?.default === true && !defaultAgent) {\n defaultAgent = id;\n }\n }\n\n // Pass 2: resolve sub-agent references against the complete defs map.\n // Code-defined agents (ctx.codeAgents) take precedence over markdown ones\n // with the same name, matching the plugin's top-level merge behaviour.\n for (const [name, refs] of Object.entries(subAgentRefs)) {\n if (refs.length === 0) continue;\n const children: Record<string, AgentDefinition> = {};\n const missing: string[] = [];\n for (const ref of refs) {\n if (ref === name) {\n throw new Error(\n `Agent '${name}' (${path.join(dir, name, \"agent.md\")}) cannot reference itself in 'agents:'.`,\n );\n }\n const sibling = ctx.codeAgents?.[ref] ?? defs[ref];\n if (!sibling) {\n missing.push(ref);\n continue;\n }\n children[ref] = sibling;\n }\n if (missing.length > 0) {\n const available =\n [...Object.keys(ctx.codeAgents ?? {}), ...Object.keys(defs)]\n .sort()\n .join(\", \") || \"<none>\";\n throw new Error(\n `Agent '${name}' references sub-agent(s) '${missing.join(\", \")}' in 'agents:', ` +\n `but no markdown or code agent(s) with those names exist. ` +\n `Available: ${available}.`,\n );\n }\n defs[name].agents = children;\n }\n\n return { defs, defaultAgent };\n}\n\n/**\n * Validates that `agents:` frontmatter is an array of non-empty strings and\n * returns it with duplicates removed. Throws with a clear per-file message\n * on malformed input rather than silently ignoring.\n */\nfunction normalizeAgentsFrontmatter(\n value: unknown,\n agentName: string,\n filePath: string,\n): string[] {\n if (!Array.isArray(value)) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'agents:' frontmatter: ` +\n `expected an array of sibling agent ids, got ${typeof value}.`,\n );\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const item of value) {\n if (typeof item !== \"string\" || item.trim() === \"\") {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'agents:' entry: ` +\n `expected non-empty string, got ${JSON.stringify(item)}.`,\n );\n }\n if (seen.has(item)) continue;\n seen.add(item);\n out.push(item);\n }\n return out;\n}\n\n/** Exposed for tests. Parses `--- yaml ---\\nbody` and validates frontmatter keys. */\nexport function parseFrontmatter(\n raw: string,\n sourcePath?: string,\n): { data: Frontmatter | null; content: string } {\n const { yaml: yamlBlock, body } = splitFrontmatter(raw);\n if (yamlBlock === null) {\n return { data: null, content: body };\n }\n let parsed: unknown;\n try {\n parsed = yaml.load(yamlBlock);\n } catch (err) {\n const src = sourcePath ? ` (${sourcePath})` : \"\";\n throw new Error(\n `Invalid YAML frontmatter${src}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (parsed === null || parsed === undefined) {\n return { data: {}, content: body };\n }\n if (typeof parsed !== \"object\" || Array.isArray(parsed)) {\n const src = sourcePath ? ` (${sourcePath})` : \"\";\n throw new Error(`Frontmatter must be a YAML object${src}`);\n }\n const data = parsed as Record<string, unknown>;\n for (const key of Object.keys(data)) {\n if (!ALLOWED_KEYS.has(key)) {\n logger.warn(\n \"Ignoring unknown frontmatter key '%s' in %s\",\n key,\n sourcePath ?? \"<inline>\",\n );\n }\n }\n return { data: data as Frontmatter, content: body };\n}\n\nconst isNumber = (v: unknown): v is number => typeof v === \"number\";\n\n/**\n * Per-key validators for {@link GenerationParams} frontmatter. Keyed by wire\n * name and typed as `Record<keyof GenerationParams, ...>`, so a new param on\n * the interface is a compile error until it gets an entry here — parsing,\n * unknown-key detection, and warnings all derive from this one table.\n */\nconst GENERATION_PARAM_SPECS: Record<\n keyof GenerationParams,\n { label: string; valid: (v: unknown) => boolean }\n> = {\n temperature: { label: \"number\", valid: isNumber },\n top_p: { label: \"number\", valid: isNumber },\n frequency_penalty: { label: \"number\", valid: isNumber },\n presence_penalty: { label: \"number\", valid: isNumber },\n stop: {\n label: \"string or string[]\",\n valid: (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((s) => typeof s === \"string\")),\n },\n};\n\n/**\n * Defensively maps a frontmatter `generationParams` map to {@link GenerationParams}.\n * Picks only known keys with the expected wire types. A key present with the\n * wrong type (e.g. `temperature: \"0.5\"`) or an unknown key (e.g. `top-p`) is\n * dropped and logged at warn level, so a silently-ignored param is visible\n * rather than mistaken for \"applied\". Returns `undefined` when no valid key is\n * present.\n */\nfunction parseGenerationParams(\n value: unknown,\n sourcePath?: string,\n): GenerationParams | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const raw = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const where = sourcePath ?? \"<inline>\";\n\n for (const [key, v] of Object.entries(raw)) {\n const spec = GENERATION_PARAM_SPECS[key as keyof GenerationParams];\n if (!spec) {\n logger.warn(\n \"Ignoring unknown generationParams key '%s' in %s\",\n key,\n where,\n );\n } else if (spec.valid(v)) {\n out[key] = v;\n } else {\n logger.warn(\n \"Ignoring generationParams.%s in %s: expected %s, got %s\",\n key,\n where,\n spec.label,\n typeof v,\n );\n }\n }\n\n return Object.keys(out).length > 0 ? (out as GenerationParams) : undefined;\n}\n\n/**\n * Defensively parses a frontmatter `skills:` list into deduped skill names.\n * Non-array values and non-string/empty entries are dropped with a warning,\n * so a malformed list is visible rather than silently applied. Returns\n * `undefined` when nothing valid is present.\n */\nfunction parseSkillsFrontmatter(\n value: unknown,\n sourcePath?: string,\n): string[] | undefined {\n if (value === undefined) return undefined;\n const where = sourcePath ?? \"<inline>\";\n if (!Array.isArray(value)) {\n logger.warn(\n \"Ignoring 'skills' in %s: expected an array of skill names\",\n where,\n );\n return undefined;\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const item of value) {\n if (typeof item !== \"string\" || item.trim() === \"\") {\n logger.warn(\n \"Ignoring invalid 'skills' entry in %s: %s\",\n where,\n JSON.stringify(item),\n );\n continue;\n }\n const name = item.trim();\n if (seen.has(name)) continue;\n seen.add(name);\n out.push(name);\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction buildDefinition(\n name: string,\n raw: string,\n filePath: string,\n ctx: LoadContext,\n): AgentDefinition {\n const { data, content } = parseFrontmatter(raw, filePath);\n const fm: Frontmatter = data ?? {};\n\n const tools = resolveFrontmatterTools(name, fm, filePath, ctx);\n const model = fm.model ?? fm.endpoint ?? ctx.defaultModel;\n\n let baseSystemPrompt: BaseSystemPromptOption | undefined;\n if (fm.baseSystemPrompt === false) baseSystemPrompt = false;\n else if (typeof fm.baseSystemPrompt === \"string\")\n baseSystemPrompt = fm.baseSystemPrompt;\n\n return {\n name,\n instructions: content,\n model,\n tools: Object.keys(tools).length > 0 ? tools : undefined,\n skills: parseSkillsFrontmatter(fm.skills, filePath),\n maxSteps: typeof fm.maxSteps === \"number\" ? fm.maxSteps : undefined,\n maxTokens: typeof fm.maxTokens === \"number\" ? fm.maxTokens : undefined,\n generationParams: parseGenerationParams(fm.generationParams, filePath),\n baseSystemPrompt,\n ephemeral: typeof fm.ephemeral === \"boolean\" ? fm.ephemeral : undefined,\n };\n}\n\nfunction resolveFrontmatterTools(\n agentName: string,\n fm: Frontmatter,\n filePath: string,\n ctx: LoadContext,\n): Record<string, AgentTool> {\n const out: Record<string, AgentTool> = {};\n const pluginIdx = ctx.plugins ?? new Map<string, ToolkitProvider>();\n\n for (const entry of fm.tools ?? []) {\n const parsed = parseToolEntry(entry, filePath, agentName);\n if (parsed.kind === \"plugin\") {\n const provider = pluginIdx.get(parsed.pluginName);\n if (!provider) {\n const available =\n pluginIdx.size > 0\n ? Array.from(pluginIdx.keys()).join(\", \")\n : \"<none>\";\n throw new Error(\n `Agent '${agentName}' (${filePath}) references 'plugin:${parsed.pluginName}', but plugin '${parsed.pluginName}' is not registered. Available: ${available}`,\n );\n }\n const entries = provider.toolkit(parsed.opts) as Record<string, unknown>;\n for (const [key, value] of Object.entries(entries)) {\n if (!isToolkitEntry(value)) {\n throw new Error(\n `Plugin '${parsed.pluginName}'.toolkit() returned a value at key '${key}' that is not a ToolkitEntry`,\n );\n }\n out[key] = value as ToolkitEntry;\n }\n } else {\n const tool = ctx.availableTools?.[parsed.toolName];\n if (!tool) {\n const available = ctx.availableTools\n ? Object.keys(ctx.availableTools).join(\", \")\n : \"<none>\";\n throw new Error(\n `Agent '${agentName}' (${filePath}) references ambient tool '${parsed.toolName}', which is not in the agents() plugin's tools field. Available: ${available}. ` +\n \"If you meant to reference a plugin, use the 'plugin:NAME' prefix.\",\n );\n }\n out[parsed.toolName] = tool;\n }\n }\n\n return out;\n}\n\ntype ParsedToolEntry =\n | { kind: \"plugin\"; pluginName: string; opts: ToolkitOptions | undefined }\n | { kind: \"ambient\"; toolName: string };\n\n/**\n * Classify one item in the `tools:` frontmatter list into either a plugin\n * reference (with optional ToolkitOptions) or an ambient tool lookup.\n *\n * Strings starting with `plugin:` are bare plugin references. Strings\n * without the prefix are ambient tool names. Object entries are\n * single-key mappings keyed by `plugin:NAME`; the value is either an\n * array (sugar for `{ only: [...] }`) or a full `ToolkitOptions` record.\n */\nfunction parseToolEntry(\n entry: FrontmatterToolEntry,\n filePath: string,\n agentName: string,\n): ParsedToolEntry {\n if (typeof entry === \"string\") {\n if (entry.startsWith(PLUGIN_PREFIX)) {\n const pluginName = entry.slice(PLUGIN_PREFIX.length);\n if (pluginName.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n return { kind: \"plugin\", pluginName, opts: undefined };\n }\n if (entry.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty string in 'tools:'.`,\n );\n }\n return { kind: \"ambient\", toolName: entry };\n }\n if (typeof entry !== \"object\" || entry === null) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'tools:' entry: ${JSON.stringify(entry)}`,\n );\n }\n const keys = Object.keys(entry);\n if (keys.length !== 1) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'tools:' object entry must have exactly one key, got: ${keys.join(\", \")}`,\n );\n }\n const key = keys[0];\n // Bare `- plugin:` (no name after the colon) parses as a mapping with the\n // key `\"plugin\"`. Catch that as a friendly error rather than dumping it\n // through the generic \"expected key 'plugin:NAME'\" branch.\n if (key === \"plugin\") {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n if (!key.startsWith(PLUGIN_PREFIX)) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'tools:' object entries are reserved for plugin references; expected key 'plugin:NAME', got '${key}'. ` +\n \"Use a bare string for ambient tools (e.g. `- get_weather`).\",\n );\n }\n const pluginName = key.slice(PLUGIN_PREFIX.length);\n if (pluginName.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n const value = entry[key];\n if (Array.isArray(value)) {\n return { kind: \"plugin\", pluginName, opts: { only: value } };\n }\n if (typeof value === \"object\" && value !== null) {\n return {\n kind: \"plugin\",\n pluginName,\n opts: value as ToolkitOptions,\n };\n }\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'plugin:${pluginName}' options must be an array of tool names or a ToolkitOptions object.`,\n );\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,SAAS,aAAa,gBAAgB;AAgG5C,MAAM,gBAAgB;;;;;;AAOtB,SAAgB,wBAAwB,UAA0B;CAChE,MAAM,aAAa,KAAK,UAAU,SAAS;CAC3C,MAAM,OAAO,KAAK,SAAS,WAAW;CACtC,MAAM,SAAS,KAAK,SAAS,KAAK,QAAQ,WAAW,CAAC;AACtD,KAAI,SAAS,cAAc,UAAU,WAAW,OAAO,WAAW,KAChE,QAAO;AAET,QAAO,KAAK,SAAS,YAAY,MAAM;;AAGzC,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;AAUF,eAAsB,kBACpB,UACA,KAC0B;CAC1B,MAAM,MAAM,MAAM,GAAG,SAAS,UAAU,QAAQ;CAChD,MAAM,OAAO,wBAAwB,SAAS;CAC9C,MAAM,EAAE,SAAS,iBAAiB,KA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M;EACN;EACA,MAAM;EACP;AAEH,OAAM,IAAI,MACR,UAAU,UAAU,KAAK,SAAS,YAAY,WAAW,sEAC1D"}
|
|
1
|
+
{"version":3,"file":"load-agents.js","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"sourcesContent":["import type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport yaml from \"js-yaml\";\nimport type { AgentAdapter } from \"shared\";\n\nimport type { GenerationParams } from \"../../agents/databricks\";\nimport type {\n AgentAuth,\n AgentDefinition,\n AgentTool,\n BaseSystemPromptOption,\n ToolkitEntry,\n ToolkitOptions,\n} from \"../../core/agent/types\";\nimport { isToolkitEntry } from \"../../core/agent/types\";\nimport { createLogger } from \"../../logging/logger\";\nimport { agentDirNames } from \"./agent-dirs\";\nimport { splitFrontmatter } from \"./frontmatter\";\n\nconst logger = createLogger(\"agents:loader\");\n\ninterface ToolkitProvider {\n toolkit: (opts?: ToolkitOptions) => Record<string, unknown>;\n}\n\nexport interface LoadContext {\n /** Default model when frontmatter has no `endpoint` and the def has no `model`. */\n defaultModel?: AgentAdapter | Promise<AgentAdapter> | string;\n /** Ambient tool library referenced by frontmatter `tools: [key1, key2]`. */\n availableTools?: Record<string, AgentTool>;\n /**\n * Registered plugin toolkits referenced by `plugin:NAME` entries in the\n * unified `tools:` frontmatter list. Keyed by plugin name; each value\n * exposes the same `toolkit(opts?)` surface as the `plugins` argument to\n * `tools(plugins) => Record<...>` in the code form.\n */\n plugins?: Map<string, ToolkitProvider>;\n /**\n * Code-defined agents contributed by `agents({ agents: { ... } })`. The\n * directory loader resolves `agents:` frontmatter references against\n * these alongside sibling markdown files, so a markdown parent can\n * delegate to a code-defined child. Code-defined names win on collision\n * with markdown names, matching the plugin's top-level merge precedence.\n */\n codeAgents?: Record<string, AgentDefinition>;\n}\n\nexport interface LoadResult {\n /** Agent definitions keyed by agent id (directory name under `dir`). */\n defs: Record<string, AgentDefinition>;\n /** First agent with `default: true` frontmatter (sorted id order), or `null`. */\n defaultAgent: string | null;\n}\n\ninterface Frontmatter {\n endpoint?: string;\n model?: string;\n /**\n * Unified tool list. Each entry is one of:\n *\n * - **`plugin:<name>`** (string) — pull every tool from the named plugin.\n * - **`plugin:<name>: [tool1, tool2]`** — pull only the listed tools\n * (shorthand for `{ only: [...] }`).\n * - **`plugin:<name>: { ...ToolkitOptions }`** — pass full\n * `prefix` / `only` / `except` / `rename` options.\n * - **`<key>`** (string, no `plugin:` prefix) — ambient tool name\n * resolved against the `agents({ tools: { ... } })` config.\n *\n * Mirrors the TS function form `tools(plugins) { ... }` where plugin\n * tools and inline tools live in the same record.\n */\n tools?: FrontmatterToolEntry[];\n /**\n * Other agent ids to expose as sub-agents. Each becomes an `agent-<id>`\n * tool at runtime. Resolution happens at directory-load time in\n * {@link loadAgentsFromDir}; the single-file {@link loadAgentFromFile} path\n * rejects non-empty values since there are no siblings to resolve against.\n */\n agents?: string[];\n /**\n * Names of global skills (from the shared `skills/` pool or a catalog\n * volume) to make visible to this agent. Per-agent skills under\n * `<id>/skills/` are always visible and need not be listed here. Ignored\n * when the plugin's `autoInheritSkills` makes every global skill visible.\n */\n skills?: string[];\n maxSteps?: number;\n maxTokens?: number;\n /**\n * Optional OpenAI-compatible generation params forwarded to the serving\n * request body (`temperature`, `top_p`, `stop`, `frequency_penalty`,\n * `presence_penalty`). Parsed defensively in {@link buildDefinition}.\n */\n generationParams?: Record<string, unknown>;\n default?: boolean;\n baseSystemPrompt?: false | string;\n ephemeral?: boolean;\n auth?: AgentAuth;\n}\n\n/**\n * Each item in {@link Frontmatter.tools}. Strings are either ambient tool\n * names (no prefix) or bare plugin references (`plugin:NAME`). Objects are\n * single-key mappings whose key is `plugin:NAME` and whose value is either\n * an array of local tool names (sugar for `{ only: [...] }`) or a full\n * `ToolkitOptions` record.\n *\n * Named `FrontmatterToolEntry` to avoid colliding with the exported\n * `ToolEntry` from `tools/define-tool.ts` — that is the plugin-author API\n * surface (`defineTool({ ... }) : ToolEntry`); this is the frontmatter\n * parse type. They are unrelated and live in different layers.\n */\ntype FrontmatterToolEntry =\n | string\n | { [key: string]: ToolkitOptions | string[] };\n\nconst PLUGIN_PREFIX = \"plugin:\";\n\n/**\n * Derives the logical agent id from a markdown path. When the file is named\n * `agent.md`, the id is the parent directory name (folder-based layout);\n * otherwise the id is the file stem (e.g. legacy single-file paths).\n */\nexport function agentIdFromMarkdownPath(filePath: string): string {\n const normalized = path.normalize(filePath);\n const base = path.basename(normalized);\n const parent = path.basename(path.dirname(normalized));\n if (base === \"agent.md\" && parent && parent !== \".\" && parent !== \"..\") {\n return parent;\n }\n return path.basename(normalized, \".md\");\n}\n\nconst ALLOWED_KEYS = new Set([\n \"endpoint\",\n \"model\",\n \"tools\",\n \"agents\",\n \"skills\",\n \"maxSteps\",\n \"maxTokens\",\n \"generationParams\",\n \"default\",\n \"baseSystemPrompt\",\n \"ephemeral\",\n \"auth\",\n]);\n\n/**\n * Loads a single markdown agent file and resolves its frontmatter against\n * registered plugin toolkits + ambient tool library.\n *\n * Rejects non-empty `agents:` frontmatter because single-file loads have\n * no siblings to resolve sub-agent references against — callers must use\n * {@link loadAgentsFromDir} when markdown agents delegate to one another.\n */\nexport async function loadAgentFromFile(\n filePath: string,\n ctx: LoadContext,\n): Promise<AgentDefinition> {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const name = agentIdFromMarkdownPath(filePath);\n const { data } = parseFrontmatter(raw, filePath);\n if (Array.isArray(data?.agents) && data.agents.length > 0) {\n throw new Error(\n `Agent '${name}' (${filePath}) declares 'agents:' in frontmatter, ` +\n `which requires loadAgentsFromDir to resolve sibling references. ` +\n `Use loadAgentsFromDir, or wire sub-agents in code via createAgent({ agents: { ... } }).`,\n );\n }\n return buildDefinition(name, raw, filePath, ctx);\n}\n\n/**\n * Scans a directory for one subdirectory per agent, each containing\n * `agent.md` (frontmatter + body). Produces an `AgentDefinition` record keyed\n * by agent id (folder name). Throws on frontmatter errors or unresolved\n * references. Returns an empty map if the directory does not exist.\n *\n * Legacy top-level `*.md` files are rejected with an error — migrate each to\n * `<id>/agent.md` under a sibling folder named for the agent id.\n *\n * Runs in two passes so sub-agent references in frontmatter (`agents: [...]`)\n * can be resolved regardless of directory iteration order:\n *\n * 1. Build every agent's definition from its own `agent.md`.\n * 2. Walk `agents:` references and wire `def.agents = { child: childDef }`\n * by looking them up in the complete map. Dangling names and\n * self-references fail loudly; mutual delegation is allowed and bounded\n * at runtime by `limits.maxSubAgentDepth`.\n */\nexport async function loadAgentsFromDir(\n dir: string,\n ctx: LoadContext,\n): Promise<LoadResult> {\n let entries: Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { defs: {}, defaultAgent: null };\n }\n throw err;\n }\n const orphanMd = entries\n .filter((e) => e.isFile() && e.name.endsWith(\".md\"))\n .map((e) => e.name)\n .sort();\n\n if (orphanMd.length > 0) {\n const hint = orphanMd\n .map((f) => `${path.basename(f, \".md\")}/agent.md`)\n .join(\", \");\n throw new Error(\n `Agents directory contains unsupported top-level markdown file(s): ${orphanMd.join(\", \")}. ` +\n `Use one folder per agent with a fixed entry file, e.g. ${hint}.`,\n );\n }\n\n // A symlink to a file is filtered out below when reading agent.md (ENOTDIR).\n const agentIds = agentDirNames(entries);\n\n const defs: Record<string, AgentDefinition> = {};\n const subAgentRefs: Record<string, string[]> = {};\n let defaultAgent: string | null = null;\n\n // Pass 1: build every agent's definition; collect sub-agent refs.\n for (const id of agentIds) {\n const agentPath = path.join(dir, id, \"agent.md\");\n let raw: string;\n try {\n raw = await fs.readFile(agentPath, \"utf-8\");\n } catch (err) {\n // No agent.md → a code-agent folder (agent.ts) or an asset dir (skills/);\n // ENOTDIR → the entry is a symlink to a file, not an agent folder.\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") continue;\n throw err;\n }\n defs[id] = buildDefinition(id, raw, agentPath, ctx);\n const { data } = parseFrontmatter(raw, agentPath);\n if (data?.agents !== undefined) {\n subAgentRefs[id] = normalizeAgentsFrontmatter(data.agents, id, agentPath);\n }\n if (data?.default === true && !defaultAgent) {\n defaultAgent = id;\n }\n }\n\n // Pass 2: resolve sub-agent references against the complete defs map.\n // Code-defined agents (ctx.codeAgents) take precedence over markdown ones\n // with the same name, matching the plugin's top-level merge behaviour.\n for (const [name, refs] of Object.entries(subAgentRefs)) {\n if (refs.length === 0) continue;\n const children: Record<string, AgentDefinition> = {};\n const missing: string[] = [];\n for (const ref of refs) {\n if (ref === name) {\n throw new Error(\n `Agent '${name}' (${path.join(dir, name, \"agent.md\")}) cannot reference itself in 'agents:'.`,\n );\n }\n const sibling = ctx.codeAgents?.[ref] ?? defs[ref];\n if (!sibling) {\n missing.push(ref);\n continue;\n }\n children[ref] = sibling;\n }\n if (missing.length > 0) {\n const available =\n [...Object.keys(ctx.codeAgents ?? {}), ...Object.keys(defs)]\n .sort()\n .join(\", \") || \"<none>\";\n throw new Error(\n `Agent '${name}' references sub-agent(s) '${missing.join(\", \")}' in 'agents:', ` +\n `but no markdown or code agent(s) with those names exist. ` +\n `Available: ${available}.`,\n );\n }\n defs[name].agents = children;\n }\n\n return { defs, defaultAgent };\n}\n\n/**\n * Validates that `agents:` frontmatter is an array of non-empty strings and\n * returns it with duplicates removed. Throws with a clear per-file message\n * on malformed input rather than silently ignoring.\n */\nfunction normalizeAgentsFrontmatter(\n value: unknown,\n agentName: string,\n filePath: string,\n): string[] {\n if (!Array.isArray(value)) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'agents:' frontmatter: ` +\n `expected an array of sibling agent ids, got ${typeof value}.`,\n );\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const item of value) {\n if (typeof item !== \"string\" || item.trim() === \"\") {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'agents:' entry: ` +\n `expected non-empty string, got ${JSON.stringify(item)}.`,\n );\n }\n if (seen.has(item)) continue;\n seen.add(item);\n out.push(item);\n }\n return out;\n}\n\n/** Exposed for tests. Parses `--- yaml ---\\nbody` and validates frontmatter keys. */\nexport function parseFrontmatter(\n raw: string,\n sourcePath?: string,\n): { data: Frontmatter | null; content: string } {\n const { yaml: yamlBlock, body } = splitFrontmatter(raw);\n if (yamlBlock === null) {\n return { data: null, content: body };\n }\n let parsed: unknown;\n try {\n parsed = yaml.load(yamlBlock);\n } catch (err) {\n const src = sourcePath ? ` (${sourcePath})` : \"\";\n throw new Error(\n `Invalid YAML frontmatter${src}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (parsed === null || parsed === undefined) {\n return { data: {}, content: body };\n }\n if (typeof parsed !== \"object\" || Array.isArray(parsed)) {\n const src = sourcePath ? ` (${sourcePath})` : \"\";\n throw new Error(`Frontmatter must be a YAML object${src}`);\n }\n const data = parsed as Record<string, unknown>;\n for (const key of Object.keys(data)) {\n if (!ALLOWED_KEYS.has(key)) {\n logger.warn(\n \"Ignoring unknown frontmatter key '%s' in %s\",\n key,\n sourcePath ?? \"<inline>\",\n );\n }\n }\n return { data: data as Frontmatter, content: body };\n}\n\nconst isNumber = (v: unknown): v is number => typeof v === \"number\";\n\n/**\n * Per-key validators for {@link GenerationParams} frontmatter. Keyed by wire\n * name and typed as `Record<keyof GenerationParams, ...>`, so a new param on\n * the interface is a compile error until it gets an entry here — parsing,\n * unknown-key detection, and warnings all derive from this one table.\n */\nconst GENERATION_PARAM_SPECS: Record<\n keyof GenerationParams,\n { label: string; valid: (v: unknown) => boolean }\n> = {\n temperature: { label: \"number\", valid: isNumber },\n top_p: { label: \"number\", valid: isNumber },\n frequency_penalty: { label: \"number\", valid: isNumber },\n presence_penalty: { label: \"number\", valid: isNumber },\n stop: {\n label: \"string or string[]\",\n valid: (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((s) => typeof s === \"string\")),\n },\n};\n\n/**\n * Defensively maps a frontmatter `generationParams` map to {@link GenerationParams}.\n * Picks only known keys with the expected wire types. A key present with the\n * wrong type (e.g. `temperature: \"0.5\"`) or an unknown key (e.g. `top-p`) is\n * dropped and logged at warn level, so a silently-ignored param is visible\n * rather than mistaken for \"applied\". Returns `undefined` when no valid key is\n * present.\n */\nfunction parseGenerationParams(\n value: unknown,\n sourcePath?: string,\n): GenerationParams | undefined {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return undefined;\n }\n const raw = value as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const where = sourcePath ?? \"<inline>\";\n\n for (const [key, v] of Object.entries(raw)) {\n const spec = GENERATION_PARAM_SPECS[key as keyof GenerationParams];\n if (!spec) {\n logger.warn(\n \"Ignoring unknown generationParams key '%s' in %s\",\n key,\n where,\n );\n } else if (spec.valid(v)) {\n out[key] = v;\n } else {\n logger.warn(\n \"Ignoring generationParams.%s in %s: expected %s, got %s\",\n key,\n where,\n spec.label,\n typeof v,\n );\n }\n }\n\n return Object.keys(out).length > 0 ? (out as GenerationParams) : undefined;\n}\n\n/**\n * Defensively parses a frontmatter `skills:` list into deduped skill names.\n * Non-array values and non-string/empty entries are dropped with a warning,\n * so a malformed list is visible rather than silently applied. Returns\n * `undefined` when nothing valid is present.\n */\nfunction parseSkillsFrontmatter(\n value: unknown,\n sourcePath?: string,\n): string[] | undefined {\n if (value === undefined) return undefined;\n const where = sourcePath ?? \"<inline>\";\n if (!Array.isArray(value)) {\n logger.warn(\n \"Ignoring 'skills' in %s: expected an array of skill names\",\n where,\n );\n return undefined;\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const item of value) {\n if (typeof item !== \"string\" || item.trim() === \"\") {\n logger.warn(\n \"Ignoring invalid 'skills' entry in %s: %s\",\n where,\n JSON.stringify(item),\n );\n continue;\n }\n const name = item.trim();\n if (seen.has(name)) continue;\n seen.add(name);\n out.push(name);\n }\n return out.length > 0 ? out : undefined;\n}\n\nfunction buildDefinition(\n name: string,\n raw: string,\n filePath: string,\n ctx: LoadContext,\n): AgentDefinition {\n const { data, content } = parseFrontmatter(raw, filePath);\n const fm: Frontmatter = data ?? {};\n\n const tools = resolveFrontmatterTools(name, fm, filePath, ctx);\n const model = fm.model ?? fm.endpoint ?? ctx.defaultModel;\n if (fm.auth !== undefined && fm.auth !== \"on-behalf-of-user\") {\n throw new Error(\n `Agent '${name}' (${filePath}) has invalid 'auth:' frontmatter: ` +\n `expected \"on-behalf-of-user\", got ${JSON.stringify(fm.auth)}.`,\n );\n }\n\n let baseSystemPrompt: BaseSystemPromptOption | undefined;\n if (fm.baseSystemPrompt === false) baseSystemPrompt = false;\n else if (typeof fm.baseSystemPrompt === \"string\")\n baseSystemPrompt = fm.baseSystemPrompt;\n\n return {\n name,\n instructions: content,\n model,\n tools: Object.keys(tools).length > 0 ? tools : undefined,\n skills: parseSkillsFrontmatter(fm.skills, filePath),\n maxSteps: typeof fm.maxSteps === \"number\" ? fm.maxSteps : undefined,\n maxTokens: typeof fm.maxTokens === \"number\" ? fm.maxTokens : undefined,\n generationParams: parseGenerationParams(fm.generationParams, filePath),\n baseSystemPrompt,\n ephemeral: typeof fm.ephemeral === \"boolean\" ? fm.ephemeral : undefined,\n auth: fm.auth,\n };\n}\n\nfunction resolveFrontmatterTools(\n agentName: string,\n fm: Frontmatter,\n filePath: string,\n ctx: LoadContext,\n): Record<string, AgentTool> {\n const out: Record<string, AgentTool> = {};\n const pluginIdx = ctx.plugins ?? new Map<string, ToolkitProvider>();\n\n for (const entry of fm.tools ?? []) {\n const parsed = parseToolEntry(entry, filePath, agentName);\n if (parsed.kind === \"plugin\") {\n const provider = pluginIdx.get(parsed.pluginName);\n if (!provider) {\n const available =\n pluginIdx.size > 0\n ? Array.from(pluginIdx.keys()).join(\", \")\n : \"<none>\";\n throw new Error(\n `Agent '${agentName}' (${filePath}) references 'plugin:${parsed.pluginName}', but plugin '${parsed.pluginName}' is not registered. Available: ${available}`,\n );\n }\n const entries = provider.toolkit(parsed.opts) as Record<string, unknown>;\n for (const [key, value] of Object.entries(entries)) {\n if (!isToolkitEntry(value)) {\n throw new Error(\n `Plugin '${parsed.pluginName}'.toolkit() returned a value at key '${key}' that is not a ToolkitEntry`,\n );\n }\n out[key] = value as ToolkitEntry;\n }\n } else {\n const tool = ctx.availableTools?.[parsed.toolName];\n if (!tool) {\n const available = ctx.availableTools\n ? Object.keys(ctx.availableTools).join(\", \")\n : \"<none>\";\n throw new Error(\n `Agent '${agentName}' (${filePath}) references ambient tool '${parsed.toolName}', which is not in the agents() plugin's tools field. Available: ${available}. ` +\n \"If you meant to reference a plugin, use the 'plugin:NAME' prefix.\",\n );\n }\n out[parsed.toolName] = tool;\n }\n }\n\n return out;\n}\n\ntype ParsedToolEntry =\n | { kind: \"plugin\"; pluginName: string; opts: ToolkitOptions | undefined }\n | { kind: \"ambient\"; toolName: string };\n\n/**\n * Classify one item in the `tools:` frontmatter list into either a plugin\n * reference (with optional ToolkitOptions) or an ambient tool lookup.\n *\n * Strings starting with `plugin:` are bare plugin references. Strings\n * without the prefix are ambient tool names. Object entries are\n * single-key mappings keyed by `plugin:NAME`; the value is either an\n * array (sugar for `{ only: [...] }`) or a full `ToolkitOptions` record.\n */\nfunction parseToolEntry(\n entry: FrontmatterToolEntry,\n filePath: string,\n agentName: string,\n): ParsedToolEntry {\n if (typeof entry === \"string\") {\n if (entry.startsWith(PLUGIN_PREFIX)) {\n const pluginName = entry.slice(PLUGIN_PREFIX.length);\n if (pluginName.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n return { kind: \"plugin\", pluginName, opts: undefined };\n }\n if (entry.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty string in 'tools:'.`,\n );\n }\n return { kind: \"ambient\", toolName: entry };\n }\n if (typeof entry !== \"object\" || entry === null) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has invalid 'tools:' entry: ${JSON.stringify(entry)}`,\n );\n }\n const keys = Object.keys(entry);\n if (keys.length !== 1) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'tools:' object entry must have exactly one key, got: ${keys.join(\", \")}`,\n );\n }\n const key = keys[0];\n // Bare `- plugin:` (no name after the colon) parses as a mapping with the\n // key `\"plugin\"`. Catch that as a friendly error rather than dumping it\n // through the generic \"expected key 'plugin:NAME'\" branch.\n if (key === \"plugin\") {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n if (!key.startsWith(PLUGIN_PREFIX)) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'tools:' object entries are reserved for plugin references; expected key 'plugin:NAME', got '${key}'. ` +\n \"Use a bare string for ambient tools (e.g. `- get_weather`).\",\n );\n }\n const pluginName = key.slice(PLUGIN_PREFIX.length);\n if (pluginName.length === 0) {\n throw new Error(\n `Agent '${agentName}' (${filePath}) has an empty plugin name in 'plugin:'.`,\n );\n }\n const value = entry[key];\n if (Array.isArray(value)) {\n return { kind: \"plugin\", pluginName, opts: { only: value } };\n }\n if (typeof value === \"object\" && value !== null) {\n return {\n kind: \"plugin\",\n pluginName,\n opts: value as ToolkitOptions,\n };\n }\n throw new Error(\n `Agent '${agentName}' (${filePath}) 'plugin:${pluginName}' options must be an array of tool names or a ToolkitOptions object.`,\n );\n}\n"],"mappings":";;;;;;;;;AAqBA,MAAM,SAAS,aAAa,gBAAgB;AAiG5C,MAAM,gBAAgB;;;;;;AAOtB,SAAgB,wBAAwB,UAA0B;CAChE,MAAM,aAAa,KAAK,UAAU,SAAS;CAC3C,MAAM,OAAO,KAAK,SAAS,WAAW;CACtC,MAAM,SAAS,KAAK,SAAS,KAAK,QAAQ,WAAW,CAAC;AACtD,KAAI,SAAS,cAAc,UAAU,WAAW,OAAO,WAAW,KAChE,QAAO;AAET,QAAO,KAAK,SAAS,YAAY,MAAM;;AAGzC,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;AAUF,eAAsB,kBACpB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Aa,IAAI,MAAM,EAAqB;AAClD,KAAI,WAAW,WAAW,EACxB,OAAM,IAAI,MACR,UAAU,UAAU,KAAK,SAAS,0CACnC;CAEH,MAAM,QAAQ,MAAM;AACpB,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO;EAAE,MAAM;EAAU;EAAY,MAAM,EAAE,MAAM,OAAO;EAAE;AAE9D,KAAI,OAAO,UAAU,YAAY,UAAU,KACzC,QAAO;EACL,MAAM;EACN;EACA,MAAM;EACP;AAEH,OAAM,IAAI,MACR,UAAU,UAAU,KAAK,SAAS,YAAY,WAAW,sEAC1D"}
|
|
@@ -2,6 +2,8 @@ import { AgentEvent, Message } from "../../shared/src/agent.js";
|
|
|
2
2
|
import { PluginConstructor, PluginData } from "../../shared/src/plugin.js";
|
|
3
3
|
import "../../shared/src/index.js";
|
|
4
4
|
import { AgentDefinition } from "./types.js";
|
|
5
|
+
import { CallerPrincipal } from "../../context/caller-context.js";
|
|
6
|
+
import "../../context/index.js";
|
|
5
7
|
|
|
6
8
|
//#region src/core/agent/run-agent.d.ts
|
|
7
9
|
interface RunAgentInput {
|
|
@@ -9,12 +11,23 @@ interface RunAgentInput {
|
|
|
9
11
|
messages: string | Message[];
|
|
10
12
|
/** Abort signal for cancellation. */
|
|
11
13
|
signal?: AbortSignal;
|
|
14
|
+
/**
|
|
15
|
+
* Explicit user credentials for standalone execution. Host and workspace ID
|
|
16
|
+
* are required, so no CLI profile or service-principal identity is selected.
|
|
17
|
+
* Omit to inherit the ambient scope, or use SP when no caller scope is open.
|
|
18
|
+
* Obtain the token through a trusted authentication flow, not model input.
|
|
19
|
+
*/
|
|
20
|
+
caller?: {
|
|
21
|
+
readonly token: string;
|
|
22
|
+
readonly principal: CallerPrincipal;
|
|
23
|
+
readonly host: string;
|
|
24
|
+
readonly workspaceId: string;
|
|
25
|
+
};
|
|
12
26
|
/**
|
|
13
27
|
* Optional plugin list. Required when `def.tools` is the function form
|
|
14
28
|
* `(plugins) => Record<string, AgentTool>` and the function dereferences
|
|
15
29
|
* any plugins. `runAgent` constructs a fresh instance per plugin and
|
|
16
|
-
* dispatches tool calls
|
|
17
|
-
* there is no HTTP request in standalone mode).
|
|
30
|
+
* dispatches tool calls with the run's ambient principal.
|
|
18
31
|
*/
|
|
19
32
|
plugins?: PluginData<PluginConstructor, unknown, string>[];
|
|
20
33
|
}
|
|
@@ -29,12 +42,12 @@ interface RunAgentResult {
|
|
|
29
42
|
* inline tools, and drives the adapter's `run()` loop to completion.
|
|
30
43
|
*
|
|
31
44
|
* Limitations vs. running through the agents() plugin:
|
|
32
|
-
* - **No
|
|
33
|
-
*
|
|
45
|
+
* - **No approval gate**: tools inherit the run's principal, SP by default.
|
|
46
|
+
* Explicit caller credentials enable user execution. The agents-plugin gate
|
|
34
47
|
* that prompts for human confirmation on `effect: "write" | "update" |
|
|
35
48
|
* "destructive"` tools is also absent. LLM-controlled tool arguments
|
|
36
|
-
* flow straight through to the
|
|
37
|
-
* trusted-prompt environment (CI, batch eval, internal scripts)
|
|
49
|
+
* flow straight through to the tools. Treat standalone runAgent as a
|
|
50
|
+
* trusted-prompt environment (CI, batch eval, internal scripts), not
|
|
38
51
|
* as an exposed user-facing surface.
|
|
39
52
|
* - **Hosted tools (MCP) are not supported** — they require a live MCP
|
|
40
53
|
* client that only exists inside the agents plugin's lifecycle.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-agent.d.ts","names":[],"sources":["../../../src/core/agent/run-agent.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"run-agent.d.ts","names":[],"sources":["../../../src/core/agent/run-agent.ts"],"mappings":";;;;;;;;UAiDiB,aAAA;;EAEf,QAAA,WAAmB,OAAA;;EAEnB,MAAA,GAAS,WAAA;EAJM;;;;;;EAWf,MAAA;IAAA,SACW,KAAA;IAAA,SACA,SAAA,EAAW,eAAA;IAAA,SACX,IAAA;IAAA,SACA,WAAA;EAAA;EAXX;;;;;;EAmBA,OAAA,GAAU,UAAA,CAAW,iBAAA;AAAA;AAAA,UAGN,cAAA;EAHL;EAKV,IAAA;EALsC;EAOtC,MAAA,EAAQ,UAAA;AAAA;;;;;;;;;AA+BV;;;;;;;;;;;;;;;;;;;;iBAAsB,QAAA,CACpB,GAAA,EAAK,eAAA,EACL,KAAA,EAAO,aAAA,GACN,OAAA,CAAQ,cAAA"}
|
|
@@ -1,4 +1,12 @@
|
|
|
1
|
+
import { createWorkspaceClient } from "../../shared/src/workspace-client/factory.js";
|
|
2
|
+
import { getClientOptions } from "../../context/client-options.js";
|
|
3
|
+
import { AuthenticationError } from "../../errors/authentication.js";
|
|
4
|
+
import { ConfigurationError } from "../../errors/configuration.js";
|
|
5
|
+
import "../../errors/index.js";
|
|
1
6
|
import { createLogger } from "../../logging/logger.js";
|
|
7
|
+
import { getCallerContext, getWorkspaceClient, runInCallerContext } from "../../context/execution-context.js";
|
|
8
|
+
import { assertPluginExecution } from "../../context/resource-capabilities.js";
|
|
9
|
+
import "../../context/index.js";
|
|
2
10
|
import { SUPERVISOR_EXTENSION_KEY, isSupervisorTool } from "../../agents/supervisor-api.js";
|
|
3
11
|
import { consumeAdapterStream } from "./consume-adapter-stream.js";
|
|
4
12
|
import { createPluginsProxy } from "./plugins-map.js";
|
|
@@ -6,7 +14,7 @@ import { resolveToolkitFromProvider } from "./toolkit-resolver.js";
|
|
|
6
14
|
import { functionToolToDefinition, isFunctionTool } from "./tools/function-tool.js";
|
|
7
15
|
import { isHostedTool } from "./tools/hosted-tools.js";
|
|
8
16
|
import { isToolkitEntry } from "./types.js";
|
|
9
|
-
import { randomUUID } from "node:crypto";
|
|
17
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
10
18
|
|
|
11
19
|
//#region src/core/agent/run-agent.ts
|
|
12
20
|
const logger = createLogger("agent:run-agent");
|
|
@@ -15,12 +23,12 @@ const logger = createLogger("agent:run-agent");
|
|
|
15
23
|
* inline tools, and drives the adapter's `run()` loop to completion.
|
|
16
24
|
*
|
|
17
25
|
* Limitations vs. running through the agents() plugin:
|
|
18
|
-
* - **No
|
|
19
|
-
*
|
|
26
|
+
* - **No approval gate**: tools inherit the run's principal, SP by default.
|
|
27
|
+
* Explicit caller credentials enable user execution. The agents-plugin gate
|
|
20
28
|
* that prompts for human confirmation on `effect: "write" | "update" |
|
|
21
29
|
* "destructive"` tools is also absent. LLM-controlled tool arguments
|
|
22
|
-
* flow straight through to the
|
|
23
|
-
* trusted-prompt environment (CI, batch eval, internal scripts)
|
|
30
|
+
* flow straight through to the tools. Treat standalone runAgent as a
|
|
31
|
+
* trusted-prompt environment (CI, batch eval, internal scripts), not
|
|
24
32
|
* as an exposed user-facing surface.
|
|
25
33
|
* - **Hosted tools (MCP) are not supported** — they require a live MCP
|
|
26
34
|
* client that only exists inside the agents plugin's lifecycle.
|
|
@@ -39,12 +47,40 @@ const logger = createLogger("agent:run-agent");
|
|
|
39
47
|
* createApp instead" message — not mid-stream.
|
|
40
48
|
*/
|
|
41
49
|
async function runAgent(def, input) {
|
|
50
|
+
if (def.auth === "on-behalf-of-user" && !input.caller && getCallerContext()?.principal.type !== "user") throw AuthenticationError.missingToken("user token (runAgent caller is required for an on-behalf-of-user agent)");
|
|
51
|
+
if (input.caller) {
|
|
52
|
+
const { principal, host, workspaceId } = input.caller;
|
|
53
|
+
const token = input.caller.token.trim();
|
|
54
|
+
if (!token) throw AuthenticationError.missingToken("user token");
|
|
55
|
+
if (principal.type !== "user" || !principal.userId.trim()) throw AuthenticationError.missingUserId();
|
|
56
|
+
if (!host.trim() || !workspaceId.trim()) throw new ConfigurationError("runAgent caller requires host and workspaceId");
|
|
57
|
+
const caller = {
|
|
58
|
+
principal: {
|
|
59
|
+
...principal,
|
|
60
|
+
userId: principal.userId.trim()
|
|
61
|
+
},
|
|
62
|
+
client: createWorkspaceClient({
|
|
63
|
+
token,
|
|
64
|
+
host,
|
|
65
|
+
authType: "pat",
|
|
66
|
+
clientOptions: getClientOptions()
|
|
67
|
+
}),
|
|
68
|
+
workspaceId: Promise.resolve(workspaceId),
|
|
69
|
+
tokenFingerprint: createHash("sha256").update(token).digest("hex").slice(0, 16)
|
|
70
|
+
};
|
|
71
|
+
const { caller: _credentials, ...scopedInput } = input;
|
|
72
|
+
return runInCallerContext(caller, () => runStandalone(def, scopedInput));
|
|
73
|
+
}
|
|
74
|
+
return runStandalone(def, input);
|
|
75
|
+
}
|
|
76
|
+
async function runStandalone(def, input) {
|
|
42
77
|
const providerCache = /* @__PURE__ */ new Map();
|
|
43
78
|
await initStandalonePlugins(input.plugins ?? [], providerCache);
|
|
44
|
-
return runAgentInternal(def, input, providerCache);
|
|
79
|
+
return runAgentInternal(def, input, providerCache, false);
|
|
45
80
|
}
|
|
46
|
-
async function runAgentInternal(def, input, providerCache) {
|
|
47
|
-
const
|
|
81
|
+
async function runAgentInternal(def, input, providerCache, parentOnBehalfOfUser) {
|
|
82
|
+
const onBehalfOfUser = parentOnBehalfOfUser || def.auth === "on-behalf-of-user";
|
|
83
|
+
const adapter = await resolveAdapter(def, onBehalfOfUser);
|
|
48
84
|
const messages = normalizeMessages(input.messages, def.instructions);
|
|
49
85
|
const toolIndex = buildStandaloneToolIndex(def, input.plugins ?? [], providerCache);
|
|
50
86
|
const tools = Array.from(toolIndex.values()).filter((e) => e.kind !== "hosted-supervisor").map((e) => e.def);
|
|
@@ -54,14 +90,17 @@ async function runAgentInternal(def, input, providerCache) {
|
|
|
54
90
|
const entry = toolIndex.get(name);
|
|
55
91
|
if (!entry) throw new Error(`Unknown tool: ${name}`);
|
|
56
92
|
if (entry.kind === "function") return entry.tool.execute(args);
|
|
57
|
-
if (entry.kind === "toolkit")
|
|
93
|
+
if (entry.kind === "toolkit") {
|
|
94
|
+
assertPluginExecution(entry.provider);
|
|
95
|
+
return entry.provider.executeAgentTool(entry.localName, args, signal);
|
|
96
|
+
}
|
|
58
97
|
if (entry.kind === "subagent") {
|
|
59
98
|
const subInput = {
|
|
60
99
|
messages: typeof args === "object" && args !== null && typeof args.input === "string" ? args.input : JSON.stringify(args),
|
|
61
100
|
signal,
|
|
62
101
|
plugins: input.plugins
|
|
63
102
|
};
|
|
64
|
-
return (await runAgentInternal(entry.agentDef, subInput, providerCache)).text;
|
|
103
|
+
return (await runAgentInternal(entry.agentDef, subInput, providerCache, onBehalfOfUser)).text;
|
|
65
104
|
}
|
|
66
105
|
if (entry.kind === "hosted-supervisor") throw new Error(`runAgent: tool "${name}" is a hosted-supervisor tool, executed server-side by the Databricks AI Gateway. It must not be invoked from the Node process.`);
|
|
67
106
|
throw new Error(`runAgent: tool "${name}" is a ${entry.kind} tool. Hosted/MCP tools are only usable via createApp({ plugins: [..., agents(...)] }).`);
|
|
@@ -120,7 +159,7 @@ async function initStandalonePlugins(plugins, cache) {
|
|
|
120
159
|
cache.set(data.name, instance);
|
|
121
160
|
}
|
|
122
161
|
}
|
|
123
|
-
async function resolveAdapter(def) {
|
|
162
|
+
async function resolveAdapter(def, onBehalfOfUser) {
|
|
124
163
|
const source = def.model ?? process.env.DATABRICKS_SERVING_ENDPOINT_NAME;
|
|
125
164
|
if (!source) {
|
|
126
165
|
const { DatabricksAdapter } = await import("../../agents/databricks.js");
|
|
@@ -128,7 +167,7 @@ async function resolveAdapter(def) {
|
|
|
128
167
|
}
|
|
129
168
|
if (typeof source === "string") {
|
|
130
169
|
const { adapterFromModelString } = await import("../../agents/databricks.js");
|
|
131
|
-
return adapterFromModelString(source);
|
|
170
|
+
return onBehalfOfUser ? adapterFromModelString(source, { workspaceClient: () => getWorkspaceClient() }) : adapterFromModelString(source);
|
|
132
171
|
}
|
|
133
172
|
return await source;
|
|
134
173
|
}
|
|
@@ -289,11 +328,8 @@ function providerCacheLookup(pluginName, cache) {
|
|
|
289
328
|
/**
|
|
290
329
|
* Lightweight `ToolProvider` shape check used by standalone `runAgent`.
|
|
291
330
|
*
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
* with a live HTTP context). Standalone plugins are constructed without a
|
|
295
|
-
* `WorkspaceClient` and have no request to scope to, so checking only the
|
|
296
|
-
* two `ToolProvider` methods is the right narrowing here.
|
|
331
|
+
* Standalone plugins need only these methods. Execution identity is inherited
|
|
332
|
+
* from the run's caller scope, without requiring a per-plugin asUser helper.
|
|
297
333
|
*/
|
|
298
334
|
function isStandaloneToolProvider(value) {
|
|
299
335
|
if (typeof value !== "object" || value === null) return false;
|