@databricks/appkit 0.69.2 → 0.69.3

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.
@@ -1,6 +1,6 @@
1
1
  //#region package.json
2
2
  var name = "@databricks/appkit";
3
- var version = "0.69.2";
3
+ var version = "0.69.3";
4
4
 
5
5
  //#endregion
6
6
  export { name, version };
@@ -17,14 +17,18 @@
17
17
  * @param contextLabel - prefix included in the error message; differentiates
18
18
  * the runtime context (e.g. `"runAgent: tools(plugins)"` vs
19
19
  * `"AgentsPlugin: tools(plugins)"`) so users know which path to debug.
20
+ * @param nonProviderNames - names of plugins that ARE registered but expose no
21
+ * agent tools (no `.toolkit()`), so a miss on one of these reports "registered
22
+ * but not a ToolProvider" instead of the misleading "not registered".
20
23
  */
21
- function createPluginsProxy(entries, contextLabel) {
24
+ function createPluginsProxy(entries, contextLabel, nonProviderNames) {
22
25
  return new Proxy(entries, {
23
26
  get(target, prop, receiver) {
24
27
  if (typeof prop !== "string") return Reflect.get(target, prop, receiver);
25
28
  if (prop in target) return Reflect.get(target, prop, receiver);
26
29
  if (prop === "then" || prop === "toJSON" || prop === "constructor" || prop === "toString" || prop === "valueOf") return;
27
30
  const available = Object.keys(target).join(", ") || "(none)";
31
+ if (nonProviderNames?.has(prop)) throw new Error(`${contextLabel} referenced plugin '${prop}', which is registered but exposes no agent tools (no .toolkit() — not a ToolProvider), so it can't be used from tools(plugins). Tool-providing plugins: ${available}.`);
28
32
  throw new Error(`${contextLabel} referenced plugin '${prop}', but it is not registered. Available: ${available}.`);
29
33
  },
30
34
  has(target, prop) {
@@ -1 +1 @@
1
- {"version":3,"file":"plugins-map.js","names":[],"sources":["../../../src/core/agent/plugins-map.ts"],"sourcesContent":["import type { Plugins, PluginToolkitProvider } from \"./types\";\n\n/**\n * Wrap a plain `Record<string, PluginToolkitProvider>` so that accessing an\n * unknown plugin name throws with a named, actionable error instead of the\n * default `TypeError: Cannot read properties of undefined (reading 'toolkit')`\n * that surfaces from chained access on a missing key.\n *\n * The {@link Plugins} type is a `Record<string, PluginToolkitProvider>`\n * without `noUncheckedIndexedAccess` workspace-wide, so unknown keys type as\n * present at compile time but resolve to `undefined` at runtime. The proxy\n * closes that gap with a runtime error that names the missing plugin and\n * lists what's available — same shape as the agents plugin's pre-existing\n * \"plugin is not registered\" errors.\n *\n * @param entries - the resolved plugin map; the proxy serves these directly\n * for known keys and throws for any other string key.\n * @param contextLabel - prefix included in the error message; differentiates\n * the runtime context (e.g. `\"runAgent: tools(plugins)\"` vs\n * `\"AgentsPlugin: tools(plugins)\"`) so users know which path to debug.\n */\nexport function createPluginsProxy(\n entries: Record<string, PluginToolkitProvider>,\n contextLabel: string,\n): Plugins {\n return new Proxy(entries, {\n get(target, prop, receiver) {\n // Symbols and well-known string accessors (e.g. `Symbol.toPrimitive`,\n // `then` checked by Promise.resolve, `toJSON`) must pass through so\n // host code that probes the object doesn't hit the missing-plugin\n // error. Only named string-key access that misses is treated as a\n // user error.\n if (typeof prop !== \"string\") {\n return Reflect.get(target, prop, receiver);\n }\n if (prop in target) {\n return Reflect.get(target, prop, receiver);\n }\n // Probes from runtime tooling (e.g. utility inspection, JSON\n // serialization, async-iterator detection) hit common property names\n // that are clearly not plugin lookups. Pass those through silently.\n if (\n prop === \"then\" ||\n prop === \"toJSON\" ||\n prop === \"constructor\" ||\n prop === \"toString\" ||\n prop === \"valueOf\"\n ) {\n return undefined;\n }\n const available = Object.keys(target).join(\", \") || \"(none)\";\n throw new Error(\n `${contextLabel} referenced plugin '${prop}', but it is not registered. ` +\n `Available: ${available}.`,\n );\n },\n has(target, prop) {\n return Reflect.has(target, prop);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n }) as Plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,mBACd,SACA,cACS;AACT,QAAO,IAAI,MAAM,SAAS;EACxB,IAAI,QAAQ,MAAM,UAAU;AAM1B,OAAI,OAAO,SAAS,SAClB,QAAO,QAAQ,IAAI,QAAQ,MAAM,SAAS;AAE5C,OAAI,QAAQ,OACV,QAAO,QAAQ,IAAI,QAAQ,MAAM,SAAS;AAK5C,OACE,SAAS,UACT,SAAS,YACT,SAAS,iBACT,SAAS,cACT,SAAS,UAET;GAEF,MAAM,YAAY,OAAO,KAAK,OAAO,CAAC,KAAK,KAAK,IAAI;AACpD,SAAM,IAAI,MACR,GAAG,aAAa,sBAAsB,KAAK,0CAC3B,UAAU,GAC3B;;EAEH,IAAI,QAAQ,MAAM;AAChB,UAAO,QAAQ,IAAI,QAAQ,KAAK;;EAElC,QAAQ,QAAQ;AACd,UAAO,QAAQ,QAAQ,OAAO;;EAEhC,yBAAyB,QAAQ,MAAM;AACrC,UAAO,QAAQ,yBAAyB,QAAQ,KAAK;;EAExD,CAAC"}
1
+ {"version":3,"file":"plugins-map.js","names":[],"sources":["../../../src/core/agent/plugins-map.ts"],"sourcesContent":["import type { Plugins, PluginToolkitProvider } from \"./types\";\n\n/**\n * Wrap a plain `Record<string, PluginToolkitProvider>` so that accessing an\n * unknown plugin name throws with a named, actionable error instead of the\n * default `TypeError: Cannot read properties of undefined (reading 'toolkit')`\n * that surfaces from chained access on a missing key.\n *\n * The {@link Plugins} type is a `Record<string, PluginToolkitProvider>`\n * without `noUncheckedIndexedAccess` workspace-wide, so unknown keys type as\n * present at compile time but resolve to `undefined` at runtime. The proxy\n * closes that gap with a runtime error that names the missing plugin and\n * lists what's available — same shape as the agents plugin's pre-existing\n * \"plugin is not registered\" errors.\n *\n * @param entries - the resolved plugin map; the proxy serves these directly\n * for known keys and throws for any other string key.\n * @param contextLabel - prefix included in the error message; differentiates\n * the runtime context (e.g. `\"runAgent: tools(plugins)\"` vs\n * `\"AgentsPlugin: tools(plugins)\"`) so users know which path to debug.\n * @param nonProviderNames - names of plugins that ARE registered but expose no\n * agent tools (no `.toolkit()`), so a miss on one of these reports \"registered\n * but not a ToolProvider\" instead of the misleading \"not registered\".\n */\nexport function createPluginsProxy(\n entries: Record<string, PluginToolkitProvider>,\n contextLabel: string,\n nonProviderNames?: ReadonlySet<string>,\n): Plugins {\n return new Proxy(entries, {\n get(target, prop, receiver) {\n // Symbols and well-known string accessors (e.g. `Symbol.toPrimitive`,\n // `then` checked by Promise.resolve, `toJSON`) must pass through so\n // host code that probes the object doesn't hit the missing-plugin\n // error. Only named string-key access that misses is treated as a\n // user error.\n if (typeof prop !== \"string\") {\n return Reflect.get(target, prop, receiver);\n }\n if (prop in target) {\n return Reflect.get(target, prop, receiver);\n }\n // Probes from runtime tooling (e.g. utility inspection, JSON\n // serialization, async-iterator detection) hit common property names\n // that are clearly not plugin lookups. Pass those through silently.\n if (\n prop === \"then\" ||\n prop === \"toJSON\" ||\n prop === \"constructor\" ||\n prop === \"toString\" ||\n prop === \"valueOf\"\n ) {\n return undefined;\n }\n const available = Object.keys(target).join(\", \") || \"(none)\";\n if (nonProviderNames?.has(prop)) {\n throw new Error(\n `${contextLabel} referenced plugin '${prop}', which is registered but ` +\n `exposes no agent tools (no .toolkit() — not a ToolProvider), so it ` +\n `can't be used from tools(plugins). Tool-providing plugins: ${available}.`,\n );\n }\n throw new Error(\n `${contextLabel} referenced plugin '${prop}', but it is not registered. ` +\n `Available: ${available}.`,\n );\n },\n has(target, prop) {\n return Reflect.has(target, prop);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n }) as Plugins;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,mBACd,SACA,cACA,kBACS;AACT,QAAO,IAAI,MAAM,SAAS;EACxB,IAAI,QAAQ,MAAM,UAAU;AAM1B,OAAI,OAAO,SAAS,SAClB,QAAO,QAAQ,IAAI,QAAQ,MAAM,SAAS;AAE5C,OAAI,QAAQ,OACV,QAAO,QAAQ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A,GAAoB,OAAA;EA44BT;;;;;;EAAA,QAh4BT,iBAAA;EAUR,YAAA,CAAa,MAAA,EAAQ,UAAA;EAkDrB,YAAA,CAAA,GAAgB,MAAA;EAAA,QAeF,WAAA;;;;;;;;;;;;UA2FN,gCAAA;;;;;;;;;;;UAuBM,aAAA;EAAA,QA2FA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;UAuOA,qBAAA;EAAA,QAsKN,iBAAA;;;;;;;UAaA,iBAAA;;UAQA,gBAAA;EAAA,QAYM,aAAA;EAAA,QA2BA,cAAA;EAAA,QAuCA,kBAAA;EAAA,QASA,gBAAA;EAAA,QAUA,mBAAA;EAAA,QAaN,YAAA;EAAA,QASA,aAAA;EAgBF,QAAA,CAAA,GAAY,OAAA;EAQlB,OAAA,CAAA;6BAE2B,GAAA,EAAO,eAAA,KAAe,OAAA;;2BAG3B,eAAA;;;oCAGS,OAAA,CAAA,MAAA;EAAA;EAAA,QAIjB,iBAAA;AAAA;;;;;;;;;;;;;;;;;;cA2CH,MAAA,EAAM,QAAA,QAAA,YAAA,EAAA,kBAAA"}
@@ -464,10 +464,11 @@ var AgentsPlugin = class extends Plugin {
464
464
  */
465
465
  buildPluginsMap() {
466
466
  const out = {};
467
- if (!this.context) return createPluginsProxy(out, `Agent '${this.name}': tools(plugins)`);
467
+ const label = `Agent '${this.name}': tools(plugins)`;
468
+ if (!this.context) return createPluginsProxy(out, label);
468
469
  for (const { name, provider } of this.context.getToolProviders()) if (typeof provider.toolkit === "function") out[name] = provider;
469
470
  else out[name] = { toolkit: (opts) => resolveToolkitFromProvider(name, provider, opts) };
470
- return createPluginsProxy(out, `Agent '${this.name}': tools(plugins)`);
471
+ return createPluginsProxy(out, label, new Set(this.context.getPluginNames().filter((n) => !(n in out))));
471
472
  }
472
473
  async applyAutoInherit(agentName, index) {
473
474
  if (!this.context) return;
@@ -762,7 +763,8 @@ var AgentsPlugin = class extends Plugin {
762
763
  limits,
763
764
  translator,
764
765
  outboundEvents,
765
- toolCallsUsed: { count: 0 }
766
+ toolCallsUsed: { count: 0 },
767
+ toolErrors: []
766
768
  };
767
769
  const deps = this.toolDispatchDeps();
768
770
  const executeTool = (name, args) => dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);
@@ -904,7 +906,8 @@ var AgentsPlugin = class extends Plugin {
904
906
  limits,
905
907
  translator: new AgentEventTranslator(),
906
908
  outboundEvents: new EventChannel(),
907
- toolCallsUsed: { count: 0 }
909
+ toolCallsUsed: { count: 0 },
910
+ toolErrors: []
908
911
  };
909
912
  const deps = this.toolDispatchDeps();
910
913
  const executeTool = (name, args) => dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);
@@ -985,6 +988,7 @@ var AgentsPlugin = class extends Plugin {
985
988
  status: "completed",
986
989
  thread_id: thread.id,
987
990
  ...mlflowTraceId ? { mlflow_trace_id: mlflowTraceId } : {},
991
+ ...runState.toolErrors.length > 0 ? { tool_errors: runState.toolErrors } : {},
988
992
  output: [message]
989
993
  });
990
994
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agents.js","names":["manifest"],"sources":["../../../src/plugins/agents/agents.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type express from \"express\";\nimport pc from \"picocolors\";\nimport type {\n AgentAdapter,\n AgentToolDefinition,\n IAppRouter,\n Message,\n PluginPhase,\n ResponseOutputMessage,\n ResponseStreamEvent,\n Thread,\n ToolProvider,\n} from \"shared\";\n\nimport { isSupervisorTool } from \"../../agents/supervisor-api\";\nimport { AppKitMcpClient, buildMcpHostPolicy } from \"../../connectors/mcp\";\nimport { getWorkspaceClient } from \"../../context\";\nimport { consumeAdapterStream } from \"../../core/agent/consume-adapter-stream\";\nimport { loadAgentsFromDir } from \"../../core/agent/load-agents\";\nimport { CODE_AGENTS_SOURCE_DIR } from \"../../core/agent/load-code-agents\";\nimport { createPluginsProxy } from \"../../core/agent/plugins-map\";\nimport type {\n ResolvedSkillCatalog,\n SkillDefinition,\n} from \"../../core/agent/skills\";\nimport { resolveToolkitFromProvider } from \"../../core/agent/toolkit-resolver\";\nimport {\n functionToolToDefinition,\n isFunctionTool,\n isHostedTool,\n resolveHostedTools,\n} from \"../../core/agent/tools\";\nimport type {\n AgentDefinition,\n AgentsPluginConfig,\n AgentTools,\n Plugins,\n PluginToolkitProvider,\n RegisteredAgent,\n ResolvedToolEntry,\n} from \"../../core/agent/types\";\nimport { isToolkitEntry } from \"../../core/agent/types\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } from \"../../registry\";\nimport type { WorkspaceClient } from \"../../workspace-client\";\nimport { ActiveStreamTracker } from \"./active-stream-tracker\";\nimport {\n buildAdapterExtensions,\n supervisorToolDescription,\n warnOnCapabilityMismatch,\n} from \"./adapter-extensions\";\nimport { requiresApproval } from \"./approval\";\nimport { LOAD_SKILL_TOOL_DEF, READ_SKILL_FILE_TOOL_DEF } from \"./builtin-tools\";\nimport { agentStreamDefaults } from \"./defaults\";\nimport { EventChannel } from \"./event-channel\";\nimport { AgentEventTranslator } from \"./event-translator\";\nimport manifest from \"./manifest.json\";\nimport {\n currentTraceId,\n initAgentTracing,\n linkTraceToRun,\n traceAgent,\n} from \"./mlflow\";\nimport { composePromptForAgent } from \"./prompt\";\nimport {\n type AgentSource,\n loadCodeAgents,\n resolveDefaultAgent,\n} from \"./registry\";\nimport { resolveApprovalPolicy, resolveLimits } from \"./resolve-config\";\nimport {\n approvalRequestSchema,\n cancelRequestSchema,\n chatRequestSchema,\n invocationsRequestSchema,\n} from \"./schemas\";\nimport {\n dispatchSkillTool,\n loadGlobalSkills,\n loadVolumeSkills,\n renderForcedSkill,\n resolveAgentSkills,\n} from \"./skill-loader\";\nimport { InMemoryThreadStore } from \"./thread-store\";\nimport { ToolApprovalGate } from \"./tool-approval-gate\";\nimport {\n dispatchToolCall,\n type RunState,\n type ToolDispatchDeps,\n} from \"./tool-dispatch\";\n\nconst logger = createLogger(\"agents\");\n\n/** Deprecated markdown location, read as a fallback with a one-time warning. */\nconst LEGACY_MARKDOWN_DIR = \"config/agents\";\n\nexport class AgentsPlugin extends Plugin implements ToolProvider {\n static manifest = defineManifest<\"agents\">(manifest);\n static phase: PluginPhase = \"deferred\";\n\n declare protected config: AgentsPluginConfig;\n\n private agents = new Map<string, RegisteredAgent>();\n private defaultAgentName: string | null = null;\n /**\n * Active SSE streams + per-user counts (the O(1) concurrency-limit check).\n * Mutated only via {@link trackStream} / {@link untrackStream}.\n */\n private streams = new ActiveStreamTracker();\n private mcpClient: AppKitMcpClient | null = null;\n private threadStore;\n private approvalGate = new ToolApprovalGate();\n /** Guards the `agents({ agents })` deprecation warning to once per instance. */\n private agentsMapDeprecationWarned = false;\n /** Guards the `config/agents` deprecation warning to once per instance. */\n private configAgentsDeprecationWarned = false;\n\n constructor(config: AgentsPluginConfig) {\n super(config);\n this.config = config;\n if (config.threadStore) {\n this.threadStore = config.threadStore;\n } else {\n this.threadStore = new InMemoryThreadStore();\n if (process.env.NODE_ENV === \"production\") {\n logger.warn(\n \"InMemoryThreadStore is in use in a production build (NODE_ENV=production). \" +\n \"Thread history is unbounded and lost on restart. \" +\n \"Pass agents({ threadStore: <persistent impl> }) for real deployments.\",\n );\n } else {\n logger.info(\n \"Using default InMemoryThreadStore (dev-only — threads are lost on restart and grow without bound).\",\n );\n }\n }\n }\n\n /**\n * Effective approval policy with defaults applied. Memoised so the\n * `timeoutMs` validation warning fires at most once per plugin instance —\n * `resolvedApprovalPolicy` gets hit on every chat stream and a noisy\n * misconfig would otherwise spam the logs.\n *\n * `timeoutMs` is clamped to a 1s floor so a misconfigured value (`0`,\n * negative, or `NaN`) can't degrade into immediate auto-denial of every\n * mutating tool call.\n */\n /**\n * Shared global skill pool (bundle `skills/` + catalog volume), loaded once\n * per registry build. Read by {@link buildRegisteredAgent} to resolve each\n * agent's visible catalog and by the live `register` path.\n */\n private globalSkills: SkillDefinition[] = [];\n\n private cachedApprovalPolicy: {\n requireForDestructive: boolean;\n timeoutMs: number;\n } | null = null;\n\n private get resolvedApprovalPolicy(): {\n requireForDestructive: boolean;\n timeoutMs: number;\n } {\n if (this.cachedApprovalPolicy) return this.cachedApprovalPolicy;\n this.cachedApprovalPolicy = resolveApprovalPolicy(this.config);\n return this.cachedApprovalPolicy;\n }\n\n /** Effective DoS limits with defaults applied. */\n private get resolvedLimits(): {\n maxConcurrentStreamsPerUser: number;\n maxToolCalls: number;\n maxSubAgentDepth: number;\n toolCallTimeoutMs: number;\n } {\n return resolveLimits(this.config);\n }\n\n /** Count active streams owned by a given user. O(1). */\n private countUserStreams(userId: string): number {\n return this.streams.count(userId);\n }\n\n private trackStream(\n requestId: string,\n userId: string,\n controller: AbortController,\n ): void {\n this.streams.track(requestId, userId, controller);\n }\n\n private untrackStream(requestId: string): void {\n this.streams.untrack(requestId);\n }\n\n async setup() {\n await initAgentTracing();\n const { agents, defaultAgentName } = await this.buildAgentRegistry();\n this.agents = agents;\n this.defaultAgentName = defaultAgentName;\n this.mountInvokeRoutes();\n this.printRegistry();\n }\n\n /**\n * Reload agents from the configured directory, preserving code-defined\n * agents. Builds a fresh registry first and only swaps on success — if\n * `loadAgents` throws (malformed markdown, missing tool reference) the\n * existing live registry stays in place and serving requests keep working.\n */\n async reload(): Promise<void> {\n const next = await this.buildAgentRegistry();\n // Deliberately NOT closing the existing mcpClient here. Tool\n // dispatch in `dispatchToolCall` reads `this.mcpClient` at call\n // time; closing it mid-stream throws \"MCP client is closed\" from\n // the next sendRpc and kills the in-flight conversation. The\n // client owns only short-lived `fetch` handles (no keep-alive\n // sockets) and the connections map persists in the live instance,\n // so dropping `this.mcpClient` would also strand in-flight tool\n // calls that resolved the field a moment earlier. Leave the live\n // client in place; `buildAgentRegistry` -> `connectHostedTools`\n // adds any new endpoints to the same instance, and stale\n // connections from a removed config become unreachable through\n // the new agent tool indexes (small memory cost, no correctness\n // hazard). The shutdown path still closes — that's process\n // teardown, where in-flight streams have already been aborted via\n // `abortActiveOperations`.\n this.agents = next.agents;\n this.defaultAgentName = next.defaultAgentName;\n }\n\n /**\n * Builds the agent registry into a fresh `Map` without touching live state.\n * Called by both `setup` and `reload`; the latter only swaps the live\n * registry once this resolves successfully (atomic reload).\n */\n private async buildAgentRegistry(): Promise<{\n agents: Map<string, RegisteredAgent>;\n defaultAgentName: string | null;\n }> {\n // Two \"code\" sources: discovered files and the deprecated `agents({ agents })` map.\n const discovered = await this.loadCodeAgents();\n const deprecatedMapRaw = this.config.agents ?? {};\n\n // Global skills (bundle + configured UC volume) load in parallel; per-agent\n // skills resolve later during agent build.\n const [bundleSkills, volumeSkills] = await Promise.all([\n this.loadGlobalSkills(),\n this.loadVolumeSkills(),\n ]);\n this.globalSkills = [...bundleSkills, ...volumeSkills];\n\n if (Object.keys(deprecatedMapRaw).length > 0) {\n this.warnAgentsMapDeprecated();\n }\n\n // On a discovered/map id clash, discovery wins (drop the map entry) rather\n // than crash boot on upgrade.\n const deprecatedMap: Record<string, AgentDefinition> = {};\n for (const [id, def] of Object.entries(deprecatedMapRaw)) {\n if (discovered[id]) {\n logger.warn(\n \"Agent '%s' is both discovered in %s and passed to agents({ agents }). \" +\n \"Using the discovered file; ignoring the map entry.\",\n id,\n CODE_AGENTS_SOURCE_DIR,\n );\n continue;\n }\n deprecatedMap[id] = def;\n }\n\n // Code agents also resolve markdown `agents: [child]` sub-agent references.\n const codeAgents: Record<string, AgentDefinition> = {\n ...discovered,\n ...deprecatedMap,\n };\n\n const { defs: fileDefs, defaultAgent: fileDefault } =\n await this.loadFileDefinitions(codeAgents);\n\n // Merge order (markdown, discovered, map) sets precedence and the\n // first-registered default fallback.\n const merged: Record<string, { def: AgentDefinition; src: AgentSource }> =\n {};\n for (const [name, def] of Object.entries(fileDefs)) {\n merged[name] = { def, src: { origin: \"file\" } };\n }\n for (const [name, def] of Object.entries(discovered)) {\n if (merged[name]?.src.origin === \"file\") {\n // Discovery is new API — clash with markdown is a hard error (the\n // deprecated map only warns). A folder with both agent.ts and\n // agent.md lands here too: one kind per folder.\n throw new Error(\n `Agent '${name}' is defined as both a code agent (agent.ts) and a markdown agent (agent.md) — ` +\n `in one folder, or across server/agents and the deprecated config/agents fallback. ` +\n `Keep a single kind per id. Available: ${Object.keys(merged).sort().join(\", \")}`,\n );\n }\n merged[name] = { def, src: { origin: \"code\" } };\n }\n for (const [name, def] of Object.entries(deprecatedMap)) {\n if (merged[name]?.src.origin === \"file\") {\n logger.warn(\n \"Agent '%s' defined in both code and a markdown file. Code definition takes precedence.\",\n name,\n );\n }\n merged[name] = { def, src: { origin: \"code\" } };\n }\n\n const agents = new Map<string, RegisteredAgent>();\n\n if (Object.keys(merged).length === 0) {\n logger.info(\n \"No agents registered (no files in %s, no discovered or code-defined agents)\",\n this.resolvedAgentsDir(),\n );\n return { agents, defaultAgentName: null };\n }\n\n for (const [name, { def, src }] of Object.entries(merged)) {\n try {\n agents.set(name, await this.buildRegisteredAgent(name, def, src));\n } catch (err) {\n throw new Error(\n `Failed to register agent '${name}' (${src.origin}): ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n\n return {\n agents,\n defaultAgentName: this.resolveDefaultAgent(agents, merged, fileDefault),\n };\n }\n\n /**\n * Resolves the default agent. Precedence: explicit `config.defaultAgent` >\n * a code/discovered agent flagged `default: true` (stable id order) >\n * markdown `default: true` > first registered (insertion order).\n */\n private resolveDefaultAgent(\n agents: Map<string, RegisteredAgent>,\n merged: Record<string, { def: AgentDefinition; src: AgentSource }>,\n fileDefault: string | null,\n ): string | null {\n return resolveDefaultAgent(\n agents,\n merged,\n fileDefault,\n this.config.defaultAgent,\n );\n }\n\n /**\n * Emits the one-time deprecation warning for the `agents({ agents })` map.\n * Guarded so `reload()` (which re-runs `buildAgentRegistry`) doesn't spam it.\n */\n private warnAgentsMapDeprecated(): void {\n if (this.agentsMapDeprecationWarned) return;\n this.agentsMapDeprecationWarned = true;\n logger.warn(\n \"agents({ agents: { ... } }) is deprecated. Put each code agent in its own folder under \" +\n \"server/agents/<id>/agent.ts (export default createAgent({ ... })) and it is discovered \" +\n \"automatically — the call collapses to agents({ ... }) with no agent map. The `agents` field \" +\n \"still works but will be removed in a future minor. See docs/plugins/agents.md.\",\n );\n }\n\n /**\n * One-time deprecation warning for markdown agents still living in\n * `config/agents/`. Guarded so `reload()` doesn't spam it.\n */\n private warnConfigAgentsDeprecated(): void {\n if (this.configAgentsDeprecationWarned) return;\n this.configAgentsDeprecationWarned = true;\n logger.warn(\n \"Markdown agents under config/agents/ are deprecated. Move each config/agents/<id>/agent.md to \" +\n \"server/agents/<id>/agent.md — every agent now lives in one place (server/agents). config/agents \" +\n \"is still read for now but will be removed in a future minor. See docs/plugins/agents.md.\",\n );\n }\n\n private resolvedAgentsDir(): string {\n return path.resolve(process.cwd(), CODE_AGENTS_SOURCE_DIR);\n }\n\n private loadCodeAgents(): Promise<Record<string, AgentDefinition>> {\n return loadCodeAgents({\n agentsDir: this.resolvedAgentsDir(),\n hasDeprecatedMap: Object.keys(this.config.agents ?? {}).length > 0,\n });\n }\n\n private async loadFileDefinitions(\n codeAgents: Record<string, AgentDefinition>,\n ): Promise<{\n defs: Record<string, AgentDefinition>;\n defaultAgent: string | null;\n }> {\n const primaryDir = this.resolvedAgentsDir();\n\n // Discovered code agents + the deprecated map resolve markdown `agents:`\n // sub-agent references, so a markdown parent can delegate to a code child.\n const baseCtx = {\n defaultModel: this.config.defaultModel,\n availableTools: this.config.tools ?? {},\n plugins: this.pluginProviderIndex(),\n };\n\n const legacyDir = path.resolve(process.cwd(), LEGACY_MARKDOWN_DIR);\n\n // Common case: no deprecated config/agents/ dir → a single scan of server/agents.\n if (!existsSync(legacyDir)) {\n return loadAgentsFromDir(primaryDir, { ...baseCtx, codeAgents });\n }\n\n // Deprecated fallback: config/agents/ exists → scan it first, then server/agents\n // with the legacy defs added as resolvable sub-agent targets, so a parent already\n // moved to server/agents can still reference a child left in config/agents\n // mid-migration. Code agents keep precedence; server/agents wins on an id clash.\n const legacy = await loadAgentsFromDir(legacyDir, {\n ...baseCtx,\n codeAgents,\n });\n const primary = await loadAgentsFromDir(primaryDir, {\n ...baseCtx,\n codeAgents: { ...legacy.defs, ...codeAgents },\n });\n\n if (Object.keys(legacy.defs).length === 0) return primary;\n\n this.warnConfigAgentsDeprecated();\n return {\n defs: { ...legacy.defs, ...primary.defs },\n defaultAgent: primary.defaultAgent ?? legacy.defaultAgent,\n };\n }\n\n /**\n * Builds the map of plugin-name → toolkit that the markdown loader consults\n * when resolving `plugin:NAME` entries in the unified `tools:` frontmatter\n * list (and, equivalently, that the code form passes as the `plugins`\n * argument to `tools(plugins) => Record<...>`).\n */\n private pluginProviderIndex(): Map<\n string,\n { toolkit: (opts?: unknown) => Record<string, unknown> }\n > {\n const out = new Map();\n if (!this.context) return out;\n for (const { name, provider } of this.context.getToolProviders()) {\n const withToolkit = provider as ToolProvider & {\n toolkit?: (opts?: unknown) => Record<string, unknown>;\n };\n if (typeof withToolkit.toolkit === \"function\") {\n out.set(name, {\n toolkit: withToolkit.toolkit.bind(withToolkit),\n });\n }\n }\n return out;\n }\n\n private async buildRegisteredAgent(\n name: string,\n def: AgentDefinition,\n src: AgentSource,\n ): Promise<RegisteredAgent> {\n const adapter = await this.resolveAdapter(def, name);\n const skills = await this.resolveAgentSkills(name, def, src);\n const toolIndex = await this.buildToolIndex(name, def, src, skills);\n\n warnOnCapabilityMismatch(name, adapter, toolIndex);\n\n return {\n name,\n instructions: def.instructions,\n adapter,\n toolIndex,\n baseSystemPrompt: def.baseSystemPrompt,\n maxSteps: def.maxSteps,\n maxTokens: def.maxTokens,\n generationParams: def.generationParams,\n ephemeral: def.ephemeral,\n skills,\n };\n }\n\n /** Loads the shared global skill pool from `<agentsDir>/skills/`. */\n private loadGlobalSkills(): Promise<SkillDefinition[]> {\n return loadGlobalSkills(this.resolvedAgentsDir());\n }\n\n /**\n * Workspace client used to read catalog skills. v1 reads as the app service\n * principal; `getWorkspaceClient()` resolves to SP outside a user scope\n * (boot and skill-tool dispatch are both unscoped). This is the single\n * switch point for a future OBO mode.\n */\n private skillWorkspaceClient(): WorkspaceClient {\n return getWorkspaceClient();\n }\n\n /** Discovers catalog skills from the configured UC Volume (best-effort). */\n private loadVolumeSkills(): Promise<SkillDefinition[]> {\n return loadVolumeSkills(this.config, () => this.skillWorkspaceClient());\n }\n\n private async resolveAgentSkills(\n name: string,\n def: AgentDefinition,\n src: AgentSource,\n ): Promise<RegisteredAgent[\"skills\"]> {\n const inherit = normalizeAutoInherit(this.config.autoInheritSkills);\n return resolveAgentSkills({\n name,\n def,\n agentsDir: this.resolvedAgentsDir(),\n isFileOrigin: src.origin === \"file\",\n autoInherit: src.origin === \"file\" ? inherit.file : inherit.code,\n globalSkills: this.globalSkills,\n });\n }\n\n private async resolveAdapter(\n def: AgentDefinition,\n name: string,\n ): Promise<AgentAdapter> {\n const source = def.model ?? this.config.defaultModel;\n // Per-agent adapter knobs from `AgentDefinition` / markdown frontmatter.\n // Only applied when AppKit builds the adapter itself (string or omitted\n // model). Users who pass a pre-built `AgentAdapter` own these settings.\n const adapterOptions: {\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: AgentDefinition[\"generationParams\"];\n } = {};\n if (def.maxSteps !== undefined) adapterOptions.maxSteps = def.maxSteps;\n if (def.maxTokens !== undefined) adapterOptions.maxTokens = def.maxTokens;\n if (def.generationParams !== undefined)\n adapterOptions.generationParams = def.generationParams;\n\n if (!source) {\n const { DatabricksAdapter } = await import(\"../../agents/databricks\");\n try {\n return await DatabricksAdapter.fromModelServing(\n undefined,\n adapterOptions,\n );\n } catch (err) {\n throw new Error(\n `Agent '${name}' has no model configured and no DATABRICKS_SERVING_ENDPOINT_NAME default available`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n if (typeof source === \"string\") {\n const { DatabricksAdapter } = await import(\"../../agents/databricks\");\n return DatabricksAdapter.fromModelServing(source, adapterOptions);\n }\n return await source;\n }\n\n /**\n * Resolves an agent's tool record into a per-agent dispatch index. Connects\n * hosted tools via MCP client. Applies `autoInheritTools` defaults when the\n * definition has no declared tools/agents.\n */\n private async buildToolIndex(\n agentName: string,\n def: AgentDefinition,\n src: AgentSource,\n skills?: ResolvedSkillCatalog,\n ): Promise<Map<string, ResolvedToolEntry>> {\n const index = new Map<string, ResolvedToolEntry>();\n const hasDeclaredTools = def.tools !== undefined;\n const toolsRecord = this.resolveDefTools(agentName, def);\n const hasExplicitSubAgents =\n def.agents && Object.keys(def.agents).length > 0;\n\n const inheritDefaults = normalizeAutoInherit(this.config.autoInheritTools);\n // Declaring `tools` (object or function, even an empty record) opts out\n // of auto-inherit. Same rule for both forms — see plan decision (E1/I1).\n const shouldInherit =\n !hasDeclaredTools &&\n !hasExplicitSubAgents &&\n (src.origin === \"file\" ? inheritDefaults.file : inheritDefaults.code);\n\n if (shouldInherit) {\n await this.applyAutoInherit(agentName, index);\n }\n\n // 1. Sub-agents → agent-<key>\n for (const [childKey, childDef] of Object.entries(def.agents ?? {})) {\n const toolName = `agent-${childKey}`;\n index.set(toolName, {\n source: \"subagent\",\n agentName: childDef.name ?? childKey,\n def: {\n name: toolName,\n description:\n childDef.instructions.slice(0, 120) ||\n `Delegate to the ${childKey} sub-agent`,\n parameters: {\n type: \"object\",\n properties: {\n input: {\n type: \"string\",\n description: \"Message to send to the sub-agent.\",\n },\n },\n required: [\"input\"],\n },\n },\n });\n }\n\n // 2. Explicit tools (toolkit entries, function tools, hosted tools)\n const hostedToCollect: import(\"../../core/agent/tools/hosted-tools\").HostedTool[] =\n [];\n for (const [key, tool] of Object.entries(toolsRecord)) {\n if (isToolkitEntry(tool)) {\n index.set(key, {\n source: \"toolkit\",\n pluginName: tool.pluginName,\n localName: tool.localName,\n def: { ...tool.def, name: key },\n });\n continue;\n }\n if (isFunctionTool(tool)) {\n index.set(key, {\n source: \"function\",\n functionTool: tool,\n def: { ...functionToolToDefinition(tool), name: key },\n });\n continue;\n }\n if (isSupervisorTool(tool)) {\n index.set(key, {\n source: \"hosted-supervisor\",\n spec: tool.spec,\n def: {\n // `def` is a placeholder so the index has a uniform shape; it\n // is intentionally not passed to the adapter's `tools` array\n // (the SA endpoint owns its own tool execution and would\n // reject our synthetic schema).\n name: key,\n description: supervisorToolDescription(tool.spec),\n parameters: { type: \"object\", properties: {} },\n },\n });\n continue;\n }\n if (isHostedTool(tool)) {\n hostedToCollect.push(tool);\n continue;\n }\n throw new Error(\n `Agent '${agentName}' tool '${key}' has an unrecognized shape`,\n );\n }\n\n if (hostedToCollect.length > 0) {\n await this.connectHostedTools(hostedToCollect, index);\n }\n\n // 3. Built-in skill tools, present only when this agent has a visible\n // catalog. Injected last so they reliably shadow any same-named tool.\n if (skills && skills.byAddress.size > 0) {\n index.set(\"load_skill\", {\n source: \"skill\",\n builtin: \"load_skill\",\n catalog: skills,\n def: LOAD_SKILL_TOOL_DEF,\n });\n index.set(\"read_skill_file\", {\n source: \"skill\",\n builtin: \"read_skill_file\",\n catalog: skills,\n def: READ_SKILL_FILE_TOOL_DEF,\n });\n }\n\n return index;\n }\n\n /**\n * Resolves an `AgentDefinition.tools` field to a plain tool record. The\n * function form is invoked exactly once at agent setup with the typed\n * {@link Plugins} map; the result replaces the function reference for the\n * remainder of the registered agent's lifetime.\n *\n * Plain object form is returned as-is; an undefined `tools` returns an\n * empty record. The function form is wrapped in a try/catch so a thrown\n * callback fails registration with a useful message instead of leaking\n * the raw stack.\n */\n private resolveDefTools(agentName: string, def: AgentDefinition): AgentTools {\n if (typeof def.tools !== \"function\") {\n return def.tools ?? {};\n }\n try {\n return def.tools(this.buildPluginsMap());\n } catch (err) {\n throw new Error(\n `Agent '${agentName}': tools(plugins) callback threw: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n\n /**\n * Builds the typed {@link Plugins} map passed to the function form of\n * `AgentDefinition.tools`. Each entry exposes the plugin instance directly\n * (so user code can call typed instance methods including `.toolkit()`);\n * plugins missing `.toolkit()` get a synthesized fallback that walks\n * `getAgentTools()` via `resolveToolkitFromProvider`.\n *\n * Wrapped in {@link createPluginsProxy} so that accessing an unknown\n * plugin name throws a named \"not registered, Available: ...\" error\n * instead of bubbling up a generic `Cannot read properties of undefined`\n * from the agent's `tools(plugins)` callback.\n */\n private buildPluginsMap(): Plugins {\n const out: Record<string, PluginToolkitProvider> = {};\n if (!this.context) {\n return createPluginsProxy(out, `Agent '${this.name}': tools(plugins)`);\n }\n for (const { name, provider } of this.context.getToolProviders()) {\n const direct = (provider as { toolkit?: unknown }).toolkit;\n if (typeof direct === \"function\") {\n out[name] = provider as unknown as PluginToolkitProvider;\n } else {\n out[name] = {\n toolkit: (opts) => resolveToolkitFromProvider(name, provider, opts),\n };\n }\n }\n return createPluginsProxy(out, `Agent '${this.name}': tools(plugins)`);\n }\n\n private async applyAutoInherit(\n agentName: string,\n index: Map<string, ResolvedToolEntry>,\n ): Promise<void> {\n if (!this.context) return;\n const inherited: string[] = [];\n const skippedByPlugin = new Map<string, string[]>();\n const recordSkip = (pluginName: string, localName: string) => {\n const list = skippedByPlugin.get(pluginName) ?? [];\n list.push(localName);\n skippedByPlugin.set(pluginName, list);\n };\n\n for (const {\n name: pluginName,\n provider,\n } of this.context.getToolProviders()) {\n if (pluginName === this.name) continue;\n const entries = resolveToolkitFromProvider(pluginName, provider);\n for (const [key, entry] of Object.entries(entries)) {\n if (entry.autoInheritable !== true) {\n recordSkip(entry.pluginName, entry.localName);\n continue;\n }\n index.set(key, {\n source: \"toolkit\",\n pluginName: entry.pluginName,\n localName: entry.localName,\n def: { ...entry.def, name: key },\n });\n inherited.push(key);\n }\n }\n\n if (inherited.length > 0) {\n logger.info(\n \"[agent %s] auto-inherited %d tool(s): %s\",\n agentName,\n inherited.length,\n inherited.join(\", \"),\n );\n }\n if (skippedByPlugin.size > 0) {\n const summary = Array.from(skippedByPlugin.entries())\n .map(([p, tools]) => `${p}(${tools.length})`)\n .join(\", \");\n logger.info(\n \"[agent %s] auto-inherit skipped %d tool(s) not marked autoInheritable: %s. Wire them explicitly via `tools:` if needed.\",\n agentName,\n Array.from(skippedByPlugin.values()).reduce(\n (n, list) => n + list.length,\n 0,\n ),\n summary,\n );\n }\n }\n\n private async connectHostedTools(\n hostedTools: import(\"../../core/agent/tools/hosted-tools\").HostedTool[],\n index: Map<string, ResolvedToolEntry>,\n ): Promise<void> {\n let host: string | undefined;\n let authenticate: () => Promise<Record<string, string>>;\n\n try {\n const { getWorkspaceClient } = await import(\"../../context\");\n const wsClient = getWorkspaceClient();\n await wsClient.config.ensureResolved();\n host = wsClient.config.host;\n authenticate = async () => {\n const headers = new Headers();\n await wsClient.config.authenticate(headers);\n return Object.fromEntries(headers.entries());\n };\n } catch {\n host = process.env.DATABRICKS_HOST;\n authenticate = async (): Promise<Record<string, string>> => {\n const token = process.env.DATABRICKS_TOKEN;\n return token ? { Authorization: `Bearer ${token}` } : {};\n };\n }\n\n if (!host) {\n logger.warn(\n \"No Databricks host available — skipping %d hosted tool(s)\",\n hostedTools.length,\n );\n return;\n }\n\n if (!this.mcpClient) {\n const policy = buildMcpHostPolicy(this.config.mcp, host);\n this.mcpClient = new AppKitMcpClient(host, authenticate, policy);\n }\n\n const endpoints = resolveHostedTools(hostedTools);\n const result = await this.mcpClient.connectAll(endpoints);\n if (result.failed.length > 0) {\n // Per-endpoint errors are already logged inside `connectAll`; this\n // aggregate warning makes the partial-success state visible at the\n // agent-registration boundary so operators see \"agent X registered\n // without N hosted-tool endpoints\" alongside the connect-time\n // errors, instead of just an opaque list of MCP failures.\n logger.warn(\n \"MCP: %s of %s endpoints failed to connect (%s). Agents that reference these endpoints will boot without their hosted tools.\",\n result.failed.length,\n endpoints.length,\n result.failed.map((f) => f.name).join(\", \"),\n );\n }\n\n for (const def of this.mcpClient.getAllToolDefinitions()) {\n index.set(def.name, {\n source: \"mcp\",\n mcpToolName: def.name,\n def,\n });\n }\n }\n\n // ----------------- ToolProvider (no tools of our own) --------------------\n\n getAgentTools(): AgentToolDefinition[] {\n return [];\n }\n\n async executeAgentTool(): Promise<unknown> {\n throw new Error(\"AgentsPlugin does not expose executeAgentTool directly\");\n }\n\n // ----------------- Route mounting and handlers ---------------------------\n\n /**\n * Mount the non-streaming invoke endpoints outside the `/api/<plugin>`\n * namespace. `/invocations` and `/responses` are aliases — both run the\n * default agent to completion and return a single JSON response. Streaming\n * lives on `POST /chat` (mounted in `injectRoutes`).\n */\n private mountInvokeRoutes() {\n if (!this.context) return;\n // Return the promise so the forwardAsyncErrors wrapper applied by\n // PluginContext.addRoute can forward rejections to the error middleware.\n const handler = (req: express.Request, res: express.Response) =>\n this._handleInvoke(req, res);\n this.context.addRoute(\"post\", \"/invocations\", handler);\n this.context.addRoute(\"post\", \"/responses\", handler);\n }\n\n injectRoutes(router: IAppRouter) {\n this.route(router, {\n name: \"chat\",\n method: \"post\",\n path: \"/chat\",\n handler: async (req, res) => this._handleChat(req, res),\n });\n this.route(router, {\n name: \"cancel\",\n method: \"post\",\n path: \"/cancel\",\n handler: async (req, res) => this._handleCancel(req, res),\n });\n this.route(router, {\n name: \"approve\",\n method: \"post\",\n path: \"/approve\",\n handler: async (req, res) => this._handleApprove(req, res),\n });\n this.route(router, {\n name: \"threads\",\n method: \"get\",\n path: \"/threads\",\n handler: async (req, res) => this._handleListThreads(req, res),\n });\n this.route(router, {\n name: \"thread\",\n method: \"get\",\n path: \"/threads/:threadId\",\n handler: async (req, res) => this._handleGetThread(req, res),\n });\n this.route(router, {\n name: \"deleteThread\",\n method: \"delete\",\n path: \"/threads/:threadId\",\n handler: async (req, res) => this._handleDeleteThread(req, res),\n });\n this.route(router, {\n name: \"info\",\n method: \"get\",\n path: \"/info\",\n handler: async (_req, res) => {\n res.json({\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\n });\n },\n });\n }\n\n clientConfig(): Record<string, unknown> {\n // Per-agent skill catalog (name + description) so the client can offer a\n // `/skill-name` autocomplete / picker. Only agents with a visible catalog\n // appear here.\n const skills: Record<string, { name: string; description: string }[]> = {};\n for (const [name, agent] of this.agents) {\n if (agent.skills) skills[name] = agent.skills.catalog;\n }\n return {\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\n skills,\n };\n }\n\n private async _handleChat(req: express.Request, res: express.Response) {\n const parsed = chatRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const {\n message,\n threadId,\n agent: agentName,\n mlflowRunId,\n skill,\n } = parsed.data;\n\n const registered = this.resolveAgent(agentName);\n if (!registered) {\n res.status(400).json({\n error: agentName\n ? `Agent \"${agentName}\" not found`\n : \"No agent registered\",\n });\n return;\n }\n\n const userId = this.resolveUserId(req);\n\n // Reject early (before allocating a thread) when the user is already at\n // their concurrent-stream limit. Prevents a misbehaving client from\n // churning thread rows while being denied elsewhere.\n const limits = this.resolvedLimits;\n if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {\n res.setHeader(\"Retry-After\", \"5\");\n res.status(429).json({\n error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.`,\n });\n return;\n }\n\n // ThreadStore can throw on backing-storage failures (DB unreachable,\n // permission errors, transient I/O). Without a try/catch the\n // `async` Express handler bubbles the rejection without a response and\n // the client connection hangs until the proxy times out. Surface the\n // failure as a 500 so the SSE client falls back instead of waiting.\n let thread: Thread;\n try {\n const existing = threadId\n ? await this.threadStore.get(threadId, userId)\n : null;\n if (threadId && !existing) {\n res.status(404).json({ error: `Thread ${threadId} not found` });\n return;\n }\n thread = existing ?? (await this.threadStore.create(userId));\n\n const userMessage: Message = {\n id: randomUUID(),\n role: \"user\",\n content: message,\n createdAt: new Date(),\n };\n await this.threadStore.addMessage(thread.id, userId, userMessage);\n } catch (err) {\n logger.error(\"threadStore failed in /chat: %O\", err);\n res.status(500).json({ error: \"Thread operation failed\" });\n return;\n }\n return this._streamAgent(\n req,\n res,\n registered,\n thread,\n userId,\n mlflowRunId,\n skill,\n );\n }\n\n /**\n * Returns the names of tools in `registered.toolIndex` whose annotations\n * would trip the approval gate. Used by the non-streaming invoke path\n * (`/invocations`, `/responses`) to fail-fast before the adapter runs:\n * those endpoints have no channel back to the user mid-call, so an agent\n * whose tool surface includes approval-gated tools cannot be served.\n *\n * Returns an empty list when the plugin is configured with\n * `approval.requireForDestructive: false` — operators who explicitly\n * disabled HITL keep the invoke surface unrestricted.\n */\n private collectApprovalRequiredToolNames(\n registered: RegisteredAgent,\n ): string[] {\n if (!this.resolvedApprovalPolicy.requireForDestructive) return [];\n const names: string[] = [];\n for (const entry of registered.toolIndex.values()) {\n if (requiresApproval(entry.def.annotations)) {\n names.push(entry.def.name);\n }\n }\n return names;\n }\n\n /**\n * Shared handler for `POST /invocations` and `POST /responses`. Runs the\n * default agent to completion and returns a single JSON response in the\n * OpenAI Responses non-streaming shape. The two endpoints are aliases —\n * streaming clients must use `POST /chat`.\n *\n * Rejects with HTTP 400 when the resolved agent has any approval-gated\n * tool in scope: HITL requires a live SSE channel, which this surface\n * does not provide. See {@link collectApprovalRequiredToolNames}.\n */\n private async _handleInvoke(req: express.Request, res: express.Response) {\n const parsed = invocationsRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { input, mlflowRunId } = parsed.data;\n const registered = this.resolveAgent();\n if (!registered) {\n res.status(400).json({ error: \"No agent registered\" });\n return;\n }\n\n // Pre-flight HITL gate. The non-streaming invoke surface has no way to\n // surface an approval prompt back to the caller and no way to receive\n // a decision mid-run, so we reject up-front instead of having the\n // approval gate auto-deny mid-stream (which would leave the caller\n // with a confusing \"denied by user\" tool result in the final text).\n const approvalGated = this.collectApprovalRequiredToolNames(registered);\n if (approvalGated.length > 0) {\n res.status(400).json({\n error:\n `Agent '${registered.name}' exposes ${approvalGated.length} approval-gated tool(s) ` +\n `(${approvalGated.join(\", \")}); /invocations and /responses are non-streaming and ` +\n \"cannot run HITL. Use POST /chat for HITL-capable agents, or disable approval via \" +\n \"agents({ approval: { requireForDestructive: false } }).\",\n });\n return;\n }\n\n const userId = this.resolveUserId(req);\n\n // Match the rate-limit gate on /chat. Without this, a client can bypass\n // `limits.maxConcurrentStreamsPerUser` by hitting /invocations instead.\n const limits = this.resolvedLimits;\n if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {\n res.setHeader(\"Retry-After\", \"5\");\n res.status(429).json({\n error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.`,\n });\n return;\n }\n\n // Same rationale as `_handleChat`: surface threadStore failures as a\n // 500 instead of letting the async handler hang the client connection.\n let thread: Thread;\n try {\n thread = await this.threadStore.create(userId);\n\n if (typeof input === \"string\") {\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"user\",\n content: input,\n createdAt: new Date(),\n });\n } else {\n for (const item of input) {\n const role = (item.role ?? \"user\") as Message[\"role\"];\n const content =\n typeof item.content === \"string\"\n ? item.content\n : JSON.stringify(item.content ?? \"\");\n if (!content) continue;\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role,\n content,\n createdAt: new Date(),\n });\n }\n }\n } catch (err) {\n logger.error(\"threadStore failed in /invocations: %O\", err);\n res.status(500).json({ error: \"Thread operation failed\" });\n return;\n }\n\n return this._runAgentNonStreaming(\n req,\n res,\n registered,\n thread,\n userId,\n mlflowRunId,\n );\n }\n\n private async _streamAgent(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: string,\n mlflowRunId?: string,\n forcedSkill?: string,\n ): Promise<void> {\n const abortController = new AbortController();\n const signal = abortController.signal;\n const requestId = randomUUID();\n this.trackStream(requestId, userId, abortController);\n\n // `hosted-supervisor` entries are not callable from the Node process\n // (the SA endpoint executes them server-side). Their `def` is a\n // placeholder; including it in the adapter's `tools` array would\n // make the SA endpoint reject the request with a schema mismatch.\n // The hosted-tool specs are routed via `AgentInput.extensions` below.\n const tools = Array.from(registered.toolIndex.values())\n .filter((e) => e.source !== \"hosted-supervisor\")\n .map((e) => e.def);\n const approvalPolicy = this.resolvedApprovalPolicy;\n const limits = this.resolvedLimits;\n const outboundEvents = new EventChannel<ResponseStreamEvent>();\n const translator = new AgentEventTranslator();\n\n // Per-run state shared with any sub-agents this run invokes. The boxed\n // tool-call counter, approval policy, and outbound event channel must\n // travel through the sub-agent path so it enforces the same budget and\n // approval gate as the top-level executeTool.\n const runState: RunState = {\n req,\n userId,\n requestId,\n abortController,\n signal,\n approvalPolicy,\n limits,\n translator,\n outboundEvents,\n toolCallsUsed: { count: 0 },\n };\n\n const deps = this.toolDispatchDeps();\n const executeTool = (name: string, args: unknown): Promise<unknown> =>\n dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);\n\n // Drive the adapter and the approval-event side-channel concurrently.\n // Outbound events from both sources flow through `outboundEvents`; the\n // generator below drains the channel in order. executeTool pushes\n // approval-pending events into the same channel before awaiting the gate.\n const driver = (async () => {\n try {\n for (const evt of translator.translate({\n type: \"metadata\",\n data: { threadId: thread.id },\n })) {\n outboundEvents.push(evt);\n }\n\n // Root MLflow span for the turn; tool-call spans nest under it.\n await traceAgent(\n registered.name ?? \"agent\",\n {\n messages: thread.messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n },\n async (span) => {\n // Link this turn's trace to an eval run when the eval runner\n // supplied one, so the trace shows under the MLflow evaluation run.\n if (mlflowRunId) linkTraceToRun(mlflowRunId);\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n let fullPrompt = composePromptForAgent(\n registered,\n this.config.baseSystemPrompt,\n {\n agentName: registered.name,\n pluginNames,\n toolNames: tools.map((t) => t.name),\n },\n );\n\n // Deterministic `/skill-name` invocation: eagerly inject the\n // requested skill's instructions into this turn rather than waiting\n // for the model to call load_skill. The tool stays available for\n // the model to auto-select others.\n if (forcedSkill) {\n const addendum = this.renderForcedSkill(registered, forcedSkill);\n if (addendum) fullPrompt = `${fullPrompt}\\n\\n${addendum}`;\n }\n\n const messagesWithSystem: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: fullPrompt,\n createdAt: new Date(),\n },\n ...thread.messages,\n ];\n\n const stream = registered.adapter.run(\n {\n messages: messagesWithSystem,\n tools,\n threadId: thread.id,\n signal,\n extensions: buildAdapterExtensions(registered.toolIndex),\n },\n { executeTool, signal },\n );\n\n // The accumulation rule (deltas append, `message` replaces) is\n // shared with `runAgent` and `runSubAgent`; see\n // `consumeAdapterStream` for the rationale.\n const fullContent = await consumeAdapterStream(stream, {\n signal,\n onEvent: (event) => {\n for (const translated of translator.translate(event)) {\n outboundEvents.push(translated);\n }\n },\n });\n\n if (fullContent) {\n span.setOutputs({ role: \"assistant\", content: fullContent });\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\n });\n }\n\n // Surface the MLflow trace id so eval runs can attach assessments\n // to this turn's trace. No-op when tracing is disabled.\n const mlflowTraceId = currentTraceId();\n if (mlflowTraceId) {\n for (const evt of translator.translate({\n type: \"metadata\",\n data: { mlflowTraceId },\n })) {\n outboundEvents.push(evt);\n }\n }\n },\n );\n\n for (const evt of translator.finalize()) outboundEvents.push(evt);\n } catch (error) {\n if (signal.aborted) {\n outboundEvents.close();\n return;\n }\n logger.error(\"Agent chat error: %O\", error);\n outboundEvents.close(error);\n return;\n } finally {\n // Any pending approval gates for this stream are auto-denied so the\n // adapter can unwind if it was still waiting.\n this.approvalGate.abortStream(requestId);\n this.untrackStream(requestId);\n // Stateless agents (e.g. autocomplete) don't persist history; drop\n // the thread so `InMemoryThreadStore` doesn't accumulate one record\n // per request. Swallow delete errors — the stream has already\n // finished and the client has the response.\n if (registered.ephemeral) {\n try {\n await this.threadStore.delete(thread.id, userId);\n } catch (err) {\n logger.warn(\n \"Failed to delete ephemeral thread %s: %O\",\n thread.id,\n err,\n );\n }\n }\n }\n outboundEvents.close();\n })();\n\n await this.executeStream<ResponseStreamEvent>(\n res,\n async function* () {\n try {\n for await (const ev of outboundEvents) {\n yield ev;\n }\n } finally {\n await driver.catch(() => undefined);\n }\n },\n {\n ...agentStreamDefaults,\n stream: { ...agentStreamDefaults.stream, streamId: requestId },\n },\n );\n }\n\n /**\n * Non-streaming counterpart to {@link _streamAgent} used by `/invocations`\n * and `/responses`. Drives the adapter to completion, persists the\n * assistant turn to the thread store, and returns a single JSON envelope\n * shaped like the OpenAI Responses non-streaming API.\n *\n * No `EventChannel`, no `AgentEventTranslator`, no SSE — the caller is\n * waiting on one HTTP response. The approval gate is force-disabled in\n * the per-run state as defense-in-depth: `_handleInvoke` already rejects\n * up-front if any tool in scope would require approval, but pinning\n * `requireForDestructive: false` here means a tool that somehow slips\n * past the precheck (e.g. annotations mutated at runtime) still won't\n * stall the request waiting for an approval prompt that no one can\n * answer.\n *\n * The `RunState` shape is otherwise unchanged so {@link dispatchToolCall}\n * — including sub-agent recursion via {@link runSubAgent} — keeps the\n * same tool-call budget, abort signal, and timeout enforcement as the\n * streaming path. A still-typed translator is constructed but only\n * consulted for `finalize()` so any in-flight `approval_pending` event\n * synthesis (which would have been a coding bug given the precheck) is\n * a dropped no-op instead of a runtime crash.\n */\n private async _runAgentNonStreaming(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: string,\n mlflowRunId?: string,\n ): Promise<void> {\n const abortController = new AbortController();\n const signal = abortController.signal;\n const requestId = randomUUID();\n this.trackStream(requestId, userId, abortController);\n\n const tools = Array.from(registered.toolIndex.values()).map((e) => e.def);\n const limits = this.resolvedLimits;\n\n // Assigned inside the span below (the only place the active trace id\n // resolves), read into the response envelope after.\n let mlflowTraceId: string | undefined;\n\n const runState: RunState = {\n req,\n userId,\n requestId,\n abortController,\n signal,\n // Force approval off for the non-streaming invoke surface. The\n // precheck in `_handleInvoke` already guarantees no approval-gated\n // tool is reachable; this is belt-and-braces.\n approvalPolicy: { requireForDestructive: false, timeoutMs: 0 },\n limits,\n translator: new AgentEventTranslator(),\n outboundEvents: new EventChannel<ResponseStreamEvent>(),\n toolCallsUsed: { count: 0 },\n };\n\n const deps = this.toolDispatchDeps();\n const executeTool = (name: string, args: unknown): Promise<unknown> =>\n dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);\n\n let fullContent = \"\";\n try {\n // Root MLflow span for the turn; tool-call spans nest under it. Mirrors\n // the streaming path so the invoke surface produces the same trace shape\n // instead of orphan root TOOL spans.\n await traceAgent(\n registered.name ?? \"agent\",\n {\n messages: thread.messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n },\n async (span) => {\n // Link this turn's trace to an eval run when the eval runner\n // supplied one, so the trace shows under the MLflow evaluation run.\n if (mlflowRunId) linkTraceToRun(mlflowRunId);\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n const fullPrompt = composePromptForAgent(\n registered,\n this.config.baseSystemPrompt,\n {\n agentName: registered.name,\n pluginNames,\n toolNames: tools.map((t) => t.name),\n },\n );\n\n const messagesWithSystem: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: fullPrompt,\n createdAt: new Date(),\n },\n ...thread.messages,\n ];\n\n const stream = registered.adapter.run(\n {\n messages: messagesWithSystem,\n tools,\n threadId: thread.id,\n signal,\n },\n { executeTool, signal },\n );\n\n fullContent = await consumeAdapterStream(stream, { signal });\n\n if (fullContent) {\n span.setOutputs({ role: \"assistant\", content: fullContent });\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\n });\n }\n\n mlflowTraceId = currentTraceId();\n },\n );\n } catch (error) {\n if (signal.aborted) {\n res.status(499).json({ error: \"Request aborted\" });\n return;\n }\n logger.error(\"Agent invoke error: %O\", error);\n const message =\n process.env.NODE_ENV === \"production\"\n ? \"Internal server error\"\n : error instanceof Error\n ? error.message\n : String(error);\n res.status(500).json({ error: message });\n return;\n } finally {\n this.approvalGate.abortStream(requestId);\n this.untrackStream(requestId);\n if (registered.ephemeral) {\n try {\n await this.threadStore.delete(thread.id, userId);\n } catch (err) {\n logger.warn(\n \"Failed to delete ephemeral thread %s: %O\",\n thread.id,\n err,\n );\n }\n }\n }\n\n const responseId = `resp_${randomUUID()}`;\n const messageId = `msg_${randomUUID()}`;\n const message: ResponseOutputMessage = {\n type: \"message\",\n id: messageId,\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: fullContent }],\n };\n res.json({\n id: responseId,\n object: \"response\",\n created_at: Math.floor(Date.now() / 1000),\n status: \"completed\",\n thread_id: thread.id,\n // Lets an eval runner attach assessments to this turn's trace; absent\n // when tracing is disabled.\n ...(mlflowTraceId ? { mlflow_trace_id: mlflowTraceId } : {}),\n output: [message],\n });\n }\n\n private dispatchSkillTool(\n entry: Extract<ResolvedToolEntry, { source: \"skill\" }>,\n args: unknown,\n ): Promise<string> {\n return dispatchSkillTool(entry, args, () => this.skillWorkspaceClient());\n }\n\n /**\n * Renders the prompt addendum for a force-loaded skill (`/skill-name`).\n * Returns null when the agent has no catalog or the name doesn't resolve —\n * an unusable request shouldn't fail the whole turn, so it's logged and the\n * model proceeds with the catalog + `load_skill` still available.\n */\n private renderForcedSkill(\n registered: RegisteredAgent,\n name: string,\n ): string | null {\n return renderForcedSkill(registered, name);\n }\n\n /** Collaborators the tool-dispatch path needs, bound to this instance. */\n private toolDispatchDeps(): ToolDispatchDeps {\n return {\n approvalGate: this.approvalGate,\n context: this.context,\n getMcpClient: () => this.mcpClient,\n agents: this.agents,\n dispatchSkillTool: (entry, args) => this.dispatchSkillTool(entry, args),\n pluginName: this.name,\n baseSystemPrompt: this.config.baseSystemPrompt,\n };\n }\n\n private async _handleCancel(req: express.Request, res: express.Response) {\n const parsed = cancelRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { streamId } = parsed.data;\n const entry = this.streams.get(streamId);\n if (!entry) {\n // Stream is unknown or already completed — idempotent no-op.\n res.json({ cancelled: true });\n return;\n }\n const userId = this.resolveUserId(req);\n if (entry.userId !== userId) {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n entry.controller.abort(\"Cancelled by user\");\n this.untrackStream(streamId);\n this.approvalGate.abortStream(streamId);\n res.json({ cancelled: true });\n }\n\n private async _handleApprove(req: express.Request, res: express.Response) {\n const parsed = approvalRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { streamId, approvalId, decision } = parsed.data;\n\n const streamEntry = this.streams.get(streamId);\n if (!streamEntry) {\n // Stream has already completed or never existed. Return 404 so the UI\n // knows the approval token is no longer valid (the waiter, if any, has\n // already been timed out or aborted).\n res.status(404).json({ error: \"Stream not found or already completed\" });\n return;\n }\n\n const userId = this.resolveUserId(req);\n if (streamEntry.userId !== userId) {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n\n const result = this.approvalGate.submit({ approvalId, userId, decision });\n if (!result.ok) {\n if (result.reason === \"forbidden\") {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n res.status(404).json({ error: \"Approval not found or already settled\" });\n return;\n }\n\n res.json({ decision });\n }\n\n private async _handleListThreads(\n req: express.Request,\n res: express.Response,\n ) {\n const userId = this.resolveUserId(req);\n const threads = await this.threadStore.list(userId);\n res.json({ threads });\n }\n\n private async _handleGetThread(req: express.Request, res: express.Response) {\n const userId = this.resolveUserId(req);\n const thread = await this.threadStore.get(req.params.threadId, userId);\n if (!thread) {\n res.status(404).json({ error: \"Thread not found\" });\n return;\n }\n res.json(thread);\n }\n\n private async _handleDeleteThread(\n req: express.Request,\n res: express.Response,\n ) {\n const userId = this.resolveUserId(req);\n const deleted = await this.threadStore.delete(req.params.threadId, userId);\n if (!deleted) {\n res.status(404).json({ error: \"Thread not found\" });\n return;\n }\n res.json({ deleted: true });\n }\n\n private resolveAgent(name?: string): RegisteredAgent | null {\n if (name) return this.agents.get(name) ?? null;\n if (this.defaultAgentName) {\n return this.agents.get(this.defaultAgentName) ?? null;\n }\n const first = this.agents.values().next();\n return first.done ? null : first.value;\n }\n\n private printRegistry(): void {\n if (this.agents.size === 0) return;\n console.log(\"\");\n console.log(` ${pc.bold(\"Agents\")} ${pc.dim(`(${this.agents.size})`)}`);\n console.log(` ${pc.dim(\"─\".repeat(60))}`);\n for (const [name, reg] of this.agents) {\n const tools = reg.toolIndex.size;\n const marker = name === this.defaultAgentName ? pc.green(\"●\") : \" \";\n console.log(\n ` ${marker} ${pc.bold(name.padEnd(24))} ${pc.dim(`${tools} tools`)}`,\n );\n }\n console.log(` ${pc.dim(\"─\".repeat(60))}`);\n console.log(\"\");\n }\n\n async shutdown(): Promise<void> {\n this.approvalGate.abortAll();\n if (this.mcpClient) {\n await this.mcpClient.close();\n this.mcpClient = null;\n }\n }\n\n exports() {\n return {\n register: (name: string, def: AgentDefinition) =>\n this.registerCodeAgent(name, def),\n list: () => Array.from(this.agents.keys()),\n get: (name: string) => this.agents.get(name) ?? null,\n reload: () => this.reload(),\n getDefault: () => this.defaultAgentName,\n getThreads: (userId: string) => this.threadStore.list(userId),\n };\n }\n\n private async registerCodeAgent(\n name: string,\n def: AgentDefinition,\n ): Promise<void> {\n const registered = await this.buildRegisteredAgent(name, def, {\n origin: \"code\",\n });\n this.agents.set(name, registered);\n if (!this.defaultAgentName) this.defaultAgentName = name;\n }\n}\n\nfunction normalizeAutoInherit(value: AgentsPluginConfig[\"autoInheritTools\"]): {\n file: boolean;\n code: boolean;\n} {\n // Default is opt-out for both origins. A markdown agent or code-defined\n // agent with no declared `tools:` gets an empty tool index unless the\n // developer explicitly flips `autoInheritTools` on. Even then, only tools\n // whose plugin author marked `autoInheritable: true` are spread — see\n // `applyAutoInherit` for the filter.\n if (value === undefined) return { file: false, code: false };\n if (typeof value === \"boolean\") return { file: value, code: value };\n return { file: value.file ?? false, code: value.code ?? false };\n}\n\n/**\n * Plugin factory for the agents plugin. Discovers agents from\n * `server/agents/<id>/agent.{ts,md}` by default (markdown still in\n * `config/agents/` is read as a deprecated fallback), resolves toolkits/tools\n * from registered plugins, exposes the `appkit.agents.*` runtime API and mounts\n * `POST /invocations` and `POST /responses` (aliased non-streaming invoke\n * endpoints) plus `POST /chat` (streaming, HITL-capable).\n *\n * @example\n * ```ts\n * import { agents, analytics, createApp, server } from \"@databricks/appkit\";\n *\n * await createApp({\n * plugins: [server(), analytics(), agents()],\n * });\n * ```\n */\nexport const agents = toPlugin(AgentsPlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,MAAM,SAAS,aAAa,SAAS;;AAGrC,MAAM,sBAAsB;AAE5B,IAAa,eAAb,cAAkC,OAA+B;CAC/D,OAAO,WAAW,eAAyBA,iBAAS;CACpD,OAAO,QAAqB;CAI5B,AAAQ,yBAAS,IAAI,KAA8B;CACnD,AAAQ,mBAAkC;;;;;CAK1C,AAAQ,UAAU,IAAI,qBAAqB;CAC3C,AAAQ,YAAoC;CAC5C,AAAQ;CACR,AAAQ,eAAe,IAAI,kBAAkB;;CAE7C,AAAQ,6BAA6B;;CAErC,AAAQ,gCAAgC;CAExC,YAAY,QAA4B;AACtC,QAAM,OAAO;AACb,OAAK,SAAS;AACd,MAAI,OAAO,YACT,MAAK,cAAc,OAAO;OACrB;AACL,QAAK,cAAc,IAAI,qBAAqB;AAC5C,OAAI,QAAQ,IAAI,aAAa,aAC3B,QAAO,KACL,oMAGD;OAED,QAAO,KACL,qGACD;;;;;;;;;;;;;;;;;;CAoBP,AAAQ,eAAkC,EAAE;CAE5C,AAAQ,uBAGG;CAEX,IAAY,yBAGV;AACA,MAAI,KAAK,qBAAsB,QAAO,KAAK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AAM;EAAO,MAAM;EAAO;AAC5D,KAAI,OAAO,UAAU,UAAW,QAAO;EAAE,MAAM;EAAO,MAAM;EAAO;AACnE,QAAO;EAAE,MAAM,MAAM,QAAQ;EAAO,MAAM,MAAM,QAAQ;EAAO;;;;;;;;;;;;;;;;;;;AAoBjE,MAAa,SAAS,SAAS,aAAa"}
1
+ {"version":3,"file":"agents.js","names":["manifest"],"sources":["../../../src/plugins/agents/agents.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type express from \"express\";\nimport pc from \"picocolors\";\nimport type {\n AgentAdapter,\n AgentToolDefinition,\n IAppRouter,\n Message,\n PluginPhase,\n ResponseOutputMessage,\n ResponseStreamEvent,\n Thread,\n ToolProvider,\n} from \"shared\";\n\nimport { isSupervisorTool } from \"../../agents/supervisor-api\";\nimport { AppKitMcpClient, buildMcpHostPolicy } from \"../../connectors/mcp\";\nimport { getWorkspaceClient } from \"../../context\";\nimport { consumeAdapterStream } from \"../../core/agent/consume-adapter-stream\";\nimport { loadAgentsFromDir } from \"../../core/agent/load-agents\";\nimport { CODE_AGENTS_SOURCE_DIR } from \"../../core/agent/load-code-agents\";\nimport { createPluginsProxy } from \"../../core/agent/plugins-map\";\nimport type {\n ResolvedSkillCatalog,\n SkillDefinition,\n} from \"../../core/agent/skills\";\nimport { resolveToolkitFromProvider } from \"../../core/agent/toolkit-resolver\";\nimport {\n functionToolToDefinition,\n isFunctionTool,\n isHostedTool,\n resolveHostedTools,\n} from \"../../core/agent/tools\";\nimport type {\n AgentDefinition,\n AgentsPluginConfig,\n AgentTools,\n Plugins,\n PluginToolkitProvider,\n RegisteredAgent,\n ResolvedToolEntry,\n} from \"../../core/agent/types\";\nimport { isToolkitEntry } from \"../../core/agent/types\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } from \"../../registry\";\nimport type { WorkspaceClient } from \"../../workspace-client\";\nimport { ActiveStreamTracker } from \"./active-stream-tracker\";\nimport {\n buildAdapterExtensions,\n supervisorToolDescription,\n warnOnCapabilityMismatch,\n} from \"./adapter-extensions\";\nimport { requiresApproval } from \"./approval\";\nimport { LOAD_SKILL_TOOL_DEF, READ_SKILL_FILE_TOOL_DEF } from \"./builtin-tools\";\nimport { agentStreamDefaults } from \"./defaults\";\nimport { EventChannel } from \"./event-channel\";\nimport { AgentEventTranslator } from \"./event-translator\";\nimport manifest from \"./manifest.json\";\nimport {\n currentTraceId,\n initAgentTracing,\n linkTraceToRun,\n traceAgent,\n} from \"./mlflow\";\nimport { composePromptForAgent } from \"./prompt\";\nimport {\n type AgentSource,\n loadCodeAgents,\n resolveDefaultAgent,\n} from \"./registry\";\nimport { resolveApprovalPolicy, resolveLimits } from \"./resolve-config\";\nimport {\n approvalRequestSchema,\n cancelRequestSchema,\n chatRequestSchema,\n invocationsRequestSchema,\n} from \"./schemas\";\nimport {\n dispatchSkillTool,\n loadGlobalSkills,\n loadVolumeSkills,\n renderForcedSkill,\n resolveAgentSkills,\n} from \"./skill-loader\";\nimport { InMemoryThreadStore } from \"./thread-store\";\nimport { ToolApprovalGate } from \"./tool-approval-gate\";\nimport {\n dispatchToolCall,\n type RunState,\n type ToolDispatchDeps,\n} from \"./tool-dispatch\";\n\nconst logger = createLogger(\"agents\");\n\n/** Deprecated markdown location, read as a fallback with a one-time warning. */\nconst LEGACY_MARKDOWN_DIR = \"config/agents\";\n\nexport class AgentsPlugin extends Plugin implements ToolProvider {\n static manifest = defineManifest<\"agents\">(manifest);\n static phase: PluginPhase = \"deferred\";\n\n declare protected config: AgentsPluginConfig;\n\n private agents = new Map<string, RegisteredAgent>();\n private defaultAgentName: string | null = null;\n /**\n * Active SSE streams + per-user counts (the O(1) concurrency-limit check).\n * Mutated only via {@link trackStream} / {@link untrackStream}.\n */\n private streams = new ActiveStreamTracker();\n private mcpClient: AppKitMcpClient | null = null;\n private threadStore;\n private approvalGate = new ToolApprovalGate();\n /** Guards the `agents({ agents })` deprecation warning to once per instance. */\n private agentsMapDeprecationWarned = false;\n /** Guards the `config/agents` deprecation warning to once per instance. */\n private configAgentsDeprecationWarned = false;\n\n constructor(config: AgentsPluginConfig) {\n super(config);\n this.config = config;\n if (config.threadStore) {\n this.threadStore = config.threadStore;\n } else {\n this.threadStore = new InMemoryThreadStore();\n if (process.env.NODE_ENV === \"production\") {\n logger.warn(\n \"InMemoryThreadStore is in use in a production build (NODE_ENV=production). \" +\n \"Thread history is unbounded and lost on restart. \" +\n \"Pass agents({ threadStore: <persistent impl> }) for real deployments.\",\n );\n } else {\n logger.info(\n \"Using default InMemoryThreadStore (dev-only — threads are lost on restart and grow without bound).\",\n );\n }\n }\n }\n\n /**\n * Effective approval policy with defaults applied. Memoised so the\n * `timeoutMs` validation warning fires at most once per plugin instance —\n * `resolvedApprovalPolicy` gets hit on every chat stream and a noisy\n * misconfig would otherwise spam the logs.\n *\n * `timeoutMs` is clamped to a 1s floor so a misconfigured value (`0`,\n * negative, or `NaN`) can't degrade into immediate auto-denial of every\n * mutating tool call.\n */\n /**\n * Shared global skill pool (bundle `skills/` + catalog volume), loaded once\n * per registry build. Read by {@link buildRegisteredAgent} to resolve each\n * agent's visible catalog and by the live `register` path.\n */\n private globalSkills: SkillDefinition[] = [];\n\n private cachedApprovalPolicy: {\n requireForDestructive: boolean;\n timeoutMs: number;\n } | null = null;\n\n private get resolvedApprovalPolicy(): {\n requireForDestructive: boolean;\n timeoutMs: number;\n } {\n if (this.cachedApprovalPolicy) return this.cachedApprovalPolicy;\n this.cachedApprovalPolicy = resolveApprovalPolicy(this.config);\n return this.cachedApprovalPolicy;\n }\n\n /** Effective DoS limits with defaults applied. */\n private get resolvedLimits(): {\n maxConcurrentStreamsPerUser: number;\n maxToolCalls: number;\n maxSubAgentDepth: number;\n toolCallTimeoutMs: number;\n } {\n return resolveLimits(this.config);\n }\n\n /** Count active streams owned by a given user. O(1). */\n private countUserStreams(userId: string): number {\n return this.streams.count(userId);\n }\n\n private trackStream(\n requestId: string,\n userId: string,\n controller: AbortController,\n ): void {\n this.streams.track(requestId, userId, controller);\n }\n\n private untrackStream(requestId: string): void {\n this.streams.untrack(requestId);\n }\n\n async setup() {\n await initAgentTracing();\n const { agents, defaultAgentName } = await this.buildAgentRegistry();\n this.agents = agents;\n this.defaultAgentName = defaultAgentName;\n this.mountInvokeRoutes();\n this.printRegistry();\n }\n\n /**\n * Reload agents from the configured directory, preserving code-defined\n * agents. Builds a fresh registry first and only swaps on success — if\n * `loadAgents` throws (malformed markdown, missing tool reference) the\n * existing live registry stays in place and serving requests keep working.\n */\n async reload(): Promise<void> {\n const next = await this.buildAgentRegistry();\n // Deliberately NOT closing the existing mcpClient here. Tool\n // dispatch in `dispatchToolCall` reads `this.mcpClient` at call\n // time; closing it mid-stream throws \"MCP client is closed\" from\n // the next sendRpc and kills the in-flight conversation. The\n // client owns only short-lived `fetch` handles (no keep-alive\n // sockets) and the connections map persists in the live instance,\n // so dropping `this.mcpClient` would also strand in-flight tool\n // calls that resolved the field a moment earlier. Leave the live\n // client in place; `buildAgentRegistry` -> `connectHostedTools`\n // adds any new endpoints to the same instance, and stale\n // connections from a removed config become unreachable through\n // the new agent tool indexes (small memory cost, no correctness\n // hazard). The shutdown path still closes — that's process\n // teardown, where in-flight streams have already been aborted via\n // `abortActiveOperations`.\n this.agents = next.agents;\n this.defaultAgentName = next.defaultAgentName;\n }\n\n /**\n * Builds the agent registry into a fresh `Map` without touching live state.\n * Called by both `setup` and `reload`; the latter only swaps the live\n * registry once this resolves successfully (atomic reload).\n */\n private async buildAgentRegistry(): Promise<{\n agents: Map<string, RegisteredAgent>;\n defaultAgentName: string | null;\n }> {\n // Two \"code\" sources: discovered files and the deprecated `agents({ agents })` map.\n const discovered = await this.loadCodeAgents();\n const deprecatedMapRaw = this.config.agents ?? {};\n\n // Global skills (bundle + configured UC volume) load in parallel; per-agent\n // skills resolve later during agent build.\n const [bundleSkills, volumeSkills] = await Promise.all([\n this.loadGlobalSkills(),\n this.loadVolumeSkills(),\n ]);\n this.globalSkills = [...bundleSkills, ...volumeSkills];\n\n if (Object.keys(deprecatedMapRaw).length > 0) {\n this.warnAgentsMapDeprecated();\n }\n\n // On a discovered/map id clash, discovery wins (drop the map entry) rather\n // than crash boot on upgrade.\n const deprecatedMap: Record<string, AgentDefinition> = {};\n for (const [id, def] of Object.entries(deprecatedMapRaw)) {\n if (discovered[id]) {\n logger.warn(\n \"Agent '%s' is both discovered in %s and passed to agents({ agents }). \" +\n \"Using the discovered file; ignoring the map entry.\",\n id,\n CODE_AGENTS_SOURCE_DIR,\n );\n continue;\n }\n deprecatedMap[id] = def;\n }\n\n // Code agents also resolve markdown `agents: [child]` sub-agent references.\n const codeAgents: Record<string, AgentDefinition> = {\n ...discovered,\n ...deprecatedMap,\n };\n\n const { defs: fileDefs, defaultAgent: fileDefault } =\n await this.loadFileDefinitions(codeAgents);\n\n // Merge order (markdown, discovered, map) sets precedence and the\n // first-registered default fallback.\n const merged: Record<string, { def: AgentDefinition; src: AgentSource }> =\n {};\n for (const [name, def] of Object.entries(fileDefs)) {\n merged[name] = { def, src: { origin: \"file\" } };\n }\n for (const [name, def] of Object.entries(discovered)) {\n if (merged[name]?.src.origin === \"file\") {\n // Discovery is new API — clash with markdown is a hard error (the\n // deprecated map only warns). A folder with both agent.ts and\n // agent.md lands here too: one kind per folder.\n throw new Error(\n `Agent '${name}' is defined as both a code agent (agent.ts) and a markdown agent (agent.md) — ` +\n `in one folder, or across server/agents and the deprecated config/agents fallback. ` +\n `Keep a single kind per id. Available: ${Object.keys(merged).sort().join(\", \")}`,\n );\n }\n merged[name] = { def, src: { origin: \"code\" } };\n }\n for (const [name, def] of Object.entries(deprecatedMap)) {\n if (merged[name]?.src.origin === \"file\") {\n logger.warn(\n \"Agent '%s' defined in both code and a markdown file. Code definition takes precedence.\",\n name,\n );\n }\n merged[name] = { def, src: { origin: \"code\" } };\n }\n\n const agents = new Map<string, RegisteredAgent>();\n\n if (Object.keys(merged).length === 0) {\n logger.info(\n \"No agents registered (no files in %s, no discovered or code-defined agents)\",\n this.resolvedAgentsDir(),\n );\n return { agents, defaultAgentName: null };\n }\n\n for (const [name, { def, src }] of Object.entries(merged)) {\n try {\n agents.set(name, await this.buildRegisteredAgent(name, def, src));\n } catch (err) {\n throw new Error(\n `Failed to register agent '${name}' (${src.origin}): ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n\n return {\n agents,\n defaultAgentName: this.resolveDefaultAgent(agents, merged, fileDefault),\n };\n }\n\n /**\n * Resolves the default agent. Precedence: explicit `config.defaultAgent` >\n * a code/discovered agent flagged `default: true` (stable id order) >\n * markdown `default: true` > first registered (insertion order).\n */\n private resolveDefaultAgent(\n agents: Map<string, RegisteredAgent>,\n merged: Record<string, { def: AgentDefinition; src: AgentSource }>,\n fileDefault: string | null,\n ): string | null {\n return resolveDefaultAgent(\n agents,\n merged,\n fileDefault,\n this.config.defaultAgent,\n );\n }\n\n /**\n * Emits the one-time deprecation warning for the `agents({ agents })` map.\n * Guarded so `reload()` (which re-runs `buildAgentRegistry`) doesn't spam it.\n */\n private warnAgentsMapDeprecated(): void {\n if (this.agentsMapDeprecationWarned) return;\n this.agentsMapDeprecationWarned = true;\n logger.warn(\n \"agents({ agents: { ... } }) is deprecated. Put each code agent in its own folder under \" +\n \"server/agents/<id>/agent.ts (export default createAgent({ ... })) and it is discovered \" +\n \"automatically — the call collapses to agents({ ... }) with no agent map. The `agents` field \" +\n \"still works but will be removed in a future minor. See docs/plugins/agents.md.\",\n );\n }\n\n /**\n * One-time deprecation warning for markdown agents still living in\n * `config/agents/`. Guarded so `reload()` doesn't spam it.\n */\n private warnConfigAgentsDeprecated(): void {\n if (this.configAgentsDeprecationWarned) return;\n this.configAgentsDeprecationWarned = true;\n logger.warn(\n \"Markdown agents under config/agents/ are deprecated. Move each config/agents/<id>/agent.md to \" +\n \"server/agents/<id>/agent.md — every agent now lives in one place (server/agents). config/agents \" +\n \"is still read for now but will be removed in a future minor. See docs/plugins/agents.md.\",\n );\n }\n\n private resolvedAgentsDir(): string {\n return path.resolve(process.cwd(), CODE_AGENTS_SOURCE_DIR);\n }\n\n private loadCodeAgents(): Promise<Record<string, AgentDefinition>> {\n return loadCodeAgents({\n agentsDir: this.resolvedAgentsDir(),\n hasDeprecatedMap: Object.keys(this.config.agents ?? {}).length > 0,\n });\n }\n\n private async loadFileDefinitions(\n codeAgents: Record<string, AgentDefinition>,\n ): Promise<{\n defs: Record<string, AgentDefinition>;\n defaultAgent: string | null;\n }> {\n const primaryDir = this.resolvedAgentsDir();\n\n // Discovered code agents + the deprecated map resolve markdown `agents:`\n // sub-agent references, so a markdown parent can delegate to a code child.\n const baseCtx = {\n defaultModel: this.config.defaultModel,\n availableTools: this.config.tools ?? {},\n plugins: this.pluginProviderIndex(),\n };\n\n const legacyDir = path.resolve(process.cwd(), LEGACY_MARKDOWN_DIR);\n\n // Common case: no deprecated config/agents/ dir → a single scan of server/agents.\n if (!existsSync(legacyDir)) {\n return loadAgentsFromDir(primaryDir, { ...baseCtx, codeAgents });\n }\n\n // Deprecated fallback: config/agents/ exists → scan it first, then server/agents\n // with the legacy defs added as resolvable sub-agent targets, so a parent already\n // moved to server/agents can still reference a child left in config/agents\n // mid-migration. Code agents keep precedence; server/agents wins on an id clash.\n const legacy = await loadAgentsFromDir(legacyDir, {\n ...baseCtx,\n codeAgents,\n });\n const primary = await loadAgentsFromDir(primaryDir, {\n ...baseCtx,\n codeAgents: { ...legacy.defs, ...codeAgents },\n });\n\n if (Object.keys(legacy.defs).length === 0) return primary;\n\n this.warnConfigAgentsDeprecated();\n return {\n defs: { ...legacy.defs, ...primary.defs },\n defaultAgent: primary.defaultAgent ?? legacy.defaultAgent,\n };\n }\n\n /**\n * Builds the map of plugin-name → toolkit that the markdown loader consults\n * when resolving `plugin:NAME` entries in the unified `tools:` frontmatter\n * list (and, equivalently, that the code form passes as the `plugins`\n * argument to `tools(plugins) => Record<...>`).\n */\n private pluginProviderIndex(): Map<\n string,\n { toolkit: (opts?: unknown) => Record<string, unknown> }\n > {\n const out = new Map();\n if (!this.context) return out;\n for (const { name, provider } of this.context.getToolProviders()) {\n const withToolkit = provider as ToolProvider & {\n toolkit?: (opts?: unknown) => Record<string, unknown>;\n };\n if (typeof withToolkit.toolkit === \"function\") {\n out.set(name, {\n toolkit: withToolkit.toolkit.bind(withToolkit),\n });\n }\n }\n return out;\n }\n\n private async buildRegisteredAgent(\n name: string,\n def: AgentDefinition,\n src: AgentSource,\n ): Promise<RegisteredAgent> {\n const adapter = await this.resolveAdapter(def, name);\n const skills = await this.resolveAgentSkills(name, def, src);\n const toolIndex = await this.buildToolIndex(name, def, src, skills);\n\n warnOnCapabilityMismatch(name, adapter, toolIndex);\n\n return {\n name,\n instructions: def.instructions,\n adapter,\n toolIndex,\n baseSystemPrompt: def.baseSystemPrompt,\n maxSteps: def.maxSteps,\n maxTokens: def.maxTokens,\n generationParams: def.generationParams,\n ephemeral: def.ephemeral,\n skills,\n };\n }\n\n /** Loads the shared global skill pool from `<agentsDir>/skills/`. */\n private loadGlobalSkills(): Promise<SkillDefinition[]> {\n return loadGlobalSkills(this.resolvedAgentsDir());\n }\n\n /**\n * Workspace client used to read catalog skills. v1 reads as the app service\n * principal; `getWorkspaceClient()` resolves to SP outside a user scope\n * (boot and skill-tool dispatch are both unscoped). This is the single\n * switch point for a future OBO mode.\n */\n private skillWorkspaceClient(): WorkspaceClient {\n return getWorkspaceClient();\n }\n\n /** Discovers catalog skills from the configured UC Volume (best-effort). */\n private loadVolumeSkills(): Promise<SkillDefinition[]> {\n return loadVolumeSkills(this.config, () => this.skillWorkspaceClient());\n }\n\n private async resolveAgentSkills(\n name: string,\n def: AgentDefinition,\n src: AgentSource,\n ): Promise<RegisteredAgent[\"skills\"]> {\n const inherit = normalizeAutoInherit(this.config.autoInheritSkills);\n return resolveAgentSkills({\n name,\n def,\n agentsDir: this.resolvedAgentsDir(),\n isFileOrigin: src.origin === \"file\",\n autoInherit: src.origin === \"file\" ? inherit.file : inherit.code,\n globalSkills: this.globalSkills,\n });\n }\n\n private async resolveAdapter(\n def: AgentDefinition,\n name: string,\n ): Promise<AgentAdapter> {\n const source = def.model ?? this.config.defaultModel;\n // Per-agent adapter knobs from `AgentDefinition` / markdown frontmatter.\n // Only applied when AppKit builds the adapter itself (string or omitted\n // model). Users who pass a pre-built `AgentAdapter` own these settings.\n const adapterOptions: {\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: AgentDefinition[\"generationParams\"];\n } = {};\n if (def.maxSteps !== undefined) adapterOptions.maxSteps = def.maxSteps;\n if (def.maxTokens !== undefined) adapterOptions.maxTokens = def.maxTokens;\n if (def.generationParams !== undefined)\n adapterOptions.generationParams = def.generationParams;\n\n if (!source) {\n const { DatabricksAdapter } = await import(\"../../agents/databricks\");\n try {\n return await DatabricksAdapter.fromModelServing(\n undefined,\n adapterOptions,\n );\n } catch (err) {\n throw new Error(\n `Agent '${name}' has no model configured and no DATABRICKS_SERVING_ENDPOINT_NAME default available`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n if (typeof source === \"string\") {\n const { DatabricksAdapter } = await import(\"../../agents/databricks\");\n return DatabricksAdapter.fromModelServing(source, adapterOptions);\n }\n return await source;\n }\n\n /**\n * Resolves an agent's tool record into a per-agent dispatch index. Connects\n * hosted tools via MCP client. Applies `autoInheritTools` defaults when the\n * definition has no declared tools/agents.\n */\n private async buildToolIndex(\n agentName: string,\n def: AgentDefinition,\n src: AgentSource,\n skills?: ResolvedSkillCatalog,\n ): Promise<Map<string, ResolvedToolEntry>> {\n const index = new Map<string, ResolvedToolEntry>();\n const hasDeclaredTools = def.tools !== undefined;\n const toolsRecord = this.resolveDefTools(agentName, def);\n const hasExplicitSubAgents =\n def.agents && Object.keys(def.agents).length > 0;\n\n const inheritDefaults = normalizeAutoInherit(this.config.autoInheritTools);\n // Declaring `tools` (object or function, even an empty record) opts out\n // of auto-inherit. Same rule for both forms — see plan decision (E1/I1).\n const shouldInherit =\n !hasDeclaredTools &&\n !hasExplicitSubAgents &&\n (src.origin === \"file\" ? inheritDefaults.file : inheritDefaults.code);\n\n if (shouldInherit) {\n await this.applyAutoInherit(agentName, index);\n }\n\n // 1. Sub-agents → agent-<key>\n for (const [childKey, childDef] of Object.entries(def.agents ?? {})) {\n const toolName = `agent-${childKey}`;\n index.set(toolName, {\n source: \"subagent\",\n agentName: childDef.name ?? childKey,\n def: {\n name: toolName,\n description:\n childDef.instructions.slice(0, 120) ||\n `Delegate to the ${childKey} sub-agent`,\n parameters: {\n type: \"object\",\n properties: {\n input: {\n type: \"string\",\n description: \"Message to send to the sub-agent.\",\n },\n },\n required: [\"input\"],\n },\n },\n });\n }\n\n // 2. Explicit tools (toolkit entries, function tools, hosted tools)\n const hostedToCollect: import(\"../../core/agent/tools/hosted-tools\").HostedTool[] =\n [];\n for (const [key, tool] of Object.entries(toolsRecord)) {\n if (isToolkitEntry(tool)) {\n index.set(key, {\n source: \"toolkit\",\n pluginName: tool.pluginName,\n localName: tool.localName,\n def: { ...tool.def, name: key },\n });\n continue;\n }\n if (isFunctionTool(tool)) {\n index.set(key, {\n source: \"function\",\n functionTool: tool,\n def: { ...functionToolToDefinition(tool), name: key },\n });\n continue;\n }\n if (isSupervisorTool(tool)) {\n index.set(key, {\n source: \"hosted-supervisor\",\n spec: tool.spec,\n def: {\n // `def` is a placeholder so the index has a uniform shape; it\n // is intentionally not passed to the adapter's `tools` array\n // (the SA endpoint owns its own tool execution and would\n // reject our synthetic schema).\n name: key,\n description: supervisorToolDescription(tool.spec),\n parameters: { type: \"object\", properties: {} },\n },\n });\n continue;\n }\n if (isHostedTool(tool)) {\n hostedToCollect.push(tool);\n continue;\n }\n throw new Error(\n `Agent '${agentName}' tool '${key}' has an unrecognized shape`,\n );\n }\n\n if (hostedToCollect.length > 0) {\n await this.connectHostedTools(hostedToCollect, index);\n }\n\n // 3. Built-in skill tools, present only when this agent has a visible\n // catalog. Injected last so they reliably shadow any same-named tool.\n if (skills && skills.byAddress.size > 0) {\n index.set(\"load_skill\", {\n source: \"skill\",\n builtin: \"load_skill\",\n catalog: skills,\n def: LOAD_SKILL_TOOL_DEF,\n });\n index.set(\"read_skill_file\", {\n source: \"skill\",\n builtin: \"read_skill_file\",\n catalog: skills,\n def: READ_SKILL_FILE_TOOL_DEF,\n });\n }\n\n return index;\n }\n\n /**\n * Resolves an `AgentDefinition.tools` field to a plain tool record. The\n * function form is invoked exactly once at agent setup with the typed\n * {@link Plugins} map; the result replaces the function reference for the\n * remainder of the registered agent's lifetime.\n *\n * Plain object form is returned as-is; an undefined `tools` returns an\n * empty record. The function form is wrapped in a try/catch so a thrown\n * callback fails registration with a useful message instead of leaking\n * the raw stack.\n */\n private resolveDefTools(agentName: string, def: AgentDefinition): AgentTools {\n if (typeof def.tools !== \"function\") {\n return def.tools ?? {};\n }\n try {\n return def.tools(this.buildPluginsMap());\n } catch (err) {\n throw new Error(\n `Agent '${agentName}': tools(plugins) callback threw: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err instanceof Error ? err : undefined },\n );\n }\n }\n\n /**\n * Builds the typed {@link Plugins} map passed to the function form of\n * `AgentDefinition.tools`. Each entry exposes the plugin instance directly\n * (so user code can call typed instance methods including `.toolkit()`);\n * plugins missing `.toolkit()` get a synthesized fallback that walks\n * `getAgentTools()` via `resolveToolkitFromProvider`.\n *\n * Wrapped in {@link createPluginsProxy} so that accessing an unknown\n * plugin name throws a named \"not registered, Available: ...\" error\n * instead of bubbling up a generic `Cannot read properties of undefined`\n * from the agent's `tools(plugins)` callback.\n */\n private buildPluginsMap(): Plugins {\n const out: Record<string, PluginToolkitProvider> = {};\n const label = `Agent '${this.name}': tools(plugins)`;\n if (!this.context) {\n return createPluginsProxy(out, label);\n }\n for (const { name, provider } of this.context.getToolProviders()) {\n const direct = (provider as { toolkit?: unknown }).toolkit;\n if (typeof direct === \"function\") {\n out[name] = provider as unknown as PluginToolkitProvider;\n } else {\n out[name] = {\n toolkit: (opts) => resolveToolkitFromProvider(name, provider, opts),\n };\n }\n }\n // Registered plugins that expose no agent tools (e.g. aiSearch) — so a\n // reference reports \"not a ToolProvider\", not the misleading \"not registered\".\n const nonProviders = new Set(\n this.context.getPluginNames().filter((n) => !(n in out)),\n );\n return createPluginsProxy(out, label, nonProviders);\n }\n\n private async applyAutoInherit(\n agentName: string,\n index: Map<string, ResolvedToolEntry>,\n ): Promise<void> {\n if (!this.context) return;\n const inherited: string[] = [];\n const skippedByPlugin = new Map<string, string[]>();\n const recordSkip = (pluginName: string, localName: string) => {\n const list = skippedByPlugin.get(pluginName) ?? [];\n list.push(localName);\n skippedByPlugin.set(pluginName, list);\n };\n\n for (const {\n name: pluginName,\n provider,\n } of this.context.getToolProviders()) {\n if (pluginName === this.name) continue;\n const entries = resolveToolkitFromProvider(pluginName, provider);\n for (const [key, entry] of Object.entries(entries)) {\n if (entry.autoInheritable !== true) {\n recordSkip(entry.pluginName, entry.localName);\n continue;\n }\n index.set(key, {\n source: \"toolkit\",\n pluginName: entry.pluginName,\n localName: entry.localName,\n def: { ...entry.def, name: key },\n });\n inherited.push(key);\n }\n }\n\n if (inherited.length > 0) {\n logger.info(\n \"[agent %s] auto-inherited %d tool(s): %s\",\n agentName,\n inherited.length,\n inherited.join(\", \"),\n );\n }\n if (skippedByPlugin.size > 0) {\n const summary = Array.from(skippedByPlugin.entries())\n .map(([p, tools]) => `${p}(${tools.length})`)\n .join(\", \");\n logger.info(\n \"[agent %s] auto-inherit skipped %d tool(s) not marked autoInheritable: %s. Wire them explicitly via `tools:` if needed.\",\n agentName,\n Array.from(skippedByPlugin.values()).reduce(\n (n, list) => n + list.length,\n 0,\n ),\n summary,\n );\n }\n }\n\n private async connectHostedTools(\n hostedTools: import(\"../../core/agent/tools/hosted-tools\").HostedTool[],\n index: Map<string, ResolvedToolEntry>,\n ): Promise<void> {\n let host: string | undefined;\n let authenticate: () => Promise<Record<string, string>>;\n\n try {\n const { getWorkspaceClient } = await import(\"../../context\");\n const wsClient = getWorkspaceClient();\n await wsClient.config.ensureResolved();\n host = wsClient.config.host;\n authenticate = async () => {\n const headers = new Headers();\n await wsClient.config.authenticate(headers);\n return Object.fromEntries(headers.entries());\n };\n } catch {\n host = process.env.DATABRICKS_HOST;\n authenticate = async (): Promise<Record<string, string>> => {\n const token = process.env.DATABRICKS_TOKEN;\n return token ? { Authorization: `Bearer ${token}` } : {};\n };\n }\n\n if (!host) {\n logger.warn(\n \"No Databricks host available — skipping %d hosted tool(s)\",\n hostedTools.length,\n );\n return;\n }\n\n if (!this.mcpClient) {\n const policy = buildMcpHostPolicy(this.config.mcp, host);\n this.mcpClient = new AppKitMcpClient(host, authenticate, policy);\n }\n\n const endpoints = resolveHostedTools(hostedTools);\n const result = await this.mcpClient.connectAll(endpoints);\n if (result.failed.length > 0) {\n // Per-endpoint errors are already logged inside `connectAll`; this\n // aggregate warning makes the partial-success state visible at the\n // agent-registration boundary so operators see \"agent X registered\n // without N hosted-tool endpoints\" alongside the connect-time\n // errors, instead of just an opaque list of MCP failures.\n logger.warn(\n \"MCP: %s of %s endpoints failed to connect (%s). Agents that reference these endpoints will boot without their hosted tools.\",\n result.failed.length,\n endpoints.length,\n result.failed.map((f) => f.name).join(\", \"),\n );\n }\n\n for (const def of this.mcpClient.getAllToolDefinitions()) {\n index.set(def.name, {\n source: \"mcp\",\n mcpToolName: def.name,\n def,\n });\n }\n }\n\n // ----------------- ToolProvider (no tools of our own) --------------------\n\n getAgentTools(): AgentToolDefinition[] {\n return [];\n }\n\n async executeAgentTool(): Promise<unknown> {\n throw new Error(\"AgentsPlugin does not expose executeAgentTool directly\");\n }\n\n // ----------------- Route mounting and handlers ---------------------------\n\n /**\n * Mount the non-streaming invoke endpoints outside the `/api/<plugin>`\n * namespace. `/invocations` and `/responses` are aliases — both run the\n * default agent to completion and return a single JSON response. Streaming\n * lives on `POST /chat` (mounted in `injectRoutes`).\n */\n private mountInvokeRoutes() {\n if (!this.context) return;\n // Return the promise so the forwardAsyncErrors wrapper applied by\n // PluginContext.addRoute can forward rejections to the error middleware.\n const handler = (req: express.Request, res: express.Response) =>\n this._handleInvoke(req, res);\n this.context.addRoute(\"post\", \"/invocations\", handler);\n this.context.addRoute(\"post\", \"/responses\", handler);\n }\n\n injectRoutes(router: IAppRouter) {\n this.route(router, {\n name: \"chat\",\n method: \"post\",\n path: \"/chat\",\n handler: async (req, res) => this._handleChat(req, res),\n });\n this.route(router, {\n name: \"cancel\",\n method: \"post\",\n path: \"/cancel\",\n handler: async (req, res) => this._handleCancel(req, res),\n });\n this.route(router, {\n name: \"approve\",\n method: \"post\",\n path: \"/approve\",\n handler: async (req, res) => this._handleApprove(req, res),\n });\n this.route(router, {\n name: \"threads\",\n method: \"get\",\n path: \"/threads\",\n handler: async (req, res) => this._handleListThreads(req, res),\n });\n this.route(router, {\n name: \"thread\",\n method: \"get\",\n path: \"/threads/:threadId\",\n handler: async (req, res) => this._handleGetThread(req, res),\n });\n this.route(router, {\n name: \"deleteThread\",\n method: \"delete\",\n path: \"/threads/:threadId\",\n handler: async (req, res) => this._handleDeleteThread(req, res),\n });\n this.route(router, {\n name: \"info\",\n method: \"get\",\n path: \"/info\",\n handler: async (_req, res) => {\n res.json({\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\n });\n },\n });\n }\n\n clientConfig(): Record<string, unknown> {\n // Per-agent skill catalog (name + description) so the client can offer a\n // `/skill-name` autocomplete / picker. Only agents with a visible catalog\n // appear here.\n const skills: Record<string, { name: string; description: string }[]> = {};\n for (const [name, agent] of this.agents) {\n if (agent.skills) skills[name] = agent.skills.catalog;\n }\n return {\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\n skills,\n };\n }\n\n private async _handleChat(req: express.Request, res: express.Response) {\n const parsed = chatRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const {\n message,\n threadId,\n agent: agentName,\n mlflowRunId,\n skill,\n } = parsed.data;\n\n const registered = this.resolveAgent(agentName);\n if (!registered) {\n res.status(400).json({\n error: agentName\n ? `Agent \"${agentName}\" not found`\n : \"No agent registered\",\n });\n return;\n }\n\n const userId = this.resolveUserId(req);\n\n // Reject early (before allocating a thread) when the user is already at\n // their concurrent-stream limit. Prevents a misbehaving client from\n // churning thread rows while being denied elsewhere.\n const limits = this.resolvedLimits;\n if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {\n res.setHeader(\"Retry-After\", \"5\");\n res.status(429).json({\n error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.`,\n });\n return;\n }\n\n // ThreadStore can throw on backing-storage failures (DB unreachable,\n // permission errors, transient I/O). Without a try/catch the\n // `async` Express handler bubbles the rejection without a response and\n // the client connection hangs until the proxy times out. Surface the\n // failure as a 500 so the SSE client falls back instead of waiting.\n let thread: Thread;\n try {\n const existing = threadId\n ? await this.threadStore.get(threadId, userId)\n : null;\n if (threadId && !existing) {\n res.status(404).json({ error: `Thread ${threadId} not found` });\n return;\n }\n thread = existing ?? (await this.threadStore.create(userId));\n\n const userMessage: Message = {\n id: randomUUID(),\n role: \"user\",\n content: message,\n createdAt: new Date(),\n };\n await this.threadStore.addMessage(thread.id, userId, userMessage);\n } catch (err) {\n logger.error(\"threadStore failed in /chat: %O\", err);\n res.status(500).json({ error: \"Thread operation failed\" });\n return;\n }\n return this._streamAgent(\n req,\n res,\n registered,\n thread,\n userId,\n mlflowRunId,\n skill,\n );\n }\n\n /**\n * Returns the names of tools in `registered.toolIndex` whose annotations\n * would trip the approval gate. Used by the non-streaming invoke path\n * (`/invocations`, `/responses`) to fail-fast before the adapter runs:\n * those endpoints have no channel back to the user mid-call, so an agent\n * whose tool surface includes approval-gated tools cannot be served.\n *\n * Returns an empty list when the plugin is configured with\n * `approval.requireForDestructive: false` — operators who explicitly\n * disabled HITL keep the invoke surface unrestricted.\n */\n private collectApprovalRequiredToolNames(\n registered: RegisteredAgent,\n ): string[] {\n if (!this.resolvedApprovalPolicy.requireForDestructive) return [];\n const names: string[] = [];\n for (const entry of registered.toolIndex.values()) {\n if (requiresApproval(entry.def.annotations)) {\n names.push(entry.def.name);\n }\n }\n return names;\n }\n\n /**\n * Shared handler for `POST /invocations` and `POST /responses`. Runs the\n * default agent to completion and returns a single JSON response in the\n * OpenAI Responses non-streaming shape. The two endpoints are aliases —\n * streaming clients must use `POST /chat`.\n *\n * Rejects with HTTP 400 when the resolved agent has any approval-gated\n * tool in scope: HITL requires a live SSE channel, which this surface\n * does not provide. See {@link collectApprovalRequiredToolNames}.\n */\n private async _handleInvoke(req: express.Request, res: express.Response) {\n const parsed = invocationsRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { input, mlflowRunId } = parsed.data;\n const registered = this.resolveAgent();\n if (!registered) {\n res.status(400).json({ error: \"No agent registered\" });\n return;\n }\n\n // Pre-flight HITL gate. The non-streaming invoke surface has no way to\n // surface an approval prompt back to the caller and no way to receive\n // a decision mid-run, so we reject up-front instead of having the\n // approval gate auto-deny mid-stream (which would leave the caller\n // with a confusing \"denied by user\" tool result in the final text).\n const approvalGated = this.collectApprovalRequiredToolNames(registered);\n if (approvalGated.length > 0) {\n res.status(400).json({\n error:\n `Agent '${registered.name}' exposes ${approvalGated.length} approval-gated tool(s) ` +\n `(${approvalGated.join(\", \")}); /invocations and /responses are non-streaming and ` +\n \"cannot run HITL. Use POST /chat for HITL-capable agents, or disable approval via \" +\n \"agents({ approval: { requireForDestructive: false } }).\",\n });\n return;\n }\n\n const userId = this.resolveUserId(req);\n\n // Match the rate-limit gate on /chat. Without this, a client can bypass\n // `limits.maxConcurrentStreamsPerUser` by hitting /invocations instead.\n const limits = this.resolvedLimits;\n if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {\n res.setHeader(\"Retry-After\", \"5\");\n res.status(429).json({\n error: `Too many concurrent streams for this user (limit ${limits.maxConcurrentStreamsPerUser}). Wait for an existing stream to complete before starting another.`,\n });\n return;\n }\n\n // Same rationale as `_handleChat`: surface threadStore failures as a\n // 500 instead of letting the async handler hang the client connection.\n let thread: Thread;\n try {\n thread = await this.threadStore.create(userId);\n\n if (typeof input === \"string\") {\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"user\",\n content: input,\n createdAt: new Date(),\n });\n } else {\n for (const item of input) {\n const role = (item.role ?? \"user\") as Message[\"role\"];\n const content =\n typeof item.content === \"string\"\n ? item.content\n : JSON.stringify(item.content ?? \"\");\n if (!content) continue;\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role,\n content,\n createdAt: new Date(),\n });\n }\n }\n } catch (err) {\n logger.error(\"threadStore failed in /invocations: %O\", err);\n res.status(500).json({ error: \"Thread operation failed\" });\n return;\n }\n\n return this._runAgentNonStreaming(\n req,\n res,\n registered,\n thread,\n userId,\n mlflowRunId,\n );\n }\n\n private async _streamAgent(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: string,\n mlflowRunId?: string,\n forcedSkill?: string,\n ): Promise<void> {\n const abortController = new AbortController();\n const signal = abortController.signal;\n const requestId = randomUUID();\n this.trackStream(requestId, userId, abortController);\n\n // `hosted-supervisor` entries are not callable from the Node process\n // (the SA endpoint executes them server-side). Their `def` is a\n // placeholder; including it in the adapter's `tools` array would\n // make the SA endpoint reject the request with a schema mismatch.\n // The hosted-tool specs are routed via `AgentInput.extensions` below.\n const tools = Array.from(registered.toolIndex.values())\n .filter((e) => e.source !== \"hosted-supervisor\")\n .map((e) => e.def);\n const approvalPolicy = this.resolvedApprovalPolicy;\n const limits = this.resolvedLimits;\n const outboundEvents = new EventChannel<ResponseStreamEvent>();\n const translator = new AgentEventTranslator();\n\n // Per-run state shared with any sub-agents this run invokes. The boxed\n // tool-call counter, approval policy, and outbound event channel must\n // travel through the sub-agent path so it enforces the same budget and\n // approval gate as the top-level executeTool.\n const runState: RunState = {\n req,\n userId,\n requestId,\n abortController,\n signal,\n approvalPolicy,\n limits,\n translator,\n outboundEvents,\n toolCallsUsed: { count: 0 },\n toolErrors: [],\n };\n\n const deps = this.toolDispatchDeps();\n const executeTool = (name: string, args: unknown): Promise<unknown> =>\n dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);\n\n // Drive the adapter and the approval-event side-channel concurrently.\n // Outbound events from both sources flow through `outboundEvents`; the\n // generator below drains the channel in order. executeTool pushes\n // approval-pending events into the same channel before awaiting the gate.\n const driver = (async () => {\n try {\n for (const evt of translator.translate({\n type: \"metadata\",\n data: { threadId: thread.id },\n })) {\n outboundEvents.push(evt);\n }\n\n // Root MLflow span for the turn; tool-call spans nest under it.\n await traceAgent(\n registered.name ?? \"agent\",\n {\n messages: thread.messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n },\n async (span) => {\n // Link this turn's trace to an eval run when the eval runner\n // supplied one, so the trace shows under the MLflow evaluation run.\n if (mlflowRunId) linkTraceToRun(mlflowRunId);\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n let fullPrompt = composePromptForAgent(\n registered,\n this.config.baseSystemPrompt,\n {\n agentName: registered.name,\n pluginNames,\n toolNames: tools.map((t) => t.name),\n },\n );\n\n // Deterministic `/skill-name` invocation: eagerly inject the\n // requested skill's instructions into this turn rather than waiting\n // for the model to call load_skill. The tool stays available for\n // the model to auto-select others.\n if (forcedSkill) {\n const addendum = this.renderForcedSkill(registered, forcedSkill);\n if (addendum) fullPrompt = `${fullPrompt}\\n\\n${addendum}`;\n }\n\n const messagesWithSystem: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: fullPrompt,\n createdAt: new Date(),\n },\n ...thread.messages,\n ];\n\n const stream = registered.adapter.run(\n {\n messages: messagesWithSystem,\n tools,\n threadId: thread.id,\n signal,\n extensions: buildAdapterExtensions(registered.toolIndex),\n },\n { executeTool, signal },\n );\n\n // The accumulation rule (deltas append, `message` replaces) is\n // shared with `runAgent` and `runSubAgent`; see\n // `consumeAdapterStream` for the rationale.\n const fullContent = await consumeAdapterStream(stream, {\n signal,\n onEvent: (event) => {\n for (const translated of translator.translate(event)) {\n outboundEvents.push(translated);\n }\n },\n });\n\n if (fullContent) {\n span.setOutputs({ role: \"assistant\", content: fullContent });\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\n });\n }\n\n // Surface the MLflow trace id so eval runs can attach assessments\n // to this turn's trace. No-op when tracing is disabled.\n const mlflowTraceId = currentTraceId();\n if (mlflowTraceId) {\n for (const evt of translator.translate({\n type: \"metadata\",\n data: { mlflowTraceId },\n })) {\n outboundEvents.push(evt);\n }\n }\n },\n );\n\n for (const evt of translator.finalize()) outboundEvents.push(evt);\n } catch (error) {\n if (signal.aborted) {\n outboundEvents.close();\n return;\n }\n logger.error(\"Agent chat error: %O\", error);\n outboundEvents.close(error);\n return;\n } finally {\n // Any pending approval gates for this stream are auto-denied so the\n // adapter can unwind if it was still waiting.\n this.approvalGate.abortStream(requestId);\n this.untrackStream(requestId);\n // Stateless agents (e.g. autocomplete) don't persist history; drop\n // the thread so `InMemoryThreadStore` doesn't accumulate one record\n // per request. Swallow delete errors — the stream has already\n // finished and the client has the response.\n if (registered.ephemeral) {\n try {\n await this.threadStore.delete(thread.id, userId);\n } catch (err) {\n logger.warn(\n \"Failed to delete ephemeral thread %s: %O\",\n thread.id,\n err,\n );\n }\n }\n }\n outboundEvents.close();\n })();\n\n await this.executeStream<ResponseStreamEvent>(\n res,\n async function* () {\n try {\n for await (const ev of outboundEvents) {\n yield ev;\n }\n } finally {\n await driver.catch(() => undefined);\n }\n },\n {\n ...agentStreamDefaults,\n stream: { ...agentStreamDefaults.stream, streamId: requestId },\n },\n );\n }\n\n /**\n * Non-streaming counterpart to {@link _streamAgent} used by `/invocations`\n * and `/responses`. Drives the adapter to completion, persists the\n * assistant turn to the thread store, and returns a single JSON envelope\n * shaped like the OpenAI Responses non-streaming API.\n *\n * No `EventChannel`, no `AgentEventTranslator`, no SSE — the caller is\n * waiting on one HTTP response. The approval gate is force-disabled in\n * the per-run state as defense-in-depth: `_handleInvoke` already rejects\n * up-front if any tool in scope would require approval, but pinning\n * `requireForDestructive: false` here means a tool that somehow slips\n * past the precheck (e.g. annotations mutated at runtime) still won't\n * stall the request waiting for an approval prompt that no one can\n * answer.\n *\n * The `RunState` shape is otherwise unchanged so {@link dispatchToolCall}\n * — including sub-agent recursion via {@link runSubAgent} — keeps the\n * same tool-call budget, abort signal, and timeout enforcement as the\n * streaming path. A still-typed translator is constructed but only\n * consulted for `finalize()` so any in-flight `approval_pending` event\n * synthesis (which would have been a coding bug given the precheck) is\n * a dropped no-op instead of a runtime crash.\n */\n private async _runAgentNonStreaming(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: string,\n mlflowRunId?: string,\n ): Promise<void> {\n const abortController = new AbortController();\n const signal = abortController.signal;\n const requestId = randomUUID();\n this.trackStream(requestId, userId, abortController);\n\n const tools = Array.from(registered.toolIndex.values()).map((e) => e.def);\n const limits = this.resolvedLimits;\n\n // Assigned inside the span below (the only place the active trace id\n // resolves), read into the response envelope after.\n let mlflowTraceId: string | undefined;\n\n const runState: RunState = {\n req,\n userId,\n requestId,\n abortController,\n signal,\n // Force approval off for the non-streaming invoke surface. The\n // precheck in `_handleInvoke` already guarantees no approval-gated\n // tool is reachable; this is belt-and-braces.\n approvalPolicy: { requireForDestructive: false, timeoutMs: 0 },\n limits,\n translator: new AgentEventTranslator(),\n outboundEvents: new EventChannel<ResponseStreamEvent>(),\n toolCallsUsed: { count: 0 },\n toolErrors: [],\n };\n\n const deps = this.toolDispatchDeps();\n const executeTool = (name: string, args: unknown): Promise<unknown> =>\n dispatchToolCall(deps, runState, registered.toolIndex, name, args, 0);\n\n let fullContent = \"\";\n try {\n // Root MLflow span for the turn; tool-call spans nest under it. Mirrors\n // the streaming path so the invoke surface produces the same trace shape\n // instead of orphan root TOOL spans.\n await traceAgent(\n registered.name ?? \"agent\",\n {\n messages: thread.messages.map((m) => ({\n role: m.role,\n content: m.content,\n })),\n },\n async (span) => {\n // Link this turn's trace to an eval run when the eval runner\n // supplied one, so the trace shows under the MLflow evaluation run.\n if (mlflowRunId) linkTraceToRun(mlflowRunId);\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n const fullPrompt = composePromptForAgent(\n registered,\n this.config.baseSystemPrompt,\n {\n agentName: registered.name,\n pluginNames,\n toolNames: tools.map((t) => t.name),\n },\n );\n\n const messagesWithSystem: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: fullPrompt,\n createdAt: new Date(),\n },\n ...thread.messages,\n ];\n\n const stream = registered.adapter.run(\n {\n messages: messagesWithSystem,\n tools,\n threadId: thread.id,\n signal,\n },\n { executeTool, signal },\n );\n\n fullContent = await consumeAdapterStream(stream, { signal });\n\n if (fullContent) {\n span.setOutputs({ role: \"assistant\", content: fullContent });\n await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\n });\n }\n\n mlflowTraceId = currentTraceId();\n },\n );\n } catch (error) {\n if (signal.aborted) {\n res.status(499).json({ error: \"Request aborted\" });\n return;\n }\n logger.error(\"Agent invoke error: %O\", error);\n const message =\n process.env.NODE_ENV === \"production\"\n ? \"Internal server error\"\n : error instanceof Error\n ? error.message\n : String(error);\n res.status(500).json({ error: message });\n return;\n } finally {\n this.approvalGate.abortStream(requestId);\n this.untrackStream(requestId);\n if (registered.ephemeral) {\n try {\n await this.threadStore.delete(thread.id, userId);\n } catch (err) {\n logger.warn(\n \"Failed to delete ephemeral thread %s: %O\",\n thread.id,\n err,\n );\n }\n }\n }\n\n const responseId = `resp_${randomUUID()}`;\n const messageId = `msg_${randomUUID()}`;\n const message: ResponseOutputMessage = {\n type: \"message\",\n id: messageId,\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text: fullContent }],\n };\n res.json({\n id: responseId,\n object: \"response\",\n created_at: Math.floor(Date.now() / 1000),\n status: \"completed\",\n thread_id: thread.id,\n // Lets an eval runner attach assessments to this turn's trace; absent\n // when tracing is disabled.\n ...(mlflowTraceId ? { mlflow_trace_id: mlflowTraceId } : {}),\n // Tool failures the model recovered from — the non-streaming equivalent\n // of the streaming path's `tool_result` error events.\n ...(runState.toolErrors.length > 0\n ? { tool_errors: runState.toolErrors }\n : {}),\n output: [message],\n });\n }\n\n private dispatchSkillTool(\n entry: Extract<ResolvedToolEntry, { source: \"skill\" }>,\n args: unknown,\n ): Promise<string> {\n return dispatchSkillTool(entry, args, () => this.skillWorkspaceClient());\n }\n\n /**\n * Renders the prompt addendum for a force-loaded skill (`/skill-name`).\n * Returns null when the agent has no catalog or the name doesn't resolve —\n * an unusable request shouldn't fail the whole turn, so it's logged and the\n * model proceeds with the catalog + `load_skill` still available.\n */\n private renderForcedSkill(\n registered: RegisteredAgent,\n name: string,\n ): string | null {\n return renderForcedSkill(registered, name);\n }\n\n /** Collaborators the tool-dispatch path needs, bound to this instance. */\n private toolDispatchDeps(): ToolDispatchDeps {\n return {\n approvalGate: this.approvalGate,\n context: this.context,\n getMcpClient: () => this.mcpClient,\n agents: this.agents,\n dispatchSkillTool: (entry, args) => this.dispatchSkillTool(entry, args),\n pluginName: this.name,\n baseSystemPrompt: this.config.baseSystemPrompt,\n };\n }\n\n private async _handleCancel(req: express.Request, res: express.Response) {\n const parsed = cancelRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { streamId } = parsed.data;\n const entry = this.streams.get(streamId);\n if (!entry) {\n // Stream is unknown or already completed — idempotent no-op.\n res.json({ cancelled: true });\n return;\n }\n const userId = this.resolveUserId(req);\n if (entry.userId !== userId) {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n entry.controller.abort(\"Cancelled by user\");\n this.untrackStream(streamId);\n this.approvalGate.abortStream(streamId);\n res.json({ cancelled: true });\n }\n\n private async _handleApprove(req: express.Request, res: express.Response) {\n const parsed = approvalRequestSchema.safeParse(req.body);\n if (!parsed.success) {\n res.status(400).json({\n error: \"Invalid request\",\n details: parsed.error.flatten().fieldErrors,\n });\n return;\n }\n const { streamId, approvalId, decision } = parsed.data;\n\n const streamEntry = this.streams.get(streamId);\n if (!streamEntry) {\n // Stream has already completed or never existed. Return 404 so the UI\n // knows the approval token is no longer valid (the waiter, if any, has\n // already been timed out or aborted).\n res.status(404).json({ error: \"Stream not found or already completed\" });\n return;\n }\n\n const userId = this.resolveUserId(req);\n if (streamEntry.userId !== userId) {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n\n const result = this.approvalGate.submit({ approvalId, userId, decision });\n if (!result.ok) {\n if (result.reason === \"forbidden\") {\n res.status(403).json({ error: \"Forbidden\" });\n return;\n }\n res.status(404).json({ error: \"Approval not found or already settled\" });\n return;\n }\n\n res.json({ decision });\n }\n\n private async _handleListThreads(\n req: express.Request,\n res: express.Response,\n ) {\n const userId = this.resolveUserId(req);\n const threads = await this.threadStore.list(userId);\n res.json({ threads });\n }\n\n private async _handleGetThread(req: express.Request, res: express.Response) {\n const userId = this.resolveUserId(req);\n const thread = await this.threadStore.get(req.params.threadId, userId);\n if (!thread) {\n res.status(404).json({ error: \"Thread not found\" });\n return;\n }\n res.json(thread);\n }\n\n private async _handleDeleteThread(\n req: express.Request,\n res: express.Response,\n ) {\n const userId = this.resolveUserId(req);\n const deleted = await this.threadStore.delete(req.params.threadId, userId);\n if (!deleted) {\n res.status(404).json({ error: \"Thread not found\" });\n return;\n }\n res.json({ deleted: true });\n }\n\n private resolveAgent(name?: string): RegisteredAgent | null {\n if (name) return this.agents.get(name) ?? null;\n if (this.defaultAgentName) {\n return this.agents.get(this.defaultAgentName) ?? null;\n }\n const first = this.agents.values().next();\n return first.done ? null : first.value;\n }\n\n private printRegistry(): void {\n if (this.agents.size === 0) return;\n console.log(\"\");\n console.log(` ${pc.bold(\"Agents\")} ${pc.dim(`(${this.agents.size})`)}`);\n console.log(` ${pc.dim(\"─\".repeat(60))}`);\n for (const [name, reg] of this.agents) {\n const tools = reg.toolIndex.size;\n const marker = name === this.defaultAgentName ? pc.green(\"●\") : \" \";\n console.log(\n ` ${marker} ${pc.bold(name.padEnd(24))} ${pc.dim(`${tools} tools`)}`,\n );\n }\n console.log(` ${pc.dim(\"─\".repeat(60))}`);\n console.log(\"\");\n }\n\n async shutdown(): Promise<void> {\n this.approvalGate.abortAll();\n if (this.mcpClient) {\n await this.mcpClient.close();\n this.mcpClient = null;\n }\n }\n\n exports() {\n return {\n register: (name: string, def: AgentDefinition) =>\n this.registerCodeAgent(name, def),\n list: () => Array.from(this.agents.keys()),\n get: (name: string) => this.agents.get(name) ?? null,\n reload: () => this.reload(),\n getDefault: () => this.defaultAgentName,\n getThreads: (userId: string) => this.threadStore.list(userId),\n };\n }\n\n private async registerCodeAgent(\n name: string,\n def: AgentDefinition,\n ): Promise<void> {\n const registered = await this.buildRegisteredAgent(name, def, {\n origin: \"code\",\n });\n this.agents.set(name, registered);\n if (!this.defaultAgentName) this.defaultAgentName = name;\n }\n}\n\nfunction normalizeAutoInherit(value: AgentsPluginConfig[\"autoInheritTools\"]): {\n file: boolean;\n code: boolean;\n} {\n // Default is opt-out for both origins. A markdown agent or code-defined\n // agent with no declared `tools:` gets an empty tool index unless the\n // developer explicitly flips `autoInheritTools` on. Even then, only tools\n // whose plugin author marked `autoInheritable: true` are spread — see\n // `applyAutoInherit` for the filter.\n if (value === undefined) return { file: false, code: false };\n if (typeof value === \"boolean\") return { file: value, code: value };\n return { file: value.file ?? false, code: value.code ?? false };\n}\n\n/**\n * Plugin factory for the agents plugin. Discovers agents from\n * `server/agents/<id>/agent.{ts,md}` by default (markdown still in\n * `config/agents/` is read as a deprecated fallback), resolves toolkits/tools\n * from registered plugins, exposes the `appkit.agents.*` runtime API and mounts\n * `POST /invocations` and `POST /responses` (aliased non-streaming invoke\n * endpoints) plus `POST /chat` (streaming, HITL-capable).\n *\n * @example\n * ```ts\n * import { agents, analytics, createApp, server } from \"@databricks/appkit\";\n *\n * await createApp({\n * plugins: [server(), analytics(), agents()],\n * });\n * ```\n */\nexport const agents = toPlugin(AgentsPlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGA,MAAM,SAAS,aAAa,SAAS;;AAGrC,MAAM,sBAAsB;AAE5B,IAAa,eAAb,cAAkC,OAA+B;CAC/D,OAAO,WAAW,eAAyBA,iBAAS;CACpD,OAAO,QAAqB;CAI5B,AAAQ,yBAAS,IAAI,KAA8B;CACnD,AAAQ,mBAAkC;;;;;CAK1C,AAAQ,UAAU,IAAI,qBAAqB;CAC3C,AAAQ,YAAoC;CAC5C,AAAQ;CACR,AAAQ,eAAe,IAAI,kBAAkB;;CAE7C,AAAQ,6BAA6B;;CAErC,AAAQ,gCAAgC;CAExC,YAAY,QAA4B;AACtC,QAAM,OAAO;AACb,OAAK,SAAS;AACd,MAAI,OAAO,YACT,MAAK,cAAc,OAAO;OACrB;AACL,QAAK,cAAc,IAAI,qBAAqB;AAC5C,OAAI,QAAQ,IAAI,aAAa,aAC3B,QAAO,KACL,oMAGD;OAED,QAAO,KACL,qGACD;;;;;;;;;;;;;;;;;;CAoBP,AAAQ,eAAkC,EAAE;CAE5C,AAAQ,uBAGG;CAEX,IAAY,yBAGV;AACA,MAAI,KAAK,qBAAsB,QAAO,KAAK;AAC3C,OAAK,uBAAuB,sBAAsB,KAAK,OAAO;AAC9D,SAAO,KAAK;;;CAId,IAAY,iBAKV;AACA,SAAO,cAAc,KAAK,OAAO;;;CAInC,AAAQ,iBAAiB,QAAwB;AAC/C,SAAO,KAAK,QAAQ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AAW,QAAO;EAAE,MAAM;EAAO,MAAM;EAAO;AAC5D,KAAI,OAAO,UAAU,UAAW,QAAO;EAAE,MAAM;EAAO,MAAM;EAAO;AACnE,QAAO;EAAE,MAAM,MAAM,QAAQ;EAAO,MAAM,MAAM,QAAQ;EAAO;;;;;;;;;;;;;;;;;;;AAoBjE,MAAa,SAAS,SAAS,aAAa"}
@@ -1,3 +1,4 @@
1
+ import { createLogger } from "../../logging/logger.js";
1
2
  import { consumeAdapterStream } from "../../core/agent/consume-adapter-stream.js";
2
3
  import { buildAdapterExtensions } from "./adapter-extensions.js";
3
4
  import { requiresApproval } from "./approval.js";
@@ -7,6 +8,7 @@ import { normalizeToolResult } from "../../core/agent/normalize-result.js";
7
8
  import { randomUUID } from "node:crypto";
8
9
 
9
10
  //#region src/plugins/agents/tool-dispatch.ts
11
+ const logger = createLogger("agents:tools");
10
12
  /**
11
13
  * Dispatch a single tool call from either the top-level adapter or a
12
14
  * sub-agent. Centralising this in one function is what makes the budget
@@ -43,28 +45,47 @@ async function dispatchToolCall(deps, runState, toolIndex, name, args, depth) {
43
45
  timeoutMs: runState.approvalPolicy.timeoutMs
44
46
  }) === "deny") return `Tool execution denied by user approval gate (tool: ${name}).`;
45
47
  }
46
- return normalizeToolResult(await traceTool(name, args, async () => {
47
- let result;
48
- if (entry.source === "toolkit") {
48
+ let toolResult;
49
+ try {
50
+ toolResult = await traceTool(name, args, () => runToolEntry(deps, runState, entry, name, args, depth));
51
+ } catch (err) {
52
+ const error = err instanceof Error ? err.message : String(err);
53
+ logger.error("Tool '%s' failed (request %s): %O", name, runState.requestId, err);
54
+ runState.toolErrors.push({
55
+ tool: name,
56
+ error
57
+ });
58
+ throw err;
59
+ }
60
+ return normalizeToolResult(toolResult);
61
+ }
62
+ /**
63
+ * Executes a resolved tool entry by source. Unknown sources fall through to
64
+ * `undefined` (the tool index only holds these six).
65
+ */
66
+ async function runToolEntry(deps, runState, entry, name, args, depth) {
67
+ switch (entry.source) {
68
+ case "toolkit":
49
69
  if (!deps.context) throw new Error("Plugin tool execution requires PluginContext; this should never happen through createApp");
50
- result = await deps.context.executeTool(runState.req, entry.pluginName, entry.localName, args, runState.signal, runState.limits.toolCallTimeoutMs);
51
- } else if (entry.source === "function") {
70
+ return deps.context.executeTool(runState.req, entry.pluginName, entry.localName, args, runState.signal, runState.limits.toolCallTimeoutMs);
71
+ case "function":
52
72
  if (typeof args !== "object" || args === null || Array.isArray(args)) throw new Error(`Function tool '${name}' received non-object arguments (got ${args === null ? "null" : Array.isArray(args) ? "array" : typeof args}); expected a JSON object.`);
53
- result = await entry.functionTool.execute(args);
54
- } else if (entry.source === "mcp") {
73
+ return entry.functionTool.execute(args);
74
+ case "mcp": {
55
75
  const mcpClient = deps.getMcpClient();
56
76
  if (!mcpClient) throw new Error("MCP client not connected");
57
77
  const oboToken = runState.req.headers["x-forwarded-access-token"];
58
78
  const mcpAuth = typeof oboToken === "string" ? { Authorization: `Bearer ${oboToken}` } : void 0;
59
- result = await mcpClient.callTool(entry.mcpToolName, args, mcpAuth);
60
- } else if (entry.source === "subagent") {
79
+ return mcpClient.callTool(entry.mcpToolName, args, mcpAuth);
80
+ }
81
+ case "subagent": {
61
82
  const childAgent = deps.agents.get(entry.agentName);
62
83
  if (!childAgent) throw new Error(`Sub-agent not found: ${entry.agentName}`);
63
- result = await runSubAgent(deps, runState, childAgent, args, depth + 1);
64
- } else if (entry.source === "hosted-supervisor") throw new Error(`Tool '${name}' is a hosted-supervisor tool and cannot be invoked from the Node process. It is executed server-side by the Databricks AI Gateway and is only reachable when the agent's model is a Supervisor API adapter.`);
65
- else if (entry.source === "skill") result = await deps.dispatchSkillTool(entry, args);
66
- return result;
67
- }));
84
+ return runSubAgent(deps, runState, childAgent, args, depth + 1);
85
+ }
86
+ case "hosted-supervisor": throw new Error(`Tool '${name}' is a hosted-supervisor tool and cannot be invoked from the Node process. It is executed server-side by the Databricks AI Gateway and is only reachable when the agent's model is a Supervisor API adapter.`);
87
+ case "skill": return deps.dispatchSkillTool(entry, args);
88
+ }
68
89
  }
69
90
  /**
70
91
  * Runs a sub-agent in response to an `agent-<key>` tool call. Returns the