-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathtest-client.ts
More file actions
338 lines (286 loc) Β· 8.88 KB
/
test-client.ts
File metadata and controls
338 lines (286 loc) Β· 8.88 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env -S deno run --allow-net --allow-env
/**
* Test client for elizaOS Supabase Edge Functions
*
* Usage:
* # Test local function
* deno run --allow-net --allow-env test-client.ts
*
* # Test deployed function
* deno run --allow-net --allow-env test-client.ts --endpoint https://your-project.supabase.co/functions/v1/eliza-chat
*
* # Interactive mode
* deno run --allow-net --allow-env test-client.ts --interactive
*/
// ============================================================================
// Configuration
// ============================================================================
interface Config {
endpoint: string;
authToken: string;
interactive: boolean;
}
function parseArgs(): Config {
const args = Deno.args;
let endpoint =
Deno.env.get("SUPABASE_FUNCTION_URL") ??
"http://localhost:54321/functions/v1/eliza-chat";
let authToken = Deno.env.get("SUPABASE_ANON_KEY") ?? "";
let interactive = false;
for (let i = 0; i < args.length; i++) {
if (args[i] === "--endpoint" && args[i + 1]) {
endpoint = args[i + 1];
i++;
} else if (args[i] === "--token" && args[i + 1]) {
authToken = args[i + 1];
i++;
} else if (args[i] === "--interactive" || args[i] === "-i") {
interactive = true;
} else if (args[i] === "--help" || args[i] === "-h") {
printHelp();
Deno.exit(0);
}
}
return { endpoint, authToken, interactive };
}
function printHelp(): void {
console.log(`
elizaOS Supabase Edge Function Test Client
Usage:
deno run --allow-net --allow-env test-client.ts [options]
Options:
--endpoint <url> Function endpoint URL (default: http://localhost:54321/functions/v1/eliza-chat)
--token <key> Supabase anon key for authorization
--interactive, -i Start interactive chat mode
--help, -h Show this help message
Environment Variables:
SUPABASE_FUNCTION_URL Default function endpoint
SUPABASE_ANON_KEY Default auth token
Examples:
# Test local function
deno run --allow-net --allow-env test-client.ts
# Test deployed function
deno run --allow-net --allow-env test-client.ts \\
--endpoint https://your-project.supabase.co/functions/v1/eliza-chat \\
--token your-anon-key
# Interactive mode
deno run --allow-net --allow-env test-client.ts --interactive
`);
}
// ============================================================================
// HTTP Client
// ============================================================================
interface ChatRequest {
message: string;
userId?: string;
conversationId?: string;
}
interface ChatResponse {
response: string;
conversationId: string;
timestamp: string;
}
interface HealthResponse {
status: string;
runtime: string;
version: string;
}
async function sendRequest<T>(
config: Config,
method: string,
path: string,
body?: Record<string, unknown>,
): Promise<{ status: number; data: T }> {
const url = `${config.endpoint}${path}`;
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (config.authToken) {
headers.Authorization = `Bearer ${config.authToken}`;
}
const response = await fetch(url, {
method,
headers,
body: body ? JSON.stringify(body) : undefined,
});
const data = (await response.json()) as T;
return { status: response.status, data };
}
async function healthCheck(config: Config): Promise<HealthResponse> {
const { status, data } = await sendRequest<HealthResponse>(
config,
"GET",
"/health",
);
if (status !== 200) {
throw new Error(`Health check failed with status ${status}`);
}
return data;
}
interface ErrorResponse {
error: string;
}
function isErrorResponse(data: unknown): data is ErrorResponse {
return typeof data === "object" && data !== null && "error" in data;
}
async function sendMessage(
config: Config,
request: ChatRequest,
): Promise<ChatResponse> {
const { status, data } = await sendRequest<ChatResponse | ErrorResponse>(
config,
"POST",
"",
request,
);
if (status !== 200) {
const errorMsg = isErrorResponse(data)
? data.error
: `Request failed with status ${status}`;
throw new Error(errorMsg);
}
return data as ChatResponse;
}
// ============================================================================
// Test Suite
// ============================================================================
async function runTests(config: Config): Promise<void> {
console.log("π§ͺ Testing elizaOS Supabase Edge Function\n");
console.log(` Endpoint: ${config.endpoint}`);
console.log(
` Auth: ${config.authToken ? "β Token provided" : "β No token"}\n`,
);
let passed = 0;
let failed = 0;
// Test 1: Health check
console.log("1οΈβ£ Testing health check...");
try {
const health = await healthCheck(config);
console.log(` Status: ${health.status}`);
console.log(` Runtime: ${health.runtime}`);
console.log(` Version: ${health.version}`);
console.log(" β
Health check passed\n");
passed++;
} catch (error) {
console.error(` β Health check failed: ${error}`);
failed++;
}
// Test 2: Chat message
console.log("2οΈβ£ Testing chat endpoint...");
const startTime = Date.now();
try {
const response = await sendMessage(config, {
message: "Hello! What's 2 + 2?",
});
const duration = Date.now() - startTime;
console.log(` Duration: ${duration}ms`);
console.log(` Response: ${response.response.slice(0, 100)}...`);
console.log(` Conversation ID: ${response.conversationId}`);
console.log(" β
Chat endpoint passed\n");
passed++;
} catch (error) {
console.error(` β Chat endpoint failed: ${error}`);
failed++;
}
// Test 3: Validation (empty message)
console.log("3οΈβ£ Testing validation (empty message)...");
try {
await sendMessage(config, { message: "" });
console.error(" β Should have rejected empty message");
failed++;
} catch (error) {
if (
String(error).includes("required") ||
String(error).includes("non-empty")
) {
console.log(
" β
Validation passed (correctly rejected empty message)\n",
);
passed++;
} else {
console.error(` β Unexpected error: ${error}`);
failed++;
}
}
// Test 4: Conversation continuity
console.log("4οΈβ£ Testing conversation ID tracking...");
try {
const response1 = await sendMessage(config, {
message: "Remember the number 42.",
});
const convId = response1.conversationId;
const response2 = await sendMessage(config, {
message: "What number did I mention?",
conversationId: convId,
});
console.log(
` Conversation ID preserved: ${response2.conversationId === convId}`,
);
console.log(" β
Conversation tracking passed\n");
passed++;
} catch (error) {
console.error(` β Conversation tracking failed: ${error}`);
failed++;
}
// Summary
console.log("β".repeat(50));
console.log(`\nπ Results: ${passed} passed, ${failed} failed`);
if (failed > 0) {
console.log(
"\nβ οΈ Some tests failed. Check your configuration and try again.",
);
Deno.exit(1);
} else {
console.log("\nπ All tests passed!");
}
}
// ============================================================================
// Interactive Mode
// ============================================================================
async function interactiveMode(config: Config): Promise<void> {
console.log("π€ elizaOS Supabase Edge Function - Interactive Mode\n");
console.log(` Endpoint: ${config.endpoint}`);
console.log(" Type 'exit' or 'quit' to end the session.\n");
let conversationId: string | undefined;
const decoder = new TextDecoder();
const encoder = new TextEncoder();
while (true) {
// Prompt
await Deno.stdout.write(encoder.encode("You: "));
// Read input
const buf = new Uint8Array(1024);
const n = await Deno.stdin.read(buf);
if (n === null) break;
const input = decoder.decode(buf.subarray(0, n)).trim();
if (input === "exit" || input === "quit") {
console.log("\nGoodbye! π");
break;
}
if (!input) continue;
try {
const response = await sendMessage(config, {
message: input,
conversationId,
});
conversationId = response.conversationId;
console.log(`\nEliza: ${response.response}\n`);
} catch (error) {
console.error(`\nError: ${error}\n`);
}
}
}
// ============================================================================
// Main
// ============================================================================
async function main(): Promise<void> {
const config = parseArgs();
if (config.interactive) {
await interactiveMode(config);
} else {
await runTests(config);
}
}
main().catch((error) => {
console.error("Fatal error:", error);
Deno.exit(1);
});