Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 7x 7x 7x 7x 7x 27x 27x 27x 27x 27x 27x 27x 14x 14x 1x 13x 13x 13x 3x 13x 13x 4x 9x 9x 9x 3x 9x 6x 6x 9x 9x 6x 6x 3x 3x 3x 3x 1x 2x 2x 1x 1x 2x 13x 9x 9x 9x 9x 9x 9x 9x 8x 8x 10x 3x 3x 3x 3x 2x 3x 1x 1x 3x 3x 3x 7x 2x 2x 2x 5x 3x 3x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 9x | import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import {
AIAction,
ExecutionLog,
Session,
SessionInput,
SystemPrompt,
} from '../core-entities';
import { ImportSessionResponseDto } from '../sessions/dto/session.dto';
export interface ExportMessage {
role: 'system' | 'user' | 'assistant' | 'tool';
content: string;
system_prompt_id?: string;
user_prompt?: string;
thoughts?: string;
tool_calls?: any[];
tool_call_id?: string;
}
export interface ExportSessionData {
model: string | null;
messages: ExportMessage[];
}
@Injectable()
export class SessionTransferService {
private readonly logger = new Logger(SessionTransferService.name);
constructor(
@InjectRepository(Session)
private sessionsRepository: Repository<Session>,
@InjectRepository(SessionInput)
private sessionInputsRepository: Repository<SessionInput>,
@InjectRepository(AIAction)
private aiActionsRepository: Repository<AIAction>,
@InjectRepository(ExecutionLog)
private executionLogsRepository: Repository<ExecutionLog>,
@InjectRepository(SystemPrompt)
private systemPromptsRepository: Repository<SystemPrompt>,
private dataSource: DataSource,
) {}
async exportSession(sessionId: string): Promise<ExportSessionData> {
const session = await this.sessionsRepository.findOne({
where: { id: sessionId },
relations: ['systemPrompt'],
});
if (!session) {
throw new NotFoundException(`Session with ID "${sessionId}" not found`);
}
// Fetch session inputs ordered by sequence_number
const sessionInputs = await this.sessionInputsRepository.find({
where: { session_id: sessionId },
order: { sequence_number: 'ASC' },
});
const messages: ExportMessage[] = [];
// 1. Add system message if exists
if (session.systemPrompt) {
messages.push({
role: 'system',
content: session.systemPrompt.prompt_content,
system_prompt_id: session.system_prompt_id || undefined,
});
}
// 2. Process each session input
for (const input of sessionInputs) {
if (input.role === 'user' && input.generated_context_string) {
// User message
messages.push({
role: 'user',
content: input.generated_context_string,
user_prompt: input.user_prompt || undefined,
});
} else if (input.role === 'model') {
// Assistant message
const msg: ExportMessage = {
role: 'assistant',
content: input.raw_llm_response || '',
};
if (input.thoughts) {
msg.thoughts = input.thoughts;
}
if (input.tool_calls) {
try {
msg.tool_calls = JSON.parse(input.tool_calls);
} catch (e) {
this.logger.warn(
`Failed to parse tool_calls for input ${input.id}`,
);
}
}
messages.push(msg);
// If this turn had tool calls, fetch and add tool results
if (msg.tool_calls && msg.tool_calls.length > 0) {
const toolActions = await this.aiActionsRepository.find({
where: { input_id: input.id },
relations: ['executionLogs'],
});
for (const action of toolActions) {
if (action.tool_call_id) {
const output = action.executionLogs?.[0]?.output || '';
const errorMessage =
action.executionLogs?.[0]?.error_message || '';
let toolResult: string;
if (output && errorMessage) {
toolResult = `${output}\n\nError: ${errorMessage}`;
} else Iif (errorMessage) {
toolResult = `Error: ${errorMessage}`;
} else if (output) {
toolResult = output;
} else {
continue; // Skip if no output or error
}
messages.push({
role: 'tool',
tool_call_id: action.tool_call_id,
content: toolResult,
});
}
}
}
}
}
return {
model: session.model_id,
messages,
};
}
async importSession(
data: ExportSessionData,
): Promise<ImportSessionResponseDto> {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
let messageCount = 0;
try {
// 1. Create new session
const session = queryRunner.manager.create(Session, {
model_id: data.model || null,
status: 'active',
});
await queryRunner.manager.save(session);
let currentAssistantInputId: string | null = null;
// 2. Process messages
for (const msg of data.messages) {
if (msg.role === 'system') {
// Handle system prompt
let systemPromptId: string | null = null;
if (msg.system_prompt_id) {
// Try to find by ID
const existing = await queryRunner.manager.findOneBy(SystemPrompt, {
id: msg.system_prompt_id,
});
if (existing) {
systemPromptId = existing.id;
}
}
if (!systemPromptId) {
// Fall back to default
const defaultPrompt = await queryRunner.manager.findOneBy(
SystemPrompt,
{
is_default: true,
},
);
systemPromptId = defaultPrompt?.id || null;
}
// Update session with system prompt
session.system_prompt_id = systemPromptId;
await queryRunner.manager.save(session);
messageCount++;
} else if (msg.role === 'user') {
// Create user SessionInput
const input = queryRunner.manager.create(SessionInput, {
session_id: session.id,
role: 'user',
generated_context_string: msg.content,
user_prompt: msg.user_prompt || null,
});
await queryRunner.manager.save(input);
messageCount++;
} else if (msg.role === 'assistant') {
// Create assistant SessionInput
const input = queryRunner.manager.create(SessionInput, {
session_id: session.id,
role: 'model',
raw_llm_response: msg.content,
thoughts: msg.thoughts || null,
tool_calls: msg.tool_calls ? JSON.stringify(msg.tool_calls) : null,
});
const savedInput = await queryRunner.manager.save(input);
currentAssistantInputId = savedInput.id;
messageCount++;
} else if (msg.role === 'tool') {
// Create placeholder AIAction + ExecutionLog
if (!currentAssistantInputId) {
this.logger.warn(
'Tool message without preceding assistant message, skipping',
);
continue;
}
const action = queryRunner.manager.create(AIAction, {
input_id: currentAssistantInputId,
action_type: 'tool',
status: 'completed',
tool_call_id: msg.tool_call_id || null,
order_of_execution: 0,
});
const savedAction = await queryRunner.manager.save(action);
const log = queryRunner.manager.create(ExecutionLog, {
action_id: savedAction.id,
output: msg.content,
});
await queryRunner.manager.save(log);
messageCount++;
}
}
await queryRunner.commitTransaction();
this.logger.log(`Session imported successfully: ${session.id}`);
return {
message: 'Import successful',
session_id: session.id,
message_count: messageCount,
};
} catch (err) {
await queryRunner.rollbackTransaction();
this.logger.error(`Import failed: ${err.message}`, err.stack);
throw new BadRequestException(`Import failed: ${err.message}`);
} finally {
await queryRunner.release();
}
}
}
|