@librechat/agents 3.4.5 → 3.4.6
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/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +268 -14
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/langfuseTraceShaping.cjs +9 -6
- package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
- package/dist/cjs/run.cjs +147 -14
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/AgentSession.cjs +93 -31
- package/dist/cjs/session/AgentSession.cjs.map +1 -1
- package/dist/cjs/session/handlers.cjs +10 -0
- package/dist/cjs/session/handlers.cjs.map +1 -1
- package/dist/cjs/stream.cjs +17 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +1 -0
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +4 -2
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +1 -0
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +28 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/utils/handlers.cjs +3 -0
- package/dist/cjs/utils/handlers.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +268 -14
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/langfuseTraceShaping.mjs +9 -6
- package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
- package/dist/esm/run.mjs +147 -14
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/AgentSession.mjs +93 -31
- package/dist/esm/session/AgentSession.mjs.map +1 -1
- package/dist/esm/session/handlers.mjs +10 -0
- package/dist/esm/session/handlers.mjs.map +1 -1
- package/dist/esm/stream.mjs +17 -3
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +1 -0
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +4 -2
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +1 -0
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +28 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/utils/handlers.mjs +3 -0
- package/dist/esm/utils/handlers.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +87 -0
- package/dist/types/langfuseTraceShaping.d.ts +4 -3
- package/dist/types/run.d.ts +9 -1
- package/dist/types/session/types.d.ts +1 -1
- package/dist/types/summarization/node.d.ts +6 -0
- package/dist/types/types/graph.d.ts +3 -3
- package/dist/types/types/stream.d.ts +57 -0
- package/dist/types/utils/handlers.d.ts +1 -0
- package/package.json +1 -1
- package/src/aggregator.test.ts +127 -0
- package/src/common/enum.ts +2 -0
- package/src/graphs/Graph.ts +365 -7
- package/src/graphs/__tests__/Graph.closeRunStep.test.ts +385 -0
- package/src/langfuseTraceShaping.ts +14 -7
- package/src/run.ts +219 -41
- package/src/session/AgentSession.ts +105 -13
- package/src/session/handlers.ts +14 -2
- package/src/session/types.ts +1 -0
- package/src/specs/activity-label-observability.live.test.ts +262 -0
- package/src/specs/activity-label-observability.test.ts +167 -0
- package/src/specs/langfuse-trace-shaping.test.ts +32 -0
- package/src/specs/run-step-timestamps.test.ts +414 -0
- package/src/stream.ts +29 -6
- package/src/summarization/node.ts +11 -0
- package/src/tools/ToolNode.ts +2 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +52 -10
- package/src/tools/__tests__/handlers.test.ts +2 -0
- package/src/tools/handlers.ts +1 -0
- package/src/tools/subagent/SubagentExecutor.ts +46 -4
- package/src/types/graph.ts +9 -6
- package/src/types/stream.ts +65 -12
- package/src/utils/handlers.ts +13 -0
|
@@ -14,6 +14,8 @@ const CHAIN_OBSERVATION_TYPE = "chain";
|
|
|
14
14
|
const TOOL_OBSERVATION_TYPE = "tool";
|
|
15
15
|
const AGENT_TRACE_TAG = "agent";
|
|
16
16
|
const TITLE_TRACE_TAG = "title";
|
|
17
|
+
const ACTIVITY_PHASE_TRACE_TAG = "activity-phase";
|
|
18
|
+
const ACTIVITY_PHASE_ROOT_NAME = "summarize-activity-phase";
|
|
17
19
|
const EPHEMERAL_AGENT_SENDER_SEPARATOR = "___";
|
|
18
20
|
const EPHEMERAL_AGENT_INDEX_SEPARATOR = "____";
|
|
19
21
|
const OBSERVATION_METADATA_LANGGRAPH_NODE = `${_langfuse_tracing.LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.langgraph_node`;
|
|
@@ -276,11 +278,11 @@ function hasTraceTag(span, expectedTag) {
|
|
|
276
278
|
}
|
|
277
279
|
function shapeRootObservationType(span) {
|
|
278
280
|
if (isGenerationSpan(span)) return;
|
|
279
|
-
if (hasTraceTag(span,
|
|
280
|
-
span.attributes[_langfuse_tracing.LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =
|
|
281
|
+
if (hasTraceTag(span, TITLE_TRACE_TAG) || span.name === ACTIVITY_PHASE_ROOT_NAME && hasTraceTag(span, ACTIVITY_PHASE_TRACE_TAG)) {
|
|
282
|
+
span.attributes[_langfuse_tracing.LangfuseOtelSpanAttributes.OBSERVATION_TYPE] = CHAIN_OBSERVATION_TYPE;
|
|
281
283
|
return;
|
|
282
284
|
}
|
|
283
|
-
if (hasTraceTag(span,
|
|
285
|
+
if (hasTraceTag(span, AGENT_TRACE_TAG)) span.attributes[_langfuse_tracing.LangfuseOtelSpanAttributes.OBSERVATION_TYPE] = ROOT_OBSERVATION_TYPE;
|
|
284
286
|
}
|
|
285
287
|
/**
|
|
286
288
|
* Reshapes spans per Langfuse-team feedback before export:
|
|
@@ -295,9 +297,10 @@ function shapeRootObservationType(span) {
|
|
|
295
297
|
* - Agent nodes become `agent` observations, while tool-dispatch nodes become
|
|
296
298
|
* stable `chain` observations whose input is scoped to the pending calls.
|
|
297
299
|
* Individual child calls remain `tool` observations (items 3 & 4).
|
|
298
|
-
* - Agent trace roots become `agent` observations
|
|
299
|
-
* `chain` observations. Root and trace input/output are
|
|
300
|
-
* question and assistant response when chat messages are
|
|
300
|
+
* - Agent trace roots become `agent` observations, while title and activity
|
|
301
|
+
* summary roots become `chain` observations. Root and trace input/output are
|
|
302
|
+
* reduced to the user question and assistant response when chat messages are
|
|
303
|
+
* available (item 2).
|
|
301
304
|
*/
|
|
302
305
|
function shapeLangfuseSpan(span) {
|
|
303
306
|
const mutable = span;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"langfuseTraceShaping.cjs","names":["LangfuseOtelSpanAttributes"],"sources":["../../src/langfuseTraceShaping.ts"],"sourcesContent":["import { LangfuseOtelSpanAttributes } from '@langfuse/tracing';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { Constants } from '@/common';\n\nconst LANGGRAPH_START_NODE = '__start__';\nconst ANONYMOUS_LAMBDA_NAME = 'RunnableLambda';\nconst LANGGRAPH_AGENT_NODE_PREFIX = 'agent=';\nconst LANGGRAPH_TOOL_NODE_PREFIX = 'tools=';\nconst AGENT_NODE_SPAN_NAME = 'agent';\nconst TOOL_DISPATCH_SPAN_NAME = 'tool-dispatch';\nconst GENERATION_SPAN_NAME = 'llm';\nconst ROOT_OBSERVATION_TYPE = 'agent';\nconst CHAIN_OBSERVATION_TYPE = 'chain';\nconst TOOL_OBSERVATION_TYPE = 'tool';\nconst AGENT_TRACE_TAG = 'agent';\nconst TITLE_TRACE_TAG = 'title';\nconst EPHEMERAL_AGENT_SENDER_SEPARATOR = '___';\nconst EPHEMERAL_AGENT_INDEX_SEPARATOR = '____';\nconst OBSERVATION_METADATA_LANGGRAPH_NODE = `${LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.langgraph_node`;\n\ntype MutableSpan = ReadableSpan & {\n name: string;\n attributes: Record<string, unknown>;\n};\n\ntype SerializedToolCall = {\n name: string;\n args: unknown;\n id?: string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction parseAttributeValue(value: unknown): unknown {\n if (typeof value !== 'string') {\n return value;\n }\n const trimmed = value.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return value;\n }\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction getMessageArray(\n value: unknown\n): Record<string, unknown>[] | undefined {\n if (Array.isArray(value)) {\n const records = value.filter(isRecord);\n return records.length > 0 ? records : undefined;\n }\n if (!isRecord(value)) {\n return undefined;\n }\n return (\n getMessageArray(value.messages) ??\n getMessageArray(value.input) ??\n getMessageArray(value.output)\n );\n}\n\nfunction getMessageRole(message: Record<string, unknown>): string | undefined {\n const id = message.id;\n if (Array.isArray(id)) {\n const className = id[id.length - 1];\n if (typeof className === 'string') {\n if (className.includes('Human')) {\n return 'user';\n }\n if (className.includes('AI')) {\n return 'assistant';\n }\n if (className.includes('System')) {\n return 'system';\n }\n if (className.includes('Tool')) {\n return 'tool';\n }\n }\n }\n const rawRole =\n message.type ?? message._type ?? message.role ?? message.sender;\n if (typeof rawRole !== 'string') {\n const kwargs = message.kwargs;\n return isRecord(kwargs) ? getMessageRole(kwargs) : undefined;\n }\n const normalized = rawRole.toLowerCase();\n if (normalized === 'human') {\n return 'user';\n }\n if (normalized === 'ai') {\n return 'assistant';\n }\n return normalized;\n}\n\nfunction getMessageText(message: Record<string, unknown>): string | undefined {\n const content =\n message.content ??\n (isRecord(message.kwargs) ? message.kwargs.content : undefined) ??\n (isRecord(message.data) ? message.data.content : undefined);\n if (typeof content === 'string') {\n return content;\n }\n if (!Array.isArray(content)) {\n return undefined;\n }\n const text = content\n .filter(isRecord)\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .join('');\n return text === '' ? undefined : text;\n}\n\nfunction findLastMessageText(value: unknown, role: string): string | undefined {\n const messages = getMessageArray(value);\n if (messages == null) {\n return undefined;\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n if (getMessageRole(messages[i]) !== role) {\n continue;\n }\n const text = getMessageText(messages[i]);\n if (text != null && text.trim() !== '') {\n return text;\n }\n }\n return undefined;\n}\n\nfunction normalizeToolCall(value: unknown): SerializedToolCall | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n const fn = value.function;\n if (isRecord(fn) && typeof fn.name === 'string') {\n return {\n name: fn.name,\n args: parseAttributeValue(fn.arguments),\n ...(typeof value.id === 'string' ? { id: value.id } : {}),\n };\n }\n if (typeof value.name !== 'string') {\n return undefined;\n }\n return {\n name: value.name,\n args: value.args ?? {},\n ...(typeof value.id === 'string' ? { id: value.id } : {}),\n };\n}\n\nfunction getMessageToolCalls(\n message: Record<string, unknown>\n): SerializedToolCall[] {\n const rawCalls =\n message.tool_calls ??\n (isRecord(message.kwargs) ? message.kwargs.tool_calls : undefined) ??\n (isRecord(message.additional_kwargs)\n ? message.additional_kwargs.tool_calls\n : undefined) ??\n (isRecord(message.data) ? message.data.tool_calls : undefined);\n if (!Array.isArray(rawCalls)) {\n return [];\n }\n const calls: SerializedToolCall[] = [];\n for (const rawCall of rawCalls) {\n const call = normalizeToolCall(rawCall);\n if (call != null) {\n calls.push(call);\n }\n }\n return calls;\n}\n\n/**\n * Id-bearing `invalid_tool_calls` on the assistant turn. ToolNode pairs these\n * with synthesized error results (and an invalid-only turn is routed on them\n * alone), so the tool-dispatch span must count them as part of the executing\n * batch — otherwise an invalid-only dispatch finds zero calls and the span\n * keeps the full serialized graph state as its input, and a mixed dispatch\n * silently omits the malformed call. `args` stays the raw unparsed string.\n */\n/** Tool-result ids present in the serialized state — ToolNode's\n * `!toolMessageIds.has(id)` execution filter, mirrored for the span. */\nfunction getToolResultIds(\n messages: Record<string, unknown>[]\n): Set<string> {\n const ids = new Set<string>();\n for (const message of messages) {\n if (getMessageRole(message) !== 'tool') {\n continue;\n }\n const rawId =\n message.tool_call_id ??\n (isRecord(message.kwargs) ? message.kwargs.tool_call_id : undefined) ??\n (isRecord(message.data) ? message.data.tool_call_id : undefined);\n if (typeof rawId === 'string' && rawId !== '') {\n ids.add(rawId);\n }\n }\n return ids;\n}\n\nfunction getMessageInvalidToolCalls(\n message: Record<string, unknown>,\n answeredIds: ReadonlySet<string>\n): SerializedToolCall[] {\n const rawCalls =\n message.invalid_tool_calls ??\n (isRecord(message.kwargs) ? message.kwargs.invalid_tool_calls : undefined) ??\n (isRecord(message.data) ? message.data.invalid_tool_calls : undefined);\n if (!Array.isArray(rawCalls)) {\n return [];\n }\n const calls: SerializedToolCall[] = [];\n for (const rawCall of rawCalls) {\n // Same attribution predicate ToolNode executes with (id-bearing,\n // non-server) so the span never claims calls the node deliberately skips.\n if (\n !isRecord(rawCall) ||\n typeof rawCall.id !== 'string' ||\n rawCall.id === '' ||\n answeredIds.has(rawCall.id) ||\n rawCall.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n continue;\n }\n // Same name fallback ToolNode synthesizes with — a nameless attributable\n // call still gets a result, so it must still count in the span input.\n const call = normalizeToolCall(\n typeof rawCall.name === 'string' && rawCall.name !== ''\n ? rawCall\n : { ...rawCall, name: 'unknown' }\n );\n if (call != null) {\n calls.push(call);\n }\n }\n return calls;\n}\n\n/** The serialized message's own id (uuid), NOT the LC-serialization type id\n * array that `message.id` carries in constructor dumps. */\nfunction getSerializedMessageId(\n message: Record<string, unknown>\n): string | undefined {\n const kwargsId = isRecord(message.kwargs) ? message.kwargs.id : undefined;\n const dataId = isRecord(message.data) ? message.data.id : undefined;\n const rawId = message.id;\n const id = kwargsId ?? dataId ?? rawId;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\n/** Latest assistant turn's tool calls — the calls this tool node is executing. */\nfunction findPendingToolCalls(value: unknown): SerializedToolCall[] {\n const messages = getMessageArray(value);\n if (messages == null) {\n return [];\n }\n /**\n * Invalid calls count only where ToolNode's own gate lets them execute:\n * the messages-state form (a bare-array state means the node returns a\n * plain output list and skips invalid handling) with an id-bearing\n * assistant message (no id, no reducer upsert). Mirrors\n * `canPromoteInvalidCalls` so the span never reports skipped calls.\n */\n const invalidCallsApply = !Array.isArray(value);\n const answeredIds = invalidCallsApply\n ? getToolResultIds(messages)\n : undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (getMessageRole(messages[i]) !== 'assistant') {\n continue;\n }\n const calls = [\n ...getMessageToolCalls(messages[i]),\n ...(invalidCallsApply && getSerializedMessageId(messages[i]) != null\n ? getMessageInvalidToolCalls(messages[i], answeredIds!)\n : []),\n ];\n if (calls.length > 0) {\n return calls;\n }\n }\n return [];\n}\n\nfunction getRootSpanParentId(span: ReadableSpan): string | undefined {\n const legacyParent = (span as { parentSpanId?: string }).parentSpanId;\n if (typeof legacyParent === 'string' && legacyParent !== '') {\n return legacyParent;\n }\n const parentContext = (span as { parentSpanContext?: { spanId?: string } })\n .parentSpanContext;\n const spanId = parentContext?.spanId;\n return typeof spanId === 'string' && spanId !== '' ? spanId : undefined;\n}\n\nfunction isRootSpan(span: ReadableSpan): boolean {\n return getRootSpanParentId(span) == null;\n}\n\n/**\n * LangGraph plumbing observations that add noise without information:\n * the duplicated `__start__` channel-seed nodes and anonymous\n * `RunnableLambda` pass-throughs (Langfuse team feedback items 4 & 5).\n * Internal ToolNode batch spans are disabled at their source so traced child\n * tools retain an exported parent. Explicitly traced ToolNodes are preserved.\n */\nexport function shouldDropLangfuseSpan(spanName: string): boolean {\n return (\n spanName === LANGGRAPH_START_NODE || spanName === ANONYMOUS_LAMBDA_NAME\n );\n}\n\nfunction shapeToolNodeSpan(span: MutableSpan): void {\n const inputKey = LangfuseOtelSpanAttributes.OBSERVATION_INPUT;\n span.name = TOOL_DISPATCH_SPAN_NAME;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n CHAIN_OBSERVATION_TYPE;\n const calls = findPendingToolCalls(\n parseAttributeValue(span.attributes[inputKey])\n );\n if (calls.length === 0) {\n return;\n }\n span.attributes[inputKey] = JSON.stringify(\n calls.map(({ name, args }) => ({ name, args }))\n );\n}\n\nfunction shapeAgentNodeSpan(span: MutableSpan): void {\n span.name = AGENT_NODE_SPAN_NAME;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n}\n\nfunction shapeRootSpan(span: MutableSpan): void {\n const inputKey = LangfuseOtelSpanAttributes.OBSERVATION_INPUT;\n const outputKey = LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT;\n const question = findLastMessageText(\n parseAttributeValue(span.attributes[inputKey]),\n 'user'\n );\n const answer = findLastMessageText(\n parseAttributeValue(span.attributes[outputKey]),\n 'assistant'\n );\n /** A generation that IS the trace root — a bare `model.invoke` with no\n * wrapping chain, i.e. the activity-label path — is also the only\n * observation carrying its own prompt: reducing its observation input\n * would discard the SystemMessage from the one place it is traced.\n * Chain/agent roots keep the full reduction; their child generations\n * still record the complete prompt. Trace-level input/output reduce\n * either way, so the trace list keeps showing question and answer. */\n if (!isGenerationSpan(span)) {\n if (question != null) {\n span.attributes[inputKey] = question;\n }\n if (answer != null) {\n span.attributes[outputKey] = answer;\n }\n }\n const traceInput = question ?? span.attributes[inputKey];\n const traceOutput = answer ?? span.attributes[outputKey];\n if (traceInput != null) {\n span.attributes[LangfuseOtelSpanAttributes.TRACE_INPUT] = traceInput;\n }\n if (traceOutput != null) {\n span.attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT] = traceOutput;\n }\n}\n\nfunction isGenerationSpan(span: MutableSpan): boolean {\n const type = span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE];\n return typeof type === 'string' && type.toLowerCase() === 'generation';\n}\n\nfunction isToolSpan(span: MutableSpan): boolean {\n const type = span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE];\n return (\n typeof type === 'string' && type.toLowerCase() === TOOL_OBSERVATION_TYPE\n );\n}\n\n/**\n * Whether the span is a LangGraph node execution whose node id is the span\n * name — the shape of the outer workflow-agent node. `@langfuse/tracing`\n * flattens object metadata to per-key attributes with string values stored\n * raw, so LangGraph's `langgraph_node` arrives directly comparable.\n */\nfunction isWorkflowNodeSpan(span: MutableSpan): boolean {\n return span.attributes[OBSERVATION_METADATA_LANGGRAPH_NODE] === span.name;\n}\n\n/**\n * LibreChat ephemeral agents are identified as\n * `endpoint__model___sender[____index]` (`__` encodes `:`; see LibreChat's\n * `encodeEphemeralAgentId`), and the outer workflow node carries that id as\n * its span name — so switching models renames the span (item 1). Returns the\n * stable human `sender` segment only when the name matches that encoding:\n * the `endpoint__model` prefix must contain both segments and — unlike\n * display names such as `LibreChat Agent: Ops___EU` — never contains\n * whitespace, so legitimate names that merely embed `___` are left alone.\n */\nfunction extractEphemeralAgentSender(name: string): string | undefined {\n let workingId = name;\n const indexSeparator = workingId.lastIndexOf(EPHEMERAL_AGENT_INDEX_SEPARATOR);\n if (\n indexSeparator !== -1 &&\n /^\\d+$/.test(\n workingId.slice(indexSeparator + EPHEMERAL_AGENT_INDEX_SEPARATOR.length)\n )\n ) {\n workingId = workingId.slice(0, indexSeparator);\n }\n const senderSeparator = workingId.indexOf(EPHEMERAL_AGENT_SENDER_SEPARATOR);\n if (senderSeparator <= 0) {\n return undefined;\n }\n const encodedPrefix = workingId.slice(0, senderSeparator);\n if (/\\s/.test(encodedPrefix)) {\n return undefined;\n }\n const prefixParts = encodedPrefix.split('__');\n if (prefixParts.length < 2 || prefixParts.some((part) => part === '')) {\n return undefined;\n }\n const sender = workingId\n .slice(senderSeparator + EPHEMERAL_AGENT_SENDER_SEPARATOR.length)\n .replace(/__/g, ':');\n return sender === '' ? undefined : sender;\n}\n\n/** Workflow-agent node spans are always children of the run's root chain and\n * always carry `langgraph_node` metadata equal to their name, so host-named\n * run roots (`LibreChat Agent: <name>`) and ordinary chains that merely look\n * like encoded ids (`pipeline__stage___EU`) are never rename candidates.\n * Successful decodes become `agent` observations, matching the inner\n * `agent=<id>` node shaping. */\nfunction shapeEphemeralAgentNodeSpan(span: MutableSpan): void {\n if (isToolSpan(span) || isRootSpan(span) || !isWorkflowNodeSpan(span)) {\n return;\n }\n const sender = extractEphemeralAgentSender(span.name);\n if (sender == null) {\n return;\n }\n span.name = sender;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n}\n\nfunction hasTraceTag(span: MutableSpan, expectedTag: string): boolean {\n const tags = parseAttributeValue(\n span.attributes[LangfuseOtelSpanAttributes.TRACE_TAGS]\n );\n return (\n Array.isArray(tags) &&\n tags.some((tag) => typeof tag === 'string' && tag === expectedTag)\n );\n}\n\nfunction shapeRootObservationType(span: MutableSpan): void {\n if (isGenerationSpan(span)) {\n return;\n }\n if (hasTraceTag(span, AGENT_TRACE_TAG)) {\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n return;\n }\n if (hasTraceTag(span, TITLE_TRACE_TAG)) {\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n CHAIN_OBSERVATION_TYPE;\n }\n}\n\n/**\n * Reshapes spans per Langfuse-team feedback before export:\n * - `agent=<id>` / `tools=<id>` node names carry the ephemeral agent id\n * (`provider__model`) — strip it so switching models doesn't break\n * name-based logic (item 1). The outer workflow node is named with the\n * bare agent id; ephemeral ids reduce to their stable sender name.\n * - LLM generation spans keep the provider client class name (`ChatOpenAI`,\n * `AzureChatOpenAI`, …); rename them to a provider-agnostic `llm` so the\n * name reflects the operation, not the model (the model stays on the\n * generation's model attribute).\n * - Agent nodes become `agent` observations, while tool-dispatch nodes become\n * stable `chain` observations whose input is scoped to the pending calls.\n * Individual child calls remain `tool` observations (items 3 & 4).\n * - Agent trace roots become `agent` observations and title trace roots become\n * `chain` observations. Root and trace input/output are reduced to the user\n * question and assistant response when chat messages are available (item 2).\n */\nexport function shapeLangfuseSpan(span: ReadableSpan): void {\n const mutable = span as MutableSpan;\n if (mutable.name.startsWith(LANGGRAPH_AGENT_NODE_PREFIX)) {\n shapeAgentNodeSpan(mutable);\n } else if (mutable.name.startsWith(LANGGRAPH_TOOL_NODE_PREFIX)) {\n shapeToolNodeSpan(mutable);\n } else if (isGenerationSpan(mutable)) {\n mutable.name = GENERATION_SPAN_NAME;\n } else {\n shapeEphemeralAgentNodeSpan(mutable);\n }\n if (!isRootSpan(span)) {\n return;\n }\n shapeRootObservationType(mutable);\n shapeRootSpan(mutable);\n}\n"],"mappings":";;;;AAIA,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MAAM,8BAA8B;AACpC,MAAM,6BAA6B;AACnC,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,uBAAuB;AAC7B,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAC/B,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,mCAAmC;AACzC,MAAM,kCAAkC;AACxC,MAAM,sCAAsC,GAAGA,kBAAAA,2BAA2B,qBAAqB;AAa/F,SAAS,SAAS,OAAkD;CAClE,OAAO,SAAS,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC3E;AAEA,SAAS,oBAAoB,OAAyB;CACpD,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,MAAM,UAAU,MAAM,KAAK;CAC3B,IAAI,CAAC,QAAQ,WAAW,GAAG,KAAK,CAAC,QAAQ,WAAW,GAAG,GACrD,OAAO;CAET,IAAI;EACF,OAAO,KAAK,MAAM,KAAK;CACzB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,gBACP,OACuC;CACvC,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,MAAM,UAAU,MAAM,OAAO,QA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AAO;AACvB"}
|
|
1
|
+
{"version":3,"file":"langfuseTraceShaping.cjs","names":["LangfuseOtelSpanAttributes"],"sources":["../../src/langfuseTraceShaping.ts"],"sourcesContent":["import { LangfuseOtelSpanAttributes } from '@langfuse/tracing';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { Constants } from '@/common';\n\nconst LANGGRAPH_START_NODE = '__start__';\nconst ANONYMOUS_LAMBDA_NAME = 'RunnableLambda';\nconst LANGGRAPH_AGENT_NODE_PREFIX = 'agent=';\nconst LANGGRAPH_TOOL_NODE_PREFIX = 'tools=';\nconst AGENT_NODE_SPAN_NAME = 'agent';\nconst TOOL_DISPATCH_SPAN_NAME = 'tool-dispatch';\nconst GENERATION_SPAN_NAME = 'llm';\nconst ROOT_OBSERVATION_TYPE = 'agent';\nconst CHAIN_OBSERVATION_TYPE = 'chain';\nconst TOOL_OBSERVATION_TYPE = 'tool';\nconst AGENT_TRACE_TAG = 'agent';\nconst TITLE_TRACE_TAG = 'title';\nconst ACTIVITY_PHASE_TRACE_TAG = 'activity-phase';\nconst ACTIVITY_PHASE_ROOT_NAME = 'summarize-activity-phase';\nconst EPHEMERAL_AGENT_SENDER_SEPARATOR = '___';\nconst EPHEMERAL_AGENT_INDEX_SEPARATOR = '____';\nconst OBSERVATION_METADATA_LANGGRAPH_NODE = `${LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.langgraph_node`;\n\ntype MutableSpan = ReadableSpan & {\n name: string;\n attributes: Record<string, unknown>;\n};\n\ntype SerializedToolCall = {\n name: string;\n args: unknown;\n id?: string;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value != null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction parseAttributeValue(value: unknown): unknown {\n if (typeof value !== 'string') {\n return value;\n }\n const trimmed = value.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return value;\n }\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nfunction getMessageArray(\n value: unknown\n): Record<string, unknown>[] | undefined {\n if (Array.isArray(value)) {\n const records = value.filter(isRecord);\n return records.length > 0 ? records : undefined;\n }\n if (!isRecord(value)) {\n return undefined;\n }\n return (\n getMessageArray(value.messages) ??\n getMessageArray(value.input) ??\n getMessageArray(value.output)\n );\n}\n\nfunction getMessageRole(message: Record<string, unknown>): string | undefined {\n const id = message.id;\n if (Array.isArray(id)) {\n const className = id[id.length - 1];\n if (typeof className === 'string') {\n if (className.includes('Human')) {\n return 'user';\n }\n if (className.includes('AI')) {\n return 'assistant';\n }\n if (className.includes('System')) {\n return 'system';\n }\n if (className.includes('Tool')) {\n return 'tool';\n }\n }\n }\n const rawRole =\n message.type ?? message._type ?? message.role ?? message.sender;\n if (typeof rawRole !== 'string') {\n const kwargs = message.kwargs;\n return isRecord(kwargs) ? getMessageRole(kwargs) : undefined;\n }\n const normalized = rawRole.toLowerCase();\n if (normalized === 'human') {\n return 'user';\n }\n if (normalized === 'ai') {\n return 'assistant';\n }\n return normalized;\n}\n\nfunction getMessageText(message: Record<string, unknown>): string | undefined {\n const content =\n message.content ??\n (isRecord(message.kwargs) ? message.kwargs.content : undefined) ??\n (isRecord(message.data) ? message.data.content : undefined);\n if (typeof content === 'string') {\n return content;\n }\n if (!Array.isArray(content)) {\n return undefined;\n }\n const text = content\n .filter(isRecord)\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .join('');\n return text === '' ? undefined : text;\n}\n\nfunction findLastMessageText(value: unknown, role: string): string | undefined {\n const messages = getMessageArray(value);\n if (messages == null) {\n return undefined;\n }\n for (let i = messages.length - 1; i >= 0; i--) {\n if (getMessageRole(messages[i]) !== role) {\n continue;\n }\n const text = getMessageText(messages[i]);\n if (text != null && text.trim() !== '') {\n return text;\n }\n }\n return undefined;\n}\n\nfunction normalizeToolCall(value: unknown): SerializedToolCall | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n const fn = value.function;\n if (isRecord(fn) && typeof fn.name === 'string') {\n return {\n name: fn.name,\n args: parseAttributeValue(fn.arguments),\n ...(typeof value.id === 'string' ? { id: value.id } : {}),\n };\n }\n if (typeof value.name !== 'string') {\n return undefined;\n }\n return {\n name: value.name,\n args: value.args ?? {},\n ...(typeof value.id === 'string' ? { id: value.id } : {}),\n };\n}\n\nfunction getMessageToolCalls(\n message: Record<string, unknown>\n): SerializedToolCall[] {\n const rawCalls =\n message.tool_calls ??\n (isRecord(message.kwargs) ? message.kwargs.tool_calls : undefined) ??\n (isRecord(message.additional_kwargs)\n ? message.additional_kwargs.tool_calls\n : undefined) ??\n (isRecord(message.data) ? message.data.tool_calls : undefined);\n if (!Array.isArray(rawCalls)) {\n return [];\n }\n const calls: SerializedToolCall[] = [];\n for (const rawCall of rawCalls) {\n const call = normalizeToolCall(rawCall);\n if (call != null) {\n calls.push(call);\n }\n }\n return calls;\n}\n\n/**\n * Id-bearing `invalid_tool_calls` on the assistant turn. ToolNode pairs these\n * with synthesized error results (and an invalid-only turn is routed on them\n * alone), so the tool-dispatch span must count them as part of the executing\n * batch — otherwise an invalid-only dispatch finds zero calls and the span\n * keeps the full serialized graph state as its input, and a mixed dispatch\n * silently omits the malformed call. `args` stays the raw unparsed string.\n */\n/** Tool-result ids present in the serialized state — ToolNode's\n * `!toolMessageIds.has(id)` execution filter, mirrored for the span. */\nfunction getToolResultIds(\n messages: Record<string, unknown>[]\n): Set<string> {\n const ids = new Set<string>();\n for (const message of messages) {\n if (getMessageRole(message) !== 'tool') {\n continue;\n }\n const rawId =\n message.tool_call_id ??\n (isRecord(message.kwargs) ? message.kwargs.tool_call_id : undefined) ??\n (isRecord(message.data) ? message.data.tool_call_id : undefined);\n if (typeof rawId === 'string' && rawId !== '') {\n ids.add(rawId);\n }\n }\n return ids;\n}\n\nfunction getMessageInvalidToolCalls(\n message: Record<string, unknown>,\n answeredIds: ReadonlySet<string>\n): SerializedToolCall[] {\n const rawCalls =\n message.invalid_tool_calls ??\n (isRecord(message.kwargs) ? message.kwargs.invalid_tool_calls : undefined) ??\n (isRecord(message.data) ? message.data.invalid_tool_calls : undefined);\n if (!Array.isArray(rawCalls)) {\n return [];\n }\n const calls: SerializedToolCall[] = [];\n for (const rawCall of rawCalls) {\n // Same attribution predicate ToolNode executes with (id-bearing,\n // non-server) so the span never claims calls the node deliberately skips.\n if (\n !isRecord(rawCall) ||\n typeof rawCall.id !== 'string' ||\n rawCall.id === '' ||\n answeredIds.has(rawCall.id) ||\n rawCall.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n continue;\n }\n // Same name fallback ToolNode synthesizes with — a nameless attributable\n // call still gets a result, so it must still count in the span input.\n const call = normalizeToolCall(\n typeof rawCall.name === 'string' && rawCall.name !== ''\n ? rawCall\n : { ...rawCall, name: 'unknown' }\n );\n if (call != null) {\n calls.push(call);\n }\n }\n return calls;\n}\n\n/** The serialized message's own id (uuid), NOT the LC-serialization type id\n * array that `message.id` carries in constructor dumps. */\nfunction getSerializedMessageId(\n message: Record<string, unknown>\n): string | undefined {\n const kwargsId = isRecord(message.kwargs) ? message.kwargs.id : undefined;\n const dataId = isRecord(message.data) ? message.data.id : undefined;\n const rawId = message.id;\n const id = kwargsId ?? dataId ?? rawId;\n return typeof id === 'string' && id !== '' ? id : undefined;\n}\n\n/** Latest assistant turn's tool calls — the calls this tool node is executing. */\nfunction findPendingToolCalls(value: unknown): SerializedToolCall[] {\n const messages = getMessageArray(value);\n if (messages == null) {\n return [];\n }\n /**\n * Invalid calls count only where ToolNode's own gate lets them execute:\n * the messages-state form (a bare-array state means the node returns a\n * plain output list and skips invalid handling) with an id-bearing\n * assistant message (no id, no reducer upsert). Mirrors\n * `canPromoteInvalidCalls` so the span never reports skipped calls.\n */\n const invalidCallsApply = !Array.isArray(value);\n const answeredIds = invalidCallsApply\n ? getToolResultIds(messages)\n : undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (getMessageRole(messages[i]) !== 'assistant') {\n continue;\n }\n const calls = [\n ...getMessageToolCalls(messages[i]),\n ...(invalidCallsApply && getSerializedMessageId(messages[i]) != null\n ? getMessageInvalidToolCalls(messages[i], answeredIds!)\n : []),\n ];\n if (calls.length > 0) {\n return calls;\n }\n }\n return [];\n}\n\nfunction getRootSpanParentId(span: ReadableSpan): string | undefined {\n const legacyParent = (span as { parentSpanId?: string }).parentSpanId;\n if (typeof legacyParent === 'string' && legacyParent !== '') {\n return legacyParent;\n }\n const parentContext = (span as { parentSpanContext?: { spanId?: string } })\n .parentSpanContext;\n const spanId = parentContext?.spanId;\n return typeof spanId === 'string' && spanId !== '' ? spanId : undefined;\n}\n\nfunction isRootSpan(span: ReadableSpan): boolean {\n return getRootSpanParentId(span) == null;\n}\n\n/**\n * LangGraph plumbing observations that add noise without information:\n * the duplicated `__start__` channel-seed nodes and anonymous\n * `RunnableLambda` pass-throughs (Langfuse team feedback items 4 & 5).\n * Internal ToolNode batch spans are disabled at their source so traced child\n * tools retain an exported parent. Explicitly traced ToolNodes are preserved.\n */\nexport function shouldDropLangfuseSpan(spanName: string): boolean {\n return (\n spanName === LANGGRAPH_START_NODE || spanName === ANONYMOUS_LAMBDA_NAME\n );\n}\n\nfunction shapeToolNodeSpan(span: MutableSpan): void {\n const inputKey = LangfuseOtelSpanAttributes.OBSERVATION_INPUT;\n span.name = TOOL_DISPATCH_SPAN_NAME;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n CHAIN_OBSERVATION_TYPE;\n const calls = findPendingToolCalls(\n parseAttributeValue(span.attributes[inputKey])\n );\n if (calls.length === 0) {\n return;\n }\n span.attributes[inputKey] = JSON.stringify(\n calls.map(({ name, args }) => ({ name, args }))\n );\n}\n\nfunction shapeAgentNodeSpan(span: MutableSpan): void {\n span.name = AGENT_NODE_SPAN_NAME;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n}\n\nfunction shapeRootSpan(span: MutableSpan): void {\n const inputKey = LangfuseOtelSpanAttributes.OBSERVATION_INPUT;\n const outputKey = LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT;\n const question = findLastMessageText(\n parseAttributeValue(span.attributes[inputKey]),\n 'user'\n );\n const answer = findLastMessageText(\n parseAttributeValue(span.attributes[outputKey]),\n 'assistant'\n );\n /** A generation that IS the trace root — a bare `model.invoke` with no\n * wrapping chain, i.e. the activity-label path — is also the only\n * observation carrying its own prompt: reducing its observation input\n * would discard the SystemMessage from the one place it is traced.\n * Chain/agent roots keep the full reduction; their child generations\n * still record the complete prompt. Trace-level input/output reduce\n * either way, so the trace list keeps showing question and answer. */\n if (!isGenerationSpan(span)) {\n if (question != null) {\n span.attributes[inputKey] = question;\n }\n if (answer != null) {\n span.attributes[outputKey] = answer;\n }\n }\n const traceInput = question ?? span.attributes[inputKey];\n const traceOutput = answer ?? span.attributes[outputKey];\n if (traceInput != null) {\n span.attributes[LangfuseOtelSpanAttributes.TRACE_INPUT] = traceInput;\n }\n if (traceOutput != null) {\n span.attributes[LangfuseOtelSpanAttributes.TRACE_OUTPUT] = traceOutput;\n }\n}\n\nfunction isGenerationSpan(span: MutableSpan): boolean {\n const type = span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE];\n return typeof type === 'string' && type.toLowerCase() === 'generation';\n}\n\nfunction isToolSpan(span: MutableSpan): boolean {\n const type = span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE];\n return (\n typeof type === 'string' && type.toLowerCase() === TOOL_OBSERVATION_TYPE\n );\n}\n\n/**\n * Whether the span is a LangGraph node execution whose node id is the span\n * name — the shape of the outer workflow-agent node. `@langfuse/tracing`\n * flattens object metadata to per-key attributes with string values stored\n * raw, so LangGraph's `langgraph_node` arrives directly comparable.\n */\nfunction isWorkflowNodeSpan(span: MutableSpan): boolean {\n return span.attributes[OBSERVATION_METADATA_LANGGRAPH_NODE] === span.name;\n}\n\n/**\n * LibreChat ephemeral agents are identified as\n * `endpoint__model___sender[____index]` (`__` encodes `:`; see LibreChat's\n * `encodeEphemeralAgentId`), and the outer workflow node carries that id as\n * its span name — so switching models renames the span (item 1). Returns the\n * stable human `sender` segment only when the name matches that encoding:\n * the `endpoint__model` prefix must contain both segments and — unlike\n * display names such as `LibreChat Agent: Ops___EU` — never contains\n * whitespace, so legitimate names that merely embed `___` are left alone.\n */\nfunction extractEphemeralAgentSender(name: string): string | undefined {\n let workingId = name;\n const indexSeparator = workingId.lastIndexOf(EPHEMERAL_AGENT_INDEX_SEPARATOR);\n if (\n indexSeparator !== -1 &&\n /^\\d+$/.test(\n workingId.slice(indexSeparator + EPHEMERAL_AGENT_INDEX_SEPARATOR.length)\n )\n ) {\n workingId = workingId.slice(0, indexSeparator);\n }\n const senderSeparator = workingId.indexOf(EPHEMERAL_AGENT_SENDER_SEPARATOR);\n if (senderSeparator <= 0) {\n return undefined;\n }\n const encodedPrefix = workingId.slice(0, senderSeparator);\n if (/\\s/.test(encodedPrefix)) {\n return undefined;\n }\n const prefixParts = encodedPrefix.split('__');\n if (prefixParts.length < 2 || prefixParts.some((part) => part === '')) {\n return undefined;\n }\n const sender = workingId\n .slice(senderSeparator + EPHEMERAL_AGENT_SENDER_SEPARATOR.length)\n .replace(/__/g, ':');\n return sender === '' ? undefined : sender;\n}\n\n/** Workflow-agent node spans are always children of the run's root chain and\n * always carry `langgraph_node` metadata equal to their name, so host-named\n * run roots (`LibreChat Agent: <name>`) and ordinary chains that merely look\n * like encoded ids (`pipeline__stage___EU`) are never rename candidates.\n * Successful decodes become `agent` observations, matching the inner\n * `agent=<id>` node shaping. */\nfunction shapeEphemeralAgentNodeSpan(span: MutableSpan): void {\n if (isToolSpan(span) || isRootSpan(span) || !isWorkflowNodeSpan(span)) {\n return;\n }\n const sender = extractEphemeralAgentSender(span.name);\n if (sender == null) {\n return;\n }\n span.name = sender;\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n}\n\nfunction hasTraceTag(span: MutableSpan, expectedTag: string): boolean {\n const tags = parseAttributeValue(\n span.attributes[LangfuseOtelSpanAttributes.TRACE_TAGS]\n );\n return (\n Array.isArray(tags) &&\n tags.some((tag) => typeof tag === 'string' && tag === expectedTag)\n );\n}\n\nfunction shapeRootObservationType(span: MutableSpan): void {\n if (isGenerationSpan(span)) {\n return;\n }\n if (\n hasTraceTag(span, TITLE_TRACE_TAG) ||\n (span.name === ACTIVITY_PHASE_ROOT_NAME &&\n hasTraceTag(span, ACTIVITY_PHASE_TRACE_TAG))\n ) {\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n CHAIN_OBSERVATION_TYPE;\n return;\n }\n if (hasTraceTag(span, AGENT_TRACE_TAG)) {\n span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] =\n ROOT_OBSERVATION_TYPE;\n }\n}\n\n/**\n * Reshapes spans per Langfuse-team feedback before export:\n * - `agent=<id>` / `tools=<id>` node names carry the ephemeral agent id\n * (`provider__model`) — strip it so switching models doesn't break\n * name-based logic (item 1). The outer workflow node is named with the\n * bare agent id; ephemeral ids reduce to their stable sender name.\n * - LLM generation spans keep the provider client class name (`ChatOpenAI`,\n * `AzureChatOpenAI`, …); rename them to a provider-agnostic `llm` so the\n * name reflects the operation, not the model (the model stays on the\n * generation's model attribute).\n * - Agent nodes become `agent` observations, while tool-dispatch nodes become\n * stable `chain` observations whose input is scoped to the pending calls.\n * Individual child calls remain `tool` observations (items 3 & 4).\n * - Agent trace roots become `agent` observations, while title and activity\n * summary roots become `chain` observations. Root and trace input/output are\n * reduced to the user question and assistant response when chat messages are\n * available (item 2).\n */\nexport function shapeLangfuseSpan(span: ReadableSpan): void {\n const mutable = span as MutableSpan;\n if (mutable.name.startsWith(LANGGRAPH_AGENT_NODE_PREFIX)) {\n shapeAgentNodeSpan(mutable);\n } else if (mutable.name.startsWith(LANGGRAPH_TOOL_NODE_PREFIX)) {\n shapeToolNodeSpan(mutable);\n } else if (isGenerationSpan(mutable)) {\n mutable.name = GENERATION_SPAN_NAME;\n } else {\n sh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AC5D,IAAI,WAAW,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,mBAAmB,IAAI,GAClE;CAEF,MAAM,SAAS,4BAA4B,KAAK,IAAI;CACpD,IAAI,UAAU,MACZ;CAEF,KAAK,OAAO;CACZ,KAAK,WAAWA,kBAAAA,2BAA2B,oBACzC;AACJ;AAEA,SAAS,YAAY,MAAmB,aAA8B;CACpE,MAAM,OAAO,oBACX,KAAK,WAAWA,kBAAAA,2BAA2B,WAC7C;CACA,OACE,MAAM,QAAQ,IAAI,KAClB,KAAK,MAAM,QAAQ,OAAO,QAAQ,YAAY,QAAQ,WAAW;AAErE;AAEA,SAAS,yBAAyB,MAAyB;CACzD,IAAI,iBAAiB,IAAI,GACvB;CAEF,IACE,YAAY,MAAM,eAAe,KAChC,KAAK,SAAS,4BACb,YAAY,MAAM,wBAAwB,GAC5C;EACA,KAAK,WAAWA,kBAAAA,2BAA2B,oBACzC;EACF;CACF;CACA,IAAI,YAAY,MAAM,eAAe,GACnC,KAAK,WAAWA,kBAAAA,2BAA2B,oBACzC;AAEN;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBAAkB,MAA0B;CAC1D,MAAM,UAAU;CAChB,IAAI,QAAQ,KAAK,WAAW,2BAA2B,GACrD,mBAAmB,OAAO;MACrB,IAAI,QAAQ,KAAK,WAAW,0BAA0B,GAC3D,kBAAkB,OAAO;MACpB,IAAI,iBAAiB,OAAO,GACjC,QAAQ,OAAO;MAEf,4BAA4B,OAAO;CAErC,IAAI,CAAC,WAAW,IAAI,GAClB;CAEF,yBAAyB,OAAO;CAChC,cAAc,OAAO;AACvB"}
|
package/dist/cjs/run.cjs
CHANGED
|
@@ -39,11 +39,14 @@ const defaultOmitOptions = new Set([
|
|
|
39
39
|
"maxOutputTokens",
|
|
40
40
|
"additionalModelRequestFields"
|
|
41
41
|
]);
|
|
42
|
+
const ACTIVITY_LABEL_TRACE_NAME = "LibreChat Activity Label";
|
|
43
|
+
const ACTIVITY_PHASE_TRACE_NAME = "LibreChat Activity Phase";
|
|
42
44
|
const CUSTOM_GRAPH_EVENTS = new Set([
|
|
43
45
|
"on_agent_update",
|
|
44
46
|
"on_run_step",
|
|
45
47
|
"on_run_step_delta",
|
|
46
48
|
"on_run_step_completed",
|
|
49
|
+
"on_run_step_closed",
|
|
47
50
|
"on_message_delta",
|
|
48
51
|
"on_reasoning_delta",
|
|
49
52
|
"on_tool_execute",
|
|
@@ -58,6 +61,7 @@ const CUSTOM_GRAPH_EVENTS = new Set([
|
|
|
58
61
|
const DIRECT_DISPATCHED_STEP_EVENTS = new Set([
|
|
59
62
|
"on_run_step",
|
|
60
63
|
"on_run_step_delta",
|
|
64
|
+
"on_run_step_closed",
|
|
61
65
|
"on_message_delta",
|
|
62
66
|
"on_reasoning_delta"
|
|
63
67
|
]);
|
|
@@ -66,6 +70,25 @@ function getStepScopedEventId(data) {
|
|
|
66
70
|
const candidate = data;
|
|
67
71
|
return typeof candidate.id === "string" ? candidate.id : void 0;
|
|
68
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Narrows an ON_RUN_STEP_COMPLETED payload (`{ result: ToolCompleteEvent }`)
|
|
75
|
+
* to the ids step closure needs. Returns undefined for malformed payloads and
|
|
76
|
+
* the resume race's empty step id.
|
|
77
|
+
*/
|
|
78
|
+
function getToolCompletion(data) {
|
|
79
|
+
if (data == null || typeof data !== "object") return;
|
|
80
|
+
const { result } = data;
|
|
81
|
+
if (result == null || typeof result !== "object") return;
|
|
82
|
+
const candidate = result;
|
|
83
|
+
if (typeof candidate.id !== "string" || candidate.id === "") return;
|
|
84
|
+
const toolCallId = candidate.tool_call?.id;
|
|
85
|
+
const completedAt = candidate.completed_at;
|
|
86
|
+
return {
|
|
87
|
+
stepId: candidate.id,
|
|
88
|
+
...typeof toolCallId === "string" ? { toolCallId } : {},
|
|
89
|
+
...typeof completedAt === "number" ? { completedAt } : {}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
69
92
|
function isLangGraphResumeMapForInterrupt(value, interruptId) {
|
|
70
93
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
71
94
|
return Object.prototype.hasOwnProperty.call(value, interruptId);
|
|
@@ -464,7 +487,32 @@ var Run = class Run {
|
|
|
464
487
|
const stepScopedEventId = getStepScopedEventId(data);
|
|
465
488
|
if (DIRECT_DISPATCHED_STEP_EVENTS.has(eventName) && this.Graph != null && stepScopedEventId != null && this.Graph.hasHandlerDispatchedEvent(eventName, stepScopedEventId)) return;
|
|
466
489
|
const handler = this.handlerRegistry?.getHandler(eventName);
|
|
467
|
-
|
|
490
|
+
/**
|
|
491
|
+
* Tool completions arriving over the custom-event channel are the only
|
|
492
|
+
* signal ToolNode (which holds no graph reference) emits — observe them
|
|
493
|
+
* here to drive step closure. Runs in `finally`, independent of handler
|
|
494
|
+
* registration, so an absent or throwing host handler cannot lose the
|
|
495
|
+
* close; duplicate callback echoes are absorbed by the terminal-status
|
|
496
|
+
* guard in `closeRunStep`.
|
|
497
|
+
*/
|
|
498
|
+
try {
|
|
499
|
+
if (handler && this.Graph) return await handler.handle(eventName, data, metadata, this.Graph);
|
|
500
|
+
} finally {
|
|
501
|
+
if (eventName === "on_run_step_completed" && this.Graph != null) {
|
|
502
|
+
const completion = getToolCompletion(data);
|
|
503
|
+
if (completion != null)
|
|
504
|
+
/**
|
|
505
|
+
* The producer stamped `completed_at` before dispatch. Carrying it
|
|
506
|
+
* through keeps the recorded duration the tool's, not the host
|
|
507
|
+
* handler's — this runs after an arbitrarily slow handler resolves.
|
|
508
|
+
*/
|
|
509
|
+
await this.Graph.recordStepCompletion(completion.stepId, {
|
|
510
|
+
toolCallId: completion.toolCallId,
|
|
511
|
+
metadata,
|
|
512
|
+
at: completion.completedAt
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
}
|
|
468
516
|
};
|
|
469
517
|
}
|
|
470
518
|
shouldClearHookSession(streamThrew) {
|
|
@@ -473,6 +521,18 @@ var Run = class Run {
|
|
|
473
521
|
isAwaitingResume(streamThrew) {
|
|
474
522
|
return this._interrupt != null && this._haltedReason == null && !streamThrew;
|
|
475
523
|
}
|
|
524
|
+
/**
|
|
525
|
+
* Terminal status for steps still open at end-of-run: `cancelled` for
|
|
526
|
+
* intentional stops (caller abort, hook halt), `failed` for unexpected
|
|
527
|
+
* stream errors, `completed` for a natural finish. Reads `_haltedReason`
|
|
528
|
+
* behind a method boundary on purpose — it is assigned inside the
|
|
529
|
+
* `consumeStream` closure, which control-flow narrowing cannot see.
|
|
530
|
+
*/
|
|
531
|
+
resolveSweepStatus(streamThrew, streamAborted) {
|
|
532
|
+
if (streamThrew) return streamAborted ? "cancelled" : "failed";
|
|
533
|
+
if (this._haltedReason != null) return "cancelled";
|
|
534
|
+
return "completed";
|
|
535
|
+
}
|
|
476
536
|
getStreamLangfuseConfig(graph) {
|
|
477
537
|
const primaryContext = graph.agentContexts.get(graph.defaultAgentId);
|
|
478
538
|
if (primaryContext != null) return require_langfuseConfig.resolveLangfuseConfig(this.langfuse, primaryContext.langfuse);
|
|
@@ -644,6 +704,14 @@ var Run = class Run {
|
|
|
644
704
|
* preserving session hooks would leak them into the next run.
|
|
645
705
|
*/
|
|
646
706
|
let streamThrew = false;
|
|
707
|
+
let streamAborted = false;
|
|
708
|
+
/**
|
|
709
|
+
* When the stream itself ended — captured before the post-stream work in
|
|
710
|
+
* the `finally` (Stop/StopFailure hooks, Langfuse disposal, which can
|
|
711
|
+
* force-flush) so a slow hook cannot inflate the terminal stamps that the
|
|
712
|
+
* sweep writes onto steps that were still open.
|
|
713
|
+
*/
|
|
714
|
+
let terminalAt;
|
|
647
715
|
const consumeStream = async () => {
|
|
648
716
|
/**
|
|
649
717
|
* `streamEvents` accepts both state inputs and `Command` (resume) at
|
|
@@ -700,9 +768,22 @@ var Run = class Run {
|
|
|
700
768
|
};
|
|
701
769
|
}
|
|
702
770
|
}
|
|
771
|
+
/**
|
|
772
|
+
* Stamped before the handler runs: the close below happens after an
|
|
773
|
+
* arbitrarily slow host handler resolves, and the step's duration
|
|
774
|
+
* should end when the model did, not when the host finished with it.
|
|
775
|
+
*/
|
|
776
|
+
const modelEndAt = eventName === "on_chat_model_end" ? Date.now() : void 0;
|
|
703
777
|
const handler = this.handlerRegistry?.getHandler(eventName);
|
|
704
778
|
if (handler) await handler.handle(eventName, data, metadata, this.Graph);
|
|
705
779
|
/**
|
|
780
|
+
* A finished model call ends its lane's open message step. Placed
|
|
781
|
+
* here — not in `ModelEndHandler` — because hosts replace the
|
|
782
|
+
* CHAT_MODEL_END handler with their own instance, which would
|
|
783
|
+
* silently drop the close.
|
|
784
|
+
*/
|
|
785
|
+
if (eventName === "on_chat_model_end" && this.Graph != null) await this.Graph.closeOpenMessageStep(metadata, modelEndAt);
|
|
786
|
+
/**
|
|
706
787
|
* Mid-flight halt: any hook (PreToolUse, PostToolUse,
|
|
707
788
|
* PostToolBatch, SubagentStart/Stop, PreCompact, PostCompact)
|
|
708
789
|
* that returned `preventContinuation: true` raises a halt
|
|
@@ -729,6 +810,7 @@ var Run = class Run {
|
|
|
729
810
|
break;
|
|
730
811
|
}
|
|
731
812
|
}
|
|
813
|
+
terminalAt = Date.now();
|
|
732
814
|
if (this._interrupt != null) await this.resolveInterruptResumeConfig(config);
|
|
733
815
|
/**
|
|
734
816
|
* Skip the Stop hook when the run paused on a HITL interrupt
|
|
@@ -787,7 +869,16 @@ var Run = class Run {
|
|
|
787
869
|
tags: ["librechat", "agent"]
|
|
788
870
|
}, consumeStream));
|
|
789
871
|
} catch (err) {
|
|
872
|
+
terminalAt = Date.now();
|
|
790
873
|
streamThrew = true;
|
|
874
|
+
/**
|
|
875
|
+
* Corroborate cancellation against an actually-aborted signal. A
|
|
876
|
+
* provider SDK or host handler can reject with an `AbortError` while
|
|
877
|
+
* nothing was cancelled — that is an unexpected failure (it also fires
|
|
878
|
+
* `StopFailure`), and naming it `cancelled` would misreport abort
|
|
879
|
+
* forensics.
|
|
880
|
+
*/
|
|
881
|
+
streamAborted = config.signal?.aborted === true || this.Graph.signal?.aborted === true;
|
|
791
882
|
if (this.hookRegistry?.hasHookFor("StopFailure", this.id) === true) {
|
|
792
883
|
const runMessages = this.Graph.getRunMessages() ?? [];
|
|
793
884
|
await require_executeHooks.executeHooks({
|
|
@@ -831,6 +922,21 @@ var Run = class Run {
|
|
|
831
922
|
this.hookRegistry?.clearHaltSignal(this.id);
|
|
832
923
|
await require_langfuse.disposeLangfuseHandler(langfuseHandler);
|
|
833
924
|
/**
|
|
925
|
+
* Terminal sweep: close every step that never reached a terminal
|
|
926
|
+
* status — `completed` on a natural end, `cancelled` on caller abort
|
|
927
|
+
* or hook halt, `failed` on an unexpected stream error. Skipped on a
|
|
928
|
+
* HITL pause, where the open steps continue after `resume()`.
|
|
929
|
+
*
|
|
930
|
+
* Runs BEFORE the callback teardown below, so a caller observing
|
|
931
|
+
* lifecycle events only through `RunnableConfig.callbacks` still
|
|
932
|
+
* receives these closures rather than being left with unmatched
|
|
933
|
+
* starts, and before `getContentParts()` so terminal stamps flow into
|
|
934
|
+
* content and session serialization.
|
|
935
|
+
*/
|
|
936
|
+
if (!this.isAwaitingResume(streamThrew)) try {
|
|
937
|
+
await this.Graph.closeUnfinishedRunSteps(this.resolveSweepStatus(streamThrew, streamAborted), terminalAt);
|
|
938
|
+
} catch {}
|
|
939
|
+
/**
|
|
834
940
|
* Break the reference chain that keeps heavy data alive via
|
|
835
941
|
* LangGraph's internal `__pregel_scratchpad.currentTaskInput` →
|
|
836
942
|
* `@langchain/core` `RunTree.extra[lc:child_config]` →
|
|
@@ -1190,17 +1296,40 @@ var Run = class Run {
|
|
|
1190
1296
|
* than the labeled agent's. Skip generation entirely instead. */
|
|
1191
1297
|
if (agentId != null && requestedContext == null) return {};
|
|
1192
1298
|
const labelContext = this.Graph == null ? void 0 : requestedContext ?? this.Graph.agentContexts.get(this.Graph.defaultAgentId);
|
|
1193
|
-
const traceMetadata = require_langfuse.createLangfuseTraceMetadata({
|
|
1194
|
-
messageId: "activity-label-" + this.id,
|
|
1195
|
-
agentName: labelContext?.name
|
|
1196
|
-
});
|
|
1197
|
-
const labelRunName = require_langfuse.getLangfuseTraceName(traceMetadata, "LibreChat Activity Label");
|
|
1198
1299
|
/** Shallow-cloned: activity labels run once per tool batch, and writing
|
|
1199
1300
|
* the Langfuse handler back onto a host-reused `chainOptions` would
|
|
1200
1301
|
* accumulate duplicate callbacks across batches. */
|
|
1201
1302
|
const labelChainOptions = { ...chainOptions ?? {} };
|
|
1202
1303
|
const labelUserId = typeof labelChainOptions.configurable?.user_id === "string" ? labelChainOptions.configurable.user_id : void 0;
|
|
1203
1304
|
const labelSessionId = typeof labelChainOptions.configurable?.thread_id === "string" ? labelChainOptions.configurable.thread_id : void 0;
|
|
1305
|
+
const labelIndex = labelSeq - 1;
|
|
1306
|
+
const labelParentMessageId = labelChainOptions.configurable?.requestBody?.parentMessageId;
|
|
1307
|
+
/** An omitted `agentId` is attributable only when exactly one context
|
|
1308
|
+
* exists. Multi-agent callers remain unattributed instead of being
|
|
1309
|
+
* incorrectly assigned to the graph's default agent. */
|
|
1310
|
+
const labelAgentId = agentId ?? (this.Graph?.agentContexts.size === 1 ? this.Graph.defaultAgentId : void 0);
|
|
1311
|
+
const labelAgentName = labelAgentId == null ? void 0 : labelContext?.name;
|
|
1312
|
+
const labelMetadata = {
|
|
1313
|
+
sourceRunId: this.id,
|
|
1314
|
+
responseId: this.id,
|
|
1315
|
+
activityIndex: labelIndex,
|
|
1316
|
+
...typeof labelParentMessageId === "string" ? { parentMessageId: labelParentMessageId } : {},
|
|
1317
|
+
...labelAgentId == null ? {} : { agentId: labelAgentId },
|
|
1318
|
+
...labelAgentName == null ? {} : { agentName: labelAgentName }
|
|
1319
|
+
};
|
|
1320
|
+
const traceMetadata = {
|
|
1321
|
+
...require_langfuse.createLangfuseTraceMetadata({
|
|
1322
|
+
messageId: "activity-label-" + this.id,
|
|
1323
|
+
parentMessageId: labelParentMessageId,
|
|
1324
|
+
agentId: labelAgentId,
|
|
1325
|
+
agentName: labelAgentName
|
|
1326
|
+
}),
|
|
1327
|
+
sourceRunId: this.id,
|
|
1328
|
+
responseId: this.id,
|
|
1329
|
+
activityIndex: String(labelIndex)
|
|
1330
|
+
};
|
|
1331
|
+
const labelRunName = labelChainOptions.runName ?? ACTIVITY_LABEL_TRACE_NAME;
|
|
1332
|
+
const labelTags = ["librechat", "activity-label"];
|
|
1204
1333
|
const labelLangfuseConfig = require_langfuseConfig.resolveLangfuseConfig(this.langfuse, labelContext?.langfuse);
|
|
1205
1334
|
require_instrumentation.initializeLangfuseTracing(labelLangfuseConfig);
|
|
1206
1335
|
/** Seed policy, threading two constraints:
|
|
@@ -1236,11 +1365,11 @@ var Run = class Run {
|
|
|
1236
1365
|
userId: labelUserId,
|
|
1237
1366
|
sessionId: labelSessionId,
|
|
1238
1367
|
traceMetadata,
|
|
1239
|
-
tags:
|
|
1368
|
+
tags: labelTags,
|
|
1240
1369
|
traceIdSeed: labelLangfuseConfig?.deterministicTraceId === true ? labelTraceSeed : void 0,
|
|
1241
1370
|
runId: labelScopeRunId,
|
|
1242
1371
|
toolOutputTracing: labelRuntimeScope.toolOutputTracing,
|
|
1243
|
-
traceName:
|
|
1372
|
+
traceName: labelRunName
|
|
1244
1373
|
});
|
|
1245
1374
|
if (labelLangfuseHandler != null) labelChainOptions.callbacks = require_callbacks.appendCallbacks(labelChainOptions.callbacks, [labelLangfuseHandler]);
|
|
1246
1375
|
/** The label prompt becomes Langfuse generation input, so the resolved
|
|
@@ -1293,15 +1422,20 @@ var Run = class Run {
|
|
|
1293
1422
|
const invokeConfig = Object.assign({}, labelChainOptions, {
|
|
1294
1423
|
run_id: labelRunId,
|
|
1295
1424
|
runId: labelRunId,
|
|
1296
|
-
runName:
|
|
1425
|
+
runName: labelRunName,
|
|
1426
|
+
tags: [...new Set([...labelChainOptions.tags ?? [], ...labelTags])],
|
|
1427
|
+
metadata: {
|
|
1428
|
+
...labelChainOptions.metadata ?? {},
|
|
1429
|
+
...labelMetadata
|
|
1430
|
+
}
|
|
1297
1431
|
});
|
|
1298
1432
|
const invokeLabel = (runtimeConfig) => require_langfuse.withLangfuseAttributes({
|
|
1299
1433
|
langfuse: labelLangfuseConfig,
|
|
1300
1434
|
userId: labelUserId,
|
|
1301
1435
|
sessionId: labelSessionId,
|
|
1302
|
-
traceName:
|
|
1436
|
+
traceName: labelRunName,
|
|
1303
1437
|
traceMetadata,
|
|
1304
|
-
tags:
|
|
1438
|
+
tags: labelTags
|
|
1305
1439
|
}, () => model.invoke([new _langchain_core_messages.SystemMessage(prompt ?? require_activityLabel.ACTIVITY_LABEL_PROMPT), new _langchain_core_messages.HumanMessage(userPrompt)], runtimeConfig));
|
|
1306
1440
|
const extractLabel = (response) => {
|
|
1307
1441
|
const content = response?.content;
|
|
@@ -1339,7 +1473,7 @@ var Run = class Run {
|
|
|
1339
1473
|
}
|
|
1340
1474
|
/**
|
|
1341
1475
|
* Generates one parent summary for two or more logical activities. The
|
|
1342
|
-
* summary model is traced as a dedicated activity-phase
|
|
1476
|
+
* summary model is traced as a dedicated activity-phase chain root in the
|
|
1343
1477
|
* conversation session, with the model callback recorded as its generation
|
|
1344
1478
|
* child. No session id means no phase trace, avoiding orphan observations.
|
|
1345
1479
|
*/
|
|
@@ -1417,8 +1551,7 @@ var Run = class Run {
|
|
|
1417
1551
|
...contributingAgentIds.length === 0 ? {} : { contributingAgentIds: contributingAgentIds.join(",") },
|
|
1418
1552
|
...closingTextPhase == null ? {} : { closingTextPhase }
|
|
1419
1553
|
};
|
|
1420
|
-
const
|
|
1421
|
-
const phaseTraceName = phaseChainOptions.runName ?? phaseRunName;
|
|
1554
|
+
const phaseTraceName = phaseChainOptions.runName ?? ACTIVITY_PHASE_TRACE_NAME;
|
|
1422
1555
|
const phaseTags = [
|
|
1423
1556
|
"librechat",
|
|
1424
1557
|
"activity-phase",
|