@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
package/index.ts ADDED
@@ -0,0 +1,1206 @@
1
+ /**
2
+ * Pi Messenger Extension
3
+ *
4
+ * Enables pi agents to discover and communicate with each other across terminal sessions.
5
+ * Uses file-based coordination - no daemon required.
6
+ */
7
+
8
+ import { homedir } from "node:os";
9
+ import * as fs from "node:fs";
10
+ import { join } from "node:path";
11
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import type { OverlayHandle, TUI } from "@earendil-works/pi-tui";
13
+ import { truncateToWidth } from "@earendil-works/pi-tui";
14
+ import { Type, type TSchema } from "typebox";
15
+
16
+ function StringEnum<T extends readonly string[]>(
17
+ values: T,
18
+ options?: { description?: string; default?: T[number] },
19
+ ): TSchema {
20
+ const unsafe = (Type as unknown as {
21
+ Unsafe?: (schema: Record<string, unknown>) => TSchema;
22
+ }).Unsafe;
23
+
24
+ if (typeof unsafe === "function") {
25
+ return unsafe({
26
+ type: "string",
27
+ enum: [...values],
28
+ ...(options?.description && { description: options.description }),
29
+ ...(options?.default && { default: options.default }),
30
+ });
31
+ }
32
+
33
+ return Type.Union(
34
+ values.map((value) => Type.Literal(value)),
35
+ options,
36
+ );
37
+ }
38
+ import {
39
+ type MessengerState,
40
+ type Dirs,
41
+ type AgentMailMessage,
42
+ MAX_CHAT_HISTORY,
43
+ formatRelativeTime,
44
+ normalizeAgentMailMessage,
45
+ stripAnsiCodes,
46
+ extractFolder,
47
+ generateAutoStatus,
48
+ computeStatus,
49
+ agentHasTask,
50
+ } from "./lib.ts";
51
+ import * as store from "./store.ts";
52
+ import * as handlers from "./handlers.ts";
53
+ import { MessengerOverlay, type OverlayCallbacks } from "./overlay.ts";
54
+ import { MessengerConfigOverlay } from "./config-overlay.ts";
55
+ import { loadConfig, loadGlobalConfig, matchesAutoRegisterPath, type MessengerConfig } from "./config.ts";
56
+ import { executeCrewAction } from "./crew/index.ts";
57
+ import { logFeedEvent, pruneFeed } from "./feed.ts";
58
+ import type { CrewParams } from "./crew/types.ts";
59
+ import {
60
+ autonomousState,
61
+ clearPlanningState,
62
+ consumePendingAutoWork,
63
+ consumePlanningOverlayPending,
64
+ dismissPlanningOverlayRun,
65
+ getPlanningOverlayPending,
66
+ isPlanningForCwd,
67
+ isPlanningStalled,
68
+ markPlanningOverlayPending,
69
+ planningState,
70
+ restoreAutonomousState,
71
+ restorePlanningState,
72
+ stopAutonomous,
73
+ isAutonomousForCwd,
74
+ } from "./crew/state.ts";
75
+ import { loadCrewConfig } from "./crew/utils/config.ts";
76
+ import * as crewStore from "./crew/store.ts";
77
+ import * as teamStore from "./crew/team/store.ts";
78
+ import { runLegacyAgentCleanupMigration } from "./crew/utils/install.ts";
79
+ import { getLiveWorkers, onLiveWorkersChanged } from "./crew/live-progress.ts";
80
+ import { shutdownAllWorkers } from "./crew/agents.ts";
81
+ import { shutdownLobbyWorkers } from "./crew/lobby.ts";
82
+
83
+ let overlayTui: TUI | null = null;
84
+ let overlayHandle: OverlayHandle | null = null;
85
+ let overlayOpening = false;
86
+
87
+ export default function piMessengerExtension(pi: ExtensionAPI) {
88
+ // One-time migration: remove stale crew agents from shared ~/.pi/agent/agents/
89
+ // (crew agents now discovered from extension-local directory)
90
+ runLegacyAgentCleanupMigration();
91
+
92
+ // ===========================================================================
93
+ // State & Configuration
94
+ // ===========================================================================
95
+
96
+ let config: MessengerConfig = loadGlobalConfig();
97
+
98
+ const state: MessengerState = {
99
+ agentName: process.env.PI_AGENT_NAME || "",
100
+ registered: false,
101
+ watcher: null,
102
+ watcherRetries: 0,
103
+ watcherRetryTimer: null,
104
+ watcherDebounceTimer: null,
105
+ reservations: [],
106
+ chatHistory: new Map(),
107
+ unreadCounts: new Map(),
108
+ broadcastHistory: [],
109
+ seenSenders: new Map(),
110
+ model: "",
111
+ cwd: "",
112
+ gitBranch: undefined,
113
+ spec: undefined,
114
+ scopeToFolder: config.scopeToFolder,
115
+ isHuman: false,
116
+ session: { toolCalls: 0, tokens: 0, filesModified: [] },
117
+ activity: { lastActivityAt: new Date().toISOString() },
118
+ statusMessage: undefined,
119
+ customStatus: false,
120
+ registryFlushTimer: null,
121
+ sessionStartedAt: new Date().toISOString(),
122
+ };
123
+
124
+ const nameTheme = { theme: config.nameTheme, customWords: config.nameWords };
125
+
126
+ const baseDir = process.env.PI_MESSENGER_DIR || join(homedir(), ".pi/agent/messenger");
127
+ const dirs: Dirs = {
128
+ base: baseDir,
129
+ registry: join(baseDir, "registry"),
130
+ inbox: join(baseDir, "inbox")
131
+ };
132
+
133
+ // ===========================================================================
134
+ // Message Delivery
135
+ // ===========================================================================
136
+
137
+ function deliverMessage(msg: AgentMailMessage): void {
138
+ // Store in chat history (keyed by sender)
139
+ let history = state.chatHistory.get(msg.from);
140
+ if (!history) {
141
+ history = [];
142
+ state.chatHistory.set(msg.from, history);
143
+ }
144
+ history.push(msg);
145
+ if (history.length > MAX_CHAT_HISTORY) history.shift();
146
+
147
+ // Increment unread count
148
+ const current = state.unreadCounts.get(msg.from) ?? 0;
149
+ state.unreadCounts.set(msg.from, current + 1);
150
+
151
+ // Trigger overlay re-render if open
152
+ overlayTui?.requestRender();
153
+
154
+ // Build message content with optional context
155
+ // Detect if this is a new agent identity (first contact OR same name but different session)
156
+ const sender = store.getActiveAgents(state, dirs).find(a => a.name === msg.from);
157
+ const senderSessionId = sender?.sessionId;
158
+ const prevSessionId = state.seenSenders.get(msg.from);
159
+ const isNewIdentity = !prevSessionId || (senderSessionId && prevSessionId !== senderSessionId);
160
+
161
+ // Update seen senders with current sessionId (only if we could look it up)
162
+ if (senderSessionId) {
163
+ state.seenSenders.set(msg.from, senderSessionId);
164
+ }
165
+
166
+ let content = "";
167
+
168
+ // Add sender details on new identity (first contact or agent restart with same name)
169
+ if (isNewIdentity && config.senderDetailsOnFirstContact && sender) {
170
+ const folder = extractFolder(sender.cwd);
171
+ const locationPart = sender.gitBranch
172
+ ? `${folder} on ${sender.gitBranch}`
173
+ : folder;
174
+ content += `*${msg.from} is in ${locationPart} (${sender.model})*\n\n`;
175
+ }
176
+
177
+ // Add reply hint
178
+ const replyHint = config.replyHint
179
+ ? ` — reply: pi_messenger({ action: "send", to: "${msg.from}", message: "..." })`
180
+ : "";
181
+
182
+ content += `**Message from ${msg.from}**${replyHint}\n\n${msg.text}`;
183
+
184
+ if (msg.replyTo) {
185
+ content = `*(reply to ${msg.replyTo.substring(0, 8)})*\n\n${content}`;
186
+ }
187
+
188
+ pi.sendMessage(
189
+ { customType: "agent_message", content, display: true, details: msg },
190
+ { triggerTurn: true, deliverAs: "steer" }
191
+ );
192
+ }
193
+
194
+ // ===========================================================================
195
+ // Stuck Detection
196
+ // ===========================================================================
197
+
198
+ const notifiedStuck = new Set<string>();
199
+
200
+ function checkStuckAgents(ctx: ExtensionContext, peers: ReturnType<typeof store.getActiveAgents>): void {
201
+ if (!config.stuckNotify || !ctx.hasUI || !state.registered) return;
202
+
203
+ const thresholdMs = config.stuckThreshold * 1000;
204
+ const allClaims = store.getClaims(dirs);
205
+ const tasksByCwd = new Map<string, ReturnType<typeof crewStore.getTasks>>();
206
+ const currentlyStuck = new Set<string>();
207
+
208
+ for (const agent of peers) {
209
+ let tasks = tasksByCwd.get(agent.cwd);
210
+ if (!tasks) {
211
+ tasks = crewStore.getTasks(agent.cwd);
212
+ tasksByCwd.set(agent.cwd, tasks);
213
+ }
214
+ const hasTask = agentHasTask(agent.name, allClaims, tasks);
215
+ const computed = computeStatus(
216
+ agent.activity?.lastActivityAt ?? agent.startedAt,
217
+ hasTask,
218
+ (agent.reservations?.length ?? 0) > 0,
219
+ thresholdMs
220
+ );
221
+
222
+ if (computed.status === "stuck") {
223
+ currentlyStuck.add(agent.name);
224
+
225
+ if (!notifiedStuck.has(agent.name)) {
226
+ notifiedStuck.add(agent.name);
227
+ logFeedEvent(ctx.cwd, agent.name, "stuck");
228
+
229
+ const idleStr = computed.idleFor ?? "unknown";
230
+ const taskInfo = hasTask ? " with task in progress" : " with reservation";
231
+ ctx.ui.notify(`\u26A0\uFE0F ${agent.name} appears stuck (idle ${idleStr}${taskInfo})`, "warning");
232
+ }
233
+ }
234
+ }
235
+
236
+ for (const name of notifiedStuck) {
237
+ if (!currentlyStuck.has(name)) {
238
+ notifiedStuck.delete(name);
239
+ }
240
+ }
241
+ }
242
+
243
+ // ===========================================================================
244
+ // Status
245
+ // ===========================================================================
246
+
247
+ function updateStatus(ctx: ExtensionContext): void {
248
+ try {
249
+ if (!ctx.hasUI || !state.registered) return;
250
+
251
+ const agents = store.getActiveAgents(state, dirs);
252
+ checkStuckAgents(ctx, agents);
253
+ const activeNames = new Set(agents.map(a => a.name));
254
+ const count = agents.length;
255
+ const theme = ctx.ui.theme;
256
+
257
+ for (const name of state.unreadCounts.keys()) {
258
+ if (!activeNames.has(name)) {
259
+ state.unreadCounts.delete(name);
260
+ }
261
+ }
262
+ for (const name of notifiedStuck) {
263
+ if (!activeNames.has(name)) {
264
+ notifiedStuck.delete(name);
265
+ }
266
+ }
267
+
268
+ // Sum remaining unread counts
269
+ let totalUnread = 0;
270
+ for (const n of state.unreadCounts.values()) totalUnread += n;
271
+
272
+ const nameStr = theme.fg("accent", state.agentName);
273
+ const countStr = theme.fg("dim", ` (${count} peer${count === 1 ? "" : "s"})`);
274
+ const unreadStr = totalUnread > 0 ? theme.fg("accent", ` ●${totalUnread}`) : "";
275
+
276
+ const planningCwd = ctx.cwd;
277
+ const planningStr =
278
+ isPlanningForCwd(planningCwd)
279
+ ? theme.fg(
280
+ "warning",
281
+ ` · plan ${planningState.pass}/${planningState.maxPasses} ${planningState.phase}${isPlanningStalled(planningCwd) ? " stalled" : ""}`,
282
+ )
283
+ : "";
284
+
285
+ const activityStr = !planningStr && state.activity.currentActivity
286
+ ? theme.fg("dim", ` · ${state.activity.currentActivity}`)
287
+ : "";
288
+
289
+ // Add crew status if autonomous mode is active
290
+ let crewStr = "";
291
+ if (autonomousState.active) {
292
+ const cwd = ctx.cwd;
293
+ const plan = crewStore.getPlan(cwd);
294
+ if (plan) {
295
+ const workerCount = getLiveWorkers(cwd).size;
296
+ crewStr = theme.fg("accent", ` ⚡${plan.completed_count}/${plan.task_count}`);
297
+ if (workerCount > 0) {
298
+ crewStr += theme.fg("dim", ` 🔨${workerCount}`);
299
+ }
300
+ }
301
+ }
302
+
303
+ ctx.ui.setStatus("messenger", `msg: ${nameStr}${countStr}${unreadStr}${planningStr}${activityStr}${crewStr}`);
304
+
305
+ maybeAutoOpenCrewOverlay(ctx);
306
+ } catch (error) {
307
+ if (!(error instanceof Error) || !error.message.includes("extension ctx is stale")) {
308
+ throw error;
309
+ }
310
+
311
+ latestCtx = null;
312
+ stopStatusHeartbeat();
313
+ }
314
+ }
315
+
316
+ function clearAllUnreadCounts(): void {
317
+ for (const key of state.unreadCounts.keys()) {
318
+ state.unreadCounts.set(key, 0);
319
+ }
320
+ }
321
+
322
+ const STATUS_HEARTBEAT_MS = 15_000;
323
+ let latestCtx: ExtensionContext | null = null;
324
+ let statusHeartbeatTimer: ReturnType<typeof setInterval> | null = null;
325
+ const AUTONOMOUS_CONTINUE_REPEAT_LIMIT = 3;
326
+ let autonomousContinueSignature: string | null = null;
327
+ let autonomousContinueRepeats = 0;
328
+
329
+ function resetAutonomousContinueGuard(): void {
330
+ autonomousContinueSignature = null;
331
+ autonomousContinueRepeats = 0;
332
+ }
333
+
334
+ function trackAutonomousContinue(signature: string): number {
335
+ if (autonomousContinueSignature === signature) {
336
+ autonomousContinueRepeats += 1;
337
+ } else {
338
+ autonomousContinueSignature = signature;
339
+ autonomousContinueRepeats = 1;
340
+ }
341
+ return autonomousContinueRepeats;
342
+ }
343
+
344
+ function startStatusHeartbeat(): void {
345
+ if (statusHeartbeatTimer) return;
346
+ statusHeartbeatTimer = setInterval(() => {
347
+ if (latestCtx) updateStatus(latestCtx);
348
+ }, STATUS_HEARTBEAT_MS);
349
+ }
350
+
351
+ function stopStatusHeartbeat(): void {
352
+ if (!statusHeartbeatTimer) return;
353
+ clearInterval(statusHeartbeatTimer);
354
+ statusHeartbeatTimer = null;
355
+ }
356
+
357
+ function captureStatusContext(ctx: ExtensionContext): void {
358
+ latestCtx = ctx;
359
+ startStatusHeartbeat();
360
+ }
361
+
362
+ onLiveWorkersChanged(() => {
363
+ if (latestCtx) updateStatus(latestCtx);
364
+ });
365
+
366
+ // ===========================================================================
367
+ // Registration Context
368
+ // ===========================================================================
369
+
370
+ function sendRegistrationContext(ctx: ExtensionContext): void {
371
+ const folder = extractFolder(ctx.cwd ?? state.cwd);
372
+ const locationPart = state.gitBranch
373
+ ? `${folder} on ${state.gitBranch}`
374
+ : folder;
375
+ pi.sendMessage({
376
+ customType: "messenger_context",
377
+ content: `You are agent "${state.agentName}" in ${locationPart}. Use pi_messenger({ action: "status" }) to see crew status, pi_messenger({ action: "work" }) to run tasks.`,
378
+ display: false
379
+ }, { triggerTurn: false });
380
+ }
381
+
382
+ // ===========================================================================
383
+ // Tool Registration
384
+ // ===========================================================================
385
+
386
+ pi.registerTool({
387
+ name: "pi_messenger",
388
+ label: "Pi Messenger",
389
+ description: `Multi-agent coordination and task orchestration.
390
+
391
+ Usage (action-based API - preferred):
392
+ // Coordination
393
+ pi_messenger({ action: "join" }) → Join mesh
394
+ pi_messenger({ action: "leave" }) → Leave mesh for this session
395
+ pi_messenger({ action: "status" }) → Get status
396
+ pi_messenger({ action: "list" }) → List agents with presence
397
+ pi_messenger({ action: "feed", limit: 20 }) → Activity feed
398
+ pi_messenger({ action: "whois", name: "AgentName" }) → Agent details
399
+ pi_messenger({ action: "set_status", message: "reviewing" }) → Set custom status
400
+ pi_messenger({ action: "reserve", paths: ["src/"] }) → Reserve files
401
+ pi_messenger({ action: "send", to: "Agent", message: "hi" }) → Send message
402
+
403
+ // Crew: Plan from PRD
404
+ pi_messenger({ action: "plan" }) → Auto-discover PRD
405
+ pi_messenger({ action: "plan", prd: "docs/PRD.md" }) → Explicit PRD path
406
+ pi_messenger({ action: "plan", prompt: "Scan for bugs" }) → Inline prompt (no PRD)
407
+ pi_messenger({ action: "plan.cancel" }) → Cancel active planning
408
+
409
+ // Crew: Work through tasks
410
+ pi_messenger({ action: "work" }) → Run ready tasks
411
+ pi_messenger({ action: "work", autonomous: true }) → Run until done/blocked
412
+ pi_messenger({ action: "work.stop" }) → Stop autonomous work for this project
413
+
414
+ // Crew: Tasks
415
+ pi_messenger({ action: "task.show", id: "task-1" }) → Show task
416
+ pi_messenger({ action: "task.list" }) → List all tasks
417
+ pi_messenger({ action: "task.split", id: "task-3" }) → Inspect task for splitting
418
+ pi_messenger({ action: "task.split", id: "task-3", subtasks: [...] }) → Execute split
419
+ pi_messenger({ action: "task.start", id: "task-1" }) → Start task
420
+ pi_messenger({ action: "task.approve", id: "task-1" }) → Approve gated task
421
+ pi_messenger({ action: "task.reject", id: "task-1", reason: "..." }) → Reject gated task and feed revision
422
+ pi_messenger({ action: "task.done", id: "task-1", summary: "..." })
423
+ pi_messenger({ action: "task.reset", id: "task-1" }) → Reset task
424
+
425
+ // Crew: Review
426
+ pi_messenger({ action: "review", target: "task-1" }) → Review impl
427
+
428
+ // Team: Optional role-aware layer around Crew
429
+ pi_messenger({ action: "team.setup", name: "migration-squad" }) → Activate profile, create starter charter, show next steps
430
+ pi_messenger({ action: "team.profile.list" }) → List built-in and saved team profiles
431
+ pi_messenger({ action: "team.profile.use", name: "migration-squad" }) → Activate a team profile
432
+ pi_messenger({ action: "team.charter.show" }) → Show project team charter
433
+ pi_messenger({ action: "team.memory.note", type: "decision", message: "..." })
434
+ pi_messenger({ action: "team.roles" }) → Resolve Team roles (packaged pi-subagents vocabulary + optional metadata)
435
+ pi_messenger({ action: "team.status" }) → Team summary`,
436
+ promptSnippet:
437
+ "Use for multi-agent coordination and Crew workflows: join/status/feed, create plans, run work waves, manage tasks, optional Team roles/profiles, reserve files, and message agents.",
438
+ parameters: Type.Object({
439
+ action: Type.Optional(Type.String({
440
+ description: "Action to perform (e.g., 'join', 'plan', 'work', 'task.start')"
441
+ })),
442
+
443
+ // ═══════════════════════════════════════════════════════════════════════
444
+ // CREW PARAMETERS
445
+ // ═══════════════════════════════════════════════════════════════════════
446
+ prd: Type.Optional(Type.String({ description: "PRD file path for plan action" })),
447
+ prompt: Type.Optional(Type.String({ description: "Inline prompt for plan action, or revision instructions for task.revise/task.revise-tree" })),
448
+ id: Type.Optional(Type.String({ description: "Task ID (task-N format)" })),
449
+ taskId: Type.Optional(Type.String({ description: "Swarm task ID (e.g., TASK-01) - for action-based claim/unclaim/complete" })),
450
+ title: Type.Optional(Type.String({ description: "Title for task.create" })),
451
+ dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task IDs this task depends on (for task.create)" })),
452
+ role: Type.Optional(Type.String({ description: "Team role for task creation/planning (built-ins follow packaged pi-subagents vocabulary; profiles may define more)" })),
453
+ riskLabels: Type.Optional(Type.Array(Type.String(), { description: "Team risk labels for approval policy" })),
454
+ target: Type.Optional(Type.String({ description: "Task ID for review action" })),
455
+ summary: Type.Optional(Type.String({ description: "Summary for task.done" })),
456
+ evidence: Type.Optional(Type.Object({
457
+ commits: Type.Optional(Type.Array(Type.String())),
458
+ tests: Type.Optional(Type.Array(Type.String())),
459
+ prs: Type.Optional(Type.Array(Type.String()))
460
+ }, { description: "Evidence for task.done" })),
461
+ content: Type.Optional(Type.String({ description: "Content for task spec" })),
462
+ count: Type.Optional(Type.Number({ description: "Suggested number of subtasks for task.split" })),
463
+ subtasks: Type.Optional(Type.Array(
464
+ Type.Object({
465
+ title: Type.String(),
466
+ content: Type.Optional(Type.String()),
467
+ }),
468
+ { description: "Subtask definitions for task.split (execute phase)" }
469
+ )),
470
+ type: Type.Optional(StringEnum(["plan", "impl", "decision", "interface", "risk", "handoff"], { description: "Review type, or Team memory type for team.memory.*" })),
471
+ autoWork: Type.Optional(Type.Boolean({ description: "Auto-start autonomous work after plan completes (default: true, pass false to review plan first)" })),
472
+ autonomous: Type.Optional(Type.Boolean({ description: "Run work continuously until done/blocked" })),
473
+ concurrency: Type.Optional(Type.Number({ description: "Override worker concurrency" })),
474
+ model: Type.Optional(Type.String({ description: "Override worker model for this work wave" })),
475
+ cascade: Type.Optional(Type.Boolean({ description: "For task.reset - also reset dependent tasks" })),
476
+ limit: Type.Optional(Type.Number({ description: "Number of events to return (for feed action, default 20)" })),
477
+ paths: Type.Optional(Type.Array(Type.String(), { description: "Paths for reserve/release actions" })),
478
+ name: Type.Optional(Type.String({ description: "Name for rename action or Team setup/profile/charter commands" })),
479
+
480
+ // ═══════════════════════════════════════════════════════════════════════
481
+ // MESSAGING & COORDINATION PARAMETERS
482
+ // ═══════════════════════════════════════════════════════════════════════
483
+ spec: Type.Optional(Type.String({ description: "Path to spec/plan file" })),
484
+ notes: Type.Optional(Type.String({ description: "Completion notes" })),
485
+ to: Type.Optional(Type.Any({ description: "Target agent name (string) or multiple names (array)" })),
486
+ message: Type.Optional(Type.String({ description: "Message to send, Team setup/charter text, or Team memory note" })),
487
+ replyTo: Type.Optional(Type.String({ description: "Message ID if this is a reply" })),
488
+ reason: Type.Optional(Type.String({ description: "Reason for reservation, claim, task block, or approval rejection feedback" })),
489
+ autoRegisterPath: Type.Optional(StringEnum(["add", "remove", "list"], { description: "Manage auto-register paths: add/remove current folder, or list all" }))
490
+ }),
491
+
492
+ async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
493
+ const params = rawParams as CrewParams;
494
+ captureStatusContext(ctx);
495
+
496
+ const action = params.action;
497
+ if (!action) {
498
+ return handlers.executeStatus(state, dirs, ctx.cwd);
499
+ }
500
+
501
+ const result = await executeCrewAction(
502
+ action,
503
+ params,
504
+ state,
505
+ dirs,
506
+ ctx,
507
+ deliverMessage,
508
+ updateStatus,
509
+ (type, data) => pi.appendEntry(type, data),
510
+ { stuckThreshold: config.stuckThreshold, crewEventsInFeed: config.crewEventsInFeed, nameTheme, feedRetention: config.feedRetention },
511
+ signal
512
+ );
513
+
514
+ if (action === "join" && state.registered && config.registrationContext) {
515
+ sendRegistrationContext(ctx);
516
+ }
517
+
518
+ if (action === "leave" && !state.registered) {
519
+ overlayHandle?.hide();
520
+ overlayHandle = null;
521
+ overlayTui = null;
522
+ overlayOpening = false;
523
+ }
524
+
525
+ return result;
526
+ }
527
+ });
528
+
529
+ // ===========================================================================
530
+ // Commands
531
+ // ===========================================================================
532
+
533
+ pi.registerCommand("messenger", {
534
+ description: "Open messenger overlay, or 'config' to manage settings",
535
+ handler: async (args, ctx) => {
536
+ captureStatusContext(ctx);
537
+ if (!ctx.hasUI) return;
538
+
539
+ // /messenger config - open config overlay
540
+ if (args[0] === "config") {
541
+ await ctx.ui.custom<void>(
542
+ (tui, theme, _keybindings, done) => {
543
+ return new MessengerConfigOverlay(tui, theme, done, ctx.cwd);
544
+ },
545
+ { overlay: true }
546
+ );
547
+ return;
548
+ }
549
+
550
+ // /messenger - open chat overlay (auto-joins if not registered)
551
+ if (!state.registered) {
552
+ if (!store.register(state, dirs, ctx, nameTheme)) {
553
+ ctx.ui.notify("Failed to join agent mesh", "error");
554
+ return;
555
+ }
556
+ store.startWatcher(state, dirs, deliverMessage);
557
+ updateStatus(ctx);
558
+ }
559
+
560
+ if (overlayHandle && overlayHandle.isHidden()) {
561
+ overlayHandle.setHidden(false);
562
+ clearAllUnreadCounts();
563
+ updateStatus(ctx);
564
+ return;
565
+ }
566
+
567
+ const callbacks: OverlayCallbacks = {
568
+ onBackground: (snapshotText) => {
569
+ overlayHandle?.setHidden(true);
570
+ pi.sendMessage({
571
+ customType: "crew_snapshot",
572
+ content: snapshotText,
573
+ display: true,
574
+ }, { triggerTurn: true });
575
+ },
576
+ };
577
+
578
+ const snapshot = await ctx.ui.custom<string | undefined>(
579
+ (tui, theme, _keybindings, done) => {
580
+ overlayTui = tui;
581
+ return new MessengerOverlay(tui, theme, state, dirs, done, callbacks, ctx.cwd);
582
+ },
583
+ {
584
+ overlay: true,
585
+ onHandle: (handle) => {
586
+ overlayHandle = handle;
587
+ },
588
+ }
589
+ );
590
+
591
+ if (snapshot) {
592
+ pi.sendMessage({
593
+ customType: "crew_snapshot",
594
+ content: snapshot,
595
+ display: true,
596
+ }, { triggerTurn: true });
597
+ }
598
+
599
+ // Overlay closed
600
+ clearAllUnreadCounts();
601
+ overlayHandle = null;
602
+ overlayTui = null;
603
+ updateStatus(ctx);
604
+ }
605
+ });
606
+
607
+ // ===========================================================================
608
+ // Message Renderer
609
+ // ===========================================================================
610
+
611
+ pi.registerMessageRenderer<AgentMailMessage>("agent_message", (message, _options, theme) => {
612
+ if (!message.details) return undefined;
613
+ const details = normalizeAgentMailMessage(message.details, {
614
+ id: "",
615
+ from: "",
616
+ to: "",
617
+ timestamp: "",
618
+ });
619
+
620
+ return {
621
+ render(width: number): string[] {
622
+ const safeFrom = stripAnsiCodes(details.from);
623
+ const safeText = stripAnsiCodes(details.text);
624
+
625
+ const header = theme.fg("accent", `From ${safeFrom}`);
626
+ const time = details.timestamp ? theme.fg("dim", ` (${formatRelativeTime(details.timestamp)})`) : "";
627
+
628
+ const result: string[] = [];
629
+ result.push(truncateToWidth(header + time, width));
630
+ result.push("");
631
+
632
+ for (const line of safeText.split("\n")) {
633
+ result.push(truncateToWidth(line, width));
634
+ }
635
+
636
+ return result;
637
+ },
638
+ invalidate() {}
639
+ };
640
+ });
641
+
642
+ // ===========================================================================
643
+ // Activity Tracking
644
+ // ===========================================================================
645
+
646
+ const EDIT_DEBOUNCE_MS = 5000;
647
+ const REGISTRY_FLUSH_MS = 10000;
648
+ const RECENT_WINDOW_MS = 60_000;
649
+ const pendingEdits = new Map<string, ReturnType<typeof setTimeout>>();
650
+ let recentCommit = false;
651
+ let recentCommitTimer: ReturnType<typeof setTimeout> | null = null;
652
+ let recentTestRuns = 0;
653
+ let recentTestTimer: ReturnType<typeof setTimeout> | null = null;
654
+ let recentEdits = 0;
655
+ let recentEditTimer: ReturnType<typeof setTimeout> | null = null;
656
+
657
+ function updateLastActivity(): void {
658
+ state.activity.lastActivityAt = new Date().toISOString();
659
+ }
660
+
661
+ function incrementToolCount(): void {
662
+ state.session.toolCalls++;
663
+ }
664
+
665
+ function setCurrentActivity(activity: string): void {
666
+ state.activity.currentActivity = activity;
667
+ }
668
+
669
+ function clearCurrentActivity(): void {
670
+ state.activity.currentActivity = undefined;
671
+ }
672
+
673
+ function setLastToolCall(toolCall: string): void {
674
+ state.activity.lastToolCall = toolCall;
675
+ }
676
+
677
+ function addModifiedFile(filePath: string): void {
678
+ const files = state.session.filesModified;
679
+ const idx = files.indexOf(filePath);
680
+ if (idx !== -1) files.splice(idx, 1);
681
+ files.push(filePath);
682
+ if (files.length > 20) files.shift();
683
+ }
684
+
685
+ function debouncedLogEdit(filePath: string, cwd: string): void {
686
+ const existing = pendingEdits.get(filePath);
687
+ if (existing) clearTimeout(existing);
688
+ pendingEdits.set(filePath, setTimeout(() => {
689
+ logFeedEvent(cwd, state.agentName, "edit", filePath);
690
+ pendingEdits.delete(filePath);
691
+ }, EDIT_DEBOUNCE_MS));
692
+ }
693
+
694
+ function scheduleRegistryFlush(ctx: ExtensionContext): void {
695
+ if (state.registryFlushTimer) return;
696
+ state.registryFlushTimer = setTimeout(() => {
697
+ state.registryFlushTimer = null;
698
+ store.flushActivityToRegistry(state, dirs, ctx);
699
+ }, REGISTRY_FLUSH_MS);
700
+ }
701
+
702
+ function isGitCommit(command: string): boolean {
703
+ return /\bgit\s+commit\b/.test(command);
704
+ }
705
+
706
+ function isTestRun(command: string): boolean {
707
+ return /\b(npm\s+test|npx\s+(jest|vitest|mocha)|pytest|go\s+test|cargo\s+test|bun\s+test)\b/.test(command);
708
+ }
709
+
710
+ function extractCommitMessage(command: string): string {
711
+ const match = command.match(/-m\s+["']([^"']+)["']/);
712
+ return match ? match[1] : "";
713
+ }
714
+
715
+ function updateAutoStatus(): void {
716
+ if (!state.registered || !config.autoStatus || state.customStatus) return;
717
+
718
+ const autoMsg = generateAutoStatus({
719
+ currentActivity: state.activity.currentActivity,
720
+ recentCommit,
721
+ recentTestRuns,
722
+ recentEdits,
723
+ sessionStartedAt: state.sessionStartedAt,
724
+ });
725
+
726
+ state.statusMessage = autoMsg;
727
+ }
728
+
729
+ function trackRecentCommit(): void {
730
+ recentCommit = true;
731
+ if (recentCommitTimer) clearTimeout(recentCommitTimer);
732
+ recentCommitTimer = setTimeout(() => { recentCommit = false; }, RECENT_WINDOW_MS);
733
+ }
734
+
735
+ function trackRecentTest(): void {
736
+ recentTestRuns++;
737
+ if (recentTestTimer) clearTimeout(recentTestTimer);
738
+ recentTestTimer = setTimeout(() => { recentTestRuns = 0; }, RECENT_WINDOW_MS);
739
+ }
740
+
741
+ function trackRecentEdit(): void {
742
+ recentEdits++;
743
+ if (recentEditTimer) clearTimeout(recentEditTimer);
744
+ recentEditTimer = setTimeout(() => { recentEdits = 0; }, RECENT_WINDOW_MS);
745
+ }
746
+
747
+ function shortenPath(filePath: string): string {
748
+ const parts = filePath.split("/");
749
+ return parts.length > 2 ? parts.slice(-2).join("/") : filePath;
750
+ }
751
+
752
+ pi.on("tool_call", async (event, ctx) => {
753
+ if (!state.registered) return;
754
+
755
+ updateLastActivity();
756
+ incrementToolCount();
757
+ scheduleRegistryFlush(ctx);
758
+
759
+ const toolName = event.toolName;
760
+ const input = event.input as Record<string, unknown>;
761
+
762
+ if (toolName === "write" || toolName === "edit") {
763
+ const path = input.path as string;
764
+ if (path) {
765
+ setCurrentActivity(`editing ${shortenPath(path)}`);
766
+ debouncedLogEdit(path, ctx.cwd);
767
+ trackRecentEdit();
768
+ }
769
+ } else if (toolName === "read") {
770
+ const path = input.path as string;
771
+ if (path) {
772
+ setCurrentActivity(`reading ${shortenPath(path)}`);
773
+ }
774
+ } else if (toolName === "bash") {
775
+ const command = input.command as string;
776
+ if (command) {
777
+ if (isGitCommit(command)) {
778
+ setCurrentActivity("committing");
779
+ } else if (isTestRun(command)) {
780
+ setCurrentActivity("running tests");
781
+ }
782
+ }
783
+ }
784
+
785
+ updateAutoStatus();
786
+ });
787
+
788
+ pi.on("tool_result", async (event, ctx) => {
789
+ if (!state.registered) return;
790
+
791
+ const toolName = event.toolName;
792
+ const input = event.input as Record<string, unknown>;
793
+
794
+ if (toolName === "write" || toolName === "edit") {
795
+ const path = input.path as string;
796
+ if (path) {
797
+ setLastToolCall(`${toolName}: ${shortenPath(path)}`);
798
+ addModifiedFile(path);
799
+ }
800
+ }
801
+
802
+ if (toolName === "bash") {
803
+ const command = input.command as string;
804
+ if (command) {
805
+ const cwd = ctx.cwd;
806
+ if (isGitCommit(command)) {
807
+ const msg = extractCommitMessage(command);
808
+ logFeedEvent(cwd, state.agentName, "commit", undefined, msg);
809
+ setLastToolCall(`commit: ${msg}`);
810
+ trackRecentCommit();
811
+ }
812
+ if (isTestRun(command)) {
813
+ const passed = !event.isError;
814
+ logFeedEvent(cwd, state.agentName, "test", undefined, passed ? "passed" : "failed");
815
+ setLastToolCall(`test: ${passed ? "passed" : "failed"}`);
816
+ trackRecentTest();
817
+ }
818
+ }
819
+ }
820
+
821
+ clearCurrentActivity();
822
+ updateAutoStatus();
823
+ scheduleRegistryFlush(ctx);
824
+ });
825
+
826
+ // ===========================================================================
827
+ // Event Handlers
828
+ // ===========================================================================
829
+
830
+ pi.on("session_start", async (_event, ctx) => {
831
+ captureStatusContext(ctx);
832
+ state.cwd = ctx.cwd;
833
+ config = loadConfig(state.cwd);
834
+ state.scopeToFolder = config.scopeToFolder;
835
+ nameTheme.theme = config.nameTheme;
836
+ nameTheme.customWords = config.nameWords;
837
+ resetAutonomousContinueGuard();
838
+ startStatusHeartbeat();
839
+ for (const entry of ctx.sessionManager.getEntries()) {
840
+ if (entry.type === "custom" && entry.customType === "crew-state") {
841
+ restoreAutonomousState(entry.data as Parameters<typeof restoreAutonomousState>[0]);
842
+ }
843
+ }
844
+ const { staleCleared } = restorePlanningState(state.cwd);
845
+ if (staleCleared && ctx.hasUI) {
846
+ ctx.ui.notify("Stale planning state cleared (planner process exited)", "warning");
847
+ }
848
+
849
+ state.isHuman = ctx.hasUI;
850
+ try { fs.rmSync(join(homedir(), ".pi/agent/messenger/feed.jsonl"), { force: true }); } catch {}
851
+
852
+ const shouldAutoRegister = config.autoRegister ||
853
+ matchesAutoRegisterPath(state.cwd, config.autoRegisterPaths);
854
+
855
+ if (!shouldAutoRegister) {
856
+ maybeAutoOpenCrewOverlay(ctx);
857
+ return;
858
+ }
859
+
860
+ if (store.register(state, dirs, ctx, nameTheme)) {
861
+ const cwd = state.cwd;
862
+ store.startWatcher(state, dirs, deliverMessage);
863
+ updateStatus(ctx);
864
+ pruneFeed(cwd, config.feedRetention);
865
+ logFeedEvent(cwd, state.agentName, "join");
866
+
867
+ if (config.registrationContext) {
868
+ sendRegistrationContext(ctx);
869
+ }
870
+ }
871
+
872
+ maybeAutoOpenCrewOverlay(ctx);
873
+ });
874
+
875
+ function recoverWatcherIfNeeded(): void {
876
+ if (state.registered && !state.watcher && !state.watcherRetryTimer) {
877
+ state.watcherRetries = 0;
878
+ store.startWatcher(state, dirs, deliverMessage);
879
+ }
880
+ }
881
+
882
+ function maybeAutoOpenCrewOverlay(ctx: ExtensionContext): void {
883
+ const cwd = ctx.cwd;
884
+ if (config.autoOverlayPlanning) {
885
+ markPlanningOverlayPending(cwd);
886
+ }
887
+
888
+ const autonomousPending =
889
+ config.autoOverlay &&
890
+ autonomousState.active &&
891
+ autonomousState.autoOverlayPending;
892
+
893
+ const planningPending =
894
+ config.autoOverlayPlanning ? getPlanningOverlayPending(cwd) : null;
895
+
896
+ if ((!autonomousPending && !planningPending) || !ctx.hasUI || overlayTui || overlayOpening) {
897
+ return;
898
+ }
899
+
900
+ if (autonomousPending) {
901
+ autonomousState.autoOverlayPending = false;
902
+ }
903
+
904
+ const planningRunId = planningPending
905
+ ? consumePlanningOverlayPending(cwd)?.runId ?? null
906
+ : null;
907
+
908
+ overlayOpening = true;
909
+ const callbacks: OverlayCallbacks = {
910
+ onBackground: (snapshotText) => {
911
+ overlayHandle?.setHidden(true);
912
+ pi.sendMessage({
913
+ customType: "crew_snapshot",
914
+ content: snapshotText,
915
+ display: true,
916
+ }, { triggerTurn: true });
917
+ },
918
+ };
919
+
920
+ ctx.ui.custom<string | undefined>(
921
+ (tui, theme, _keybindings, done) => {
922
+ overlayTui = tui;
923
+ return new MessengerOverlay(tui, theme, state, dirs, done, callbacks, ctx.cwd);
924
+ },
925
+ {
926
+ overlay: true,
927
+ onHandle: (handle) => {
928
+ overlayHandle = handle;
929
+ },
930
+ }
931
+ ).then((snapshot) => {
932
+ if (planningRunId) {
933
+ dismissPlanningOverlayRun(planningRunId);
934
+ }
935
+ if (snapshot) {
936
+ pi.sendMessage({
937
+ customType: "crew_snapshot",
938
+ content: snapshot,
939
+ display: true,
940
+ }, { triggerTurn: true });
941
+ }
942
+ clearAllUnreadCounts();
943
+ overlayOpening = false;
944
+ overlayHandle = null;
945
+ overlayTui = null;
946
+ updateStatus(ctx);
947
+ }).catch(() => {
948
+ overlayOpening = false;
949
+ overlayHandle = null;
950
+ overlayTui = null;
951
+ if (config.autoOverlayPlanning) {
952
+ markPlanningOverlayPending(cwd);
953
+ }
954
+ });
955
+ }
956
+
957
+ pi.on("session_tree", async (_event, ctx) => {
958
+ captureStatusContext(ctx);
959
+ const { staleCleared } = restorePlanningState(ctx.cwd);
960
+ if (staleCleared && ctx.hasUI) {
961
+ ctx.ui.notify("Stale planning state cleared (planner process exited)", "warning");
962
+ }
963
+ updateStatus(ctx);
964
+ maybeAutoOpenCrewOverlay(ctx);
965
+ });
966
+
967
+ pi.on("turn_end", async (event, ctx) => {
968
+ captureStatusContext(ctx);
969
+ store.processAllPendingMessages(state, dirs, deliverMessage);
970
+ const lobbyId = process.env.PI_LOBBY_ID;
971
+ if (lobbyId) {
972
+ const cwd = ctx.cwd;
973
+ const aliveFile = join(cwd, ".pi", "messenger", "crew", `lobby-${lobbyId}.alive`);
974
+ if (fs.existsSync(aliveFile)) {
975
+ pi.sendMessage({
976
+ customType: "lobby_keepalive",
977
+ content: "[Keep-alive] Planning in progress. No task assigned yet. Acknowledge with a single period.",
978
+ display: false,
979
+ }, { triggerTurn: true, deliverAs: "steer" });
980
+ }
981
+ }
982
+ recoverWatcherIfNeeded();
983
+ updateStatus(ctx);
984
+
985
+ if (state.registered) {
986
+ const msg = event.message as unknown as Record<string, unknown> | undefined;
987
+ if (msg && msg.role === "assistant" && msg.usage) {
988
+ const usage = msg.usage as { totalTokens?: number; input?: number; output?: number };
989
+ const total = usage.totalTokens ?? ((usage.input ?? 0) + (usage.output ?? 0));
990
+ if (total > 0) {
991
+ state.session.tokens += total;
992
+ scheduleRegistryFlush(ctx);
993
+ }
994
+ }
995
+ }
996
+
997
+ maybeAutoOpenCrewOverlay(ctx);
998
+ });
999
+
1000
+ // ===========================================================================
1001
+ // Crew Autonomous Mode Continuation
1002
+ // ===========================================================================
1003
+
1004
+ pi.on("agent_end", async (_event, ctx) => {
1005
+ if (process.env.PI_CREW_WORKER === "1" || process.env.PI_LOBBY_ID) {
1006
+ return;
1007
+ }
1008
+
1009
+ if (!state.registered) {
1010
+ if (autonomousState.active) {
1011
+ stopAutonomous("manual");
1012
+ pi.appendEntry("crew-state", autonomousState);
1013
+ resetAutonomousContinueGuard();
1014
+ if (ctx.hasUI) {
1015
+ ctx.ui.notify("Autonomous stopped: this session is not registered in pi-messenger.", "warning");
1016
+ }
1017
+ }
1018
+ return;
1019
+ }
1020
+
1021
+ // --- Auto-work after plan completion ---
1022
+ const autoWork = consumePendingAutoWork();
1023
+ if (autoWork && !overlayTui) {
1024
+ const cwd = autoWork.cwd;
1025
+ const crewConfig = loadCrewConfig(crewStore.getCrewDir(cwd));
1026
+ const readyTasks = crewStore.getReadyTasks(cwd, { advisory: crewConfig.dependencies === "advisory" });
1027
+ const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
1028
+ if (startableTasks.length > 0) {
1029
+ const plan = crewStore.getPlan(cwd);
1030
+ const label = plan ? crewStore.getPlanLabel(plan) : "plan";
1031
+ pi.sendMessage({
1032
+ customType: "crew_auto_work",
1033
+ content: `Plan complete — ${startableTasks.length} task(s) ready for ${label}. Starting autonomous work.\n\nCall: pi_messenger({ action: "work", autonomous: true })`,
1034
+ display: true,
1035
+ }, { triggerTurn: true, deliverAs: "steer" });
1036
+ return;
1037
+ }
1038
+ if (readyTasks.length > 0) {
1039
+ const rejected = readyTasks.filter(teamStore.taskNeedsRevision);
1040
+ const pending = readyTasks.filter(teamStore.taskPendingApproval);
1041
+ pi.sendMessage({
1042
+ customType: rejected.length > 0 ? "crew_auto_work_needs_revision" : "crew_auto_work_needs_approval",
1043
+ content: rejected.length > 0
1044
+ ? `Plan complete — ${rejected.length} ready task(s) need revision before autonomous work can start.`
1045
+ : `Plan complete — ${pending.length} ready task(s) need lead approval before autonomous work can start.`,
1046
+ display: true,
1047
+ });
1048
+ return;
1049
+ }
1050
+ }
1051
+
1052
+ // --- Existing autonomous continuation ---
1053
+ if (!autonomousState.active) {
1054
+ resetAutonomousContinueGuard();
1055
+ return;
1056
+ }
1057
+
1058
+ const currentCwd = ctx.cwd;
1059
+ if (!isAutonomousForCwd(currentCwd)) {
1060
+ resetAutonomousContinueGuard();
1061
+ return;
1062
+ }
1063
+
1064
+ const cwd = autonomousState.cwd ?? currentCwd;
1065
+ const crewDir = join(cwd, ".pi", "messenger", "crew");
1066
+ const crewConfig = loadCrewConfig(crewDir);
1067
+
1068
+ // Check max waves limit
1069
+ if (autonomousState.waveNumber >= crewConfig.work.maxWaves) {
1070
+ stopAutonomous("manual");
1071
+ pi.appendEntry("crew-state", autonomousState);
1072
+ resetAutonomousContinueGuard();
1073
+ if (ctx.hasUI) {
1074
+ ctx.ui.notify(`Autonomous stopped: max waves (${crewConfig.work.maxWaves}) reached`, "warning");
1075
+ }
1076
+ return;
1077
+ }
1078
+
1079
+ // Check for ready tasks
1080
+ const readyTasks = crewStore.getReadyTasks(cwd, { advisory: crewConfig.dependencies === "advisory" });
1081
+ const startableTasks = readyTasks.filter(t => !teamStore.taskNeedsApproval(t));
1082
+
1083
+ if (startableTasks.length === 0) {
1084
+ // No ready tasks - check if all done or blocked
1085
+ const allTasks = crewStore.getTasks(cwd);
1086
+ const allDone = allTasks.every(t => t.status === "done");
1087
+ const needsApproval = readyTasks.filter(teamStore.taskPendingApproval);
1088
+ const rejected = readyTasks.filter(teamStore.taskNeedsRevision);
1089
+
1090
+ stopAutonomous(allDone ? "completed" : "blocked");
1091
+ pi.appendEntry("crew-state", autonomousState);
1092
+ resetAutonomousContinueGuard();
1093
+
1094
+ const plan = crewStore.getPlan(cwd);
1095
+ if (ctx.hasUI) {
1096
+ if (allDone) {
1097
+ ctx.ui.notify(`✅ All tasks complete for ${plan?.prd ?? "plan"}!`, "info");
1098
+ } else if (rejected.length > 0) {
1099
+ ctx.ui.notify(`Autonomous stopped: ${rejected.length} task(s) need revision`, "warning");
1100
+ } else if (needsApproval.length > 0) {
1101
+ ctx.ui.notify(`Autonomous stopped: ${needsApproval.length} task(s) need lead approval`, "warning");
1102
+ } else {
1103
+ const blocked = allTasks.filter(t => t.status === "blocked");
1104
+ ctx.ui.notify(`Autonomous stopped: ${blocked.length} task(s) blocked`, "warning");
1105
+ }
1106
+ }
1107
+ return;
1108
+ }
1109
+
1110
+ const continueSignature = `${cwd}:${autonomousState.waveNumber}:${startableTasks.map(task => task.id).sort().join(",")}`;
1111
+ const continueRepeatCount = trackAutonomousContinue(continueSignature);
1112
+ if (continueRepeatCount >= AUTONOMOUS_CONTINUE_REPEAT_LIMIT) {
1113
+ stopAutonomous("manual");
1114
+ pi.appendEntry("crew-state", autonomousState);
1115
+ resetAutonomousContinueGuard();
1116
+
1117
+ const plan = crewStore.getPlan(cwd);
1118
+ const message = `Autonomous work on ${plan?.prd ?? "plan"} stopped after ${continueRepeatCount} repeated continuation retries without wave progress. Resolve the abort condition, then run pi_messenger({ action: "work", autonomous: true }).`;
1119
+ if (ctx.hasUI) {
1120
+ ctx.ui.notify(message, "warning");
1121
+ }
1122
+ pi.sendMessage({
1123
+ customType: "crew_continue_stopped",
1124
+ content: message,
1125
+ display: true,
1126
+ });
1127
+ return;
1128
+ }
1129
+
1130
+ // Continue to next wave
1131
+ // Note: waveNumber was already incremented by addWaveResult() in work.ts
1132
+ const plan = crewStore.getPlan(cwd);
1133
+ pi.sendMessage({
1134
+ customType: "crew_continue",
1135
+ content: `Continuing autonomous work on ${plan?.prd ?? "plan"}. Wave ${autonomousState.waveNumber} with ${startableTasks.length} ready task(s).`,
1136
+ display: true
1137
+ }, { triggerTurn: true, deliverAs: "steer" });
1138
+
1139
+ // The steer message will trigger the LLM to call work again
1140
+ });
1141
+
1142
+ pi.on("session_shutdown", async (_event, ctx) => {
1143
+ latestCtx = null;
1144
+ const cwd = ctx.cwd || state.cwd;
1145
+ if (cwd) {
1146
+ shutdownLobbyWorkers(cwd);
1147
+ }
1148
+ shutdownAllWorkers();
1149
+ stopStatusHeartbeat();
1150
+ overlayOpening = false;
1151
+ overlayHandle = null;
1152
+ overlayTui = null;
1153
+ if (cwd && isPlanningForCwd(cwd) && planningState.pid === process.pid) {
1154
+ clearPlanningState(cwd);
1155
+ }
1156
+ if (cwd && state.registered) {
1157
+ logFeedEvent(cwd, state.agentName, "leave");
1158
+ }
1159
+ if (state.registryFlushTimer) {
1160
+ clearTimeout(state.registryFlushTimer);
1161
+ state.registryFlushTimer = null;
1162
+ }
1163
+ for (const timer of pendingEdits.values()) {
1164
+ clearTimeout(timer);
1165
+ }
1166
+ pendingEdits.clear();
1167
+ if (recentCommitTimer) { clearTimeout(recentCommitTimer); recentCommitTimer = null; }
1168
+ if (recentTestTimer) { clearTimeout(recentTestTimer); recentTestTimer = null; }
1169
+ if (recentEditTimer) { clearTimeout(recentEditTimer); recentEditTimer = null; }
1170
+ store.stopWatcher(state);
1171
+ try {
1172
+ store.unregister(state, dirs);
1173
+ } catch {
1174
+ // Safe to ignore during shutdown: the process is exiting, so any leftover
1175
+ // registration will be cleaned up as stale on the next registry read.
1176
+ }
1177
+ });
1178
+
1179
+ // ===========================================================================
1180
+ // Reservation Enforcement
1181
+ // ===========================================================================
1182
+
1183
+ pi.on("tool_call", async (event, _ctx) => {
1184
+ if (!["edit", "write"].includes(event.toolName)) return;
1185
+
1186
+ const input = event.input as Record<string, unknown>;
1187
+ const filePath = typeof input.path === "string" ? input.path : null;
1188
+ if (!filePath) return;
1189
+
1190
+ const conflicts = store.getConflictsWithOtherAgents(filePath, state, dirs);
1191
+ if (conflicts.length === 0) return;
1192
+
1193
+ const c = conflicts[0];
1194
+ const folder = extractFolder(c.registration.cwd);
1195
+ const locationPart = c.registration.gitBranch
1196
+ ? ` (in ${folder} on ${c.registration.gitBranch})`
1197
+ : ` (in ${folder})`;
1198
+
1199
+ const lines = [filePath, `Reserved by: ${c.agent}${locationPart}`];
1200
+ if (c.reason) lines.push(`Reason: "${c.reason}"`);
1201
+ lines.push("");
1202
+ lines.push(`Coordinate via pi_messenger({ action: "send", to: "${c.agent}", message: "..." })`);
1203
+
1204
+ return { block: true, reason: lines.join("\n") };
1205
+ });
1206
+ }