forked from instantlyeasy/claude-code-sdk-ts
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsessions.js
More file actions
234 lines (192 loc) · 6.93 KB
/
sessions.js
File metadata and controls
234 lines (192 loc) · 6.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* Session Management Examples
*
* This file demonstrates how to use session management features
* to maintain conversation context across multiple queries.
*/
import { claude, query } from '@instantlyeasy/claude-code-sdk-ts';
// Example 1: Basic session continuation
async function basicSessionExample() {
console.log('=== Basic Session Example ===\n');
const builder = claude()
.withModel('sonnet')
.skipPermissions();
// First query - establish context
console.log('Query 1: Asking Claude to remember a number...');
const parser1 = builder.query('Remember this number: 42. I will ask you about it later.');
const sessionId = await parser1.getSessionId();
const response1 = await parser1.asText();
console.log('Response:', response1);
console.log('Session ID:', sessionId);
// Second query - test memory
console.log('\nQuery 2: Testing Claude\'s memory...');
const response2 = await builder
.withSessionId(sessionId)
.query('What number did I ask you to remember?')
.asText();
console.log('Response:', response2);
// Third query - more context
console.log('\nQuery 3: Adding more context...');
const response3 = await builder
.withSessionId(sessionId)
.query('Multiply that number by 2 and tell me the result.')
.asText();
console.log('Response:', response3);
}
// Example 2: Session with file operations
async function fileOperationSessionExample() {
console.log('\n\n=== File Operation Session Example ===\n');
const builder = claude()
.withModel('sonnet')
.skipPermissions()
.allowTools('Write', 'Read', 'Edit');
// Create a file
console.log('Creating a test file...');
const parser1 = builder.query('Create a file called session-test.txt with the content "Initial content"');
const sessionId = await parser1.getSessionId();
await parser1.asResult();
console.log('File created');
// Modify the file in the same session
console.log('\nModifying the file...');
await builder
.withSessionId(sessionId)
.query('Append " - Modified in session" to session-test.txt')
.asResult();
console.log('File modified');
// Read the file to verify
console.log('\nReading the file...');
const content = await builder
.withSessionId(sessionId)
.query('Read session-test.txt and tell me its contents')
.asText();
console.log('File contents:', content);
// Clean up
console.log('\nCleaning up...');
await builder
.withSessionId(sessionId)
.query('Delete session-test.txt')
.asResult();
console.log('File deleted');
}
// Example 3: Classic API with sessionId option
async function classicAPIExample() {
console.log('\n=== Classic API with sessionId Example ===\n');
// Step 1: Start a conversation using classic API to establish a session
console.log('Step 1: Starting initial conversation with classic API...');
let sessionId = null;
let firstResponse = '';
const initialOptions = {
model: 'sonnet',
permissionMode: 'bypassPermissions'
};
for await (const message of query(
'Pick a completely random card from a standard deck of 52 playing cards',
initialOptions
)) {
// Extract session ID from any message that has it
if (message.session_id) {
sessionId = message.session_id;
}
if (message.type === 'assistant') {
for (const block of message.content) {
if (block.type === 'text') {
firstResponse += block.text;
}
}
}
}
console.log('First response:', firstResponse);
console.log('Extracted session ID:', sessionId);
// Step 2: Continue the conversation using the extracted session ID
if (sessionId) {
console.log('\nStep 2: Continuing conversation with session ID...');
const continueOptions = {
sessionId: sessionId,
model: 'sonnet',
permissionMode: 'bypassPermissions'
};
let secondResponse = '';
for await (const message of query('Which card did you pick?', continueOptions)) {
if (message.type === 'assistant') {
for (const block of message.content) {
if (block.type === 'text') {
secondResponse += block.text;
}
}
}
}
console.log('Second response:', secondResponse);
console.log('\n✅ Classic API session management working properly!');
} else {
console.log('❌ Could not extract session ID from first conversation.');
}
}
// Example 4: Complex workflow with session
async function complexWorkflowExample() {
console.log('\n\n=== Complex Workflow Session Example ===\n');
const builder = claude()
.withModel('opus')
.skipPermissions();
// Step 1: Analyze a topic
console.log('Step 1: Setting up context...');
const parser1 = builder.query(`
You are helping me create a simple web application.
The app should be a todo list with the following features:
1. Add new todos
2. Mark todos as complete
3. Delete todos
4. Filter by status (all, active, completed)
Please acknowledge that you understand the requirements.
`);
const sessionId = await parser1.getSessionId();
const ack = await parser1.asText();
console.log('Claude:', ack.substring(0, 100) + '...');
// Step 2: Plan the implementation
console.log('\n\nStep 2: Planning the implementation...');
const plan = await builder
.withSessionId(sessionId)
.query('What files should we create for this todo app? List them with their purpose.')
.asText();
console.log('Implementation plan:', plan.substring(0, 200) + '...');
// Step 3: Review the session context
console.log('\nStep 3: Verifying session context...');
const review = await builder
.withSessionId(sessionId)
.query('Summarize what we discussed about the todo app requirements')
.asText();
console.log('Context review:', review.substring(0, 200) + '...');
return sessionId;
}
// Example 5: Resuming a session later
async function resumeSessionExample(existingSessionId) {
console.log('\n\n=== Resume Session Example ===\n');
console.log('Resuming session:', existingSessionId);
const response = await claude()
.withModel('opus')
.skipPermissions()
.withSessionId(existingSessionId)
.query('What were the main features we discussed for the todo app?')
.asText();
console.log('Claude remembers:', response.substring(0, 200) + '...');
}
// Run all examples
async function main() {
try {
// Run basic session example
await basicSessionExample();
// Run file operation example (commented out to avoid creating files)
// await fileOperationSessionExample();
// Run classic API example
await classicAPIExample();
// Run complex workflow and get session ID
const sessionId = await complexWorkflowExample();
// Demonstrate resuming a session
if (sessionId) {
await resumeSessionExample(sessionId);
}
console.log('\n✅ All session examples completed successfully!');
} catch (error) {
console.error('Error:', error);
}
}
main();