v4.3.17: handleCodeChat → gateway/chat/code-chat.ts 분리 보관
- handle-chat.ts에서 handleCodeChat(180줄) + _overlapLen 헬퍼를 별도 파일로 이동 (handle-chat.ts 3,222→3,033줄, 189줄 감소) - code-chat.ts는 createCodeChat 팩토리로 정의, handle-chat.ts에서 필요한 의존성만 주입 - server.ts는 기존 createHandleChat 팩토리 사용 그대로 유지, handleCodeChat은 handle-chat.ts 내부에서 code-chat.ts 팩토리로 생성 - 빌드 성공 + 재시작 후 일반 채팅/code_ai 채팅(python_eval) 모두 정상 동작 확인
This commit is contained in:
1 parent
41f7e702a9
commit
d1032019de
2 files changed
+235
-198
No files matched your search
@@ -0,0 +1,226 @@
|
||||
import { getConfig, getUserWorkspace } from '../../config/config';
|
||||
import { getModelForRole } from '../../providers/factory';
|
||||
import { getOllamaClient } from '../../agents/ollama-client';
|
||||
import { getWorkspace, setWorkspace } from '../session';
|
||||
import type { ToolResult } from './execute-tool';
|
||||
|
||||
export interface HandleChatResult {
|
||||
type: 'chat' | 'execute';
|
||||
text: string;
|
||||
thinking?: string;
|
||||
toolResults?: ToolResult[];
|
||||
usage?: { promptTokens: number; completionTokens: number; ctxWindow: number };
|
||||
}
|
||||
|
||||
// Longest suffix of `a` that is a prefix of `b`. Used to strip the duplicated
|
||||
// preamble weaker models re-emit at the start of each new tool round.
|
||||
function _overlapLen(a: string, b: string): number {
|
||||
const max = Math.min(a.length, b.length);
|
||||
for (let L = max; L > 0; L--) {
|
||||
if (a.slice(a.length - L) === b.slice(0, L)) return L;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export interface CodeChatDeps {
|
||||
executeTool: (name: string, args: any, workspacePath: string, sessionId?: string, sendSSE?: (type: string, data: any) => void, username?: string) => Promise<ToolResult>;
|
||||
buildTools: () => any[];
|
||||
logToolCall: (workspacePath: string, toolName: string, args: any, result: string, error: boolean) => void;
|
||||
normalizeToolArgs: (rawArgs: any) => any;
|
||||
getModelProfileExtraPrompt: (modelName: string) => string;
|
||||
codeAiLocalSessions: Set<string>;
|
||||
}
|
||||
|
||||
export function createCodeChat(deps: CodeChatDeps) {
|
||||
const {
|
||||
executeTool,
|
||||
buildTools,
|
||||
logToolCall,
|
||||
normalizeToolArgs,
|
||||
getModelProfileExtraPrompt,
|
||||
codeAiLocalSessions,
|
||||
} = deps;
|
||||
|
||||
async function handleCodeChat(
|
||||
message: string,
|
||||
sessionId: string,
|
||||
sendSSE: (event: string, data: any) => void,
|
||||
abortSignal?: { aborted: boolean },
|
||||
modelOverride?: string,
|
||||
username?: string,
|
||||
historyOverride?: Array<{ role: string; content: string }>,
|
||||
useTools: boolean = true,
|
||||
boardContext?: string,
|
||||
): Promise<HandleChatResult> {
|
||||
const ollama = getOllamaClient();
|
||||
const configuredWorkspace = getConfig().getWorkspacePath();
|
||||
const sessionWorkspace = getWorkspace(sessionId, username);
|
||||
const userWorkspace = username ? getUserWorkspace(username) : null;
|
||||
const workspacePath = sessionWorkspace || userWorkspace || configuredWorkspace;
|
||||
if (workspacePath && sessionWorkspace !== workspacePath) setWorkspace(sessionId, workspacePath, username);
|
||||
|
||||
const isLocal = codeAiLocalSessions.has(String(sessionId));
|
||||
const history = (historyOverride || []).map(m => ({ role: (m.role === 'user' ? 'user' : 'assistant') as 'user' | 'assistant', content: String(m.content) }));
|
||||
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', timeZone: 'Asia/Seoul' });
|
||||
const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Seoul' });
|
||||
|
||||
// Tools available in the editor: everything except browser/messaging/timer/etc.
|
||||
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
|
||||
// useTools:false → plan/ask phase; pass empty tools so the model generates text only
|
||||
const tools = useTools ? buildTools().filter((t: any) => !codeAiBlockedTools.has(String(t?.function?.name || ''))) : [];
|
||||
|
||||
const _modelDisplayName = modelOverride ? modelOverride.replace(/:cloud$/, '') : 'AI';
|
||||
const systemPrompt = `You are an expert coding assistant embedded in the user's code editor. Your model name is "${_modelDisplayName}" — if asked who you are or what model you are, always answer truthfully with this name. Current date: ${dateStr}, ${timeStr}.
|
||||
|
||||
When making code changes, use tools to edit files — do NOT output code in markdown fenced blocks (\\\`\\\`\\\`). For questions, explanations, or analysis, respond directly in text without using tools. Never repeat or re-summarize what was already said. Start tool calls immediately without preamble.${isLocal ? `
|
||||
|
||||
CLIENT-LOCAL MODE: Files are stored in the user's local browser folder via the File System Access API — NOT on the server. The shell, run_command, and bash tools are NOT available in this mode and will return an error if called. After creating or editing files, tell the user the files are ready and they can open them in their browser. NEVER call shell/run_command/bash to open, run, or verify files in this mode.` : ''}
|
||||
|
||||
CONTEXT: The current file and all open project files are ALREADY provided in the conversation WITH line numbers (look for "[현재 파일: …]" and "[파일: …]" blocks). Do NOT call coder_read_file for a file whose content is already shown — edit it directly. Only call coder_read_file for files that are NOT present in the context.
|
||||
|
||||
AVAILABLE TOOLS:
|
||||
- coder_read_file(filename): Read file content WITH line numbers. Use ONLY for files not already shown in the context above.
|
||||
- coder_list_files(directory): List files in a directory.
|
||||
- search_files(pattern): Search file contents with regex.
|
||||
- coder_patch_file(filename, edits): PREFERRED edit tool. Uses SEARCH/REPLACE blocks — no line numbers needed.
|
||||
- coder_write_file(filename, content): Create a new file. For existing files, use coder_patch_file or coder_overwrite_lines instead.
|
||||
- coder_overwrite_lines(filename, start_line, end_line, new_content): Replace lines by number (1-based).
|
||||
- coder_insert_lines(filename, after_line, content): Insert lines after a line number (0 = beginning).
|
||||
- coder_delete_lines(filename, start_line, end_line): Delete lines by line number.
|
||||
- coder_str_replace(filename, find, replace): Find exact text and replace.
|
||||
- coder_move_file(source, destination): Move or rename a file. Parent directories are created automatically. Works in both server workspace and client-local mode.
|
||||
- shell(command): Run terminal commands to test code.
|
||||
- python_eval(code): Run Python code.
|
||||
- web_search(query): Search the web.
|
||||
|
||||
coder_patch_file FORMAT (PREFERRED for all edits):
|
||||
------- SEARCH
|
||||
exact text to find (must match the CHARACTER-BY-CHARACTER including indentation and whitespace)
|
||||
=======
|
||||
replacement text (leave empty between ======= and +++++++ to delete)
|
||||
+++++++ REPLACE
|
||||
|
||||
Multiple edits: list SEARCH/REPLACE blocks in file order. Each SEARCH text must match EXACTLY — copy it verbatim from coder_read_file output. Do NOT modify the marker format.
|
||||
|
||||
TOOL USE RULES:
|
||||
- The current/open files are already in context with line numbers — edit them directly without coder_read_file. Only coder_read_file for files NOT shown.
|
||||
- Default to coder_patch_file for most changes. Use coder_write_file only for new files.
|
||||
- After editing: briefly state what you changed (1 line). No extended explanations.
|
||||
- NEVER output code in markdown fences (\\\`\\\`\\\`). ALL code changes via tool calls.
|
||||
- NEVER start your message with "Great", "Certainly", "Okay", "Sure", or similar filler.
|
||||
- Do not ask for more information than necessary. Use tools to find answers.
|
||||
- Keep responses concise. Avoid lengthy preambles or exhaustive file-by-file breakdowns unless explicitly asked for a detailed report.
|
||||
|
||||
CODE QUALITY:
|
||||
- Write complete, runnable code. No placeholder TODO comments, no stub functions.
|
||||
- Stay in the same language/framework as the existing code.
|
||||
- Never run package install commands (pip, npm, apt-get).
|
||||
- If a tool call fails, re-read the file and retry with correct code.${boardContext ? `\n\nTARGET BOARD:\n${boardContext}` : ''}`;
|
||||
|
||||
const messages: any[] = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
...history,
|
||||
{ role: 'user', content: message },
|
||||
];
|
||||
|
||||
const allToolResults: ToolResult[] = [];
|
||||
let allThinking = '';
|
||||
let finalText = '';
|
||||
let streamedText = ''; // everything streamed to the client this turn (for cross-round dedup)
|
||||
let lastUsage: { promptTokens: number; completionTokens: number; ctxWindow: number } | undefined;
|
||||
|
||||
const MAX_ROUNDS = 12;
|
||||
for (let round = 0; round < MAX_ROUNDS; round++) {
|
||||
if (abortSignal?.aborted) break;
|
||||
|
||||
// Round 0 streams live; later rounds buffer so we can strip any duplicated
|
||||
// preamble before showing it.
|
||||
let roundRaw = '';
|
||||
const onToken = round === 0
|
||||
? (t: string) => { roundRaw += t; streamedText += t; try { sendSSE('token', { text: t }); } catch {} }
|
||||
: (t: string) => { roundRaw += t; };
|
||||
|
||||
let response: any;
|
||||
try {
|
||||
const result = await ollama.chatWithThinkingStream(messages, 'executor', onToken, {
|
||||
tools,
|
||||
temperature: 0.3,
|
||||
// num_ctx omitted → adapter sizes it to the prompt (up to the model's native
|
||||
// context_length) so large code files aren't silently truncated.
|
||||
num_predict: 32768,
|
||||
think: true,
|
||||
model: modelOverride,
|
||||
});
|
||||
response = result.message;
|
||||
if (result.thinking) allThinking += (allThinking ? '\n\n' : '') + result.thinking;
|
||||
if (result.usage) {
|
||||
lastUsage = result.usage;
|
||||
try { sendSSE('usage', result.usage); } catch {}
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('[code-chat] generation error:', err?.message || err);
|
||||
if (finalText || streamedText) break;
|
||||
return { type: 'chat', text: `Error: ${err?.message || err}` };
|
||||
}
|
||||
|
||||
// For later rounds, emit the deduplicated remainder of this round's text now.
|
||||
if (round > 0 && roundRaw) {
|
||||
const shown = roundRaw.slice(_overlapLen(streamedText, roundRaw));
|
||||
if (shown) { streamedText += shown; try { sendSSE('token', { text: shown }); } catch {} }
|
||||
}
|
||||
|
||||
let toolCalls: any[] = response?.tool_calls || [];
|
||||
if (!toolCalls.length) {
|
||||
// No tools → this is the final answer. Use the deduped visible text.
|
||||
const content = String(response?.content || '');
|
||||
finalText = round === 0 ? content : (streamedText || content);
|
||||
break;
|
||||
}
|
||||
|
||||
// Assistant turn carrying the tool calls, then execute each and feed results back.
|
||||
messages.push(response);
|
||||
for (let i = 0; i < toolCalls.length; i++) {
|
||||
if (!(toolCalls[i] as any).id) {
|
||||
(toolCalls[i] as any).id = `call_${(toolCalls[i].function?.name || 'tool').replace(/\W/g, '_')}_${i}_${Date.now()}`;
|
||||
}
|
||||
}
|
||||
for (const call of toolCalls) {
|
||||
if (abortSignal?.aborted) break;
|
||||
const toolCallId = String((call as any)?.id || '').trim();
|
||||
const toolName = call.function?.name || 'unknown';
|
||||
const toolArgs = normalizeToolArgs(call.function?.arguments);
|
||||
if (codeAiBlockedTools.has(toolName)) {
|
||||
const blocked = `[BLOCKED] ${toolName} is not available in Code mode. Use file tools (coder_read_file, coder_patch_file, coder_overwrite_lines, coder_write_file) or shell instead.`;
|
||||
allToolResults.push({ name: toolName, args: toolArgs, result: blocked, error: true });
|
||||
try { sendSSE('tool_result', { action: toolName, result: blocked, error: true, stepNum: allToolResults.length }); } catch {}
|
||||
messages.push({ role: 'tool', name: toolName, tool_name: toolName, tool_call_id: toolCallId || undefined, content: blocked });
|
||||
continue;
|
||||
}
|
||||
try { sendSSE('tool_call', { action: toolName, args: toolArgs, stepNum: allToolResults.length + 1 }); } catch {}
|
||||
let toolResult: ToolResult;
|
||||
try {
|
||||
toolResult = await executeTool(toolName, toolArgs, workspacePath, sessionId, sendSSE, username);
|
||||
} catch (err: any) {
|
||||
toolResult = { name: toolName, args: toolArgs, result: `Tool error: ${err?.message || err}`, error: true };
|
||||
}
|
||||
allToolResults.push(toolResult);
|
||||
logToolCall(workspacePath, toolName, toolArgs, toolResult.result, toolResult.error);
|
||||
try { sendSSE('tool_result', { action: toolName, result: toolResult.result.slice(0, 500), error: toolResult.error, stepNum: allToolResults.length }); } catch {}
|
||||
messages.push({ role: 'tool', name: toolName, tool_name: toolName, tool_call_id: toolCallId || undefined, content: toolResult.result });
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalText && streamedText) finalText = streamedText;
|
||||
return {
|
||||
type: allToolResults.length ? 'execute' : 'chat',
|
||||
text: finalText,
|
||||
thinking: allThinking || undefined,
|
||||
toolResults: allToolResults,
|
||||
usage: lastUsage,
|
||||
};
|
||||
}
|
||||
|
||||
return { handleCodeChat };
|
||||
}
|
||||
@@ -66,6 +66,7 @@ import {
|
||||
import { OllamaProcessManager } from '../infra/ollama-process-manager';
|
||||
import { raceWithWatchdog, PreemptState } from '../tasks/preempt-watchdog';
|
||||
import type { ToolResult } from './execute-tool';
|
||||
import { createCodeChat, type HandleChatResult as CodeChatHandleChatResult } from './code-chat';
|
||||
import { createPreflightAdvisor, type PreflightAdvisorCtx } from './preflight-advisor';
|
||||
import { createBrowserDesktopAdvisors, type BrowserDesktopAdvisorCtx } from './browser-desktop-advisor';
|
||||
import type { SkillsManager } from '../skills-manager';
|
||||
@@ -82,24 +83,6 @@ export interface HandleChatResult {
|
||||
usage?: { promptTokens: number; completionTokens: number; ctxWindow: number };
|
||||
}
|
||||
|
||||
// Longest suffix of `a` that is a prefix of `b`. Used to strip the duplicated
|
||||
// preamble weaker models re-emit at the start of each new tool round.
|
||||
function _overlapLen(a: string, b: string): number {
|
||||
const max = Math.min(a.length, b.length);
|
||||
for (let L = max; L > 0; L--) {
|
||||
if (a.slice(a.length - L) === b.slice(0, L)) return L;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// This module holds the two largest, most tightly-coupled functions in the
|
||||
// gateway: handleChat (the core tool-execution loop, called from every chat
|
||||
// route, background task, telegram/kakao message, and heartbeat) and its
|
||||
// sibling handleCodeChat (same shape, used only by the code-editor's /api/chat
|
||||
// path). They share every dependency below, so they're bundled into one
|
||||
// factory rather than split — most of these deps (broadcastWS, skillsManager,
|
||||
// codeAiLocalSessions, etc.) are module-level state/functions in server.ts
|
||||
// that many other already-extracted files also depend on.
|
||||
export interface HandleChatDeps {
|
||||
logToolCall: (workspacePath: string, toolName: string, args: any, result: string, error: boolean) => void;
|
||||
logToDaily: (workspacePath: string, role: string, content: string, sessionId?: string) => void;
|
||||
@@ -177,186 +160,14 @@ export function createHandleChat(deps: HandleChatDeps) {
|
||||
CONFIG_DIR_PATH,
|
||||
} = deps;
|
||||
|
||||
async function handleCodeChat(
|
||||
message: string,
|
||||
sessionId: string,
|
||||
sendSSE: (event: string, data: any) => void,
|
||||
abortSignal?: { aborted: boolean },
|
||||
modelOverride?: string,
|
||||
username?: string,
|
||||
historyOverride?: Array<{ role: string; content: string }>,
|
||||
useTools: boolean = true,
|
||||
boardContext?: string,
|
||||
): Promise<HandleChatResult> {
|
||||
const ollama = getOllamaClient();
|
||||
const configuredWorkspace = getConfig().getWorkspacePath();
|
||||
const sessionWorkspace = getWorkspace(sessionId, username);
|
||||
const userWorkspace = username ? getUserWorkspace(username) : null;
|
||||
const workspacePath = sessionWorkspace || userWorkspace || configuredWorkspace;
|
||||
if (workspacePath && sessionWorkspace !== workspacePath) setWorkspace(sessionId, workspacePath, username);
|
||||
|
||||
const isLocal = codeAiLocalSessions.has(String(sessionId));
|
||||
const history = (historyOverride || []).map(m => ({ role: (m.role === 'user' ? 'user' : 'assistant') as 'user' | 'assistant', content: String(m.content) }));
|
||||
|
||||
const now = new Date();
|
||||
const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', timeZone: 'Asia/Seoul' });
|
||||
const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Seoul' });
|
||||
|
||||
// Tools available in the editor: everything except browser/messaging/timer/etc.
|
||||
const codeAiBlockedTools = new Set(['start_task', 'task_control', 'write_note', 'browser_open', 'browser_snapshot', 'browser_click', 'browser_fill', 'browser_press_key', 'browser_wait', 'browser_close', 'image_search', 'image_url', 'image_edit', 'image_info', 'image_read', 'weather_search', 'weather_map_screenshot', 'start_timer', 'send_message', 'send_telegram', 'kakao_send_message', 'create_presentation', 'edit_presentation', 'spawn_subagent', 'schedule_job', 'parse_schedule_pattern']);
|
||||
// useTools:false → plan/ask phase; pass empty tools so the model generates text only
|
||||
const tools = useTools ? buildTools().filter((t: any) => !codeAiBlockedTools.has(String(t?.function?.name || ''))) : [];
|
||||
|
||||
const _modelDisplayName = modelOverride ? modelOverride.replace(/:cloud$/, '') : 'AI';
|
||||
const systemPrompt = `You are an expert coding assistant embedded in the user's code editor. Your model name is "${_modelDisplayName}" — if asked who you are or what model you are, always answer truthfully with this name. Current date: ${dateStr}, ${timeStr}.
|
||||
|
||||
When making code changes, use tools to edit files — do NOT output code in markdown fenced blocks (\\\`\\\`\\\`). For questions, explanations, or analysis, respond directly in text without using tools. Never repeat or re-summarize what was already said. Start tool calls immediately without preamble.${isLocal ? `
|
||||
|
||||
CLIENT-LOCAL MODE: Files are stored in the user's local browser folder via the File System Access API — NOT on the server. The shell, run_command, and bash tools are NOT available in this mode and will return an error if called. After creating or editing files, tell the user the files are ready and they can open them in their browser. NEVER call shell/run_command/bash to open, run, or verify files in this mode.` : ''}
|
||||
|
||||
CONTEXT: The current file and all open project files are ALREADY provided in the conversation WITH line numbers (look for "[현재 파일: …]" and "[파일: …]" blocks). Do NOT call coder_read_file for a file whose content is already shown — edit it directly. Only call coder_read_file for a file that is NOT present in the context.
|
||||
|
||||
AVAILABLE TOOLS:
|
||||
- coder_read_file(filename): Read file content WITH line numbers. Use ONLY for files not already shown in the context above.
|
||||
- coder_list_files(directory): List files in a directory.
|
||||
- search_files(pattern): Search file contents with regex.
|
||||
- coder_patch_file(filename, edits): PREFERRED edit tool. Uses SEARCH/REPLACE blocks — no line numbers needed.
|
||||
- coder_write_file(filename, content): Create a new file. For existing files, use coder_patch_file or coder_overwrite_lines instead.
|
||||
- coder_overwrite_lines(filename, start_line, end_line, new_content): Replace lines by number (1-based).
|
||||
- coder_insert_lines(filename, after_line, content): Insert lines after a line number (0 = beginning).
|
||||
- coder_delete_lines(filename, start_line, end_line): Delete lines by number.
|
||||
- coder_str_replace(filename, find, replace): Find exact text and replace.
|
||||
- coder_move_file(source, destination): Move or rename a file. Parent directories are created automatically. Works in both server workspace and client-local mode.
|
||||
- shell(command): Run terminal commands to test code.
|
||||
- python_eval(code): Run Python code.
|
||||
- web_search(query): Search the web.
|
||||
|
||||
coder_patch_file FORMAT (PREFERRED for all edits):
|
||||
------- SEARCH
|
||||
exact text to find (must match the file CHARACTER-BY-CHARACTER including indentation and whitespace)
|
||||
=======
|
||||
replacement text (leave empty between ======= and +++++++ to delete)
|
||||
+++++++ REPLACE
|
||||
|
||||
Multiple edits: list SEARCH/REPLACE blocks in file order. Each SEARCH text must match EXACTLY — copy it verbatim from coder_read_file output. Do NOT modify the marker format.
|
||||
|
||||
TOOL USE RULES:
|
||||
- The current/open files are already in context with line numbers — edit them directly without coder_read_file. Only coder_read_file for files NOT shown.
|
||||
- Default to coder_patch_file for most changes. Use coder_write_file only for new files.
|
||||
- After editing: briefly state what you changed (1 line). No extended explanations.
|
||||
- NEVER output code in markdown fences (\\\`\\\`\\\`). ALL code changes via tool calls.
|
||||
- NEVER start your message with "Great", "Certainly", "Okay", "Sure", or similar filler.
|
||||
- Do not ask for more information than necessary. Use tools to find answers.
|
||||
- Keep responses concise. Avoid lengthy preambles or exhaustive file-by-file breakdowns unless explicitly asked for a detailed plan.
|
||||
|
||||
CODE QUALITY:
|
||||
- Write complete, runnable code. No placeholder TODO comments, no stub functions.
|
||||
- Stay in the same language/framework as the existing code.
|
||||
- Never run package install commands (pip, npm, apt-get).
|
||||
- If a tool call fails, re-read the file and retry with correct content.${boardContext ? `\n\nTARGET BOARD:\n${boardContext}` : ''}`;
|
||||
|
||||
const messages: any[] = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
...history,
|
||||
{ role: 'user', content: message },
|
||||
];
|
||||
|
||||
const allToolResults: ToolResult[] = [];
|
||||
let allThinking = '';
|
||||
let finalText = '';
|
||||
let streamedText = ''; // everything streamed to the client this turn (for cross-round dedup)
|
||||
let lastUsage: { promptTokens: number; completionTokens: number; ctxWindow: number } | undefined;
|
||||
|
||||
const MAX_ROUNDS = 12;
|
||||
for (let round = 0; round < MAX_ROUNDS; round++) {
|
||||
if (abortSignal?.aborted) break;
|
||||
|
||||
// Round 0 streams live; later rounds buffer so we can strip any duplicated
|
||||
// preamble before showing it.
|
||||
let roundRaw = '';
|
||||
const onToken = round === 0
|
||||
? (t: string) => { roundRaw += t; streamedText += t; try { sendSSE('token', { text: t }); } catch {} }
|
||||
: (t: string) => { roundRaw += t; };
|
||||
|
||||
let response: any;
|
||||
try {
|
||||
const result = await ollama.chatWithThinkingStream(messages, 'executor', onToken, {
|
||||
tools,
|
||||
temperature: 0.3,
|
||||
// num_ctx omitted → adapter sizes it to the prompt (up to the model's native
|
||||
// context_length) so large code files aren't silently truncated.
|
||||
num_predict: 32768,
|
||||
think: true,
|
||||
model: modelOverride,
|
||||
});
|
||||
response = result.message;
|
||||
if (result.thinking) allThinking += (allThinking ? '\n\n' : '') + result.thinking;
|
||||
if (result.usage) {
|
||||
lastUsage = result.usage;
|
||||
try { sendSSE('usage', result.usage); } catch {}
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('[code-chat] generation error:', err?.message || err);
|
||||
if (finalText || streamedText) break;
|
||||
return { type: 'chat', text: `Error: ${err?.message || err}` };
|
||||
}
|
||||
|
||||
// For later rounds, emit the deduplicated remainder of this round's text now.
|
||||
if (round > 0 && roundRaw) {
|
||||
const shown = roundRaw.slice(_overlapLen(streamedText, roundRaw));
|
||||
if (shown) { streamedText += shown; try { sendSSE('token', { text: shown }); } catch {} }
|
||||
}
|
||||
|
||||
let toolCalls: any[] = response?.tool_calls || [];
|
||||
if (!toolCalls.length) {
|
||||
// No tools → this is the final answer. Use the deduped visible text.
|
||||
const content = String(response?.content || '');
|
||||
finalText = round === 0 ? content : (streamedText || content);
|
||||
break;
|
||||
}
|
||||
|
||||
// Assistant turn carrying the tool calls, then execute each and feed results back.
|
||||
messages.push(response);
|
||||
for (let i = 0; i < toolCalls.length; i++) {
|
||||
if (!(toolCalls[i] as any).id) {
|
||||
(toolCalls[i] as any).id = `call_${(toolCalls[i].function?.name || 'tool').replace(/\W/g, '_')}_${i}_${Date.now()}`;
|
||||
}
|
||||
}
|
||||
for (const call of toolCalls) {
|
||||
if (abortSignal?.aborted) break;
|
||||
const toolCallId = String((call as any)?.id || '').trim();
|
||||
const toolName = call.function?.name || 'unknown';
|
||||
const toolArgs = normalizeToolArgs(call.function?.arguments);
|
||||
if (codeAiBlockedTools.has(toolName)) {
|
||||
const blocked = `[BLOCKED] ${toolName} is not available in Code mode. Use file tools (coder_read_file, coder_patch_file, coder_overwrite_lines, coder_write_file) or shell instead.`;
|
||||
allToolResults.push({ name: toolName, args: toolArgs, result: blocked, error: true });
|
||||
try { sendSSE('tool_result', { action: toolName, result: blocked, error: true, stepNum: allToolResults.length }); } catch {}
|
||||
messages.push({ role: 'tool', name: toolName, tool_name: toolName, tool_call_id: toolCallId || undefined, content: blocked });
|
||||
continue;
|
||||
}
|
||||
try { sendSSE('tool_call', { action: toolName, args: toolArgs, stepNum: allToolResults.length + 1 }); } catch {}
|
||||
let toolResult: ToolResult;
|
||||
try {
|
||||
toolResult = await executeTool(toolName, toolArgs, workspacePath, sessionId, sendSSE, username);
|
||||
} catch (err: any) {
|
||||
toolResult = { name: toolName, args: toolArgs, result: `Tool error: ${err?.message || err}`, error: true };
|
||||
}
|
||||
allToolResults.push(toolResult);
|
||||
logToolCall(workspacePath, toolName, toolArgs, toolResult.result, toolResult.error);
|
||||
try { sendSSE('tool_result', { action: toolName, result: toolResult.result.slice(0, 500), error: toolResult.error, stepNum: allToolResults.length }); } catch {}
|
||||
messages.push({ role: 'tool', name: toolName, tool_name: toolName, tool_call_id: toolCallId || undefined, content: toolResult.result });
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalText && streamedText) finalText = streamedText;
|
||||
return {
|
||||
type: allToolResults.length ? 'execute' : 'chat',
|
||||
text: finalText,
|
||||
thinking: allThinking || undefined,
|
||||
toolResults: allToolResults,
|
||||
usage: lastUsage,
|
||||
};
|
||||
}
|
||||
const { handleCodeChat } = createCodeChat({
|
||||
executeTool,
|
||||
buildTools,
|
||||
logToolCall,
|
||||
normalizeToolArgs,
|
||||
getModelProfileExtraPrompt,
|
||||
codeAiLocalSessions,
|
||||
});
|
||||
|
||||
async function handleChat(
|
||||
message: string,
|
||||
|
||||
Reference in new issue
Block a user