-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-node.mjs
More file actions
160 lines (140 loc) · 4.05 KB
/
agent-node.mjs
File metadata and controls
160 lines (140 loc) · 4.05 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
#!/usr/bin/env node
/**
* LOGAN Chat Agent — Node.js
*
* A complete, runnable agent that chats with the user through LOGAN's Chat tab.
* Uses the HTTP API directly — no dependencies beyond Node.js (v18+).
*
* Usage:
* node examples/agent-node.mjs
*
* Prerequisites:
* - LOGAN is running with a file open
*/
import { readFileSync } from 'fs';
import { join } from 'path';
import { homedir } from 'os';
import http from 'http';
import { matchIntent, isStopWord, HELP_TEXT } from './agent-intents.mjs';
// --- Config ---
const PORT_FILE = join(homedir(), '.logan', 'mcp-port');
const WAIT_TIMEOUT = 300; // seconds
// --- Read LOGAN port ---
let port;
try {
port = parseInt(readFileSync(PORT_FILE, 'utf-8').trim(), 10);
} catch {
console.error(`ERROR: LOGAN is not running (no ${PORT_FILE})`);
process.exit(1);
}
const BASE = `http://127.0.0.1:${port}`;
// --- HTTP helpers ---
function apiCall(method, path, body) {
return new Promise((resolve, reject) => {
const payload = body ? JSON.stringify(body) : undefined;
const req = http.request(
{
hostname: '127.0.0.1',
port,
path,
method,
headers: {
'Content-Type': 'application/json',
...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
},
timeout: 60000,
},
(res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch {
reject(new Error('Invalid JSON response'));
}
});
}
);
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
if (payload) req.write(payload);
req.end();
});
}
async function sendMessage(text) {
await apiCall('POST', '/api/agent-message', { message: text });
console.log(`[agent] ${text}`);
}
/**
* Wait for a user message via SSE. Returns the message text,
* or null on timeout.
*/
function waitForMessage(timeoutSec = 120) {
return new Promise((resolve) => {
const timer = setTimeout(() => {
req.destroy();
resolve(null);
}, timeoutSec * 1000);
const req = http.get(
{
hostname: '127.0.0.1',
port,
path: '/api/events?name=LOGAN%20Built-in%20Agent',
headers: { Accept: 'text/event-stream' },
},
(res) => {
let buf = '';
res.on('data', (chunk) => {
buf += chunk.toString();
const frames = buf.split('\n\n');
buf = frames.pop(); // keep incomplete tail
for (const frame of frames) {
const dataLine = frame.split('\n').find((l) => l.startsWith('data: '));
if (!dataLine) continue;
try {
const msg = JSON.parse(dataLine.slice(6));
if (msg.from === 'user') {
clearTimeout(timer);
req.destroy();
resolve(msg.text);
return;
}
} catch { /* ignore */ }
}
});
res.on('end', () => {
clearTimeout(timer);
resolve(null);
});
}
);
req.on('error', () => {
clearTimeout(timer);
resolve(null);
});
});
}
// --- Main loop ---
console.log('=== LOGAN Chat Agent (Node.js) ===');
console.log(`Connecting to LOGAN on port ${port}...`);
await sendMessage("Hi! I'm a LOGAN agent. " + HELP_TEXT.split('\n')[0]);
while (true) {
console.log('[waiting for user message...]');
const userMsg = await waitForMessage(WAIT_TIMEOUT);
if (userMsg === null) {
await sendMessage('Session timed out. Run me again when ready!');
console.log('Timed out. Exiting.');
break;
}
console.log(`[user] ${userMsg}`);
if (isStopWord(userMsg)) {
await sendMessage('Goodbye!');
console.log('User ended the session.');
break;
}
// Dispatch to intent engine
const response = await matchIntent(userMsg, apiCall);
await sendMessage(response);
}
console.log('=== Agent exited ===');