-
Notifications
You must be signed in to change notification settings - Fork 447
Expand file tree
/
Copy pathindex.ts
More file actions
332 lines (288 loc) · 12.7 KB
/
Copy pathindex.ts
File metadata and controls
332 lines (288 loc) · 12.7 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
/**
* streaming-chat — Interactive Multi-Agent Streaming Chat
*
* Squad SDK sample for MVP Summit.
* Demonstrates: SquadClientWithPool, CastingEngine, SessionPool,
* EventBus, StreamingPipeline, and readline-based interactive chat.
*
* Run with `npx tsx index.ts` (live Copilot) or set SQUAD_DEMO_MODE=true
* for a self-contained demo that simulates streaming without auth.
*/
import * as readline from 'node:readline';
// SDK barrel exports: CastingEngine, StreamingPipeline
import { CastingEngine, StreamingPipeline } from '@bradygaster/squad-sdk';
import type { StreamDelta } from '@bradygaster/squad-sdk';
// Client sub-path exports: SquadClientWithPool, EventBus
import { SquadClientWithPool, EventBus } from '@bradygaster/squad-sdk/client';
// ────────────────────────────────────────────────────────────────────────────
// Agent definitions
// ────────────────────────────────────────────────────────────────────────────
interface AgentInfo {
name: string;
role: string;
color: string;
keywords: string[];
sessionId?: string;
systemPrompt: string;
}
const AGENTS: AgentInfo[] = [
{
name: 'McManus',
role: 'Backend',
color: '\x1b[36m', // cyan
keywords: ['api', 'server', 'database', 'backend', 'endpoint', 'rest', 'sql', 'auth'],
systemPrompt: 'You are McManus, a bold backend engineer. Keep answers concise and code-focused.',
},
{
name: 'Kobayashi',
role: 'Frontend',
color: '\x1b[35m', // magenta
keywords: ['ui', 'frontend', 'component', 'css', 'react', 'style', 'layout', 'ux'],
systemPrompt: 'You are Kobayashi, a precise frontend designer. Respond with clean, visual solutions.',
},
{
name: 'Fenster',
role: 'Tester',
color: '\x1b[33m', // yellow
keywords: ['test', 'bug', 'qa', 'coverage', 'assert', 'fixture', 'mock', 'spec'],
systemPrompt: 'You are Fenster, an eccentric tester. You find bugs nobody else can see.',
},
];
const RESET = '\x1b[0m';
const DIM = '\x1b[2m';
const BOLD = '\x1b[1m';
// ────────────────────────────────────────────────────────────────────────────
// Routing — match message to an agent by keyword
// ────────────────────────────────────────────────────────────────────────────
function routeMessage(message: string): AgentInfo {
const lower = message.toLowerCase();
for (const agent of AGENTS) {
if (agent.keywords.some((kw) => lower.includes(kw))) {
return agent;
}
}
// Default to the first agent (Backend)
return AGENTS[0];
}
// ────────────────────────────────────────────────────────────────────────────
// Demo mode — simulated streaming when Copilot auth is unavailable
// ────────────────────────────────────────────────────────────────────────────
const DEMO_RESPONSES: Record<string, string[]> = {
Backend: [
"Sure thing. I'd scaffold that with an Express router — `app.post('/api/users', validate(schema), async (req, res) => { ... })`. Want me to wire up the Postgres pool too?",
"The connection pool is the bottleneck. Switch to `pg-pool` with `max: 20` and add a health-check endpoint at `/api/health` that pings the DB.",
"For auth, I'd use JWT with short-lived access tokens (15 min) and a refresh token rotation. The middleware hooks into `req.user` before any route handler fires.",
],
Frontend: [
"Clean layout here: a flex container with `gap: 1rem`, the sidebar at `width: 280px`, and the main content area filling the rest. Dark mode toggles via a CSS custom property on `:root`.",
"I'd reach for a compound component pattern — `<Tabs>`, `<Tabs.List>`, `<Tabs.Panel>`. Keep state in context, expose it via `useTabsContext()`. No prop drilling.",
"For the loading skeleton, use `@keyframes shimmer` with a linear gradient. It's lighter than a spinner and feels more polished during data fetches.",
],
Tester: [
"That function has no edge-case coverage. What happens when `input` is an empty string? Or `null`? I'd add at least 3 boundary tests before shipping.",
"The mock is too loose — `vi.fn().mockResolvedValue({})` hides real failures. Use `vi.fn().mockResolvedValue({ id: 1, name: 'test' })` so the shape matches prod.",
"Coverage says 94% but the missing 6% is the error path. Add a test that forces the API call to reject and verify the error boundary catches it.",
],
};
function getDemoResponse(role: string): string {
const responses = DEMO_RESPONSES[role] ?? DEMO_RESPONSES['Backend'];
return responses[Math.floor(Math.random() * responses.length)];
}
async function simulateStreaming(
pipeline: StreamingPipeline,
agent: AgentInfo,
_message: string,
): Promise<void> {
const sessionId = agent.sessionId ?? `demo-${agent.role.toLowerCase()}`;
const response = getDemoResponse(agent.role);
const words = response.split(' ');
pipeline.markMessageStart(sessionId);
for (let i = 0; i < words.length; i++) {
const chunk = (i === 0 ? '' : ' ') + words[i];
const delta: StreamDelta = {
type: 'message_delta',
sessionId,
agentName: agent.name,
content: chunk,
index: i,
timestamp: new Date(),
};
await pipeline.processEvent(delta);
// Simulate token-by-token delay (40–80 ms per word)
await new Promise((r) => setTimeout(r, 40 + Math.random() * 40));
}
}
// ────────────────────────────────────────────────────────────────────────────
// Live mode — real Copilot SDK sessions
// ────────────────────────────────────────────────────────────────────────────
async function sendLiveMessage(
client: SquadClientWithPool,
pipeline: StreamingPipeline,
agent: AgentInfo,
message: string,
): Promise<void> {
const sessionId = agent.sessionId;
if (!sessionId) {
console.error(` ${DIM}(no session for ${agent.name})${RESET}`);
return;
}
pipeline.markMessageStart(sessionId);
// Retrieve the session from the pool and send
const sessions = await client.listSessions();
const meta = sessions.find((s) => s.sessionId === sessionId);
if (!meta) {
console.error(` ${DIM}(session ${sessionId} not found)${RESET}`);
return;
}
// Resume the session to get a SquadSession handle, then send
const session = await client.resumeSession(sessionId);
// Register delta listener to feed the pipeline
const handler = (event: { type: string; [key: string]: unknown }) => {
if (event.type === 'message_delta') {
const content =
(event['deltaContent'] as string) ??
(event['delta'] as string) ??
(event['content'] as string) ??
'';
if (content) {
void pipeline.processEvent({
type: 'message_delta',
sessionId: sessionId!,
agentName: agent.name,
content,
index: typeof event['index'] === 'number' ? event['index'] : 0,
timestamp: new Date(),
});
}
}
};
session.on('message_delta', handler);
try {
if (session.sendAndWait) {
await session.sendAndWait({ prompt: message }, 120_000);
} else {
await session.sendMessage({ prompt: message });
}
} finally {
session.off('message_delta', handler);
}
}
// ────────────────────────────────────────────────────────────────────────────
// Main
// ────────────────────────────────────────────────────────────────────────────
export async function main(): Promise<void> {
const demoMode = process.env['SQUAD_DEMO_MODE'] === 'true';
// ── Banner ──
console.log();
console.log(`${BOLD} ╔═══════════════════════════════════════════════╗${RESET}`);
console.log(`${BOLD} ║ 🎬 Squad Streaming Chat · MVP Summit ║${RESET}`);
console.log(`${BOLD} ╚═══════════════════════════════════════════════╝${RESET}`);
console.log();
// ── Cast agents ──
const casting = new CastingEngine();
const cast = casting.castTeam({
universe: 'usual-suspects',
requiredRoles: ['developer', 'designer', 'tester'],
});
console.log(` ${DIM}Cast:${RESET}`);
for (const member of cast) {
const match = AGENTS.find((a) => a.name === member.name);
if (match) {
console.log(` ${match.color}● ${member.name}${RESET} — ${member.role} ${DIM}(${member.personality})${RESET}`);
}
}
console.log();
// ── Streaming pipeline ──
const pipeline = new StreamingPipeline();
let currentLine = '';
pipeline.onDelta((event) => {
currentLine += event.content;
process.stdout.write(event.content);
});
// ── Client + sessions ──
let client: SquadClientWithPool | null = null;
const eventBus = new EventBus();
if (!demoMode) {
try {
client = new SquadClientWithPool({ pool: { maxConcurrent: 5 } });
await client.connect();
// Create a session per agent
for (const agent of AGENTS) {
const session = await client.createSession({
streaming: true,
systemMessage: { mode: 'append', content: agent.systemPrompt },
});
agent.sessionId = session.sessionId;
pipeline.attachToSession(session.sessionId);
}
// Wire EventBus
client.eventBus.onAny((event) => {
void eventBus.emit({
type: event.type as 'session.created',
sessionId: event.sessionId,
payload: event.payload,
timestamp: event.timestamp,
});
});
console.log(` ${DIM}Connected to Copilot — live mode${RESET}`);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.log(` ${DIM}⚠ Could not connect to Copilot: ${msg}${RESET}`);
console.log(` ${DIM} Falling back to demo mode (simulated streaming)${RESET}`);
client = null;
}
}
if (!client) {
// Demo-mode session IDs for pipeline attachment
for (const agent of AGENTS) {
agent.sessionId = `demo-${agent.role.toLowerCase()}`;
pipeline.attachToSession(agent.sessionId);
}
console.log(` ${DIM}Running in demo mode — responses are simulated${RESET}`);
}
console.log(` ${DIM}Type a message. Use /quit to exit.${RESET}`);
console.log(` ${DIM}Keyword routing: api/server → Backend · ui/react → Frontend · test/bug → Tester${RESET}`);
console.log();
// ── Readline loop ──
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: `${BOLD} ◆ you >${RESET} `,
});
rl.prompt();
for await (const line of rl) {
const input = line.trim();
if (!input) {
rl.prompt();
continue;
}
if (input === '/quit') {
console.log(`\n ${DIM}👋 Goodbye!${RESET}\n`);
break;
}
// Route
const agent = routeMessage(input);
console.log(`\n ${agent.color}${BOLD}${agent.name}${RESET} ${DIM}(${agent.role})${RESET}`);
process.stdout.write(' ');
currentLine = '';
// Stream response
if (client) {
await sendLiveMessage(client, pipeline, agent, input);
} else {
await simulateStreaming(pipeline, agent, input);
}
console.log('\n');
rl.prompt();
}
// ── Cleanup ──
rl.close();
if (client) {
await client.shutdown();
}
pipeline.clear();
}
// Run
main().catch((err) => {
console.error('Fatal error:', err);
process.exit(1);
});