@linxiraos/pi-messenger 1.1.0

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +676 -0
  2. package/README.md +424 -0
  3. package/config-overlay.ts +171 -0
  4. package/config.ts +209 -0
  5. package/crew/agents/crew-plan-sync.md +64 -0
  6. package/crew/agents/crew-planner.md +172 -0
  7. package/crew/agents/crew-reviewer.md +58 -0
  8. package/crew/agents/crew-worker.md +129 -0
  9. package/crew/agents.ts +434 -0
  10. package/crew/handlers/coordination.ts +332 -0
  11. package/crew/handlers/plan.ts +906 -0
  12. package/crew/handlers/review.ts +333 -0
  13. package/crew/handlers/revise.ts +376 -0
  14. package/crew/handlers/status.ts +295 -0
  15. package/crew/handlers/sync.ts +233 -0
  16. package/crew/handlers/task.ts +792 -0
  17. package/crew/handlers/team.ts +235 -0
  18. package/crew/handlers/work.ts +425 -0
  19. package/crew/id-allocator.ts +30 -0
  20. package/crew/index.ts +257 -0
  21. package/crew/live-progress.ts +58 -0
  22. package/crew/lobby.ts +473 -0
  23. package/crew/prompt.ts +252 -0
  24. package/crew/registry.ts +114 -0
  25. package/crew/spawn.ts +111 -0
  26. package/crew/state-autonomous.ts +164 -0
  27. package/crew/state-planning.ts +263 -0
  28. package/crew/state.ts +20 -0
  29. package/crew/store.ts +642 -0
  30. package/crew/task-actions.ts +131 -0
  31. package/crew/team/store.ts +479 -0
  32. package/crew/team/subagent-roles.ts +87 -0
  33. package/crew/team/types.ts +50 -0
  34. package/crew/types.ts +194 -0
  35. package/crew/utils/artifacts.ts +62 -0
  36. package/crew/utils/config.ts +156 -0
  37. package/crew/utils/discover.ts +219 -0
  38. package/crew/utils/install.ts +85 -0
  39. package/crew/utils/progress.ts +187 -0
  40. package/crew/utils/result.ts +16 -0
  41. package/crew/utils/risk-labels.ts +7 -0
  42. package/crew/utils/task-format.ts +14 -0
  43. package/crew/utils/team-roles.ts +28 -0
  44. package/crew/utils/truncate.ts +79 -0
  45. package/crew/utils/verdict.ts +55 -0
  46. package/feed.ts +268 -0
  47. package/handlers.ts +1107 -0
  48. package/index.ts +1206 -0
  49. package/install.mjs +189 -0
  50. package/lib.ts +467 -0
  51. package/overlay-actions.ts +511 -0
  52. package/overlay-coordinator.ts +150 -0
  53. package/overlay-render.ts +676 -0
  54. package/overlay.ts +830 -0
  55. package/package.json +62 -0
  56. package/skills/pi-messenger-crew/SKILL.md +347 -0
  57. package/store.ts +1139 -0
  58. package/vitest.config.ts +10 -0
@@ -0,0 +1,511 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { matchesKey, type TUI } from "@earendil-works/pi-tui";
3
+ import type { AgentMailMessage, Dirs, MessengerState } from "./lib.ts";
4
+ import { MAX_CHAT_HISTORY } from "./lib.ts";
5
+ import { sendMessageToAgent, getActiveAgents } from "./store.ts";
6
+ import { logFeedEvent } from "./feed.ts";
7
+ import * as crewStore from "./crew/store.ts";
8
+ import { executeTaskAction as runTaskAction } from "./crew/task-actions.ts";
9
+ import type { Task } from "./crew/types.ts";
10
+ import { getLiveWorkers } from "./crew/live-progress.ts";
11
+ import { hasActiveWorker } from "./crew/registry.ts";
12
+ import { cancelPlanningRun } from "./crew/state.ts";
13
+
14
+ interface ConfirmAction {
15
+ type: "reset" | "cascade-reset" | "delete" | "cancel-planning";
16
+ taskId: string;
17
+ label: string;
18
+ }
19
+
20
+ export interface CrewViewState {
21
+ scrollOffset: number;
22
+ selectedTaskIndex: number;
23
+ mode: "list" | "detail";
24
+ detailScroll: number;
25
+ detailAutoScroll: boolean;
26
+ confirmAction: ConfirmAction | null;
27
+ blockReasonInput: string;
28
+ messageInput: string;
29
+ inputMode: "normal" | "block-reason" | "message" | "revise-prompt";
30
+ reviseScope: "single" | "tree";
31
+ revisePromptInput: string;
32
+ lastSeenEventTs: string | null;
33
+ notification: { message: string; expiresAt: number } | null;
34
+ notificationTimer: ReturnType<typeof setTimeout> | null;
35
+ feedFocus: boolean;
36
+ mentionCandidates: string[];
37
+ mentionIndex: number;
38
+ }
39
+
40
+ export function createCrewViewState(): CrewViewState {
41
+ return {
42
+ scrollOffset: 0,
43
+ selectedTaskIndex: 0,
44
+ mode: "list",
45
+ detailScroll: 0,
46
+ detailAutoScroll: true,
47
+ confirmAction: null,
48
+ blockReasonInput: "",
49
+ messageInput: "",
50
+ inputMode: "normal",
51
+ reviseScope: "single",
52
+ revisePromptInput: "",
53
+ lastSeenEventTs: null,
54
+ notification: null,
55
+ notificationTimer: null,
56
+ feedFocus: false,
57
+ mentionCandidates: [],
58
+ mentionIndex: -1,
59
+ };
60
+ }
61
+
62
+ function hasLiveWorker(cwd: string, taskId: string): boolean {
63
+ return hasActiveWorker(cwd, taskId);
64
+ }
65
+
66
+ function isPrintable(data: string): boolean {
67
+ return data.length > 0 && data.charCodeAt(0) >= 32;
68
+ }
69
+
70
+ function executeTaskAction(
71
+ cwd: string,
72
+ action: string,
73
+ taskId: string,
74
+ agentName: string,
75
+ reason?: string,
76
+ ): { success: boolean; message: string } {
77
+ if (
78
+ action !== "start" &&
79
+ action !== "block" &&
80
+ action !== "unblock" &&
81
+ action !== "reset" &&
82
+ action !== "cascade-reset" &&
83
+ action !== "delete" &&
84
+ action !== "stop"
85
+ ) {
86
+ return { success: false, message: `Unknown action: ${action}` };
87
+ }
88
+
89
+ const result = runTaskAction(cwd, action, taskId, agentName, reason, {
90
+ isWorkerActive: id => hasLiveWorker(cwd, id),
91
+ });
92
+ return { success: result.success, message: result.message };
93
+ }
94
+
95
+ export function setNotification(viewState: CrewViewState, tui: TUI, success: boolean, message: string): void {
96
+ if (viewState.notificationTimer) clearTimeout(viewState.notificationTimer);
97
+ viewState.notification = { message: `${success ? "✓" : "✗"} ${message}`, expiresAt: Date.now() + 2000 };
98
+ viewState.notificationTimer = setTimeout(() => {
99
+ viewState.notificationTimer = null;
100
+ tui.requestRender();
101
+ }, 2000);
102
+ }
103
+
104
+ function addToChatHistory(state: MessengerState, recipient: string, message: AgentMailMessage): void {
105
+ let history = state.chatHistory.get(recipient);
106
+ if (!history) {
107
+ history = [];
108
+ state.chatHistory.set(recipient, history);
109
+ }
110
+ history.push(message);
111
+ if (history.length > MAX_CHAT_HISTORY) history.shift();
112
+ }
113
+
114
+ function addToBroadcastHistory(state: MessengerState, text: string): void {
115
+ const broadcastMsg: AgentMailMessage = {
116
+ id: randomUUID(),
117
+ from: state.agentName,
118
+ to: "broadcast",
119
+ text,
120
+ timestamp: new Date().toISOString(),
121
+ replyTo: null,
122
+ };
123
+ state.broadcastHistory.push(broadcastMsg);
124
+ if (state.broadcastHistory.length > MAX_CHAT_HISTORY) {
125
+ state.broadcastHistory.shift();
126
+ }
127
+ }
128
+
129
+ function previewText(text: string): string {
130
+ return text.length > 200 ? `${text.slice(0, 197)}...` : text;
131
+ }
132
+
133
+ export function handleConfirmInput(data: string, viewState: CrewViewState, cwd: string, agentName: string, tui: TUI): void {
134
+ const action = viewState.confirmAction;
135
+ if (!action) return;
136
+ if (matchesKey(data, "y")) {
137
+ if (action.type === "cancel-planning") {
138
+ cancelPlanningRun(cwd);
139
+ logFeedEvent(cwd, agentName, "plan.cancel");
140
+ viewState.confirmAction = null;
141
+ setNotification(viewState, tui, true, "Planning cancelled");
142
+ tui.requestRender();
143
+ return;
144
+ }
145
+ const result = executeTaskAction(cwd, action.type, action.taskId, agentName);
146
+ if (action.type === "delete") {
147
+ const tasks = crewStore.getTasks(cwd);
148
+ if (tasks.length > 0) {
149
+ viewState.selectedTaskIndex = Math.max(0, Math.min(viewState.selectedTaskIndex, tasks.length - 1));
150
+ } else {
151
+ viewState.selectedTaskIndex = 0;
152
+ if (viewState.mode === "detail") viewState.mode = "list";
153
+ }
154
+ }
155
+ viewState.confirmAction = null;
156
+ setNotification(viewState, tui, result.success, result.message);
157
+ tui.requestRender();
158
+ return;
159
+ }
160
+ if (matchesKey(data, "n") || matchesKey(data, "escape")) {
161
+ viewState.confirmAction = null;
162
+ tui.requestRender();
163
+ }
164
+ }
165
+
166
+ export function handleBlockReasonInput(
167
+ data: string,
168
+ viewState: CrewViewState,
169
+ cwd: string,
170
+ task: Task | undefined,
171
+ agentName: string,
172
+ tui: TUI,
173
+ ): void {
174
+ if (matchesKey(data, "escape")) {
175
+ viewState.inputMode = "normal";
176
+ viewState.blockReasonInput = "";
177
+ tui.requestRender();
178
+ return;
179
+ }
180
+ if (matchesKey(data, "enter")) {
181
+ const reason = viewState.blockReasonInput.trim();
182
+ if (!reason || !task) return;
183
+ const result = executeTaskAction(cwd, "block", task.id, agentName, reason);
184
+ viewState.inputMode = "normal";
185
+ viewState.blockReasonInput = "";
186
+ setNotification(viewState, tui, result.success, result.message);
187
+ tui.requestRender();
188
+ return;
189
+ }
190
+ if (matchesKey(data, "backspace")) {
191
+ if (viewState.blockReasonInput.length > 0) {
192
+ viewState.blockReasonInput = viewState.blockReasonInput.slice(0, -1);
193
+ tui.requestRender();
194
+ }
195
+ return;
196
+ }
197
+ if (isPrintable(data)) {
198
+ viewState.blockReasonInput += data;
199
+ tui.requestRender();
200
+ }
201
+ }
202
+
203
+ export function handleRevisePromptInput(
204
+ data: string,
205
+ viewState: CrewViewState,
206
+ cwd: string,
207
+ task: Task | undefined,
208
+ agentName: string,
209
+ tui: TUI,
210
+ ): void {
211
+ if (matchesKey(data, "escape")) {
212
+ viewState.inputMode = "normal";
213
+ viewState.revisePromptInput = "";
214
+ tui.requestRender();
215
+ return;
216
+ }
217
+ if (matchesKey(data, "enter")) {
218
+ if (!task) return;
219
+ if (task.status === "in_progress") {
220
+ setNotification(viewState, tui, false, "Cannot revise in_progress task");
221
+ viewState.inputMode = "normal";
222
+ viewState.revisePromptInput = "";
223
+ tui.requestRender();
224
+ return;
225
+ }
226
+
227
+ const prompt = viewState.revisePromptInput.trim() || undefined;
228
+ const scope = viewState.reviseScope;
229
+ viewState.inputMode = "normal";
230
+ viewState.revisePromptInput = "";
231
+
232
+ const label = scope === "tree" ? `Revising ${task.id} + tree...` : `Revising ${task.id}...`;
233
+ setNotification(viewState, tui, true, label);
234
+
235
+ const vs = viewState;
236
+ const t = tui;
237
+ const fn = scope === "tree" ? "executeReviseTree" : "executeRevise";
238
+ import("./crew/handlers/revise.ts")
239
+ .then(m => m[fn](cwd, task.id, prompt, agentName))
240
+ .then(result => {
241
+ setNotification(vs, t, result.success, result.message);
242
+ })
243
+ .catch(err => {
244
+ logFeedEvent(cwd, agentName, scope === "tree" ? "task.revise-tree" : "task.revise", task.id, `failed: ${err instanceof Error ? err.message : "unknown"}`);
245
+ });
246
+ tui.requestRender();
247
+ return;
248
+ }
249
+ if (matchesKey(data, "backspace")) {
250
+ if (viewState.revisePromptInput.length > 0) {
251
+ viewState.revisePromptInput = viewState.revisePromptInput.slice(0, -1);
252
+ tui.requestRender();
253
+ }
254
+ return;
255
+ }
256
+ if (isPrintable(data)) {
257
+ viewState.revisePromptInput += data;
258
+ tui.requestRender();
259
+ }
260
+ }
261
+
262
+ function resetMessageInput(viewState: CrewViewState): void {
263
+ viewState.inputMode = "normal";
264
+ viewState.messageInput = "";
265
+ viewState.mentionCandidates = [];
266
+ viewState.mentionIndex = -1;
267
+ }
268
+
269
+ function collectMentionCandidates(
270
+ prefix: string,
271
+ state: MessengerState,
272
+ dirs: Dirs,
273
+ cwd: string,
274
+ ): string[] {
275
+ const seen = new Set<string>();
276
+ const names: string[] = [];
277
+
278
+ for (const agent of getActiveAgents(state, dirs)) {
279
+ if (agent.name === state.agentName) continue;
280
+ if (!seen.has(agent.name)) {
281
+ seen.add(agent.name);
282
+ names.push(agent.name);
283
+ }
284
+ }
285
+
286
+ for (const worker of getLiveWorkers(cwd).values()) {
287
+ if (!seen.has(worker.name)) {
288
+ seen.add(worker.name);
289
+ names.push(worker.name);
290
+ }
291
+ }
292
+
293
+ names.push("all");
294
+
295
+ if (!prefix) return names;
296
+ const lower = prefix.toLowerCase();
297
+ return names.filter(n => n.toLowerCase().startsWith(lower));
298
+ }
299
+
300
+ function sendDirectMessage(
301
+ state: MessengerState,
302
+ dirs: Dirs,
303
+ cwd: string,
304
+ target: string,
305
+ text: string,
306
+ tui: TUI,
307
+ viewState: CrewViewState,
308
+ ): void {
309
+ try {
310
+ const msg = sendMessageToAgent(state, dirs, target, text);
311
+ addToChatHistory(state, target, msg);
312
+ logFeedEvent(cwd, state.agentName, "message", target, previewText(text));
313
+ resetMessageInput(viewState);
314
+ setNotification(viewState, tui, true, `Sent to ${target}`);
315
+ tui.requestRender();
316
+ } catch (err) {
317
+ const msg = err instanceof Error ? err.message : "unknown error";
318
+ setNotification(viewState, tui, false, `Failed to send to ${target}: ${msg}`);
319
+ tui.requestRender();
320
+ }
321
+ }
322
+
323
+ function sendBroadcastMessage(
324
+ state: MessengerState,
325
+ dirs: Dirs,
326
+ cwd: string,
327
+ text: string,
328
+ tui: TUI,
329
+ viewState: CrewViewState,
330
+ ): void {
331
+ const peers = getActiveAgents(state, dirs);
332
+ if (peers.length === 0) {
333
+ setNotification(viewState, tui, false, "No peers available for @all");
334
+ tui.requestRender();
335
+ return;
336
+ }
337
+
338
+ let sentCount = 0;
339
+ for (const peer of peers) {
340
+ try {
341
+ sendMessageToAgent(state, dirs, peer.name, text);
342
+ sentCount++;
343
+ } catch {
344
+ // Ignore per-recipient failures
345
+ }
346
+ }
347
+
348
+ if (sentCount === 0) {
349
+ setNotification(viewState, tui, false, "Broadcast failed");
350
+ tui.requestRender();
351
+ return;
352
+ }
353
+
354
+ addToBroadcastHistory(state, text);
355
+ logFeedEvent(cwd, state.agentName, "message", undefined, previewText(text));
356
+ resetMessageInput(viewState);
357
+ setNotification(viewState, tui, true, `Broadcast to ${sentCount} peer${sentCount === 1 ? "" : "s"}`);
358
+ tui.requestRender();
359
+ }
360
+
361
+ export function handleMessageInput(
362
+ data: string,
363
+ viewState: CrewViewState,
364
+ state: MessengerState,
365
+ dirs: Dirs,
366
+ cwd: string,
367
+ tui: TUI,
368
+ ): void {
369
+ if (matchesKey(data, "escape")) {
370
+ resetMessageInput(viewState);
371
+ tui.requestRender();
372
+ return;
373
+ }
374
+
375
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
376
+ const input = viewState.messageInput;
377
+ const cycling = viewState.mentionIndex >= 0 && viewState.mentionCandidates.length > 0;
378
+ if (!input.startsWith("@") || (input.includes(" ") && !cycling)) return;
379
+
380
+ const reverse = matchesKey(data, "shift+tab");
381
+
382
+ if (!cycling) {
383
+ const prefix = input.slice(1);
384
+ viewState.mentionCandidates = collectMentionCandidates(prefix, state, dirs, cwd);
385
+ if (viewState.mentionCandidates.length === 0) return;
386
+ viewState.mentionIndex = 0;
387
+ } else {
388
+ const delta = reverse ? -1 : 1;
389
+ viewState.mentionIndex = (viewState.mentionIndex + delta + viewState.mentionCandidates.length) % viewState.mentionCandidates.length;
390
+ }
391
+
392
+ viewState.messageInput = `@${viewState.mentionCandidates[viewState.mentionIndex]} `;
393
+ tui.requestRender();
394
+ return;
395
+ }
396
+
397
+ if (matchesKey(data, "enter")) {
398
+ const raw = viewState.messageInput.trim();
399
+ if (!raw) return;
400
+
401
+ if (raw.startsWith("@all ")) {
402
+ const text = raw.slice(5).trim();
403
+ if (!text) return;
404
+ sendBroadcastMessage(state, dirs, cwd, text, tui, viewState);
405
+ return;
406
+ }
407
+
408
+ if (raw.startsWith("@")) {
409
+ const firstSpace = raw.indexOf(" ");
410
+ if (firstSpace <= 1) {
411
+ setNotification(viewState, tui, false, "Use @name <message> or type to broadcast");
412
+ tui.requestRender();
413
+ return;
414
+ }
415
+
416
+ const target = raw.slice(1, firstSpace).trim();
417
+ const text = raw.slice(firstSpace + 1).trim();
418
+ if (!target || !text) {
419
+ setNotification(viewState, tui, false, "Use @name <message> or type to broadcast");
420
+ tui.requestRender();
421
+ return;
422
+ }
423
+
424
+ sendDirectMessage(state, dirs, cwd, target, text, tui, viewState);
425
+ return;
426
+ }
427
+
428
+ sendBroadcastMessage(state, dirs, cwd, raw, tui, viewState);
429
+ return;
430
+ }
431
+
432
+ if (matchesKey(data, "backspace")) {
433
+ if (viewState.messageInput.length > 0) {
434
+ viewState.messageInput = viewState.messageInput.slice(0, -1);
435
+ viewState.mentionCandidates = [];
436
+ viewState.mentionIndex = -1;
437
+ tui.requestRender();
438
+ }
439
+ return;
440
+ }
441
+
442
+ if (isPrintable(data)) {
443
+ viewState.messageInput += data;
444
+ viewState.mentionCandidates = [];
445
+ viewState.mentionIndex = -1;
446
+ tui.requestRender();
447
+ }
448
+ }
449
+
450
+ export function handleCrewKeyBinding(
451
+ data: string,
452
+ task: Task,
453
+ viewState: CrewViewState,
454
+ cwd: string,
455
+ agentName: string,
456
+ tui: TUI,
457
+ ): void {
458
+ if (matchesKey(data, "r") && ["done", "blocked", "in_progress"].includes(task.status)) {
459
+ viewState.confirmAction = { type: "reset", taskId: task.id, label: task.title };
460
+ tui.requestRender();
461
+ return;
462
+ }
463
+ if (matchesKey(data, "shift+r") && ["done", "blocked", "in_progress"].includes(task.status)) {
464
+ viewState.confirmAction = { type: "cascade-reset", taskId: task.id, label: task.title };
465
+ tui.requestRender();
466
+ return;
467
+ }
468
+ if (matchesKey(data, "u") && task.status === "blocked") {
469
+ const result = executeTaskAction(cwd, "unblock", task.id, agentName);
470
+ setNotification(viewState, tui, result.success, result.message);
471
+ tui.requestRender();
472
+ return;
473
+ }
474
+ if (matchesKey(data, "shift+s") && task.status !== "done" && !task.milestone) {
475
+ setNotification(viewState, tui, true, `Split: pi_messenger({ action: "task.split", id: "${task.id}" })`);
476
+ tui.requestRender();
477
+ return;
478
+ }
479
+ if (matchesKey(data, "b") && task.status === "in_progress") {
480
+ viewState.inputMode = "block-reason";
481
+ viewState.blockReasonInput = "";
482
+ tui.requestRender();
483
+ return;
484
+ }
485
+ if (matchesKey(data, "q") && task.status === "in_progress") {
486
+ const result = executeTaskAction(cwd, "stop", task.id, agentName);
487
+ setNotification(viewState, tui, result.success, result.message);
488
+ tui.requestRender();
489
+ return;
490
+ }
491
+ if (matchesKey(data, "x")) {
492
+ if (task.status === "in_progress" && hasLiveWorker(cwd, task.id)) return;
493
+ viewState.confirmAction = { type: "delete", taskId: task.id, label: task.title };
494
+ tui.requestRender();
495
+ return;
496
+ }
497
+ if (matchesKey(data, "p") && task.status !== "in_progress" && !task.milestone) {
498
+ viewState.inputMode = "revise-prompt";
499
+ viewState.reviseScope = "single";
500
+ viewState.revisePromptInput = "";
501
+ tui.requestRender();
502
+ return;
503
+ }
504
+ if (matchesKey(data, "shift+p") && task.status !== "in_progress" && !task.milestone) {
505
+ viewState.inputMode = "revise-prompt";
506
+ viewState.reviseScope = "tree";
507
+ viewState.revisePromptInput = "";
508
+ tui.requestRender();
509
+ return;
510
+ }
511
+ }
@@ -0,0 +1,150 @@
1
+ import type { OverlayHandle, TUI } from "@earendil-works/pi-tui";
2
+
3
+ const QUIET_PERIOD_MS = 80;
4
+ const RENDER_THROTTLE_MS = 32;
5
+ const STDOUT_GUARD_MS = 32;
6
+
7
+ type StdoutWrite = typeof process.stdout.write;
8
+
9
+ function hasRenderableOutput(chunk: unknown): boolean {
10
+ if (typeof chunk === "string") return chunk.length > 0;
11
+ if (chunk instanceof Uint8Array) return chunk.length > 0;
12
+ return false;
13
+ }
14
+
15
+ /**
16
+ * Coordinates overlay rendering with main agent stdout to prevent visual collision.
17
+ *
18
+ * Strategy: Keep overlay visible, but schedule a "repair" render after foreign
19
+ * output settles. Brief visual corruption is acceptable if it self-heals quickly.
20
+ */
21
+ export class OverlayRenderCoordinator {
22
+ private tui: TUI | null = null;
23
+ private handle: OverlayHandle | null = null;
24
+ private originalRequestRender: TUI["requestRender"] | null = null;
25
+ private originalStdoutWrite: StdoutWrite | null = null;
26
+ private repairTimer: ReturnType<typeof setTimeout> | null = null;
27
+ private lastRenderAt = 0;
28
+ private stdoutGuardUntil = 0;
29
+ private foreignOutputDetected = false;
30
+
31
+ installStdoutInterceptor(): void {
32
+ if (this.originalStdoutWrite) return;
33
+
34
+ const original = process.stdout.write.bind(process.stdout) as StdoutWrite;
35
+ this.originalStdoutWrite = original;
36
+
37
+ const coordinator = this;
38
+ (process.stdout.write as StdoutWrite) = function writeIntercept(
39
+ chunk: Parameters<StdoutWrite>[0],
40
+ ...args: Parameters<StdoutWrite> extends [unknown, ...infer Rest] ? Rest : never
41
+ ) {
42
+ const result = original(chunk, ...args);
43
+ coordinator.handleStdoutWrite(chunk);
44
+ return result;
45
+ } as StdoutWrite;
46
+ }
47
+
48
+ uninstallStdoutInterceptor(): void {
49
+ if (!this.originalStdoutWrite) return;
50
+ (process.stdout.write as StdoutWrite) = this.originalStdoutWrite;
51
+ this.originalStdoutWrite = null;
52
+ }
53
+
54
+ attach(tui: TUI): void {
55
+ if (this.tui === tui && this.originalRequestRender) return;
56
+
57
+ this.detach();
58
+ this.tui = tui;
59
+ this.originalRequestRender = tui.requestRender.bind(tui);
60
+ tui.requestRender = ((force?: boolean) => {
61
+ this.requestRender(force);
62
+ }) as TUI["requestRender"];
63
+ }
64
+
65
+ setHandle(handle: OverlayHandle | null): void {
66
+ this.handle = handle;
67
+ }
68
+
69
+ detach(): void {
70
+ if (this.repairTimer) {
71
+ clearTimeout(this.repairTimer);
72
+ this.repairTimer = null;
73
+ }
74
+ if (this.tui && this.originalRequestRender) {
75
+ this.tui.requestRender = this.originalRequestRender;
76
+ }
77
+ this.tui = null;
78
+ this.handle = null;
79
+ this.originalRequestRender = null;
80
+ this.lastRenderAt = 0;
81
+ this.stdoutGuardUntil = 0;
82
+ this.foreignOutputDetected = false;
83
+ }
84
+
85
+ dispose(): void {
86
+ this.detach();
87
+ this.uninstallStdoutInterceptor();
88
+ }
89
+
90
+ /** Called by hooks when main agent activity is expected */
91
+ noteForegroundActivity(): void {
92
+ if (!this.tui || !this.handle) return;
93
+ if (this.handle.isHidden()) return;
94
+
95
+ this.foreignOutputDetected = true;
96
+ this.scheduleRepair();
97
+ }
98
+
99
+ private handleStdoutWrite(chunk: unknown): void {
100
+ if (!this.tui || !this.handle) return;
101
+ if (!hasRenderableOutput(chunk)) return;
102
+ if (Date.now() <= this.stdoutGuardUntil) return;
103
+ if (this.handle.isHidden()) return;
104
+
105
+ this.foreignOutputDetected = true;
106
+ this.scheduleRepair();
107
+ }
108
+
109
+ private scheduleRepair(): void {
110
+ if (this.repairTimer) clearTimeout(this.repairTimer);
111
+ this.repairTimer = setTimeout(() => {
112
+ this.repairTimer = null;
113
+ this.repair();
114
+ }, QUIET_PERIOD_MS);
115
+ }
116
+
117
+ private repair(): void {
118
+ if (!this.tui || !this.handle) return;
119
+ if (this.handle.isHidden()) return;
120
+ if (!this.foreignOutputDetected) return;
121
+
122
+ this.foreignOutputDetected = false;
123
+ this.flushRender(true);
124
+ }
125
+
126
+ requestRender(force = false): void {
127
+ if (!this.originalRequestRender) return;
128
+ if (this.handle?.isHidden()) return;
129
+
130
+ const now = Date.now();
131
+ if (!force) {
132
+ const elapsed = now - this.lastRenderAt;
133
+ if (elapsed < RENDER_THROTTLE_MS) {
134
+ // Skip this render, repair timer will catch up
135
+ return;
136
+ }
137
+ }
138
+
139
+ this.flushRender(force);
140
+ }
141
+
142
+ private flushRender(force: boolean): void {
143
+ if (!this.originalRequestRender) return;
144
+ if (this.handle?.isHidden()) return;
145
+
146
+ this.lastRenderAt = Date.now();
147
+ this.stdoutGuardUntil = this.lastRenderAt + STDOUT_GUARD_MS;
148
+ this.originalRequestRender(force);
149
+ }
150
+ }