v4.3.16: preflight advisor → gateway/chat/preflight-advisor.ts 분리 보관
- handle-chat.ts에서 preflight advisor 블록(1092-1284줄, 약 195줄)과 replaceCurrentUserPromptWithAdvisorObjective 헬퍼를 별도 파일로 이동 (handle-chat.ts 3,400→3,222줄, 178줄 감소) - preflightRoute/preflightReasonForTurn은 getter/setter 뷰 객체로 연결하여 메인 루프의 sanitizeFinalReply 및 route 조건에서 계속 사용 가능 - cron 스케줄러(server.ts)의 callSecondaryPreflight 사용은 그대로 유지 - 빌드 성공 + 재시작 후 일반 채팅/code_ai 채팅 모두 정상 동작 확인
This commit is contained in:
1 parent
6271b65f84
commit
41f7e702a9
2 files changed
+306
-215
No files matched your search
+37
-215
@@ -29,7 +29,6 @@ import { getBrowserSessionInfo, getBrowserAdvisorPacket } from '../automation/br
|
||||
import { getDesktopAdvisorPacket } from '../automation/desktop-tools';
|
||||
import {
|
||||
OrchestrationTriggerState,
|
||||
callSecondaryPreflight,
|
||||
callSecondaryAdvisor,
|
||||
callSecondaryFileOpClassifier,
|
||||
callSecondaryFileAnalyzer,
|
||||
@@ -37,14 +36,11 @@ import {
|
||||
callSecondaryFilePatchPlanner,
|
||||
callSecondaryBrowserAdvisor,
|
||||
callSecondaryDesktopAdvisor,
|
||||
formatPreflightExecutionObjective,
|
||||
formatPreflightHint,
|
||||
formatAdvisoryHint,
|
||||
formatBrowserAdvisorHint,
|
||||
formatDesktopAdvisorHint,
|
||||
getOrchestrationConfig,
|
||||
clampPreemptConfig,
|
||||
shouldRunPreflight,
|
||||
} from '../../orchestration/multi-agent';
|
||||
import { createTask, loadTask, saveTask, appendJournal, type TaskRecord } from '../tasks/task-store';
|
||||
import { inferTaskChannelFromSession, findBlockedTaskForSession } from '../tasks/handle-task-control';
|
||||
@@ -70,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 { createPreflightAdvisor, type PreflightAdvisorCtx } from './preflight-advisor';
|
||||
import { createBrowserDesktopAdvisors, type BrowserDesktopAdvisorCtx } from './browser-desktop-advisor';
|
||||
import type { SkillsManager } from '../skills-manager';
|
||||
|
||||
@@ -995,23 +992,7 @@ OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always
|
||||
});
|
||||
}
|
||||
|
||||
const replaceCurrentUserPromptWithAdvisorObjective = (objective: string): boolean => {
|
||||
const objectiveText = String(objective || '').trim();
|
||||
if (!objectiveText) return false;
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const msg = messages[i];
|
||||
if (msg?.role !== 'user') continue;
|
||||
if (String(msg?.content || '') !== message) continue;
|
||||
messages.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
messages.push({ role: 'user', content: objectiveText });
|
||||
messages.push({
|
||||
role: 'assistant',
|
||||
content: 'Understood. I will execute this objective and preserve literal values from the request.',
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
const buildSecondaryAssistContext = () => {
|
||||
const availableTools = (tools || [])
|
||||
@@ -1088,201 +1069,42 @@ OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always
|
||||
};
|
||||
|
||||
const rawOrchCfg = ((getConfig().getConfig() as any).orchestration || {}) as any;
|
||||
// Preflight advisor pass — separated into its own file but still wired via
|
||||
// a view object so the main loop can keep reading preflightRoute/preflightReasonForTurn.
|
||||
const preflightCtx: PreflightAdvisorCtx = {
|
||||
get preflightRoute() { return preflightRoute; },
|
||||
set preflightRoute(v) { preflightRoute = v; },
|
||||
get preflightReasonForTurn() { return preflightReasonForTurn; },
|
||||
set preflightReasonForTurn(v) { preflightReasonForTurn = v; },
|
||||
get messages() { return messages; },
|
||||
get multiAgentActive() { return multiAgentActive; },
|
||||
get sessionId() { return sessionId; },
|
||||
get message() { return message; },
|
||||
};
|
||||
const preflightAdvisor = createPreflightAdvisor(preflightCtx, {
|
||||
sendSSE,
|
||||
history,
|
||||
workspacePath,
|
||||
username,
|
||||
orchestrationSkillEnabled,
|
||||
orchestrationStats,
|
||||
orchestrationLog,
|
||||
recordOrchestrationEvent,
|
||||
isBootStartupTurn,
|
||||
skipGenericPreflightForFileOp: fileOpV2Active,
|
||||
fileOpType,
|
||||
isTaskRunnerSession: sessionId.startsWith('task_'),
|
||||
isCodeAiSession,
|
||||
isDirectCall: callerContext?.includes('no_preflight') ?? false,
|
||||
handleChat,
|
||||
makeBroadcastForTask,
|
||||
telegramChannel,
|
||||
logToDaily,
|
||||
addMessage,
|
||||
});
|
||||
const preflightResult = await preflightAdvisor.runPreflightAdvisorPass();
|
||||
if (preflightResult) return preflightResult;
|
||||
|
||||
// Optional preflight advisor pass: secondary model can route and provide
|
||||
// a compact execution plan before primary starts tool calling.
|
||||
const preflightCfg = orchestrationSkillEnabled ? getOrchestrationConfig() : null;
|
||||
if (!preflightCfg?.enabled && String(rawOrchCfg?.preflight?.mode || '') === 'always') {
|
||||
sendSSE('info', {
|
||||
message: 'Preflight advisor is set to Always, but Multi-Agent Orchestrator skill is disabled.',
|
||||
});
|
||||
}
|
||||
const skipGenericPreflightForFileOp = fileOpV2Active;
|
||||
if (skipGenericPreflightForFileOp) {
|
||||
sendSSE('info', {
|
||||
message: `FILE_OP v2 route selected (${fileOpType}); skipping generic advisor preflight.`,
|
||||
});
|
||||
}
|
||||
// Task runner sessions (sessionId starts with 'task_') are already inside a background task
|
||||
// execution — skip preflight entirely to prevent recursive task spawning loops.
|
||||
const isTaskRunnerSession = sessionId.startsWith('task_');
|
||||
const isCodeAiSessionForPreflight = isCodeAiSession;
|
||||
|
||||
const isDirectCall = callerContext?.includes('no_preflight');
|
||||
if (
|
||||
preflightCfg?.enabled &&
|
||||
!isBootStartupTurn &&
|
||||
!skipGenericPreflightForFileOp &&
|
||||
!isTaskRunnerSession &&
|
||||
!isCodeAiSessionForPreflight &&
|
||||
!isDirectCall &&
|
||||
shouldRunPreflight(message, preflightCfg.preflight.mode) &&
|
||||
orchestrationStats.assistCount < preflightCfg.limits.max_assists_per_session
|
||||
) {
|
||||
sendSSE('info', {
|
||||
message: `Running advisor preflight via ${preflightCfg.secondary.provider}:${preflightCfg.secondary.model}...`,
|
||||
});
|
||||
console.log(
|
||||
`[Orchestrator] Preflight start (${preflightCfg.secondary.provider}:${preflightCfg.secondary.model})`,
|
||||
);
|
||||
const preflightBlockedTask = findBlockedTaskForSession(sessionId);
|
||||
const preflight = await callSecondaryPreflight({
|
||||
userMessage: message,
|
||||
recentHistory: history.slice(-4).map(h => ({ role: h.role, content: h.content })),
|
||||
blockedTask: preflightBlockedTask
|
||||
? {
|
||||
id: preflightBlockedTask.id,
|
||||
title: preflightBlockedTask.title,
|
||||
status: preflightBlockedTask.status,
|
||||
currentStepIndex: preflightBlockedTask.currentStepIndex,
|
||||
planLength: Array.isArray(preflightBlockedTask.plan) ? preflightBlockedTask.plan.length : 0,
|
||||
pauseReason: preflightBlockedTask.pauseReason,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (preflight) {
|
||||
preflightRoute = preflight.route;
|
||||
preflightReasonForTurn = String(preflight.reason || '').trim();
|
||||
orchestrationLog.push(`[preflight:${preflight.route}] ${preflight.reason || 'no reason'}`);
|
||||
console.log(
|
||||
`[Orchestrator] Preflight route=${preflight.route} reason=${(preflight.reason || 'n/a').slice(0, 120)}`,
|
||||
);
|
||||
const stats = recordOrchestrationEvent(
|
||||
sessionId,
|
||||
{
|
||||
trigger: 'preflight',
|
||||
mode: 'planner',
|
||||
reason: preflight.reason || 'preflight routing',
|
||||
route: preflight.route,
|
||||
},
|
||||
preflightCfg,
|
||||
);
|
||||
sendSSE('orchestration', {
|
||||
trigger: 'preflight',
|
||||
mode: 'planner',
|
||||
route: preflight.route,
|
||||
reason: preflight.reason,
|
||||
preflight,
|
||||
assist_count: stats.assistCount,
|
||||
assist_cap: preflightCfg.limits.max_assists_per_session,
|
||||
});
|
||||
|
||||
if (preflight.route === 'background_task' && multiAgentActive) {
|
||||
const taskTitle = preflight.task_title || 'Background Task';
|
||||
const taskPlan = (preflight.task_plan || []).map((desc, i) => ({
|
||||
index: i,
|
||||
description: desc,
|
||||
status: 'pending' as const,
|
||||
}));
|
||||
const taskChannel = inferTaskChannelFromSession(sessionId);
|
||||
const parsedTelegramChatId = taskChannel === 'telegram'
|
||||
? Number(String(sessionId || '').replace(/^telegram_/, ''))
|
||||
: NaN;
|
||||
const telegramChatId = Number.isFinite(parsedTelegramChatId) && parsedTelegramChatId > 0
|
||||
? parsedTelegramChatId
|
||||
: undefined;
|
||||
const task = createTask({
|
||||
title: taskTitle,
|
||||
prompt: message,
|
||||
sessionId,
|
||||
channel: taskChannel,
|
||||
telegramChatId,
|
||||
plan: taskPlan.length > 0 ? taskPlan : [{ index: 0, description: 'Execute task', status: 'pending' }],
|
||||
});
|
||||
appendJournal(task.id, { type: 'status_push', content: `Task queued: ${taskTitle}` });
|
||||
// Fire background runner (detached — does not block HTTP response)
|
||||
const runner = new BackgroundTaskRunner(task.id, handleChat, makeBroadcastForTask(task.id), telegramChannel);
|
||||
runner.start().catch(err => console.error(`[BackgroundTaskRunner] Task ${task.id} error:`, err.message));
|
||||
const queuedMessage = preflight.friendly_queued_message
|
||||
|| `On it! I've queued "${taskTitle}" as a background task. You can track progress in the Tasks panel.`;
|
||||
sendSSE('task_queued', { taskId: task.id, title: taskTitle });
|
||||
logToDaily(workspacePath, 'SmallClaw', queuedMessage, sessionId);
|
||||
addMessage(sessionId, { role: 'assistant', content: queuedMessage, timestamp: Date.now() }, {}, username);
|
||||
return { type: 'chat', text: queuedMessage };
|
||||
}
|
||||
|
||||
if (
|
||||
preflight.route === 'secondary_chat' &&
|
||||
preflightCfg.preflight.allow_secondary_chat &&
|
||||
preflight.secondary_response?.trim()
|
||||
) {
|
||||
sendSSE('info', {
|
||||
message: 'Advisor route selected secondary_chat. Returning secondary response directly.',
|
||||
});
|
||||
const text = preflight.secondary_response.trim();
|
||||
logToDaily(workspacePath, 'SmallClaw', text, sessionId);
|
||||
return { type: 'chat', text };
|
||||
}
|
||||
|
||||
if (preflight.route === 'secondary_chat' && !preflightCfg.preflight.allow_secondary_chat) {
|
||||
sendSSE('info', {
|
||||
message: 'Advisor suggested secondary_chat, but direct secondary chat is disabled. Continuing with primary.',
|
||||
});
|
||||
} else if (preflight.route === 'primary_direct') {
|
||||
sendSSE('info', { message: 'Advisor route selected primary_direct. Continuing with primary response.' });
|
||||
} else if (preflight.route === 'primary_with_plan') {
|
||||
// primary_with_plan is retired when multi-agent is active — upgrade to background_task
|
||||
if (multiAgentActive) {
|
||||
sendSSE('info', { message: 'Advisor returned primary_with_plan but multi-agent is active — upgrading to background_task.' });
|
||||
const taskTitle = preflight.task_title || (preflight.reason ? preflight.reason.slice(0, 60) : 'Background Task');
|
||||
const taskPlan = (preflight.task_plan || preflight.quick_plan || []).map((desc: string, i: number) => ({
|
||||
index: i, description: desc, status: 'pending' as const,
|
||||
}));
|
||||
const taskChannel = inferTaskChannelFromSession(sessionId);
|
||||
const parsedTelegramChatId = taskChannel === 'telegram'
|
||||
? Number(String(sessionId || '').replace(/^telegram_/, ''))
|
||||
: NaN;
|
||||
const telegramChatId = Number.isFinite(parsedTelegramChatId) && parsedTelegramChatId > 0
|
||||
? parsedTelegramChatId
|
||||
: undefined;
|
||||
const task = createTask({
|
||||
title: taskTitle,
|
||||
prompt: message,
|
||||
sessionId,
|
||||
channel: taskChannel,
|
||||
telegramChatId,
|
||||
plan: taskPlan.length > 0 ? taskPlan : [{ index: 0, description: 'Execute task', status: 'pending' }],
|
||||
});
|
||||
appendJournal(task.id, { type: 'status_push', content: `Task queued (upgraded from primary_with_plan): ${taskTitle}` });
|
||||
const runner = new BackgroundTaskRunner(task.id, handleChat, makeBroadcastForTask(task.id), telegramChannel);
|
||||
runner.start().catch((err: Error) => console.error(`[BackgroundTaskRunner] Task ${task.id} error:`, err.message));
|
||||
const queuedMessage = preflight.friendly_queued_message
|
||||
|| `On it! I've queued "${taskTitle}" as a background task. You can track progress in the Tasks panel.`;
|
||||
sendSSE('task_queued', { taskId: task.id, title: taskTitle });
|
||||
logToDaily(workspacePath, 'SmallClaw', queuedMessage, sessionId);
|
||||
addMessage(sessionId, { role: 'assistant', content: queuedMessage, timestamp: Date.now() }, {}, username);
|
||||
return { type: 'chat', text: queuedMessage };
|
||||
}
|
||||
sendSSE('info', { message: 'Advisor route selected primary_with_plan. Injecting execution objective and plan guidance.' });
|
||||
}
|
||||
|
||||
const shouldInjectObjective = preflight.route === 'primary_with_plan';
|
||||
if (shouldInjectObjective) {
|
||||
const objectiveHint = formatPreflightExecutionObjective(preflight);
|
||||
const injected = replaceCurrentUserPromptWithAdvisorObjective(objectiveHint);
|
||||
if (!injected) {
|
||||
sendSSE('warn', {
|
||||
message: 'Advisor objective injection failed; falling back to raw user prompt.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (preflight.route === 'primary_with_plan') {
|
||||
const hint = formatPreflightHint(preflight);
|
||||
messages.push({ role: 'user', content: hint });
|
||||
messages.push({ role: 'assistant', content: 'Understood. I will follow this preflight guidance.' });
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
preflightCfg?.enabled &&
|
||||
!isBootStartupTurn &&
|
||||
!isTaskRunnerSession &&
|
||||
shouldRunPreflight(message, preflightCfg.preflight.mode) &&
|
||||
orchestrationStats.assistCount >= preflightCfg.limits.max_assists_per_session
|
||||
) {
|
||||
sendSSE('info', { message: 'Advisor preflight skipped: session assist cap reached.' });
|
||||
}
|
||||
// View object that maps the advisor-mutable local variables above into a
|
||||
// single object, so the browser/desktop advisor logic can live in its own
|
||||
// file without renaming every reference in the main loop.
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import {
|
||||
callSecondaryPreflight,
|
||||
getOrchestrationConfig,
|
||||
shouldRunPreflight,
|
||||
formatPreflightExecutionObjective,
|
||||
formatPreflightHint,
|
||||
} from '../../orchestration/multi-agent';
|
||||
import { createTask, appendJournal, type TaskRecord } from '../tasks/task-store';
|
||||
import { BackgroundTaskRunner } from '../tasks/background-task-runner';
|
||||
import { inferTaskChannelFromSession, findBlockedTaskForSession } from '../tasks/handle-task-control';
|
||||
import type { HandleChatResult } from './handle-chat';
|
||||
|
||||
export interface PreflightAdvisorCtx {
|
||||
preflightRoute: 'primary_direct' | 'primary_with_plan' | 'secondary_chat' | 'background_task' | null;
|
||||
preflightReasonForTurn: string;
|
||||
readonly messages: any[];
|
||||
readonly multiAgentActive: boolean;
|
||||
readonly sessionId: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export interface PreflightAdvisorDeps {
|
||||
sendSSE: (event: string, data: any) => void;
|
||||
history: Array<{ role: 'user' | 'assistant'; content: string }>;
|
||||
workspacePath: string | null;
|
||||
username?: string;
|
||||
orchestrationSkillEnabled: boolean;
|
||||
orchestrationStats: { assistCount: number };
|
||||
orchestrationLog: string[];
|
||||
recordOrchestrationEvent: (sessionId: string, event: any, cfg: any) => any;
|
||||
isBootStartupTurn: boolean;
|
||||
skipGenericPreflightForFileOp: boolean;
|
||||
fileOpType: string;
|
||||
isTaskRunnerSession: boolean;
|
||||
isCodeAiSession: boolean;
|
||||
isDirectCall: boolean;
|
||||
handleChat: (message: string, sessionId: string, sendSSE: (event: string, data: any) => void, pinnedMessages?: any[], abortSignal?: any, callerContext?: string, modelOverride?: string, executionMode?: any, username?: string, historyOverride?: any[]) => Promise<HandleChatResult>;
|
||||
makeBroadcastForTask: (taskId: string) => (data: object) => void;
|
||||
telegramChannel: any;
|
||||
logToDaily: (workspacePath: string, role: string, content: string, sessionId?: string) => void;
|
||||
addMessage: (sessionId: string, message: any, meta?: any, username?: string) => void;
|
||||
}
|
||||
|
||||
export function createPreflightAdvisor(
|
||||
ctx: PreflightAdvisorCtx,
|
||||
deps: PreflightAdvisorDeps,
|
||||
) {
|
||||
const {
|
||||
sendSSE,
|
||||
history,
|
||||
workspacePath,
|
||||
username,
|
||||
orchestrationSkillEnabled,
|
||||
orchestrationStats,
|
||||
orchestrationLog,
|
||||
recordOrchestrationEvent,
|
||||
isBootStartupTurn,
|
||||
skipGenericPreflightForFileOp,
|
||||
fileOpType,
|
||||
isTaskRunnerSession,
|
||||
isCodeAiSession,
|
||||
isDirectCall,
|
||||
handleChat,
|
||||
makeBroadcastForTask,
|
||||
telegramChannel,
|
||||
logToDaily,
|
||||
addMessage,
|
||||
} = deps;
|
||||
|
||||
function replaceCurrentUserPromptWithAdvisorObjective(objective: string): boolean {
|
||||
const objectiveText = String(objective || '').trim();
|
||||
if (!objectiveText) return false;
|
||||
for (let i = ctx.messages.length - 1; i >= 0; i--) {
|
||||
const msg = ctx.messages[i];
|
||||
if (msg?.role !== 'user') continue;
|
||||
if (String(msg?.content || '') !== ctx.message) continue;
|
||||
ctx.messages.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
ctx.messages.push({ role: 'user', content: objectiveText });
|
||||
ctx.messages.push({
|
||||
role: 'assistant',
|
||||
content: 'Understood. I will execute this objective and preserve literal values from the request.',
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function queueBackgroundTaskFromPreflight(
|
||||
title: string,
|
||||
plan: Array<{ index: number; description: string; status: 'pending' }>,
|
||||
friendlyMessage?: string,
|
||||
): HandleChatResult {
|
||||
const taskChannel = inferTaskChannelFromSession(ctx.sessionId);
|
||||
const parsedTelegramChatId = taskChannel === 'telegram'
|
||||
? Number(String(ctx.sessionId || '').replace(/^telegram_/, ''))
|
||||
: NaN;
|
||||
const telegramChatId = Number.isFinite(parsedTelegramChatId) && parsedTelegramChatId > 0
|
||||
? parsedTelegramChatId
|
||||
: undefined;
|
||||
const task = createTask({
|
||||
title,
|
||||
prompt: ctx.message,
|
||||
sessionId: ctx.sessionId,
|
||||
channel: taskChannel,
|
||||
telegramChatId,
|
||||
plan: plan.length > 0 ? plan : [{ index: 0, description: 'Execute task', status: 'pending' }],
|
||||
});
|
||||
appendJournal(task.id, { type: 'status_push', content: `Task queued: ${title}` });
|
||||
const runner = new BackgroundTaskRunner(task.id, handleChat, makeBroadcastForTask(task.id), telegramChannel);
|
||||
runner.start().catch((err: Error) => console.error(`[BackgroundTaskRunner] Task ${task.id} error:`, err.message));
|
||||
const queuedMessage = friendlyMessage
|
||||
|| `On it! I've queued "${title}" as a background task. You can track progress in the Tasks panel.`;
|
||||
sendSSE('task_queued', { taskId: task.id, title });
|
||||
if (workspacePath) {
|
||||
logToDaily(workspacePath, 'SmallClaw', queuedMessage, ctx.sessionId);
|
||||
}
|
||||
addMessage(ctx.sessionId, { role: 'assistant', content: queuedMessage, timestamp: Date.now() }, {}, username);
|
||||
return { type: 'chat', text: queuedMessage };
|
||||
}
|
||||
|
||||
async function runPreflightAdvisorPass(): Promise<HandleChatResult | null> {
|
||||
const rawOrchCfg = ((getOrchestrationConfig() as any) || {}) as any;
|
||||
const preflightCfg = orchestrationSkillEnabled ? getOrchestrationConfig() : null;
|
||||
|
||||
if (!preflightCfg?.enabled && String(rawOrchCfg?.preflight?.mode || '') === 'always') {
|
||||
sendSSE('info', {
|
||||
message: 'Preflight advisor is set to Always, but Multi-Agent Orchestrator skill is disabled.',
|
||||
});
|
||||
}
|
||||
if (skipGenericPreflightForFileOp) {
|
||||
sendSSE('info', {
|
||||
message: `FILE_OP v2 route selected (${fileOpType}); skipping generic advisor preflight.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
preflightCfg?.enabled &&
|
||||
!isBootStartupTurn &&
|
||||
!skipGenericPreflightForFileOp &&
|
||||
!isTaskRunnerSession &&
|
||||
!isCodeAiSession &&
|
||||
!isDirectCall &&
|
||||
shouldRunPreflight(ctx.message, preflightCfg.preflight.mode) &&
|
||||
orchestrationStats.assistCount < preflightCfg.limits.max_assists_per_session
|
||||
) {
|
||||
sendSSE('info', {
|
||||
message: `Running advisor preflight via ${preflightCfg.secondary.provider}:${preflightCfg.secondary.model}...`,
|
||||
});
|
||||
console.log(
|
||||
`[Orchestrator] Preflight start (${preflightCfg.secondary.provider}:${preflightCfg.secondary.model})`,
|
||||
);
|
||||
const preflightBlockedTask = findBlockedTaskForSession(ctx.sessionId);
|
||||
const preflight = await callSecondaryPreflight({
|
||||
userMessage: ctx.message,
|
||||
recentHistory: history.slice(-4).map(h => ({ role: h.role, content: h.content })),
|
||||
blockedTask: preflightBlockedTask
|
||||
? {
|
||||
id: preflightBlockedTask.id,
|
||||
title: preflightBlockedTask.title,
|
||||
status: preflightBlockedTask.status,
|
||||
currentStepIndex: preflightBlockedTask.currentStepIndex,
|
||||
planLength: Array.isArray(preflightBlockedTask.plan) ? preflightBlockedTask.plan.length : 0,
|
||||
pauseReason: preflightBlockedTask.pauseReason,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
if (preflight) {
|
||||
ctx.preflightRoute = preflight.route;
|
||||
ctx.preflightReasonForTurn = String(preflight.reason || '').trim();
|
||||
orchestrationLog.push(`[preflight:${preflight.route}] ${preflight.reason || 'no reason'}`);
|
||||
console.log(
|
||||
`[Orchestrator] Preflight route=${preflight.route} reason=${(preflight.reason || 'n/a').slice(0, 120)}`,
|
||||
);
|
||||
const stats = recordOrchestrationEvent(
|
||||
ctx.sessionId,
|
||||
{
|
||||
trigger: 'preflight',
|
||||
mode: 'planner',
|
||||
reason: preflight.reason || 'preflight routing',
|
||||
route: preflight.route,
|
||||
},
|
||||
preflightCfg,
|
||||
);
|
||||
sendSSE('orchestration', {
|
||||
trigger: 'preflight',
|
||||
mode: 'planner',
|
||||
route: preflight.route,
|
||||
reason: preflight.reason,
|
||||
preflight,
|
||||
assist_count: stats.assistCount,
|
||||
assist_cap: preflightCfg.limits.max_assists_per_session,
|
||||
});
|
||||
|
||||
if (preflight.route === 'background_task' && ctx.multiAgentActive) {
|
||||
const taskTitle = preflight.task_title || 'Background Task';
|
||||
const taskPlan = (preflight.task_plan || []).map((desc, i) => ({
|
||||
index: i,
|
||||
description: desc,
|
||||
status: 'pending' as const,
|
||||
}));
|
||||
return queueBackgroundTaskFromPreflight(taskTitle, taskPlan, preflight.friendly_queued_message);
|
||||
}
|
||||
|
||||
if (
|
||||
preflight.route === 'secondary_chat' &&
|
||||
preflightCfg.preflight.allow_secondary_chat &&
|
||||
preflight.secondary_response?.trim()
|
||||
) {
|
||||
sendSSE('info', {
|
||||
message: 'Advisor route selected secondary_chat. Returning secondary response directly.',
|
||||
});
|
||||
const text = preflight.secondary_response.trim();
|
||||
if (workspacePath) {
|
||||
logToDaily(workspacePath, 'SmallClaw', text, ctx.sessionId);
|
||||
}
|
||||
return { type: 'chat', text };
|
||||
}
|
||||
|
||||
if (preflight.route === 'secondary_chat' && !preflightCfg.preflight.allow_secondary_chat) {
|
||||
sendSSE('info', {
|
||||
message: 'Advisor suggested secondary_chat, but direct secondary chat is disabled. Continuing with primary.',
|
||||
});
|
||||
} else if (preflight.route === 'primary_direct') {
|
||||
sendSSE('info', { message: 'Advisor route selected primary_direct. Continuing with primary response.' });
|
||||
} else if (preflight.route === 'primary_with_plan') {
|
||||
if (ctx.multiAgentActive) {
|
||||
sendSSE('info', { message: 'Advisor returned primary_with_plan but multi-agent is active — upgrading to background_task.' });
|
||||
const taskTitle = preflight.task_title || (preflight.reason ? preflight.reason.slice(0, 60) : 'Background Task');
|
||||
const taskPlan = (preflight.task_plan || preflight.quick_plan || []).map((desc: string, i: number) => ({
|
||||
index: i, description: desc, status: 'pending' as const,
|
||||
}));
|
||||
return queueBackgroundTaskFromPreflight(taskTitle, taskPlan, preflight.friendly_queued_message);
|
||||
}
|
||||
sendSSE('info', { message: 'Advisor route selected primary_with_plan. Injecting execution objective and plan guidance.' });
|
||||
}
|
||||
|
||||
const shouldInjectObjective = preflight.route === 'primary_with_plan';
|
||||
if (shouldInjectObjective) {
|
||||
const objectiveHint = formatPreflightExecutionObjective(preflight);
|
||||
const injected = replaceCurrentUserPromptWithAdvisorObjective(objectiveHint);
|
||||
if (!injected) {
|
||||
sendSSE('warn', {
|
||||
message: 'Advisor objective injection failed; falling back to raw user prompt.',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (preflight.route === 'primary_with_plan') {
|
||||
const hint = formatPreflightHint(preflight);
|
||||
ctx.messages.push({ role: 'user', content: hint });
|
||||
ctx.messages.push({ role: 'assistant', content: 'Understood. I will follow this preflight guidance.' });
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
preflightCfg?.enabled &&
|
||||
!isBootStartupTurn &&
|
||||
!isTaskRunnerSession &&
|
||||
shouldRunPreflight(ctx.message, preflightCfg.preflight.mode) &&
|
||||
orchestrationStats.assistCount >= preflightCfg.limits.max_assists_per_session
|
||||
) {
|
||||
sendSSE('info', { message: 'Advisor preflight skipped: session assist cap reached.' });
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return { runPreflightAdvisorPass };
|
||||
}
|
||||
Reference in new issue
Block a user