tycono 0.1.96-beta.4 → 0.1.96-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  <p align="center">
2
- <img src=".github/assets/hero-office.png" alt="Tycono — AI Office" width="720" />
2
+ <img src=".github/assets/wave-org-propagation.png" alt="Tycono — CEO dispatches through org hierarchy in real time" width="720" />
3
3
  </p>
4
4
 
5
5
  <h1 align="center">tycono</h1>
6
6
 
7
7
  <p align="center">
8
- <strong>Build an AI company. Watch them work.</strong><br>
9
- <sub>Infrastructure-as-Code defined servers. Company-as-Code defines organizations.</sub>
8
+ <strong>Cursor gives you one AI developer. Tycono gives you an AI team.</strong><br>
9
+ <sub>Give one order. Watch your AI team plan, build, and learn together.</sub>
10
10
  </p>
11
11
 
12
12
  <p align="center">
@@ -25,9 +25,11 @@
25
25
 
26
26
  ---
27
27
 
28
- **tycono** is an open-source platform that lets you define and run an AI-powered organization. Roles, authority, knowledge, and workflows all defined in files, executed by AI agents, visualized in real time.
28
+ Cursor, Lovable, Bolt they all give you **one AI agent**. It helps, but you still drive everything.
29
29
 
30
- One command. Your AI company is running.
30
+ **tycono** gives you an **AI team**. A CTO reviews architecture. Engineers write code. A PM breaks down tasks. QA catches bugs. You just give the order and watch them work.
31
+
32
+ One command. Your AI team is running.
31
33
 
32
34
  ```bash
33
35
  npx tycono
@@ -45,6 +47,10 @@ dispatch → watch → relay → quality gate → re-dispatch (if needed)
45
47
 
46
48
  CEO delegates to C-levels, C-levels dispatch to their teams. Authority is enforced — engineers can't make CEO decisions, PMs can't merge code. The org chart isn't decoration, it's the execution engine.
47
49
 
50
+ <p align="center">
51
+ <img src=".github/assets/wave-org-propagation.png" alt="Wave Center — org propagation with real-time status" width="640" />
52
+ </p>
53
+
48
54
  ### 2. Observability — See everything, intervene anytime
49
55
 
50
56
  Your AI team isn't a black box. Watch every agent work in real time, inject directives mid-execution, and drill down to any level.
@@ -79,16 +85,16 @@ Session 50 is dramatically smarter than session 1. Your company learns.
79
85
 
80
86
  ## Why Tycono?
81
87
 
82
- Coding agents simulate **one developer**. Tycono simulates **the entire company**.
88
+ Same goal as Cursor, Lovable, Bolt **get AI to do your work**. Different method.
83
89
 
84
- | | Single AI Agent | Tycono |
90
+ | | Cursor / Lovable / Bolt | Tycono |
85
91
  |---|---|---|
86
- | **What it runs** | One agent, one context | Multiple roles with org hierarchy |
87
- | **Knowledge** | Resets every session | Compounds forever (AKB Pre-K/Post-K) |
88
- | **Authority** | Can do anything (or nothing) | Scoped each role has clear boundaries |
89
- | **Delegation** | Manual prompt chaining | CEO dispatches, org chart routes automatically |
90
- | **Scale** | 1 agent | 7 700 agents |
91
- | **Visibility** | Terminal output | Real-time org tree + activity stream |
92
+ | **Agents** | 1 AI helps you | **AI team works for you** |
93
+ | **Your role** | Keep directing | **Give one order, watch** |
94
+ | **Knowledge** | Resets every session | **Compounds forever** |
95
+ | **Quality** | You review everything | **QA agent catches bugs** |
96
+ | **Scale** | 1 task at a time | **Parallel across roles** |
97
+ | **Visibility** | Editor / chat | **Real-time org tree** |
92
98
 
93
99
  ## Company-as-Code
94
100
 
@@ -254,9 +260,9 @@ npx tycono --version # Show version
254
260
  - [x] CEO Wave dispatch with org-tree targeting
255
261
  - [x] AKB — Pre-K / Post-K knowledge loop
256
262
  - [x] Port Registry for multi-agent isolation
257
- - [ ] **TUI mode** — terminal-native multi-panel interface
263
+ - [ ] **TUI mode** — terminal-native multi-panel interface *(in progress)*
258
264
  - [ ] Git worktree isolation per agent session
259
- - [ ] Desktop app (.dmg / .exe) — background execution, system notifications
265
+ - [ ] **Desktop app** (.dmg / .exe) — background execution, notifications, no API key setup needed
260
266
  - [ ] Multi-LLM support (OpenAI, local models)
261
267
 
262
268
  ## Built with Tycono
package/bin/tycono.ts CHANGED
@@ -213,6 +213,27 @@ async function startServerForTui(): Promise<void> {
213
213
  const port = process.env.PORT ? Number(process.env.PORT) : await findFreePort();
214
214
  process.env.PORT = String(port);
215
215
 
216
+ // Suppress ALL server output BEFORE creating server — hijack process streams
217
+ const logFile = path.resolve(process.env.COMPANY_ROOT || process.cwd(), '.tycono', 'server.log');
218
+ try { fs.mkdirSync(path.dirname(logFile), { recursive: true }); } catch {}
219
+ const logFd = fs.openSync(logFile, 'a');
220
+ const logStream = fs.createWriteStream(logFile, { fd: logFd });
221
+ const origStdoutWrite = process.stdout.write.bind(process.stdout);
222
+ const origStderrWrite = process.stderr.write.bind(process.stderr);
223
+ // Intercept all stdout/stderr — only allow Ink's output (ANSI escape sequences)
224
+ const isInkOutput = (s: string) => s.includes('\x1b[') || s.includes('\x1b(');
225
+ process.stdout.write = ((chunk: any, ...args: any[]) => {
226
+ const str = typeof chunk === 'string' ? chunk : chunk.toString();
227
+ if (isInkOutput(str)) return origStdoutWrite(chunk, ...args);
228
+ logStream.write(str);
229
+ return true;
230
+ }) as any;
231
+ process.stderr.write = ((chunk: any, ...args: any[]) => {
232
+ logStream.write(typeof chunk === 'string' ? chunk : chunk.toString());
233
+ return true;
234
+ }) as any;
235
+ const origLog = (...args: unknown[]) => origStdoutWrite(args.join(' ') + '\n');
236
+
216
237
  const { createHttpServer } = await import('../src/api/src/create-server.js');
217
238
  const server = createHttpServer();
218
239
 
@@ -222,17 +243,6 @@ async function startServerForTui(): Promise<void> {
222
243
  server.listen(port, host, () => resolve());
223
244
  });
224
245
 
225
- // Suppress API server logs in TUI mode — redirect to file
226
- const logFile = path.resolve(process.env.COMPANY_ROOT || process.cwd(), '.tycono', 'server.log');
227
- try { fs.mkdirSync(path.dirname(logFile), { recursive: true }); } catch {}
228
- const logStream = fs.createWriteStream(logFile, { flags: 'a' });
229
- const origLog = console.log;
230
- const origErr = console.error;
231
- const origWarn = console.warn;
232
- console.log = (...args: unknown[]) => logStream.write(args.join(' ') + '\n');
233
- console.error = (...args: unknown[]) => logStream.write('[ERROR] ' + args.join(' ') + '\n');
234
- console.warn = (...args: unknown[]) => logStream.write('[WARN] ' + args.join(' ') + '\n');
235
-
236
246
  origLog(` API server started on port ${port}`);
237
247
  origLog(` Logs: ${logFile}`);
238
248
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tycono",
3
- "version": "0.1.96-beta.4",
3
+ "version": "0.1.96-beta.40",
4
4
  "description": "Build an AI company. Watch them work.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -6,6 +6,7 @@
6
6
  import { Router } from 'express';
7
7
  import { portRegistry } from '../services/port-registry.js';
8
8
  import { executionManager } from '../services/execution-manager.js';
9
+ import { getSession } from '../services/session-store.js';
9
10
 
10
11
  export const activeSessionsRouter = Router();
11
12
 
@@ -17,8 +18,10 @@ activeSessionsRouter.get('/', (_req, res) => {
17
18
 
18
19
  const enriched = sessions.map(s => {
19
20
  const exec = executionManager.getActiveExecution(s.sessionId);
21
+ const session = getSession(s.sessionId);
20
22
  return {
21
23
  ...s,
24
+ waveId: session?.waveId ?? null,
22
25
  messageStatus: exec?.status ?? null,
23
26
  roleName: exec?.roleId ?? s.roleId,
24
27
  alive: s.pid ? isAlive(s.pid) : null,
@@ -212,10 +212,8 @@ function handleStartJob(body: Record<string, unknown>, res: ServerResponse): voi
212
212
  const attachments = body.attachments as ImageAttachment[] | undefined;
213
213
 
214
214
  if (type === 'wave') {
215
- if (!directive) {
216
- jsonResponse(res, 400, { error: 'directive is required for wave jobs' });
217
- return;
218
- }
215
+ // directive가 없으면 idle 상태로 시작 (empty wave)
216
+ const actualDirective = directive || '';
219
217
 
220
218
  const targetRoles = body.targetRoles as string[] | undefined;
221
219
  const continuous = body.continuous === true;
@@ -224,7 +222,7 @@ function handleStartJob(body: Record<string, unknown>, res: ServerResponse): voi
224
222
  {
225
223
  const state = supervisorHeartbeat.start(
226
224
  `wave-${Date.now()}`,
227
- directive,
225
+ actualDirective,
228
226
  targetRoles && targetRoles.length > 0 ? targetRoles : undefined,
229
227
  continuous,
230
228
  );
@@ -238,7 +236,7 @@ function handleStartJob(body: Record<string, unknown>, res: ServerResponse): voi
238
236
  waveId: state.waveId,
239
237
  supervisorSessionId: state.supervisorSessionId,
240
238
  mode: 'supervisor',
241
- directive,
239
+ directive: actualDirective,
242
240
  });
243
241
  return;
244
242
  }
@@ -497,12 +495,8 @@ function handleWaveStream(waveId: string, url: string, res: ServerResponse, req:
497
495
  sessionIds = waveMultiplexer.getWaveSessionIds(waveId);
498
496
  }
499
497
 
500
- if (sessionIds.length === 0) {
501
- res.writeHead(404, { 'Content-Type': 'application/json' });
502
- res.end(JSON.stringify({ error: `No sessions found for wave: ${waveId}` }));
503
- return;
504
- }
505
-
498
+ // Don't 404 on empty waves — keep SSE alive, sessions will appear later
499
+ // (e.g. idle wave waiting for first directive, or supervisor restarting)
506
500
  const client = waveMultiplexer.attach(waveId, res as any, fromWaveSeq);
507
501
 
508
502
  req.on('close', () => {
@@ -88,6 +88,14 @@ class SupervisorHeartbeat {
88
88
  };
89
89
 
90
90
  this.supervisors.set(waveId, state);
91
+
92
+ // Empty directive → idle wave (don't spawn supervisor yet)
93
+ if (!directive) {
94
+ state.status = 'stopped';
95
+ console.log(`[Supervisor] Idle wave created: ${waveId} (no directive)`);
96
+ return state;
97
+ }
98
+
91
99
  this.spawnSupervisor(state);
92
100
  return state;
93
101
  }
@@ -133,6 +141,25 @@ class SupervisorHeartbeat {
133
141
 
134
142
  state.pendingDirectives.push(directive);
135
143
  console.log(`[Supervisor] Directive queued for wave ${waveId}: ${text.slice(0, 80)}`);
144
+
145
+ // If supervisor is stopped (agent finished or idle wave), wake it up
146
+ if (state.status === 'stopped') {
147
+ // Update the wave's directive if it was empty (idle wave first message)
148
+ if (!state.directive) {
149
+ state.directive = text;
150
+ }
151
+ state.crashCount = 0;
152
+
153
+ // Dual Mode: Conversation vs Dispatch (code-level enforcement)
154
+ // If directive looks like a question/status check → spawn conversation mode
155
+ // If directive looks like a task → spawn full supervisor with dispatch tools
156
+ if (this.isConversationDirective(text)) {
157
+ this.spawnConversation(state, text);
158
+ } else {
159
+ this.scheduleRestart(state, 0);
160
+ }
161
+ }
162
+
136
163
  return directive;
137
164
  }
138
165
 
@@ -215,6 +242,120 @@ class SupervisorHeartbeat {
215
242
  .filter(s => s.status === 'running' || s.status === 'starting' || s.status === 'restarting');
216
243
  }
217
244
 
245
+ /* ─── Internal: Dual Mode ─────────────────── */
246
+
247
+ /**
248
+ * Heuristic: is this directive a question/status check (conversation)
249
+ * or a work task (needs dispatch)?
250
+ *
251
+ * Conversation signals: question marks, status keywords, short length
252
+ * Dispatch signals: imperative verbs (만들어, 수정해, 구현해), long directives
253
+ */
254
+ private isConversationDirective(text: string): boolean {
255
+ const t = text.trim();
256
+
257
+ // Short messages with question marks → conversation
258
+ if (t.includes('?') && t.length < 100) return true;
259
+
260
+ // Korean question patterns
261
+ const questionPatterns = [
262
+ /확인해/, /알려줘/, /보여줘/, /어때/, /뭐야/, /뭐지/, /뭘까/,
263
+ /상태/, /상황/, /진행/, /현재/, /어디/, /얼마/,
264
+ /what/i, /how.*going/i, /status/i, /check/i, /show/i, /tell/i,
265
+ ];
266
+ if (questionPatterns.some(p => p.test(t))) return true;
267
+
268
+ // Long directives with action verbs → dispatch
269
+ const taskPatterns = [
270
+ /만들어/, /구현해/, /개발해/, /수정해/, /변경해/, /리팩토링/,
271
+ /설계해/, /작성해/, /배포해/, /테스트해/, /고쳐/,
272
+ /build/i, /create/i, /implement/i, /develop/i, /fix/i, /deploy/i, /refactor/i,
273
+ ];
274
+ if (taskPatterns.some(p => p.test(t))) return false;
275
+
276
+ // Default: short → conversation, long → dispatch
277
+ return t.length < 60;
278
+ }
279
+
280
+ /**
281
+ * Spawn a lightweight conversation session (no dispatch tools).
282
+ * CEO reads files and answers directly.
283
+ */
284
+ private spawnConversation(state: SupervisorState, directive: string): void {
285
+ // Build conversation context: previous directives + last execution summary
286
+ const deliveredDirectives = state.pendingDirectives.filter(d => d.delivered);
287
+ const directiveHistory = deliveredDirectives.length > 0
288
+ ? deliveredDirectives.map(d => `- CEO: "${d.text}"`).join('\n')
289
+ : '';
290
+
291
+ // Extract last execution's output from activity stream (what "just happened")
292
+ let lastExecutionSummary = '';
293
+ if (state.supervisorSessionId) {
294
+ try {
295
+ const events = ActivityStream.readAll(state.supervisorSessionId);
296
+ // Get last text outputs (the supervisor's final response)
297
+ const textEvents = events.filter(e => e.type === 'text' && e.roleId === 'ceo');
298
+ const toolEvents = events.filter(e => e.type === 'tool:start' && e.roleId === 'ceo');
299
+
300
+ // Summarize: what tools were used + final text
301
+ const toolSummary = toolEvents.slice(-10).map(e => {
302
+ const name = (e.data.name as string) ?? '';
303
+ const inp = e.data.input as Record<string, unknown> | undefined;
304
+ const detail = inp?.file_path ?? inp?.command ?? '';
305
+ return ` → ${name} ${String(detail).slice(0, 60)}`;
306
+ }).join('\n');
307
+
308
+ const lastText = textEvents.slice(-5).map(e => String(e.data.text ?? '')).join('').slice(-500);
309
+
310
+ if (toolSummary || lastText) {
311
+ lastExecutionSummary = `\n[Previous execution in this wave]\nTools used:\n${toolSummary}\n\nLast response:\n${lastText.slice(0, 500)}\n`;
312
+ }
313
+ } catch { /* ignore */ }
314
+ }
315
+
316
+ const context = [directiveHistory, lastExecutionSummary].filter(Boolean).join('\n');
317
+
318
+ const task = `${context ? context + '\n' : ''}[CEO Question] ${directive}
319
+
320
+ You are the CEO's AI assistant. The above shows what happened previously in this wave.
321
+ Answer the CEO's question based on context. Be specific — reference files, results, and actions from the previous execution.
322
+ Do NOT dispatch anyone. Do NOT create new files. Just answer concisely.`;
323
+
324
+ // Reuse session
325
+ let sessionId = state.supervisorSessionId;
326
+ if (!sessionId || !getSession(sessionId)) {
327
+ const session = createSession('ceo', {
328
+ mode: 'do',
329
+ source: 'wave',
330
+ waveId: state.waveId,
331
+ });
332
+ sessionId = session.id;
333
+ state.supervisorSessionId = sessionId;
334
+ }
335
+
336
+ state.status = 'running';
337
+
338
+ try {
339
+ const exec = executionManager.startExecution({
340
+ type: 'assign', // assign = no supervisor tools (dispatch/watch/amend)
341
+ roleId: 'ceo',
342
+ task,
343
+ sourceRole: 'ceo',
344
+ readOnly: true, // readOnly = no code changes, conversation only
345
+ sessionId,
346
+ });
347
+
348
+ state.executionId = exec.id;
349
+ this.watchExecution(state, exec);
350
+
351
+ console.log(`[Supervisor] Conversation mode for wave ${state.waveId} | directive: ${directive.slice(0, 60)}`);
352
+ } catch (err) {
353
+ console.error(`[Supervisor] Conversation spawn failed:`, err);
354
+ // Fallback to full supervisor
355
+ this.scheduleRestart(state, 0);
356
+ }
357
+ }
358
+
218
359
  /* ─── Internal: Spawn / Restart ────────────── */
219
360
 
220
361
  private spawnSupervisor(state: SupervisorState): void {
@@ -245,12 +386,45 @@ class SupervisorHeartbeat {
245
386
  ? `\n\n⚠️ [RECOVERY] This is a restart after crash #${state.crashCount}. Check all session states via supervision watch.`
246
387
  : '';
247
388
 
248
- const supervisorTask = `[CEO Supervisor] ${state.directive}
389
+ // Build conversation context from previous directives
390
+ const deliveredDirectives = state.pendingDirectives.filter(d => d.delivered);
391
+ const conversationHistory = deliveredDirectives.length > 0
392
+ ? `\n## Previous Conversation in This Wave
393
+ ${deliveredDirectives.map((d, i) => `${i + 1}. CEO said: "${d.text}"`).join('\n')}
394
+
395
+ You are continuing this conversation. The CEO's latest message builds on the above context.
396
+ Do NOT re-analyze from scratch — reference your previous findings.\n`
397
+ : '';
249
398
 
399
+ const supervisorTask = `[CEO Supervisor] ${state.directive}
400
+ ${conversationHistory}
250
401
  ## Your Role
251
- You are the CEO Supervisor — the root of the supervision tree.
252
- Your job: dispatch C-Level roles, watch their progress, relay opinions between them,
253
- and ensure the CEO's directive is fulfilled.
402
+ You are the CEO Supervisor — the CEO's AI proxy.
403
+ You can answer questions directly OR dispatch C-Level roles for complex work.
404
+
405
+ ## Response Mode Decision (BEFORE dispatching)
406
+
407
+ ⛔ Dispatch is expensive (spawns entire teams). Judge first:
408
+
409
+ **1. Direct Answer** — Can YOU handle this without dispatching?
410
+ - Status check, progress report → Read files/docs yourself, answer directly
411
+ - Simple question → Answer directly
412
+ - Opinion request → Answer directly
413
+ - Clarification on previous work → Answer from context
414
+ → **Do NOT dispatch. Just answer.**
415
+
416
+ **2. Selective Dispatch** — Only specific C-Level(s) needed?
417
+ - "코드 수정해" → CTO only
418
+ - "디자인 개선해" → CBO only
419
+ - "테스트해봐" → CTO only (who dispatches QA)
420
+ → **Dispatch only the relevant C-Level(s).**
421
+
422
+ **3. Full Dispatch** — Multi-team collaboration required?
423
+ - "새 기능 만들어" → CTO + CBO
424
+ - "출시 준비해" → All C-Levels
425
+ → **Dispatch multiple C-Levels with clear tasks.**
426
+
427
+ **Default: Direct Answer first. Dispatch only when code changes or creative work is needed.**
254
428
 
255
429
  ## Available C-Level Roles
256
430
  ${cLevelList}
@@ -333,13 +507,14 @@ ${state.continuous ? `## Continuous Improvement Mode (ON)
333
507
  5. 사용자가 Stop을 누를 때까지 계속한다. 스스로 done 선언하지 마라.
334
508
 
335
509
  ` : ''}## Instructions
336
- 1. Analyze the directive and decide which C-Level roles to dispatch (not necessarily all)
337
- 2. Dispatch them with clear tasks
338
- 3. Enter supervision watch loop
339
- 4. Monitor, **actively relay results between teams**, course-correct
340
- 5. When subordinates report done **verify deliverables against requirements (G-09)**
341
- 6. If gaps existre-dispatch with specific feedback. Repeat 3-5.
342
- 7. Only when ALL requirements are met compile results and report`;
510
+ 1. **First: Apply Response Mode Decision** Can you answer directly? If yes, answer and report done.
511
+ 2. If dispatch is needed: decide which C-Level roles (not necessarily all)
512
+ 3. Dispatch with clear, specific tasks
513
+ 4. Enter supervision watch loop
514
+ 5. Monitor, **actively relay results between teams**, course-correct
515
+ 6. When subordinates report done **verify deliverables against requirements (G-09)**
516
+ 7. If gaps exist re-dispatch with specific feedback. Repeat 4-6.
517
+ 8. Only when ALL requirements are met → compile results and report`;
343
518
 
344
519
  // BUG-008 fix: Wave:Supervisor:Session = 1:1:1 invariant.
345
520
  // Reuse existing session on restart instead of creating a new one.
@@ -83,19 +83,30 @@ class WaveMultiplexer {
83
83
 
84
84
  const sessions = this.waveSessions.get(waveId);
85
85
  if (sessions) {
86
- // Phase 1: Replay all historical events sorted by timestamp
87
- const allEvents: { event: ActivityEvent; sessionId: string }[] = [];
86
+ // Phase 1: Replay recent historical events (capped to prevent OOM)
87
+ // Only replay from recent sessions (last 5) to avoid 120-session waves killing memory
88
+ const MAX_REPLAY_SESSIONS = 5;
89
+ const MAX_REPLAY_EVENTS = 200;
90
+
91
+ const sessionList = Array.from(sessions.values());
92
+ const recentSessions = sessionList.slice(-MAX_REPLAY_SESSIONS);
88
93
 
89
- for (const [, exec] of sessions) {
94
+ const allEvents: { event: ActivityEvent; sessionId: string }[] = [];
95
+ for (const exec of recentSessions) {
90
96
  const events = ActivityStream.readFrom(exec.sessionId, 0);
91
- for (const event of events) {
97
+ // Take last N events per session
98
+ const recent = events.slice(-50);
99
+ for (const event of recent) {
92
100
  allEvents.push({ event, sessionId: exec.sessionId });
93
101
  }
94
102
  }
95
103
 
96
104
  allEvents.sort((a, b) => a.event.ts.localeCompare(b.event.ts));
97
105
 
98
- for (const item of allEvents) {
106
+ // Cap total replay events
107
+ const replayEvents = allEvents.slice(-MAX_REPLAY_EVENTS);
108
+
109
+ for (const item of replayEvents) {
99
110
  const waveSeq = client.waveSeq++;
100
111
  if (waveSeq < fromWaveSeq) continue;
101
112
 
@@ -111,8 +122,10 @@ class WaveMultiplexer {
111
122
  } as WaveStreamEnvelope);
112
123
  }
113
124
 
125
+ console.log(`[WaveMux] Replayed ${replayEvents.length} events (${sessionList.length} total sessions, ${recentSessions.length} replayed)`);
126
+
114
127
  // Phase 2: Subscribe to live events for active sessions
115
- for (const [, exec] of sessions) {
128
+ for (const [, exec] of sessionList) {
116
129
  if (exec.status === 'running' || exec.status === 'awaiting_input') {
117
130
  this.subscribeSessionToClient(waveId, client, exec, true);
118
131
  }
@@ -137,7 +150,8 @@ class WaveMultiplexer {
137
150
  });
138
151
 
139
152
  const events = ActivityStream.readFrom(execution.sessionId, 0);
140
- for (const event of events) {
153
+ const recentEvents = events.slice(-50); // Cap replay per session
154
+ for (const event of recentEvents) {
141
155
  const key = `${event.roleId}:${event.seq}`;
142
156
  if (client.sentEvents.has(key)) continue;
143
157
  client.sentEvents.add(key);
package/src/tui/api.ts CHANGED
@@ -16,7 +16,7 @@ export function getBaseUrl(): string {
16
16
 
17
17
  /* ─── HTTP helpers ─── */
18
18
 
19
- async function fetchJson<T>(path: string, options?: { method?: string; body?: unknown }): Promise<T> {
19
+ export async function fetchJson<T>(path: string, options?: { method?: string; body?: unknown }): Promise<T> {
20
20
  const url = `${BASE_URL}${path}`;
21
21
  const method = options?.method ?? 'GET';
22
22
  const bodyStr = options?.body ? JSON.stringify(options.body) : undefined;
@@ -83,6 +83,7 @@ export interface SessionInfo {
83
83
  status: string;
84
84
  source: string;
85
85
  waveId?: string;
86
+ parentSessionId?: string;
86
87
  createdAt: string;
87
88
  }
88
89
 
@@ -129,7 +130,7 @@ export async function fetchExecStatus(): Promise<ExecStatus> {
129
130
  return fetchJson<ExecStatus>('/api/exec/status');
130
131
  }
131
132
 
132
- export async function dispatchWave(directive: string, options?: {
133
+ export async function dispatchWave(directive?: string, options?: {
133
134
  targetRoles?: string[];
134
135
  continuous?: boolean;
135
136
  }): Promise<WaveResponse> {
@@ -137,7 +138,7 @@ export async function dispatchWave(directive: string, options?: {
137
138
  method: 'POST',
138
139
  body: {
139
140
  type: 'wave',
140
- directive,
141
+ directive: directive ?? '',
141
142
  targetRoles: options?.targetRoles,
142
143
  continuous: options?.continuous ?? false,
143
144
  },
@@ -155,6 +156,39 @@ export async function fetchActiveWaves(): Promise<{ waves: Array<{ waveId: strin
155
156
  return fetchJson('/api/waves/active');
156
157
  }
157
158
 
159
+ /* ─── Active Sessions (port/worktree visibility) ─── */
160
+
161
+ export interface ActiveSessionInfo {
162
+ sessionId: string;
163
+ roleId: string;
164
+ task: string;
165
+ ports: { api: number; vite: number; hmr?: number };
166
+ worktreePath?: string;
167
+ pid?: number;
168
+ startedAt: string;
169
+ status: 'active' | 'idle' | 'dead';
170
+ waveId?: string | null;
171
+ messageStatus?: string | null;
172
+ alive?: boolean | null;
173
+ }
174
+
175
+ export interface ActiveSessionsResponse {
176
+ sessions: ActiveSessionInfo[];
177
+ summary: { active: number; totalPorts: number };
178
+ }
179
+
180
+ export async function fetchActiveSessions(): Promise<ActiveSessionsResponse> {
181
+ return fetchJson<ActiveSessionsResponse>('/api/active-sessions');
182
+ }
183
+
184
+ export async function killSession(sessionId: string): Promise<{ ok: boolean }> {
185
+ return fetchJson<{ ok: boolean }>(`/api/active-sessions/${sessionId}`, { method: 'DELETE' });
186
+ }
187
+
188
+ export async function cleanupSessions(): Promise<{ cleaned: number; remaining: number }> {
189
+ return fetchJson<{ cleaned: number; remaining: number }>('/api/active-sessions/cleanup', { method: 'POST' });
190
+ }
191
+
158
192
  /* ─── Setup API calls ─── */
159
193
 
160
194
  export interface TeamTemplate {
@@ -232,9 +266,12 @@ export function subscribeToWaveStream(
232
266
  }
233
267
  }
234
268
 
235
- if (eventType === 'activity' && data) {
269
+ if ((eventType === 'activity' || eventType === 'wave:event') && data) {
236
270
  try {
237
- onEvent(JSON.parse(data) as SSEEvent);
271
+ const parsed = JSON.parse(data);
272
+ // wave:event wraps the actual event in .event field
273
+ const evt = parsed.event ?? parsed;
274
+ onEvent(evt as SSEEvent);
238
275
  } catch { /* ignore parse errors */ }
239
276
  } else if (eventType === 'stream:end' && data) {
240
277
  try {