@databricks/appkit 0.68.0 → 0.69.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/databricks.d.ts.map +1 -1
- package/dist/agents/databricks.js +31 -8
- package/dist/agents/databricks.js.map +1 -1
- package/dist/appkit/package.js +1 -1
- package/dist/core/agent/skills/types.d.ts +6 -1
- package/dist/core/agent/skills/types.d.ts.map +1 -1
- package/dist/plugins/agents/active-stream-tracker.js +52 -0
- package/dist/plugins/agents/active-stream-tracker.js.map +1 -0
- package/dist/plugins/agents/adapter-extensions.js +50 -0
- package/dist/plugins/agents/adapter-extensions.js.map +1 -0
- package/dist/plugins/agents/agents.d.ts +6 -77
- package/dist/plugins/agents/agents.d.ts.map +1 -1
- package/dist/plugins/agents/agents.js +57 -431
- package/dist/plugins/agents/agents.js.map +1 -1
- package/dist/plugins/agents/approval.js +28 -0
- package/dist/plugins/agents/approval.js.map +1 -0
- package/dist/plugins/agents/builtin-tools.js +39 -0
- package/dist/plugins/agents/builtin-tools.js.map +1 -0
- package/dist/plugins/agents/prompt.js +27 -0
- package/dist/plugins/agents/prompt.js.map +1 -0
- package/dist/plugins/agents/registry.js +56 -0
- package/dist/plugins/agents/registry.js.map +1 -0
- package/dist/plugins/agents/resolve-config.js +40 -0
- package/dist/plugins/agents/resolve-config.js.map +1 -0
- package/dist/plugins/agents/skill-loader.js +139 -0
- package/dist/plugins/agents/skill-loader.js.map +1 -0
- package/dist/plugins/agents/tool-dispatch.js +124 -0
- package/dist/plugins/agents/tool-dispatch.js.map +1 -0
- package/dist/shared/src/schemas/manifest.d.ts +33 -33
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"databricks.d.ts","names":[],"sources":["../../src/agents/databricks.ts"],"mappings":";;;;;;;;;;AAwCA;;UAAiB,gBAAA;EAAgB;EAE/B,WAAA;EAEA;EAAA,KAAA;EAIA;EAFA,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GnB;;;;;;;;EAAA,OAtDW,mBAAA,CACX,OAAA,EAAS,sBAAA,GACR,OAAA,CAAQ,iBAAA;EA4GA;;;;;;;;;;;;;;;AAoZb;;;;;EApZa,OAzDE,gBAAA,CACX,YAAA,WACA,OAAA,GAAU,mBAAA,GACT,OAAA,CAAQ,iBAAA;EA4cF;;;;;;;;;;;;;;;;;;;;;EAAA,OAxZI,iBAAA,CACX,OAAA,EArDQ,2BAAA,GAsDP,OAAA,CAAQ,YAAA;EAKJ,GAAA,CACL,KAAA,EAAO,UAAA,EACP,OAAA,EAAS,eAAA,GACR,cAAA,CAAe,UAAA;;UAuDH,iBAAA;EAAA,QA8CA,gBAAA;EAAA,QAyLA,gBAAA;;;;;;UAoCP,aAAA;EAAA,QAgDA,UAAA;AAAA;;;;;;;;iBA0BM,kBAAA,CACd,IAAA,WACC,KAAA;EAAQ,IAAA;EAAc,IAAA;AAAA"}
|
|
@@ -53,6 +53,15 @@ function isStreamingDeltaToolCall(value) {
|
|
|
53
53
|
function throwIfExceedsStreamLimit(label, currentLength, chunk, max) {
|
|
54
54
|
if (currentLength + chunk.length > max) throw new Error(`DatabricksAdapter: ${label} exceeds configured limit (${max} UTF-16 code units)`);
|
|
55
55
|
}
|
|
56
|
+
/** Text of a harmony `reasoning` part: `summary[].text` plus an optional `text`. */
|
|
57
|
+
function reasoningPartText(part) {
|
|
58
|
+
let text = "";
|
|
59
|
+
if (Array.isArray(part.summary)) {
|
|
60
|
+
for (const s of part.summary) if (isRecord(s) && typeof s.text === "string") text += s.text;
|
|
61
|
+
}
|
|
62
|
+
if (typeof part.text === "string") text += part.text;
|
|
63
|
+
return text;
|
|
64
|
+
}
|
|
56
65
|
function isStreamBodyOptions(o) {
|
|
57
66
|
return "streamBody" in o;
|
|
58
67
|
}
|
|
@@ -347,14 +356,28 @@ var DatabricksAdapter = class DatabricksAdapter {
|
|
|
347
356
|
}
|
|
348
357
|
const deltaUnknown = openAiChoicesDelta(parsed);
|
|
349
358
|
if (!isRecord(deltaUnknown)) continue;
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
359
|
+
const contentUnknown = deltaUnknown.content;
|
|
360
|
+
const parts = typeof contentUnknown === "string" ? [{
|
|
361
|
+
type: "text",
|
|
362
|
+
text: contentUnknown
|
|
363
|
+
}] : Array.isArray(contentUnknown) ? contentUnknown : [];
|
|
364
|
+
for (const part of parts) {
|
|
365
|
+
if (!isRecord(part)) continue;
|
|
366
|
+
if (part.type === "text" && typeof part.text === "string") {
|
|
367
|
+
const content = part.text;
|
|
368
|
+
throwIfExceedsStreamLimit("streamed assistant text", fullText.length, content, this.maxStreamTextChars);
|
|
369
|
+
fullText += content;
|
|
370
|
+
yield {
|
|
371
|
+
type: "message_delta",
|
|
372
|
+
content
|
|
373
|
+
};
|
|
374
|
+
} else if (part.type === "reasoning") {
|
|
375
|
+
const content = reasoningPartText(part);
|
|
376
|
+
if (content) yield {
|
|
377
|
+
type: "thinking",
|
|
378
|
+
content
|
|
379
|
+
};
|
|
380
|
+
}
|
|
358
381
|
}
|
|
359
382
|
const toolCallsRaw = deltaUnknown.tool_calls;
|
|
360
383
|
if (!Array.isArray(toolCallsRaw)) continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"databricks.js","names":["servingStream"],"sources":["../../src/agents/databricks.ts"],"sourcesContent":["import type {\n AgentAdapter,\n AgentEvent,\n AgentInput,\n AgentRunContext,\n AgentToolDefinition,\n} from \"shared\";\n\nimport {\n type StreamBody,\n stream as servingStream,\n} from \"../connectors/serving/client\";\nimport { APPKIT_USER_AGENT, getClientOptions } from \"../context/client-options\";\nimport { createWorkspaceClient } from \"../workspace-client\";\n\n/** Default cap for a single incomplete SSE line tail (DoS guard). */\nconst DEFAULT_MAX_SSE_LINE_CHARS = 1024 * 1024;\n\n/** Default cap for accumulated assistant text from `delta.content`. */\nconst DEFAULT_MAX_STREAM_TEXT_CHARS = 4 * 1024 * 1024;\n\n/** Default cap for accumulated JSON arguments per streamed tool call index. */\nconst DEFAULT_MAX_TOOL_ARGUMENT_CHARS = 2 * 1024 * 1024;\n\n/** Cap text length before running Python-style tool-call regex (ReDoS guard). */\nconst PYTHON_STYLE_TOOL_PARSE_MAX_INPUT = 64 * 1024;\n\n/** Fallback HTTP timeout when the raw fetch adapter path receives no AbortSignal from the runner. */\nconst RAW_FETCH_DEFAULT_TIMEOUT_MS = 120_000;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Optional generation parameters forwarded to the OpenAI-compatible serving\n * request body. Names match the serving API wire keys. Only keys that are set\n * are sent — undefined values are omitted so the endpoint applies its own\n * defaults. Ranges are not validated here; the serving endpoint validates.\n */\nexport interface GenerationParams {\n /** Sampling temperature. */\n temperature?: number;\n /** Nucleus sampling probability mass (`top_p`). */\n top_p?: number;\n /** Stop sequence(s) that end generation. */\n stop?: string | string[];\n /** Penalize tokens by frequency. */\n frequency_penalty?: number;\n /** Penalize tokens by prior presence. */\n presence_penalty?: number;\n}\n\nconst GENERATION_PARAM_KEYS = [\n \"temperature\",\n \"top_p\",\n \"stop\",\n \"frequency_penalty\",\n \"presence_penalty\",\n] as const satisfies readonly (keyof GenerationParams)[];\n\n/** Copy only the set generation params onto the request body. */\nfunction applyGenerationParams(\n body: Record<string, unknown>,\n params: GenerationParams,\n): void {\n for (const key of GENERATION_PARAM_KEYS) {\n const value = params[key];\n if (value !== undefined) body[key] = value;\n }\n}\n\nfunction extractLlamaToolJsonSlice(text: string): string | undefined {\n const start = text.indexOf(\"[{\");\n if (start < 0) return undefined;\n const endBracket = text.lastIndexOf(\"}]\");\n if (endBracket < start) return undefined;\n return text.slice(start, endBracket + 2);\n}\n\n/** OpenAI SSE payload: `{ choices: [{ delta }] }`. */\nfunction openAiChoicesDelta(parsed: unknown): unknown {\n if (!isRecord(parsed)) return undefined;\n const choices = parsed.choices;\n if (!Array.isArray(choices) || choices.length < 1) return undefined;\n const first = choices[0];\n if (!isRecord(first)) return undefined;\n return first.delta;\n}\n\nfunction isStreamingDeltaToolCall(value: unknown): value is DeltaToolCall {\n if (!isRecord(value)) return false;\n return typeof value.index === \"number\";\n}\n\nfunction throwIfExceedsStreamLimit(\n label: string,\n currentLength: number,\n chunk: string,\n max: number,\n): void {\n if (currentLength + chunk.length > max) {\n throw new Error(\n `DatabricksAdapter: ${label} exceeds configured limit (${max} UTF-16 code units)`,\n );\n }\n}\n\n/**\n * Escape-hatch options: provide an `endpointUrl` + `authenticate()` and the\n * adapter uses a bare `fetch()` to call it. Useful for tests and for pointing\n * the adapter at non-workspace endpoints (reverse proxies, mocks).\n */\ninterface RawFetchAdapterOptions {\n endpointUrl: string;\n authenticate: () => Promise<Record<string, string>>;\n maxSteps?: number;\n maxTokens?: number;\n /** Optional generation params forwarded to the serving request body. */\n generationParams?: GenerationParams;\n /** Max length of one SSE line (including an incomplete tail in the buffer). */\n maxSseLineChars?: number;\n /** Max total length of assistant `delta.content` across the stream. */\n maxStreamTextChars?: number;\n /** Max length of streamed `function.arguments` per tool call index. */\n maxToolArgumentsChars?: number;\n}\n\n/**\n * Preferred options: caller provides the transport function directly.\n * The `fromServingEndpoint` / `fromModelServing` factories use this to route\n * through `connectors/serving/stream`, which centralises URL encoding, auth\n * via the SDK's `apiClient.request`, and any future retries/telemetry.\n */\ninterface StreamBodyAdapterOptions {\n streamBody: StreamBody;\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ntype DatabricksAdapterOptions =\n | RawFetchAdapterOptions\n | StreamBodyAdapterOptions;\n\nfunction isStreamBodyOptions(\n o: DatabricksAdapterOptions,\n): o is StreamBodyAdapterOptions {\n return \"streamBody\" in o;\n}\n\n/**\n * Duck-typed subset of the Databricks SDK `WorkspaceClient`. Callers of\n * `fromServingEndpoint` and `fromModelServing` pass a real `WorkspaceClient`,\n * but we only need the `apiClient.request` surface — so we declare the minimal\n * interface rather than importing the SDK type directly. This keeps the adapter\n * free of a hard compile-time dependency on `@databricks/sdk-experimental`.\n */\ninterface WorkspaceClientLike {\n apiClient: {\n request(options: Record<string, unknown>): Promise<unknown>;\n };\n}\n\ninterface ServingEndpointOptions {\n workspaceClient: WorkspaceClientLike;\n endpointName: string;\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ninterface ModelServingOptions {\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n workspaceClient?: WorkspaceClientLike;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ninterface OpenAIMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n /**\n * Opaque Vertex/Gemini \"thought signature\" blob the request must echo\n * back verbatim on the next turn. Vertex's OpenAI-compat proxy emits\n * this as `thoughtSignature` (camelCase) at the top level of the\n * tool_call delta (verified against `gemini-3.1-flash-lite-preview`),\n * and accepts the same spelling back on outbound. Non-Gemini endpoints\n * (Claude on Databricks, external OpenAI-compat models, Llama, etc.)\n * leave this undefined and the serializer omits the key.\n * See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures\n */\n thoughtSignature?: string;\n}\n\ninterface OpenAITool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: unknown;\n };\n}\n\ninterface DeltaToolCall {\n index: number;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n /** See {@link OpenAIToolCall.thoughtSignature}. */\n thoughtSignature?: string;\n}\n\n/**\n * Adapter that talks directly to Databricks Model Serving `/invocations` endpoint.\n *\n * No dependency on the Vercel AI SDK or LangChain. Uses raw `fetch()` to POST\n * OpenAI-compatible payloads and parses the SSE stream itself. Calls\n * `authenticate()` per-request so tokens are always fresh.\n *\n * Handles both structured `tool_calls` responses and text-based tool call\n * fallback parsing for models that output tool calls as text.\n *\n * @example Using the factory (recommended)\n * ```ts\n * import { createApp, createAgent, agents, createWorkspaceClient } from \"@databricks/appkit\";\n * import { DatabricksAdapter } from \"@databricks/appkit/beta\";\n *\n * const adapter = DatabricksAdapter.fromServingEndpoint({\n * workspaceClient: createWorkspaceClient(),\n * endpointName: \"my-endpoint\",\n * });\n *\n * await createApp({\n * plugins: [\n * agents({\n * agents: {\n * assistant: createAgent({\n * instructions: \"You are a helpful assistant.\",\n * model: adapter,\n * }),\n * },\n * }),\n * ],\n * });\n * ```\n *\n * @example Using the raw constructor\n * ```ts\n * const adapter = new DatabricksAdapter({\n * endpointUrl: \"https://host/serving-endpoints/my-endpoint/invocations\",\n * authenticate: async () => ({ Authorization: `Bearer ${token}` }),\n * });\n * ```\n */\nexport class DatabricksAdapter implements AgentAdapter {\n private streamBody: StreamBody;\n private maxSteps: number;\n private maxTokens: number;\n private generationParams: GenerationParams;\n private maxSseLineChars: number;\n private maxStreamTextChars: number;\n private maxToolArgumentsChars: number;\n\n constructor(options: DatabricksAdapterOptions) {\n this.maxSteps = options.maxSteps ?? 10;\n this.maxTokens = options.maxTokens ?? 4096;\n this.generationParams = options.generationParams ?? {};\n this.maxSseLineChars =\n options.maxSseLineChars ?? DEFAULT_MAX_SSE_LINE_CHARS;\n this.maxStreamTextChars =\n options.maxStreamTextChars ?? DEFAULT_MAX_STREAM_TEXT_CHARS;\n this.maxToolArgumentsChars =\n options.maxToolArgumentsChars ?? DEFAULT_MAX_TOOL_ARGUMENT_CHARS;\n\n if (isStreamBodyOptions(options)) {\n this.streamBody = options.streamBody;\n } else {\n const { endpointUrl, authenticate } = options;\n this.streamBody = async (body, signal) => {\n const fetchSignal =\n signal ?? AbortSignal.timeout(RAW_FETCH_DEFAULT_TIMEOUT_MS);\n const authHeaders = await authenticate();\n const response = await fetch(endpointUrl, {\n method: \"POST\",\n headers: {\n \"User-Agent\": APPKIT_USER_AGENT,\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n },\n body: JSON.stringify(body),\n signal: fetchSignal,\n });\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"Unknown error\");\n throw new Error(\n `Databricks API error (${response.status}): ${errorText}`,\n );\n }\n if (!response.body) throw new Error(\"No response body\");\n return response.body;\n };\n }\n }\n\n /**\n * Creates a DatabricksAdapter for a Databricks Model Serving endpoint.\n *\n * Routes through the shared `connectors/serving/stream` helper, which\n * delegates to the SDK's `apiClient.request({ raw: true })`. That gives the\n * adapter centralised URL encoding + authentication with the rest of the\n * serving surface — no bespoke `fetch()` + `authenticate()` plumbing.\n */\n static async fromServingEndpoint(\n options: ServingEndpointOptions,\n ): Promise<DatabricksAdapter> {\n const {\n workspaceClient,\n endpointName,\n maxSteps,\n maxTokens,\n generationParams,\n maxSseLineChars,\n maxStreamTextChars,\n maxToolArgumentsChars,\n } = options;\n return new DatabricksAdapter({\n streamBody: (body, signal) =>\n // Cast through the structural shape: the connector types\n // `workspaceClient` as the SDK's concrete `WorkspaceClient`, but we\n // only need `apiClient.request`.\n servingStream(\n workspaceClient as unknown as Parameters<typeof servingStream>[0],\n endpointName,\n body,\n signal,\n ),\n maxSteps,\n maxTokens,\n generationParams,\n maxSseLineChars,\n maxStreamTextChars,\n maxToolArgumentsChars,\n });\n }\n\n /**\n * Creates a DatabricksAdapter from a Model Serving endpoint name.\n * Auto-creates a WorkspaceClient internally. Reads the endpoint name\n * from the argument or the `DATABRICKS_SERVING_ENDPOINT_NAME` env var.\n *\n * @example\n * ```ts\n * // Reads endpoint from DATABRICKS_SERVING_ENDPOINT_NAME env var\n * const adapter = await DatabricksAdapter.fromModelServing();\n *\n * // Explicit endpoint\n * const adapter = await DatabricksAdapter.fromModelServing(\"my-endpoint\");\n *\n * // With options\n * const adapter = await DatabricksAdapter.fromModelServing(\"my-endpoint\", {\n * maxSteps: 5,\n * maxTokens: 2048,\n * });\n * ```\n */\n static async fromModelServing(\n endpointName?: string,\n options?: ModelServingOptions,\n ): Promise<DatabricksAdapter> {\n const resolvedEndpoint =\n endpointName ?? process.env.DATABRICKS_SERVING_ENDPOINT_NAME;\n\n if (!resolvedEndpoint) {\n throw new Error(\n \"No endpoint name provided and DATABRICKS_SERVING_ENDPOINT_NAME env var is not set. \" +\n \"Pass an endpoint name or set DATABRICKS_SERVING_ENDPOINT_NAME.\",\n );\n }\n\n let workspaceClient: WorkspaceClientLike | undefined =\n options?.workspaceClient;\n if (!workspaceClient) {\n workspaceClient = createWorkspaceClient({\n clientOptions: getClientOptions(),\n }) as unknown as WorkspaceClientLike;\n }\n\n return DatabricksAdapter.fromServingEndpoint({\n workspaceClient,\n endpointName: resolvedEndpoint,\n maxSteps: options?.maxSteps,\n maxTokens: options?.maxTokens,\n generationParams: options?.generationParams,\n maxSseLineChars: options?.maxSseLineChars,\n maxStreamTextChars: options?.maxStreamTextChars,\n maxToolArgumentsChars: options?.maxToolArgumentsChars,\n });\n }\n\n /**\n * Discoverability shim for the Supervisor API adapter. Returns an\n * {@link AgentAdapter} (a `SupervisorApiAdapter` at runtime), NOT a\n * {@link DatabricksAdapter} — the two are separate classes (different\n * wire formats, different lifecycle). The return type is the\n * {@link AgentAdapter} interface so callers aren't bound to the concrete\n * class. Surfaced here so application developers see a single\n * `DatabricksAdapter.from*` autocomplete root.\n *\n * Dynamic-imports `./supervisor-api` to avoid forming a load-time cycle:\n * both files share `connectors/serving/client.ts`.\n *\n * @example\n * ```ts\n * import { DatabricksAdapter } from \"@databricks/appkit/beta\";\n *\n * const model = await DatabricksAdapter.fromSupervisorApi({\n * model: \"databricks-claude-sonnet-4-5\",\n * });\n * ```\n */\n static async fromSupervisorApi(\n options: import(\"./supervisor-api\").SupervisorApiAdapterOptions,\n ): Promise<AgentAdapter> {\n const { fromSupervisorApi } = await import(\"./supervisor-api\");\n return fromSupervisorApi(options);\n }\n\n async *run(\n input: AgentInput,\n context: AgentRunContext,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n // Databricks API requires tool names to match [a-zA-Z0-9_-].\n // Our tool names use dots (e.g. \"analytics.query\"), so we swap dots\n // for double-underscores in the wire format and map back on receipt.\n const nameToWire = new Map<string, string>();\n const wireToName = new Map<string, string>();\n for (const tool of input.tools) {\n const wire = tool.name.replace(/\\./g, \"__\");\n if (wireToName.has(wire) && wireToName.get(wire) !== tool.name) {\n throw new Error(\n `Tool name collision: '${tool.name}' and '${wireToName.get(wire)}' both map to wire name '${wire}'`,\n );\n }\n nameToWire.set(tool.name, wire);\n wireToName.set(wire, tool.name);\n }\n\n const tools = this.buildTools(input.tools, nameToWire);\n const messages = this.buildMessages(input.messages, nameToWire);\n\n yield { type: \"status\", status: \"running\" };\n\n for (let step = 0; step < this.maxSteps; step++) {\n if (context.signal?.aborted) break;\n\n const { text, toolCalls } = yield* this.streamCompletion(\n messages,\n tools,\n context,\n );\n\n if (toolCalls.length === 0) {\n const parsed = parseTextToolCalls(text);\n if (parsed.length > 0) {\n yield* this.executeToolCalls(parsed, messages, context, nameToWire);\n continue;\n }\n break;\n }\n\n messages.push({\n role: \"assistant\",\n content: text || null,\n tool_calls: toolCalls,\n });\n\n for (const tc of toolCalls) {\n const wireName = tc.function.name;\n const originalName = wireToName.get(wireName) ?? wireName;\n yield* this.executeSingleTool(tc, originalName, messages, context);\n }\n }\n }\n\n /** Parse wire arguments, emit tool_call / tool_result, append tool messages. */\n private async *executeSingleTool(\n tc: OpenAIToolCall,\n originalName: string,\n messages: OpenAIMessage[],\n context: AgentRunContext,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n let args: unknown;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = {};\n }\n\n yield { type: \"tool_call\", callId: tc.id, name: originalName, args };\n\n try {\n const result = await context.executeTool(originalName, args);\n const resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n yield { type: \"tool_result\", callId: tc.id, result };\n\n messages.push({\n role: \"tool\",\n content: resultStr,\n tool_call_id: tc.id,\n });\n } catch (error) {\n const errMsg =\n error instanceof Error ? error.message : \"Tool execution failed\";\n\n yield {\n type: \"tool_result\",\n callId: tc.id,\n result: null,\n error: errMsg,\n };\n\n messages.push({\n role: \"tool\",\n content: JSON.stringify({ error: errMsg }),\n tool_call_id: tc.id,\n });\n }\n }\n\n private async *streamCompletion(\n messages: OpenAIMessage[],\n tools: OpenAITool[],\n context: AgentRunContext,\n ): AsyncGenerator<\n AgentEvent,\n { text: string; toolCalls: OpenAIToolCall[] },\n unknown\n > {\n const body: Record<string, unknown> = {\n messages,\n stream: true,\n max_tokens: this.maxTokens,\n };\n\n applyGenerationParams(body, this.generationParams);\n\n if (tools.length > 0) {\n body.tools = tools;\n }\n\n let responseBody: ReadableStream<Uint8Array>;\n try {\n responseBody = await this.streamBody(body, context.signal);\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Stream request failed\";\n yield { type: \"status\", status: \"error\", error: msg };\n throw err;\n }\n\n const reader = responseBody.getReader();\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n let fullText = \"\";\n const toolCallAccumulator = new Map<\n number,\n {\n id: string;\n name: string;\n arguments: string;\n thoughtSignature?: string;\n }\n >();\n\n try {\n while (true) {\n if (context.signal?.aborted) break;\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n if (buffer.length > this.maxSseLineChars) {\n throw new Error(\n `DatabricksAdapter: SSE line buffer exceeds configured limit (${this.maxSseLineChars} UTF-16 code units)`,\n );\n }\n\n for (const line of lines) {\n if (line.length > this.maxSseLineChars) {\n throw new Error(\n `DatabricksAdapter: SSE line exceeds configured limit (${this.maxSseLineChars} UTF-16 code units)`,\n );\n }\n\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data: \")) continue;\n const data = trimmed.slice(6);\n if (data === \"[DONE]\") continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch (parseErr) {\n console.debug(\n \"[DatabricksAdapter] malformed SSE data line JSON\",\n { line: `${data.slice(0, 256)}${data.length > 256 ? \"…\" : \"\"}` },\n parseErr,\n );\n continue;\n }\n\n const deltaUnknown = openAiChoicesDelta(parsed);\n if (!isRecord(deltaUnknown)) continue;\n\n if (typeof deltaUnknown.content === \"string\") {\n const content = deltaUnknown.content;\n throwIfExceedsStreamLimit(\n \"streamed assistant text\",\n fullText.length,\n content,\n this.maxStreamTextChars,\n );\n fullText += content;\n yield { type: \"message_delta\" as const, content };\n }\n\n const toolCallsRaw = deltaUnknown.tool_calls;\n if (!Array.isArray(toolCallsRaw)) continue;\n\n for (const tc of toolCallsRaw) {\n if (!isStreamingDeltaToolCall(tc)) continue;\n const sig = tc.thoughtSignature;\n const existing = toolCallAccumulator.get(tc.index);\n if (existing) {\n if (tc.function?.arguments) {\n throwIfExceedsStreamLimit(\n \"tool call arguments\",\n existing.arguments.length,\n tc.function.arguments,\n this.maxToolArgumentsChars,\n );\n existing.arguments += tc.function.arguments;\n }\n if (sig && !existing.thoughtSignature) {\n existing.thoughtSignature = sig;\n }\n } else {\n const initial = tc.function?.arguments ?? \"\";\n if (initial.length > this.maxToolArgumentsChars) {\n throw new Error(\n `DatabricksAdapter: tool call arguments exceed configured limit (${this.maxToolArgumentsChars} UTF-16 code units)`,\n );\n }\n toolCallAccumulator.set(tc.index, {\n id: tc.id ?? `call_${tc.index}`,\n name: tc.function?.name ?? \"\",\n arguments: initial,\n ...(sig ? { thoughtSignature: sig } : {}),\n });\n }\n }\n }\n }\n } finally {\n try {\n await reader.cancel();\n } catch (cancelErr) {\n console.debug(\n \"[DatabricksAdapter] reader.cancel() failed during teardown\",\n cancelErr,\n );\n }\n try {\n reader.releaseLock();\n } catch (unlockErr) {\n console.debug(\n \"[DatabricksAdapter] reader.releaseLock() failed during teardown\",\n unlockErr,\n );\n }\n }\n\n const toolCalls: OpenAIToolCall[] = Array.from(\n toolCallAccumulator.values(),\n ).map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments || \"{}\" },\n ...(tc.thoughtSignature ? { thoughtSignature: tc.thoughtSignature } : {}),\n }));\n\n return { text: fullText, toolCalls };\n }\n\n private async *executeToolCalls(\n calls: Array<{ name: string; args: unknown }>,\n messages: OpenAIMessage[],\n context: AgentRunContext,\n nameToWire: Map<string, string>,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n const wireToolName = (name: string) =>\n nameToWire.get(name) ?? name.replace(/\\./g, \"__\");\n\n const toolCallObjs: OpenAIToolCall[] = calls.map((c, i) => ({\n id: `text_call_${i}`,\n type: \"function\" as const,\n function: {\n name: wireToolName(c.name),\n arguments: JSON.stringify(c.args),\n },\n }));\n\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: toolCallObjs,\n });\n\n for (let i = 0; i < toolCallObjs.length; i++) {\n const tc = toolCallObjs[i];\n const originalName = calls[i]?.name ?? tc.function.name;\n yield* this.executeSingleTool(tc, originalName, messages, context);\n }\n }\n\n /**\n * Maps AppKit {@link AgentInput} messages into OpenAI-compatible wire messages.\n * Preserves multi-turn tool state (`toolCalls` → `tool_calls`, `toolCallId` →\n * `tool_call_id`) so resumed threads and hydrated history reach the model.\n */\n private buildMessages(\n messages: AgentInput[\"messages\"],\n nameToWire: Map<string, string>,\n ): OpenAIMessage[] {\n const wireToolName = (name: string) =>\n nameToWire.get(name) ?? name.replace(/\\./g, \"__\");\n\n return messages.map((m) => {\n let content: string | null = m.content;\n if (\n m.role === \"assistant\" &&\n m.toolCalls &&\n m.toolCalls.length > 0 &&\n (!m.content || m.content.trim() === \"\")\n ) {\n content = null;\n }\n\n const out: OpenAIMessage = {\n role: m.role as OpenAIMessage[\"role\"],\n content,\n };\n\n if (m.toolCallId) {\n out.tool_call_id = m.toolCallId;\n }\n\n if (m.toolCalls && m.toolCalls.length > 0) {\n out.tool_calls = m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: wireToolName(tc.name),\n arguments:\n typeof tc.args === \"string\"\n ? tc.args\n : JSON.stringify(tc.args ?? {}),\n },\n ...(tc.thoughtSignature\n ? { thoughtSignature: tc.thoughtSignature }\n : {}),\n }));\n }\n\n return out;\n });\n }\n\n private buildTools(\n definitions: AgentToolDefinition[],\n nameToWire: Map<string, string>,\n ): OpenAITool[] {\n return definitions.map((def) => ({\n type: \"function\" as const,\n function: {\n name: nameToWire.get(def.name) ?? def.name,\n description: def.description,\n parameters: def.parameters,\n },\n }));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text-based tool call parsing (fallback)\n// ---------------------------------------------------------------------------\n\n/**\n * Parses text-based tool calls from model output.\n *\n * Handles two formats:\n * 1. Llama native: `[{\"name\": \"tool_name\", \"parameters\": {\"arg\": \"val\"}}]`\n * 2. Python-style: `[tool_name(arg1='val1', arg2='val2')]`\n */\nexport function parseTextToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n const trimmed = text.trim();\n\n const jsonResult = tryParseLlamaJsonToolCalls(trimmed);\n if (jsonResult.length > 0) return jsonResult;\n\n const pyResult = tryParsePythonStyleToolCalls(trimmed);\n if (pyResult.length > 0) return pyResult;\n\n return [];\n}\n\nfunction isLlamaToolJsonItem(value: unknown): value is Record<\n string,\n unknown\n> & {\n name: string;\n} {\n if (!isRecord(value)) return false;\n return typeof value.name === \"string\";\n}\n\nfunction tryParseLlamaJsonToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n const slice = extractLlamaToolJsonSlice(text);\n if (!slice) return [];\n\n try {\n const parsed: unknown = JSON.parse(slice);\n if (!Array.isArray(parsed)) return [];\n\n return parsed.filter(isLlamaToolJsonItem).map((item) => ({\n name: item.name,\n args: item.parameters ?? item.arguments ?? item.args ?? {},\n }));\n } catch {\n return [];\n }\n}\n\nfunction tryParsePythonStyleToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n if (text.length > PYTHON_STYLE_TOOL_PARSE_MAX_INPUT) {\n return [];\n }\n\n const pattern = /\\[?([a-zA-Z_][\\w.]*)\\(([^)]*)\\)\\]?/g;\n const results: Array<{ name: string; args: unknown }> = [];\n\n for (const match of text.matchAll(pattern)) {\n const name = match[1];\n const argsStr = match[2];\n\n const args: Record<string, unknown> = {};\n const argPattern = /(\\w+)\\s*=\\s*(?:'([^']*)'|\"([^\"]*)\"|(\\S+))/g;\n for (const argMatch of argsStr.matchAll(argPattern)) {\n const key = argMatch[1];\n const value = argMatch[2] ?? argMatch[3] ?? argMatch[4];\n args[key] = value;\n }\n\n results.push({ name, args });\n }\n\n return results;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,6BAA6B,OAAO;;AAG1C,MAAM,gCAAgC,IAAI,OAAO;;AAGjD,MAAM,kCAAkC,IAAI,OAAO;;AAGnD,MAAM,oCAAoC,KAAK;;AAG/C,MAAM,+BAA+B;AAErC,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAsBhD,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACD;;AAGD,SAAS,sBACP,MACA,QACM;AACN,MAAK,MAAM,OAAO,uBAAuB;EACvC,MAAM,QAAQ,OAAO;AACrB,MAAI,UAAU,OAAW,MAAK,OAAO;;;AAIzC,SAAS,0BAA0B,MAAkC;CACnE,MAAM,QAAQ,KAAK,QAAQ,KAAK;AAChC,KAAI,QAAQ,EAAG,QAAO;CACtB,MAAM,aAAa,KAAK,YAAY,KAAK;AACzC,KAAI,aAAa,MAAO,QAAO;AAC/B,QAAO,KAAK,MAAM,OAAO,aAAa,EAAE;;;AAI1C,SAAS,mBAAmB,QAA0B;AACpD,KAAI,CAAC,SAAS,OAAO,CAAE,QAAO;CAC9B,MAAM,UAAU,OAAO;AACvB,KAAI,CAAC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,SAAS,EAAG,QAAO;CAC1D,MAAM,QAAQ,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ACG;AACN,SAAO,EAAE;;;AAIb,SAAS,6BACP,MACwC;AACxC,KAAI,KAAK,SAAS,kCAChB,QAAO,EAAE;CAGX,MAAM,UAAU;CAChB,MAAM,UAAkD,EAAE;AAE1D,MAAK,MAAM,SAAS,KAAK,SAAS,QAAQ,EAAE;EAC1C,MAAM,OAAO,MAAM;EACnB,MAAM,UAAU,MAAM;EAEtB,MAAM,OAAgC,EAAE;AAExC,OAAK,MAAM,YAAY,QAAQ,SADZ,6CACgC,EAAE;GACnD,MAAM,MAAM,SAAS;AAErB,QAAK,OADS,SAAS,MAAM,SAAS,MAAM,SAAS;;AAIvD,UAAQ,KAAK;GAAE;GAAM;GAAM,CAAC;;AAG9B,QAAO"}
|
|
1
|
+
{"version":3,"file":"databricks.js","names":["servingStream"],"sources":["../../src/agents/databricks.ts"],"sourcesContent":["import type {\n AgentAdapter,\n AgentEvent,\n AgentInput,\n AgentRunContext,\n AgentToolDefinition,\n} from \"shared\";\n\nimport {\n type StreamBody,\n stream as servingStream,\n} from \"../connectors/serving/client\";\nimport { APPKIT_USER_AGENT, getClientOptions } from \"../context/client-options\";\nimport { createWorkspaceClient } from \"../workspace-client\";\n\n/** Default cap for a single incomplete SSE line tail (DoS guard). */\nconst DEFAULT_MAX_SSE_LINE_CHARS = 1024 * 1024;\n\n/** Default cap for accumulated assistant text from `delta.content`. */\nconst DEFAULT_MAX_STREAM_TEXT_CHARS = 4 * 1024 * 1024;\n\n/** Default cap for accumulated JSON arguments per streamed tool call index. */\nconst DEFAULT_MAX_TOOL_ARGUMENT_CHARS = 2 * 1024 * 1024;\n\n/** Cap text length before running Python-style tool-call regex (ReDoS guard). */\nconst PYTHON_STYLE_TOOL_PARSE_MAX_INPUT = 64 * 1024;\n\n/** Fallback HTTP timeout when the raw fetch adapter path receives no AbortSignal from the runner. */\nconst RAW_FETCH_DEFAULT_TIMEOUT_MS = 120_000;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Optional generation parameters forwarded to the OpenAI-compatible serving\n * request body. Names match the serving API wire keys. Only keys that are set\n * are sent — undefined values are omitted so the endpoint applies its own\n * defaults. Ranges are not validated here; the serving endpoint validates.\n */\nexport interface GenerationParams {\n /** Sampling temperature. */\n temperature?: number;\n /** Nucleus sampling probability mass (`top_p`). */\n top_p?: number;\n /** Stop sequence(s) that end generation. */\n stop?: string | string[];\n /** Penalize tokens by frequency. */\n frequency_penalty?: number;\n /** Penalize tokens by prior presence. */\n presence_penalty?: number;\n}\n\nconst GENERATION_PARAM_KEYS = [\n \"temperature\",\n \"top_p\",\n \"stop\",\n \"frequency_penalty\",\n \"presence_penalty\",\n] as const satisfies readonly (keyof GenerationParams)[];\n\n/** Copy only the set generation params onto the request body. */\nfunction applyGenerationParams(\n body: Record<string, unknown>,\n params: GenerationParams,\n): void {\n for (const key of GENERATION_PARAM_KEYS) {\n const value = params[key];\n if (value !== undefined) body[key] = value;\n }\n}\n\nfunction extractLlamaToolJsonSlice(text: string): string | undefined {\n const start = text.indexOf(\"[{\");\n if (start < 0) return undefined;\n const endBracket = text.lastIndexOf(\"}]\");\n if (endBracket < start) return undefined;\n return text.slice(start, endBracket + 2);\n}\n\n/** OpenAI SSE payload: `{ choices: [{ delta }] }`. */\nfunction openAiChoicesDelta(parsed: unknown): unknown {\n if (!isRecord(parsed)) return undefined;\n const choices = parsed.choices;\n if (!Array.isArray(choices) || choices.length < 1) return undefined;\n const first = choices[0];\n if (!isRecord(first)) return undefined;\n return first.delta;\n}\n\nfunction isStreamingDeltaToolCall(value: unknown): value is DeltaToolCall {\n if (!isRecord(value)) return false;\n return typeof value.index === \"number\";\n}\n\nfunction throwIfExceedsStreamLimit(\n label: string,\n currentLength: number,\n chunk: string,\n max: number,\n): void {\n if (currentLength + chunk.length > max) {\n throw new Error(\n `DatabricksAdapter: ${label} exceeds configured limit (${max} UTF-16 code units)`,\n );\n }\n}\n\n/** Text of a harmony `reasoning` part: `summary[].text` plus an optional `text`. */\nfunction reasoningPartText(part: Record<string, unknown>): string {\n let text = \"\";\n if (Array.isArray(part.summary)) {\n for (const s of part.summary) {\n if (isRecord(s) && typeof s.text === \"string\") text += s.text;\n }\n }\n if (typeof part.text === \"string\") text += part.text;\n return text;\n}\n\n/**\n * Escape-hatch options: provide an `endpointUrl` + `authenticate()` and the\n * adapter uses a bare `fetch()` to call it. Useful for tests and for pointing\n * the adapter at non-workspace endpoints (reverse proxies, mocks).\n */\ninterface RawFetchAdapterOptions {\n endpointUrl: string;\n authenticate: () => Promise<Record<string, string>>;\n maxSteps?: number;\n maxTokens?: number;\n /** Optional generation params forwarded to the serving request body. */\n generationParams?: GenerationParams;\n /** Max length of one SSE line (including an incomplete tail in the buffer). */\n maxSseLineChars?: number;\n /** Max total length of assistant `delta.content` across the stream. */\n maxStreamTextChars?: number;\n /** Max length of streamed `function.arguments` per tool call index. */\n maxToolArgumentsChars?: number;\n}\n\n/**\n * Preferred options: caller provides the transport function directly.\n * The `fromServingEndpoint` / `fromModelServing` factories use this to route\n * through `connectors/serving/stream`, which centralises URL encoding, auth\n * via the SDK's `apiClient.request`, and any future retries/telemetry.\n */\ninterface StreamBodyAdapterOptions {\n streamBody: StreamBody;\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ntype DatabricksAdapterOptions =\n | RawFetchAdapterOptions\n | StreamBodyAdapterOptions;\n\nfunction isStreamBodyOptions(\n o: DatabricksAdapterOptions,\n): o is StreamBodyAdapterOptions {\n return \"streamBody\" in o;\n}\n\n/**\n * Duck-typed subset of the Databricks SDK `WorkspaceClient`. Callers of\n * `fromServingEndpoint` and `fromModelServing` pass a real `WorkspaceClient`,\n * but we only need the `apiClient.request` surface — so we declare the minimal\n * interface rather than importing the SDK type directly. This keeps the adapter\n * free of a hard compile-time dependency on `@databricks/sdk-experimental`.\n */\ninterface WorkspaceClientLike {\n apiClient: {\n request(options: Record<string, unknown>): Promise<unknown>;\n };\n}\n\ninterface ServingEndpointOptions {\n workspaceClient: WorkspaceClientLike;\n endpointName: string;\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ninterface ModelServingOptions {\n maxSteps?: number;\n maxTokens?: number;\n generationParams?: GenerationParams;\n workspaceClient?: WorkspaceClientLike;\n maxSseLineChars?: number;\n maxStreamTextChars?: number;\n maxToolArgumentsChars?: number;\n}\n\ninterface OpenAIMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | null;\n tool_calls?: OpenAIToolCall[];\n tool_call_id?: string;\n}\n\ninterface OpenAIToolCall {\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n /**\n * Opaque Vertex/Gemini \"thought signature\" blob the request must echo\n * back verbatim on the next turn. Vertex's OpenAI-compat proxy emits\n * this as `thoughtSignature` (camelCase) at the top level of the\n * tool_call delta (verified against `gemini-3.1-flash-lite-preview`),\n * and accepts the same spelling back on outbound. Non-Gemini endpoints\n * (Claude on Databricks, external OpenAI-compat models, Llama, etc.)\n * leave this undefined and the serializer omits the key.\n * See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thought-signatures\n */\n thoughtSignature?: string;\n}\n\ninterface OpenAITool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: unknown;\n };\n}\n\ninterface DeltaToolCall {\n index: number;\n id?: string;\n type?: string;\n function?: { name?: string; arguments?: string };\n /** See {@link OpenAIToolCall.thoughtSignature}. */\n thoughtSignature?: string;\n}\n\n/**\n * Adapter that talks directly to Databricks Model Serving `/invocations` endpoint.\n *\n * No dependency on the Vercel AI SDK or LangChain. Uses raw `fetch()` to POST\n * OpenAI-compatible payloads and parses the SSE stream itself. Calls\n * `authenticate()` per-request so tokens are always fresh.\n *\n * Handles both structured `tool_calls` responses and text-based tool call\n * fallback parsing for models that output tool calls as text.\n *\n * @example Using the factory (recommended)\n * ```ts\n * import { createApp, createAgent, agents, createWorkspaceClient } from \"@databricks/appkit\";\n * import { DatabricksAdapter } from \"@databricks/appkit/beta\";\n *\n * const adapter = DatabricksAdapter.fromServingEndpoint({\n * workspaceClient: createWorkspaceClient(),\n * endpointName: \"my-endpoint\",\n * });\n *\n * await createApp({\n * plugins: [\n * agents({\n * agents: {\n * assistant: createAgent({\n * instructions: \"You are a helpful assistant.\",\n * model: adapter,\n * }),\n * },\n * }),\n * ],\n * });\n * ```\n *\n * @example Using the raw constructor\n * ```ts\n * const adapter = new DatabricksAdapter({\n * endpointUrl: \"https://host/serving-endpoints/my-endpoint/invocations\",\n * authenticate: async () => ({ Authorization: `Bearer ${token}` }),\n * });\n * ```\n */\nexport class DatabricksAdapter implements AgentAdapter {\n private streamBody: StreamBody;\n private maxSteps: number;\n private maxTokens: number;\n private generationParams: GenerationParams;\n private maxSseLineChars: number;\n private maxStreamTextChars: number;\n private maxToolArgumentsChars: number;\n\n constructor(options: DatabricksAdapterOptions) {\n this.maxSteps = options.maxSteps ?? 10;\n this.maxTokens = options.maxTokens ?? 4096;\n this.generationParams = options.generationParams ?? {};\n this.maxSseLineChars =\n options.maxSseLineChars ?? DEFAULT_MAX_SSE_LINE_CHARS;\n this.maxStreamTextChars =\n options.maxStreamTextChars ?? DEFAULT_MAX_STREAM_TEXT_CHARS;\n this.maxToolArgumentsChars =\n options.maxToolArgumentsChars ?? DEFAULT_MAX_TOOL_ARGUMENT_CHARS;\n\n if (isStreamBodyOptions(options)) {\n this.streamBody = options.streamBody;\n } else {\n const { endpointUrl, authenticate } = options;\n this.streamBody = async (body, signal) => {\n const fetchSignal =\n signal ?? AbortSignal.timeout(RAW_FETCH_DEFAULT_TIMEOUT_MS);\n const authHeaders = await authenticate();\n const response = await fetch(endpointUrl, {\n method: \"POST\",\n headers: {\n \"User-Agent\": APPKIT_USER_AGENT,\n \"Content-Type\": \"application/json\",\n ...authHeaders,\n },\n body: JSON.stringify(body),\n signal: fetchSignal,\n });\n if (!response.ok) {\n const errorText = await response.text().catch(() => \"Unknown error\");\n throw new Error(\n `Databricks API error (${response.status}): ${errorText}`,\n );\n }\n if (!response.body) throw new Error(\"No response body\");\n return response.body;\n };\n }\n }\n\n /**\n * Creates a DatabricksAdapter for a Databricks Model Serving endpoint.\n *\n * Routes through the shared `connectors/serving/stream` helper, which\n * delegates to the SDK's `apiClient.request({ raw: true })`. That gives the\n * adapter centralised URL encoding + authentication with the rest of the\n * serving surface — no bespoke `fetch()` + `authenticate()` plumbing.\n */\n static async fromServingEndpoint(\n options: ServingEndpointOptions,\n ): Promise<DatabricksAdapter> {\n const {\n workspaceClient,\n endpointName,\n maxSteps,\n maxTokens,\n generationParams,\n maxSseLineChars,\n maxStreamTextChars,\n maxToolArgumentsChars,\n } = options;\n return new DatabricksAdapter({\n streamBody: (body, signal) =>\n // Cast through the structural shape: the connector types\n // `workspaceClient` as the SDK's concrete `WorkspaceClient`, but we\n // only need `apiClient.request`.\n servingStream(\n workspaceClient as unknown as Parameters<typeof servingStream>[0],\n endpointName,\n body,\n signal,\n ),\n maxSteps,\n maxTokens,\n generationParams,\n maxSseLineChars,\n maxStreamTextChars,\n maxToolArgumentsChars,\n });\n }\n\n /**\n * Creates a DatabricksAdapter from a Model Serving endpoint name.\n * Auto-creates a WorkspaceClient internally. Reads the endpoint name\n * from the argument or the `DATABRICKS_SERVING_ENDPOINT_NAME` env var.\n *\n * @example\n * ```ts\n * // Reads endpoint from DATABRICKS_SERVING_ENDPOINT_NAME env var\n * const adapter = await DatabricksAdapter.fromModelServing();\n *\n * // Explicit endpoint\n * const adapter = await DatabricksAdapter.fromModelServing(\"my-endpoint\");\n *\n * // With options\n * const adapter = await DatabricksAdapter.fromModelServing(\"my-endpoint\", {\n * maxSteps: 5,\n * maxTokens: 2048,\n * });\n * ```\n */\n static async fromModelServing(\n endpointName?: string,\n options?: ModelServingOptions,\n ): Promise<DatabricksAdapter> {\n const resolvedEndpoint =\n endpointName ?? process.env.DATABRICKS_SERVING_ENDPOINT_NAME;\n\n if (!resolvedEndpoint) {\n throw new Error(\n \"No endpoint name provided and DATABRICKS_SERVING_ENDPOINT_NAME env var is not set. \" +\n \"Pass an endpoint name or set DATABRICKS_SERVING_ENDPOINT_NAME.\",\n );\n }\n\n let workspaceClient: WorkspaceClientLike | undefined =\n options?.workspaceClient;\n if (!workspaceClient) {\n workspaceClient = createWorkspaceClient({\n clientOptions: getClientOptions(),\n }) as unknown as WorkspaceClientLike;\n }\n\n return DatabricksAdapter.fromServingEndpoint({\n workspaceClient,\n endpointName: resolvedEndpoint,\n maxSteps: options?.maxSteps,\n maxTokens: options?.maxTokens,\n generationParams: options?.generationParams,\n maxSseLineChars: options?.maxSseLineChars,\n maxStreamTextChars: options?.maxStreamTextChars,\n maxToolArgumentsChars: options?.maxToolArgumentsChars,\n });\n }\n\n /**\n * Discoverability shim for the Supervisor API adapter. Returns an\n * {@link AgentAdapter} (a `SupervisorApiAdapter` at runtime), NOT a\n * {@link DatabricksAdapter} — the two are separate classes (different\n * wire formats, different lifecycle). The return type is the\n * {@link AgentAdapter} interface so callers aren't bound to the concrete\n * class. Surfaced here so application developers see a single\n * `DatabricksAdapter.from*` autocomplete root.\n *\n * Dynamic-imports `./supervisor-api` to avoid forming a load-time cycle:\n * both files share `connectors/serving/client.ts`.\n *\n * @example\n * ```ts\n * import { DatabricksAdapter } from \"@databricks/appkit/beta\";\n *\n * const model = await DatabricksAdapter.fromSupervisorApi({\n * model: \"databricks-claude-sonnet-4-5\",\n * });\n * ```\n */\n static async fromSupervisorApi(\n options: import(\"./supervisor-api\").SupervisorApiAdapterOptions,\n ): Promise<AgentAdapter> {\n const { fromSupervisorApi } = await import(\"./supervisor-api\");\n return fromSupervisorApi(options);\n }\n\n async *run(\n input: AgentInput,\n context: AgentRunContext,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n // Databricks API requires tool names to match [a-zA-Z0-9_-].\n // Our tool names use dots (e.g. \"analytics.query\"), so we swap dots\n // for double-underscores in the wire format and map back on receipt.\n const nameToWire = new Map<string, string>();\n const wireToName = new Map<string, string>();\n for (const tool of input.tools) {\n const wire = tool.name.replace(/\\./g, \"__\");\n if (wireToName.has(wire) && wireToName.get(wire) !== tool.name) {\n throw new Error(\n `Tool name collision: '${tool.name}' and '${wireToName.get(wire)}' both map to wire name '${wire}'`,\n );\n }\n nameToWire.set(tool.name, wire);\n wireToName.set(wire, tool.name);\n }\n\n const tools = this.buildTools(input.tools, nameToWire);\n const messages = this.buildMessages(input.messages, nameToWire);\n\n yield { type: \"status\", status: \"running\" };\n\n for (let step = 0; step < this.maxSteps; step++) {\n if (context.signal?.aborted) break;\n\n const { text, toolCalls } = yield* this.streamCompletion(\n messages,\n tools,\n context,\n );\n\n if (toolCalls.length === 0) {\n const parsed = parseTextToolCalls(text);\n if (parsed.length > 0) {\n yield* this.executeToolCalls(parsed, messages, context, nameToWire);\n continue;\n }\n break;\n }\n\n messages.push({\n role: \"assistant\",\n content: text || null,\n tool_calls: toolCalls,\n });\n\n for (const tc of toolCalls) {\n const wireName = tc.function.name;\n const originalName = wireToName.get(wireName) ?? wireName;\n yield* this.executeSingleTool(tc, originalName, messages, context);\n }\n }\n }\n\n /** Parse wire arguments, emit tool_call / tool_result, append tool messages. */\n private async *executeSingleTool(\n tc: OpenAIToolCall,\n originalName: string,\n messages: OpenAIMessage[],\n context: AgentRunContext,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n let args: unknown;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = {};\n }\n\n yield { type: \"tool_call\", callId: tc.id, name: originalName, args };\n\n try {\n const result = await context.executeTool(originalName, args);\n const resultStr =\n typeof result === \"string\" ? result : JSON.stringify(result);\n\n yield { type: \"tool_result\", callId: tc.id, result };\n\n messages.push({\n role: \"tool\",\n content: resultStr,\n tool_call_id: tc.id,\n });\n } catch (error) {\n const errMsg =\n error instanceof Error ? error.message : \"Tool execution failed\";\n\n yield {\n type: \"tool_result\",\n callId: tc.id,\n result: null,\n error: errMsg,\n };\n\n messages.push({\n role: \"tool\",\n content: JSON.stringify({ error: errMsg }),\n tool_call_id: tc.id,\n });\n }\n }\n\n private async *streamCompletion(\n messages: OpenAIMessage[],\n tools: OpenAITool[],\n context: AgentRunContext,\n ): AsyncGenerator<\n AgentEvent,\n { text: string; toolCalls: OpenAIToolCall[] },\n unknown\n > {\n const body: Record<string, unknown> = {\n messages,\n stream: true,\n max_tokens: this.maxTokens,\n };\n\n applyGenerationParams(body, this.generationParams);\n\n if (tools.length > 0) {\n body.tools = tools;\n }\n\n let responseBody: ReadableStream<Uint8Array>;\n try {\n responseBody = await this.streamBody(body, context.signal);\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Stream request failed\";\n yield { type: \"status\", status: \"error\", error: msg };\n throw err;\n }\n\n const reader = responseBody.getReader();\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n let fullText = \"\";\n const toolCallAccumulator = new Map<\n number,\n {\n id: string;\n name: string;\n arguments: string;\n thoughtSignature?: string;\n }\n >();\n\n try {\n while (true) {\n if (context.signal?.aborted) break;\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\";\n\n if (buffer.length > this.maxSseLineChars) {\n throw new Error(\n `DatabricksAdapter: SSE line buffer exceeds configured limit (${this.maxSseLineChars} UTF-16 code units)`,\n );\n }\n\n for (const line of lines) {\n if (line.length > this.maxSseLineChars) {\n throw new Error(\n `DatabricksAdapter: SSE line exceeds configured limit (${this.maxSseLineChars} UTF-16 code units)`,\n );\n }\n\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"data: \")) continue;\n const data = trimmed.slice(6);\n if (data === \"[DONE]\") continue;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch (parseErr) {\n console.debug(\n \"[DatabricksAdapter] malformed SSE data line JSON\",\n { line: `${data.slice(0, 256)}${data.length > 256 ? \"…\" : \"\"}` },\n parseErr,\n );\n continue;\n }\n\n const deltaUnknown = openAiChoicesDelta(parsed);\n if (!isRecord(deltaUnknown)) continue;\n\n // gpt-oss (harmony) sends delta.content as an array of parts\n // (text = answer, reasoning = chain-of-thought), not a string.\n const contentUnknown = deltaUnknown.content;\n const parts =\n typeof contentUnknown === \"string\"\n ? [{ type: \"text\", text: contentUnknown }]\n : Array.isArray(contentUnknown)\n ? contentUnknown\n : [];\n\n for (const part of parts) {\n if (!isRecord(part)) continue;\n if (part.type === \"text\" && typeof part.text === \"string\") {\n const content = part.text;\n throwIfExceedsStreamLimit(\n \"streamed assistant text\",\n fullText.length,\n content,\n this.maxStreamTextChars,\n );\n fullText += content;\n yield { type: \"message_delta\" as const, content };\n } else if (part.type === \"reasoning\") {\n const content = reasoningPartText(part);\n if (content) yield { type: \"thinking\" as const, content };\n }\n }\n\n const toolCallsRaw = deltaUnknown.tool_calls;\n if (!Array.isArray(toolCallsRaw)) continue;\n\n for (const tc of toolCallsRaw) {\n if (!isStreamingDeltaToolCall(tc)) continue;\n const sig = tc.thoughtSignature;\n const existing = toolCallAccumulator.get(tc.index);\n if (existing) {\n if (tc.function?.arguments) {\n throwIfExceedsStreamLimit(\n \"tool call arguments\",\n existing.arguments.length,\n tc.function.arguments,\n this.maxToolArgumentsChars,\n );\n existing.arguments += tc.function.arguments;\n }\n if (sig && !existing.thoughtSignature) {\n existing.thoughtSignature = sig;\n }\n } else {\n const initial = tc.function?.arguments ?? \"\";\n if (initial.length > this.maxToolArgumentsChars) {\n throw new Error(\n `DatabricksAdapter: tool call arguments exceed configured limit (${this.maxToolArgumentsChars} UTF-16 code units)`,\n );\n }\n toolCallAccumulator.set(tc.index, {\n id: tc.id ?? `call_${tc.index}`,\n name: tc.function?.name ?? \"\",\n arguments: initial,\n ...(sig ? { thoughtSignature: sig } : {}),\n });\n }\n }\n }\n }\n } finally {\n try {\n await reader.cancel();\n } catch (cancelErr) {\n console.debug(\n \"[DatabricksAdapter] reader.cancel() failed during teardown\",\n cancelErr,\n );\n }\n try {\n reader.releaseLock();\n } catch (unlockErr) {\n console.debug(\n \"[DatabricksAdapter] reader.releaseLock() failed during teardown\",\n unlockErr,\n );\n }\n }\n\n const toolCalls: OpenAIToolCall[] = Array.from(\n toolCallAccumulator.values(),\n ).map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: { name: tc.name, arguments: tc.arguments || \"{}\" },\n ...(tc.thoughtSignature ? { thoughtSignature: tc.thoughtSignature } : {}),\n }));\n\n return { text: fullText, toolCalls };\n }\n\n private async *executeToolCalls(\n calls: Array<{ name: string; args: unknown }>,\n messages: OpenAIMessage[],\n context: AgentRunContext,\n nameToWire: Map<string, string>,\n ): AsyncGenerator<AgentEvent, void, unknown> {\n const wireToolName = (name: string) =>\n nameToWire.get(name) ?? name.replace(/\\./g, \"__\");\n\n const toolCallObjs: OpenAIToolCall[] = calls.map((c, i) => ({\n id: `text_call_${i}`,\n type: \"function\" as const,\n function: {\n name: wireToolName(c.name),\n arguments: JSON.stringify(c.args),\n },\n }));\n\n messages.push({\n role: \"assistant\",\n content: null,\n tool_calls: toolCallObjs,\n });\n\n for (let i = 0; i < toolCallObjs.length; i++) {\n const tc = toolCallObjs[i];\n const originalName = calls[i]?.name ?? tc.function.name;\n yield* this.executeSingleTool(tc, originalName, messages, context);\n }\n }\n\n /**\n * Maps AppKit {@link AgentInput} messages into OpenAI-compatible wire messages.\n * Preserves multi-turn tool state (`toolCalls` → `tool_calls`, `toolCallId` →\n * `tool_call_id`) so resumed threads and hydrated history reach the model.\n */\n private buildMessages(\n messages: AgentInput[\"messages\"],\n nameToWire: Map<string, string>,\n ): OpenAIMessage[] {\n const wireToolName = (name: string) =>\n nameToWire.get(name) ?? name.replace(/\\./g, \"__\");\n\n return messages.map((m) => {\n let content: string | null = m.content;\n if (\n m.role === \"assistant\" &&\n m.toolCalls &&\n m.toolCalls.length > 0 &&\n (!m.content || m.content.trim() === \"\")\n ) {\n content = null;\n }\n\n const out: OpenAIMessage = {\n role: m.role as OpenAIMessage[\"role\"],\n content,\n };\n\n if (m.toolCallId) {\n out.tool_call_id = m.toolCallId;\n }\n\n if (m.toolCalls && m.toolCalls.length > 0) {\n out.tool_calls = m.toolCalls.map((tc) => ({\n id: tc.id,\n type: \"function\" as const,\n function: {\n name: wireToolName(tc.name),\n arguments:\n typeof tc.args === \"string\"\n ? tc.args\n : JSON.stringify(tc.args ?? {}),\n },\n ...(tc.thoughtSignature\n ? { thoughtSignature: tc.thoughtSignature }\n : {}),\n }));\n }\n\n return out;\n });\n }\n\n private buildTools(\n definitions: AgentToolDefinition[],\n nameToWire: Map<string, string>,\n ): OpenAITool[] {\n return definitions.map((def) => ({\n type: \"function\" as const,\n function: {\n name: nameToWire.get(def.name) ?? def.name,\n description: def.description,\n parameters: def.parameters,\n },\n }));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Text-based tool call parsing (fallback)\n// ---------------------------------------------------------------------------\n\n/**\n * Parses text-based tool calls from model output.\n *\n * Handles two formats:\n * 1. Llama native: `[{\"name\": \"tool_name\", \"parameters\": {\"arg\": \"val\"}}]`\n * 2. Python-style: `[tool_name(arg1='val1', arg2='val2')]`\n */\nexport function parseTextToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n const trimmed = text.trim();\n\n const jsonResult = tryParseLlamaJsonToolCalls(trimmed);\n if (jsonResult.length > 0) return jsonResult;\n\n const pyResult = tryParsePythonStyleToolCalls(trimmed);\n if (pyResult.length > 0) return pyResult;\n\n return [];\n}\n\nfunction isLlamaToolJsonItem(value: unknown): value is Record<\n string,\n unknown\n> & {\n name: string;\n} {\n if (!isRecord(value)) return false;\n return typeof value.name === \"string\";\n}\n\nfunction tryParseLlamaJsonToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n const slice = extractLlamaToolJsonSlice(text);\n if (!slice) return [];\n\n try {\n const parsed: unknown = JSON.parse(slice);\n if (!Array.isArray(parsed)) return [];\n\n return parsed.filter(isLlamaToolJsonItem).map((item) => ({\n name: item.name,\n args: item.parameters ?? item.arguments ?? item.args ?? {},\n }));\n } catch {\n return [];\n }\n}\n\nfunction tryParsePythonStyleToolCalls(\n text: string,\n): Array<{ name: string; args: unknown }> {\n if (text.length > PYTHON_STYLE_TOOL_PARSE_MAX_INPUT) {\n return [];\n }\n\n const pattern = /\\[?([a-zA-Z_][\\w.]*)\\(([^)]*)\\)\\]?/g;\n const results: Array<{ name: string; args: unknown }> = [];\n\n for (const match of text.matchAll(pattern)) {\n const name = match[1];\n const argsStr = match[2];\n\n const args: Record<string, unknown> = {};\n const argPattern = /(\\w+)\\s*=\\s*(?:'([^']*)'|\"([^\"]*)\"|(\\S+))/g;\n for (const argMatch of argsStr.matchAll(argPattern)) {\n const key = argMatch[1];\n const value = argMatch[2] ?? argMatch[3] ?? argMatch[4];\n args[key] = value;\n }\n\n results.push({ name, args });\n }\n\n return results;\n}\n"],"mappings":";;;;;;AAgBA,MAAM,6BAA6B,OAAO;;AAG1C,MAAM,gCAAgC,IAAI,OAAO;;AAGjD,MAAM,kCAAkC,IAAI,OAAO;;AAGnD,MAAM,oCAAoC,KAAK;;AAG/C,MAAM,+BAA+B;AAErC,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAsBhD,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACD;;AAGD,SAAS,sBACP,MACA,QACM;AACN,MAAK,MAAM,OAAO,uBAAuB;EACvC,MAAM,QAAQ,OAAO;AACrB,MAAI,UAAU,OAAW,MAAK,OAAO;;;AAIzC,SAAS,0BAA0B,MAAkC;CACnE,MAAM,QAAQ,KAAK,QAAQ,KAAK;AAChC,KAAI,QAAQ,EAAG,QAAO;CACtB,MAAM,aAAa,KAAK,YAAY,KAAK;AACzC,KAAI,aAAa,MAAO,QAAO;AAC/B,QAAO,KAAK,MAAM,OAAO,aAAa,EAAE;;;AAI1C,SAAS,mBAAmB,QAA0B;AACpD,KAAI,CAAC,SAAS,OAAO,CAAE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|
source: SkillSource;
|
|
20
20
|
/** Absolute directory containing `SKILL.md` and any bundled resources. */
|
|
21
21
|
dir: string;
|
|
22
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* Relative posix paths of bundled resource files (excludes `SKILL.md`).
|
|
24
|
+
* Bundle skills recurse into subdirectories; volume skills list one level
|
|
25
|
+
* only, so nested files under a volume skill are not exposed to
|
|
26
|
+
* `read_skill_file`.
|
|
27
|
+
*/
|
|
23
28
|
files: string[];
|
|
24
29
|
/**
|
|
25
30
|
* Optional advisory tool allowlist from frontmatter `allowed-tools`. Surfaced
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/core/agent/skills/types.ts"],"mappings":";;KACY,WAAA;;;;;AASZ;;;UAAiB,eAAA;EAEf;EAAA,IAAA;EAIA;EAFA,WAAA;EAIQ;EAFR,IAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/core/agent/skills/types.ts"],"mappings":";;KACY,WAAA;;;;;AASZ;;;UAAiB,eAAA;EAEf;EAAA,IAAA;EAIA;EAFA,WAAA;EAIQ;EAFR,IAAA;EAWA;EATA,MAAA,EAAQ,WAAA;EAeI;EAbZ,GAAA;EAiBe;;;;;AAYjB;EAtBE,KAAA;;;;;;EAMA,YAAA;AAAA;;UAIe,iBAAA;EAaQ;EAXvB,IAAA;EACA,WAAA;AAAA;;;;;;;UASe,oBAAA;EACf,SAAA,EAAW,GAAA,SAAY,eAAA;EACvB,SAAA,EAAW,GAAA;EACX,OAAA,EAAS,iBAAA;AAAA"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//#region src/plugins/agents/active-stream-tracker.ts
|
|
2
|
+
/**
|
|
3
|
+
* Tracks active SSE streams and a per-user stream count for the agents plugin's
|
|
4
|
+
* concurrency limit. The count is kept in sync with the stream map on every
|
|
5
|
+
* {@link track}/{@link untrack} so the limit check is O(1) instead of O(n) over
|
|
6
|
+
* all active streams on every request. `track` and `untrack` are the only
|
|
7
|
+
* writers, which is what keeps the counter from drifting from the map.
|
|
8
|
+
*
|
|
9
|
+
* Distinct from the SSE-layer `StreamRegistry` in `src/stream/` (which buffers
|
|
10
|
+
* events per connection for reconnection replay) — this only counts streams.
|
|
11
|
+
*/
|
|
12
|
+
var ActiveStreamTracker = class {
|
|
13
|
+
activeStreams = /* @__PURE__ */ new Map();
|
|
14
|
+
userStreamCounts = /* @__PURE__ */ new Map();
|
|
15
|
+
/** Count active streams owned by a given user. O(1). */
|
|
16
|
+
count(userId) {
|
|
17
|
+
return this.userStreamCounts.get(userId) ?? 0;
|
|
18
|
+
}
|
|
19
|
+
/** Total active streams across all users. */
|
|
20
|
+
get size() {
|
|
21
|
+
return this.activeStreams.size;
|
|
22
|
+
}
|
|
23
|
+
/** Look up an active stream by request id. */
|
|
24
|
+
get(requestId) {
|
|
25
|
+
return this.activeStreams.get(requestId);
|
|
26
|
+
}
|
|
27
|
+
/** Register a stream for `userId` and bump the per-user counter. */
|
|
28
|
+
track(requestId, userId, controller) {
|
|
29
|
+
this.activeStreams.set(requestId, {
|
|
30
|
+
controller,
|
|
31
|
+
userId
|
|
32
|
+
});
|
|
33
|
+
this.userStreamCounts.set(userId, (this.userStreamCounts.get(userId) ?? 0) + 1);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Remove a stream and decrement the per-user counter. Idempotent — calling
|
|
37
|
+
* twice for the same `requestId` is a no-op. Drops the counter key entirely
|
|
38
|
+
* when it reaches zero so the map can't grow unbounded across many users.
|
|
39
|
+
*/
|
|
40
|
+
untrack(requestId) {
|
|
41
|
+
const entry = this.activeStreams.get(requestId);
|
|
42
|
+
if (!entry) return;
|
|
43
|
+
this.activeStreams.delete(requestId);
|
|
44
|
+
const next = (this.userStreamCounts.get(entry.userId) ?? 0) - 1;
|
|
45
|
+
if (next <= 0) this.userStreamCounts.delete(entry.userId);
|
|
46
|
+
else this.userStreamCounts.set(entry.userId, next);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { ActiveStreamTracker };
|
|
52
|
+
//# sourceMappingURL=active-stream-tracker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"active-stream-tracker.js","names":[],"sources":["../../../src/plugins/agents/active-stream-tracker.ts"],"sourcesContent":["/**\n * Tracks active SSE streams and a per-user stream count for the agents plugin's\n * concurrency limit. The count is kept in sync with the stream map on every\n * {@link track}/{@link untrack} so the limit check is O(1) instead of O(n) over\n * all active streams on every request. `track` and `untrack` are the only\n * writers, which is what keeps the counter from drifting from the map.\n *\n * Distinct from the SSE-layer `StreamRegistry` in `src/stream/` (which buffers\n * events per connection for reconnection replay) — this only counts streams.\n */\nexport class ActiveStreamTracker {\n private readonly activeStreams = new Map<\n string,\n { controller: AbortController; userId: string }\n >();\n private readonly userStreamCounts = new Map<string, number>();\n\n /** Count active streams owned by a given user. O(1). */\n count(userId: string): number {\n return this.userStreamCounts.get(userId) ?? 0;\n }\n\n /** Total active streams across all users. */\n get size(): number {\n return this.activeStreams.size;\n }\n\n /** Look up an active stream by request id. */\n get(\n requestId: string,\n ): { controller: AbortController; userId: string } | undefined {\n return this.activeStreams.get(requestId);\n }\n\n /** Register a stream for `userId` and bump the per-user counter. */\n track(requestId: string, userId: string, controller: AbortController): 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 and decrement the per-user counter. Idempotent — calling\n * twice for the same `requestId` is a no-op. Drops the counter key entirely\n * when it reaches zero so the map can't grow unbounded across many users.\n */\n untrack(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"],"mappings":";;;;;;;;;;;AAUA,IAAa,sBAAb,MAAiC;CAC/B,AAAiB,gCAAgB,IAAI,KAGlC;CACH,AAAiB,mCAAmB,IAAI,KAAqB;;CAG7D,MAAM,QAAwB;AAC5B,SAAO,KAAK,iBAAiB,IAAI,OAAO,IAAI;;;CAI9C,IAAI,OAAe;AACjB,SAAO,KAAK,cAAc;;;CAI5B,IACE,WAC6D;AAC7D,SAAO,KAAK,cAAc,IAAI,UAAU;;;CAI1C,MAAM,WAAmB,QAAgB,YAAmC;AAC1E,OAAK,cAAc,IAAI,WAAW;GAAE;GAAY;GAAQ,CAAC;AACzD,OAAK,iBAAiB,IACpB,SACC,KAAK,iBAAiB,IAAI,OAAO,IAAI,KAAK,EAC5C;;;;;;;CAQH,QAAQ,WAAyB;EAC/B,MAAM,QAAQ,KAAK,cAAc,IAAI,UAAU;AAC/C,MAAI,CAAC,MAAO;AACZ,OAAK,cAAc,OAAO,UAAU;EACpC,MAAM,QAAQ,KAAK,iBAAiB,IAAI,MAAM,OAAO,IAAI,KAAK;AAC9D,MAAI,QAAQ,EACV,MAAK,iBAAiB,OAAO,MAAM,OAAO;MAE1C,MAAK,iBAAiB,IAAI,MAAM,QAAQ,KAAK"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createLogger } from "../../logging/logger.js";
|
|
2
|
+
import { SUPERVISOR_EXTENSION_KEY } from "../../agents/supervisor-api.js";
|
|
3
|
+
|
|
4
|
+
//#region src/plugins/agents/adapter-extensions.ts
|
|
5
|
+
const logger = createLogger("agents");
|
|
6
|
+
/**
|
|
7
|
+
* Pulls the LLM-readable description off any {@link SupervisorTool} kind.
|
|
8
|
+
* Used to populate the synthetic placeholder `def.description` on
|
|
9
|
+
* hosted-supervisor tool-index entries.
|
|
10
|
+
*/
|
|
11
|
+
function supervisorToolDescription(spec) {
|
|
12
|
+
switch (spec.type) {
|
|
13
|
+
case "genie_space": return spec.genie_space.description;
|
|
14
|
+
case "uc_function": return spec.uc_function.description;
|
|
15
|
+
case "knowledge_assistant": return spec.knowledge_assistant.description;
|
|
16
|
+
case "app": return spec.app.description;
|
|
17
|
+
case "uc_connection": return spec.uc_connection.description;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Builds the `AgentInput.extensions` payload from a tool index, aggregating
|
|
22
|
+
* the hosted-supervisor specs under {@link SUPERVISOR_EXTENSION_KEY}. Returns
|
|
23
|
+
* `undefined` when there are no adapter-side hosted tools so the field stays
|
|
24
|
+
* absent on the wire — adapters that don't read extensions never see it.
|
|
25
|
+
*/
|
|
26
|
+
function buildAdapterExtensions(toolIndex) {
|
|
27
|
+
const supervisorSpecs = [];
|
|
28
|
+
for (const entry of toolIndex.values()) if (entry.source === "hosted-supervisor") supervisorSpecs.push(entry.spec);
|
|
29
|
+
if (supervisorSpecs.length === 0) return void 0;
|
|
30
|
+
return { [SUPERVISOR_EXTENSION_KEY]: { hostedTools: supervisorSpecs } };
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Compares the adapter's declared capabilities against the tool index and
|
|
34
|
+
* logs a warning when the agent's tool declarations would be silently
|
|
35
|
+
* dropped at runtime. Warn-not-throw: misconfiguration is loud enough to
|
|
36
|
+
* notice without taking the whole app down.
|
|
37
|
+
*/
|
|
38
|
+
function warnOnCapabilityMismatch(agentName, adapter, toolIndex) {
|
|
39
|
+
const accepted = new Set(adapter.acceptsExtensions ?? []);
|
|
40
|
+
const hostedSupervisorKeys = [];
|
|
41
|
+
const inputToolKeys = [];
|
|
42
|
+
for (const [key, entry] of toolIndex) if (entry.source === "hosted-supervisor") hostedSupervisorKeys.push(key);
|
|
43
|
+
else inputToolKeys.push(key);
|
|
44
|
+
if (hostedSupervisorKeys.length > 0 && !accepted.has(SUPERVISOR_EXTENSION_KEY)) logger.warn(`Agent '${agentName}' declares hosted-supervisor tools (${hostedSupervisorKeys.join(", ")}) but its model adapter does not accept the 'databricks.supervisor' extension. These tools will not reach the model. Pair them with \`DatabricksAdapter.fromSupervisorApi(...)\`, or remove them.`);
|
|
45
|
+
if (adapter.consumesInputTools === false && inputToolKeys.length > 0) logger.warn(`Agent '${agentName}' declares function tools / sub-agents / MCP tools (${inputToolKeys.join(", ")}) but its model adapter does not consume input.tools (Supervisor API owns its own tool loop). These tools will not be exposed to the model. See docs/plugins/agents.md.`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
export { buildAdapterExtensions, supervisorToolDescription, warnOnCapabilityMismatch };
|
|
50
|
+
//# sourceMappingURL=adapter-extensions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-extensions.js","names":[],"sources":["../../../src/plugins/agents/adapter-extensions.ts"],"sourcesContent":["import type { AgentAdapter } from \"shared\";\n\nimport {\n SUPERVISOR_EXTENSION_KEY,\n type SupervisorTool,\n} from \"../../agents/supervisor-api\";\nimport type { ResolvedToolEntry } from \"../../core/agent/types\";\nimport { createLogger } from \"../../logging/logger\";\n\nconst logger = createLogger(\"agents\");\n\n/**\n * Pulls the LLM-readable description off any {@link SupervisorTool} kind.\n * Used to populate the synthetic placeholder `def.description` on\n * hosted-supervisor tool-index entries.\n */\nexport function supervisorToolDescription(spec: SupervisorTool): string {\n switch (spec.type) {\n case \"genie_space\":\n return spec.genie_space.description;\n case \"uc_function\":\n return spec.uc_function.description;\n case \"knowledge_assistant\":\n return spec.knowledge_assistant.description;\n case \"app\":\n return spec.app.description;\n case \"uc_connection\":\n return spec.uc_connection.description;\n }\n}\n\n/**\n * Builds the `AgentInput.extensions` payload from a tool index, aggregating\n * the hosted-supervisor specs under {@link SUPERVISOR_EXTENSION_KEY}. Returns\n * `undefined` when there are no adapter-side hosted tools so the field stays\n * absent on the wire — adapters that don't read extensions never see it.\n */\nexport function buildAdapterExtensions(\n toolIndex: Map<string, ResolvedToolEntry>,\n): Readonly<Record<string, unknown>> | undefined {\n const supervisorSpecs: SupervisorTool[] = [];\n for (const entry of toolIndex.values()) {\n if (entry.source === \"hosted-supervisor\") {\n supervisorSpecs.push(entry.spec);\n }\n }\n if (supervisorSpecs.length === 0) return undefined;\n return {\n [SUPERVISOR_EXTENSION_KEY]: { hostedTools: supervisorSpecs },\n };\n}\n\n/**\n * Compares the adapter's declared capabilities against the tool index and\n * logs a warning when the agent's tool declarations would be silently\n * dropped at runtime. Warn-not-throw: misconfiguration is loud enough to\n * notice without taking the whole app down.\n */\nexport function warnOnCapabilityMismatch(\n agentName: string,\n adapter: AgentAdapter,\n toolIndex: Map<string, ResolvedToolEntry>,\n): void {\n const accepted = new Set(adapter.acceptsExtensions ?? []);\n\n const hostedSupervisorKeys: string[] = [];\n const inputToolKeys: string[] = [];\n for (const [key, entry] of toolIndex) {\n if (entry.source === \"hosted-supervisor\") {\n hostedSupervisorKeys.push(key);\n } else {\n inputToolKeys.push(key);\n }\n }\n\n if (\n hostedSupervisorKeys.length > 0 &&\n !accepted.has(SUPERVISOR_EXTENSION_KEY)\n ) {\n logger.warn(\n `Agent '${agentName}' declares hosted-supervisor tools (${hostedSupervisorKeys.join(\", \")}) ` +\n \"but its model adapter does not accept the 'databricks.supervisor' extension. \" +\n \"These tools will not reach the model. Pair them with `DatabricksAdapter.fromSupervisorApi(...)`, or remove them.\",\n );\n }\n\n // `consumesInputTools` defaults to true. Only warn when an adapter\n // explicitly opts out (`false`) and an input tool would be silently\n // ignored.\n if (adapter.consumesInputTools === false && inputToolKeys.length > 0) {\n logger.warn(\n `Agent '${agentName}' declares function tools / sub-agents / MCP tools (${inputToolKeys.join(\", \")}) ` +\n \"but its model adapter does not consume input.tools (Supervisor API owns its own tool loop). \" +\n \"These tools will not be exposed to the model. See docs/plugins/agents.md.\",\n );\n }\n}\n"],"mappings":";;;;AASA,MAAM,SAAS,aAAa,SAAS;;;;;;AAOrC,SAAgB,0BAA0B,MAA8B;AACtE,SAAQ,KAAK,MAAb;EACE,KAAK,cACH,QAAO,KAAK,YAAY;EAC1B,KAAK,cACH,QAAO,KAAK,YAAY;EAC1B,KAAK,sBACH,QAAO,KAAK,oBAAoB;EAClC,KAAK,MACH,QAAO,KAAK,IAAI;EAClB,KAAK,gBACH,QAAO,KAAK,cAAc;;;;;;;;;AAUhC,SAAgB,uBACd,WAC+C;CAC/C,MAAM,kBAAoC,EAAE;AAC5C,MAAK,MAAM,SAAS,UAAU,QAAQ,CACpC,KAAI,MAAM,WAAW,oBACnB,iBAAgB,KAAK,MAAM,KAAK;AAGpC,KAAI,gBAAgB,WAAW,EAAG,QAAO;AACzC,QAAO,GACJ,2BAA2B,EAAE,aAAa,iBAAiB,EAC7D;;;;;;;;AASH,SAAgB,yBACd,WACA,SACA,WACM;CACN,MAAM,WAAW,IAAI,IAAI,QAAQ,qBAAqB,EAAE,CAAC;CAEzD,MAAM,uBAAiC,EAAE;CACzC,MAAM,gBAA0B,EAAE;AAClC,MAAK,MAAM,CAAC,KAAK,UAAU,UACzB,KAAI,MAAM,WAAW,oBACnB,sBAAqB,KAAK,IAAI;KAE9B,eAAc,KAAK,IAAI;AAI3B,KACE,qBAAqB,SAAS,KAC9B,CAAC,SAAS,IAAI,yBAAyB,CAEvC,QAAO,KACL,UAAU,UAAU,sCAAsC,qBAAqB,KAAK,KAAK,CAAC,mMAG3F;AAMH,KAAI,QAAQ,uBAAuB,SAAS,cAAc,SAAS,EACjE,QAAO,KACL,UAAU,UAAU,sDAAsD,cAAc,KAAK,KAAK,CAAC,yKAGpG"}
|
|
@@ -14,14 +14,11 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
14
14
|
protected config: AgentsPluginConfig;
|
|
15
15
|
private agents;
|
|
16
16
|
private defaultAgentName;
|
|
17
|
-
private activeStreams;
|
|
18
17
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* active stream on every request. Mutated only via {@link trackStream}
|
|
22
|
-
* and {@link untrackStream}.
|
|
18
|
+
* Active SSE streams + per-user counts (the O(1) concurrency-limit check).
|
|
19
|
+
* Mutated only via {@link trackStream} / {@link untrackStream}.
|
|
23
20
|
*/
|
|
24
|
-
private
|
|
21
|
+
private streams;
|
|
25
22
|
private mcpClient;
|
|
26
23
|
private threadStore;
|
|
27
24
|
private approvalGate;
|
|
@@ -52,18 +49,7 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
52
49
|
private get resolvedLimits();
|
|
53
50
|
/** Count active streams owned by a given user. O(1). */
|
|
54
51
|
private countUserStreams;
|
|
55
|
-
/**
|
|
56
|
-
* Register a stream for `userId` and bump the per-user counter. Paired
|
|
57
|
-
* with {@link untrackStream}; the two helpers are the only writers to
|
|
58
|
-
* `activeStreams` + `userStreamCounts`, so the counter cannot drift from
|
|
59
|
-
* the map.
|
|
60
|
-
*/
|
|
61
52
|
private trackStream;
|
|
62
|
-
/**
|
|
63
|
-
* Remove a stream from the active map and decrement the per-user
|
|
64
|
-
* counter. Idempotent — calling twice for the same `requestId` is a
|
|
65
|
-
* no-op (the second call sees no entry and returns early).
|
|
66
|
-
*/
|
|
67
53
|
private untrackStream;
|
|
68
54
|
setup(): Promise<void>;
|
|
69
55
|
/**
|
|
@@ -96,15 +82,7 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
96
82
|
*/
|
|
97
83
|
private warnConfigAgentsDeprecated;
|
|
98
84
|
private resolvedAgentsDir;
|
|
99
|
-
/**
|
|
100
|
-
* Discovers code agents (see {@link resolveCodeAgentsDir} and
|
|
101
|
-
* {@link loadCodeAgentsFromDir}). Warns if sources exist but nothing was
|
|
102
|
-
* discovered — usually the build didn't emit the compiled agents — unless
|
|
103
|
-
* the deprecated `agents({ agents })` map is carrying them instead.
|
|
104
|
-
*/
|
|
105
85
|
private loadCodeAgents;
|
|
106
|
-
/** True when `dir` holds at least one `<id>/agent.ts` folder. */
|
|
107
|
-
private hasCodeAgentSources;
|
|
108
86
|
private loadFileDefinitions;
|
|
109
87
|
/**
|
|
110
88
|
* Builds the map of plugin-name → toolkit that the markdown loader consults
|
|
@@ -116,8 +94,6 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
116
94
|
private buildRegisteredAgent;
|
|
117
95
|
/** Loads the shared global skill pool from `<agentsDir>/skills/`. */
|
|
118
96
|
private loadGlobalSkills;
|
|
119
|
-
/** Configured catalog-skills volume path, or null when none is set. */
|
|
120
|
-
private resolveSkillsVolume;
|
|
121
97
|
/**
|
|
122
98
|
* Workspace client used to read catalog skills. v1 reads as the app service
|
|
123
99
|
* principal; `getWorkspaceClient()` resolves to SP outside a user scope
|
|
@@ -125,23 +101,8 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
125
101
|
* switch point for a future OBO mode.
|
|
126
102
|
*/
|
|
127
103
|
private skillWorkspaceClient;
|
|
128
|
-
/**
|
|
129
|
-
* Discovers catalog skills from the configured UC Volume, read as the
|
|
130
|
-
* service principal at boot (and on `reload()`). Each `<volume>/<name>/`
|
|
131
|
-
* folder with a `SKILL.md` becomes a `source: "volume"` skill. Best-effort:
|
|
132
|
-
* a missing volume, unavailable workspace client, or a malformed individual
|
|
133
|
-
* skill is logged and skipped rather than failing the whole registry build.
|
|
134
|
-
*/
|
|
104
|
+
/** Discovers catalog skills from the configured UC Volume (best-effort). */
|
|
135
105
|
private loadVolumeSkills;
|
|
136
|
-
/** Lists a volume skill's resource files (one level, excluding SKILL.md). */
|
|
137
|
-
private listVolumeSkillFiles;
|
|
138
|
-
/**
|
|
139
|
-
* Resolves the per-agent skill catalog: loads this agent's private skills
|
|
140
|
-
* (`<agentsDir>/<id>/skills/`, file-origin only), then applies visibility
|
|
141
|
-
* (opt-in via `def.skills` or `autoInheritSkills`) and collision rules
|
|
142
|
-
* against the shared global pool. Returns `undefined` when nothing is
|
|
143
|
-
* visible so the prompt catalog and dispatch can cheaply skip skills.
|
|
144
|
-
*/
|
|
145
106
|
private resolveAgentSkills;
|
|
146
107
|
private resolveAdapter;
|
|
147
108
|
/**
|
|
@@ -237,25 +198,6 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
237
198
|
* a dropped no-op instead of a runtime crash.
|
|
238
199
|
*/
|
|
239
200
|
private _runAgentNonStreaming;
|
|
240
|
-
/**
|
|
241
|
-
* Dispatch a single tool call from either the top-level adapter or a
|
|
242
|
-
* sub-agent. Centralising this in one method is what makes the budget
|
|
243
|
-
* counter, approval gate, and abort signal observe sub-agent activity:
|
|
244
|
-
* `runSubAgent` reuses the same `runState` and so increments the same
|
|
245
|
-
* counter and emits approval events through the same channel.
|
|
246
|
-
*
|
|
247
|
-
* `depth` is the current sub-agent recursion depth (0 at the top level).
|
|
248
|
-
* It is forwarded to `runSubAgent` when the dispatched entry is itself a
|
|
249
|
-
* sub-agent, so depth limits remain enforced.
|
|
250
|
-
*/
|
|
251
|
-
private dispatchToolCall;
|
|
252
|
-
/**
|
|
253
|
-
* Executes the built-in `load_skill` / `read_skill_file` tools against the
|
|
254
|
-
* agent's resolved skill catalog. `load_skill` returns a skill's body plus a
|
|
255
|
-
* manifest of bundled files; `read_skill_file` returns the contents of one
|
|
256
|
-
* of those files (bundle skills only in v1 — catalog-volume resource reads
|
|
257
|
-
* arrive with the volume source).
|
|
258
|
-
*/
|
|
259
201
|
private dispatchSkillTool;
|
|
260
202
|
/**
|
|
261
203
|
* Renders the prompt addendum for a force-loaded skill (`/skill-name`).
|
|
@@ -264,21 +206,8 @@ declare class AgentsPlugin extends Plugin implements ToolProvider {
|
|
|
264
206
|
* model proceeds with the catalog + `load_skill` still available.
|
|
265
207
|
*/
|
|
266
208
|
private renderForcedSkill;
|
|
267
|
-
/**
|
|
268
|
-
|
|
269
|
-
* concatenated text output to hand back to the parent adapter as the tool
|
|
270
|
-
* result.
|
|
271
|
-
*
|
|
272
|
-
* `depth` starts at 1 for a top-level sub-agent invocation (i.e. the
|
|
273
|
-
* outer `_streamAgent` calls `runSubAgent(..., 1)`) and increments on
|
|
274
|
-
* each nested `runSubAgent` call. Depths exceeding
|
|
275
|
-
* `limits.maxSubAgentDepth` are rejected before any adapter work.
|
|
276
|
-
*
|
|
277
|
-
* Sub-agent tool calls run through `dispatchToolCall` with the same
|
|
278
|
-
* `runState` as the parent — the budget counter and approval gate are
|
|
279
|
-
* therefore enforced for every nested call, not only at the top level.
|
|
280
|
-
*/
|
|
281
|
-
private runSubAgent;
|
|
209
|
+
/** Collaborators the tool-dispatch path needs, bound to this instance. */
|
|
210
|
+
private toolDispatchDeps;
|
|
282
211
|
private _handleCancel;
|
|
283
212
|
private _handleApprove;
|
|
284
213
|
private _handleListThreads;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;cAqGa,YAAA,SAAqB,MAAA,YAAkB,YAAA;EAAA,OAC3C,QAAA,EADiB,cAAA;EAAA,OAEjB,KAAA,EAAO,WAAA;EAAA,UAEI,MAAA,EAAQ,kBAAA;EAAA,QAElB,MAAA;EAAA,QACA,gBAAA;;AAPV;;;UAYU,OAAA;EAAA,QACA,SAAA;EAAA,QACA,WAAA;EAAA,QACA,YAAA;EAqFG;EAAA,QAnFH,0BAAA;EAwvBS;EAAA,QAtvBT,6BAAA;cAEI,MAAA,EAAQ,kBAAA;EAg0BJ;;;;;;;;;;EAr1B8C;;;;;EAAA,QAyDtD,YAAA;EAAA,QAEA,oBAAA;EAAA,YAKI,sBAAA,CAAA;EA5DM;EAAA,YAsEN,cAAA,CAAA;EApEJ;EAAA,QA8EA,gBAAA;EAAA,QAIA,WAAA;EAAA,QAQA,aAAA;EAIF,KAAA,CAAA,GAAK,OAAA;EArFH;;;;;;EAoGF,MAAA,CAAA,GAAU,OAAA;EAxDR;;;;;EAAA,QAkFM,kBAAA;EAzCR;;;;;EAAA,QAsJE,mBAAA;EAiBA;;;;EAAA,QAAA,uBAAA;EAuFA;;;;EAAA,QAxEA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