@cap-js/agents 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +2 -0
  2. package/cds-plugin.js +2 -2
  3. package/lib/agents/middleware/content-filter.js +3 -2
  4. package/lib/agents/middleware/index.js +11 -0
  5. package/lib/agents/middleware/remote-mcp.js +62 -0
  6. package/lib/agents/middleware/tool-wrap.js +52 -0
  7. package/lib/compile.js +6 -2
  8. package/lib/eval/Judge.js +239 -0
  9. package/lib/eval/eval-describe.js +69 -0
  10. package/lib/eval/eval-run.js +147 -0
  11. package/lib/eval/index.js +6 -0
  12. package/lib/eval/metrics.js +53 -0
  13. package/lib/eval/span-collector.js +50 -0
  14. package/lib/index.js +2 -1
  15. package/lib/models/aicore.js +23 -6
  16. package/lib/preview/chat.html +368 -65
  17. package/lib/protocol/agent-card.js +6 -2
  18. package/lib/sidecar.js +1 -1
  19. package/lib/telemetry/chat-tracing.js +39 -8
  20. package/lib/telemetry/mlflow/credentials.js +79 -0
  21. package/lib/telemetry/mlflow/evaluation.js +38 -0
  22. package/lib/telemetry/mlflow/exporter/DatabricksExporter.js +75 -0
  23. package/lib/telemetry/mlflow/exporter/MlflowExporter.js +115 -0
  24. package/lib/telemetry/mlflow/exporter/index.js +23 -0
  25. package/lib/telemetry/mlflow/index.js +16 -0
  26. package/lib/telemetry/mlflow/prompts.js +123 -0
  27. package/lib/telemetry/mlflow/tracing.js +264 -0
  28. package/lib/telemetry/tool-tracing.js +27 -54
  29. package/lib/telemetry/tracing.js +3 -1
  30. package/lib/utils/markdown.js +1 -11
  31. package/lib/utils/resilience.js +133 -0
  32. package/lib/utils/utils.js +17 -0
  33. package/package.json +23 -14
  34. package/srv/handlers/chat.js +278 -0
  35. package/srv/handlers/graph-executor.js +43 -37
  36. package/srv/handlers/index.js +3 -0
  37. package/srv/handlers/mcp-tools.js +7 -45
  38. package/srv/handlers/sub-agent-tools.js +8 -1
  39. package/srv/handlers/tools.js +9 -5
  40. package/index.js +0 -0
  41. package/lib/telemetry/mlflow.js +0 -290
  42. /package/{index.cds → srv/entities.cds} +0 -0
@@ -1,290 +0,0 @@
1
- /**
2
- * MLflow span attribute helpers for @cap-js/agents.
3
- *
4
- * Adds mlflow.* attributes to existing OTel spans so the MLflow OTLP
5
- * ingestion endpoint can assemble them into proper MLflow traces.
6
- *
7
- * All functions return {} when cds.env.agents.mlflow is falsy (zero overhead).
8
- *
9
- * The exporter itself is configured via setupMlflowExporter() as a
10
- * RoutingSpanProcessor that lazily creates per-experiment-ID exporters —
11
- * existing exporters (Dynatrace, Cloud Logging, Grafana, etc.) continue
12
- * to work unchanged.
13
- */
14
- import cds from "@sap/cds"
15
-
16
- /**
17
- * Resolve the MLflow experiment ID for the current request context.
18
- *
19
- * Resolution order:
20
- * 1. @Core.SchemaVersion annotation on the service (feature-toggleable via cds.context.model)
21
- * 2. cds.env.requires["mlflow"].credentials.MLFLOW_EXPERIMENT_ID
22
- * 3. process.env.MLFLOW_EXPERIMENT_ID
23
- *
24
- * MLflow requires experiment IDs to be numeric (int64). Throws if annotation
25
- * value is not a valid integer string.
26
- */
27
- function resolveExperimentId() {
28
- // Read from @Core.SchemaVersion on the active service (feature-toggle-aware)
29
- const serviceName = cds.context?.["agent.service"]
30
- if (serviceName) {
31
- const definition =
32
- cds.context?.model?.definitions?.[serviceName] || cds.services?.[serviceName]?.definition
33
- const annotated = definition?.["@Core.SchemaVersion"]
34
- if (annotated) {
35
- const id = String(annotated)
36
- if (!/^\d+$/.test(id)) {
37
- throw new Error(
38
- `@Core.SchemaVersion on "${serviceName}" must be a numeric string (MLflow experiment ID requires int64). Got: "${id}"`,
39
- )
40
- }
41
- return id
42
- }
43
- }
44
-
45
- // Fallback: credentials / env
46
- const creds = cds.env.requires?.mlflow?.credentials || cds.env.requires?.mlflow?.credentials
47
- return creds?.MLFLOW_EXPERIMENT_ID || process.env.MLFLOW_EXPERIMENT_ID
48
- }
49
-
50
- /**
51
- * Build mlflow.* span attributes for a given span type.
52
- * @param {"LLM"|"AGENT"|"TOOL"|"CHAIN"|"RETRIEVER"} spanType
53
- * @param {{ inputs?: any, outputs?: any, model?: string, provider?: string, functionName?: string, tokenUsage?: object }} [opts]
54
- * @returns {Record<string, string>} Attributes to set on span, or {} when disabled
55
- */
56
- export function mlflowAttrs(spanType, opts = {}) {
57
- if (!cds.env.agents?.mlflow) return {}
58
- const experimentId = resolveExperimentId()
59
- const attrs = {}
60
- if (experimentId) attrs["mlflow.experimentId"] = String(experimentId)
61
- attrs["mlflow.spanType"] = spanType
62
- if (opts.model) attrs["mlflow.llm.model"] = String(opts.model)
63
- if (opts.provider) attrs["mlflow.llm.provider"] = String(opts.provider)
64
- if (opts.functionName) attrs["mlflow.spanFunctionName"] = String(opts.functionName)
65
- if (opts.inputs !== undefined) attrs["mlflow.spanInputs"] = JSON.stringify(opts.inputs)
66
- if (opts.outputs !== undefined) attrs["mlflow.spanOutputs"] = JSON.stringify(opts.outputs)
67
- if (opts.tokenUsage) {
68
- attrs["mlflow.chat.tokenUsage"] = JSON.stringify({
69
- input_tokens: opts.tokenUsage.input_tokens,
70
- output_tokens: opts.tokenUsage.output_tokens,
71
- total_tokens: opts.tokenUsage.total_tokens,
72
- cache_creation_input_tokens: opts.tokenUsage.cache_creation_input_tokens,
73
- cache_read_input_tokens: opts.tokenUsage.cache_read_input_tokens,
74
- })
75
- }
76
- return attrs
77
- }
78
-
79
- /**
80
- * Build mlflow trace-level tag attributes (set on root/workflow span).
81
- * Uses mlflow.traceTag.* prefix so MLflow server extracts them as trace tags.
82
- * Also sets OTel semconv user.id and session.id which MLflow reads natively.
83
- * @returns {Record<string, string>} Attributes to set on root span, or {} when disabled
84
- */
85
- export function mlflowTraceAttrs() {
86
- if (!cds.env.agents?.mlflow) return {}
87
- const session = String(cds.context?.["agent.context.id"] || "")
88
- const user = String(cds.context?.user?.id || "")
89
- const tenant = String(cds.context?.tenant || "")
90
- return {
91
- // OTel semconv keys MLflow reads natively for user/session display
92
- "session.id": session,
93
- "user.id": user,
94
- // mlflow.traceTag.* prefix for custom trace tags
95
- "mlflow.traceTag.tenant": tenant,
96
- }
97
- }
98
-
99
- /**
100
- * Spread attributes object onto an OTel span (null-safe).
101
- * Coerces all values to strings to prevent [object Object] in downstream systems.
102
- * @param {import("@opentelemetry/api").Span | null} span
103
- * @param {Record<string, string>} attrs
104
- */
105
- export function setSpanAttrs(span, attrs) {
106
- if (!cds.env.agents?.mlflow) return
107
- if (!span) return
108
- for (const [k, v] of Object.entries(attrs)) {
109
- if (v !== undefined && v !== null) span.setAttribute(k, v)
110
- }
111
- }
112
-
113
- /**
114
- * SpanProcessor that routes spans to per-experiment-ID BatchSpanProcessors.
115
- * Lazily creates an OTLPTraceExporter for each unique mlflow.experimentId
116
- * seen on spans, so different services (or feature-toggled @Core.SchemaVersion
117
- * values) export to the correct MLflow experiment.
118
- *
119
- * Supports both static headers (PAT token) and async header factories (OAuth).
120
- */
121
- export class RoutingSpanProcessor {
122
- constructor({ url, headersConfig, ucTableName, BatchSpanProcessor, OTLPTraceExporter }) {
123
- this._url = url
124
- this._headersConfig = headersConfig
125
- this._ucTableName = ucTableName
126
- this._BatchSpanProcessor = BatchSpanProcessor
127
- this._OTLPTraceExporter = OTLPTraceExporter
128
- this._processors = new Map()
129
- }
130
-
131
- onStart() {}
132
-
133
- onEnd(span) {
134
- const expId = span.attributes?.["mlflow.experimentId"]
135
- if (!expId) return
136
- this._getOrCreate(expId).onEnd(span)
137
- }
138
-
139
- _getOrCreate(experimentId) {
140
- if (this._processors.has(experimentId)) return this._processors.get(experimentId)
141
- const ucHeader = this._ucTableName
142
- ? { "X-Databricks-UC-Table-Name": this._ucTableName }
143
- : undefined
144
- // Build headers — async factory or static object
145
- const headers =
146
- typeof this._headersConfig === "function"
147
- ? async () => ({
148
- ...(await this._headersConfig()),
149
- "x-mlflow-experiment-id": experimentId,
150
- ...ucHeader,
151
- })
152
- : {
153
- ...this._headersConfig,
154
- "x-mlflow-experiment-id": experimentId,
155
- ...ucHeader,
156
- }
157
- const exporter = new this._OTLPTraceExporter({ url: this._url, headers })
158
- const proc = new this._BatchSpanProcessor(exporter)
159
- this._processors.set(experimentId, proc)
160
- return proc
161
- }
162
-
163
- async forceFlush() {
164
- await Promise.all([...this._processors.values()].map((p) => p.forceFlush()))
165
- }
166
-
167
- async shutdown() {
168
- await Promise.all([...this._processors.values()].map((p) => p.shutdown()))
169
- this._processors.clear()
170
- }
171
- }
172
-
173
- /**
174
- * Register MLflow OTLP RoutingSpanProcessor. No-op when credentials missing.
175
- * Reads from cds.env.requires["mlflow"].credentials
176
- *
177
- * Auth: OAuth (clientid+clientsecret+url) takes precedence over static MLFLOW_TOKEN.
178
- * UC: set UC_CATALOG + UC_SCHEMA + UC_TABLE_PREFIX for Unity Catalog trace storage.
179
- */
180
- export async function setupMlflowExporter() {
181
- if (!cds.env.agents?.mlflow) return
182
-
183
- const LOG = cds.log("agents")
184
- try {
185
- const creds = cds.env.requires?.mlflow?.credentials || {}
186
- const host = creds.MLFLOW_HOST
187
- const token = creds.MLFLOW_TOKEN
188
- const mlflowEndpoint =
189
- creds.MLFLOW_OTLP_ENDPOINT || (host && `${host.replace(/\/$/, "")}/v1/traces`)
190
-
191
- // Resolve authentication mode
192
- let headersConfig
193
- if (creds.clientid && creds.clientsecret) {
194
- const tokenUrl = `${creds.url ?? host.replace(/\/$/, "")}/oidc/v1/token`
195
- let cached = null
196
- let expiresAt = 0
197
- headersConfig = async function fetchToken() {
198
- // Return cached token if still valid (60s buffer before expiry)
199
- if (cached && Date.now() < expiresAt) return cached
200
- const res = await fetch(tokenUrl, {
201
- method: "POST",
202
- headers: {
203
- Authorization:
204
- "Basic " + Buffer.from(`${creds.clientid}:${creds.clientsecret}`).toString("base64"),
205
- "Content-Type": "application/x-www-form-urlencoded",
206
- },
207
- body: `grant_type=client_credentials&scope=all-apis`,
208
- signal: AbortSignal.timeout(10_000),
209
- })
210
- if (!res.ok) {
211
- const body = await res.text().catch(() => "")
212
- const msg = `MLFlow oauth export failed: HTTP ${res.status} ${res.statusText}`
213
- throw cds.error({ message: msg, response: body })
214
- }
215
- const { access_token, expires_in } = await res.json()
216
- cached = { Authorization: `Bearer ${access_token}` }
217
- expiresAt = Date.now() + (expires_in - 60) * 1000
218
- return cached
219
- }
220
- LOG.debug("MLflow: using OAuth client credentials authentication")
221
- } else if (token) {
222
- headersConfig = { Authorization: `Bearer ${token}` }
223
- } else {
224
- headersConfig = {}
225
- LOG.debug("MLflow: no auth credentials — assuming unauthenticated MLflow server")
226
- }
227
-
228
- if (!mlflowEndpoint) {
229
- LOG.warn(
230
- "MLflow: no endpoint configured (MLFLOW_HOST or MLFLOW_OTLP_ENDPOINT) — export disabled",
231
- )
232
- return
233
- }
234
-
235
- const ucCatalog = creds.UC_CATALOG
236
- const ucSchema = creds.UC_SCHEMA
237
- const ucTablePrefix = creds.UC_TABLE_PREFIX
238
- const ucTableName =
239
- ucCatalog && ucSchema && ucTablePrefix
240
- ? `${ucCatalog}.${ucSchema}.${ucTablePrefix}_otel_spans`
241
- : undefined
242
-
243
- const { trace } = await import("@opentelemetry/api")
244
- const provider = trace.getTracerProvider()
245
- const delegate = provider.getDelegate?.() || provider
246
-
247
- let BatchSpanProcessor, OTLPTraceExporter
248
- try {
249
- const { createRequire } = await import("node:module")
250
- const req = createRequire(process.cwd() + "/")
251
- ;({ BatchSpanProcessor } = req("@opentelemetry/sdk-trace-base"))
252
- ;({ OTLPTraceExporter } = req("@opentelemetry/exporter-trace-otlp-proto"))
253
- } catch (err) {
254
- LOG.warn(
255
- "MLflow: @opentelemetry/exporter-trace-otlp-proto not resolvable from the application. " +
256
- "Install a version matching your @cap-js/telemetry major " +
257
- "(v1 → ^0.57, v2 → ^0.221). Export disabled.",
258
- { error: err.message },
259
- )
260
- return
261
- }
262
-
263
- const routing = new RoutingSpanProcessor({
264
- url: mlflowEndpoint,
265
- headersConfig,
266
- ucTableName,
267
- BatchSpanProcessor,
268
- OTLPTraceExporter,
269
- })
270
-
271
- if (delegate.addSpanProcessor) {
272
- // OTEL SDK v1
273
- delegate.addSpanProcessor(routing)
274
- } else if (delegate._activeSpanProcessor?._spanProcessors) {
275
- // OTEL SDK v2: no addSpanProcessor — push into MultiSpanProcessor
276
- delegate._activeSpanProcessor._spanProcessors.push(routing)
277
- } else {
278
- LOG.warn(
279
- "MLflow: no TracerProvider with addSpanProcessor — ensure @cap-js/telemetry is loaded",
280
- )
281
- return
282
- }
283
- LOG.info("MLflow: routing span processor added (per-experiment export)", {
284
- endpoint: mlflowEndpoint,
285
- ...(ucTableName && { ucTableName }),
286
- })
287
- } catch (err) {
288
- LOG.error("MLflow: failed to configure OTLP export", { error: err.message })
289
- }
290
- }
File without changes