@librechat/agents 3.2.65 → 3.2.66

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 (56) hide show
  1. package/dist/cjs/graphs/Graph.cjs +15 -2
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/instrumentation.cjs +15 -3
  4. package/dist/cjs/instrumentation.cjs.map +1 -1
  5. package/dist/cjs/langfuseToolOutputTracing.cjs +1 -2
  6. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  7. package/dist/cjs/langfuseTraceShaping.cjs +51 -24
  8. package/dist/cjs/langfuseTraceShaping.cjs.map +1 -1
  9. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +8 -0
  10. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  11. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +8 -0
  12. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  13. package/dist/cjs/tools/BashExecutor.cjs +9 -8
  14. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  15. package/dist/cjs/tools/CodeExecutor.cjs +9 -7
  16. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  17. package/dist/esm/graphs/Graph.mjs +15 -2
  18. package/dist/esm/graphs/Graph.mjs.map +1 -1
  19. package/dist/esm/instrumentation.mjs +15 -3
  20. package/dist/esm/instrumentation.mjs.map +1 -1
  21. package/dist/esm/langfuseToolOutputTracing.mjs +1 -2
  22. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  23. package/dist/esm/langfuseTraceShaping.mjs +51 -24
  24. package/dist/esm/langfuseTraceShaping.mjs.map +1 -1
  25. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +8 -0
  26. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  27. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +8 -0
  28. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  29. package/dist/esm/tools/BashExecutor.mjs +9 -8
  30. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  31. package/dist/esm/tools/CodeExecutor.mjs +9 -7
  32. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  33. package/dist/types/graphs/Graph.d.ts +2 -0
  34. package/dist/types/langfuseTraceShaping.d.ts +12 -6
  35. package/dist/types/tools/BashExecutor.d.ts +7 -6
  36. package/dist/types/tools/CodeExecutor.d.ts +7 -5
  37. package/dist/types/types/graph.d.ts +10 -3
  38. package/package.json +1 -1
  39. package/src/graphs/Graph.ts +21 -3
  40. package/src/instrumentation.ts +20 -0
  41. package/src/langfuseToolOutputTracing.ts +2 -4
  42. package/src/langfuseTraceShaping.ts +73 -20
  43. package/src/llm/anthropic/utils/cross-provider-server-tools.test.ts +110 -0
  44. package/src/llm/anthropic/utils/message_inputs.ts +15 -0
  45. package/src/llm/bedrock/utils/cross-provider-server-tools.test.ts +122 -0
  46. package/src/llm/bedrock/utils/message_inputs.ts +13 -0
  47. package/src/specs/langfuse-instrumentation.test.ts +64 -0
  48. package/src/specs/langfuse-routing.integration.test.ts +49 -4
  49. package/src/specs/langfuse-tool-output-tracing.test.ts +5 -4
  50. package/src/specs/langfuse-trace-shaping.test.ts +80 -9
  51. package/src/specs/subagent.test.ts +180 -0
  52. package/src/tools/BashExecutor.ts +9 -8
  53. package/src/tools/CodeExecutor.ts +9 -7
  54. package/src/tools/__tests__/BashExecutor.test.ts +16 -5
  55. package/src/tools/__tests__/CodeExecutor.stateful.test.ts +17 -6
  56. package/src/types/graph.ts +10 -3
@@ -312,6 +312,186 @@ describe('Subagent Integration', () => {
312
312
  createWorkflowSpy.mockRestore();
313
313
  });
314
314
 
315
+ it('forwards event-driven tools through nested child graphs', async () => {
316
+ const originalCreateWorkflow = StandardGraph.prototype.createWorkflow;
317
+ const parentToolHandler = jest.fn(
318
+ (_event: string, rawData: unknown): void => {
319
+ const request = rawData as t.ToolExecuteBatchRequest;
320
+ request.resolve(
321
+ request.toolCalls.map((call) => ({
322
+ toolCallId: call.id,
323
+ status: 'success' as const,
324
+ content: `ran ${call.name}`,
325
+ }))
326
+ );
327
+ }
328
+ );
329
+ const parentUpdateHandler = jest.fn();
330
+ let specialistToolDefinitions: t.LCTool[] | undefined;
331
+ let forwardedToolResults: t.ToolExecuteResult[] | undefined;
332
+
333
+ const createWorkflowSpy = jest
334
+ .spyOn(StandardGraph.prototype, 'createWorkflow')
335
+ .mockImplementation(function (this: StandardGraph) {
336
+ const workflow = originalCreateWorkflow.call(this);
337
+ if (this.defaultAgentId === 'router') {
338
+ return {
339
+ invoke: jest.fn(async () => {
340
+ const routerContext = this.agentContexts.get('router');
341
+ const nestedTool = (
342
+ routerContext?.graphTools as t.GenericTool[] | undefined
343
+ )?.find(
344
+ (tool) => 'name' in tool && tool.name === Constants.SUBAGENT
345
+ );
346
+ if (nestedTool == null) {
347
+ throw new Error('Nested subagent tool was not created');
348
+ }
349
+ await nestedTool.invoke(
350
+ {
351
+ description: 'Use the event-driven lookup tool.',
352
+ subagent_type: 'specialist',
353
+ },
354
+ callerConfig
355
+ );
356
+ return { messages: [new AIMessage('router done')] };
357
+ }),
358
+ } as unknown as ReturnType<StandardGraph['createWorkflow']>;
359
+ }
360
+ if (this.defaultAgentId === 'specialist') {
361
+ specialistToolDefinitions =
362
+ this.agentContexts.get('specialist')?.toolDefinitions;
363
+ return {
364
+ invoke: jest.fn(async (_state, options) => {
365
+ const invokeOptions = options as
366
+ | { callbacks?: unknown[] }
367
+ | undefined;
368
+ const forwarder = (invokeOptions?.callbacks ?? [])[0] as
369
+ | {
370
+ handleCustomEvent?: (
371
+ eventName: string,
372
+ data: unknown,
373
+ runId: string
374
+ ) => Promise<void> | void;
375
+ }
376
+ | undefined;
377
+ if (forwarder?.handleCustomEvent != null) {
378
+ forwardedToolResults = await new Promise<t.ToolExecuteResult[]>(
379
+ (resolve, reject) => {
380
+ const request: t.ToolExecuteBatchRequest = {
381
+ toolCalls: [
382
+ { id: 'nested-call', name: 'mcp_lookup', args: {} },
383
+ ],
384
+ agentId: 'specialist',
385
+ resolve,
386
+ reject,
387
+ };
388
+ void forwarder.handleCustomEvent?.(
389
+ GraphEvents.ON_TOOL_EXECUTE,
390
+ request,
391
+ 'specialist-run'
392
+ );
393
+ }
394
+ );
395
+ await forwarder.handleCustomEvent(
396
+ GraphEvents.ON_RUN_STEP,
397
+ { id: 'specialist-step', type: 'tool_calls' },
398
+ 'specialist-run'
399
+ );
400
+ }
401
+ return { messages: [new AIMessage('specialist done')] };
402
+ }),
403
+ } as unknown as ReturnType<StandardGraph['createWorkflow']>;
404
+ }
405
+ return workflow;
406
+ });
407
+
408
+ const rootAgent: t.AgentInputs = {
409
+ agentId: 'root',
410
+ provider: Providers.OPENAI,
411
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
412
+ instructions: 'Delegate through the router.',
413
+ maxContextTokens: 8000,
414
+ maxSubagentDepth: 2,
415
+ subagentConfigs: [
416
+ {
417
+ type: 'router',
418
+ name: 'Router',
419
+ description: 'Routes work to specialists.',
420
+ allowNested: true,
421
+ agentInputs: {
422
+ agentId: 'router',
423
+ provider: Providers.OPENAI,
424
+ clientOptions: { modelName: 'gpt-4o-mini', apiKey: 'test-key' },
425
+ instructions: 'Delegate to the specialist.',
426
+ maxContextTokens: 8000,
427
+ subagentConfigs: [
428
+ {
429
+ type: 'specialist',
430
+ name: 'Specialist',
431
+ description: 'Uses an event-driven tool.',
432
+ agentInputs: {
433
+ agentId: 'specialist',
434
+ provider: Providers.OPENAI,
435
+ clientOptions: {
436
+ modelName: 'gpt-4o-mini',
437
+ apiKey: 'test-key',
438
+ },
439
+ instructions: 'Use the lookup tool.',
440
+ maxContextTokens: 8000,
441
+ toolDefinitions: [{ name: 'mcp_lookup' }],
442
+ },
443
+ },
444
+ ],
445
+ },
446
+ },
447
+ ],
448
+ };
449
+
450
+ try {
451
+ const run = await Run.create<t.IState>({
452
+ runId: `nested-event-tools-${Date.now()}`,
453
+ graphConfig: { type: 'standard', agents: [rootAgent] },
454
+ customHandlers: {
455
+ [GraphEvents.ON_TOOL_EXECUTE]: { handle: parentToolHandler },
456
+ [GraphEvents.ON_SUBAGENT_UPDATE]: {
457
+ handle: parentUpdateHandler,
458
+ },
459
+ },
460
+ returnContent: true,
461
+ skipCleanup: true,
462
+ });
463
+ const rootContext = (run.Graph as StandardGraph).agentContexts.get(
464
+ 'root'
465
+ );
466
+ const rootSubagentTool = (
467
+ rootContext?.graphTools as t.GenericTool[] | undefined
468
+ )?.find((tool) => 'name' in tool && tool.name === Constants.SUBAGENT);
469
+ expect(rootSubagentTool).toBeDefined();
470
+
471
+ await rootSubagentTool!.invoke(
472
+ { description: 'Route this task.', subagent_type: 'router' },
473
+ callerConfig
474
+ );
475
+
476
+ expect(specialistToolDefinitions).toEqual([{ name: 'mcp_lookup' }]);
477
+ expect(parentToolHandler).toHaveBeenCalledTimes(1);
478
+ expect(forwardedToolResults).toEqual([
479
+ {
480
+ toolCallId: 'nested-call',
481
+ status: 'success',
482
+ content: 'ran mcp_lookup',
483
+ },
484
+ ]);
485
+ const forwardedSubagentTypes = parentUpdateHandler.mock.calls.map(
486
+ ([, data]) => (data as t.SubagentUpdateEvent).subagentType
487
+ );
488
+ expect(forwardedSubagentTypes).toContain('router');
489
+ expect(forwardedSubagentTypes).not.toContain('specialist');
490
+ } finally {
491
+ createWorkflowSpy.mockRestore();
492
+ }
493
+ });
494
+
315
495
  it('should not create subagent tool when maxSubagentDepth is 0', async () => {
316
496
  const agentWithZeroDepth: t.AgentInputs = {
317
497
  ...createParentAgent(),
@@ -58,17 +58,18 @@ Usage:
58
58
  `.trim();
59
59
 
60
60
  /**
61
- * Bash statefulness is filesystem-tier: on a warm session the machine (files
62
- * including /tmp, installed packages, background processes) persists between
63
- * calls, but each call may start a fresh shell so shell variables and cwd
64
- * are NOT reliable, and the machine can be reset at any time. Only /mnt/data
65
- * is durable.
61
+ * Bash statefulness is filesystem-tier and scoped to `/mnt/data`. The machine
62
+ * is warm across calls, but each call runs in a fresh sandbox (new process
63
+ * tree + private /tmp), so background processes are reaped when the call ends
64
+ * and anything written outside /mnt/data is discarded. The note must not
65
+ * promise otherwise: a model told background processes survive will start a
66
+ * server in one call and assume it is listening in the next.
66
67
  */
67
68
  export const STATEFUL_BASH_NOTE =
68
- 'Session state (best-effort): commands in this conversation usually run on the same machine, so files (including /tmp), installed packages, and running background processes from earlier calls typically persist. Each call may still start a fresh shell do not rely on shell variables or the working directory carrying over and the machine may be reset at any time. Only /mnt/data is durable.';
69
+ 'Session state: commands in this conversation run on the same warm machine, so files written to /mnt/data persist between calls. Each call runs in a fresh, isolated sandbox: shell variables, the working directory, /tmp, and background processes do NOT survive after the call returns a process started in one call is terminated when that call ends. Only /mnt/data is durable (the machine itself may also be reset at any time).';
69
70
 
70
71
  export const StatefulBashExecutionToolDescription = `
71
- Runs bash commands and returns stdout/stderr output from a session-based execution environment, similar to a long-running machine.
72
+ Runs bash commands and returns stdout/stderr output. Commands in this conversation share one warm machine with a persistent /mnt/data, but each command runs in its own isolated sandbox (not a persistent shell session).
72
73
 
73
74
  ${STATEFUL_BASH_NOTE}
74
75
 
@@ -125,7 +126,7 @@ export function buildBashExecutionToolDescription(options?: {
125
126
  const STATELESS_BASH_PARAM_NOTE =
126
127
  'The environment is stateless; variables and state don\'t persist between executions.';
127
128
  const STATEFUL_BASH_PARAM_NOTE =
128
- 'Files, installed packages, and background processes usually persist between calls, but each call may start a fresh shell (do not rely on shell variables or cwd) and the machine may reset. Only /mnt/data is durable.';
129
+ 'Files written to /mnt/data persist between calls on the same warm machine. Each call runs in a fresh sandbox: shell variables, cwd, /tmp, and background processes do NOT survive the call. Only /mnt/data is durable.';
129
130
 
130
131
  export function buildBashExecutionToolSchema(opts?: {
131
132
  statefulSessions?: boolean;
@@ -150,16 +150,18 @@ Usage:
150
150
  `.trim();
151
151
 
152
152
  /**
153
- * Best-effort statefulness note. Deliberately hedged: warm reuse is an
154
- * optimization, not a guarantee (the runtime may be reset on idle timeout,
155
- * eviction, or the 8h VM lifetime), so the model must never depend on carried
156
- * state for correctness and must persist anything durable to /mnt/data.
153
+ * Statefulness here is FILESYSTEM-tier, not runtime-tier. Executions in a
154
+ * session reuse one warm machine, so `/mnt/data` carries across calls but
155
+ * every execution is a brand-new interpreter process in a fresh sandbox, so
156
+ * variables and imports never survive. The note must not imply otherwise: a
157
+ * model told its in-memory state persists writes `df = ...` in one call and
158
+ * `df.head()` in the next, then hits a NameError it was told to treat as rare.
157
159
  */
158
160
  export const STATEFUL_ENV_NOTE =
159
- 'Session state (best-effort): consecutive executions in this conversation usually share one runtime, so variables, imports, and in-memory data from earlier successful calls are typically still available. The runtime may be reset at any time, so treat carried-over state as an optimization, never a guarantee. Anything that must survive MUST be written to /mnt/data. If a NameError/ImportError signals lost state, re-run the needed setup and continue.';
161
+ 'Session state: executions in this conversation run on the same warm machine, so files persist between calls but each execution is a NEW process. Variables, imports, and in-memory data NEVER carry over: every call must re-import and rebuild the state it needs. Only /mnt/data is durable (the machine itself may also be reset at any time), so write anything that must survive there and read it back next call.';
160
162
 
161
163
  export const StatefulCodeExecutionToolDescription = `
162
- Runs code and returns stdout/stderr output from a session-based execution environment, similar to a long-running command-line session.
164
+ Runs code and returns stdout/stderr output. Executions in this conversation share one warm machine with a persistent /mnt/data, but each execution runs as a separate process (not a notebook-style kernel).
163
165
 
164
166
  ${STATEFUL_ENV_NOTE}
165
167
 
@@ -181,7 +183,7 @@ export function buildCodeExecutionToolDescription(opts?: {
181
183
  const STATELESS_CODE_PARAM_NOTE =
182
184
  'The environment is stateless; variables and imports don\'t persist between executions.';
183
185
  const STATEFUL_CODE_PARAM_NOTE =
184
- 'Executions in this conversation usually share one runtime: variables and imports from prior successful calls are typically still defined, but the runtime may reset between calls. Rebuild state on NameError/ImportError; persist anything important to /mnt/data.';
186
+ 'Executions in this conversation share one warm machine, so files written to /mnt/data persist between calls. Each execution is a new process: variables and imports do NOT carry over re-import and reload from /mnt/data every call.';
185
187
 
186
188
  export function buildCodeExecutionToolSchema(opts?: {
187
189
  statefulSessions?: boolean;
@@ -65,13 +65,24 @@ describe('buildBashExecutionToolDescription', () => {
65
65
  ).toBe(StatefulBashExecutionToolDescription);
66
66
  });
67
67
 
68
- it('hedges: usually-persists but may-reset, and only /mnt/data is durable', () => {
68
+ /* Filesystem-tier only: each call runs in a fresh sandbox (new process
69
+ * tree + private /tmp), so background processes are reaped and non-
70
+ * /mnt/data writes are discarded. The description must not promise
71
+ * otherwise. */
72
+ it('promises /mnt/data persistence WITHOUT promising surviving processes or /tmp', () => {
69
73
  const d = StatefulBashExecutionToolDescription;
70
- expect(d).toContain('usually');
71
- expect(d).toContain('may be reset');
74
+ expect(d).toContain('same warm machine');
72
75
  expect(d).toContain('Only /mnt/data is durable');
73
- /* filesystem-tier, not shell-variable-tier */
74
- expect(d).toContain('do not rely on shell variables');
76
+ expect(d).toContain('background processes do NOT survive');
77
+ expect(d).toContain('/tmp');
78
+ });
79
+
80
+ it('never claims /tmp or background processes persist between calls', () => {
81
+ const d = StatefulBashExecutionToolDescription;
82
+ expect(d).not.toContain('files (including /tmp)');
83
+ expect(d).not.toContain(
84
+ 'background processes from earlier calls typically persist'
85
+ );
75
86
  });
76
87
 
77
88
  it('keeps the artifact-path guidance in both variants', () => {
@@ -41,22 +41,33 @@ describe('CodeExecutor stateful description', () => {
41
41
  );
42
42
  });
43
43
 
44
- it('hedges the stateful wording and keeps /mnt/data as the durable store', () => {
44
+ /* Statefulness is filesystem-tier only: the machine is warm across calls,
45
+ * but every execution is a new interpreter process, so in-memory state never
46
+ * carries over. The description must not imply a notebook-style kernel. */
47
+ it('promises filesystem persistence WITHOUT promising a shared runtime', () => {
45
48
  const d = StatefulCodeExecutionToolDescription;
46
- expect(d).toContain('usually share one runtime');
47
- expect(d).toContain('may be reset at any time');
48
- expect(d).toContain('MUST be written to /mnt/data');
49
+ expect(d).toContain('same warm machine');
50
+ expect(d).toContain('/mnt/data');
51
+ expect(d).toContain('NEW process');
52
+ expect(d).toContain('NEVER carry over');
49
53
  expect(d).toContain(CODE_ARTIFACT_PATH_GUIDANCE);
50
54
  });
51
55
 
56
+ it('never claims variables/imports survive between executions', () => {
57
+ const d = StatefulCodeExecutionToolDescription;
58
+ expect(d).not.toContain('share one runtime');
59
+ expect(d).not.toContain('typically still available');
60
+ });
61
+
52
62
  it('adjusts the code-param note per mode', () => {
53
63
  const stateless =
54
64
  buildCodeExecutionToolSchema().properties.code.description;
55
65
  const stateful = buildCodeExecutionToolSchema({ statefulSessions: true })
56
66
  .properties.code.description;
57
67
  expect(stateless).toContain('variables and imports don\'t persist');
58
- expect(stateful).toContain('typically still defined');
59
- expect(stateful).toContain('may reset between calls');
68
+ expect(stateful).toContain('do NOT carry over');
69
+ expect(stateful).toContain('/mnt/data');
70
+ expect(stateful).not.toContain('typically still defined');
60
71
  });
61
72
  });
62
73
 
@@ -534,9 +534,9 @@ export type LangfuseToolOutputTracingConfig = {
534
534
 
535
535
  export type LangfuseToolNodeTracingConfig = {
536
536
  /**
537
- * Overrides ToolNode callback tracing. ToolNode spans are exported by the
538
- * env-backed Langfuse callback, so this only enables tracing when that
539
- * callback is configured.
537
+ * Opts into the internal ToolNode batch observation. Graph tool-dispatch
538
+ * and individual tool observations are exported without this wrapper, so
539
+ * the default is false to avoid a redundant hierarchy level.
540
540
  */
541
541
  enabled?: boolean;
542
542
  };
@@ -546,6 +546,13 @@ export interface LangfuseConfig {
546
546
  publicKey?: string;
547
547
  secretKey?: string;
548
548
  baseUrl?: string;
549
+ /**
550
+ * Environment identifier attached to exported traces (Langfuse
551
+ * `environment`). When unset, falls back to `LANGFUSE_TRACING_ENVIRONMENT`
552
+ * then `NODE_ENV`, so production traces are not collapsed under the
553
+ * `default` environment.
554
+ */
555
+ environment?: string;
549
556
  metadata?: Record<string, string | number | boolean | null | undefined>;
550
557
  /**
551
558
  * Internal OTLP span attributes to attach to Langfuse observations before