illuma-agents 1.0.37 → 1.0.39

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 (139) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +112 -14
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +5 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +148 -8
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +128 -61
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +22 -7
  12. package/dist/cjs/main.cjs.map +1 -1
  13. package/dist/cjs/messages/cache.cjs +140 -46
  14. package/dist/cjs/messages/cache.cjs.map +1 -1
  15. package/dist/cjs/messages/core.cjs +1 -1
  16. package/dist/cjs/messages/core.cjs.map +1 -1
  17. package/dist/cjs/messages/tools.cjs +2 -2
  18. package/dist/cjs/messages/tools.cjs.map +1 -1
  19. package/dist/cjs/schemas/validate.cjs +173 -0
  20. package/dist/cjs/schemas/validate.cjs.map +1 -0
  21. package/dist/cjs/stream.cjs +4 -2
  22. package/dist/cjs/stream.cjs.map +1 -1
  23. package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
  24. package/dist/cjs/tools/CodeExecutor.cjs +22 -21
  25. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  26. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
  27. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  28. package/dist/cjs/tools/ToolNode.cjs +101 -2
  29. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  30. package/dist/cjs/tools/ToolSearch.cjs +862 -0
  31. package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
  32. package/dist/esm/agents/AgentContext.mjs +112 -14
  33. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  34. package/dist/esm/common/enum.mjs +5 -1
  35. package/dist/esm/common/enum.mjs.map +1 -1
  36. package/dist/esm/graphs/Graph.mjs +149 -9
  37. package/dist/esm/graphs/Graph.mjs.map +1 -1
  38. package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
  39. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  40. package/dist/esm/llm/bedrock/index.mjs +127 -60
  41. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  42. package/dist/esm/main.mjs +2 -1
  43. package/dist/esm/main.mjs.map +1 -1
  44. package/dist/esm/messages/cache.mjs +140 -46
  45. package/dist/esm/messages/cache.mjs.map +1 -1
  46. package/dist/esm/messages/core.mjs +1 -1
  47. package/dist/esm/messages/core.mjs.map +1 -1
  48. package/dist/esm/messages/tools.mjs +2 -2
  49. package/dist/esm/messages/tools.mjs.map +1 -1
  50. package/dist/esm/schemas/validate.mjs +167 -0
  51. package/dist/esm/schemas/validate.mjs.map +1 -0
  52. package/dist/esm/stream.mjs +4 -2
  53. package/dist/esm/stream.mjs.map +1 -1
  54. package/dist/esm/tools/BrowserTools.mjs.map +1 -1
  55. package/dist/esm/tools/CodeExecutor.mjs +22 -21
  56. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  57. package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
  58. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  59. package/dist/esm/tools/ToolNode.mjs +102 -3
  60. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  61. package/dist/esm/tools/ToolSearch.mjs +827 -0
  62. package/dist/esm/tools/ToolSearch.mjs.map +1 -0
  63. package/dist/types/agents/AgentContext.d.ts +51 -1
  64. package/dist/types/common/enum.d.ts +6 -2
  65. package/dist/types/graphs/Graph.d.ts +12 -0
  66. package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
  67. package/dist/types/index.d.ts +2 -1
  68. package/dist/types/llm/bedrock/index.d.ts +89 -11
  69. package/dist/types/llm/bedrock/types.d.ts +27 -0
  70. package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
  71. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
  72. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
  73. package/dist/types/messages/cache.d.ts +4 -1
  74. package/dist/types/schemas/index.d.ts +1 -0
  75. package/dist/types/schemas/validate.d.ts +36 -0
  76. package/dist/types/tools/CodeExecutor.d.ts +0 -3
  77. package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
  78. package/dist/types/tools/ToolNode.d.ts +3 -1
  79. package/dist/types/tools/ToolSearch.d.ts +148 -0
  80. package/dist/types/types/graph.d.ts +71 -0
  81. package/dist/types/types/llm.d.ts +3 -1
  82. package/dist/types/types/tools.d.ts +42 -2
  83. package/package.json +13 -6
  84. package/src/agents/AgentContext.test.ts +312 -0
  85. package/src/agents/AgentContext.ts +144 -16
  86. package/src/common/enum.ts +5 -1
  87. package/src/graphs/Graph.ts +214 -13
  88. package/src/graphs/MultiAgentGraph.ts +350 -13
  89. package/src/index.ts +4 -1
  90. package/src/llm/bedrock/index.ts +221 -99
  91. package/src/llm/bedrock/llm.spec.ts +616 -0
  92. package/src/llm/bedrock/types.ts +51 -0
  93. package/src/llm/bedrock/utils/index.ts +18 -0
  94. package/src/llm/bedrock/utils/message_inputs.ts +563 -0
  95. package/src/llm/bedrock/utils/message_outputs.ts +310 -0
  96. package/src/messages/__tests__/tools.test.ts +21 -21
  97. package/src/messages/cache.test.ts +304 -0
  98. package/src/messages/cache.ts +183 -53
  99. package/src/messages/core.ts +1 -1
  100. package/src/messages/tools.ts +2 -2
  101. package/src/schemas/index.ts +2 -0
  102. package/src/schemas/validate.test.ts +358 -0
  103. package/src/schemas/validate.ts +238 -0
  104. package/src/scripts/caching.ts +27 -19
  105. package/src/scripts/code_exec_files.ts +58 -15
  106. package/src/scripts/code_exec_multi_session.ts +241 -0
  107. package/src/scripts/code_exec_session.ts +282 -0
  108. package/src/scripts/multi-agent-conditional.ts +1 -0
  109. package/src/scripts/multi-agent-supervisor.ts +1 -0
  110. package/src/scripts/programmatic_exec_agent.ts +4 -4
  111. package/src/scripts/test-handoff-preamble.ts +277 -0
  112. package/src/scripts/test-parallel-handoffs.ts +291 -0
  113. package/src/scripts/test-tools-before-handoff.ts +8 -4
  114. package/src/scripts/test_code_api.ts +361 -0
  115. package/src/scripts/thinking-bedrock.ts +159 -0
  116. package/src/scripts/thinking.ts +39 -18
  117. package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
  118. package/src/scripts/tools.ts +7 -3
  119. package/src/specs/cache.simple.test.ts +396 -0
  120. package/src/stream.ts +4 -2
  121. package/src/tools/BrowserTools.ts +39 -17
  122. package/src/tools/CodeExecutor.ts +26 -23
  123. package/src/tools/ProgrammaticToolCalling.ts +18 -14
  124. package/src/tools/ToolNode.ts +114 -1
  125. package/src/tools/ToolSearch.ts +1041 -0
  126. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
  127. package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
  128. package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
  129. package/src/types/graph.test.ts +183 -0
  130. package/src/types/graph.ts +73 -0
  131. package/src/types/llm.ts +3 -1
  132. package/src/types/tools.ts +51 -2
  133. package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
  134. package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
  135. package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
  136. package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
  137. package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
  138. package/src/tools/ToolSearchRegex.ts +0 -535
  139. package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
@@ -1,7 +1,11 @@
1
1
  // src/scripts/test-prompt-caching.ts
2
2
  import { config } from 'dotenv';
3
3
  config();
4
- import { HumanMessage, SystemMessage, BaseMessage } from '@langchain/core/messages';
4
+ import {
5
+ HumanMessage,
6
+ SystemMessage,
7
+ BaseMessage,
8
+ } from '@langchain/core/messages';
5
9
  import type { UsageMetadata } from '@langchain/core/messages';
6
10
  import type * as t from '@/types';
7
11
  import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
@@ -11,7 +15,7 @@ import { getLLMConfig } from '@/utils/llmConfig';
11
15
  import { getArgs } from '@/scripts/args';
12
16
  import { Run } from '@/run';
13
17
 
14
- const CACHED_TEXT = `Ahoy there, me hearties! This be a grand tale o' the mighty prompt cachin' treasure map, a secret technique used by the wise Anthropic seafarers to stash away vast hordes o' text booty on their mystical servers! Arrr, 'tis a pirate's dream indeed - no need to haul the same heavy chest o' gold doubloons across the vast digital ocean with every message! When ye mark yer precious cargo with the secret flag 'cache_control: { type: \"ephemeral\" }', the text be safely buried on their distant shores, ready for plunderin' again without the weight slowin' down yer ship! The wise pirates at Anthropic introduced this magical scroll in the summer o' 2024, markin' it with the mysterious insignia 'anthropic-beta: prompt-caching-2024-07-31' that must be flown high on yer vessel's headers. This crafty script be testin' the waters of this new treasure map system, sendin' out three separate voyages across the AI seas: first to bury the treasure, second to dig it up again without payin' the full toll, and third to see if the map still leads to gold after the sands o' time have shifted (about thirty seconds o' waitin', which be an eternity for an impatient buccaneer!). The great advantage for a scurvy pirate captain is clear as Caribbean waters - ye can load up yer vessel with all manner o' reference scrolls, ancient tomes, and navigational charts without weighin' down each and every message ye send to port! This be savin' ye countless tokens, which as any seafarin' AI wrangler knows, be as precious as Spanish gold. The cached text could contain the full history o' the Seven Seas, detailed maps o' every port from Tortuga to Singapore, or the complete collection o' pirate shanties ever sung by drunken sailors under the light o' the silvery moon. When properly implemented, this mighty cachin' system keeps all that knowledge ready at hand without the Claude kraken needin' to process it anew with each passin' breeze. By Blackbeard's beard, 'tis a revolution in how we manage our conversational ships! The script be employin' the finest LangChain riggin' and custom-carved event handlers to properly track the treasure as it flows back and forth. If ye be successful in yer implementation, ye should witness the miracle o' significantly reduced token counts in yer usage metrics, faster responses from the AI oracle, and the ability to maintain vast knowledge without payin' the full price each time! So hoist the Jolly Roger, load yer pistols with API keys, and set sail on the grand adventure o' prompt cachin'! May the winds o' efficient token usage fill yer sails, and may ye never have to pay full price for passin' the same mammoth context to Claude again! Remember, a clever pirate only pays for their tokens once, then lets the cache do the heavy liftin'! YARRR! This file also contains the secrets of the legendary Pirate Code, passed down through generations of seafarers since the Golden Age of Piracy. It includes detailed accounts of famous pirate captains like Blackbeard, Calico Jack, Anne Bonny, and Mary Read, along with their most profitable plundering routes and techniques for capturing merchant vessels. The text chronicles the exact locations of at least seventeen buried treasures across the Caribbean, complete with riddles and map coordinates that only a true pirate could decipher. There are sections dedicated to ship maintenance, including how to properly seal a leaking hull during battle and the best methods for keeping your cannons in prime firing condition even in humid tropical conditions. The document contains an extensive glossary of pirate terminology, from 'avast' to 'Yellow Jack,' ensuring any landlubber can speak like a seasoned salt with enough study. There's a comprehensive guide to navigating by the stars without modern instruments, perfect for when your GPS fails in the middle of a daring escape. The cache also includes detailed recipes for grog, hardtack that won't break your teeth, and how to keep citrus fruits fresh to prevent scurvy during long voyages. The legendary Black Spot ritual is described in terrifying detail, along with other pirate superstitions and their origins in maritime folklore. A section on pirate governance explains the democratic nature of most pirate ships, how booty was divided fairly, and how captains were elected and deposed when necessary. The file even contains sheet music for dozens of sea shanties, with notes on when each should be sung for maximum crew morale during different sailing conditions. All of this knowledge is wrapped in colorful pirate dialect that would make any AI assistant respond with appropriate 'arghs' and 'avasts' when properly prompted!`
18
+ const CACHED_TEXT = `Ahoy there, me hearties! This be a grand tale o' the mighty prompt cachin' treasure map, a secret technique used by the wise Anthropic seafarers to stash away vast hordes o' text booty on their mystical servers! Arrr, 'tis a pirate's dream indeed - no need to haul the same heavy chest o' gold doubloons across the vast digital ocean with every message! When ye mark yer precious cargo with the secret flag 'cache_control: { type: \"ephemeral\" }', the text be safely buried on their distant shores, ready for plunderin' again without the weight slowin' down yer ship! The wise pirates at Anthropic introduced this magical scroll in the summer o' 2024, markin' it with the mysterious insignia 'anthropic-beta: prompt-caching-2024-07-31' that must be flown high on yer vessel's headers. This crafty script be testin' the waters of this new treasure map system, sendin' out three separate voyages across the AI seas: first to bury the treasure, second to dig it up again without payin' the full toll, and third to see if the map still leads to gold after the sands o' time have shifted (about thirty seconds o' waitin', which be an eternity for an impatient buccaneer!). The great advantage for a scurvy pirate captain is clear as Caribbean waters - ye can load up yer vessel with all manner o' reference scrolls, ancient tomes, and navigational charts without weighin' down each and every message ye send to port! This be savin' ye countless tokens, which as any seafarin' AI wrangler knows, be as precious as Spanish gold. The cached text could contain the full history o' the Seven Seas, detailed maps o' every port from Tortuga to Singapore, or the complete collection o' pirate shanties ever sung by drunken sailors under the light o' the silvery moon. When properly implemented, this mighty cachin' system keeps all that knowledge ready at hand without the Claude kraken needin' to process it anew with each passin' breeze. By Blackbeard's beard, 'tis a revolution in how we manage our conversational ships! The script be employin' the finest LangChain riggin' and custom-carved event handlers to properly track the treasure as it flows back and forth. If ye be successful in yer implementation, ye should witness the miracle o' significantly reduced token counts in yer usage metrics, faster responses from the AI oracle, and the ability to maintain vast knowledge without payin' the full price each time! So hoist the Jolly Roger, load yer pistols with API keys, and set sail on the grand adventure o' prompt cachin'! May the winds o' efficient token usage fill yer sails, and may ye never have to pay full price for passin' the same mammoth context to Claude again! Remember, a clever pirate only pays for their tokens once, then lets the cache do the heavy liftin'! YARRR! This file also contains the secrets of the legendary Pirate Code, passed down through generations of seafarers since the Golden Age of Piracy. It includes detailed accounts of famous pirate captains like Blackbeard, Calico Jack, Anne Bonny, and Mary Read, along with their most profitable plundering routes and techniques for capturing merchant vessels. The text chronicles the exact locations of at least seventeen buried treasures across the Caribbean, complete with riddles and map coordinates that only a true pirate could decipher. There are sections dedicated to ship maintenance, including how to properly seal a leaking hull during battle and the best methods for keeping your cannons in prime firing condition even in humid tropical conditions. The document contains an extensive glossary of pirate terminology, from 'avast' to 'Yellow Jack,' ensuring any landlubber can speak like a seasoned salt with enough study. There's a comprehensive guide to navigating by the stars without modern instruments, perfect for when your GPS fails in the middle of a daring escape. The cache also includes detailed recipes for grog, hardtack that won't break your teeth, and how to keep citrus fruits fresh to prevent scurvy during long voyages. The legendary Black Spot ritual is described in terrifying detail, along with other pirate superstitions and their origins in maritime folklore. A section on pirate governance explains the democratic nature of most pirate ships, how booty was divided fairly, and how captains were elected and deposed when necessary. The file even contains sheet music for dozens of sea shanties, with notes on when each should be sung for maximum crew morale during different sailing conditions. All of this knowledge is wrapped in colorful pirate dialect that would make any AI assistant respond with appropriate 'arghs' and 'avasts' when properly prompted!`;
15
19
 
16
20
  const conversationHistory: BaseMessage[] = [];
17
21
  let _contentParts: t.MessageContentComplex[] = [];
@@ -23,7 +27,7 @@ async function testPromptCaching(): Promise<void> {
23
27
  ${CACHED_TEXT}`;
24
28
  const { contentParts, aggregateContent } = createContentAggregator();
25
29
  _contentParts = contentParts as t.MessageContentComplex[];
26
-
30
+
27
31
  // Set up event handlers
28
32
  const customHandlers = {
29
33
  [GraphEvents.TOOL_END]: new ToolEndHandler(),
@@ -33,29 +37,33 @@ ${CACHED_TEXT}`;
33
37
  [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
34
38
  // Additional handlers for tracking usage metrics
35
39
  [GraphEvents.ON_RUN_STEP_COMPLETED]: {
36
- handle: (event: GraphEvents.ON_RUN_STEP_COMPLETED, data: t.StreamEventData): void => {
40
+ handle: (
41
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
42
+ data: t.StreamEventData
43
+ ): void => {
37
44
  console.log('====== ON_RUN_STEP_COMPLETED ======');
38
- aggregateContent({ event, data: data as unknown as { result: t.ToolEndEvent } });
39
- }
45
+ aggregateContent({
46
+ event,
47
+ data: data as unknown as { result: t.ToolEndEvent },
48
+ });
49
+ },
40
50
  },
41
51
  };
42
52
 
43
- const baseLlmConfig: t.LLMConfig & t.AnthropicClientOptions = getLLMConfig(Providers.ANTHROPIC);
44
-
53
+ const baseLlmConfig: t.LLMConfig & t.AnthropicClientOptions = getLLMConfig(
54
+ Providers.ANTHROPIC
55
+ );
56
+
45
57
  if (baseLlmConfig.provider !== 'anthropic') {
46
- console.error('This test requires Anthropic as the LLM provider. Please specify provider=anthropic');
58
+ console.error(
59
+ 'This test requires Anthropic as the LLM provider. Please specify provider=anthropic'
60
+ );
47
61
  process.exit(1);
48
62
  }
49
-
63
+
50
64
  const llmConfig = {
51
65
  ...baseLlmConfig,
52
- clientOptions: {
53
- ...baseLlmConfig.clientOptions,
54
- defaultHeaders: {
55
- ...baseLlmConfig.clientOptions?.defaultHeaders,
56
- "anthropic-beta": "prompt-caching-2024-07-31",
57
- }
58
- }
66
+ promptCache: true,
59
67
  };
60
68
 
61
69
  const run = await Run.create<t.IState>({
@@ -94,7 +102,7 @@ ${CACHED_TEXT}`;
94
102
  console.log('\n\nTest 2: Second request (should use cache)');
95
103
  const userMessage2 = `Summarize the key concepts from the context information.`;
96
104
  conversationHistory.push(new HumanMessage(userMessage2));
97
-
105
+
98
106
  console.log('Running second query to use cache...');
99
107
  const secondInputs = { messages: [...conversationHistory] };
100
108
  await run.processStream(secondInputs, config);
@@ -121,4 +129,4 @@ testPromptCaching().catch((err) => {
121
129
  console.log('Content parts:');
122
130
  console.dir(_contentParts, { depth: null });
123
131
  process.exit(1);
124
- });
132
+ });
@@ -1,4 +1,11 @@
1
- // src/scripts/cli.ts
1
+ // src/scripts/code_exec_files.ts
2
+ /**
3
+ * Tests automatic session tracking for code execution file persistence.
4
+ * Files created in one execution are automatically available in subsequent executions
5
+ * without the LLM needing to track or pass session_id.
6
+ *
7
+ * Run with: npm run code_exec_files
8
+ */
2
9
  import { config } from 'dotenv';
3
10
  config();
4
11
  import { HumanMessage, BaseMessage } from '@langchain/core/messages';
@@ -12,12 +19,39 @@ import {
12
19
  } from '@/events';
13
20
  import { getLLMConfig } from '@/utils/llmConfig';
14
21
  import { getArgs } from '@/scripts/args';
15
- import { GraphEvents } from '@/common';
22
+ import { Constants, GraphEvents } from '@/common';
16
23
  import { Run } from '@/run';
17
24
  import { createCodeExecutionTool } from '@/tools/CodeExecutor';
18
25
 
19
26
  const conversationHistory: BaseMessage[] = [];
20
27
 
28
+ /**
29
+ * Prints session context from the graph for debugging
30
+ */
31
+ function printSessionContext(run: Run<t.IState>): void {
32
+ const graph = run.Graph;
33
+ if (!graph) {
34
+ console.log('[Session] No graph available');
35
+ return;
36
+ }
37
+
38
+ const session = graph.sessions.get(Constants.EXECUTE_CODE) as
39
+ | t.CodeSessionContext
40
+ | undefined;
41
+
42
+ if (!session) {
43
+ console.log('[Session] No session context stored yet');
44
+ return;
45
+ }
46
+
47
+ console.log('[Session] Current session context:');
48
+ console.log(` - session_id: ${session.session_id}`);
49
+ console.log(` - files: ${JSON.stringify(session.files, null, 2)}`);
50
+ console.log(
51
+ ` - lastUpdated: ${new Date(session.lastUpdated).toISOString()}`
52
+ );
53
+ }
54
+
21
55
  async function testCodeExecution(): Promise<void> {
22
56
  const { userName, location, provider, currentDate } = await getArgs();
23
57
  const { contentParts, aggregateContent } = createContentAggregator();
@@ -72,7 +106,7 @@ async function testCodeExecution(): Promise<void> {
72
106
  handle: (
73
107
  _event: string,
74
108
  data: t.StreamEventData,
75
- metadata?: Record<string, unknown>
109
+ _metadata?: Record<string, unknown>
76
110
  ): void => {
77
111
  console.log('====== TOOL_START ======');
78
112
  console.dir(data, { depth: null });
@@ -96,7 +130,7 @@ async function testCodeExecution(): Promise<void> {
96
130
  customHandlers,
97
131
  });
98
132
 
99
- const config: Partial<RunnableConfig> & {
133
+ const streamConfig: Partial<RunnableConfig> & {
100
134
  version: 'v1' | 'v2';
101
135
  run_id?: string;
102
136
  streamMode: string;
@@ -107,10 +141,12 @@ async function testCodeExecution(): Promise<void> {
107
141
  },
108
142
  streamMode: 'values',
109
143
  version: 'v2' as const,
110
- // recursionLimit: 3,
111
144
  };
112
145
 
113
- console.log('Test 1: Create Project Plan');
146
+ console.log('\n========== Test 1: Create Project Plan ==========\n');
147
+ console.log(
148
+ 'Creating initial file - this establishes the session context.\n'
149
+ );
114
150
 
115
151
  const userMessage1 = `
116
152
  Hi ${userName} here. We are testing your file capabilities.
@@ -125,36 +161,43 @@ async function testCodeExecution(): Promise<void> {
125
161
  let inputs = {
126
162
  messages: conversationHistory,
127
163
  };
128
- const finalContentParts1 = await run.processStream(inputs, config);
164
+ await run.processStream(inputs, streamConfig);
129
165
  const finalMessages1 = run.getRunMessages();
130
166
  if (finalMessages1) {
131
167
  conversationHistory.push(...finalMessages1);
132
168
  }
133
- console.log('\n\n====================\n\n');
169
+
170
+ console.log('\n\n========== Session Context After Test 1 ==========\n');
171
+ printSessionContext(run);
134
172
  console.dir(contentParts, { depth: null });
135
173
 
136
- console.log('Test 2: Edit Project Plan');
174
+ console.log('\n========== Test 2: Edit Project Plan ==========\n');
175
+ console.log(
176
+ 'Editing the file from Test 1 - session_id is automatically injected.\n'
177
+ );
137
178
 
138
179
  const userMessage2 = `
139
180
  Thanks for creating the project plan. Now I'd like you to edit the same plan to:
140
181
 
141
- 1. Add a new section called "Technology Stack" that contains: "The technology stack for this project includes the following technologies" and nothing more.
142
-
182
+ 1. Read the existing project_plan.txt file
183
+ 2. Add a new section called "Technology Stack" that contains: "The technology stack for this project includes the following technologies" and nothing more.
184
+ 3. Save this as a new file called "project_plan_v2.txt" (remember files are read-only)
185
+ 4. Print the contents of both files to verify
143
186
  `;
144
187
 
145
- // Make sure to pass the file ID of the previous file you created and explicitly duplicate or rename the file in your code so we can then access it. Also print the contents of the new file to ensure we did what we wanted.`;
146
-
147
188
  conversationHistory.push(new HumanMessage(userMessage2));
148
189
 
149
190
  inputs = {
150
191
  messages: conversationHistory,
151
192
  };
152
- const finalContentParts2 = await run.processStream(inputs, config);
193
+ await run.processStream(inputs, streamConfig);
153
194
  const finalMessages2 = run.getRunMessages();
154
195
  if (finalMessages2) {
155
196
  conversationHistory.push(...finalMessages2);
156
197
  }
157
- console.log('\n\n====================\n\n');
198
+
199
+ console.log('\n\n========== Session Context After Test 2 ==========\n');
200
+ printSessionContext(run);
158
201
  console.dir(contentParts, { depth: null });
159
202
 
160
203
  const { handleLLMEnd, collected } = createMetadataAggregator();
@@ -0,0 +1,241 @@
1
+ // src/scripts/code_exec_multi_session.ts
2
+ /**
3
+ * Tests multi-session file tracking for code execution.
4
+ * Verifies that:
5
+ * 1. Files from multiple executions are accumulated
6
+ * 2. Each file tracks its source session_id
7
+ * 3. Edited/recreated files replace older versions (latest preferred)
8
+ *
9
+ * Run with: npm run code_exec_multi_session
10
+ */
11
+ import { config } from 'dotenv';
12
+ config();
13
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
14
+ import type { RunnableConfig } from '@langchain/core/runnables';
15
+ import type * as t from '@/types';
16
+ import { ChatModelStreamHandler } from '@/stream';
17
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
18
+ import { getLLMConfig } from '@/utils/llmConfig';
19
+ import { getArgs } from '@/scripts/args';
20
+ import { Constants, GraphEvents } from '@/common';
21
+ import { Run } from '@/run';
22
+ import { createCodeExecutionTool } from '@/tools/CodeExecutor';
23
+
24
+ const conversationHistory: BaseMessage[] = [];
25
+
26
+ /**
27
+ * Prints session context from the graph
28
+ */
29
+ function printSessionContext(run: Run<t.IState>, label: string): void {
30
+ const graph = run.Graph;
31
+ if (!graph) {
32
+ console.log(`\n[${label}] No graph available`);
33
+ return;
34
+ }
35
+
36
+ const session = graph.sessions.get(Constants.EXECUTE_CODE) as
37
+ | t.CodeSessionContext
38
+ | undefined;
39
+
40
+ console.log(`\n========== ${label} ==========`);
41
+ if (!session) {
42
+ console.log(' No session context stored yet');
43
+ return;
44
+ }
45
+
46
+ console.log(` Latest session_id: ${session.session_id}`);
47
+ console.log(` Files tracked: ${session.files.length}`);
48
+ for (const file of session.files) {
49
+ console.log(` - ${file.name} (session: ${file.session_id})`);
50
+ }
51
+ }
52
+
53
+ async function testMultiSessionFiles(): Promise<void> {
54
+ const { provider } = await getArgs();
55
+
56
+ const customHandlers = {
57
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
58
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
59
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
60
+ };
61
+
62
+ const llmConfig = getLLMConfig(provider);
63
+
64
+ const run = await Run.create<t.IState>({
65
+ runId: 'multi-session-test',
66
+ graphConfig: {
67
+ type: 'standard',
68
+ llmConfig,
69
+ tools: [createCodeExecutionTool()],
70
+ instructions: `You are a coding assistant. Execute code exactly as requested.
71
+ When asked to create files, use Python and save to /mnt/data/.
72
+ When reading files, print their contents.
73
+ Be concise in responses.`,
74
+ },
75
+ returnContent: true,
76
+ customHandlers,
77
+ });
78
+
79
+ const streamConfig: Partial<RunnableConfig> & {
80
+ version: 'v1' | 'v2';
81
+ streamMode: string;
82
+ } = {
83
+ configurable: {
84
+ provider,
85
+ thread_id: 'multi-session-test',
86
+ },
87
+ streamMode: 'values',
88
+ version: 'v2' as const,
89
+ };
90
+
91
+ // ========== TEST 1: Create first file ==========
92
+ console.log('\n\n' + '='.repeat(60));
93
+ console.log('TEST 1: Create first file (file_a.txt)');
94
+ console.log('='.repeat(60));
95
+
96
+ conversationHistory.push(
97
+ new HumanMessage(`
98
+ Create a file called "file_a.txt" with the content:
99
+ "This is file A, version 1"
100
+ Print confirmation when done.
101
+ `)
102
+ );
103
+
104
+ await run.processStream({ messages: conversationHistory }, streamConfig);
105
+ const messages1 = run.getRunMessages();
106
+ if (messages1) conversationHistory.push(...messages1);
107
+
108
+ printSessionContext(run, 'After Test 1');
109
+
110
+ // ========== TEST 2: Create second file (different session) ==========
111
+ console.log('\n\n' + '='.repeat(60));
112
+ console.log('TEST 2: Create second file (file_b.txt)');
113
+ console.log('Expecting: Both file_a.txt and file_b.txt tracked');
114
+ console.log('='.repeat(60));
115
+
116
+ conversationHistory.push(
117
+ new HumanMessage(`
118
+ Create a NEW file called "file_b.txt" with the content:
119
+ "This is file B"
120
+ Print confirmation when done.
121
+ `)
122
+ );
123
+
124
+ await run.processStream({ messages: conversationHistory }, streamConfig);
125
+ const messages2 = run.getRunMessages();
126
+ if (messages2) conversationHistory.push(...messages2);
127
+
128
+ printSessionContext(run, 'After Test 2');
129
+
130
+ // ========== TEST 3: Read BOTH files (verifies accumulation) ==========
131
+ console.log('\n\n' + '='.repeat(60));
132
+ console.log('TEST 3: Read BOTH files from previous executions');
133
+ console.log('This verifies multi-session file accumulation works');
134
+ console.log('='.repeat(60));
135
+
136
+ conversationHistory.push(
137
+ new HumanMessage(`
138
+ Read and print the contents of BOTH files:
139
+ 1. file_a.txt
140
+ 2. file_b.txt
141
+
142
+ Show me what's in each file.
143
+ `)
144
+ );
145
+
146
+ await run.processStream({ messages: conversationHistory }, streamConfig);
147
+ const messages3 = run.getRunMessages();
148
+ if (messages3) conversationHistory.push(...messages3);
149
+
150
+ printSessionContext(run, 'After Test 3');
151
+
152
+ // ========== TEST 4: Edit file_a.txt (verifies latest-wins) ==========
153
+ console.log('\n\n' + '='.repeat(60));
154
+ console.log('TEST 4: Edit file_a.txt (create new version)');
155
+ console.log('Expecting: Old file_a.txt replaced with new version');
156
+ console.log('='.repeat(60));
157
+
158
+ conversationHistory.push(
159
+ new HumanMessage(`
160
+ Create an UPDATED version of "file_a.txt" with the content:
161
+ "This is file A, version 2 - UPDATED"
162
+ Print confirmation when done.
163
+ `)
164
+ );
165
+
166
+ await run.processStream({ messages: conversationHistory }, streamConfig);
167
+ const messages4 = run.getRunMessages();
168
+ if (messages4) conversationHistory.push(...messages4);
169
+
170
+ printSessionContext(run, 'After Test 4');
171
+
172
+ // ========== TEST 5: Read file_a.txt (verifies latest version) ==========
173
+ console.log('\n\n' + '='.repeat(60));
174
+ console.log('TEST 5: Read file_a.txt to verify it has the UPDATED content');
175
+ console.log('Expected: "version 2 - UPDATED" NOT "version 1"');
176
+ console.log('='.repeat(60));
177
+
178
+ conversationHistory.push(
179
+ new HumanMessage(`
180
+ Read and print the contents of file_a.txt.
181
+ Tell me what version it shows.
182
+ `)
183
+ );
184
+
185
+ await run.processStream({ messages: conversationHistory }, streamConfig);
186
+ const messages5 = run.getRunMessages();
187
+ if (messages5) conversationHistory.push(...messages5);
188
+
189
+ printSessionContext(run, 'Final Session State');
190
+
191
+ // ========== SUMMARY ==========
192
+ console.log('\n\n' + '='.repeat(60));
193
+ console.log('TEST SUMMARY');
194
+ console.log('='.repeat(60));
195
+
196
+ const finalSession = run.Graph?.sessions.get(Constants.EXECUTE_CODE) as
197
+ | t.CodeSessionContext
198
+ | undefined;
199
+
200
+ if (finalSession) {
201
+ const uniqueSessionIds = new Set(
202
+ finalSession.files.map((f) => f.session_id)
203
+ );
204
+ console.log(`\nTotal files tracked: ${finalSession.files.length}`);
205
+ console.log(`Unique session_ids: ${uniqueSessionIds.size}`);
206
+ console.log('\nFiles:');
207
+ for (const file of finalSession.files) {
208
+ console.log(
209
+ ` - ${file.name} (session: ${file.session_id?.slice(0, 20)}...)`
210
+ );
211
+ }
212
+
213
+ // Verify expectations
214
+ const fileACount = finalSession.files.filter(
215
+ (f) => f.name === 'file_a.txt'
216
+ ).length;
217
+ const fileBCount = finalSession.files.filter(
218
+ (f) => f.name === 'file_b.txt'
219
+ ).length;
220
+
221
+ console.log('\n✓ Checks:');
222
+ console.log(` file_a.txt count: ${fileACount} (expected: 1, latest wins)`);
223
+ console.log(` file_b.txt count: ${fileBCount} (expected: 1)`);
224
+
225
+ if (fileACount === 1 && fileBCount === 1) {
226
+ console.log('\n✅ All tests passed! Multi-session tracking works.');
227
+ } else {
228
+ console.log('\n❌ Test failed - unexpected file counts');
229
+ }
230
+ }
231
+ }
232
+
233
+ process.on('unhandledRejection', (reason, promise) => {
234
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
235
+ process.exit(1);
236
+ });
237
+
238
+ testMultiSessionFiles().catch((err) => {
239
+ console.error('Test failed:', err);
240
+ process.exit(1);
241
+ });