@linxiraos/pi-messenger 1.1.0 → 1.3.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 (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
@@ -1,511 +1,519 @@
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
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { matchesKey, type TUI } from "@linxiraos/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(
134
+ data: string,
135
+ viewState: CrewViewState,
136
+ cwd: string,
137
+ agentName: string,
138
+ tui: TUI,
139
+ ): void {
140
+ const action = viewState.confirmAction;
141
+ if (!action) return;
142
+ if (matchesKey(data, "y")) {
143
+ if (action.type === "cancel-planning") {
144
+ cancelPlanningRun(cwd);
145
+ logFeedEvent(cwd, agentName, "plan.cancel");
146
+ viewState.confirmAction = null;
147
+ setNotification(viewState, tui, true, "Planning cancelled");
148
+ tui.requestRender();
149
+ return;
150
+ }
151
+ const result = executeTaskAction(cwd, action.type, action.taskId, agentName);
152
+ if (action.type === "delete") {
153
+ const tasks = crewStore.getTasks(cwd);
154
+ if (tasks.length > 0) {
155
+ viewState.selectedTaskIndex = Math.max(0, Math.min(viewState.selectedTaskIndex, tasks.length - 1));
156
+ } else {
157
+ viewState.selectedTaskIndex = 0;
158
+ if (viewState.mode === "detail") viewState.mode = "list";
159
+ }
160
+ }
161
+ viewState.confirmAction = null;
162
+ setNotification(viewState, tui, result.success, result.message);
163
+ tui.requestRender();
164
+ return;
165
+ }
166
+ if (matchesKey(data, "n") || matchesKey(data, "escape")) {
167
+ viewState.confirmAction = null;
168
+ tui.requestRender();
169
+ }
170
+ }
171
+
172
+ export function handleBlockReasonInput(
173
+ data: string,
174
+ viewState: CrewViewState,
175
+ cwd: string,
176
+ task: Task | undefined,
177
+ agentName: string,
178
+ tui: TUI,
179
+ ): void {
180
+ if (matchesKey(data, "escape")) {
181
+ viewState.inputMode = "normal";
182
+ viewState.blockReasonInput = "";
183
+ tui.requestRender();
184
+ return;
185
+ }
186
+ if (matchesKey(data, "enter")) {
187
+ const reason = viewState.blockReasonInput.trim();
188
+ if (!reason || !task) return;
189
+ const result = executeTaskAction(cwd, "block", task.id, agentName, reason);
190
+ viewState.inputMode = "normal";
191
+ viewState.blockReasonInput = "";
192
+ setNotification(viewState, tui, result.success, result.message);
193
+ tui.requestRender();
194
+ return;
195
+ }
196
+ if (matchesKey(data, "backspace")) {
197
+ if (viewState.blockReasonInput.length > 0) {
198
+ viewState.blockReasonInput = viewState.blockReasonInput.slice(0, -1);
199
+ tui.requestRender();
200
+ }
201
+ return;
202
+ }
203
+ if (isPrintable(data)) {
204
+ viewState.blockReasonInput += data;
205
+ tui.requestRender();
206
+ }
207
+ }
208
+
209
+ export function handleRevisePromptInput(
210
+ data: string,
211
+ viewState: CrewViewState,
212
+ cwd: string,
213
+ task: Task | undefined,
214
+ agentName: string,
215
+ tui: TUI,
216
+ ): void {
217
+ if (matchesKey(data, "escape")) {
218
+ viewState.inputMode = "normal";
219
+ viewState.revisePromptInput = "";
220
+ tui.requestRender();
221
+ return;
222
+ }
223
+ if (matchesKey(data, "enter")) {
224
+ if (!task) return;
225
+ if (task.status === "in_progress") {
226
+ setNotification(viewState, tui, false, "Cannot revise in_progress task");
227
+ viewState.inputMode = "normal";
228
+ viewState.revisePromptInput = "";
229
+ tui.requestRender();
230
+ return;
231
+ }
232
+
233
+ const prompt = viewState.revisePromptInput.trim() || undefined;
234
+ const scope = viewState.reviseScope;
235
+ viewState.inputMode = "normal";
236
+ viewState.revisePromptInput = "";
237
+
238
+ const label = scope === "tree" ? `Revising ${task.id} + tree...` : `Revising ${task.id}...`;
239
+ setNotification(viewState, tui, true, label);
240
+
241
+ const vs = viewState;
242
+ const t = tui;
243
+ const fn = scope === "tree" ? "executeReviseTree" : "executeRevise";
244
+ import("./crew/handlers/revise.ts")
245
+ .then(m => m[fn](cwd, task.id, prompt, agentName))
246
+ .then(result => {
247
+ setNotification(vs, t, result.success, result.message);
248
+ })
249
+ .catch(err => {
250
+ logFeedEvent(
251
+ cwd,
252
+ agentName,
253
+ scope === "tree" ? "task.revise-tree" : "task.revise",
254
+ task.id,
255
+ `failed: ${err instanceof Error ? err.message : "unknown"}`,
256
+ );
257
+ });
258
+ tui.requestRender();
259
+ return;
260
+ }
261
+ if (matchesKey(data, "backspace")) {
262
+ if (viewState.revisePromptInput.length > 0) {
263
+ viewState.revisePromptInput = viewState.revisePromptInput.slice(0, -1);
264
+ tui.requestRender();
265
+ }
266
+ return;
267
+ }
268
+ if (isPrintable(data)) {
269
+ viewState.revisePromptInput += data;
270
+ tui.requestRender();
271
+ }
272
+ }
273
+
274
+ function resetMessageInput(viewState: CrewViewState): void {
275
+ viewState.inputMode = "normal";
276
+ viewState.messageInput = "";
277
+ viewState.mentionCandidates = [];
278
+ viewState.mentionIndex = -1;
279
+ }
280
+
281
+ function collectMentionCandidates(prefix: string, state: MessengerState, dirs: Dirs, cwd: string): string[] {
282
+ const seen = new Set<string>();
283
+ const names: string[] = [];
284
+
285
+ for (const agent of getActiveAgents(state, dirs)) {
286
+ if (agent.name === state.agentName) continue;
287
+ if (!seen.has(agent.name)) {
288
+ seen.add(agent.name);
289
+ names.push(agent.name);
290
+ }
291
+ }
292
+
293
+ for (const worker of getLiveWorkers(cwd).values()) {
294
+ if (!seen.has(worker.name)) {
295
+ seen.add(worker.name);
296
+ names.push(worker.name);
297
+ }
298
+ }
299
+
300
+ names.push("all");
301
+
302
+ if (!prefix) return names;
303
+ const lower = prefix.toLowerCase();
304
+ return names.filter(n => n.toLowerCase().startsWith(lower));
305
+ }
306
+
307
+ function sendDirectMessage(
308
+ state: MessengerState,
309
+ dirs: Dirs,
310
+ cwd: string,
311
+ target: string,
312
+ text: string,
313
+ tui: TUI,
314
+ viewState: CrewViewState,
315
+ ): void {
316
+ try {
317
+ const msg = sendMessageToAgent(state, dirs, target, text);
318
+ addToChatHistory(state, target, msg);
319
+ logFeedEvent(cwd, state.agentName, "message", target, previewText(text));
320
+ resetMessageInput(viewState);
321
+ setNotification(viewState, tui, true, `Sent to ${target}`);
322
+ tui.requestRender();
323
+ } catch (err) {
324
+ const msg = err instanceof Error ? err.message : "unknown error";
325
+ setNotification(viewState, tui, false, `Failed to send to ${target}: ${msg}`);
326
+ tui.requestRender();
327
+ }
328
+ }
329
+
330
+ function sendBroadcastMessage(
331
+ state: MessengerState,
332
+ dirs: Dirs,
333
+ cwd: string,
334
+ text: string,
335
+ tui: TUI,
336
+ viewState: CrewViewState,
337
+ ): void {
338
+ const peers = getActiveAgents(state, dirs);
339
+ if (peers.length === 0) {
340
+ setNotification(viewState, tui, false, "No peers available for @all");
341
+ tui.requestRender();
342
+ return;
343
+ }
344
+
345
+ let sentCount = 0;
346
+ for (const peer of peers) {
347
+ try {
348
+ sendMessageToAgent(state, dirs, peer.name, text);
349
+ sentCount++;
350
+ } catch {
351
+ // Ignore per-recipient failures
352
+ }
353
+ }
354
+
355
+ if (sentCount === 0) {
356
+ setNotification(viewState, tui, false, "Broadcast failed");
357
+ tui.requestRender();
358
+ return;
359
+ }
360
+
361
+ addToBroadcastHistory(state, text);
362
+ logFeedEvent(cwd, state.agentName, "message", undefined, previewText(text));
363
+ resetMessageInput(viewState);
364
+ setNotification(viewState, tui, true, `Broadcast to ${sentCount} peer${sentCount === 1 ? "" : "s"}`);
365
+ tui.requestRender();
366
+ }
367
+
368
+ export function handleMessageInput(
369
+ data: string,
370
+ viewState: CrewViewState,
371
+ state: MessengerState,
372
+ dirs: Dirs,
373
+ cwd: string,
374
+ tui: TUI,
375
+ ): void {
376
+ if (matchesKey(data, "escape")) {
377
+ resetMessageInput(viewState);
378
+ tui.requestRender();
379
+ return;
380
+ }
381
+
382
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
383
+ const input = viewState.messageInput;
384
+ const cycling = viewState.mentionIndex >= 0 && viewState.mentionCandidates.length > 0;
385
+ if (!input.startsWith("@") || (input.includes(" ") && !cycling)) return;
386
+
387
+ const reverse = matchesKey(data, "shift+tab");
388
+
389
+ if (!cycling) {
390
+ const prefix = input.slice(1);
391
+ viewState.mentionCandidates = collectMentionCandidates(prefix, state, dirs, cwd);
392
+ if (viewState.mentionCandidates.length === 0) return;
393
+ viewState.mentionIndex = 0;
394
+ } else {
395
+ const delta = reverse ? -1 : 1;
396
+ viewState.mentionIndex =
397
+ (viewState.mentionIndex + delta + viewState.mentionCandidates.length) % viewState.mentionCandidates.length;
398
+ }
399
+
400
+ viewState.messageInput = `@${viewState.mentionCandidates[viewState.mentionIndex]} `;
401
+ tui.requestRender();
402
+ return;
403
+ }
404
+
405
+ if (matchesKey(data, "enter")) {
406
+ const raw = viewState.messageInput.trim();
407
+ if (!raw) return;
408
+
409
+ if (raw.startsWith("@all ")) {
410
+ const text = raw.slice(5).trim();
411
+ if (!text) return;
412
+ sendBroadcastMessage(state, dirs, cwd, text, tui, viewState);
413
+ return;
414
+ }
415
+
416
+ if (raw.startsWith("@")) {
417
+ const firstSpace = raw.indexOf(" ");
418
+ if (firstSpace <= 1) {
419
+ setNotification(viewState, tui, false, "Use @name <message> or type to broadcast");
420
+ tui.requestRender();
421
+ return;
422
+ }
423
+
424
+ const target = raw.slice(1, firstSpace).trim();
425
+ const text = raw.slice(firstSpace + 1).trim();
426
+ if (!target || !text) {
427
+ setNotification(viewState, tui, false, "Use @name <message> or type to broadcast");
428
+ tui.requestRender();
429
+ return;
430
+ }
431
+
432
+ sendDirectMessage(state, dirs, cwd, target, text, tui, viewState);
433
+ return;
434
+ }
435
+
436
+ sendBroadcastMessage(state, dirs, cwd, raw, tui, viewState);
437
+ return;
438
+ }
439
+
440
+ if (matchesKey(data, "backspace")) {
441
+ if (viewState.messageInput.length > 0) {
442
+ viewState.messageInput = viewState.messageInput.slice(0, -1);
443
+ viewState.mentionCandidates = [];
444
+ viewState.mentionIndex = -1;
445
+ tui.requestRender();
446
+ }
447
+ return;
448
+ }
449
+
450
+ if (isPrintable(data)) {
451
+ viewState.messageInput += data;
452
+ viewState.mentionCandidates = [];
453
+ viewState.mentionIndex = -1;
454
+ tui.requestRender();
455
+ }
456
+ }
457
+
458
+ export function handleCrewKeyBinding(
459
+ data: string,
460
+ task: Task,
461
+ viewState: CrewViewState,
462
+ cwd: string,
463
+ agentName: string,
464
+ tui: TUI,
465
+ ): void {
466
+ if (matchesKey(data, "r") && ["done", "blocked", "in_progress"].includes(task.status)) {
467
+ viewState.confirmAction = { type: "reset", taskId: task.id, label: task.title };
468
+ tui.requestRender();
469
+ return;
470
+ }
471
+ if (matchesKey(data, "shift+r") && ["done", "blocked", "in_progress"].includes(task.status)) {
472
+ viewState.confirmAction = { type: "cascade-reset", taskId: task.id, label: task.title };
473
+ tui.requestRender();
474
+ return;
475
+ }
476
+ if (matchesKey(data, "u") && task.status === "blocked") {
477
+ const result = executeTaskAction(cwd, "unblock", task.id, agentName);
478
+ setNotification(viewState, tui, result.success, result.message);
479
+ tui.requestRender();
480
+ return;
481
+ }
482
+ if (matchesKey(data, "shift+s") && task.status !== "done" && !task.milestone) {
483
+ setNotification(viewState, tui, true, `Split: pi_messenger({ action: "task.split", id: "${task.id}" })`);
484
+ tui.requestRender();
485
+ return;
486
+ }
487
+ if (matchesKey(data, "b") && task.status === "in_progress") {
488
+ viewState.inputMode = "block-reason";
489
+ viewState.blockReasonInput = "";
490
+ tui.requestRender();
491
+ return;
492
+ }
493
+ if (matchesKey(data, "q") && task.status === "in_progress") {
494
+ const result = executeTaskAction(cwd, "stop", task.id, agentName);
495
+ setNotification(viewState, tui, result.success, result.message);
496
+ tui.requestRender();
497
+ return;
498
+ }
499
+ if (matchesKey(data, "x")) {
500
+ if (task.status === "in_progress" && hasLiveWorker(cwd, task.id)) return;
501
+ viewState.confirmAction = { type: "delete", taskId: task.id, label: task.title };
502
+ tui.requestRender();
503
+ return;
504
+ }
505
+ if (matchesKey(data, "p") && task.status !== "in_progress" && !task.milestone) {
506
+ viewState.inputMode = "revise-prompt";
507
+ viewState.reviseScope = "single";
508
+ viewState.revisePromptInput = "";
509
+ tui.requestRender();
510
+ return;
511
+ }
512
+ if (matchesKey(data, "shift+p") && task.status !== "in_progress" && !task.milestone) {
513
+ viewState.inputMode = "revise-prompt";
514
+ viewState.reviseScope = "tree";
515
+ viewState.revisePromptInput = "";
516
+ tui.requestRender();
517
+ return;
518
+ }
519
+ }