@databricks/appkit 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/CLAUDE.md +1 -0
  2. package/NOTICE.md +1 -0
  3. package/dist/appkit/package.js +1 -1
  4. package/dist/beta.d.ts +14 -1
  5. package/dist/beta.js +12 -1
  6. package/dist/connectors/index.js +3 -0
  7. package/dist/connectors/mcp/client.d.ts +60 -0
  8. package/dist/connectors/mcp/client.d.ts.map +1 -0
  9. package/dist/connectors/mcp/client.js +197 -0
  10. package/dist/connectors/mcp/client.js.map +1 -0
  11. package/dist/connectors/mcp/host-policy.d.ts +51 -0
  12. package/dist/connectors/mcp/host-policy.d.ts.map +1 -0
  13. package/dist/connectors/mcp/host-policy.js +168 -0
  14. package/dist/connectors/mcp/host-policy.js.map +1 -0
  15. package/dist/connectors/mcp/index.d.ts +3 -0
  16. package/dist/connectors/mcp/index.js +4 -0
  17. package/dist/connectors/mcp/types.d.ts +16 -0
  18. package/dist/connectors/mcp/types.d.ts.map +1 -0
  19. package/dist/context/index.js +1 -1
  20. package/dist/core/agent/build-toolkit.d.ts +2 -0
  21. package/dist/core/agent/build-toolkit.js +50 -0
  22. package/dist/core/agent/build-toolkit.js.map +1 -0
  23. package/dist/core/agent/consume-adapter-stream.js +33 -0
  24. package/dist/core/agent/consume-adapter-stream.js.map +1 -0
  25. package/dist/core/agent/create-agent.d.ts +27 -0
  26. package/dist/core/agent/create-agent.d.ts.map +1 -0
  27. package/dist/core/agent/create-agent.js +50 -0
  28. package/dist/core/agent/create-agent.js.map +1 -0
  29. package/dist/core/agent/load-agents.d.ts +67 -0
  30. package/dist/core/agent/load-agents.d.ts.map +1 -0
  31. package/dist/core/agent/load-agents.js +228 -0
  32. package/dist/core/agent/load-agents.js.map +1 -0
  33. package/dist/core/agent/normalize-result.js +39 -0
  34. package/dist/core/agent/normalize-result.js.map +1 -0
  35. package/dist/core/agent/run-agent.d.ts +34 -0
  36. package/dist/core/agent/run-agent.d.ts.map +1 -0
  37. package/dist/core/agent/run-agent.js +146 -0
  38. package/dist/core/agent/run-agent.js.map +1 -0
  39. package/dist/core/agent/system-prompt.js +38 -0
  40. package/dist/core/agent/system-prompt.js.map +1 -0
  41. package/dist/core/agent/tools/define-tool.d.ts +54 -0
  42. package/dist/core/agent/tools/define-tool.d.ts.map +1 -0
  43. package/dist/core/agent/tools/define-tool.js +50 -0
  44. package/dist/core/agent/tools/define-tool.js.map +1 -0
  45. package/dist/core/agent/tools/function-tool.d.ts +27 -0
  46. package/dist/core/agent/tools/function-tool.d.ts.map +1 -0
  47. package/dist/core/agent/tools/function-tool.js +21 -0
  48. package/dist/core/agent/tools/function-tool.js.map +1 -0
  49. package/dist/core/agent/tools/hosted-tools.d.ts +47 -0
  50. package/dist/core/agent/tools/hosted-tools.d.ts.map +1 -0
  51. package/dist/core/agent/tools/hosted-tools.js +67 -0
  52. package/dist/core/agent/tools/hosted-tools.js.map +1 -0
  53. package/dist/core/agent/tools/index.d.ts +5 -0
  54. package/dist/core/agent/tools/index.js +7 -0
  55. package/dist/core/agent/tools/json-schema.js +24 -0
  56. package/dist/core/agent/tools/json-schema.js.map +1 -0
  57. package/dist/core/agent/tools/sql-policy.js +256 -0
  58. package/dist/core/agent/tools/sql-policy.js.map +1 -0
  59. package/dist/core/agent/tools/tool.d.ts +34 -0
  60. package/dist/core/agent/tools/tool.d.ts.map +1 -0
  61. package/dist/core/agent/tools/tool.js +41 -0
  62. package/dist/core/agent/tools/tool.js.map +1 -0
  63. package/dist/core/agent/types.d.ts +214 -0
  64. package/dist/core/agent/types.d.ts.map +1 -0
  65. package/dist/core/agent/types.js +12 -0
  66. package/dist/core/agent/types.js.map +1 -0
  67. package/dist/core/appkit.d.ts +1 -0
  68. package/dist/core/appkit.d.ts.map +1 -1
  69. package/dist/core/appkit.js +31 -4
  70. package/dist/core/appkit.js.map +1 -1
  71. package/dist/core/plugin-context.d.ts +133 -0
  72. package/dist/core/plugin-context.d.ts.map +1 -0
  73. package/dist/core/plugin-context.js +220 -0
  74. package/dist/core/plugin-context.js.map +1 -0
  75. package/dist/index.d.ts +11 -11
  76. package/dist/internal-telemetry/appkit-log.js +19 -0
  77. package/dist/internal-telemetry/appkit-log.js.map +1 -0
  78. package/dist/internal-telemetry/config.js +15 -0
  79. package/dist/internal-telemetry/config.js.map +1 -0
  80. package/dist/internal-telemetry/index.js +4 -0
  81. package/dist/internal-telemetry/reporter.js +132 -0
  82. package/dist/internal-telemetry/reporter.js.map +1 -0
  83. package/dist/plugin/index.d.ts +1 -1
  84. package/dist/plugin/plugin.d.ts +18 -3
  85. package/dist/plugin/plugin.d.ts.map +1 -1
  86. package/dist/plugin/plugin.js +26 -2
  87. package/dist/plugin/plugin.js.map +1 -1
  88. package/dist/plugin/to-plugin.d.ts +15 -4
  89. package/dist/plugin/to-plugin.d.ts.map +1 -1
  90. package/dist/plugin/to-plugin.js +14 -4
  91. package/dist/plugin/to-plugin.js.map +1 -1
  92. package/dist/plugins/agents/agents.d.ts +4 -0
  93. package/dist/plugins/agents/agents.js +882 -0
  94. package/dist/plugins/agents/agents.js.map +1 -0
  95. package/dist/plugins/agents/defaults.js +13 -0
  96. package/dist/plugins/agents/defaults.js.map +1 -0
  97. package/dist/plugins/agents/event-channel.js +64 -0
  98. package/dist/plugins/agents/event-channel.js.map +1 -0
  99. package/dist/plugins/agents/event-translator.js +224 -0
  100. package/dist/plugins/agents/event-translator.js.map +1 -0
  101. package/dist/plugins/agents/index.d.ts +4 -0
  102. package/dist/plugins/agents/index.js +6 -0
  103. package/dist/plugins/agents/manifest.js +27 -0
  104. package/dist/plugins/agents/manifest.js.map +1 -0
  105. package/dist/plugins/agents/schemas.js +51 -0
  106. package/dist/plugins/agents/schemas.js.map +1 -0
  107. package/dist/plugins/agents/thread-store.js +58 -0
  108. package/dist/plugins/agents/thread-store.js.map +1 -0
  109. package/dist/plugins/agents/tool-approval-gate.js +75 -0
  110. package/dist/plugins/agents/tool-approval-gate.js.map +1 -0
  111. package/dist/plugins/analytics/analytics.d.ts +17 -2
  112. package/dist/plugins/analytics/analytics.d.ts.map +1 -1
  113. package/dist/plugins/analytics/analytics.js +33 -0
  114. package/dist/plugins/analytics/analytics.js.map +1 -1
  115. package/dist/plugins/files/plugin.d.ts +22 -3
  116. package/dist/plugins/files/plugin.d.ts.map +1 -1
  117. package/dist/plugins/files/plugin.js +102 -2
  118. package/dist/plugins/files/plugin.js.map +1 -1
  119. package/dist/plugins/genie/genie.d.ts +15 -2
  120. package/dist/plugins/genie/genie.d.ts.map +1 -1
  121. package/dist/plugins/genie/genie.js +45 -0
  122. package/dist/plugins/genie/genie.js.map +1 -1
  123. package/dist/plugins/jobs/plugin.d.ts +2 -1
  124. package/dist/plugins/jobs/plugin.d.ts.map +1 -1
  125. package/dist/plugins/jobs/plugin.js +1 -1
  126. package/dist/plugins/lakebase/index.d.ts +2 -2
  127. package/dist/plugins/lakebase/index.js +1 -1
  128. package/dist/plugins/lakebase/lakebase.d.ts +33 -4
  129. package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
  130. package/dist/plugins/lakebase/lakebase.js +77 -5
  131. package/dist/plugins/lakebase/lakebase.js.map +1 -1
  132. package/dist/plugins/lakebase/types.d.ts +38 -1
  133. package/dist/plugins/lakebase/types.d.ts.map +1 -1
  134. package/dist/plugins/server/index.d.ts +12 -1
  135. package/dist/plugins/server/index.d.ts.map +1 -1
  136. package/dist/plugins/server/index.js +39 -5
  137. package/dist/plugins/server/index.js.map +1 -1
  138. package/dist/plugins/server/types.d.ts +0 -3
  139. package/dist/plugins/server/types.d.ts.map +1 -1
  140. package/dist/plugins/serving/serving.d.ts +2 -1
  141. package/dist/plugins/serving/serving.d.ts.map +1 -1
  142. package/dist/shared/src/agent.d.ts +63 -1
  143. package/dist/shared/src/agent.d.ts.map +1 -1
  144. package/dist/shared/src/index.d.ts +1 -1
  145. package/dist/shared/src/plugin.d.ts +8 -0
  146. package/dist/shared/src/plugin.d.ts.map +1 -1
  147. package/docs/api/appkit/Class.Plugin.md +65 -23
  148. package/docs/api/appkit/Function.createApp.md +10 -8
  149. package/docs/privacy.md +41 -0
  150. package/llms.txt +1 -0
  151. package/package.json +4 -2
  152. package/sbom.cdx.json +1 -1
@@ -0,0 +1,882 @@
1
+ import { createLogger } from "../../logging/logger.js";
2
+ import { Plugin } from "../../plugin/plugin.js";
3
+ import { toPlugin } from "../../plugin/to-plugin.js";
4
+ import "../../plugin/index.js";
5
+ import { buildMcpHostPolicy } from "../../connectors/mcp/host-policy.js";
6
+ import { AppKitMcpClient } from "../../connectors/mcp/client.js";
7
+ import "../../connectors/mcp/index.js";
8
+ import { consumeAdapterStream } from "../../core/agent/consume-adapter-stream.js";
9
+ import { functionToolToDefinition, isFunctionTool } from "../../core/agent/tools/function-tool.js";
10
+ import { isHostedTool, resolveHostedTools } from "../../core/agent/tools/hosted-tools.js";
11
+ import { isToolkitEntry } from "../../core/agent/types.js";
12
+ import "../../core/agent/tools/index.js";
13
+ import { loadAgentsFromDir } from "../../core/agent/load-agents.js";
14
+ import { normalizeToolResult } from "../../core/agent/normalize-result.js";
15
+ import { buildBaseSystemPrompt, composeSystemPrompt } from "../../core/agent/system-prompt.js";
16
+ import { agentStreamDefaults } from "./defaults.js";
17
+ import { EventChannel } from "./event-channel.js";
18
+ import { AgentEventTranslator } from "./event-translator.js";
19
+ import manifest_default from "./manifest.js";
20
+ import { approvalRequestSchema, cancelRequestSchema, chatRequestSchema, invocationsRequestSchema } from "./schemas.js";
21
+ import { InMemoryThreadStore } from "./thread-store.js";
22
+ import { ToolApprovalGate } from "./tool-approval-gate.js";
23
+ import { randomUUID } from "node:crypto";
24
+ import pc from "picocolors";
25
+ import path from "node:path";
26
+
27
+ //#region src/plugins/agents/agents.ts
28
+ const logger = createLogger("agents");
29
+ const DEFAULT_AGENTS_DIR = "./config/agents";
30
+ /**
31
+ * Decide whether a tool call must traverse the approval gate. Honours both
32
+ * the modern `effect` field (mutating values: write / update / destructive)
33
+ * and the legacy `destructive: true` boolean. The contract is documented on
34
+ * `ToolAnnotations.effect` in shared/agent.ts.
35
+ *
36
+ * Without this, a tool authored only with `effect: "destructive"` (the
37
+ * preferred API) bypassed the gate entirely.
38
+ */
39
+ function requiresApproval(annotations) {
40
+ if (!annotations) return false;
41
+ if (annotations.destructive === true) return true;
42
+ switch (annotations.effect) {
43
+ case "write":
44
+ case "update":
45
+ case "destructive": return true;
46
+ case "read":
47
+ case void 0: return false;
48
+ default:
49
+ annotations.effect;
50
+ return false;
51
+ }
52
+ }
53
+ var AgentsPlugin = class extends Plugin {
54
+ static manifest = manifest_default;
55
+ static phase = "deferred";
56
+ agents = /* @__PURE__ */ new Map();
57
+ defaultAgentName = null;
58
+ activeStreams = /* @__PURE__ */ new Map();
59
+ mcpClient = null;
60
+ threadStore;
61
+ approvalGate = new ToolApprovalGate();
62
+ constructor(config) {
63
+ super(config);
64
+ this.config = config;
65
+ if (config.threadStore) this.threadStore = config.threadStore;
66
+ else {
67
+ this.threadStore = new InMemoryThreadStore();
68
+ if (process.env.NODE_ENV === "production") logger.warn("InMemoryThreadStore is in use in a production build (NODE_ENV=production). Thread history is unbounded and lost on restart. Pass agents({ threadStore: <persistent impl> }) for real deployments.");
69
+ else logger.info("Using default InMemoryThreadStore (dev-only — threads are lost on restart and grow without bound).");
70
+ }
71
+ }
72
+ /** Effective approval policy with defaults applied. */
73
+ get resolvedApprovalPolicy() {
74
+ const cfg = this.config.approval ?? {};
75
+ return {
76
+ requireForDestructive: cfg.requireForDestructive ?? true,
77
+ timeoutMs: cfg.timeoutMs ?? 6e4
78
+ };
79
+ }
80
+ /** Effective DoS limits with defaults applied. */
81
+ get resolvedLimits() {
82
+ const cfg = this.config.limits ?? {};
83
+ return {
84
+ maxConcurrentStreamsPerUser: cfg.maxConcurrentStreamsPerUser ?? 5,
85
+ maxToolCalls: cfg.maxToolCalls ?? 50,
86
+ maxSubAgentDepth: cfg.maxSubAgentDepth ?? 3,
87
+ toolCallTimeoutMs: cfg.toolCallTimeoutMs ?? 3e5
88
+ };
89
+ }
90
+ /** Count active streams owned by a given user. */
91
+ countUserStreams(userId) {
92
+ let n = 0;
93
+ for (const entry of this.activeStreams.values()) if (entry.userId === userId) n++;
94
+ return n;
95
+ }
96
+ async setup() {
97
+ const { agents, defaultAgentName } = await this.buildAgentRegistry();
98
+ this.agents = agents;
99
+ this.defaultAgentName = defaultAgentName;
100
+ this.mountInvocationsRoute();
101
+ this.printRegistry();
102
+ }
103
+ /**
104
+ * Reload agents from the configured directory, preserving code-defined
105
+ * agents. Builds a fresh registry first and only swaps on success — if
106
+ * `loadAgents` throws (malformed markdown, missing tool reference) the
107
+ * existing live registry stays in place and serving requests keep working.
108
+ */
109
+ async reload() {
110
+ const next = await this.buildAgentRegistry();
111
+ if (this.mcpClient) {
112
+ await this.mcpClient.close();
113
+ this.mcpClient = null;
114
+ }
115
+ this.agents = next.agents;
116
+ this.defaultAgentName = next.defaultAgentName;
117
+ }
118
+ /**
119
+ * Builds the agent registry into a fresh `Map` without touching live state.
120
+ * Called by both `setup` and `reload`; the latter only swaps the live
121
+ * registry once this resolves successfully (atomic reload).
122
+ */
123
+ async buildAgentRegistry() {
124
+ const { defs: fileDefs, defaultAgent: fileDefault } = await this.loadFileDefinitions();
125
+ const codeDefs = this.config.agents ?? {};
126
+ for (const name of Object.keys(fileDefs)) if (codeDefs[name]) logger.warn("Agent '%s' defined in both code and a markdown file. Code definition takes precedence.", name);
127
+ const merged = {};
128
+ for (const [name, def] of Object.entries(fileDefs)) merged[name] = {
129
+ def,
130
+ src: { origin: "file" }
131
+ };
132
+ for (const [name, def] of Object.entries(codeDefs)) merged[name] = {
133
+ def,
134
+ src: { origin: "code" }
135
+ };
136
+ const agents = /* @__PURE__ */ new Map();
137
+ let defaultAgentName = null;
138
+ if (Object.keys(merged).length === 0) {
139
+ logger.info("No agents registered (no files in %s, no code-defined agents)", this.resolvedAgentsDir() ?? "<disabled>");
140
+ return {
141
+ agents,
142
+ defaultAgentName
143
+ };
144
+ }
145
+ for (const [name, { def, src }] of Object.entries(merged)) try {
146
+ const registered = await this.buildRegisteredAgent(name, def, src);
147
+ agents.set(name, registered);
148
+ if (!defaultAgentName) defaultAgentName = name;
149
+ } catch (err) {
150
+ throw new Error(`Failed to register agent '${name}' (${src.origin}): ${err instanceof Error ? err.message : String(err)}`, { cause: err instanceof Error ? err : void 0 });
151
+ }
152
+ if (this.config.defaultAgent) {
153
+ if (!agents.has(this.config.defaultAgent)) throw new Error(`defaultAgent '${this.config.defaultAgent}' is not registered. Available: ${Array.from(agents.keys()).join(", ")}`);
154
+ defaultAgentName = this.config.defaultAgent;
155
+ } else if (fileDefault && agents.has(fileDefault)) defaultAgentName = fileDefault;
156
+ return {
157
+ agents,
158
+ defaultAgentName
159
+ };
160
+ }
161
+ resolvedAgentsDir() {
162
+ if (this.config.dir === false) return null;
163
+ const dir = this.config.dir ?? DEFAULT_AGENTS_DIR;
164
+ return path.isAbsolute(dir) ? dir : path.resolve(process.cwd(), dir);
165
+ }
166
+ async loadFileDefinitions() {
167
+ const dir = this.resolvedAgentsDir();
168
+ if (!dir) return {
169
+ defs: {},
170
+ defaultAgent: null
171
+ };
172
+ const pluginToolProviders = this.pluginProviderIndex();
173
+ const ambient = this.config.tools ?? {};
174
+ return await loadAgentsFromDir(dir, {
175
+ defaultModel: this.config.defaultModel,
176
+ availableTools: ambient,
177
+ plugins: pluginToolProviders,
178
+ codeAgents: this.config.agents
179
+ });
180
+ }
181
+ /**
182
+ * Builds the map of plugin-name → toolkit that the markdown loader consults
183
+ * when resolving `toolkits:` frontmatter entries.
184
+ */
185
+ pluginProviderIndex() {
186
+ const out = /* @__PURE__ */ new Map();
187
+ if (!this.context) return out;
188
+ for (const { name, provider } of this.context.getToolProviders()) {
189
+ const withToolkit = provider;
190
+ if (typeof withToolkit.toolkit === "function") out.set(name, { toolkit: withToolkit.toolkit.bind(withToolkit) });
191
+ }
192
+ return out;
193
+ }
194
+ async buildRegisteredAgent(name, def, src) {
195
+ const adapter = await this.resolveAdapter(def, name);
196
+ const toolIndex = await this.buildToolIndex(name, def, src);
197
+ return {
198
+ name,
199
+ instructions: def.instructions,
200
+ adapter,
201
+ toolIndex,
202
+ baseSystemPrompt: def.baseSystemPrompt,
203
+ maxSteps: def.maxSteps,
204
+ maxTokens: def.maxTokens,
205
+ ephemeral: def.ephemeral
206
+ };
207
+ }
208
+ async resolveAdapter(def, name) {
209
+ const source = def.model ?? this.config.defaultModel;
210
+ const adapterOptions = {};
211
+ if (def.maxSteps !== void 0) adapterOptions.maxSteps = def.maxSteps;
212
+ if (def.maxTokens !== void 0) adapterOptions.maxTokens = def.maxTokens;
213
+ if (!source) {
214
+ const { DatabricksAdapter } = await import("../../agents/databricks.js");
215
+ try {
216
+ return await DatabricksAdapter.fromModelServing(void 0, adapterOptions);
217
+ } catch (err) {
218
+ throw new Error(`Agent '${name}' has no model configured and no DATABRICKS_AGENT_ENDPOINT default available`, { cause: err instanceof Error ? err : void 0 });
219
+ }
220
+ }
221
+ if (typeof source === "string") {
222
+ const { DatabricksAdapter } = await import("../../agents/databricks.js");
223
+ return DatabricksAdapter.fromModelServing(source, adapterOptions);
224
+ }
225
+ return await source;
226
+ }
227
+ /**
228
+ * Resolves an agent's tool record into a per-agent dispatch index. Connects
229
+ * hosted tools via MCP client. Applies `autoInheritTools` defaults when the
230
+ * definition has no declared tools/agents.
231
+ */
232
+ async buildToolIndex(agentName, def, src) {
233
+ const index = /* @__PURE__ */ new Map();
234
+ const hasExplicitTools = def.tools && Object.keys(def.tools).length > 0;
235
+ const hasExplicitSubAgents = def.agents && Object.keys(def.agents).length > 0;
236
+ const inheritDefaults = normalizeAutoInherit(this.config.autoInheritTools);
237
+ if (!hasExplicitTools && !hasExplicitSubAgents && (src.origin === "file" ? inheritDefaults.file : inheritDefaults.code)) await this.applyAutoInherit(agentName, index);
238
+ for (const [childKey, childDef] of Object.entries(def.agents ?? {})) {
239
+ const toolName = `agent-${childKey}`;
240
+ index.set(toolName, {
241
+ source: "subagent",
242
+ agentName: childDef.name ?? childKey,
243
+ def: {
244
+ name: toolName,
245
+ description: childDef.instructions.slice(0, 120) || `Delegate to the ${childKey} sub-agent`,
246
+ parameters: {
247
+ type: "object",
248
+ properties: { input: {
249
+ type: "string",
250
+ description: "Message to send to the sub-agent."
251
+ } },
252
+ required: ["input"]
253
+ }
254
+ }
255
+ });
256
+ }
257
+ const hostedToCollect = [];
258
+ for (const [key, tool] of Object.entries(def.tools ?? {})) {
259
+ if (isToolkitEntry(tool)) {
260
+ index.set(key, {
261
+ source: "toolkit",
262
+ pluginName: tool.pluginName,
263
+ localName: tool.localName,
264
+ def: {
265
+ ...tool.def,
266
+ name: key
267
+ }
268
+ });
269
+ continue;
270
+ }
271
+ if (isFunctionTool(tool)) {
272
+ index.set(key, {
273
+ source: "function",
274
+ functionTool: tool,
275
+ def: {
276
+ ...functionToolToDefinition(tool),
277
+ name: key
278
+ }
279
+ });
280
+ continue;
281
+ }
282
+ if (isHostedTool(tool)) {
283
+ hostedToCollect.push(tool);
284
+ continue;
285
+ }
286
+ throw new Error(`Agent '${agentName}' tool '${key}' has an unrecognized shape`);
287
+ }
288
+ if (hostedToCollect.length > 0) await this.connectHostedTools(hostedToCollect, index);
289
+ return index;
290
+ }
291
+ async applyAutoInherit(agentName, index) {
292
+ if (!this.context) return;
293
+ const inherited = [];
294
+ const skippedByPlugin = /* @__PURE__ */ new Map();
295
+ const recordSkip = (pluginName, localName) => {
296
+ const list = skippedByPlugin.get(pluginName) ?? [];
297
+ list.push(localName);
298
+ skippedByPlugin.set(pluginName, list);
299
+ };
300
+ for (const { name: pluginName, provider } of this.context.getToolProviders()) {
301
+ if (pluginName === this.name) continue;
302
+ const withToolkit = provider;
303
+ if (typeof withToolkit.toolkit === "function") {
304
+ const entries = withToolkit.toolkit();
305
+ for (const [key, maybeEntry] of Object.entries(entries)) {
306
+ if (!isToolkitEntry(maybeEntry)) continue;
307
+ if (maybeEntry.autoInheritable !== true) {
308
+ recordSkip(maybeEntry.pluginName, maybeEntry.localName);
309
+ continue;
310
+ }
311
+ index.set(key, {
312
+ source: "toolkit",
313
+ pluginName: maybeEntry.pluginName,
314
+ localName: maybeEntry.localName,
315
+ def: {
316
+ ...maybeEntry.def,
317
+ name: key
318
+ }
319
+ });
320
+ inherited.push(key);
321
+ }
322
+ continue;
323
+ }
324
+ for (const tool of provider.getAgentTools()) recordSkip(pluginName, tool.name);
325
+ }
326
+ if (inherited.length > 0) logger.info("[agent %s] auto-inherited %d tool(s): %s", agentName, inherited.length, inherited.join(", "));
327
+ if (skippedByPlugin.size > 0) {
328
+ const summary = Array.from(skippedByPlugin.entries()).map(([p, tools]) => `${p}(${tools.length})`).join(", ");
329
+ logger.info("[agent %s] auto-inherit skipped %d tool(s) not marked autoInheritable: %s. Wire them explicitly via `tools:` if needed.", agentName, Array.from(skippedByPlugin.values()).reduce((n, list) => n + list.length, 0), summary);
330
+ }
331
+ }
332
+ async connectHostedTools(hostedTools, index) {
333
+ let host;
334
+ let authenticate;
335
+ try {
336
+ const { getWorkspaceClient } = await import("../../context/index.js");
337
+ const wsClient = getWorkspaceClient();
338
+ await wsClient.config.ensureResolved();
339
+ host = wsClient.config.host;
340
+ authenticate = async () => {
341
+ const headers = new Headers();
342
+ await wsClient.config.authenticate(headers);
343
+ return Object.fromEntries(headers.entries());
344
+ };
345
+ } catch {
346
+ host = process.env.DATABRICKS_HOST;
347
+ authenticate = async () => {
348
+ const token = process.env.DATABRICKS_TOKEN;
349
+ return token ? { Authorization: `Bearer ${token}` } : {};
350
+ };
351
+ }
352
+ if (!host) {
353
+ logger.warn("No Databricks host available — skipping %d hosted tool(s)", hostedTools.length);
354
+ return;
355
+ }
356
+ if (!this.mcpClient) {
357
+ const policy = buildMcpHostPolicy(this.config.mcp, host);
358
+ this.mcpClient = new AppKitMcpClient(host, authenticate, policy);
359
+ }
360
+ const endpoints = resolveHostedTools(hostedTools);
361
+ await this.mcpClient.connectAll(endpoints);
362
+ for (const def of this.mcpClient.getAllToolDefinitions()) index.set(def.name, {
363
+ source: "mcp",
364
+ mcpToolName: def.name,
365
+ def
366
+ });
367
+ }
368
+ getAgentTools() {
369
+ return [];
370
+ }
371
+ async executeAgentTool() {
372
+ throw new Error("AgentsPlugin does not expose executeAgentTool directly");
373
+ }
374
+ mountInvocationsRoute() {
375
+ if (!this.context) return;
376
+ this.context.addRoute("post", "/invocations", (req, res) => {
377
+ this._handleInvocations(req, res);
378
+ });
379
+ }
380
+ injectRoutes(router) {
381
+ this.route(router, {
382
+ name: "chat",
383
+ method: "post",
384
+ path: "/chat",
385
+ handler: async (req, res) => this._handleChat(req, res)
386
+ });
387
+ this.route(router, {
388
+ name: "cancel",
389
+ method: "post",
390
+ path: "/cancel",
391
+ handler: async (req, res) => this._handleCancel(req, res)
392
+ });
393
+ this.route(router, {
394
+ name: "approve",
395
+ method: "post",
396
+ path: "/approve",
397
+ handler: async (req, res) => this._handleApprove(req, res)
398
+ });
399
+ this.route(router, {
400
+ name: "threads",
401
+ method: "get",
402
+ path: "/threads",
403
+ handler: async (req, res) => this._handleListThreads(req, res)
404
+ });
405
+ this.route(router, {
406
+ name: "thread",
407
+ method: "get",
408
+ path: "/threads/:threadId",
409
+ handler: async (req, res) => this._handleGetThread(req, res)
410
+ });
411
+ this.route(router, {
412
+ name: "deleteThread",
413
+ method: "delete",
414
+ path: "/threads/:threadId",
415
+ handler: async (req, res) => this._handleDeleteThread(req, res)
416
+ });
417
+ this.route(router, {
418
+ name: "info",
419
+ method: "get",
420
+ path: "/info",
421
+ handler: async (_req, res) => {
422
+ res.json({
423
+ agents: Array.from(this.agents.keys()),
424
+ defaultAgent: this.defaultAgentName
425
+ });
426
+ }
427
+ });
428
+ }
429
+ clientConfig() {
430
+ return {
431
+ agents: Array.from(this.agents.keys()),
432
+ defaultAgent: this.defaultAgentName
433
+ };
434
+ }
435
+ async _handleChat(req, res) {
436
+ const parsed = chatRequestSchema.safeParse(req.body);
437
+ if (!parsed.success) {
438
+ res.status(400).json({
439
+ error: "Invalid request",
440
+ details: parsed.error.flatten().fieldErrors
441
+ });
442
+ return;
443
+ }
444
+ const { message, threadId, agent: agentName } = parsed.data;
445
+ const registered = this.resolveAgent(agentName);
446
+ if (!registered) {
447
+ res.status(400).json({ error: agentName ? `Agent "${agentName}" not found` : "No agent registered" });
448
+ return;
449
+ }
450
+ const userId = this.resolveUserId(req);
451
+ const limits = this.resolvedLimits;
452
+ if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {
453
+ res.setHeader("Retry-After", "5");
454
+ res.status(429).json({ error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.` });
455
+ return;
456
+ }
457
+ let thread = threadId ? await this.threadStore.get(threadId, userId) : null;
458
+ if (threadId && !thread) {
459
+ res.status(404).json({ error: `Thread ${threadId} not found` });
460
+ return;
461
+ }
462
+ if (!thread) thread = await this.threadStore.create(userId);
463
+ const userMessage = {
464
+ id: randomUUID(),
465
+ role: "user",
466
+ content: message,
467
+ createdAt: /* @__PURE__ */ new Date()
468
+ };
469
+ await this.threadStore.addMessage(thread.id, userId, userMessage);
470
+ return this._streamAgent(req, res, registered, thread, userId);
471
+ }
472
+ async _handleInvocations(req, res) {
473
+ const parsed = invocationsRequestSchema.safeParse(req.body);
474
+ if (!parsed.success) {
475
+ res.status(400).json({
476
+ error: "Invalid request",
477
+ details: parsed.error.flatten().fieldErrors
478
+ });
479
+ return;
480
+ }
481
+ const { input } = parsed.data;
482
+ const registered = this.resolveAgent();
483
+ if (!registered) {
484
+ res.status(400).json({ error: "No agent registered" });
485
+ return;
486
+ }
487
+ const userId = this.resolveUserId(req);
488
+ const limits = this.resolvedLimits;
489
+ if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {
490
+ res.setHeader("Retry-After", "5");
491
+ res.status(429).json({ error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.` });
492
+ return;
493
+ }
494
+ const thread = await this.threadStore.create(userId);
495
+ if (typeof input === "string") await this.threadStore.addMessage(thread.id, userId, {
496
+ id: randomUUID(),
497
+ role: "user",
498
+ content: input,
499
+ createdAt: /* @__PURE__ */ new Date()
500
+ });
501
+ else for (const item of input) {
502
+ const role = item.role ?? "user";
503
+ const content = typeof item.content === "string" ? item.content : JSON.stringify(item.content ?? "");
504
+ if (!content) continue;
505
+ await this.threadStore.addMessage(thread.id, userId, {
506
+ id: randomUUID(),
507
+ role,
508
+ content,
509
+ createdAt: /* @__PURE__ */ new Date()
510
+ });
511
+ }
512
+ return this._streamAgent(req, res, registered, thread, userId);
513
+ }
514
+ async _streamAgent(req, res, registered, thread, userId) {
515
+ const abortController = new AbortController();
516
+ const signal = abortController.signal;
517
+ const requestId = randomUUID();
518
+ this.activeStreams.set(requestId, {
519
+ controller: abortController,
520
+ userId
521
+ });
522
+ const tools = Array.from(registered.toolIndex.values()).map((e) => e.def);
523
+ const approvalPolicy = this.resolvedApprovalPolicy;
524
+ const limits = this.resolvedLimits;
525
+ const outboundEvents = new EventChannel();
526
+ const translator = new AgentEventTranslator();
527
+ const runState = {
528
+ req,
529
+ userId,
530
+ requestId,
531
+ abortController,
532
+ signal,
533
+ approvalPolicy,
534
+ limits,
535
+ translator,
536
+ outboundEvents,
537
+ toolCallsUsed: { count: 0 }
538
+ };
539
+ const executeTool = (name, args) => this.dispatchToolCall(runState, registered.toolIndex, name, args, 0);
540
+ const driver = (async () => {
541
+ try {
542
+ for (const evt of translator.translate({
543
+ type: "metadata",
544
+ data: { threadId: thread.id }
545
+ })) outboundEvents.push(evt);
546
+ const pluginNames = this.context ? this.context.getPluginNames().filter((n) => n !== this.name && n !== "server") : [];
547
+ const messagesWithSystem = [{
548
+ id: "system",
549
+ role: "system",
550
+ content: composePromptForAgent(registered, this.config.baseSystemPrompt, {
551
+ agentName: registered.name,
552
+ pluginNames,
553
+ toolNames: tools.map((t) => t.name)
554
+ }),
555
+ createdAt: /* @__PURE__ */ new Date()
556
+ }, ...thread.messages];
557
+ const fullContent = await consumeAdapterStream(registered.adapter.run({
558
+ messages: messagesWithSystem,
559
+ tools,
560
+ threadId: thread.id,
561
+ signal
562
+ }, {
563
+ executeTool,
564
+ signal
565
+ }), {
566
+ signal,
567
+ onEvent: (event) => {
568
+ for (const translated of translator.translate(event)) outboundEvents.push(translated);
569
+ }
570
+ });
571
+ if (fullContent) await this.threadStore.addMessage(thread.id, userId, {
572
+ id: randomUUID(),
573
+ role: "assistant",
574
+ content: fullContent,
575
+ createdAt: /* @__PURE__ */ new Date()
576
+ });
577
+ for (const evt of translator.finalize()) outboundEvents.push(evt);
578
+ } catch (error) {
579
+ if (signal.aborted) {
580
+ outboundEvents.close();
581
+ return;
582
+ }
583
+ logger.error("Agent chat error: %O", error);
584
+ outboundEvents.close(error);
585
+ return;
586
+ } finally {
587
+ this.approvalGate.abortStream(requestId);
588
+ this.activeStreams.delete(requestId);
589
+ if (registered.ephemeral) try {
590
+ await this.threadStore.delete(thread.id, userId);
591
+ } catch (err) {
592
+ logger.warn("Failed to delete ephemeral thread %s: %O", thread.id, err);
593
+ }
594
+ }
595
+ outboundEvents.close();
596
+ })();
597
+ await this.executeStream(res, async function* () {
598
+ try {
599
+ for await (const ev of outboundEvents) yield ev;
600
+ } finally {
601
+ await driver.catch(() => void 0);
602
+ }
603
+ }, {
604
+ ...agentStreamDefaults,
605
+ stream: {
606
+ ...agentStreamDefaults.stream,
607
+ streamId: requestId
608
+ }
609
+ });
610
+ }
611
+ /**
612
+ * Dispatch a single tool call from either the top-level adapter or a
613
+ * sub-agent. Centralising this in one method is what makes the budget
614
+ * counter, approval gate, and abort signal observe sub-agent activity:
615
+ * `runSubAgent` reuses the same `runState` and so increments the same
616
+ * counter and emits approval events through the same channel.
617
+ *
618
+ * `depth` is the current sub-agent recursion depth (0 at the top level).
619
+ * It is forwarded to `runSubAgent` when the dispatched entry is itself a
620
+ * sub-agent, so depth limits remain enforced.
621
+ */
622
+ async dispatchToolCall(runState, toolIndex, name, args, depth) {
623
+ if (runState.toolCallsUsed.count >= runState.limits.maxToolCalls) {
624
+ runState.abortController.abort(/* @__PURE__ */ new Error(`Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}).`));
625
+ throw new Error(`Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}). Raise agents({ limits: { maxToolCalls } }) or review the agent's tool-selection logic.`);
626
+ }
627
+ runState.toolCallsUsed.count++;
628
+ const entry = toolIndex.get(name);
629
+ if (!entry) throw new Error(`Unknown tool: ${name}`);
630
+ if (runState.approvalPolicy.requireForDestructive && requiresApproval(entry.def.annotations)) {
631
+ const approvalId = randomUUID();
632
+ for (const ev of runState.translator.translate({
633
+ type: "approval_pending",
634
+ approvalId,
635
+ streamId: runState.requestId,
636
+ toolName: name,
637
+ args,
638
+ annotations: entry.def.annotations
639
+ })) runState.outboundEvents.push(ev);
640
+ if (await this.approvalGate.wait({
641
+ approvalId,
642
+ streamId: runState.requestId,
643
+ userId: runState.userId,
644
+ timeoutMs: runState.approvalPolicy.timeoutMs
645
+ }) === "deny") return `Tool execution denied by user approval gate (tool: ${name}).`;
646
+ }
647
+ let result;
648
+ if (entry.source === "toolkit") {
649
+ if (!this.context) throw new Error("Plugin tool execution requires PluginContext; this should never happen through createApp");
650
+ result = await this.context.executeTool(runState.req, entry.pluginName, entry.localName, args, runState.signal, runState.limits.toolCallTimeoutMs);
651
+ } else if (entry.source === "function") result = await entry.functionTool.execute(args);
652
+ else if (entry.source === "mcp") {
653
+ if (!this.mcpClient) throw new Error("MCP client not connected");
654
+ const oboToken = runState.req.headers["x-forwarded-access-token"];
655
+ const mcpAuth = typeof oboToken === "string" ? { Authorization: `Bearer ${oboToken}` } : void 0;
656
+ result = await this.mcpClient.callTool(entry.mcpToolName, args, mcpAuth);
657
+ } else if (entry.source === "subagent") {
658
+ const childAgent = this.agents.get(entry.agentName);
659
+ if (!childAgent) throw new Error(`Sub-agent not found: ${entry.agentName}`);
660
+ result = await this.runSubAgent(runState, childAgent, args, depth + 1);
661
+ }
662
+ return normalizeToolResult(result);
663
+ }
664
+ /**
665
+ * Runs a sub-agent in response to an `agent-<key>` tool call. Returns the
666
+ * concatenated text output to hand back to the parent adapter as the tool
667
+ * result.
668
+ *
669
+ * `depth` starts at 1 for a top-level sub-agent invocation (i.e. the
670
+ * outer `_streamAgent` calls `runSubAgent(..., 1)`) and increments on
671
+ * each nested `runSubAgent` call. Depths exceeding
672
+ * `limits.maxSubAgentDepth` are rejected before any adapter work.
673
+ *
674
+ * Sub-agent tool calls run through `dispatchToolCall` with the same
675
+ * `runState` as the parent — the budget counter and approval gate are
676
+ * therefore enforced for every nested call, not only at the top level.
677
+ */
678
+ async runSubAgent(runState, child, args, depth) {
679
+ if (depth > runState.limits.maxSubAgentDepth) throw new Error(`Sub-agent depth exceeded (limit ${runState.limits.maxSubAgentDepth}). Raise agents({ limits: { maxSubAgentDepth } }) or break the delegation cycle.`);
680
+ const input = typeof args === "object" && args !== null && typeof args.input === "string" ? args.input : JSON.stringify(args);
681
+ const childTools = Array.from(child.toolIndex.values()).map((e) => e.def);
682
+ const childExecute = (name, childArgs) => this.dispatchToolCall(runState, child.toolIndex, name, childArgs, depth);
683
+ const runContext = {
684
+ executeTool: childExecute,
685
+ signal: runState.signal
686
+ };
687
+ const pluginNames = this.context ? this.context.getPluginNames().filter((n) => n !== this.name && n !== "server") : [];
688
+ const messages = [{
689
+ id: "system",
690
+ role: "system",
691
+ content: composePromptForAgent(child, this.config.baseSystemPrompt, {
692
+ agentName: child.name,
693
+ pluginNames,
694
+ toolNames: childTools.map((t) => t.name)
695
+ }),
696
+ createdAt: /* @__PURE__ */ new Date()
697
+ }, {
698
+ id: randomUUID(),
699
+ role: "user",
700
+ content: input,
701
+ createdAt: /* @__PURE__ */ new Date()
702
+ }];
703
+ return consumeAdapterStream(child.adapter.run({
704
+ messages,
705
+ tools: childTools,
706
+ threadId: randomUUID(),
707
+ signal: runState.signal
708
+ }, runContext), {
709
+ signal: runState.signal,
710
+ onEvent: (event) => {
711
+ if (event.type === "metadata") return;
712
+ for (const translated of runState.translator.translate(event)) runState.outboundEvents.push(translated);
713
+ }
714
+ });
715
+ }
716
+ async _handleCancel(req, res) {
717
+ const parsed = cancelRequestSchema.safeParse(req.body);
718
+ if (!parsed.success) {
719
+ res.status(400).json({
720
+ error: "Invalid request",
721
+ details: parsed.error.flatten().fieldErrors
722
+ });
723
+ return;
724
+ }
725
+ const { streamId } = parsed.data;
726
+ const entry = this.activeStreams.get(streamId);
727
+ if (!entry) {
728
+ res.json({ cancelled: true });
729
+ return;
730
+ }
731
+ const userId = this.resolveUserId(req);
732
+ if (entry.userId !== userId) {
733
+ res.status(403).json({ error: "Forbidden" });
734
+ return;
735
+ }
736
+ entry.controller.abort("Cancelled by user");
737
+ this.activeStreams.delete(streamId);
738
+ this.approvalGate.abortStream(streamId);
739
+ res.json({ cancelled: true });
740
+ }
741
+ async _handleApprove(req, res) {
742
+ const parsed = approvalRequestSchema.safeParse(req.body);
743
+ if (!parsed.success) {
744
+ res.status(400).json({
745
+ error: "Invalid request",
746
+ details: parsed.error.flatten().fieldErrors
747
+ });
748
+ return;
749
+ }
750
+ const { streamId, approvalId, decision } = parsed.data;
751
+ const streamEntry = this.activeStreams.get(streamId);
752
+ if (!streamEntry) {
753
+ res.status(404).json({ error: "Stream not found or already completed" });
754
+ return;
755
+ }
756
+ const userId = this.resolveUserId(req);
757
+ if (streamEntry.userId !== userId) {
758
+ res.status(403).json({ error: "Forbidden" });
759
+ return;
760
+ }
761
+ const result = this.approvalGate.submit({
762
+ approvalId,
763
+ userId,
764
+ decision
765
+ });
766
+ if (!result.ok) {
767
+ if (result.reason === "forbidden") {
768
+ res.status(403).json({ error: "Forbidden" });
769
+ return;
770
+ }
771
+ res.status(404).json({ error: "Approval not found or already settled" });
772
+ return;
773
+ }
774
+ res.json({ decision });
775
+ }
776
+ async _handleListThreads(req, res) {
777
+ const userId = this.resolveUserId(req);
778
+ const threads = await this.threadStore.list(userId);
779
+ res.json({ threads });
780
+ }
781
+ async _handleGetThread(req, res) {
782
+ const userId = this.resolveUserId(req);
783
+ const thread = await this.threadStore.get(req.params.threadId, userId);
784
+ if (!thread) {
785
+ res.status(404).json({ error: "Thread not found" });
786
+ return;
787
+ }
788
+ res.json(thread);
789
+ }
790
+ async _handleDeleteThread(req, res) {
791
+ const userId = this.resolveUserId(req);
792
+ if (!await this.threadStore.delete(req.params.threadId, userId)) {
793
+ res.status(404).json({ error: "Thread not found" });
794
+ return;
795
+ }
796
+ res.json({ deleted: true });
797
+ }
798
+ resolveAgent(name) {
799
+ if (name) return this.agents.get(name) ?? null;
800
+ if (this.defaultAgentName) return this.agents.get(this.defaultAgentName) ?? null;
801
+ const first = this.agents.values().next();
802
+ return first.done ? null : first.value;
803
+ }
804
+ printRegistry() {
805
+ if (this.agents.size === 0) return;
806
+ console.log("");
807
+ console.log(` ${pc.bold("Agents")} ${pc.dim(`(${this.agents.size})`)}`);
808
+ console.log(` ${pc.dim("─".repeat(60))}`);
809
+ for (const [name, reg] of this.agents) {
810
+ const tools = reg.toolIndex.size;
811
+ const marker = name === this.defaultAgentName ? pc.green("●") : " ";
812
+ console.log(` ${marker} ${pc.bold(name.padEnd(24))} ${pc.dim(`${tools} tools`)}`);
813
+ }
814
+ console.log(` ${pc.dim("─".repeat(60))}`);
815
+ console.log("");
816
+ }
817
+ async shutdown() {
818
+ this.approvalGate.abortAll();
819
+ if (this.mcpClient) {
820
+ await this.mcpClient.close();
821
+ this.mcpClient = null;
822
+ }
823
+ }
824
+ exports() {
825
+ return {
826
+ register: (name, def) => this.registerCodeAgent(name, def),
827
+ list: () => Array.from(this.agents.keys()),
828
+ get: (name) => this.agents.get(name) ?? null,
829
+ reload: () => this.reload(),
830
+ getDefault: () => this.defaultAgentName,
831
+ getThreads: (userId) => this.threadStore.list(userId)
832
+ };
833
+ }
834
+ async registerCodeAgent(name, def) {
835
+ const registered = await this.buildRegisteredAgent(name, def, { origin: "code" });
836
+ this.agents.set(name, registered);
837
+ if (!this.defaultAgentName) this.defaultAgentName = name;
838
+ }
839
+ };
840
+ function normalizeAutoInherit(value) {
841
+ if (value === void 0) return {
842
+ file: false,
843
+ code: false
844
+ };
845
+ if (typeof value === "boolean") return {
846
+ file: value,
847
+ code: value
848
+ };
849
+ return {
850
+ file: value.file ?? false,
851
+ code: value.code ?? false
852
+ };
853
+ }
854
+ function composePromptForAgent(registered, pluginLevel, ctx) {
855
+ const perAgent = registered.baseSystemPrompt;
856
+ const resolved = perAgent !== void 0 ? perAgent : pluginLevel;
857
+ let base = "";
858
+ if (resolved === false) base = "";
859
+ else if (typeof resolved === "string") base = resolved;
860
+ else if (typeof resolved === "function") base = resolved(ctx);
861
+ else base = buildBaseSystemPrompt(ctx);
862
+ return composeSystemPrompt(base, registered.instructions);
863
+ }
864
+ /**
865
+ * Plugin factory for the agents plugin. Reads `config/agents/*.md` by default,
866
+ * resolves toolkits/tools from registered plugins, exposes `appkit.agents.*`
867
+ * runtime API and mounts `/invocations`.
868
+ *
869
+ * @example
870
+ * ```ts
871
+ * import { agents, analytics, createApp, server } from "@databricks/appkit";
872
+ *
873
+ * await createApp({
874
+ * plugins: [server(), analytics(), agents()],
875
+ * });
876
+ * ```
877
+ */
878
+ const agents = toPlugin(AgentsPlugin);
879
+
880
+ //#endregion
881
+ export { AgentsPlugin };
882
+ //# sourceMappingURL=agents.js.map