@librechat/agents 3.0.75 → 3.0.77
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/agents/AgentContext.cjs +1 -4
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +36 -8
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +22 -21
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +28 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +1 -4
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +37 -9
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +22 -21
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +28 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +6 -0
- package/dist/types/tools/CodeExecutor.d.ts +0 -3
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
- package/dist/types/tools/ToolNode.d.ts +3 -1
- package/dist/types/types/llm.d.ts +3 -1
- package/dist/types/types/tools.d.ts +32 -0
- package/package.json +3 -2
- package/src/agents/AgentContext.ts +1 -8
- package/src/graphs/Graph.ts +46 -13
- package/src/scripts/caching.ts +27 -19
- package/src/scripts/code_exec_files.ts +58 -15
- package/src/scripts/code_exec_session.ts +282 -0
- package/src/scripts/test_code_api.ts +361 -0
- package/src/tools/CodeExecutor.ts +26 -23
- package/src/tools/ProgrammaticToolCalling.ts +18 -14
- package/src/tools/ToolNode.ts +33 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
- package/src/types/llm.ts +3 -1
- package/src/types/tools.ts +40 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// src/scripts/code_exec_session.ts
|
|
2
|
+
/**
|
|
3
|
+
* Test script for automatic session tracking in code execution tools.
|
|
4
|
+
*
|
|
5
|
+
* This tests the automatic session_id injection feature where:
|
|
6
|
+
* 1. First code execution generates files and returns a session_id
|
|
7
|
+
* 2. Session context is stored in Graph.sessions
|
|
8
|
+
* 3. Subsequent code executions automatically have access to previous files
|
|
9
|
+
* without the LLM needing to explicitly pass session_id
|
|
10
|
+
*
|
|
11
|
+
* Run with: npm run code_exec_session
|
|
12
|
+
*/
|
|
13
|
+
import { config } from 'dotenv';
|
|
14
|
+
config();
|
|
15
|
+
import { HumanMessage, BaseMessage } from '@langchain/core/messages';
|
|
16
|
+
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
17
|
+
import type * as t from '@/types';
|
|
18
|
+
import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
|
|
19
|
+
import {
|
|
20
|
+
ToolEndHandler,
|
|
21
|
+
ModelEndHandler,
|
|
22
|
+
createMetadataAggregator,
|
|
23
|
+
} from '@/events';
|
|
24
|
+
import { getLLMConfig } from '@/utils/llmConfig';
|
|
25
|
+
import { getArgs } from '@/scripts/args';
|
|
26
|
+
import { Constants, GraphEvents } from '@/common';
|
|
27
|
+
import { Run } from '@/run';
|
|
28
|
+
import { createCodeExecutionTool } from '@/tools/CodeExecutor';
|
|
29
|
+
|
|
30
|
+
const conversationHistory: BaseMessage[] = [];
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Prints a formatted section header for test output
|
|
34
|
+
*/
|
|
35
|
+
function printSection(title: string): void {
|
|
36
|
+
console.log('\n' + '='.repeat(60));
|
|
37
|
+
console.log(` ${title}`);
|
|
38
|
+
console.log('='.repeat(60) + '\n');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Prints session context from the graph for debugging
|
|
43
|
+
*/
|
|
44
|
+
function printSessionContext(run: Run<t.IState>): void {
|
|
45
|
+
const graph = run.Graph;
|
|
46
|
+
if (!graph) {
|
|
47
|
+
console.log('[Session] No graph available');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const session = graph.sessions.get(Constants.EXECUTE_CODE) as
|
|
52
|
+
| t.CodeSessionContext
|
|
53
|
+
| undefined;
|
|
54
|
+
|
|
55
|
+
if (!session) {
|
|
56
|
+
console.log('[Session] No session context stored yet');
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
console.log('[Session] Current session context:');
|
|
61
|
+
console.log(` - session_id: ${session.session_id}`);
|
|
62
|
+
console.log(` - files: ${JSON.stringify(session.files, null, 2)}`);
|
|
63
|
+
console.log(
|
|
64
|
+
` - lastUpdated: ${new Date(session.lastUpdated).toISOString()}`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function testAutomaticSessionTracking(): Promise<void> {
|
|
69
|
+
const { userName, location, provider, currentDate } = await getArgs();
|
|
70
|
+
const { contentParts, aggregateContent } = createContentAggregator();
|
|
71
|
+
|
|
72
|
+
const customHandlers = {
|
|
73
|
+
[GraphEvents.TOOL_END]: new ToolEndHandler(),
|
|
74
|
+
[GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
|
|
75
|
+
[GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
|
|
76
|
+
[GraphEvents.ON_RUN_STEP_COMPLETED]: {
|
|
77
|
+
handle: (
|
|
78
|
+
event: GraphEvents.ON_RUN_STEP_COMPLETED,
|
|
79
|
+
data: t.StreamEventData
|
|
80
|
+
): void => {
|
|
81
|
+
console.log('====== ON_RUN_STEP_COMPLETED ======');
|
|
82
|
+
console.dir(data, { depth: null });
|
|
83
|
+
aggregateContent({
|
|
84
|
+
event,
|
|
85
|
+
data: data as unknown as { result: t.ToolEndEvent },
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
[GraphEvents.ON_RUN_STEP]: {
|
|
90
|
+
handle: (
|
|
91
|
+
event: GraphEvents.ON_RUN_STEP,
|
|
92
|
+
data: t.StreamEventData
|
|
93
|
+
): void => {
|
|
94
|
+
console.log('====== ON_RUN_STEP ======');
|
|
95
|
+
console.dir(data, { depth: null });
|
|
96
|
+
aggregateContent({ event, data: data as t.RunStep });
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
[GraphEvents.ON_RUN_STEP_DELTA]: {
|
|
100
|
+
handle: (
|
|
101
|
+
event: GraphEvents.ON_RUN_STEP_DELTA,
|
|
102
|
+
data: t.StreamEventData
|
|
103
|
+
): void => {
|
|
104
|
+
aggregateContent({ event, data: data as t.RunStepDeltaEvent });
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
[GraphEvents.ON_MESSAGE_DELTA]: {
|
|
108
|
+
handle: (
|
|
109
|
+
event: GraphEvents.ON_MESSAGE_DELTA,
|
|
110
|
+
data: t.StreamEventData
|
|
111
|
+
): void => {
|
|
112
|
+
aggregateContent({ event, data: data as t.MessageDeltaEvent });
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
[GraphEvents.TOOL_START]: {
|
|
116
|
+
handle: (
|
|
117
|
+
_event: string,
|
|
118
|
+
data: t.StreamEventData,
|
|
119
|
+
_metadata?: Record<string, unknown>
|
|
120
|
+
): void => {
|
|
121
|
+
console.log('====== TOOL_START ======');
|
|
122
|
+
console.dir(data, { depth: null });
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const llmConfig = getLLMConfig(provider);
|
|
128
|
+
|
|
129
|
+
const run = await Run.create<t.IState>({
|
|
130
|
+
runId: 'session-tracking-test-1',
|
|
131
|
+
graphConfig: {
|
|
132
|
+
type: 'standard',
|
|
133
|
+
llmConfig,
|
|
134
|
+
tools: [createCodeExecutionTool()],
|
|
135
|
+
instructions: `You are an AI assistant testing automatic file persistence.
|
|
136
|
+
When writing Python code:
|
|
137
|
+
- Use print() for all outputs
|
|
138
|
+
- Files from previous executions are automatically available in /mnt/data/
|
|
139
|
+
- Files are READ-ONLY; write modifications to NEW filenames
|
|
140
|
+
- IMPORTANT: Do NOT include session_id in your tool calls - it's handled automatically.`,
|
|
141
|
+
additional_instructions: `User: ${userName}, Location: ${location}, Date: ${currentDate}.`,
|
|
142
|
+
},
|
|
143
|
+
returnContent: true,
|
|
144
|
+
customHandlers,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const streamConfig: Partial<RunnableConfig> & {
|
|
148
|
+
version: 'v1' | 'v2';
|
|
149
|
+
run_id?: string;
|
|
150
|
+
streamMode: string;
|
|
151
|
+
} = {
|
|
152
|
+
configurable: {
|
|
153
|
+
provider,
|
|
154
|
+
thread_id: 'session-tracking-test',
|
|
155
|
+
},
|
|
156
|
+
streamMode: 'values',
|
|
157
|
+
version: 'v2' as const,
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// =========================================================================
|
|
161
|
+
// Test 1: Create initial file (establishes session)
|
|
162
|
+
// =========================================================================
|
|
163
|
+
printSection('Test 1: Create Initial File');
|
|
164
|
+
console.log(
|
|
165
|
+
'This test creates a file, which should establish a session context.\n'
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
const userMessage1 = `
|
|
169
|
+
Create a Python file that writes a simple JSON config file named "app_config.json" with the following content:
|
|
170
|
+
{
|
|
171
|
+
"app_name": "TestApp",
|
|
172
|
+
"version": "1.0.0",
|
|
173
|
+
"debug": true
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
After writing, print the contents to confirm it was created correctly.
|
|
177
|
+
`;
|
|
178
|
+
|
|
179
|
+
conversationHistory.push(new HumanMessage(userMessage1));
|
|
180
|
+
await run.processStream({ messages: conversationHistory }, streamConfig);
|
|
181
|
+
|
|
182
|
+
const finalMessages1 = run.getRunMessages();
|
|
183
|
+
if (finalMessages1) {
|
|
184
|
+
conversationHistory.push(...finalMessages1);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
printSection('Session Context After Test 1');
|
|
188
|
+
printSessionContext(run);
|
|
189
|
+
|
|
190
|
+
// =========================================================================
|
|
191
|
+
// Test 2: Access previously created file (uses automatic session injection)
|
|
192
|
+
// =========================================================================
|
|
193
|
+
printSection('Test 2: Access Previous File (Automatic Session)');
|
|
194
|
+
console.log('This test reads the file created in Test 1.');
|
|
195
|
+
console.log(
|
|
196
|
+
'The LLM does NOT need to provide session_id - it should be injected automatically.\n'
|
|
197
|
+
);
|
|
198
|
+
|
|
199
|
+
const userMessage2 = `
|
|
200
|
+
Now read the app_config.json file that was just created and:
|
|
201
|
+
1. Print its contents
|
|
202
|
+
2. Confirm the version is "1.0.0"
|
|
203
|
+
|
|
204
|
+
Note: You should be able to access this file from the previous execution automatically.
|
|
205
|
+
`;
|
|
206
|
+
|
|
207
|
+
conversationHistory.push(new HumanMessage(userMessage2));
|
|
208
|
+
await run.processStream({ messages: conversationHistory }, streamConfig);
|
|
209
|
+
|
|
210
|
+
const finalMessages2 = run.getRunMessages();
|
|
211
|
+
if (finalMessages2) {
|
|
212
|
+
conversationHistory.push(...finalMessages2);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
printSection('Session Context After Test 2');
|
|
216
|
+
printSessionContext(run);
|
|
217
|
+
|
|
218
|
+
// =========================================================================
|
|
219
|
+
// Test 3: Modify file (write to new filename)
|
|
220
|
+
// =========================================================================
|
|
221
|
+
printSection('Test 3: Modify File (Write to New Filename)');
|
|
222
|
+
console.log(
|
|
223
|
+
'This test modifies the config by reading the old file and writing a new one.\n'
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
const userMessage3 = `
|
|
227
|
+
Read app_config.json, update the version to "2.0.0" and debug to false,
|
|
228
|
+
then save it as "app_config_v2.json". Print both the old and new contents.
|
|
229
|
+
`;
|
|
230
|
+
|
|
231
|
+
conversationHistory.push(new HumanMessage(userMessage3));
|
|
232
|
+
await run.processStream({ messages: conversationHistory }, streamConfig);
|
|
233
|
+
|
|
234
|
+
const finalMessages3 = run.getRunMessages();
|
|
235
|
+
if (finalMessages3) {
|
|
236
|
+
conversationHistory.push(...finalMessages3);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
printSection('Session Context After Test 3');
|
|
240
|
+
printSessionContext(run);
|
|
241
|
+
|
|
242
|
+
// =========================================================================
|
|
243
|
+
// Summary
|
|
244
|
+
// =========================================================================
|
|
245
|
+
printSection('Test Summary');
|
|
246
|
+
console.log('The automatic session tracking feature should have:');
|
|
247
|
+
console.log('1. Stored the session_id after the first code execution');
|
|
248
|
+
console.log('2. Automatically injected it into subsequent executions');
|
|
249
|
+
console.log('3. Accumulated file references across all executions');
|
|
250
|
+
console.log('\nCheck the session context output above to verify.\n');
|
|
251
|
+
|
|
252
|
+
// Generate title
|
|
253
|
+
const { handleLLMEnd, collected } = createMetadataAggregator();
|
|
254
|
+
const titleResult = await run.generateTitle({
|
|
255
|
+
provider,
|
|
256
|
+
inputText: 'Testing automatic session tracking for code execution',
|
|
257
|
+
contentParts,
|
|
258
|
+
chainOptions: {
|
|
259
|
+
callbacks: [{ handleLLMEnd }],
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
console.log('Generated Title:', titleResult);
|
|
263
|
+
console.log('Collected metadata:', collected);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
267
|
+
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
268
|
+
console.log('Conversation history:');
|
|
269
|
+
console.dir(conversationHistory, { depth: null });
|
|
270
|
+
process.exit(1);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
process.on('uncaughtException', (err) => {
|
|
274
|
+
console.error('Uncaught Exception:', err);
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
testAutomaticSessionTracking().catch((err) => {
|
|
278
|
+
console.error(err);
|
|
279
|
+
console.log('Conversation history:');
|
|
280
|
+
console.dir(conversationHistory, { depth: null });
|
|
281
|
+
process.exit(1);
|
|
282
|
+
});
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
// src/scripts/test_code_api.ts
|
|
2
|
+
/**
|
|
3
|
+
* Direct test of the Code API to verify session file persistence.
|
|
4
|
+
* This bypasses the LLM and tests the API directly.
|
|
5
|
+
*
|
|
6
|
+
* Run with: npx ts-node -r dotenv/config src/scripts/test_code_api.ts
|
|
7
|
+
*/
|
|
8
|
+
import { config } from 'dotenv';
|
|
9
|
+
config();
|
|
10
|
+
|
|
11
|
+
import fetch, { RequestInit } from 'node-fetch';
|
|
12
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
13
|
+
|
|
14
|
+
const API_KEY = process.env.LIBRECHAT_CODE_API_KEY ?? '';
|
|
15
|
+
const BASE_URL =
|
|
16
|
+
process.env.LIBRECHAT_CODE_BASEURL ?? 'https://api.librechat.ai/v1';
|
|
17
|
+
const PROXY = process.env.PROXY;
|
|
18
|
+
|
|
19
|
+
if (!API_KEY) {
|
|
20
|
+
console.error('LIBRECHAT_CODE_API_KEY not set');
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface FileRef {
|
|
25
|
+
id: string;
|
|
26
|
+
name: string;
|
|
27
|
+
session_id?: string;
|
|
28
|
+
/** Lineage tracking - present if file was modified from previous session */
|
|
29
|
+
modified_from?: {
|
|
30
|
+
id: string;
|
|
31
|
+
session_id: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface ExecResult {
|
|
36
|
+
session_id: string;
|
|
37
|
+
stdout: string;
|
|
38
|
+
stderr: string;
|
|
39
|
+
files?: FileRef[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface FileInfo {
|
|
43
|
+
name: string;
|
|
44
|
+
metadata: Record<string, string>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function makeRequest(
|
|
48
|
+
endpoint: string,
|
|
49
|
+
body?: Record<string, unknown>
|
|
50
|
+
): Promise<unknown> {
|
|
51
|
+
const fetchOptions: RequestInit = {
|
|
52
|
+
method: body ? 'POST' : 'GET',
|
|
53
|
+
headers: {
|
|
54
|
+
'Content-Type': 'application/json',
|
|
55
|
+
'User-Agent': 'LibreChat/1.0',
|
|
56
|
+
'X-API-Key': API_KEY,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
if (body) {
|
|
61
|
+
fetchOptions.body = JSON.stringify(body);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (PROXY) {
|
|
65
|
+
fetchOptions.agent = new HttpsProxyAgent(PROXY);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
console.log(`\n>>> ${body ? 'POST' : 'GET'} ${endpoint}`);
|
|
69
|
+
if (body) {
|
|
70
|
+
console.log('Body:', JSON.stringify(body, null, 2));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const response = await fetch(endpoint, fetchOptions);
|
|
74
|
+
const result = await response.json();
|
|
75
|
+
|
|
76
|
+
console.log(`<<< Response (${response.status}):`);
|
|
77
|
+
console.log(JSON.stringify(result, null, 2));
|
|
78
|
+
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
throw new Error(`HTTP ${response.status}: ${JSON.stringify(result)}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return result;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function testCodeAPI(): Promise<void> {
|
|
87
|
+
console.log('='.repeat(60));
|
|
88
|
+
console.log('TEST 1: Create a file');
|
|
89
|
+
console.log('='.repeat(60));
|
|
90
|
+
|
|
91
|
+
const createCode = `
|
|
92
|
+
import json
|
|
93
|
+
|
|
94
|
+
config = {
|
|
95
|
+
"app_name": "TestApp",
|
|
96
|
+
"version": "1.0.0",
|
|
97
|
+
"debug": True
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
with open("/mnt/data/test_config.json", "w") as f:
|
|
101
|
+
json.dump(config, f, indent=2)
|
|
102
|
+
|
|
103
|
+
with open("/mnt/data/test_config.json", "r") as f:
|
|
104
|
+
print(f.read())
|
|
105
|
+
`;
|
|
106
|
+
|
|
107
|
+
const result1 = (await makeRequest(`${BASE_URL}/exec`, {
|
|
108
|
+
lang: 'py',
|
|
109
|
+
code: createCode,
|
|
110
|
+
})) as ExecResult;
|
|
111
|
+
|
|
112
|
+
const sessionId = result1.session_id;
|
|
113
|
+
const files = result1.files ?? [];
|
|
114
|
+
|
|
115
|
+
console.log('\n--- Result Summary ---');
|
|
116
|
+
console.log('session_id:', sessionId);
|
|
117
|
+
console.log('files:', files);
|
|
118
|
+
console.log('stdout:', result1.stdout);
|
|
119
|
+
console.log('stderr:', result1.stderr);
|
|
120
|
+
|
|
121
|
+
if (!sessionId || files.length === 0) {
|
|
122
|
+
console.error('\n❌ No session_id or files returned!');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Check if files now include session_id (new API feature)
|
|
127
|
+
const hasSessionIdInFiles = files.some((f) => f.session_id != null);
|
|
128
|
+
console.log('\n✅ Files include session_id:', hasSessionIdInFiles);
|
|
129
|
+
|
|
130
|
+
console.log('\n' + '='.repeat(60));
|
|
131
|
+
console.log(
|
|
132
|
+
'TEST 2: Fetch files IMMEDIATELY (no delay - testing race condition fix)'
|
|
133
|
+
);
|
|
134
|
+
console.log('='.repeat(60));
|
|
135
|
+
|
|
136
|
+
const filesResult = (await makeRequest(
|
|
137
|
+
`${BASE_URL}/files/${sessionId}?detail=full`
|
|
138
|
+
)) as FileInfo[];
|
|
139
|
+
|
|
140
|
+
console.log('\n--- Files in session (detail=full) ---');
|
|
141
|
+
for (const file of filesResult) {
|
|
142
|
+
console.log('File:', file.name);
|
|
143
|
+
console.log(' metadata:', file.metadata);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (filesResult.length === 0) {
|
|
147
|
+
console.log(
|
|
148
|
+
'\n⚠️ Files endpoint returned empty - race condition may still exist'
|
|
149
|
+
);
|
|
150
|
+
} else {
|
|
151
|
+
console.log('\n✅ Files available immediately!');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Test new normalized detail level
|
|
155
|
+
console.log('\n' + '='.repeat(60));
|
|
156
|
+
console.log('TEST 2b: Fetch files with detail=normalized');
|
|
157
|
+
console.log('='.repeat(60));
|
|
158
|
+
|
|
159
|
+
const normalizedResult = (await makeRequest(
|
|
160
|
+
`${BASE_URL}/files/${sessionId}?detail=normalized`
|
|
161
|
+
)) as FileRef[];
|
|
162
|
+
|
|
163
|
+
console.log('\n--- Files in session (detail=normalized) ---');
|
|
164
|
+
console.log(JSON.stringify(normalizedResult, null, 2));
|
|
165
|
+
|
|
166
|
+
console.log('\n' + '='.repeat(60));
|
|
167
|
+
console.log(
|
|
168
|
+
'TEST 3: Read file IMMEDIATELY using files from original response'
|
|
169
|
+
);
|
|
170
|
+
console.log('='.repeat(60));
|
|
171
|
+
|
|
172
|
+
// Use files directly - if API returns session_id, use that; otherwise add it
|
|
173
|
+
const fileReferences: FileRef[] = files.map((file) => ({
|
|
174
|
+
session_id: file.session_id ?? sessionId,
|
|
175
|
+
id: file.id,
|
|
176
|
+
name: file.name,
|
|
177
|
+
}));
|
|
178
|
+
|
|
179
|
+
console.log(
|
|
180
|
+
'\nFile references we will send:',
|
|
181
|
+
JSON.stringify(fileReferences, null, 2)
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
const readCode = `
|
|
185
|
+
import json
|
|
186
|
+
|
|
187
|
+
with open("/mnt/data/test_config.json", "r") as f:
|
|
188
|
+
config = json.load(f)
|
|
189
|
+
print("Read config:")
|
|
190
|
+
print(json.dumps(config, indent=2))
|
|
191
|
+
print("Version:", config.get("version"))
|
|
192
|
+
`;
|
|
193
|
+
|
|
194
|
+
const result2 = (await makeRequest(`${BASE_URL}/exec`, {
|
|
195
|
+
lang: 'py',
|
|
196
|
+
code: readCode,
|
|
197
|
+
files: fileReferences,
|
|
198
|
+
})) as ExecResult;
|
|
199
|
+
|
|
200
|
+
console.log('\n--- Result Summary ---');
|
|
201
|
+
console.log('stdout:', result2.stdout);
|
|
202
|
+
console.log('stderr:', result2.stderr);
|
|
203
|
+
|
|
204
|
+
if (result2.stderr && result2.stderr.includes('FileNotFoundError')) {
|
|
205
|
+
console.log(
|
|
206
|
+
'\n❌ File not found! The file reference format might be wrong.'
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
// Try alternative format - just session_id
|
|
210
|
+
console.log('\n' + '='.repeat(60));
|
|
211
|
+
console.log('TEST 4: Try with just session_id in request');
|
|
212
|
+
console.log('='.repeat(60));
|
|
213
|
+
|
|
214
|
+
const result3 = (await makeRequest(`${BASE_URL}/exec`, {
|
|
215
|
+
lang: 'py',
|
|
216
|
+
code: readCode,
|
|
217
|
+
session_id: sessionId,
|
|
218
|
+
})) as ExecResult;
|
|
219
|
+
|
|
220
|
+
console.log('\n--- Result Summary ---');
|
|
221
|
+
console.log('stdout:', result3.stdout);
|
|
222
|
+
console.log('stderr:', result3.stderr);
|
|
223
|
+
} else {
|
|
224
|
+
console.log('\n✅ File read successfully!');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ============================================================
|
|
228
|
+
// TEST 4: MODIFY the file (same filename) - tests editable files
|
|
229
|
+
// ============================================================
|
|
230
|
+
console.log('\n' + '='.repeat(60));
|
|
231
|
+
console.log('TEST 4: MODIFY file in-place (testing editable files feature)');
|
|
232
|
+
console.log('='.repeat(60));
|
|
233
|
+
|
|
234
|
+
const modifyCode = `
|
|
235
|
+
import json
|
|
236
|
+
|
|
237
|
+
# Read the existing file
|
|
238
|
+
with open("/mnt/data/test_config.json", "r") as f:
|
|
239
|
+
config = json.load(f)
|
|
240
|
+
|
|
241
|
+
print("Original config:")
|
|
242
|
+
print(json.dumps(config, indent=2))
|
|
243
|
+
|
|
244
|
+
# Modify the config
|
|
245
|
+
config["version"] = "2.0.0"
|
|
246
|
+
config["modified"] = True
|
|
247
|
+
|
|
248
|
+
# Write BACK to the SAME filename (should work now!)
|
|
249
|
+
with open("/mnt/data/test_config.json", "w") as f:
|
|
250
|
+
json.dump(config, f, indent=2)
|
|
251
|
+
|
|
252
|
+
# Verify the write
|
|
253
|
+
with open("/mnt/data/test_config.json", "r") as f:
|
|
254
|
+
updated = json.load(f)
|
|
255
|
+
|
|
256
|
+
print("\\nUpdated config:")
|
|
257
|
+
print(json.dumps(updated, indent=2))
|
|
258
|
+
`;
|
|
259
|
+
|
|
260
|
+
const result3 = (await makeRequest(`${BASE_URL}/exec`, {
|
|
261
|
+
lang: 'py',
|
|
262
|
+
code: modifyCode,
|
|
263
|
+
files: fileReferences,
|
|
264
|
+
})) as ExecResult;
|
|
265
|
+
|
|
266
|
+
console.log('\n--- Result Summary ---');
|
|
267
|
+
console.log('stdout:', result3.stdout);
|
|
268
|
+
console.log('stderr:', result3.stderr);
|
|
269
|
+
console.log('files:', JSON.stringify(result3.files, null, 2));
|
|
270
|
+
|
|
271
|
+
if (result3.stderr && result3.stderr.includes('Permission denied')) {
|
|
272
|
+
console.log('\n❌ Permission denied - files are still read-only!');
|
|
273
|
+
} else if (result3.stderr && result3.stderr.includes('Error')) {
|
|
274
|
+
console.log('\n❌ Error modifying file:', result3.stderr);
|
|
275
|
+
} else {
|
|
276
|
+
console.log('\n✅ File modified successfully!');
|
|
277
|
+
|
|
278
|
+
// Check for modified_from lineage
|
|
279
|
+
const modifiedFile = result3.files?.find(
|
|
280
|
+
(f) => f.name === 'test_config.json'
|
|
281
|
+
);
|
|
282
|
+
if (modifiedFile) {
|
|
283
|
+
console.log('\n--- Modified File Details ---');
|
|
284
|
+
console.log(' id:', modifiedFile.id);
|
|
285
|
+
console.log(' name:', modifiedFile.name);
|
|
286
|
+
console.log(' session_id:', modifiedFile.session_id);
|
|
287
|
+
if (modifiedFile.modified_from) {
|
|
288
|
+
console.log(
|
|
289
|
+
' modified_from:',
|
|
290
|
+
JSON.stringify(modifiedFile.modified_from)
|
|
291
|
+
);
|
|
292
|
+
console.log(
|
|
293
|
+
'\n✅ Lineage tracking working! File shows it was modified from previous session.'
|
|
294
|
+
);
|
|
295
|
+
} else {
|
|
296
|
+
console.log(
|
|
297
|
+
'\n⚠️ No modified_from field - lineage tracking not present'
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
} else {
|
|
301
|
+
console.log('\n⚠️ Modified file not found in response files array');
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ============================================================
|
|
306
|
+
// TEST 5: Verify modification persists in next execution
|
|
307
|
+
// ============================================================
|
|
308
|
+
console.log('\n' + '='.repeat(60));
|
|
309
|
+
console.log(
|
|
310
|
+
'TEST 5: Verify modified file can be read in subsequent execution'
|
|
311
|
+
);
|
|
312
|
+
console.log('='.repeat(60));
|
|
313
|
+
|
|
314
|
+
// Use the new file references from the modify response
|
|
315
|
+
const newFileRefs: FileRef[] = (result3.files ?? []).map((file) => ({
|
|
316
|
+
session_id: file.session_id ?? result3.session_id,
|
|
317
|
+
id: file.id,
|
|
318
|
+
name: file.name,
|
|
319
|
+
}));
|
|
320
|
+
|
|
321
|
+
if (newFileRefs.length === 0) {
|
|
322
|
+
console.log(
|
|
323
|
+
'\n⚠️ No files returned from modification, skipping verification'
|
|
324
|
+
);
|
|
325
|
+
} else {
|
|
326
|
+
console.log(
|
|
327
|
+
'\nUsing new file references:',
|
|
328
|
+
JSON.stringify(newFileRefs, null, 2)
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
const verifyCode = `
|
|
332
|
+
import json
|
|
333
|
+
|
|
334
|
+
with open("/mnt/data/test_config.json", "r") as f:
|
|
335
|
+
config = json.load(f)
|
|
336
|
+
|
|
337
|
+
print("Verified config:")
|
|
338
|
+
print(json.dumps(config, indent=2))
|
|
339
|
+
|
|
340
|
+
if config.get("version") == "2.0.0" and config.get("modified") == True:
|
|
341
|
+
print("\\n✅ Modification persisted correctly!")
|
|
342
|
+
else:
|
|
343
|
+
print("\\n❌ Modification did NOT persist!")
|
|
344
|
+
`;
|
|
345
|
+
|
|
346
|
+
const result4 = (await makeRequest(`${BASE_URL}/exec`, {
|
|
347
|
+
lang: 'py',
|
|
348
|
+
code: verifyCode,
|
|
349
|
+
files: newFileRefs,
|
|
350
|
+
})) as ExecResult;
|
|
351
|
+
|
|
352
|
+
console.log('\n--- Result Summary ---');
|
|
353
|
+
console.log('stdout:', result4.stdout);
|
|
354
|
+
console.log('stderr:', result4.stderr);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
testCodeAPI().catch((err) => {
|
|
359
|
+
console.error('Error:', err);
|
|
360
|
+
process.exit(1);
|
|
361
|
+
});
|