@databricks/appkit 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CLAUDE.md +54 -1
  2. package/NOTICE.md +2 -0
  3. package/dist/agents/databricks.d.ts.map +1 -1
  4. package/dist/agents/databricks.js +8 -3
  5. package/dist/agents/databricks.js.map +1 -1
  6. package/dist/appkit/package.js +1 -1
  7. package/dist/beta.d.ts +16 -1
  8. package/dist/beta.js +14 -1
  9. package/dist/connectors/index.js +3 -0
  10. package/dist/connectors/mcp/client.d.ts +85 -0
  11. package/dist/connectors/mcp/client.d.ts.map +1 -0
  12. package/dist/connectors/mcp/client.js +296 -0
  13. package/dist/connectors/mcp/client.js.map +1 -0
  14. package/dist/connectors/mcp/host-policy.d.ts +51 -0
  15. package/dist/connectors/mcp/host-policy.d.ts.map +1 -0
  16. package/dist/connectors/mcp/host-policy.js +168 -0
  17. package/dist/connectors/mcp/host-policy.js.map +1 -0
  18. package/dist/connectors/mcp/index.d.ts +3 -0
  19. package/dist/connectors/mcp/index.js +4 -0
  20. package/dist/connectors/mcp/types.d.ts +16 -0
  21. package/dist/connectors/mcp/types.d.ts.map +1 -0
  22. package/dist/context/index.js +1 -1
  23. package/dist/core/agent/build-toolkit.d.ts +2 -0
  24. package/dist/core/agent/build-toolkit.js +45 -0
  25. package/dist/core/agent/build-toolkit.js.map +1 -0
  26. package/dist/core/agent/consume-adapter-stream.js +33 -0
  27. package/dist/core/agent/consume-adapter-stream.js.map +1 -0
  28. package/dist/core/agent/create-agent.d.ts +27 -0
  29. package/dist/core/agent/create-agent.d.ts.map +1 -0
  30. package/dist/core/agent/create-agent.js +50 -0
  31. package/dist/core/agent/create-agent.js.map +1 -0
  32. package/dist/core/agent/load-agents.d.ts +72 -0
  33. package/dist/core/agent/load-agents.d.ts.map +1 -0
  34. package/dist/core/agent/load-agents.js +268 -0
  35. package/dist/core/agent/load-agents.js.map +1 -0
  36. package/dist/core/agent/normalize-result.js +39 -0
  37. package/dist/core/agent/normalize-result.js.map +1 -0
  38. package/dist/core/agent/plugins-map.js +44 -0
  39. package/dist/core/agent/plugins-map.js.map +1 -0
  40. package/dist/core/agent/run-agent.d.ts +58 -0
  41. package/dist/core/agent/run-agent.d.ts.map +1 -0
  42. package/dist/core/agent/run-agent.js +257 -0
  43. package/dist/core/agent/run-agent.js.map +1 -0
  44. package/dist/core/agent/system-prompt.js +38 -0
  45. package/dist/core/agent/system-prompt.js.map +1 -0
  46. package/dist/core/agent/toolkit-options.js +28 -0
  47. package/dist/core/agent/toolkit-options.js.map +1 -0
  48. package/dist/core/agent/toolkit-resolver.js +44 -0
  49. package/dist/core/agent/toolkit-resolver.js.map +1 -0
  50. package/dist/core/agent/tools/define-tool.d.ts +66 -0
  51. package/dist/core/agent/tools/define-tool.d.ts.map +1 -0
  52. package/dist/core/agent/tools/define-tool.js +50 -0
  53. package/dist/core/agent/tools/define-tool.js.map +1 -0
  54. package/dist/core/agent/tools/function-tool.d.ts +38 -0
  55. package/dist/core/agent/tools/function-tool.d.ts.map +1 -0
  56. package/dist/core/agent/tools/function-tool.js +22 -0
  57. package/dist/core/agent/tools/function-tool.js.map +1 -0
  58. package/dist/core/agent/tools/hosted-tools.d.ts +47 -0
  59. package/dist/core/agent/tools/hosted-tools.d.ts.map +1 -0
  60. package/dist/core/agent/tools/hosted-tools.js +67 -0
  61. package/dist/core/agent/tools/hosted-tools.js.map +1 -0
  62. package/dist/core/agent/tools/index.d.ts +5 -0
  63. package/dist/core/agent/tools/index.js +7 -0
  64. package/dist/core/agent/tools/json-schema.js +24 -0
  65. package/dist/core/agent/tools/json-schema.js.map +1 -0
  66. package/dist/core/agent/tools/sql-policy.js +256 -0
  67. package/dist/core/agent/tools/sql-policy.js.map +1 -0
  68. package/dist/core/agent/tools/tool.d.ts +63 -0
  69. package/dist/core/agent/tools/tool.d.ts.map +1 -0
  70. package/dist/core/agent/tools/tool.js +42 -0
  71. package/dist/core/agent/tools/tool.js.map +1 -0
  72. package/dist/core/agent/types.d.ts +299 -0
  73. package/dist/core/agent/types.d.ts.map +1 -0
  74. package/dist/core/agent/types.js +12 -0
  75. package/dist/core/agent/types.js.map +1 -0
  76. package/dist/core/appkit.d.ts +1 -0
  77. package/dist/core/appkit.d.ts.map +1 -1
  78. package/dist/core/appkit.js +31 -4
  79. package/dist/core/appkit.js.map +1 -1
  80. package/dist/core/plugin-context.d.ts +133 -0
  81. package/dist/core/plugin-context.d.ts.map +1 -0
  82. package/dist/core/plugin-context.js +220 -0
  83. package/dist/core/plugin-context.js.map +1 -0
  84. package/dist/index.d.ts +11 -11
  85. package/dist/internal-telemetry/appkit-log.js +19 -0
  86. package/dist/internal-telemetry/appkit-log.js.map +1 -0
  87. package/dist/internal-telemetry/config.js +15 -0
  88. package/dist/internal-telemetry/config.js.map +1 -0
  89. package/dist/internal-telemetry/index.js +4 -0
  90. package/dist/internal-telemetry/reporter.js +132 -0
  91. package/dist/internal-telemetry/reporter.js.map +1 -0
  92. package/dist/plugin/plugin.d.ts +18 -3
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/plugin/plugin.js +26 -2
  95. package/dist/plugin/plugin.js.map +1 -1
  96. package/dist/plugin/to-plugin.d.ts +3 -2
  97. package/dist/plugin/to-plugin.d.ts.map +1 -1
  98. package/dist/plugin/to-plugin.js +7 -4
  99. package/dist/plugin/to-plugin.js.map +1 -1
  100. package/dist/plugins/agents/agents.d.ts +186 -0
  101. package/dist/plugins/agents/agents.d.ts.map +1 -0
  102. package/dist/plugins/agents/agents.js +979 -0
  103. package/dist/plugins/agents/agents.js.map +1 -0
  104. package/dist/plugins/agents/defaults.js +13 -0
  105. package/dist/plugins/agents/defaults.js.map +1 -0
  106. package/dist/plugins/agents/event-channel.js +64 -0
  107. package/dist/plugins/agents/event-channel.js.map +1 -0
  108. package/dist/plugins/agents/event-translator.js +224 -0
  109. package/dist/plugins/agents/event-translator.js.map +1 -0
  110. package/dist/plugins/agents/index.d.ts +4 -0
  111. package/dist/plugins/agents/index.js +6 -0
  112. package/dist/plugins/agents/manifest.js +26 -0
  113. package/dist/plugins/agents/manifest.js.map +1 -0
  114. package/dist/plugins/agents/schemas.js +51 -0
  115. package/dist/plugins/agents/schemas.js.map +1 -0
  116. package/dist/plugins/agents/thread-store.js +58 -0
  117. package/dist/plugins/agents/thread-store.js.map +1 -0
  118. package/dist/plugins/agents/tool-approval-gate.js +75 -0
  119. package/dist/plugins/agents/tool-approval-gate.js.map +1 -0
  120. package/dist/plugins/analytics/analytics.d.ts +15 -1
  121. package/dist/plugins/analytics/analytics.d.ts.map +1 -1
  122. package/dist/plugins/analytics/analytics.js +37 -2
  123. package/dist/plugins/analytics/analytics.js.map +1 -1
  124. package/dist/plugins/analytics/index.js +1 -0
  125. package/dist/plugins/analytics/types.js +15 -0
  126. package/dist/plugins/analytics/types.js.map +1 -0
  127. package/dist/plugins/beta-exports.generated.d.ts +2 -0
  128. package/dist/plugins/beta-exports.generated.js +4 -0
  129. package/dist/plugins/files/plugin.d.ts +20 -2
  130. package/dist/plugins/files/plugin.d.ts.map +1 -1
  131. package/dist/plugins/files/plugin.js +120 -2
  132. package/dist/plugins/files/plugin.js.map +1 -1
  133. package/dist/plugins/genie/genie.d.ts +17 -3
  134. package/dist/plugins/genie/genie.d.ts.map +1 -1
  135. package/dist/plugins/genie/genie.js +61 -2
  136. package/dist/plugins/genie/genie.js.map +1 -1
  137. package/dist/plugins/genie/types.d.ts +10 -2
  138. package/dist/plugins/genie/types.d.ts.map +1 -1
  139. package/dist/plugins/jobs/plugin.js +1 -1
  140. package/dist/plugins/lakebase/index.d.ts +2 -2
  141. package/dist/plugins/lakebase/index.js +1 -1
  142. package/dist/plugins/lakebase/lakebase.d.ts +31 -3
  143. package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
  144. package/dist/plugins/lakebase/lakebase.js +77 -5
  145. package/dist/plugins/lakebase/lakebase.js.map +1 -1
  146. package/dist/plugins/lakebase/types.d.ts +39 -1
  147. package/dist/plugins/lakebase/types.d.ts.map +1 -1
  148. package/dist/plugins/server/index.d.ts +12 -0
  149. package/dist/plugins/server/index.d.ts.map +1 -1
  150. package/dist/plugins/server/index.js +47 -10
  151. package/dist/plugins/server/index.js.map +1 -1
  152. package/dist/plugins/server/types.d.ts +11 -3
  153. package/dist/plugins/server/types.d.ts.map +1 -1
  154. package/dist/shared/src/agent.d.ts +75 -1
  155. package/dist/shared/src/agent.d.ts.map +1 -1
  156. package/dist/shared/src/index.d.ts +1 -1
  157. package/dist/shared/src/plugin.d.ts +8 -0
  158. package/dist/shared/src/plugin.d.ts.map +1 -1
  159. package/docs/api/appkit/Class.AppKitMcpClient.md +157 -0
  160. package/docs/api/appkit/Class.DatabricksAdapter.md +151 -0
  161. package/docs/api/appkit/Class.Plugin.md +65 -23
  162. package/docs/api/appkit/Function.agentIdFromMarkdownPath.md +18 -0
  163. package/docs/api/appkit/Function.createAgent.md +33 -0
  164. package/docs/api/appkit/Function.createApp.md +10 -8
  165. package/docs/api/appkit/Function.defineTool.md +26 -0
  166. package/docs/api/appkit/Function.executeFromRegistry.md +25 -0
  167. package/docs/api/appkit/Function.functionToolToDefinition.md +16 -0
  168. package/docs/api/appkit/Function.isFunctionTool.md +16 -0
  169. package/docs/api/appkit/Function.isHostedTool.md +16 -0
  170. package/docs/api/appkit/Function.isToolkitEntry.md +18 -0
  171. package/docs/api/appkit/Function.loadAgentFromFile.md +21 -0
  172. package/docs/api/appkit/Function.loadAgentsFromDir.md +26 -0
  173. package/docs/api/appkit/Function.mcpServer.md +28 -0
  174. package/docs/api/appkit/Function.parseTextToolCalls.md +26 -0
  175. package/docs/api/appkit/Function.resolveHostedTools.md +16 -0
  176. package/docs/api/appkit/Function.runAgent.md +26 -0
  177. package/docs/api/appkit/Function.tool.md +28 -0
  178. package/docs/api/appkit/Function.toolsFromRegistry.md +20 -0
  179. package/docs/api/appkit/Interface.AgentAdapter.md +21 -0
  180. package/docs/api/appkit/Interface.AgentDefinition.md +112 -0
  181. package/docs/api/appkit/Interface.AgentInput.md +37 -0
  182. package/docs/api/appkit/Interface.AgentRunContext.md +32 -0
  183. package/docs/api/appkit/Interface.AgentToolDefinition.md +37 -0
  184. package/docs/api/appkit/Interface.AgentsPluginConfig.md +241 -0
  185. package/docs/api/appkit/Interface.AutoInheritToolsConfig.md +27 -0
  186. package/docs/api/appkit/Interface.BasePluginConfig.md +1 -0
  187. package/docs/api/appkit/Interface.FunctionTool.md +80 -0
  188. package/docs/api/appkit/Interface.McpConnectAllResult.md +38 -0
  189. package/docs/api/appkit/Interface.Message.md +55 -0
  190. package/docs/api/appkit/Interface.PluginToolkitProvider.md +22 -0
  191. package/docs/api/appkit/Interface.PromptContext.md +30 -0
  192. package/docs/api/appkit/Interface.RegisteredAgent.md +75 -0
  193. package/docs/api/appkit/Interface.RunAgentInput.md +34 -0
  194. package/docs/api/appkit/Interface.RunAgentResult.md +23 -0
  195. package/docs/api/appkit/Interface.Thread.md +46 -0
  196. package/docs/api/appkit/Interface.ThreadStore.md +103 -0
  197. package/docs/api/appkit/Interface.ToolAnnotations.md +56 -0
  198. package/docs/api/appkit/Interface.ToolConfig.md +72 -0
  199. package/docs/api/appkit/Interface.ToolEntry.md +73 -0
  200. package/docs/api/appkit/Interface.ToolProvider.md +38 -0
  201. package/docs/api/appkit/Interface.ToolkitEntry.md +59 -0
  202. package/docs/api/appkit/Interface.ToolkitOptions.md +45 -0
  203. package/docs/api/appkit/TypeAlias.AgentEvent.md +299 -0
  204. package/docs/api/appkit/TypeAlias.AgentTool.md +11 -0
  205. package/docs/api/appkit/TypeAlias.AgentTools.md +8 -0
  206. package/docs/api/appkit/TypeAlias.AgentToolsFn.md +20 -0
  207. package/docs/api/appkit/TypeAlias.BaseSystemPromptOption.md +9 -0
  208. package/docs/api/appkit/TypeAlias.HostedTool.md +10 -0
  209. package/docs/api/appkit/TypeAlias.Plugins.md +26 -0
  210. package/docs/api/appkit/TypeAlias.ResolvedToolEntry.md +29 -0
  211. package/docs/api/appkit/TypeAlias.ToolRegistry.md +6 -0
  212. package/docs/api/appkit/Variable.agents.md +19 -0
  213. package/docs/api/appkit.md +113 -62
  214. package/docs/plugins/agents.md +441 -0
  215. package/docs/privacy.md +41 -0
  216. package/llms.txt +54 -1
  217. package/package.json +4 -2
  218. package/sbom.cdx.json +1 -1
@@ -0,0 +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,SAAS;AACd,MAAI,OAAO,YACT,MAAK,cAAc,OAAO;OACrB;AACL,QAAK,cAAc,IAAI,qBAA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;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"}
@@ -0,0 +1,13 @@
1
+ //#region src/plugins/agents/defaults.ts
2
+ const agentStreamDefaults = {
3
+ default: {
4
+ cache: { enabled: false },
5
+ retry: { enabled: false },
6
+ timeout: 3e5
7
+ },
8
+ stream: { bufferSize: 200 }
9
+ };
10
+
11
+ //#endregion
12
+ export { agentStreamDefaults };
13
+ //# sourceMappingURL=defaults.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaults.js","names":[],"sources":["../../../src/plugins/agents/defaults.ts"],"sourcesContent":["import type { StreamExecutionSettings } from \"shared\";\n\nexport const agentStreamDefaults: StreamExecutionSettings = {\n default: {\n cache: { enabled: false },\n retry: { enabled: false },\n timeout: 300_000,\n },\n stream: {\n bufferSize: 200,\n },\n};\n"],"mappings":";AAEA,MAAa,sBAA+C;CAC1D,SAAS;EACP,OAAO,EAAE,SAAS,OAAO;EACzB,OAAO,EAAE,SAAS,OAAO;EACzB,SAAS;EACV;CACD,QAAQ,EACN,YAAY,KACb;CACF"}
@@ -0,0 +1,64 @@
1
+ //#region src/plugins/agents/event-channel.ts
2
+ var EventChannel = class {
3
+ queue = [];
4
+ waiters = [];
5
+ closed = false;
6
+ error = void 0;
7
+ /** Synchronously enqueue an event. Safe to call from non-async contexts. */
8
+ push(value) {
9
+ if (this.closed) return;
10
+ const waiter = this.waiters.shift();
11
+ if (waiter) waiter.resolve({
12
+ value,
13
+ done: false
14
+ });
15
+ else this.queue.push(value);
16
+ }
17
+ /**
18
+ * Close the channel. Any pending `next()` calls resolve with `done: true`.
19
+ * If `error` is supplied, pending `next()` calls reject with it and future
20
+ * calls do the same.
21
+ */
22
+ close(error) {
23
+ if (this.closed) return;
24
+ this.closed = true;
25
+ this.error = error;
26
+ while (this.waiters.length > 0) {
27
+ const waiter = this.waiters.shift();
28
+ if (!waiter) break;
29
+ if (error) waiter.reject(error);
30
+ else waiter.resolve({
31
+ value: void 0,
32
+ done: true
33
+ });
34
+ }
35
+ }
36
+ [Symbol.asyncIterator]() {
37
+ return { next: () => {
38
+ if (this.queue.length > 0) {
39
+ const value = this.queue.shift();
40
+ return Promise.resolve({
41
+ value,
42
+ done: false
43
+ });
44
+ }
45
+ if (this.closed) {
46
+ if (this.error) return Promise.reject(this.error);
47
+ return Promise.resolve({
48
+ value: void 0,
49
+ done: true
50
+ });
51
+ }
52
+ return new Promise((resolve, reject) => {
53
+ this.waiters.push({
54
+ resolve,
55
+ reject
56
+ });
57
+ });
58
+ } };
59
+ }
60
+ };
61
+
62
+ //#endregion
63
+ export { EventChannel };
64
+ //# sourceMappingURL=event-channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-channel.js","names":[],"sources":["../../../src/plugins/agents/event-channel.ts"],"sourcesContent":["/**\n * Single-producer/single-consumer async queue used by the agents plugin to\n * merge streams of SSE events from two concurrent sources: the adapter's\n * `run()` generator, and out-of-band events emitted by `executeTool` (e.g.\n * human-approval requests).\n *\n * The consumer drains the channel as an async iterable; the producer pushes\n * events synchronously and closes the channel when the source has completed\n * or errored.\n */\ninterface Waiter<T> {\n resolve: (value: IteratorResult<T>) => void;\n reject: (error: unknown) => void;\n}\n\nexport class EventChannel<T> {\n private queue: T[] = [];\n private waiters: Array<Waiter<T>> = [];\n private closed = false;\n private error: unknown = undefined;\n\n /** Synchronously enqueue an event. Safe to call from non-async contexts. */\n push(value: T): void {\n if (this.closed) return;\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter.resolve({ value, done: false });\n } else {\n this.queue.push(value);\n }\n }\n\n /**\n * Close the channel. Any pending `next()` calls resolve with `done: true`.\n * If `error` is supplied, pending `next()` calls reject with it and future\n * calls do the same.\n */\n close(error?: unknown): void {\n if (this.closed) return;\n this.closed = true;\n this.error = error;\n while (this.waiters.length > 0) {\n const waiter = this.waiters.shift();\n if (!waiter) break;\n if (error) {\n waiter.reject(error);\n } else {\n waiter.resolve({ value: undefined as never, done: true });\n }\n }\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: (): Promise<IteratorResult<T>> => {\n if (this.queue.length > 0) {\n const value = this.queue.shift() as T;\n return Promise.resolve({ value, done: false });\n }\n if (this.closed) {\n if (this.error) return Promise.reject(this.error);\n return Promise.resolve({ value: undefined as never, done: true });\n }\n return new Promise((resolve, reject) => {\n this.waiters.push({ resolve, reject });\n });\n },\n };\n }\n}\n"],"mappings":";AAeA,IAAa,eAAb,MAA6B;CAC3B,AAAQ,QAAa,EAAE;CACvB,AAAQ,UAA4B,EAAE;CACtC,AAAQ,SAAS;CACjB,AAAQ,QAAiB;;CAGzB,KAAK,OAAgB;AACnB,MAAI,KAAK,OAAQ;EACjB,MAAM,SAAS,KAAK,QAAQ,OAAO;AACnC,MAAI,OACF,QAAO,QAAQ;GAAE;GAAO,MAAM;GAAO,CAAC;MAEtC,MAAK,MAAM,KAAK,MAAM;;;;;;;CAS1B,MAAM,OAAuB;AAC3B,MAAI,KAAK,OAAQ;AACjB,OAAK,SAAS;AACd,OAAK,QAAQ;AACb,SAAO,KAAK,QAAQ,SAAS,GAAG;GAC9B,MAAM,SAAS,KAAK,QAAQ,OAAO;AACnC,OAAI,CAAC,OAAQ;AACb,OAAI,MACF,QAAO,OAAO,MAAM;OAEpB,QAAO,QAAQ;IAAE,OAAO;IAAoB,MAAM;IAAM,CAAC;;;CAK/D,CAAC,OAAO,iBAAmC;AACzC,SAAO,EACL,YAAwC;AACtC,OAAI,KAAK,MAAM,SAAS,GAAG;IACzB,MAAM,QAAQ,KAAK,MAAM,OAAO;AAChC,WAAO,QAAQ,QAAQ;KAAE;KAAO,MAAM;KAAO,CAAC;;AAEhD,OAAI,KAAK,QAAQ;AACf,QAAI,KAAK,MAAO,QAAO,QAAQ,OAAO,KAAK,MAAM;AACjD,WAAO,QAAQ,QAAQ;KAAE,OAAO;KAAoB,MAAM;KAAM,CAAC;;AAEnE,UAAO,IAAI,SAAS,SAAS,WAAW;AACtC,SAAK,QAAQ,KAAK;KAAE;KAAS;KAAQ,CAAC;KACtC;KAEL"}
@@ -0,0 +1,224 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ //#region src/plugins/agents/event-translator.ts
4
+ /**
5
+ * Translates internal `AgentEvent` stream into Responses API SSE events.
6
+ *
7
+ * Stateful: one instance per streaming request. Tracks sequence numbers and
8
+ * allocates `output_index` strictly monotonically — each emitted output
9
+ * item (message, function call, function call output) claims the next
10
+ * available index and, once claimed, never reuses an earlier one. This is a
11
+ * Responses-API contract that OpenAI's own SDK parsers enforce.
12
+ *
13
+ * A message is opened lazily on the first `message_delta` or `message`
14
+ * event. If a `tool_call` or `tool_result` arrives while a message is open
15
+ * (common ReAct flow: partial text → tool call → more text), the open
16
+ * message is closed (`response.output_item.done`) BEFORE the tool item is
17
+ * added, so subsequent text resumes as a new message item at a strictly
18
+ * later index.
19
+ */
20
+ var AgentEventTranslator = class {
21
+ seqNum = 0;
22
+ nextOutputIndex = 0;
23
+ currentMessage = null;
24
+ finalized = false;
25
+ translate(event) {
26
+ switch (event.type) {
27
+ case "message_delta": return this.handleMessageDelta(event.content);
28
+ case "message": return this.handleFullMessage(event.content);
29
+ case "tool_call": return this.handleToolCall(event.callId, event.name, event.args);
30
+ case "tool_result": return this.handleToolResult(event.callId, event.result, event.error);
31
+ case "thinking": return [{
32
+ type: "appkit.thinking",
33
+ content: event.content,
34
+ sequence_number: this.seqNum++
35
+ }];
36
+ case "metadata": return [{
37
+ type: "appkit.metadata",
38
+ data: event.data,
39
+ sequence_number: this.seqNum++
40
+ }];
41
+ case "approval_pending": return [{
42
+ type: "appkit.approval_pending",
43
+ approval_id: event.approvalId,
44
+ stream_id: event.streamId,
45
+ tool_name: event.toolName,
46
+ args: event.args,
47
+ annotations: event.annotations,
48
+ sequence_number: this.seqNum++
49
+ }];
50
+ case "status": return this.handleStatus(event.status, event.error);
51
+ }
52
+ }
53
+ finalize() {
54
+ if (this.finalized) return [];
55
+ this.finalized = true;
56
+ const events = [];
57
+ const closeEvent = this.closeCurrentMessage();
58
+ if (closeEvent) events.push(closeEvent);
59
+ events.push({
60
+ type: "response.completed",
61
+ sequence_number: this.seqNum++,
62
+ response: {}
63
+ });
64
+ return events;
65
+ }
66
+ handleMessageDelta(content) {
67
+ const events = [];
68
+ if (!this.currentMessage) {
69
+ const id = `msg_${randomUUID()}`;
70
+ const outputIndex = this.nextOutputIndex++;
71
+ this.currentMessage = {
72
+ id,
73
+ text: content,
74
+ outputIndex
75
+ };
76
+ const item = {
77
+ type: "message",
78
+ id,
79
+ status: "in_progress",
80
+ role: "assistant",
81
+ content: []
82
+ };
83
+ events.push({
84
+ type: "response.output_item.added",
85
+ output_index: outputIndex,
86
+ item,
87
+ sequence_number: this.seqNum++
88
+ });
89
+ } else this.currentMessage.text += content;
90
+ events.push({
91
+ type: "response.output_text.delta",
92
+ item_id: this.currentMessage.id,
93
+ output_index: this.currentMessage.outputIndex,
94
+ content_index: 0,
95
+ delta: content,
96
+ sequence_number: this.seqNum++
97
+ });
98
+ return events;
99
+ }
100
+ handleFullMessage(content) {
101
+ const events = [];
102
+ if (!this.currentMessage) {
103
+ const id = `msg_${randomUUID()}`;
104
+ const outputIndex = this.nextOutputIndex++;
105
+ this.currentMessage = {
106
+ id,
107
+ text: content,
108
+ outputIndex
109
+ };
110
+ const addedItem = {
111
+ type: "message",
112
+ id,
113
+ status: "in_progress",
114
+ role: "assistant",
115
+ content: []
116
+ };
117
+ events.push({
118
+ type: "response.output_item.added",
119
+ output_index: outputIndex,
120
+ item: addedItem,
121
+ sequence_number: this.seqNum++
122
+ });
123
+ } else this.currentMessage.text = content;
124
+ const closeEvent = this.closeCurrentMessage();
125
+ if (closeEvent) events.push(closeEvent);
126
+ return events;
127
+ }
128
+ handleToolCall(callId, name, args) {
129
+ const events = [];
130
+ const closeEvent = this.closeCurrentMessage();
131
+ if (closeEvent) events.push(closeEvent);
132
+ const outputIndex = this.nextOutputIndex++;
133
+ const item = {
134
+ type: "function_call",
135
+ id: `fc_${randomUUID()}`,
136
+ call_id: callId,
137
+ name,
138
+ arguments: typeof args === "string" ? args : JSON.stringify(args)
139
+ };
140
+ events.push({
141
+ type: "response.output_item.added",
142
+ output_index: outputIndex,
143
+ item,
144
+ sequence_number: this.seqNum++
145
+ }, {
146
+ type: "response.output_item.done",
147
+ output_index: outputIndex,
148
+ item,
149
+ sequence_number: this.seqNum++
150
+ });
151
+ return events;
152
+ }
153
+ handleToolResult(callId, result, error) {
154
+ const events = [];
155
+ const closeEvent = this.closeCurrentMessage();
156
+ if (closeEvent) events.push(closeEvent);
157
+ const outputIndex = this.nextOutputIndex++;
158
+ let output;
159
+ if (error !== void 0) output = error;
160
+ else if (typeof result === "string") output = result;
161
+ else if (result === void 0) output = "";
162
+ else output = JSON.stringify(result);
163
+ const item = {
164
+ type: "function_call_output",
165
+ id: `fc_output_${randomUUID()}`,
166
+ call_id: callId,
167
+ output
168
+ };
169
+ events.push({
170
+ type: "response.output_item.added",
171
+ output_index: outputIndex,
172
+ item,
173
+ sequence_number: this.seqNum++
174
+ }, {
175
+ type: "response.output_item.done",
176
+ output_index: outputIndex,
177
+ item,
178
+ sequence_number: this.seqNum++
179
+ });
180
+ return events;
181
+ }
182
+ /**
183
+ * Emit an `response.output_item.done` for the currently-open message, if
184
+ * any, and clear the state. Returns the event to the caller so it can be
185
+ * pushed at the right moment in the sequence. Returns `null` when there
186
+ * is no open message.
187
+ */
188
+ closeCurrentMessage() {
189
+ if (!this.currentMessage) return null;
190
+ const { id, text, outputIndex } = this.currentMessage;
191
+ this.currentMessage = null;
192
+ return {
193
+ type: "response.output_item.done",
194
+ output_index: outputIndex,
195
+ item: {
196
+ type: "message",
197
+ id,
198
+ status: "completed",
199
+ role: "assistant",
200
+ content: [{
201
+ type: "output_text",
202
+ text
203
+ }]
204
+ },
205
+ sequence_number: this.seqNum++
206
+ };
207
+ }
208
+ handleStatus(status, error) {
209
+ if (status === "error") return [{
210
+ type: "error",
211
+ error: error ?? "Unknown error",
212
+ sequence_number: this.seqNum++
213
+ }, {
214
+ type: "response.failed",
215
+ sequence_number: this.seqNum++
216
+ }];
217
+ if (status === "complete") return this.finalize();
218
+ return [];
219
+ }
220
+ };
221
+
222
+ //#endregion
223
+ export { AgentEventTranslator };
224
+ //# sourceMappingURL=event-translator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-translator.js","names":[],"sources":["../../../src/plugins/agents/event-translator.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type {\n AgentEvent,\n ResponseFunctionCallOutput,\n ResponseFunctionToolCall,\n ResponseOutputMessage,\n ResponseStreamEvent,\n} from \"shared\";\n\n/**\n * Translates internal `AgentEvent` stream into Responses API SSE events.\n *\n * Stateful: one instance per streaming request. Tracks sequence numbers and\n * allocates `output_index` strictly monotonically — each emitted output\n * item (message, function call, function call output) claims the next\n * available index and, once claimed, never reuses an earlier one. This is a\n * Responses-API contract that OpenAI's own SDK parsers enforce.\n *\n * A message is opened lazily on the first `message_delta` or `message`\n * event. If a `tool_call` or `tool_result` arrives while a message is open\n * (common ReAct flow: partial text → tool call → more text), the open\n * message is closed (`response.output_item.done`) BEFORE the tool item is\n * added, so subsequent text resumes as a new message item at a strictly\n * later index.\n */\nexport class AgentEventTranslator {\n private seqNum = 0;\n private nextOutputIndex = 0;\n private currentMessage: {\n id: string;\n text: string;\n outputIndex: number;\n } | null = null;\n private finalized = false;\n\n translate(event: AgentEvent): ResponseStreamEvent[] {\n switch (event.type) {\n case \"message_delta\":\n return this.handleMessageDelta(event.content);\n case \"message\":\n return this.handleFullMessage(event.content);\n case \"tool_call\":\n return this.handleToolCall(event.callId, event.name, event.args);\n case \"tool_result\":\n return this.handleToolResult(event.callId, event.result, event.error);\n case \"thinking\":\n return [\n {\n type: \"appkit.thinking\",\n content: event.content,\n sequence_number: this.seqNum++,\n },\n ];\n case \"metadata\":\n return [\n {\n type: \"appkit.metadata\",\n data: event.data,\n sequence_number: this.seqNum++,\n },\n ];\n case \"approval_pending\":\n return [\n {\n type: \"appkit.approval_pending\",\n approval_id: event.approvalId,\n stream_id: event.streamId,\n tool_name: event.toolName,\n args: event.args,\n annotations: event.annotations,\n sequence_number: this.seqNum++,\n },\n ];\n case \"status\":\n return this.handleStatus(event.status, event.error);\n }\n }\n\n finalize(): ResponseStreamEvent[] {\n if (this.finalized) return [];\n this.finalized = true;\n\n const events: ResponseStreamEvent[] = [];\n const closeEvent = this.closeCurrentMessage();\n if (closeEvent) events.push(closeEvent);\n\n events.push({\n type: \"response.completed\",\n sequence_number: this.seqNum++,\n response: {},\n });\n\n return events;\n }\n\n private handleMessageDelta(content: string): ResponseStreamEvent[] {\n const events: ResponseStreamEvent[] = [];\n\n if (!this.currentMessage) {\n const id = `msg_${randomUUID()}`;\n const outputIndex = this.nextOutputIndex++;\n this.currentMessage = { id, text: content, outputIndex };\n const item: ResponseOutputMessage = {\n type: \"message\",\n id,\n status: \"in_progress\",\n role: \"assistant\",\n content: [],\n };\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item,\n sequence_number: this.seqNum++,\n });\n } else {\n this.currentMessage.text += content;\n }\n\n events.push({\n type: \"response.output_text.delta\",\n item_id: this.currentMessage.id,\n output_index: this.currentMessage.outputIndex,\n content_index: 0,\n delta: content,\n sequence_number: this.seqNum++,\n });\n\n return events;\n }\n\n private handleFullMessage(content: string): ResponseStreamEvent[] {\n const events: ResponseStreamEvent[] = [];\n\n if (!this.currentMessage) {\n // No prior deltas — open and immediately close.\n const id = `msg_${randomUUID()}`;\n const outputIndex = this.nextOutputIndex++;\n this.currentMessage = { id, text: content, outputIndex };\n const addedItem: ResponseOutputMessage = {\n type: \"message\",\n id,\n status: \"in_progress\",\n role: \"assistant\",\n content: [],\n };\n events.push({\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item: addedItem,\n sequence_number: this.seqNum++,\n });\n } else {\n // Deltas already opened the item; `message` overrides the accumulated\n // text (per adapter contract) and closes it.\n this.currentMessage.text = content;\n }\n\n const closeEvent = this.closeCurrentMessage();\n if (closeEvent) events.push(closeEvent);\n return events;\n }\n\n private handleToolCall(\n callId: string,\n name: string,\n args: unknown,\n ): ResponseStreamEvent[] {\n const events: ResponseStreamEvent[] = [];\n const closeEvent = this.closeCurrentMessage();\n if (closeEvent) events.push(closeEvent);\n\n const outputIndex = this.nextOutputIndex++;\n const item: ResponseFunctionToolCall = {\n type: \"function_call\",\n id: `fc_${randomUUID()}`,\n call_id: callId,\n name,\n arguments: typeof args === \"string\" ? args : JSON.stringify(args),\n };\n\n events.push(\n {\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item,\n sequence_number: this.seqNum++,\n },\n {\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item,\n sequence_number: this.seqNum++,\n },\n );\n return events;\n }\n\n private handleToolResult(\n callId: string,\n result: unknown,\n error?: string,\n ): ResponseStreamEvent[] {\n const events: ResponseStreamEvent[] = [];\n const closeEvent = this.closeCurrentMessage();\n if (closeEvent) events.push(closeEvent);\n\n const outputIndex = this.nextOutputIndex++;\n // Coalesce `undefined` → \"\" so the wire shape is always a string (the\n // Responses API contract). Non-string results are JSON-serialised.\n let output: string;\n if (error !== undefined) {\n output = error;\n } else if (typeof result === \"string\") {\n output = result;\n } else if (result === undefined) {\n output = \"\";\n } else {\n output = JSON.stringify(result);\n }\n const item: ResponseFunctionCallOutput = {\n type: \"function_call_output\",\n id: `fc_output_${randomUUID()}`,\n call_id: callId,\n output,\n };\n\n events.push(\n {\n type: \"response.output_item.added\",\n output_index: outputIndex,\n item,\n sequence_number: this.seqNum++,\n },\n {\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item,\n sequence_number: this.seqNum++,\n },\n );\n return events;\n }\n\n /**\n * Emit an `response.output_item.done` for the currently-open message, if\n * any, and clear the state. Returns the event to the caller so it can be\n * pushed at the right moment in the sequence. Returns `null` when there\n * is no open message.\n */\n private closeCurrentMessage(): ResponseStreamEvent | null {\n if (!this.currentMessage) return null;\n const { id, text, outputIndex } = this.currentMessage;\n this.currentMessage = null;\n const doneItem: ResponseOutputMessage = {\n type: \"message\",\n id,\n status: \"completed\",\n role: \"assistant\",\n content: [{ type: \"output_text\", text }],\n };\n return {\n type: \"response.output_item.done\",\n output_index: outputIndex,\n item: doneItem,\n sequence_number: this.seqNum++,\n };\n }\n\n private handleStatus(status: string, error?: string): ResponseStreamEvent[] {\n if (status === \"error\") {\n return [\n {\n type: \"error\",\n error: error ?? \"Unknown error\",\n sequence_number: this.seqNum++,\n },\n {\n type: \"response.failed\",\n sequence_number: this.seqNum++,\n },\n ];\n }\n\n if (status === \"complete\") {\n return this.finalize();\n }\n\n return [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,IAAa,uBAAb,MAAkC;CAChC,AAAQ,SAAS;CACjB,AAAQ,kBAAkB;CAC1B,AAAQ,iBAIG;CACX,AAAQ,YAAY;CAEpB,UAAU,OAA0C;AAClD,UAAQ,MAAM,MAAd;GACE,KAAK,gBACH,QAAO,KAAK,mBAAmB,MAAM,QAAQ;GAC/C,KAAK,UACH,QAAO,KAAK,kBAAkB,MAAM,QAAQ;GAC9C,KAAK,YACH,QAAO,KAAK,eAAe,MAAM,QAAQ,MAAM,MAAM,MAAM,KAAK;GAClE,KAAK,cACH,QAAO,KAAK,iBAAiB,MAAM,QAAQ,MAAM,QAAQ,MAAM,MAAM;GACvE,KAAK,WACH,QAAO,CACL;IACE,MAAM;IACN,SAAS,MAAM;IACf,iBAAiB,KAAK;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CACF;AACD,SAAO;;;;;;;;CAST,AAAQ,sBAAkD;AACxD,MAAI,CAAC,KAAK,eAAgB,QAAO;EACjC,MAAM,EAAE,IAAI,MAAM,gBAAgB,KAAK;AACvC,OAAK,iBAAiB;AAQtB,SAAO;GACL,MAAM;GACN,cAAc;GACd,MAVsC;IACtC,MAAM;IACN;IACA,QAAQ;IACR,MAAM;IACN,SAAS,CAAC;KAAE,MAAM;KAAe;KAAM,CAAC;IACzC;GAKC,iBAAiB,KAAK;GACvB;;CAGH,AAAQ,aAAa,QAAgB,OAAuC;AAC1E,MAAI,WAAW,QACb,QAAO,CACL;GACE,MAAM;GACN,OAAO,SAAS;GAChB,iBAAiB,KAAK;GACvB,EACD;GACE,MAAM;GACN,iBAAiB,KAAK;GACvB,CACF;AAGH,MAAI,WAAW,WACb,QAAO,KAAK,UAAU;AAGxB,SAAO,EAAE"}
@@ -0,0 +1,4 @@
1
+ import { AgentDefinition, AgentTool, AgentTools, AgentToolsFn, AgentsPluginConfig, AutoInheritToolsConfig, BaseSystemPromptOption, PluginToolkitProvider, Plugins, PromptContext, RegisteredAgent, ResolvedToolEntry, ToolkitEntry, ToolkitOptions, isToolkitEntry } from "../../core/agent/types.js";
2
+ import "../../core/agent/build-toolkit.js";
3
+ import { LoadContext, LoadResult, agentIdFromMarkdownPath, loadAgentFromFile, loadAgentsFromDir } from "../../core/agent/load-agents.js";
4
+ import { AgentsPlugin, agents } from "./agents.js";
@@ -0,0 +1,6 @@
1
+ import { buildToolkitEntries } from "../../core/agent/build-toolkit.js";
2
+ import { isToolkitEntry } from "../../core/agent/types.js";
3
+ import { agentIdFromMarkdownPath, loadAgentFromFile, loadAgentsFromDir, parseFrontmatter } from "../../core/agent/load-agents.js";
4
+ import { AgentsPlugin, agents } from "./agents.js";
5
+
6
+ export { };
@@ -0,0 +1,26 @@
1
+ //#region src/plugins/agents/manifest.json
2
+ var manifest_default = {
3
+ $schema: "https://databricks.github.io/appkit/schemas/plugin-manifest.schema.json",
4
+ name: "agents",
5
+ displayName: "Agents Plugin",
6
+ stability: "beta",
7
+ description: "AI agents driven by markdown configs or code, with auto-tool-discovery from registered plugins",
8
+ resources: {
9
+ "required": [],
10
+ "optional": [{
11
+ "type": "serving_endpoint",
12
+ "alias": "Default LLM for agents",
13
+ "resourceKey": "agents-serving-endpoint",
14
+ "description": "Default streaming-capable LLM endpoint for agents that don't pin their own model",
15
+ "permission": "CAN_QUERY",
16
+ "fields": { "name": {
17
+ "env": "DATABRICKS_SERVING_ENDPOINT_NAME",
18
+ "description": "Default LLM serving endpoint name"
19
+ } }
20
+ }]
21
+ }
22
+ };
23
+
24
+ //#endregion
25
+ export { manifest_default as default };
26
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.js","names":[],"sources":["../../../src/plugins/agents/manifest.json"],"sourcesContent":[""],"mappings":""}
@@ -0,0 +1,51 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/plugins/agents/schemas.ts
4
+ /**
5
+ * Static body cap for the `message` field on `POST /chat`. 64 000 characters
6
+ * is well above any legitimate chat turn (~16k tokens at 4 chars/token) and
7
+ * bounds the per-request cost of appending to `InMemoryThreadStore` without
8
+ * requiring per-deployment configuration.
9
+ */
10
+ const MAX_MESSAGE_CHARS = 64e3;
11
+ /** Cap applied to `/invocations` when `input` is a raw string. */
12
+ const MAX_INVOCATIONS_INPUT_CHARS = 64e3;
13
+ /**
14
+ * Cap on the number of items accepted in an `/invocations` `input` array
15
+ * (one element per seeded message). Protects against a single request
16
+ * seeding hundreds of messages into the thread store.
17
+ */
18
+ const MAX_INVOCATIONS_INPUT_ITEMS = 100;
19
+ /** Per-message `content` size cap (string form). */
20
+ const MAX_INVOCATIONS_ITEM_CHARS = 64e3;
21
+ /** Per-message `content` size cap (array form). */
22
+ const MAX_INVOCATIONS_ITEM_ARRAY_ITEMS = 100;
23
+ const chatRequestSchema = z.object({
24
+ message: z.string().min(1, "message must not be empty").max(MAX_MESSAGE_CHARS, `message exceeds the ${MAX_MESSAGE_CHARS}-character limit`),
25
+ threadId: z.string().optional(),
26
+ agent: z.string().optional()
27
+ });
28
+ const messageItemSchema = z.object({
29
+ role: z.enum([
30
+ "user",
31
+ "assistant",
32
+ "system"
33
+ ]).optional(),
34
+ content: z.union([z.string().max(MAX_INVOCATIONS_ITEM_CHARS), z.array(z.any()).max(MAX_INVOCATIONS_ITEM_ARRAY_ITEMS)]).optional(),
35
+ type: z.string().optional()
36
+ });
37
+ const invocationsRequestSchema = z.object({
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
+ model: z.string().optional()
41
+ });
42
+ const approvalRequestSchema = z.object({
43
+ streamId: z.string().min(1, "streamId is required"),
44
+ approvalId: z.string().min(1, "approvalId is required"),
45
+ decision: z.enum(["approve", "deny"])
46
+ });
47
+ const cancelRequestSchema = z.object({ streamId: z.string().min(1, "streamId is required") });
48
+
49
+ //#endregion
50
+ export { approvalRequestSchema, cancelRequestSchema, chatRequestSchema, invocationsRequestSchema };
51
+ //# sourceMappingURL=schemas.js.map
@@ -0,0 +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,CA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