@databricks/appkit 0.36.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -149,7 +149,7 @@ var AgentsPlugin = class extends Plugin {
149
149
  const { agents, defaultAgentName } = await this.buildAgentRegistry();
150
150
  this.agents = agents;
151
151
  this.defaultAgentName = defaultAgentName;
152
- this.mountInvocationsRoute();
152
+ this.mountInvokeRoutes();
153
153
  this.printRegistry();
154
154
  }
155
155
  /**
@@ -455,11 +455,19 @@ var AgentsPlugin = class extends Plugin {
455
455
  async executeAgentTool() {
456
456
  throw new Error("AgentsPlugin does not expose executeAgentTool directly");
457
457
  }
458
- mountInvocationsRoute() {
458
+ /**
459
+ * Mount the non-streaming invoke endpoints outside the `/api/<plugin>`
460
+ * namespace. `/invocations` and `/responses` are aliases — both run the
461
+ * default agent to completion and return a single JSON response. Streaming
462
+ * lives on `POST /chat` (mounted in `injectRoutes`).
463
+ */
464
+ mountInvokeRoutes() {
459
465
  if (!this.context) return;
460
- this.context.addRoute("post", "/invocations", (req, res) => {
461
- this._handleInvocations(req, res);
462
- });
466
+ const handler = (req, res) => {
467
+ this._handleInvoke(req, res);
468
+ };
469
+ this.context.addRoute("post", "/invocations", handler);
470
+ this.context.addRoute("post", "/responses", handler);
463
471
  }
464
472
  injectRoutes(router) {
465
473
  this.route(router, {
@@ -560,7 +568,34 @@ var AgentsPlugin = class extends Plugin {
560
568
  }
561
569
  return this._streamAgent(req, res, registered, thread, userId);
562
570
  }
563
- async _handleInvocations(req, res) {
571
+ /**
572
+ * Returns the names of tools in `registered.toolIndex` whose annotations
573
+ * would trip the approval gate. Used by the non-streaming invoke path
574
+ * (`/invocations`, `/responses`) to fail-fast before the adapter runs:
575
+ * those endpoints have no channel back to the user mid-call, so an agent
576
+ * whose tool surface includes approval-gated tools cannot be served.
577
+ *
578
+ * Returns an empty list when the plugin is configured with
579
+ * `approval.requireForDestructive: false` — operators who explicitly
580
+ * disabled HITL keep the invoke surface unrestricted.
581
+ */
582
+ collectApprovalRequiredToolNames(registered) {
583
+ if (!this.resolvedApprovalPolicy.requireForDestructive) return [];
584
+ const names = [];
585
+ for (const entry of registered.toolIndex.values()) if (requiresApproval(entry.def.annotations)) names.push(entry.def.name);
586
+ return names;
587
+ }
588
+ /**
589
+ * Shared handler for `POST /invocations` and `POST /responses`. Runs the
590
+ * default agent to completion and returns a single JSON response in the
591
+ * OpenAI Responses non-streaming shape. The two endpoints are aliases —
592
+ * streaming clients must use `POST /chat`.
593
+ *
594
+ * Rejects with HTTP 400 when the resolved agent has any approval-gated
595
+ * tool in scope: HITL requires a live SSE channel, which this surface
596
+ * does not provide. See {@link collectApprovalRequiredToolNames}.
597
+ */
598
+ async _handleInvoke(req, res) {
564
599
  const parsed = invocationsRequestSchema.safeParse(req.body);
565
600
  if (!parsed.success) {
566
601
  res.status(400).json({
@@ -575,6 +610,11 @@ var AgentsPlugin = class extends Plugin {
575
610
  res.status(400).json({ error: "No agent registered" });
576
611
  return;
577
612
  }
613
+ const approvalGated = this.collectApprovalRequiredToolNames(registered);
614
+ if (approvalGated.length > 0) {
615
+ res.status(400).json({ error: `Agent '${registered.name}' exposes ${approvalGated.length} approval-gated tool(s) (${approvalGated.join(", ")}); /invocations and /responses are non-streaming and cannot run HITL. Use POST /chat for HITL-capable agents, or disable approval via agents({ approval: { requireForDestructive: false } }).` });
616
+ return;
617
+ }
578
618
  const userId = this.resolveUserId(req);
579
619
  const limits = this.resolvedLimits;
580
620
  if (this.countUserStreams(userId) >= limits.maxConcurrentStreamsPerUser) {
@@ -607,7 +647,7 @@ var AgentsPlugin = class extends Plugin {
607
647
  res.status(500).json({ error: "Thread operation failed" });
608
648
  return;
609
649
  }
610
- return this._streamAgent(req, res, registered, thread, userId);
650
+ return this._runAgentNonStreaming(req, res, registered, thread, userId);
611
651
  }
612
652
  async _streamAgent(req, res, registered, thread, userId) {
613
653
  const abortController = new AbortController();
@@ -704,6 +744,117 @@ var AgentsPlugin = class extends Plugin {
704
744
  });
705
745
  }
706
746
  /**
747
+ * Non-streaming counterpart to {@link _streamAgent} used by `/invocations`
748
+ * and `/responses`. Drives the adapter to completion, persists the
749
+ * assistant turn to the thread store, and returns a single JSON envelope
750
+ * shaped like the OpenAI Responses non-streaming API.
751
+ *
752
+ * No `EventChannel`, no `AgentEventTranslator`, no SSE — the caller is
753
+ * waiting on one HTTP response. The approval gate is force-disabled in
754
+ * the per-run state as defense-in-depth: `_handleInvoke` already rejects
755
+ * up-front if any tool in scope would require approval, but pinning
756
+ * `requireForDestructive: false` here means a tool that somehow slips
757
+ * past the precheck (e.g. annotations mutated at runtime) still won't
758
+ * stall the request waiting for an approval prompt that no one can
759
+ * answer.
760
+ *
761
+ * The `RunState` shape is otherwise unchanged so {@link dispatchToolCall}
762
+ * — including sub-agent recursion via {@link runSubAgent} — keeps the
763
+ * same tool-call budget, abort signal, and timeout enforcement as the
764
+ * streaming path. A still-typed translator is constructed but only
765
+ * consulted for `finalize()` so any in-flight `approval_pending` event
766
+ * synthesis (which would have been a coding bug given the precheck) is
767
+ * a dropped no-op instead of a runtime crash.
768
+ */
769
+ async _runAgentNonStreaming(req, res, registered, thread, userId) {
770
+ const abortController = new AbortController();
771
+ const signal = abortController.signal;
772
+ const requestId = randomUUID();
773
+ this.trackStream(requestId, userId, abortController);
774
+ const tools = Array.from(registered.toolIndex.values()).map((e) => e.def);
775
+ const runState = {
776
+ req,
777
+ userId,
778
+ requestId,
779
+ abortController,
780
+ signal,
781
+ approvalPolicy: {
782
+ requireForDestructive: false,
783
+ timeoutMs: 0
784
+ },
785
+ limits: this.resolvedLimits,
786
+ translator: new AgentEventTranslator(),
787
+ outboundEvents: new EventChannel(),
788
+ toolCallsUsed: { count: 0 }
789
+ };
790
+ const executeTool = (name, args) => this.dispatchToolCall(runState, registered.toolIndex, name, args, 0);
791
+ let fullContent = "";
792
+ try {
793
+ const pluginNames = this.context ? this.context.getPluginNames().filter((n) => n !== this.name && n !== "server") : [];
794
+ const messagesWithSystem = [{
795
+ id: "system",
796
+ role: "system",
797
+ content: composePromptForAgent(registered, this.config.baseSystemPrompt, {
798
+ agentName: registered.name,
799
+ pluginNames,
800
+ toolNames: tools.map((t) => t.name)
801
+ }),
802
+ createdAt: /* @__PURE__ */ new Date()
803
+ }, ...thread.messages];
804
+ fullContent = await consumeAdapterStream(registered.adapter.run({
805
+ messages: messagesWithSystem,
806
+ tools,
807
+ threadId: thread.id,
808
+ signal
809
+ }, {
810
+ executeTool,
811
+ signal
812
+ }), { signal });
813
+ if (fullContent) await this.threadStore.addMessage(thread.id, userId, {
814
+ id: randomUUID(),
815
+ role: "assistant",
816
+ content: fullContent,
817
+ createdAt: /* @__PURE__ */ new Date()
818
+ });
819
+ } catch (error) {
820
+ if (signal.aborted) {
821
+ res.status(499).json({ error: "Request aborted" });
822
+ return;
823
+ }
824
+ logger.error("Agent invoke error: %O", error);
825
+ const message = process.env.NODE_ENV === "production" ? "Internal server error" : error instanceof Error ? error.message : String(error);
826
+ res.status(500).json({ error: message });
827
+ return;
828
+ } finally {
829
+ this.approvalGate.abortStream(requestId);
830
+ this.untrackStream(requestId);
831
+ if (registered.ephemeral) try {
832
+ await this.threadStore.delete(thread.id, userId);
833
+ } catch (err) {
834
+ logger.warn("Failed to delete ephemeral thread %s: %O", thread.id, err);
835
+ }
836
+ }
837
+ const responseId = `resp_${randomUUID()}`;
838
+ const message = {
839
+ type: "message",
840
+ id: `msg_${randomUUID()}`,
841
+ status: "completed",
842
+ role: "assistant",
843
+ content: [{
844
+ type: "output_text",
845
+ text: fullContent
846
+ }]
847
+ };
848
+ res.json({
849
+ id: responseId,
850
+ object: "response",
851
+ created_at: Math.floor(Date.now() / 1e3),
852
+ status: "completed",
853
+ thread_id: thread.id,
854
+ output: [message]
855
+ });
856
+ }
857
+ /**
707
858
  * Dispatch a single tool call from either the top-level adapter or a
708
859
  * sub-agent. Centralising this in one method is what makes the budget
709
860
  * counter, approval gate, and abort signal observe sub-agent activity:
@@ -961,7 +1112,8 @@ function composePromptForAgent(registered, pluginLevel, ctx) {
961
1112
  /**
962
1113
  * Plugin factory for the agents plugin. Reads `config/agents/*.md` by default,
963
1114
  * resolves toolkits/tools from registered plugins, exposes `appkit.agents.*`
964
- * runtime API and mounts `/invocations`.
1115
+ * runtime API and mounts `POST /invocations` and `POST /responses` (aliased
1116
+ * non-streaming invoke endpoints) plus `POST /chat` (streaming, HITL-capable).
965
1117
  *
966
1118
  * @example
967
1119
  * ```ts
@@ -1 +1 @@
1
- {"version":3,"file":"agents.js","names":["manifest"],"sources":["../../../src/plugins/agents/agents.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport type express from \"express\";\nimport pc from \"picocolors\";\nimport type {\n AgentAdapter,\n AgentEvent,\n AgentRunContext,\n AgentToolDefinition,\n IAppRouter,\n Message,\n PluginPhase,\n ResponseStreamEvent,\n Thread,\n ToolAnnotations,\n ToolProvider,\n} from \"shared\";\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 { normalizeToolResult } from \"../../core/agent/normalize-result\";\nimport { createPluginsProxy } from \"../../core/agent/plugins-map\";\nimport {\n buildBaseSystemPrompt,\n composeSystemPrompt,\n} from \"../../core/agent/system-prompt\";\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 BaseSystemPromptOption,\n Plugins,\n PluginToolkitProvider,\n PromptContext,\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 type { PluginManifest } from \"../../registry\";\nimport { agentStreamDefaults } from \"./defaults\";\nimport { EventChannel } from \"./event-channel\";\nimport { AgentEventTranslator } from \"./event-translator\";\nimport manifest from \"./manifest.json\";\nimport {\n approvalRequestSchema,\n cancelRequestSchema,\n chatRequestSchema,\n invocationsRequestSchema,\n} from \"./schemas\";\nimport { InMemoryThreadStore } from \"./thread-store\";\nimport { ToolApprovalGate } from \"./tool-approval-gate\";\n\nconst logger = createLogger(\"agents\");\n\nconst DEFAULT_AGENTS_DIR = \"./config/agents\";\n\n/**\n * Context flag recorded on the in-memory AgentDefinition to indicate whether\n * it came from markdown (file) or from user code. Drives the asymmetric\n * `autoInheritTools` default.\n */\ninterface AgentSource {\n origin: \"file\" | \"code\";\n}\n\n/**\n * Decide whether a tool call must traverse the approval gate. Honours both\n * the modern `effect` field (mutating values: write / update / destructive)\n * and the legacy `destructive: true` boolean. The contract is documented on\n * `ToolAnnotations.effect` in shared/agent.ts.\n *\n * Without this, a tool authored only with `effect: \"destructive\"` (the\n * preferred API) bypassed the gate entirely.\n */\nfunction requiresApproval(annotations: ToolAnnotations | undefined): boolean {\n if (!annotations) return false;\n if (annotations.destructive === true) return true;\n switch (annotations.effect) {\n case \"write\":\n case \"update\":\n case \"destructive\":\n return true;\n case \"read\":\n case undefined:\n return false;\n default: {\n const _exhaustive: never = annotations.effect;\n return false;\n }\n }\n}\n\n/**\n * Per-stream state shared between the top-level `executeTool` and any\n * `runSubAgent` calls below it. Carrying the budget counter, abort signal,\n * approval policy, and event-channel through one object is what lets the\n * sub-agent path enforce the same limits and approval gate as the parent.\n *\n * Without this shared state the sub-agent path silently bypassed both the\n * tool-call budget and the destructive-tool approval gate.\n */\ninterface RunState {\n req: express.Request;\n userId: string;\n requestId: string;\n abortController: AbortController;\n signal: AbortSignal;\n approvalPolicy: { requireForDestructive: boolean; timeoutMs: number };\n limits: {\n maxConcurrentStreamsPerUser: number;\n maxToolCalls: number;\n maxSubAgentDepth: number;\n toolCallTimeoutMs: number;\n };\n translator: AgentEventTranslator;\n outboundEvents: EventChannel<ResponseStreamEvent>;\n /** Boxed mutable counter shared across parent + all sub-agent dispatches. */\n toolCallsUsed: { count: number };\n}\n\nexport class AgentsPlugin extends Plugin implements ToolProvider {\n static manifest = manifest as PluginManifest;\n static phase: PluginPhase = \"deferred\";\n\n protected declare config: AgentsPluginConfig;\n\n private agents = new Map<string, RegisteredAgent>();\n private defaultAgentName: string | null = null;\n private activeStreams = new Map<\n string,\n { controller: AbortController; userId: string }\n >();\n /**\n * Per-user stream count, kept in sync with `activeStreams` so the\n * concurrent-stream rate limit check is O(1) instead of O(n) over every\n * active stream on every request. Mutated only via {@link trackStream}\n * and {@link untrackStream}.\n */\n private userStreamCounts = new Map<string, number>();\n private mcpClient: AppKitMcpClient | null = null;\n private threadStore;\n private approvalGate = new ToolApprovalGate();\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 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 const cfg = this.config.approval ?? {};\n const APPROVAL_TIMEOUT_FLOOR_MS = 1_000;\n const APPROVAL_TIMEOUT_DEFAULT_MS = 60_000;\n let timeoutMs = cfg.timeoutMs ?? APPROVAL_TIMEOUT_DEFAULT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs < APPROVAL_TIMEOUT_FLOOR_MS) {\n logger.warn(\n \"approval.timeoutMs=%s is below the %sms floor; using default %sms instead. Mutating tool calls would otherwise auto-deny before any UI could respond.\",\n cfg.timeoutMs,\n APPROVAL_TIMEOUT_FLOOR_MS,\n APPROVAL_TIMEOUT_DEFAULT_MS,\n );\n timeoutMs = APPROVAL_TIMEOUT_DEFAULT_MS;\n }\n this.cachedApprovalPolicy = {\n requireForDestructive: cfg.requireForDestructive ?? true,\n timeoutMs,\n };\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 const cfg = this.config.limits ?? {};\n return {\n maxConcurrentStreamsPerUser: cfg.maxConcurrentStreamsPerUser ?? 5,\n maxToolCalls: cfg.maxToolCalls ?? 50,\n maxSubAgentDepth: cfg.maxSubAgentDepth ?? 3,\n // 5 minutes is the floor for cold SQL Warehouse / long Genie /\n // long Lakebase calls. The previous PluginContext default of 30s\n // truncated legitimate analytics queries on cold compute.\n toolCallTimeoutMs: cfg.toolCallTimeoutMs ?? 300_000,\n };\n }\n\n /** Count active streams owned by a given user. O(1). */\n private countUserStreams(userId: string): number {\n return this.userStreamCounts.get(userId) ?? 0;\n }\n\n /**\n * Register a stream for `userId` and bump the per-user counter. Paired\n * with {@link untrackStream}; the two helpers are the only writers to\n * `activeStreams` + `userStreamCounts`, so the counter cannot drift from\n * the map.\n */\n private trackStream(\n requestId: string,\n userId: string,\n controller: AbortController,\n ): void {\n this.activeStreams.set(requestId, { controller, userId });\n this.userStreamCounts.set(\n userId,\n (this.userStreamCounts.get(userId) ?? 0) + 1,\n );\n }\n\n /**\n * Remove a stream from the active map and decrement the per-user\n * counter. Idempotent — calling twice for the same `requestId` is a\n * no-op (the second call sees no entry and returns early).\n */\n private untrackStream(requestId: string): void {\n const entry = this.activeStreams.get(requestId);\n if (!entry) return;\n this.activeStreams.delete(requestId);\n const next = (this.userStreamCounts.get(entry.userId) ?? 0) - 1;\n if (next <= 0) {\n this.userStreamCounts.delete(entry.userId);\n } else {\n this.userStreamCounts.set(entry.userId, next);\n }\n }\n\n async setup() {\n const { agents, defaultAgentName } = await this.buildAgentRegistry();\n this.agents = agents;\n this.defaultAgentName = defaultAgentName;\n this.mountInvocationsRoute();\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 const { defs: fileDefs, defaultAgent: fileDefault } =\n await this.loadFileDefinitions();\n\n const codeDefs = this.config.agents ?? {};\n\n for (const name of Object.keys(fileDefs)) {\n if (codeDefs[name]) {\n logger.warn(\n \"Agent '%s' defined in both code and a markdown file. Code definition takes precedence.\",\n name,\n );\n }\n }\n\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(codeDefs)) {\n merged[name] = { def, src: { origin: \"code\" } };\n }\n\n const agents = new Map<string, RegisteredAgent>();\n let defaultAgentName: string | null = null;\n\n if (Object.keys(merged).length === 0) {\n logger.info(\n \"No agents registered (no files in %s, no code-defined agents)\",\n this.resolvedAgentsDir() ?? \"<disabled>\",\n );\n return { agents, defaultAgentName };\n }\n\n for (const [name, { def, src }] of Object.entries(merged)) {\n try {\n const registered = await this.buildRegisteredAgent(name, def, src);\n agents.set(name, registered);\n if (!defaultAgentName) defaultAgentName = name;\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 if (this.config.defaultAgent) {\n if (!agents.has(this.config.defaultAgent)) {\n throw new Error(\n `defaultAgent '${this.config.defaultAgent}' is not registered. Available: ${Array.from(agents.keys()).join(\", \")}`,\n );\n }\n defaultAgentName = this.config.defaultAgent;\n } else if (fileDefault && agents.has(fileDefault)) {\n defaultAgentName = fileDefault;\n }\n\n return { agents, defaultAgentName };\n }\n\n private resolvedAgentsDir(): string | null {\n if (this.config.dir === false) return null;\n const dir = this.config.dir ?? DEFAULT_AGENTS_DIR;\n return path.isAbsolute(dir) ? dir : path.resolve(process.cwd(), dir);\n }\n\n private async loadFileDefinitions(): Promise<{\n defs: Record<string, AgentDefinition>;\n defaultAgent: string | null;\n }> {\n const dir = this.resolvedAgentsDir();\n if (!dir) return { defs: {}, defaultAgent: null };\n\n const pluginToolProviders = this.pluginProviderIndex();\n const ambient = this.config.tools ?? {};\n\n const result = await loadAgentsFromDir(dir, {\n defaultModel: this.config.defaultModel,\n availableTools: ambient,\n plugins: pluginToolProviders,\n codeAgents: this.config.agents,\n });\n\n return result;\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 toolIndex = await this.buildToolIndex(name, def, src);\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 ephemeral: def.ephemeral,\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: { maxSteps?: number; maxTokens?: number } = {};\n if (def.maxSteps !== undefined) adapterOptions.maxSteps = def.maxSteps;\n if (def.maxTokens !== undefined) adapterOptions.maxTokens = def.maxTokens;\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 ): 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 (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 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 private mountInvocationsRoute() {\n if (!this.context) return;\n this.context.addRoute(\n \"post\",\n \"/invocations\",\n (req: express.Request, res: express.Response) => {\n this._handleInvocations(req, res);\n },\n );\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 return {\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\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 { message, threadId, agent: agentName } = 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(req, res, registered, thread, userId);\n }\n\n private async _handleInvocations(\n req: express.Request,\n res: express.Response,\n ) {\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 } = parsed.data;\n const registered = this.resolveAgent();\n if (!registered) {\n res.status(400).json({ error: \"No agent registered\" });\n return;\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._streamAgent(req, res, registered, thread, userId);\n }\n\n private async _streamAgent(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: 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 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 executeTool = (name: string, args: unknown): Promise<unknown> =>\n this.dispatchToolCall(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 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 // The accumulation rule (deltas append, `message` replaces) is shared\n // with `runAgent` and `runSubAgent`; see `consumeAdapterStream` for\n // 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 await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\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 * Dispatch a single tool call from either the top-level adapter or a\n * sub-agent. Centralising this in one method is what makes the budget\n * counter, approval gate, and abort signal observe sub-agent activity:\n * `runSubAgent` reuses the same `runState` and so increments the same\n * counter and emits approval events through the same channel.\n *\n * `depth` is the current sub-agent recursion depth (0 at the top level).\n * It is forwarded to `runSubAgent` when the dispatched entry is itself a\n * sub-agent, so depth limits remain enforced.\n */\n private async dispatchToolCall(\n runState: RunState,\n toolIndex: Map<string, ResolvedToolEntry>,\n name: string,\n args: unknown,\n depth: number,\n ): Promise<unknown> {\n if (runState.toolCallsUsed.count >= runState.limits.maxToolCalls) {\n runState.abortController.abort(\n new Error(\n `Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}).`,\n ),\n );\n throw new Error(\n `Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}). Raise agents({ limits: { maxToolCalls } }) or review the agent's tool-selection logic.`,\n );\n }\n runState.toolCallsUsed.count++;\n\n const entry = toolIndex.get(name);\n if (!entry) throw new Error(`Unknown tool: ${name}`);\n\n if (\n runState.approvalPolicy.requireForDestructive &&\n requiresApproval(entry.def.annotations)\n ) {\n const approvalId = randomUUID();\n for (const ev of runState.translator.translate({\n type: \"approval_pending\",\n approvalId,\n streamId: runState.requestId,\n toolName: name,\n args,\n annotations: entry.def.annotations,\n })) {\n runState.outboundEvents.push(ev);\n }\n const decision = await this.approvalGate.wait({\n approvalId,\n streamId: runState.requestId,\n userId: runState.userId,\n timeoutMs: runState.approvalPolicy.timeoutMs,\n });\n if (decision === \"deny\") {\n return `Tool execution denied by user approval gate (tool: ${name}).`;\n }\n }\n\n let result: unknown;\n if (entry.source === \"toolkit\") {\n if (!this.context) {\n throw new Error(\n \"Plugin tool execution requires PluginContext; this should never happen through createApp\",\n );\n }\n result = await this.context.executeTool(\n runState.req,\n entry.pluginName,\n entry.localName,\n args,\n runState.signal,\n runState.limits.toolCallTimeoutMs,\n );\n } else if (entry.source === \"function\") {\n // Function tools declare their parameters as a JSON-object schema,\n // so adapters always serialize `args` as an object. A non-object\n // value here means the upstream model emitted malformed tool-call\n // JSON; surface a clear error rather than silently passing through\n // a wrong-shape value the tool will then choke on.\n if (typeof args !== \"object\" || args === null || Array.isArray(args)) {\n throw new Error(\n `Function tool '${name}' received non-object arguments (got ${args === null ? \"null\" : Array.isArray(args) ? \"array\" : typeof args}); expected a JSON object.`,\n );\n }\n result = await entry.functionTool.execute(\n args as Record<string, unknown>,\n );\n } else if (entry.source === \"mcp\") {\n if (!this.mcpClient) throw new Error(\"MCP client not connected\");\n const oboToken = runState.req.headers[\"x-forwarded-access-token\"];\n const mcpAuth =\n typeof oboToken === \"string\"\n ? { Authorization: `Bearer ${oboToken}` }\n : undefined;\n result = await this.mcpClient.callTool(entry.mcpToolName, args, mcpAuth);\n } else if (entry.source === \"subagent\") {\n const childAgent = this.agents.get(entry.agentName);\n if (!childAgent)\n throw new Error(`Sub-agent not found: ${entry.agentName}`);\n result = await this.runSubAgent(runState, childAgent, args, depth + 1);\n }\n\n return normalizeToolResult(result);\n }\n\n /**\n * Runs a sub-agent in response to an `agent-<key>` tool call. Returns the\n * concatenated text output to hand back to the parent adapter as the tool\n * result.\n *\n * `depth` starts at 1 for a top-level sub-agent invocation (i.e. the\n * outer `_streamAgent` calls `runSubAgent(..., 1)`) and increments on\n * each nested `runSubAgent` call. Depths exceeding\n * `limits.maxSubAgentDepth` are rejected before any adapter work.\n *\n * Sub-agent tool calls run through `dispatchToolCall` with the same\n * `runState` as the parent — the budget counter and approval gate are\n * therefore enforced for every nested call, not only at the top level.\n */\n private async runSubAgent(\n runState: RunState,\n child: RegisteredAgent,\n args: unknown,\n depth: number,\n ): Promise<string> {\n if (depth > runState.limits.maxSubAgentDepth) {\n throw new Error(\n `Sub-agent depth exceeded (limit ${runState.limits.maxSubAgentDepth}). ` +\n `Raise agents({ limits: { maxSubAgentDepth } }) or break the delegation cycle.`,\n );\n }\n\n const input =\n typeof args === \"object\" &&\n args !== null &&\n typeof (args as { input?: unknown }).input === \"string\"\n ? (args as { input: string }).input\n : JSON.stringify(args);\n const childTools = Array.from(child.toolIndex.values()).map((e) => e.def);\n\n const childExecute = (name: string, childArgs: unknown): Promise<unknown> =>\n this.dispatchToolCall(runState, child.toolIndex, name, childArgs, depth);\n\n const runContext: AgentRunContext = {\n executeTool: childExecute,\n signal: runState.signal,\n };\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n const systemPrompt = composePromptForAgent(\n child,\n this.config.baseSystemPrompt,\n {\n agentName: child.name,\n pluginNames,\n toolNames: childTools.map((t) => t.name),\n },\n );\n\n const messages: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: systemPrompt,\n createdAt: new Date(),\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: input,\n createdAt: new Date(),\n },\n ];\n\n return consumeAdapterStream(\n child.adapter.run(\n {\n messages,\n tools: childTools,\n threadId: randomUUID(),\n signal: runState.signal,\n },\n runContext,\n ),\n {\n signal: runState.signal,\n // Forward every sub-agent event into the parent's outbound SSE\n // stream so the client sees nested tool_call / tool_result events\n // (UI-action tools like apply_filter / highlight_period rely on\n // this) and the sub-agent's streaming text as it's generated.\n //\n // `metadata` is the one exception: sub-agents have their own\n // threadId, and forwarding it would overwrite the parent's\n // thread state on the client and break multi-turn continuity.\n // Approval-pending events emitted by `dispatchToolCall` already\n // reach `outboundEvents` directly, so they are not routed here.\n onEvent: (event) => {\n if (event.type === \"metadata\") return;\n for (const translated of runState.translator.translate(event)) {\n runState.outboundEvents.push(translated);\n }\n },\n },\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.activeStreams.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.activeStreams.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\nfunction composePromptForAgent(\n registered: RegisteredAgent,\n pluginLevel: BaseSystemPromptOption | undefined,\n ctx: PromptContext,\n): string {\n const perAgent = registered.baseSystemPrompt;\n const resolved = perAgent !== undefined ? perAgent : pluginLevel;\n\n let base = \"\";\n if (resolved === false) {\n base = \"\";\n } else if (typeof resolved === \"string\") {\n base = resolved;\n } else if (typeof resolved === \"function\") {\n base = resolved(ctx);\n } else {\n base = buildBaseSystemPrompt(ctx);\n }\n\n return composeSystemPrompt(base, registered.instructions);\n}\n\n/**\n * Plugin factory for the agents plugin. Reads `config/agents/*.md` by default,\n * resolves toolkits/tools from registered plugins, exposes `appkit.agents.*`\n * runtime API and mounts `/invocations`.\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,SAAS,aAAa,SAAS;AAErC,MAAM,qBAAqB;;;;;;;;;;AAoB3B,SAAS,iBAAiB,aAAmD;AAC3E,KAAI,CAAC,YAAa,QAAO;AACzB,KAAI,YAAY,gBAAgB,KAAM,QAAO;AAC7C,SAAQ,YAAY,QAApB;EACE,KAAK;EACL,KAAK;EACL,KAAK,cACH,QAAO;EACT,KAAK;EACL,KAAK,OACH,QAAO;EACT;AAC6B,eAAY;AACvC,UAAO;;;AAiCb,IAAa,eAAb,cAAkC,OAA+B;CAC/D,OAAO,WAAWA;CAClB,OAAO,QAAqB;CAI5B,AAAQ,yBAAS,IAAI,KAA8B;CACnD,AAAQ,mBAAkC;CAC1C,AAAQ,gCAAgB,IAAI,KAGzB;;;;;;;CAOH,AAAQ,mCAAmB,IAAI,KAAqB;CACpD,AAAQ,YAAoC;CAC5C,AAAQ;CACR,AAAQ,eAAe,IAAI,kBAAkB;CAE7C,YAAY,QAA4B;AACtC,QAAM,OAAO;AACb,OAAK,SA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AC5D,KAAI,OAAO,UAAU,UAAW,QAAO;EAAE,MAAM;EAAO,MAAM;EAAO;AACnE,QAAO;EAAE,MAAM,MAAM,QAAQ;EAAO,MAAM,MAAM,QAAQ;EAAO;;AAGjE,SAAS,sBACP,YACA,aACA,KACQ;CACR,MAAM,WAAW,WAAW;CAC5B,MAAM,WAAW,aAAa,SAAY,WAAW;CAErD,IAAI,OAAO;AACX,KAAI,aAAa,MACf,QAAO;UACE,OAAO,aAAa,SAC7B,QAAO;UACE,OAAO,aAAa,WAC7B,QAAO,SAAS,IAAI;KAEpB,QAAO,sBAAsB,IAAI;AAGnC,QAAO,oBAAoB,MAAM,WAAW,aAAa;;;;;;;;;;;;;;;;AAiB3D,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 path from \"node:path\";\nimport type express from \"express\";\nimport pc from \"picocolors\";\nimport type {\n AgentAdapter,\n AgentEvent,\n AgentRunContext,\n AgentToolDefinition,\n IAppRouter,\n Message,\n PluginPhase,\n ResponseOutputMessage,\n ResponseStreamEvent,\n Thread,\n ToolAnnotations,\n ToolProvider,\n} from \"shared\";\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 { normalizeToolResult } from \"../../core/agent/normalize-result\";\nimport { createPluginsProxy } from \"../../core/agent/plugins-map\";\nimport {\n buildBaseSystemPrompt,\n composeSystemPrompt,\n} from \"../../core/agent/system-prompt\";\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 BaseSystemPromptOption,\n Plugins,\n PluginToolkitProvider,\n PromptContext,\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 type { PluginManifest } from \"../../registry\";\nimport { agentStreamDefaults } from \"./defaults\";\nimport { EventChannel } from \"./event-channel\";\nimport { AgentEventTranslator } from \"./event-translator\";\nimport manifest from \"./manifest.json\";\nimport {\n approvalRequestSchema,\n cancelRequestSchema,\n chatRequestSchema,\n invocationsRequestSchema,\n} from \"./schemas\";\nimport { InMemoryThreadStore } from \"./thread-store\";\nimport { ToolApprovalGate } from \"./tool-approval-gate\";\n\nconst logger = createLogger(\"agents\");\n\nconst DEFAULT_AGENTS_DIR = \"./config/agents\";\n\n/**\n * Context flag recorded on the in-memory AgentDefinition to indicate whether\n * it came from markdown (file) or from user code. Drives the asymmetric\n * `autoInheritTools` default.\n */\ninterface AgentSource {\n origin: \"file\" | \"code\";\n}\n\n/**\n * Decide whether a tool call must traverse the approval gate. Honours both\n * the modern `effect` field (mutating values: write / update / destructive)\n * and the legacy `destructive: true` boolean. The contract is documented on\n * `ToolAnnotations.effect` in shared/agent.ts.\n *\n * Without this, a tool authored only with `effect: \"destructive\"` (the\n * preferred API) bypassed the gate entirely.\n */\nfunction requiresApproval(annotations: ToolAnnotations | undefined): boolean {\n if (!annotations) return false;\n if (annotations.destructive === true) return true;\n switch (annotations.effect) {\n case \"write\":\n case \"update\":\n case \"destructive\":\n return true;\n case \"read\":\n case undefined:\n return false;\n default: {\n const _exhaustive: never = annotations.effect;\n return false;\n }\n }\n}\n\n/**\n * Per-stream state shared between the top-level `executeTool` and any\n * `runSubAgent` calls below it. Carrying the budget counter, abort signal,\n * approval policy, and event-channel through one object is what lets the\n * sub-agent path enforce the same limits and approval gate as the parent.\n *\n * Without this shared state the sub-agent path silently bypassed both the\n * tool-call budget and the destructive-tool approval gate.\n */\ninterface RunState {\n req: express.Request;\n userId: string;\n requestId: string;\n abortController: AbortController;\n signal: AbortSignal;\n approvalPolicy: { requireForDestructive: boolean; timeoutMs: number };\n limits: {\n maxConcurrentStreamsPerUser: number;\n maxToolCalls: number;\n maxSubAgentDepth: number;\n toolCallTimeoutMs: number;\n };\n translator: AgentEventTranslator;\n outboundEvents: EventChannel<ResponseStreamEvent>;\n /** Boxed mutable counter shared across parent + all sub-agent dispatches. */\n toolCallsUsed: { count: number };\n}\n\nexport class AgentsPlugin extends Plugin implements ToolProvider {\n static manifest = manifest as PluginManifest;\n static phase: PluginPhase = \"deferred\";\n\n protected declare config: AgentsPluginConfig;\n\n private agents = new Map<string, RegisteredAgent>();\n private defaultAgentName: string | null = null;\n private activeStreams = new Map<\n string,\n { controller: AbortController; userId: string }\n >();\n /**\n * Per-user stream count, kept in sync with `activeStreams` so the\n * concurrent-stream rate limit check is O(1) instead of O(n) over every\n * active stream on every request. Mutated only via {@link trackStream}\n * and {@link untrackStream}.\n */\n private userStreamCounts = new Map<string, number>();\n private mcpClient: AppKitMcpClient | null = null;\n private threadStore;\n private approvalGate = new ToolApprovalGate();\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 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 const cfg = this.config.approval ?? {};\n const APPROVAL_TIMEOUT_FLOOR_MS = 1_000;\n const APPROVAL_TIMEOUT_DEFAULT_MS = 60_000;\n let timeoutMs = cfg.timeoutMs ?? APPROVAL_TIMEOUT_DEFAULT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs < APPROVAL_TIMEOUT_FLOOR_MS) {\n logger.warn(\n \"approval.timeoutMs=%s is below the %sms floor; using default %sms instead. Mutating tool calls would otherwise auto-deny before any UI could respond.\",\n cfg.timeoutMs,\n APPROVAL_TIMEOUT_FLOOR_MS,\n APPROVAL_TIMEOUT_DEFAULT_MS,\n );\n timeoutMs = APPROVAL_TIMEOUT_DEFAULT_MS;\n }\n this.cachedApprovalPolicy = {\n requireForDestructive: cfg.requireForDestructive ?? true,\n timeoutMs,\n };\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 const cfg = this.config.limits ?? {};\n return {\n maxConcurrentStreamsPerUser: cfg.maxConcurrentStreamsPerUser ?? 5,\n maxToolCalls: cfg.maxToolCalls ?? 50,\n maxSubAgentDepth: cfg.maxSubAgentDepth ?? 3,\n // 5 minutes is the floor for cold SQL Warehouse / long Genie /\n // long Lakebase calls. The previous PluginContext default of 30s\n // truncated legitimate analytics queries on cold compute.\n toolCallTimeoutMs: cfg.toolCallTimeoutMs ?? 300_000,\n };\n }\n\n /** Count active streams owned by a given user. O(1). */\n private countUserStreams(userId: string): number {\n return this.userStreamCounts.get(userId) ?? 0;\n }\n\n /**\n * Register a stream for `userId` and bump the per-user counter. Paired\n * with {@link untrackStream}; the two helpers are the only writers to\n * `activeStreams` + `userStreamCounts`, so the counter cannot drift from\n * the map.\n */\n private trackStream(\n requestId: string,\n userId: string,\n controller: AbortController,\n ): void {\n this.activeStreams.set(requestId, { controller, userId });\n this.userStreamCounts.set(\n userId,\n (this.userStreamCounts.get(userId) ?? 0) + 1,\n );\n }\n\n /**\n * Remove a stream from the active map and decrement the per-user\n * counter. Idempotent — calling twice for the same `requestId` is a\n * no-op (the second call sees no entry and returns early).\n */\n private untrackStream(requestId: string): void {\n const entry = this.activeStreams.get(requestId);\n if (!entry) return;\n this.activeStreams.delete(requestId);\n const next = (this.userStreamCounts.get(entry.userId) ?? 0) - 1;\n if (next <= 0) {\n this.userStreamCounts.delete(entry.userId);\n } else {\n this.userStreamCounts.set(entry.userId, next);\n }\n }\n\n async setup() {\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 const { defs: fileDefs, defaultAgent: fileDefault } =\n await this.loadFileDefinitions();\n\n const codeDefs = this.config.agents ?? {};\n\n for (const name of Object.keys(fileDefs)) {\n if (codeDefs[name]) {\n logger.warn(\n \"Agent '%s' defined in both code and a markdown file. Code definition takes precedence.\",\n name,\n );\n }\n }\n\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(codeDefs)) {\n merged[name] = { def, src: { origin: \"code\" } };\n }\n\n const agents = new Map<string, RegisteredAgent>();\n let defaultAgentName: string | null = null;\n\n if (Object.keys(merged).length === 0) {\n logger.info(\n \"No agents registered (no files in %s, no code-defined agents)\",\n this.resolvedAgentsDir() ?? \"<disabled>\",\n );\n return { agents, defaultAgentName };\n }\n\n for (const [name, { def, src }] of Object.entries(merged)) {\n try {\n const registered = await this.buildRegisteredAgent(name, def, src);\n agents.set(name, registered);\n if (!defaultAgentName) defaultAgentName = name;\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 if (this.config.defaultAgent) {\n if (!agents.has(this.config.defaultAgent)) {\n throw new Error(\n `defaultAgent '${this.config.defaultAgent}' is not registered. Available: ${Array.from(agents.keys()).join(\", \")}`,\n );\n }\n defaultAgentName = this.config.defaultAgent;\n } else if (fileDefault && agents.has(fileDefault)) {\n defaultAgentName = fileDefault;\n }\n\n return { agents, defaultAgentName };\n }\n\n private resolvedAgentsDir(): string | null {\n if (this.config.dir === false) return null;\n const dir = this.config.dir ?? DEFAULT_AGENTS_DIR;\n return path.isAbsolute(dir) ? dir : path.resolve(process.cwd(), dir);\n }\n\n private async loadFileDefinitions(): Promise<{\n defs: Record<string, AgentDefinition>;\n defaultAgent: string | null;\n }> {\n const dir = this.resolvedAgentsDir();\n if (!dir) return { defs: {}, defaultAgent: null };\n\n const pluginToolProviders = this.pluginProviderIndex();\n const ambient = this.config.tools ?? {};\n\n const result = await loadAgentsFromDir(dir, {\n defaultModel: this.config.defaultModel,\n availableTools: ambient,\n plugins: pluginToolProviders,\n codeAgents: this.config.agents,\n });\n\n return result;\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 toolIndex = await this.buildToolIndex(name, def, src);\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 ephemeral: def.ephemeral,\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: { maxSteps?: number; maxTokens?: number } = {};\n if (def.maxSteps !== undefined) adapterOptions.maxSteps = def.maxSteps;\n if (def.maxTokens !== undefined) adapterOptions.maxTokens = def.maxTokens;\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 ): 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 (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 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 const handler = (req: express.Request, res: express.Response) => {\n this._handleInvoke(req, res);\n };\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 return {\n agents: Array.from(this.agents.keys()),\n defaultAgent: this.defaultAgentName,\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 { message, threadId, agent: agentName } = 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(req, res, registered, thread, userId);\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 } = 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(req, res, registered, thread, userId);\n }\n\n private async _streamAgent(\n req: express.Request,\n res: express.Response,\n registered: RegisteredAgent,\n thread: Thread,\n userId: 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 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 executeTool = (name: string, args: unknown): Promise<unknown> =>\n this.dispatchToolCall(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 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 // The accumulation rule (deltas append, `message` replaces) is shared\n // with `runAgent` and `runSubAgent`; see `consumeAdapterStream` for\n // 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 await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\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 ): 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 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 executeTool = (name: string, args: unknown): Promise<unknown> =>\n this.dispatchToolCall(runState, registered.toolIndex, name, args, 0);\n\n let fullContent = \"\";\n try {\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 await this.threadStore.addMessage(thread.id, userId, {\n id: randomUUID(),\n role: \"assistant\",\n content: fullContent,\n createdAt: new Date(),\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 output: [message],\n });\n }\n\n /**\n * Dispatch a single tool call from either the top-level adapter or a\n * sub-agent. Centralising this in one method is what makes the budget\n * counter, approval gate, and abort signal observe sub-agent activity:\n * `runSubAgent` reuses the same `runState` and so increments the same\n * counter and emits approval events through the same channel.\n *\n * `depth` is the current sub-agent recursion depth (0 at the top level).\n * It is forwarded to `runSubAgent` when the dispatched entry is itself a\n * sub-agent, so depth limits remain enforced.\n */\n private async dispatchToolCall(\n runState: RunState,\n toolIndex: Map<string, ResolvedToolEntry>,\n name: string,\n args: unknown,\n depth: number,\n ): Promise<unknown> {\n if (runState.toolCallsUsed.count >= runState.limits.maxToolCalls) {\n runState.abortController.abort(\n new Error(\n `Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}).`,\n ),\n );\n throw new Error(\n `Tool-call budget exhausted (limit ${runState.limits.maxToolCalls}). Raise agents({ limits: { maxToolCalls } }) or review the agent's tool-selection logic.`,\n );\n }\n runState.toolCallsUsed.count++;\n\n const entry = toolIndex.get(name);\n if (!entry) throw new Error(`Unknown tool: ${name}`);\n\n if (\n runState.approvalPolicy.requireForDestructive &&\n requiresApproval(entry.def.annotations)\n ) {\n const approvalId = randomUUID();\n for (const ev of runState.translator.translate({\n type: \"approval_pending\",\n approvalId,\n streamId: runState.requestId,\n toolName: name,\n args,\n annotations: entry.def.annotations,\n })) {\n runState.outboundEvents.push(ev);\n }\n const decision = await this.approvalGate.wait({\n approvalId,\n streamId: runState.requestId,\n userId: runState.userId,\n timeoutMs: runState.approvalPolicy.timeoutMs,\n });\n if (decision === \"deny\") {\n return `Tool execution denied by user approval gate (tool: ${name}).`;\n }\n }\n\n let result: unknown;\n if (entry.source === \"toolkit\") {\n if (!this.context) {\n throw new Error(\n \"Plugin tool execution requires PluginContext; this should never happen through createApp\",\n );\n }\n result = await this.context.executeTool(\n runState.req,\n entry.pluginName,\n entry.localName,\n args,\n runState.signal,\n runState.limits.toolCallTimeoutMs,\n );\n } else if (entry.source === \"function\") {\n // Function tools declare their parameters as a JSON-object schema,\n // so adapters always serialize `args` as an object. A non-object\n // value here means the upstream model emitted malformed tool-call\n // JSON; surface a clear error rather than silently passing through\n // a wrong-shape value the tool will then choke on.\n if (typeof args !== \"object\" || args === null || Array.isArray(args)) {\n throw new Error(\n `Function tool '${name}' received non-object arguments (got ${args === null ? \"null\" : Array.isArray(args) ? \"array\" : typeof args}); expected a JSON object.`,\n );\n }\n result = await entry.functionTool.execute(\n args as Record<string, unknown>,\n );\n } else if (entry.source === \"mcp\") {\n if (!this.mcpClient) throw new Error(\"MCP client not connected\");\n const oboToken = runState.req.headers[\"x-forwarded-access-token\"];\n const mcpAuth =\n typeof oboToken === \"string\"\n ? { Authorization: `Bearer ${oboToken}` }\n : undefined;\n result = await this.mcpClient.callTool(entry.mcpToolName, args, mcpAuth);\n } else if (entry.source === \"subagent\") {\n const childAgent = this.agents.get(entry.agentName);\n if (!childAgent)\n throw new Error(`Sub-agent not found: ${entry.agentName}`);\n result = await this.runSubAgent(runState, childAgent, args, depth + 1);\n }\n\n return normalizeToolResult(result);\n }\n\n /**\n * Runs a sub-agent in response to an `agent-<key>` tool call. Returns the\n * concatenated text output to hand back to the parent adapter as the tool\n * result.\n *\n * `depth` starts at 1 for a top-level sub-agent invocation (i.e. the\n * outer `_streamAgent` calls `runSubAgent(..., 1)`) and increments on\n * each nested `runSubAgent` call. Depths exceeding\n * `limits.maxSubAgentDepth` are rejected before any adapter work.\n *\n * Sub-agent tool calls run through `dispatchToolCall` with the same\n * `runState` as the parent — the budget counter and approval gate are\n * therefore enforced for every nested call, not only at the top level.\n */\n private async runSubAgent(\n runState: RunState,\n child: RegisteredAgent,\n args: unknown,\n depth: number,\n ): Promise<string> {\n if (depth > runState.limits.maxSubAgentDepth) {\n throw new Error(\n `Sub-agent depth exceeded (limit ${runState.limits.maxSubAgentDepth}). ` +\n `Raise agents({ limits: { maxSubAgentDepth } }) or break the delegation cycle.`,\n );\n }\n\n const input =\n typeof args === \"object\" &&\n args !== null &&\n typeof (args as { input?: unknown }).input === \"string\"\n ? (args as { input: string }).input\n : JSON.stringify(args);\n const childTools = Array.from(child.toolIndex.values()).map((e) => e.def);\n\n const childExecute = (name: string, childArgs: unknown): Promise<unknown> =>\n this.dispatchToolCall(runState, child.toolIndex, name, childArgs, depth);\n\n const runContext: AgentRunContext = {\n executeTool: childExecute,\n signal: runState.signal,\n };\n\n const pluginNames = this.context\n ? this.context\n .getPluginNames()\n .filter((n) => n !== this.name && n !== \"server\")\n : [];\n const systemPrompt = composePromptForAgent(\n child,\n this.config.baseSystemPrompt,\n {\n agentName: child.name,\n pluginNames,\n toolNames: childTools.map((t) => t.name),\n },\n );\n\n const messages: Message[] = [\n {\n id: \"system\",\n role: \"system\",\n content: systemPrompt,\n createdAt: new Date(),\n },\n {\n id: randomUUID(),\n role: \"user\",\n content: input,\n createdAt: new Date(),\n },\n ];\n\n return consumeAdapterStream(\n child.adapter.run(\n {\n messages,\n tools: childTools,\n threadId: randomUUID(),\n signal: runState.signal,\n },\n runContext,\n ),\n {\n signal: runState.signal,\n // Forward every sub-agent event into the parent's outbound SSE\n // stream so the client sees nested tool_call / tool_result events\n // (UI-action tools like apply_filter / highlight_period rely on\n // this) and the sub-agent's streaming text as it's generated.\n //\n // `metadata` is the one exception: sub-agents have their own\n // threadId, and forwarding it would overwrite the parent's\n // thread state on the client and break multi-turn continuity.\n // Approval-pending events emitted by `dispatchToolCall` already\n // reach `outboundEvents` directly, so they are not routed here.\n onEvent: (event) => {\n if (event.type === \"metadata\") return;\n for (const translated of runState.translator.translate(event)) {\n runState.outboundEvents.push(translated);\n }\n },\n },\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.activeStreams.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.activeStreams.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\nfunction composePromptForAgent(\n registered: RegisteredAgent,\n pluginLevel: BaseSystemPromptOption | undefined,\n ctx: PromptContext,\n): string {\n const perAgent = registered.baseSystemPrompt;\n const resolved = perAgent !== undefined ? perAgent : pluginLevel;\n\n let base = \"\";\n if (resolved === false) {\n base = \"\";\n } else if (typeof resolved === \"string\") {\n base = resolved;\n } else if (typeof resolved === \"function\") {\n base = resolved(ctx);\n } else {\n base = buildBaseSystemPrompt(ctx);\n }\n\n return composeSystemPrompt(base, registered.instructions);\n}\n\n/**\n * Plugin factory for the agents plugin. Reads `config/agents/*.md` by default,\n * resolves toolkits/tools from registered plugins, exposes `appkit.agents.*`\n * runtime API and mounts `POST /invocations` and `POST /responses` (aliased\n * non-streaming invoke 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAM,SAAS,aAAa,SAAS;AAErC,MAAM,qBAAqB;;;;;;;;;;AAoB3B,SAAS,iBAAiB,aAAmD;AAC3E,KAAI,CAAC,YAAa,QAAO;AACzB,KAAI,YAAY,gBAAgB,KAAM,QAAO;AAC7C,SAAQ,YAAY,QAApB;EACE,KAAK;EACL,KAAK;EACL,KAAK,cACH,QAAO;EACT,KAAK;EACL,KAAK,OACH,QAAO;EACT;AAC6B,eAAY;AACvC,UAAO;;;AAiCb,IAAa,eAAb,cAAkC,OAA+B;CAC/D,OAAO,WAAWA;CAClB,OAAO,QAAqB;CAI5B,AAAQ,yBAAS,IAAI,KAA8B;CACnD,AAAQ,mBAAkC;CAC1C,AAAQ,gCAAgB,IAAI,KAGzB;;;;;;;CAOH,AAAQ,mCAAmB,IAAI,KAAqB;CACpD,AAAQ,YAAoC;CAC5C,AAAQ;CACR,AAAQ,eAAe,IAAI,kBAAkB;CAE7C,YAAY,QAA4B;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;AACjC,MAAI,CAAC,KAAK,iBAAkB,MAAK,mBAAmB;;;AAIxD,SAAS,qBAAqB,OAG5B;AAMA,KAAI,UAAU,OAAW,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;;AAGjE,SAAS,sBACP,YACA,aACA,KACQ;CACR,MAAM,WAAW,WAAW;CAC5B,MAAM,WAAW,aAAa,SAAY,WAAW;CAErD,IAAI,OAAO;AACX,KAAI,aAAa,MACf,QAAO;UACE,OAAO,aAAa,SAC7B,QAAO;UACE,OAAO,aAAa,WAC7B,QAAO,SAAS,IAAI;KAEpB,QAAO,sBAAsB,IAAI;AAGnC,QAAO,oBAAoB,MAAM,WAAW,aAAa;;;;;;;;;;;;;;;;;AAkB3D,MAAa,SAAS,SAAS,aAAa"}
@@ -36,7 +36,6 @@ const messageItemSchema = z.object({
36
36
  });
37
37
  const invocationsRequestSchema = z.object({
38
38
  input: z.union([z.string().min(1).max(MAX_INVOCATIONS_INPUT_CHARS), z.array(messageItemSchema).min(1).max(MAX_INVOCATIONS_INPUT_ITEMS, `input array exceeds the ${MAX_INVOCATIONS_INPUT_ITEMS}-item limit`)]),
39
- stream: z.boolean().optional().default(true),
40
39
  model: z.string().optional()
41
40
  });
42
41
  const approvalRequestSchema = z.object({
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.js","names":[],"sources":["../../../src/plugins/agents/schemas.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Static body cap for the `message` field on `POST /chat`. 64 000 characters\n * is well above any legitimate chat turn (~16k tokens at 4 chars/token) and\n * bounds the per-request cost of appending to `InMemoryThreadStore` without\n * requiring per-deployment configuration.\n */\nconst MAX_MESSAGE_CHARS = 64_000;\n\n/** Cap applied to `/invocations` when `input` is a raw string. */\nconst MAX_INVOCATIONS_INPUT_CHARS = 64_000;\n\n/**\n * Cap on the number of items accepted in an `/invocations` `input` array\n * (one element per seeded message). Protects against a single request\n * seeding hundreds of messages into the thread store.\n */\nconst MAX_INVOCATIONS_INPUT_ITEMS = 100;\n\n/** Per-message `content` size cap (string form). */\nconst MAX_INVOCATIONS_ITEM_CHARS = 64_000;\n\n/** Per-message `content` size cap (array form). */\nconst MAX_INVOCATIONS_ITEM_ARRAY_ITEMS = 100;\n\nexport const chatRequestSchema = z.object({\n message: z\n .string()\n .min(1, \"message must not be empty\")\n .max(\n MAX_MESSAGE_CHARS,\n `message exceeds the ${MAX_MESSAGE_CHARS}-character limit`,\n ),\n threadId: z.string().optional(),\n agent: z.string().optional(),\n});\n\nconst messageItemSchema = z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]).optional(),\n content: z\n .union([\n z.string().max(MAX_INVOCATIONS_ITEM_CHARS),\n z.array(z.any()).max(MAX_INVOCATIONS_ITEM_ARRAY_ITEMS),\n ])\n .optional(),\n type: z.string().optional(),\n});\n\nexport const invocationsRequestSchema = z.object({\n input: z.union([\n z.string().min(1).max(MAX_INVOCATIONS_INPUT_CHARS),\n z\n .array(messageItemSchema)\n .min(1)\n .max(\n MAX_INVOCATIONS_INPUT_ITEMS,\n `input array exceeds the ${MAX_INVOCATIONS_INPUT_ITEMS}-item limit`,\n ),\n ]),\n stream: z.boolean().optional().default(true),\n model: z.string().optional(),\n});\n\nexport const approvalRequestSchema = z.object({\n streamId: z.string().min(1, \"streamId is required\"),\n approvalId: z.string().min(1, \"approvalId is required\"),\n decision: z.enum([\"approve\", \"deny\"]),\n});\n\nexport const cancelRequestSchema = z.object({\n streamId: z.string().min(1, \"streamId is required\"),\n});\n"],"mappings":";;;;;;;;;AAQA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;AAOpC,MAAM,8BAA8B;;AAGpC,MAAM,6BAA6B;;AAGnC,MAAM,mCAAmC;AAEzC,MAAa,oBAAoB,EAAE,OAAO;CACxC,SAAS,EACN,QAAQ,CACR,IAAI,GAAG,4BAA4B,CACnC,IACC,mBACA,uBAAuB,kBAAkB,kBAC1C;CACH,UAAU,EAAE,QAAQ,CAAC,UAAU;CAC/B,OAAO,EAAE,QAAQ,CAAC,UAAU;CAC7B,CAAC;AAEF,MAAM,oBAAoB,EAAE,OAAO;CACjC,MAAM,EAAE,KAAK;EAAC;EAAQ;EAAa;EAAS,CAAC,CAAC,UAAU;CACxD,SAAS,EACN,MAAM,CACL,EAAE,QAAQ,CAAC,IAAI,2BAA2B,EAC1C,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,IAAI,iCAAiC,CACvD,CAAC,CACD,UAAU;CACb,MAAM,EAAE,QAAQ,CAAC,UAAU;CAC5B,CAAC;AAEF,MAAa,2BAA2B,EAAE,OAAO;CAC/C,OAAO,EAAE,MAAM,CACb,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,4BAA4B,EAClD,EACG,MAAM,kBAAkB,CACxB,IAAI,EAAE,CACN,IACC,6BACA,2BAA2B,4BAA4B,aACxD,CACJ,CAAC;CACF,QAAQ,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,KAAK;CAC5C,OAAO,EAAE,QAAQ,CAAC,UAAU;CAC7B,CAAC;AAEF,MAAa,wBAAwB,EAAE,OAAO;CAC5C,UAAU,EAAE,QAAQ,CAAC,IAAI,GAAG,uBAAuB;CACnD,YAAY,EAAE,QAAQ,CAAC,IAAI,GAAG,yBAAyB;CACvD,UAAU,EAAE,KAAK,CAAC,WAAW,OAAO,CAAC;CACtC,CAAC;AAEF,MAAa,sBAAsB,EAAE,OAAO,EAC1C,UAAU,EAAE,QAAQ,CAAC,IAAI,GAAG,uBAAuB,EACpD,CAAC"}
1
+ {"version":3,"file":"schemas.js","names":[],"sources":["../../../src/plugins/agents/schemas.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Static body cap for the `message` field on `POST /chat`. 64 000 characters\n * is well above any legitimate chat turn (~16k tokens at 4 chars/token) and\n * bounds the per-request cost of appending to `InMemoryThreadStore` without\n * requiring per-deployment configuration.\n */\nconst MAX_MESSAGE_CHARS = 64_000;\n\n/** Cap applied to `/invocations` when `input` is a raw string. */\nconst MAX_INVOCATIONS_INPUT_CHARS = 64_000;\n\n/**\n * Cap on the number of items accepted in an `/invocations` `input` array\n * (one element per seeded message). Protects against a single request\n * seeding hundreds of messages into the thread store.\n */\nconst MAX_INVOCATIONS_INPUT_ITEMS = 100;\n\n/** Per-message `content` size cap (string form). */\nconst MAX_INVOCATIONS_ITEM_CHARS = 64_000;\n\n/** Per-message `content` size cap (array form). */\nconst MAX_INVOCATIONS_ITEM_ARRAY_ITEMS = 100;\n\nexport const chatRequestSchema = z.object({\n message: z\n .string()\n .min(1, \"message must not be empty\")\n .max(\n MAX_MESSAGE_CHARS,\n `message exceeds the ${MAX_MESSAGE_CHARS}-character limit`,\n ),\n threadId: z.string().optional(),\n agent: z.string().optional(),\n});\n\nconst messageItemSchema = z.object({\n role: z.enum([\"user\", \"assistant\", \"system\"]).optional(),\n content: z\n .union([\n z.string().max(MAX_INVOCATIONS_ITEM_CHARS),\n z.array(z.any()).max(MAX_INVOCATIONS_ITEM_ARRAY_ITEMS),\n ])\n .optional(),\n type: z.string().optional(),\n});\n\nexport const invocationsRequestSchema = z.object({\n input: z.union([\n z.string().min(1).max(MAX_INVOCATIONS_INPUT_CHARS),\n z\n .array(messageItemSchema)\n .min(1)\n .max(\n MAX_INVOCATIONS_INPUT_ITEMS,\n `input array exceeds the ${MAX_INVOCATIONS_INPUT_ITEMS}-item limit`,\n ),\n ]),\n model: z.string().optional(),\n});\n\nexport const approvalRequestSchema = z.object({\n streamId: z.string().min(1, \"streamId is required\"),\n approvalId: z.string().min(1, \"approvalId is required\"),\n decision: z.enum([\"approve\", \"deny\"]),\n});\n\nexport const cancelRequestSchema = z.object({\n streamId: z.string().min(1, \"streamId is required\"),\n});\n"],"mappings":";;;;;;;;;AAQA,MAAM,oBAAoB;;AAG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