feat: wake agent via gateway WebSocket API instead of api.spawn

Replace non-existent api.spawn with direct WebSocket call to
gateway "agent" method — the same mechanism used by sessions_spawn
and cron internally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
operator
2026-04-19 05:31:13 +00:00
parent 2d3d24b0ac
commit ce61834738

View File

@@ -188,56 +188,94 @@ export default {
} }
/** /**
* Wake/spawn agent with task context for slot execution. * Wake agent via gateway WebSocket API.
* This is the callback invoked by CalendarScheduler when a slot is ready. * Uses callGateway("agent") to trigger an agent turn — the same mechanism
* used by sessions_spawn and cron internally.
*/ */
async function wakeAgent(context: AgentWakeContext): Promise<boolean> { async function wakeAgent(context: AgentWakeContext): Promise<boolean> {
logger.info(`Waking agent for slot: ${context.taskDescription}`); logger.info(`Waking agent for slot: ${context.taskDescription}`);
const agentId = process.env.AGENT_ID || 'unknown';
try { try {
// Method 1: Use OpenClaw spawn API if available (preferred) // Connect to gateway via WebSocket and trigger an agent turn
if (api.spawn) { const gatewayUrl = 'ws://127.0.0.1:18789';
const result = await api.spawn({ const ws = await import('ws');
task: context.prompt, const WebSocket = ws.default || ws.WebSocket || ws;
timeoutSeconds: context.slot.estimated_duration * 60, // Convert to seconds
const result = await new Promise<{ sessionId?: string; error?: string }>((resolve, reject) => {
const timeout = setTimeout(() => {
client.close();
reject(new Error('Gateway connection timeout'));
}, 15000);
const client = new WebSocket(gatewayUrl);
client.on('error', (err: Error) => {
clearTimeout(timeout);
reject(err);
}); });
if (result?.sessionId) { client.on('open', () => {
logger.info(`Agent spawned for calendar slot: session=${result.sessionId}`); // Send hello
client.send(JSON.stringify({
jsonrpc: '2.0',
method: 'hello',
params: {
clientName: 'harbor-forge-calendar',
mode: 'backend',
},
id: 1,
}));
});
// Track session completion let helloAcked = false;
trackSessionCompletion(result.sessionId, context);
return true;
}
}
// Method 2: Send notification/alert to wake agent (fallback) client.on('message', (data: Buffer | string) => {
// This relies on the agent's heartbeat to check for notifications try {
logger.warn('OpenClaw spawn API not available, using notification fallback'); const msg = JSON.parse(data.toString());
// Send calendar wakeup notification via backend if (!helloAcked && msg.id === 1) {
const live = resolveConfig(); helloAcked = true;
const agentId = process.env.AGENT_ID || 'unknown'; // Send agent turn request
client.send(JSON.stringify({
jsonrpc: '2.0',
method: 'agent',
params: {
message: context.prompt,
agentId,
timeoutSeconds: context.slot.estimated_duration * 60,
},
id: 2,
}));
return;
}
const notifyResponse = await fetch(`${live.backendUrl}/calendar/agent/notify`, { if (msg.id === 2) {
method: 'POST', clearTimeout(timeout);
headers: { client.close();
'Content-Type': 'application/json', if (msg.error) {
'X-Agent-ID': agentId, resolve({ error: msg.error.message || JSON.stringify(msg.error) });
'X-Claw-Identifier': live.identifier || hostname(), } else {
}, resolve({ sessionId: msg.result?.sessionId || 'ok' });
body: JSON.stringify({ }
agent_id: agentId, }
message: context.prompt, } catch {
slot_id: context.slot.id || context.slot.virtual_id, // ignore parse errors
task_description: context.taskDescription, }
}), });
}); });
return notifyResponse.ok; if (result.error) {
logger.error(`Gateway agent call failed: ${result.error}`);
return false;
}
logger.info(`Agent woken via gateway for slot: session=${result.sessionId}`);
return true;
} catch (err) { } catch (err) {
logger.error('Failed to wake agent:', err); logger.error('Failed to wake agent via gateway:', err);
return false; return false;
} }
} }