-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathsession.ts
More file actions
286 lines (237 loc) · 8.14 KB
/
Copy pathsession.ts
File metadata and controls
286 lines (237 loc) · 8.14 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* Claudian - Session Utilities
*
* Session recovery and history reconstruction.
*/
import type { ChatMessage, ToolCallInfo } from '../core/types';
import { extractUserQuery, formatCurrentNote } from './context';
// ============================================
// Session Recovery
// ============================================
const SESSION_ERROR_PATTERNS = [
'session expired',
'session not found',
'invalid session',
'session invalid',
'process exited with code',
] as const;
const SESSION_ERROR_COMPOUND_PATTERNS = [
{ includes: ['session', 'expired'] },
{ includes: ['resume', 'failed'] },
{ includes: ['resume', 'error'] },
] as const;
export function isSessionExpiredError(error: unknown): boolean {
const msg = error instanceof Error ? error.message.toLowerCase() : '';
for (const pattern of SESSION_ERROR_PATTERNS) {
if (msg.includes(pattern)) {
return true;
}
}
for (const { includes } of SESSION_ERROR_COMPOUND_PATTERNS) {
if (includes.every(part => msg.includes(part))) {
return true;
}
}
return false;
}
// ============================================
// Authentication Error Detection
// ============================================
const AUTH_ERROR_PATTERNS = [
'authentication_failed',
'authentication_error',
'oauth token has expired',
'failed to authenticate',
'obtain a new token',
'refresh your existing token',
'invalid api key',
'invalid x-api-key',
'api key not found',
] as const;
const AUTH_ERROR_COMPOUND_PATTERNS = [
{ includes: ['401', 'authentication'] },
{ includes: ['token', 'expired'] },
{ includes: ['oauth', 'expired'] },
] as const;
/**
* Detects authentication/OAuth errors from the Claude API.
* These are distinct from session expiry — retrying won't help
* because the underlying credentials are invalid.
*/
export function isAuthenticationError(error: unknown): boolean {
let msg = '';
if (error instanceof Error) {
msg = error.message.toLowerCase();
} else if (typeof error === 'string') {
msg = error.toLowerCase();
}
if (!msg) return false;
for (const pattern of AUTH_ERROR_PATTERNS) {
if (msg.includes(pattern)) {
return true;
}
}
for (const { includes } of AUTH_ERROR_COMPOUND_PATTERNS) {
if (includes.every(part => msg.includes(part))) {
return true;
}
}
return false;
}
// ============================================
// History Reconstruction
// ============================================
/**
* Formats tool input for inclusion in rebuilt context.
* Includes all non-null parameters, truncates long string values.
*/
function formatToolInput(input: Record<string, unknown>, maxLength = 200): string {
if (!input || Object.keys(input).length === 0) return '';
try {
const parts: string[] = [];
for (const [key, value] of Object.entries(input)) {
if (value === undefined || value === null) continue;
let valueStr: string;
if (typeof value === 'string') {
valueStr = value.length > 100 ? `${value.slice(0, 100)}...` : value;
} else if (typeof value === 'object') {
valueStr = '[object]';
} else {
valueStr = String(value);
}
parts.push(`${key}=${valueStr}`);
}
const result = parts.join(', ');
return result.length > maxLength ? `${result.slice(0, maxLength)}...` : result;
} catch {
return '[input formatting error]';
}
}
/**
* Formats a tool call for inclusion in rebuilt context.
*
* Strategy:
* - Always include tool name and input (so Claude knows what was attempted)
* - Only include results for failed tools (errors are important to remember)
* - Successful tools can be re-executed if needed
*/
export function formatToolCallForContext(toolCall: ToolCallInfo, maxErrorLength = 500): string {
const status = toolCall.status ?? 'completed';
const isFailed = status === 'error' || status === 'blocked';
const inputStr = formatToolInput(toolCall.input);
const inputPart = inputStr ? ` input: ${inputStr}` : '';
if (!isFailed) {
return `[Tool ${toolCall.name}${inputPart} status=${status}]`;
}
const hasResult = typeof toolCall.result === 'string' && toolCall.result.trim().length > 0;
if (!hasResult) {
return `[Tool ${toolCall.name}${inputPart} status=${status}]`;
}
const errorMsg = truncateToolResult(toolCall.result as string, maxErrorLength);
return `[Tool ${toolCall.name}${inputPart} status=${status}] error: ${errorMsg}`;
}
export function truncateToolResult(result: string, maxLength = 500): string {
if (result.length > maxLength) {
return `${result.slice(0, maxLength)}... (truncated)`;
}
return result;
}
export function formatContextLine(message: ChatMessage): string | null {
if (!message.currentNote) {
return null;
}
return formatCurrentNote(message.currentNote);
}
/**
* Formats thinking blocks for inclusion in rebuilt context.
* Just indicates that thinking occurred (content not included - Claude will think anew).
*/
function formatThinkingBlocks(message: ChatMessage): string[] {
if (!message.contentBlocks) return [];
const thinkingBlocks = message.contentBlocks.filter(
(block): block is { type: 'thinking'; content: string; durationSeconds?: number } =>
block.type === 'thinking'
);
if (thinkingBlocks.length === 0) return [];
const totalDuration = thinkingBlocks.reduce(
(sum, block) => sum + (block.durationSeconds ?? 0),
0
);
const durationPart = totalDuration > 0 ? `, ${totalDuration.toFixed(1)}s total` : '';
return [`[Thinking: ${thinkingBlocks.length} block(s)${durationPart}]`];
}
export function buildContextFromHistory(messages: ChatMessage[]): string {
const parts: string[] = [];
for (const message of messages) {
if (message.role !== 'user' && message.role !== 'assistant') {
continue;
}
if (message.isInterrupt) {
continue;
}
if (message.role === 'assistant') {
const hasContent = message.content && message.content.trim().length > 0;
const hasToolCalls = message.toolCalls && message.toolCalls.length > 0;
const hasThinking = message.contentBlocks?.some(b => b.type === 'thinking');
if (!hasContent && !hasToolCalls && !hasThinking) {
continue;
}
}
const role = message.role === 'user' ? 'User' : 'Assistant';
const lines: string[] = [];
const content = message.content?.trim();
const contextLine = formatContextLine(message);
const userPayload = contextLine
? content
? `${contextLine}\n\n${content}`
: contextLine
: content;
lines.push(userPayload ? `${role}: ${userPayload}` : `${role}:`);
if (message.role === 'assistant') {
const thinkingLines = formatThinkingBlocks(message);
if (thinkingLines.length > 0) {
lines.push(...thinkingLines);
}
}
if (message.role === 'assistant' && message.toolCalls?.length) {
const toolLines = message.toolCalls
.map(tc => formatToolCallForContext(tc))
.filter(Boolean) as string[];
if (toolLines.length > 0) {
lines.push(...toolLines);
}
}
parts.push(lines.join('\n'));
}
return parts.join('\n\n');
}
export function getLastUserMessage(messages: ChatMessage[]): ChatMessage | undefined {
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'user') {
return messages[i];
}
}
return undefined;
}
/**
* Builds a prompt with history context for session recovery.
* Avoids duplicating the current prompt if it's already the last user message.
*/
export function buildPromptWithHistoryContext(
historyContext: string | null,
prompt: string,
actualPrompt: string,
conversationHistory: ChatMessage[]
): string {
if (!historyContext) return prompt;
const lastUserMessage = getLastUserMessage(conversationHistory);
// Compare actual user queries, not XML-wrapped versions
const lastUserQuery = lastUserMessage?.displayContent
?? extractUserQuery(lastUserMessage?.content ?? '');
const currentUserQuery = extractUserQuery(actualPrompt);
const shouldAppendPrompt = !lastUserMessage ||
lastUserQuery.trim() !== currentUserQuery.trim();
return shouldAppendPrompt
? `${historyContext}\n\nUser: ${prompt}`
: historyContext;
}