@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
package/handlers.ts CHANGED
@@ -1,1107 +1,1041 @@
1
- /**
2
- * Pi Messenger - Tool and Command Handlers
3
- */
4
-
5
- import { existsSync } from "node:fs";
6
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
- import {
8
- type MessengerState,
9
- type Dirs,
10
- type AgentMailMessage,
11
- type AgentRegistration,
12
- type NameThemeConfig,
13
- type SpecClaims,
14
- type SpecCompletions,
15
- extractFolder,
16
- truncatePathLeft,
17
- displaySpecPath,
18
- resolveSpecPath,
19
- computeStatus,
20
- STATUS_INDICATORS,
21
- formatDuration,
22
- buildSelfRegistration,
23
- agentHasTask,
24
- } from "./lib.ts";
25
- import * as store from "./store.ts";
26
- import * as crewStore from "./crew/store.ts";
27
- import { getAutoRegisterPaths, saveAutoRegisterPaths, matchesAutoRegisterPath } from "./config.ts";
28
- import { readFeedEvents, logFeedEvent, pruneFeed, formatFeedLine, isCrewEvent, type FeedEvent } from "./feed.ts";
29
- import { isAutonomousForCwd, isPlanningForCwd } from "./crew/state.ts";
30
- import { loadCrewConfig } from "./crew/utils/config.ts";
31
-
32
- let messagesSentThisSession = 0;
33
-
34
- // =============================================================================
35
- // Tool Result Helper
36
- // =============================================================================
37
-
38
- function result(text: string, details: Record<string, unknown>) {
39
- return {
40
- content: [{ type: "text" as const, text }],
41
- details
42
- };
43
- }
44
-
45
- // =============================================================================
46
- // Not Registered Error
47
- // =============================================================================
48
-
49
- export function notRegisteredError() {
50
- return result(
51
- "Not registered. Use pi_messenger({ action: \"join\" }) to join the agent mesh first.",
52
- { mode: "error", error: "not_registered" }
53
- );
54
- }
55
-
56
- // =============================================================================
57
- // Tool Execute Functions
58
- // =============================================================================
59
-
60
- export function executeJoin(
61
- state: MessengerState,
62
- dirs: Dirs,
63
- ctx: ExtensionContext,
64
- deliverFn: (msg: AgentMailMessage) => void,
65
- updateStatusFn: (ctx: ExtensionContext) => void,
66
- specPath?: string,
67
- nameTheme?: NameThemeConfig,
68
- feedRetention?: number
69
- ) {
70
- if (state.registered) {
71
- const agents = store.getActiveAgents(state, dirs);
72
- return result(
73
- `Already joined as ${state.agentName}. ${agents.length} peer${agents.length === 1 ? "" : "s"} active.`,
74
- { mode: "join", alreadyJoined: true, name: state.agentName, peerCount: agents.length }
75
- );
76
- }
77
-
78
- state.isHuman = ctx.hasUI;
79
- const cwd = ctx.cwd;
80
-
81
- if (!store.register(state, dirs, ctx, nameTheme)) {
82
- return result(
83
- "Failed to join the agent mesh. Check logs for details.",
84
- { mode: "join", error: "registration_failed" }
85
- );
86
- }
87
-
88
- store.startWatcher(state, dirs, deliverFn);
89
- updateStatusFn(ctx);
90
- pruneFeed(cwd, feedRetention ?? 50);
91
- logFeedEvent(cwd, state.agentName, "join");
92
-
93
- let specWarning = "";
94
- if (specPath) {
95
- state.spec = resolveSpecPath(specPath, cwd);
96
- store.updateRegistration(state, dirs, ctx);
97
- if (!existsSync(state.spec)) {
98
- specWarning = `\n\nWarning: Spec file not found at ${displaySpecPath(state.spec, cwd)}.`;
99
- }
100
- }
101
-
102
- const agents = store.getActiveAgents(state, dirs);
103
- const folder = extractFolder(cwd);
104
- const locationPart = state.gitBranch ? `${folder} on ${state.gitBranch}` : folder;
105
-
106
- let text = `Joined as ${state.agentName} in ${locationPart}. ${agents.length} peer${agents.length === 1 ? "" : "s"} active.`;
107
-
108
- if (state.spec) {
109
- text += `\nSpec: ${displaySpecPath(state.spec, cwd)}`;
110
- }
111
-
112
- if (agents.length > 0) {
113
- text += `\n\nActive peers: ${agents.map(a => a.name).join(", ")}`;
114
- text += `\n\nUse pi_messenger({ action: "list" }) for details, or pi_messenger({ action: "send", to: "Name", message: "..." }) to send.`;
115
- }
116
-
117
- if (specWarning) {
118
- text += specWarning;
119
- }
120
-
121
- return result(text, {
122
- mode: "join",
123
- name: state.agentName,
124
- location: locationPart,
125
- peerCount: agents.length,
126
- peers: agents.map(a => a.name),
127
- spec: state.spec ? displaySpecPath(state.spec, cwd) : undefined
128
- });
129
- }
130
-
131
- export async function executeLeave(
132
- state: MessengerState,
133
- dirs: Dirs,
134
- ctx: ExtensionContext,
135
- ) {
136
- if (!state.registered) {
137
- return notRegisteredError();
138
- }
139
-
140
- const cwd = ctx.cwd;
141
-
142
- if (isPlanningForCwd(cwd)) {
143
- return result(
144
- "Cannot leave while Crew planning is active for this project. Cancel it first with pi_messenger({ action: \"plan.cancel\" }).",
145
- { mode: "leave", error: "planning_active" }
146
- );
147
- }
148
-
149
- if (isAutonomousForCwd(cwd)) {
150
- return result(
151
- "Cannot leave while autonomous Crew work is active for this project. Stop it first with pi_messenger({ action: \"work.stop\" }).",
152
- { mode: "leave", error: "autonomous_active" }
153
- );
154
- }
155
-
156
- const inProgressTasks = crewStore
157
- .getTasks(cwd)
158
- .filter(task => task.status === "in_progress" && task.assigned_to === state.agentName)
159
- .map(task => task.id);
160
-
161
- if (inProgressTasks.length > 0) {
162
- return result(
163
- `Cannot leave while Crew task${inProgressTasks.length === 1 ? "" : "s"} assigned to you ${inProgressTasks.length === 1 ? "is" : "are"} still in progress: ${inProgressTasks.join(", ")}. Finish, block, or reset ${inProgressTasks.length === 1 ? "it" : "them"} first.`,
164
- { mode: "leave", error: "crew_tasks_in_progress", taskIds: inProgressTasks }
165
- );
166
- }
167
-
168
- const activeClaim = store.getAgentCurrentClaim(dirs, state.agentName);
169
- let releasedClaim: { spec: string; taskId: string; reason?: string } | undefined;
170
- if (activeClaim) {
171
- const claimDisplay = displaySpecPath(activeClaim.spec, cwd);
172
- try {
173
- const unclaimResult = await store.unclaimTask(dirs, activeClaim.spec, activeClaim.taskId, state.agentName);
174
- if (!store.isUnclaimSuccess(unclaimResult)) {
175
- return result(
176
- `Cannot leave because the active swarm claim ${activeClaim.taskId} in ${claimDisplay} could not be released. Resolve it first and retry.`,
177
- {
178
- mode: "leave",
179
- error: unclaimResult.error,
180
- activeClaim: { ...activeClaim, spec: claimDisplay },
181
- ...(store.isUnclaimNotYours(unclaimResult) ? { claimedBy: unclaimResult.claimedBy } : {}),
182
- }
183
- );
184
- }
185
- releasedClaim = activeClaim;
186
- } catch (error) {
187
- const message = error instanceof Error ? error.message : String(error);
188
- return result(
189
- `Cannot leave because the active swarm claim ${activeClaim.taskId} in ${claimDisplay} could not be released: ${message}`,
190
- {
191
- mode: "leave",
192
- error: "unclaim_failed",
193
- message,
194
- activeClaim: { ...activeClaim, spec: claimDisplay },
195
- }
196
- );
197
- }
198
- }
199
-
200
- const releasedReservations = state.reservations.map(r => r.pattern);
201
- state.reservations = [];
202
- store.updateRegistration(state, dirs, ctx);
203
- for (const pattern of releasedReservations) {
204
- logFeedEvent(cwd, state.agentName, "release", pattern);
205
- }
206
-
207
- try {
208
- store.unregister(state, dirs);
209
- } catch (error) {
210
- const message = error instanceof Error ? error.message : String(error);
211
- return result(
212
- `Could not leave pi-messenger: ${message}`,
213
- { mode: "leave", error: "unregister_failed", message }
214
- );
215
- }
216
-
217
- logFeedEvent(cwd, state.agentName, "leave");
218
- store.stopWatcher(state);
219
-
220
- if (ctx.hasUI) {
221
- ctx.ui.setStatus("messenger", undefined);
222
- }
223
-
224
- const claimText = releasedClaim
225
- ? `\nReleased claim: ${releasedClaim.taskId} in ${displaySpecPath(releasedClaim.spec, cwd)}`
226
- : "";
227
-
228
- return result(
229
- `Left pi-messenger.${releasedReservations.length > 0 ? `\nReleased reservations: ${releasedReservations.join(", ")}` : ""}${claimText}`,
230
- {
231
- mode: "leave",
232
- releasedReservations,
233
- releasedClaim: releasedClaim
234
- ? {
235
- ...releasedClaim,
236
- spec: displaySpecPath(releasedClaim.spec, cwd),
237
- }
238
- : undefined,
239
- }
240
- );
241
- }
242
-
243
- export function executeStatus(state: MessengerState, dirs: Dirs, cwd: string) {
244
- if (!state.registered) {
245
- return notRegisteredError();
246
- }
247
-
248
- const agents = store.getActiveAgents(state, dirs);
249
- const folder = extractFolder(cwd);
250
- const location = state.gitBranch ? `${folder} (${state.gitBranch})` : folder;
251
- const myClaim = store.getAgentCurrentClaim(dirs, state.agentName);
252
-
253
- let text = `You: ${state.agentName}\n`;
254
- text += `Location: ${location}\n`;
255
-
256
- if (state.spec) {
257
- const specDisplay = displaySpecPath(state.spec, cwd);
258
- text += `Spec: ${specDisplay}\n`;
259
- if (myClaim) {
260
- text += `Claim: ${myClaim.taskId}${myClaim.reason ? ` - ${myClaim.reason}` : ""}\n`;
261
- }
262
- }
263
-
264
- text += `Peers: ${agents.length}\n`;
265
- if (state.reservations.length > 0) {
266
- const myRes = state.reservations.map(r => `🔒 ${truncatePathLeft(r.pattern, 40)}`);
267
- text += `Reservations: ${myRes.join(", ")}\n`;
268
- }
269
- text += `\nUse pi_messenger({ action: "list" }) for details, pi_messenger({ action: "task.list" }) for tasks.`;
270
-
271
- return result(text, {
272
- mode: "status",
273
- registered: true,
274
- self: state.agentName,
275
- folder,
276
- gitBranch: state.gitBranch,
277
- peerCount: agents.length,
278
- spec: state.spec ? displaySpecPath(state.spec, cwd) : undefined,
279
- claim: myClaim
280
- ? {
281
- ...myClaim,
282
- spec: displaySpecPath(myClaim.spec, cwd)
283
- }
284
- : undefined,
285
- reservations: state.reservations
286
- });
287
- }
288
-
289
- export function executeList(state: MessengerState, dirs: Dirs, cwd: string, config?: { stuckThreshold?: number }) {
290
- if (!state.registered) {
291
- return notRegisteredError();
292
- }
293
-
294
- const thresholdMs = (config?.stuckThreshold ?? 900) * 1000;
295
- const peers = store.getActiveAgents(state, dirs);
296
- const folder = extractFolder(cwd);
297
- const totalCount = peers.length + 1;
298
-
299
- const lines: string[] = [];
300
- lines.push(`# Agents (${totalCount} online - project: ${folder})`, "");
301
-
302
- function formatAgentLine(
303
- a: AgentRegistration,
304
- isSelf: boolean,
305
- hasTask: boolean
306
- ): string {
307
- const computed = computeStatus(
308
- a.activity?.lastActivityAt ?? a.startedAt,
309
- hasTask,
310
- (a.reservations?.length ?? 0) > 0,
311
- thresholdMs
312
- );
313
- const indicator = STATUS_INDICATORS[computed.status];
314
- const nameLabel = isSelf ? `${a.name} (you)` : a.name;
315
-
316
- const parts: string[] = [`${indicator} ${nameLabel}`];
317
-
318
- if (a.activity?.currentActivity) {
319
- parts.push(a.activity.currentActivity);
320
- } else if (computed.status === "idle" && computed.idleFor) {
321
- parts.push(`idle ${computed.idleFor}`);
322
- } else if (computed.status === "away" && computed.idleFor) {
323
- parts.push(`away ${computed.idleFor}`);
324
- } else if (computed.status === "stuck" && computed.idleFor) {
325
- parts.push(`stuck ${computed.idleFor}`);
326
- }
327
-
328
- parts.push(`${a.session?.toolCalls ?? 0} tools`);
329
-
330
- const tokens = a.session?.tokens ?? 0;
331
- if (tokens >= 1000) {
332
- parts.push(`${(tokens / 1000).toFixed(1)}k`);
333
- } else {
334
- parts.push(`${tokens}`);
335
- }
336
-
337
- if (a.reservations && a.reservations.length > 0) {
338
- const resParts = a.reservations.map(r => r.pattern).join(", ");
339
- parts.push(`\u{1F4C1} ${resParts}`);
340
- }
341
-
342
- if (a.statusMessage) {
343
- parts.push(a.statusMessage);
344
- }
345
-
346
- return parts.join(" - ");
347
- }
348
-
349
- const allClaims = store.getClaims(dirs);
350
-
351
- lines.push(formatAgentLine(buildSelfRegistration(state), true, agentHasTask(state.agentName, allClaims, crewStore.getTasks(cwd))));
352
-
353
- for (const a of peers) {
354
- lines.push(formatAgentLine(a, false, agentHasTask(a.name, allClaims, crewStore.getTasks(a.cwd))));
355
- }
356
-
357
- const recentEvents = readFeedEvents(cwd, 5);
358
- if (recentEvents.length > 0) {
359
- lines.push("", "# Recent Activity", "");
360
- for (const event of recentEvents) {
361
- lines.push(formatFeedLine(event));
362
- }
363
- }
364
-
365
- return result(
366
- lines.join("\n").trim(),
367
- { mode: "list", registered: true, agents: peers, self: state.agentName, totalCount }
368
- );
369
- }
370
-
371
- export function executeSend(
372
- state: MessengerState,
373
- dirs: Dirs,
374
- cwd: string,
375
- to: string | string[] | undefined,
376
- broadcast: boolean | undefined,
377
- message?: string,
378
- replyTo?: string
379
- ) {
380
- if (!state.registered) {
381
- return notRegisteredError();
382
- }
383
-
384
- if (!message) {
385
- return result(
386
- "Error: message is required when sending.",
387
- { mode: "send", error: "missing_message" }
388
- );
389
- }
390
-
391
- const crewDir = crewStore.getCrewDir(cwd);
392
- const crewConfig = loadCrewConfig(crewDir);
393
- const budget = crewConfig.messageBudgets?.[crewConfig.coordination] ?? 10;
394
- if (messagesSentThisSession >= budget) {
395
- return result(
396
- `Message budget reached (${messagesSentThisSession}/${budget} for ${crewConfig.coordination} level). Focus on your task.`,
397
- { mode: "send", error: "budget_exceeded" }
398
- );
399
- }
400
-
401
- let recipients: string[];
402
- if (broadcast) {
403
- if (process.env.PI_CREW_WORKER) {
404
- messagesSentThisSession++;
405
- const preview = message.length > 200 ? message.slice(0, 197) + "..." : message;
406
- logFeedEvent(cwd, state.agentName, "message", undefined, preview);
407
- const remaining = budget - messagesSentThisSession;
408
- return result(
409
- `Broadcast logged. (${remaining} message${remaining === 1 ? "" : "s"} remaining)`,
410
- { mode: "send", sent: ["feed"], failed: [] }
411
- );
412
- }
413
- const agents = store.getActiveAgents(state, dirs);
414
- recipients = agents.map(a => a.name);
415
- if (recipients.length === 0) {
416
- return result(
417
- "No active agents to broadcast to.",
418
- { mode: "send", error: "no_recipients" }
419
- );
420
- }
421
- } else if (to) {
422
- recipients = [...new Set(Array.isArray(to) ? to : [to])];
423
- if (recipients.length === 0) {
424
- return result(
425
- "Error: recipient list cannot be empty.",
426
- { mode: "send", error: "empty_recipients" }
427
- );
428
- }
429
- } else {
430
- return result(
431
- "Error: specify 'to' or 'broadcast: true'.",
432
- { mode: "send", error: "missing_recipient" }
433
- );
434
- }
435
-
436
- const sent: string[] = [];
437
- const failed: Array<{ name: string; error: string }> = [];
438
-
439
- for (const recipient of recipients) {
440
- if (recipient === state.agentName) {
441
- failed.push({ name: recipient, error: "cannot send to self" });
442
- continue;
443
- }
444
-
445
- const validation = store.validateTargetAgent(recipient, dirs);
446
- if (!validation.valid) {
447
- const errorMap: Record<string, string> = {
448
- invalid_name: "invalid name",
449
- not_found: "not found",
450
- not_active: "no longer active",
451
- invalid_registration: "invalid registration",
452
- };
453
- const errKey = (validation as { valid: false; error: string }).error;
454
- failed.push({ name: recipient, error: errorMap[errKey] });
455
- continue;
456
- }
457
-
458
- try {
459
- store.sendMessageToAgent(state, dirs, recipient, message, replyTo);
460
- sent.push(recipient);
461
- } catch (err) {
462
- const msg = err instanceof Error ? err.message : "write failed";
463
- failed.push({ name: recipient, error: msg });
464
- }
465
- }
466
-
467
- if (sent.length === 0) {
468
- const failedStr = failed.map(f => `${f.name} (${f.error})`).join(", ");
469
- return result(
470
- `Failed to send: ${failedStr}`,
471
- { mode: "send", error: "all_failed", sent: [], failed }
472
- );
473
- }
474
-
475
- messagesSentThisSession++;
476
-
477
- const preview = message.length > 200 ? message.slice(0, 197) + "..." : message;
478
- if (broadcast) {
479
- logFeedEvent(cwd, state.agentName, "message", undefined, preview);
480
- } else {
481
- for (const name of sent) {
482
- logFeedEvent(cwd, state.agentName, "message", name, preview);
483
- }
484
- }
485
-
486
- const remaining = budget - messagesSentThisSession;
487
- let text = `Message sent to ${sent.join(", ")}. (${remaining} message${remaining === 1 ? "" : "s"} remaining)`;
488
- if (failed.length > 0) {
489
- const failedStr = failed.map(f => `${f.name} (${f.error})`).join(", ");
490
- text += ` Failed: ${failedStr}`;
491
- }
492
-
493
- return result(text, { mode: "send", sent, failed });
494
- }
495
-
496
- export function executeReserve(
497
- state: MessengerState,
498
- dirs: Dirs,
499
- ctx: ExtensionContext,
500
- patterns: string[],
501
- reason?: string
502
- ) {
503
- if (!state.registered) {
504
- return notRegisteredError();
505
- }
506
-
507
- if (patterns.length === 0) {
508
- return result(
509
- "Error: at least one pattern required.",
510
- { mode: "reserve", error: "empty_patterns" }
511
- );
512
- }
513
-
514
- const now = new Date().toISOString();
515
-
516
- for (const pattern of patterns) {
517
- state.reservations = state.reservations.filter(r => r.pattern !== pattern);
518
- state.reservations.push({ pattern, reason, since: now });
519
- }
520
-
521
- store.updateRegistration(state, dirs, ctx);
522
-
523
- for (const pattern of patterns) {
524
- logFeedEvent(ctx.cwd, state.agentName, "reserve", pattern, reason);
525
- }
526
-
527
- return result(`Reserved: ${patterns.join(", ")}`, { mode: "reserve", patterns, reason });
528
- }
529
-
530
- export function executeRelease(
531
- state: MessengerState,
532
- dirs: Dirs,
533
- ctx: ExtensionContext,
534
- release: string[] | true
535
- ) {
536
- if (!state.registered) {
537
- return notRegisteredError();
538
- }
539
-
540
- if (release === true) {
541
- const released = state.reservations.map(r => r.pattern);
542
- state.reservations = [];
543
- store.updateRegistration(state, dirs, ctx);
544
- for (const pattern of released) {
545
- logFeedEvent(ctx.cwd, state.agentName, "release", pattern);
546
- }
547
- return result(
548
- released.length > 0 ? `Released all: ${released.join(", ")}` : "No reservations to release.",
549
- { mode: "release", released }
550
- );
551
- }
552
-
553
- const patterns = release;
554
- const releasedPatterns = state.reservations.filter(r => patterns.includes(r.pattern)).map(r => r.pattern);
555
- state.reservations = state.reservations.filter(r => !patterns.includes(r.pattern));
556
-
557
- store.updateRegistration(state, dirs, ctx);
558
- for (const pattern of releasedPatterns) {
559
- logFeedEvent(ctx.cwd, state.agentName, "release", pattern);
560
- }
561
-
562
- return result(`Released ${releasedPatterns.length} reservation(s).`, { mode: "release", released: releasedPatterns });
563
- }
564
-
565
- export function executeRename(
566
- state: MessengerState,
567
- dirs: Dirs,
568
- ctx: ExtensionContext,
569
- newName: string,
570
- deliverFn: (msg: AgentMailMessage) => void,
571
- updateStatusFn: (ctx: ExtensionContext) => void
572
- ) {
573
- store.stopWatcher(state);
574
-
575
- const renameResult = store.renameAgent(state, dirs, ctx, newName, deliverFn);
576
-
577
- if (!renameResult.success) {
578
- store.startWatcher(state, dirs, deliverFn);
579
-
580
- const errCode = (renameResult as { success: false; error: string }).error;
581
- const errorMessages: Record<string, string> = {
582
- not_registered: "Cannot rename - not registered.",
583
- invalid_name: `Invalid name "${newName}" - use only letters, numbers, underscore, hyphen.`,
584
- name_taken: `Name "${newName}" is already in use by another agent.`,
585
- same_name: `Already named "${newName}".`,
586
- race_lost: `Name "${newName}" was claimed by another agent.`,
587
- };
588
- return result(
589
- `Error: ${errorMessages[errCode]}`,
590
- { mode: "rename", error: errCode }
591
- );
592
- }
593
-
594
- state.watcherRetries = 0;
595
- store.startWatcher(state, dirs, deliverFn);
596
- updateStatusFn(ctx);
597
-
598
- return result(
599
- `Renamed from "${renameResult.oldName}" to "${renameResult.newName}".`,
600
- { mode: "rename", oldName: renameResult.oldName, newName: renameResult.newName }
601
- );
602
- }
603
-
604
- export function executeSetSpec(
605
- state: MessengerState,
606
- dirs: Dirs,
607
- ctx: ExtensionContext,
608
- specPath: string
609
- ) {
610
- const cwd = ctx.cwd;
611
- const absPath = resolveSpecPath(specPath, cwd);
612
- state.spec = absPath;
613
- store.updateRegistration(state, dirs, ctx);
614
- const display = displaySpecPath(absPath, cwd);
615
- const warning = existsSync(absPath) ? "" : `\n\nWarning: Spec file not found at ${display}.`;
616
- return result(`Spec set to ${display}${warning}`, { mode: "spec", spec: display });
617
- }
618
-
619
- export async function executeClaim(
620
- state: MessengerState,
621
- dirs: Dirs,
622
- ctx: ExtensionContext,
623
- taskId: string,
624
- specPath?: string,
625
- reason?: string
626
- ) {
627
- const cwd = ctx.cwd;
628
- const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
629
- if (!spec) {
630
- return result(
631
- "Error: No spec registered. Use `spec` parameter or join with a spec first.",
632
- { mode: "claim", error: "no_spec" }
633
- );
634
- }
635
-
636
- const warning = specPath && !existsSync(spec)
637
- ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.`
638
- : "";
639
-
640
- const claimResult = await store.claimTask(
641
- dirs,
642
- spec,
643
- taskId,
644
- state.agentName,
645
- ctx.sessionManager.getSessionId(),
646
- process.pid,
647
- reason
648
- );
649
-
650
- const display = displaySpecPath(spec, cwd);
651
- if (store.isClaimSuccess(claimResult)) {
652
- return result(`Claimed ${taskId} in ${display}${warning}`, {
653
- mode: "claim",
654
- spec: display,
655
- taskId,
656
- claimedAt: claimResult.claimedAt,
657
- reason
658
- });
659
- }
660
-
661
- if (store.isClaimAlreadyHaveClaim(claimResult)) {
662
- const existingDisplay = displaySpecPath(claimResult.existing.spec, cwd);
663
- return result(
664
- `Error: You already have a claim on ${claimResult.existing.taskId} in ${existingDisplay}. Complete or unclaim it first.${warning}`,
665
- {
666
- mode: "claim",
667
- error: "already_have_claim",
668
- existing: { spec: existingDisplay, taskId: claimResult.existing.taskId }
669
- }
670
- );
671
- }
672
-
673
- // isClaimAlreadyClaimed
674
- return result(
675
- `Error: ${taskId} is already claimed by ${claimResult.conflict.agent}.${warning}`,
676
- { mode: "claim", error: "already_claimed", taskId, conflict: claimResult.conflict }
677
- );
678
- }
679
-
680
- export async function executeUnclaim(
681
- state: MessengerState,
682
- dirs: Dirs,
683
- cwd: string,
684
- taskId: string,
685
- specPath?: string
686
- ) {
687
- const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
688
- if (!spec) {
689
- return result("Error: No spec registered.", { mode: "unclaim", error: "no_spec" });
690
- }
691
-
692
- const warning = specPath && !existsSync(spec)
693
- ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.`
694
- : "";
695
-
696
- const unclaimResult = await store.unclaimTask(dirs, spec, taskId, state.agentName);
697
- const display = displaySpecPath(spec, cwd);
698
-
699
- if (store.isUnclaimSuccess(unclaimResult)) {
700
- return result(`Released claim on ${taskId}${warning}`, { mode: "unclaim", spec: display, taskId });
701
- }
702
-
703
- if (store.isUnclaimNotYours(unclaimResult)) {
704
- return result(
705
- `Error: ${taskId} is claimed by ${unclaimResult.claimedBy}, not you.${warning}`,
706
- { mode: "unclaim", error: "not_your_claim", taskId, claimedBy: unclaimResult.claimedBy }
707
- );
708
- }
709
-
710
- // error === "not_claimed"
711
- return result(`Error: ${taskId} is not claimed.${warning}`, { mode: "unclaim", error: "not_claimed", taskId });
712
- }
713
-
714
- export async function executeComplete(
715
- state: MessengerState,
716
- dirs: Dirs,
717
- cwd: string,
718
- taskId: string,
719
- notes?: string,
720
- specPath?: string
721
- ) {
722
- const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
723
- if (!spec) {
724
- return result("Error: No spec registered.", { mode: "complete", error: "no_spec" });
725
- }
726
-
727
- const warning = specPath && !existsSync(spec)
728
- ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.`
729
- : "";
730
-
731
- const completeResult = await store.completeTask(dirs, spec, taskId, state.agentName, notes);
732
- const display = displaySpecPath(spec, cwd);
733
-
734
- if (store.isCompleteSuccess(completeResult)) {
735
- return result(`Completed ${taskId} in ${display}${warning}`, {
736
- mode: "complete",
737
- spec: display,
738
- taskId,
739
- completedAt: completeResult.completedAt
740
- });
741
- }
742
-
743
- if (store.isCompleteAlreadyCompleted(completeResult)) {
744
- return result(
745
- `Error: ${taskId} was already completed by ${completeResult.completion.completedBy}.${warning}`,
746
- { mode: "complete", error: "already_completed", taskId, completion: completeResult.completion }
747
- );
748
- }
749
-
750
- if (store.isCompleteNotYours(completeResult)) {
751
- return result(
752
- `Error: ${taskId} is claimed by ${completeResult.claimedBy}, not you.${warning}`,
753
- { mode: "complete", error: "not_your_claim", taskId, claimedBy: completeResult.claimedBy }
754
- );
755
- }
756
-
757
- // error === "not_claimed"
758
- return result(`Error: ${taskId} is not claimed.${warning}`, { mode: "complete", error: "not_claimed", taskId });
759
- }
760
-
761
- export function executeSwarm(
762
- state: MessengerState,
763
- dirs: Dirs,
764
- cwd: string,
765
- specPath?: string
766
- ) {
767
- const claims = store.getClaims(dirs);
768
- const completions = store.getCompletions(dirs);
769
- const agents = store.getActiveAgents(state, dirs);
770
-
771
- const absByDisplay = new Map<string, string>();
772
- const addAbs = (abs: string) => {
773
- const display = displaySpecPath(abs, cwd);
774
- if (!absByDisplay.has(display)) absByDisplay.set(display, abs);
775
- };
776
-
777
- for (const abs of Object.keys(claims)) addAbs(abs);
778
- for (const abs of Object.keys(completions)) addAbs(abs);
779
- if (state.spec) addAbs(state.spec);
780
- for (const agent of agents) {
781
- if (agent.spec) addAbs(agent.spec);
782
- }
783
-
784
- const specAgents: Record<string, string[]> = {};
785
- if (state.spec) {
786
- const display = displaySpecPath(state.spec, cwd);
787
- specAgents[display] = [state.agentName];
788
- }
789
- for (const agent of agents) {
790
- if (!agent.spec) continue;
791
- const display = displaySpecPath(agent.spec, cwd);
792
- if (!specAgents[display]) specAgents[display] = [];
793
- specAgents[display].push(agent.name);
794
- }
795
-
796
- const myClaim = store.getAgentCurrentClaim(dirs, state.agentName);
797
- const mySpec = state.spec ? displaySpecPath(state.spec, cwd) : undefined;
798
-
799
- if (specPath) {
800
- const absSpec = resolveSpecPath(specPath, cwd);
801
- const display = displaySpecPath(absSpec, cwd);
802
- const warning = !existsSync(absSpec)
803
- ? `\n\nWarning: Spec file not found at ${display}.`
804
- : "";
805
- const specClaims: SpecClaims = claims[absSpec] || {};
806
- const specCompletions: SpecCompletions = completions[absSpec] || {};
807
- const specAgentList = specAgents[display] || [];
808
-
809
- const lines = [`Swarm: ${display}`, ""];
810
- const completedIds = Object.keys(specCompletions);
811
- lines.push(`Completed: ${completedIds.length > 0 ? completedIds.join(", ") : "(none)"}`);
812
-
813
- const inProgress = Object.entries(specClaims).map(([tid, c]) =>
814
- `${tid} (${c.agent === state.agentName ? "you" : c.agent})`
815
- );
816
- lines.push(`In progress: ${inProgress.length > 0 ? inProgress.join(", ") : "(none)"}`);
817
-
818
- const teammates = specAgentList.filter(name => name !== state.agentName);
819
- if (teammates.length > 0) lines.push(`Teammates: ${teammates.join(", ")}`);
820
-
821
- return result(lines.join("\n") + warning, {
822
- mode: "swarm",
823
- spec: display,
824
- agents: specAgentList,
825
- claims: specClaims,
826
- completions: specCompletions
827
- });
828
- }
829
-
830
- const allSpecs = new Set<string>([
831
- ...absByDisplay.keys(),
832
- ...Object.keys(specAgents)
833
- ]);
834
-
835
- const lines = ["Swarm Status:", ""];
836
- const specsData: Record<string, { agents: string[]; claims: SpecClaims; completions: SpecCompletions }> = {};
837
-
838
- for (const display of Array.from(allSpecs).sort((a, b) => a.localeCompare(b))) {
839
- const absSpec = absByDisplay.get(display) ?? resolveSpecPath(display, cwd);
840
- const specClaims: SpecClaims = claims[absSpec] || {};
841
- const specCompletions: SpecCompletions = completions[absSpec] || {};
842
- const specAgentList = specAgents[display] || [];
843
-
844
- specsData[display] = { agents: specAgentList, claims: specClaims, completions: specCompletions };
845
-
846
- const isMySpec = display === mySpec;
847
- lines.push(`${display}${isMySpec ? " (your spec)" : ""}:`);
848
-
849
- const completedIds = Object.keys(specCompletions);
850
- lines.push(` Completed: ${completedIds.length > 0 ? completedIds.join(", ") : "(none)"}`);
851
-
852
- const inProgress = Object.entries(specClaims).map(([tid, c]) =>
853
- `${tid} (${c.agent === state.agentName ? "you" : c.agent})`
854
- );
855
- lines.push(` In progress: ${inProgress.length > 0 ? inProgress.join(", ") : "(none)"}`);
856
-
857
- const idle = specAgentList.filter(name =>
858
- !Object.values(specClaims).some(c => c.agent === name)
859
- );
860
- if (idle.length > 0) lines.push(` Idle: ${idle.join(", ")}`);
861
- lines.push("");
862
- }
863
-
864
- return result(lines.join("\n").trim(), {
865
- mode: "swarm",
866
- yourSpec: mySpec,
867
- yourClaim: myClaim?.taskId,
868
- specs: specsData
869
- });
870
- }
871
-
872
- export function executeSetStatus(
873
- state: MessengerState,
874
- dirs: Dirs,
875
- ctx: ExtensionContext,
876
- message?: string
877
- ) {
878
- if (!state.registered) {
879
- return notRegisteredError();
880
- }
881
-
882
- if (!message || message.trim() === "") {
883
- state.statusMessage = undefined;
884
- state.customStatus = false;
885
- store.updateRegistration(state, dirs, ctx);
886
- return result(
887
- "Custom status cleared. Auto-status will resume.",
888
- { mode: "set_status", cleared: true }
889
- );
890
- }
891
-
892
- state.statusMessage = message.trim();
893
- state.customStatus = true;
894
- store.updateRegistration(state, dirs, ctx);
895
- return result(
896
- `Status set to: ${state.statusMessage}`,
897
- { mode: "set_status", message: state.statusMessage }
898
- );
899
- }
900
-
901
- export function executeFeed(
902
- cwd: string,
903
- limit?: number,
904
- crewEventsInFeed: boolean = true
905
- ) {
906
- const effectiveLimit = limit ?? 20;
907
- let events: FeedEvent[];
908
- if (!crewEventsInFeed) {
909
- events = readFeedEvents(cwd, effectiveLimit * 2);
910
- events = events.filter(e => !isCrewEvent(e.type));
911
- events = events.slice(-effectiveLimit);
912
- } else {
913
- events = readFeedEvents(cwd, effectiveLimit);
914
- }
915
-
916
- if (events.length === 0) {
917
- return result(
918
- "# Activity Feed\n\nNo activity yet.",
919
- { mode: "feed", events: [] }
920
- );
921
- }
922
-
923
- const lines: string[] = [`# Activity Feed (last ${events.length})`, ""];
924
- for (const event of events) {
925
- lines.push(formatFeedLine(event));
926
- }
927
-
928
- return result(lines.join("\n"), { mode: "feed", events });
929
- }
930
-
931
- export function executeWhois(
932
- state: MessengerState,
933
- dirs: Dirs,
934
- cwd: string,
935
- name: string,
936
- config?: { stuckThreshold?: number }
937
- ) {
938
- if (!state.registered) {
939
- return notRegisteredError();
940
- }
941
-
942
- const thresholdMs = (config?.stuckThreshold ?? 900) * 1000;
943
-
944
- const agents = store.getActiveAgents(state, dirs);
945
- const agent = agents.find(a => a.name === name);
946
- if (!agent) {
947
- if (name === state.agentName) {
948
- return executeWhoisSelf(state, dirs, cwd, thresholdMs);
949
- }
950
- return result(
951
- `Agent "${name}" not found or not active.`,
952
- { mode: "whois", error: "not_found", name }
953
- );
954
- }
955
-
956
- return formatWhoisOutput(agent, false, dirs, cwd, thresholdMs);
957
- }
958
-
959
- function executeWhoisSelf(
960
- state: MessengerState,
961
- dirs: Dirs,
962
- cwd: string,
963
- thresholdMs: number
964
- ) {
965
- return formatWhoisOutput(buildSelfRegistration(state), true, dirs, cwd, thresholdMs);
966
- }
967
-
968
- function formatWhoisOutput(
969
- agent: AgentRegistration,
970
- isSelf: boolean,
971
- dirs: Dirs,
972
- cwd: string,
973
- thresholdMs: number
974
- ) {
975
- const allClaims = store.getClaims(dirs);
976
- const hasTask = agentHasTask(agent.name, allClaims, crewStore.getTasks(agent.cwd));
977
-
978
- const computed = computeStatus(
979
- agent.activity?.lastActivityAt ?? agent.startedAt,
980
- hasTask,
981
- (agent.reservations?.length ?? 0) > 0,
982
- thresholdMs
983
- );
984
-
985
- const indicator = STATUS_INDICATORS[computed.status];
986
- const statusLabel = computed.status.charAt(0).toUpperCase() + computed.status.slice(1);
987
- const idleStr = computed.idleFor ? ` for ${computed.idleFor}` : "";
988
-
989
- const sessionAge = formatDuration(Date.now() - new Date(agent.startedAt).getTime());
990
- const tokens = agent.session?.tokens ?? 0;
991
- const tokenStr = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : `${tokens}`;
992
-
993
- const lines: string[] = [];
994
- lines.push(`# ${agent.name}${isSelf ? " (you)" : ""}`, "");
995
- lines.push(`${indicator} ${statusLabel}${idleStr}`);
996
- if (agent.model) lines.push(`Model: ${agent.model}`);
997
- if (agent.gitBranch) lines.push(`Branch: ${agent.gitBranch}`);
998
- lines.push(`Session: ${sessionAge} - ${agent.session?.toolCalls ?? 0} tool calls - ${tokenStr} tokens`);
999
-
1000
- if (agent.statusMessage) {
1001
- lines.push(`Status: ${agent.statusMessage}`);
1002
- }
1003
-
1004
- if (agent.reservations && agent.reservations.length > 0) {
1005
- lines.push("", "## Reservations");
1006
- for (const r of agent.reservations) {
1007
- lines.push(`- ${r.pattern}${r.reason ? ` (${r.reason})` : ""}`);
1008
- }
1009
- }
1010
-
1011
- if (agent.session?.filesModified && agent.session.filesModified.length > 0) {
1012
- lines.push("", "## Recent Files");
1013
- for (const f of agent.session.filesModified.slice(-10)) {
1014
- lines.push(`- ${f}`);
1015
- }
1016
- }
1017
-
1018
- const feedCwd = isSelf ? cwd : agent.cwd;
1019
- const allFeedEvents = readFeedEvents(feedCwd, 100);
1020
- const agentEvents = allFeedEvents.filter(e => e.agent === agent.name).slice(-10);
1021
- if (agentEvents.length > 0) {
1022
- lines.push("", "## Recent Activity");
1023
- for (const e of agentEvents) {
1024
- lines.push(`- ${formatFeedLine(e)}`);
1025
- }
1026
- }
1027
-
1028
- return result(lines.join("\n"), { mode: "whois", agent });
1029
- }
1030
-
1031
- export function executeAutoRegisterPath(
1032
- action: "add" | "remove" | "list",
1033
- cwd: string
1034
- ) {
1035
- const paths = getAutoRegisterPaths();
1036
-
1037
- if (action === "list") {
1038
- if (paths.length === 0) {
1039
- return result(
1040
- "No auto-register paths configured.\n\nUse pi_messenger({ action: \"autoRegisterPath\", autoRegisterPath: \"add\" }) to add the current folder.",
1041
- { mode: "autoRegisterPath", action: "list", paths: [], currentFolder: cwd, isCurrentInList: false }
1042
- );
1043
- }
1044
-
1045
- const isCurrentInList = matchesAutoRegisterPath(cwd, paths);
1046
- const lines = ["Auto-register paths:", ""];
1047
- for (const p of paths) {
1048
- const marker = p === cwd ? " (current)" : "";
1049
- lines.push(` ${p}${marker}`);
1050
- }
1051
- lines.push("");
1052
- lines.push(`Current folder: ${cwd}`);
1053
- lines.push(`Status: ${isCurrentInList ? "Will auto-register here" : "Will NOT auto-register here"}`);
1054
-
1055
- return result(lines.join("\n"), {
1056
- mode: "autoRegisterPath",
1057
- action: "list",
1058
- paths,
1059
- currentFolder: cwd,
1060
- isCurrentInList
1061
- });
1062
- }
1063
-
1064
- if (action === "add") {
1065
- if (paths.includes(cwd)) {
1066
- return result(
1067
- `Current folder already in auto-register paths:\n ${cwd}`,
1068
- { mode: "autoRegisterPath", action: "add", alreadyExists: true, path: cwd }
1069
- );
1070
- }
1071
-
1072
- const newPaths = [...paths, cwd];
1073
- saveAutoRegisterPaths(newPaths);
1074
-
1075
- return result(
1076
- `Added to auto-register paths:\n ${cwd}\n\nAgents starting in this folder will now auto-join the mesh.`,
1077
- { mode: "autoRegisterPath", action: "add", path: cwd, paths: newPaths }
1078
- );
1079
- }
1080
-
1081
- if (action === "remove") {
1082
- if (!paths.includes(cwd)) {
1083
- // Check if it matches via glob but isn't exact
1084
- const isMatched = matchesAutoRegisterPath(cwd, paths);
1085
- if (isMatched) {
1086
- return result(
1087
- `Current folder matches a glob pattern but isn't an exact entry.\nManually edit ~/.pi/agent/pi-messenger.json to modify glob patterns.`,
1088
- { mode: "autoRegisterPath", action: "remove", notExact: true, path: cwd }
1089
- );
1090
- }
1091
- return result(
1092
- `Current folder not in auto-register paths:\n ${cwd}`,
1093
- { mode: "autoRegisterPath", action: "remove", notFound: true, path: cwd }
1094
- );
1095
- }
1096
-
1097
- const newPaths = paths.filter(p => p !== cwd);
1098
- saveAutoRegisterPaths(newPaths);
1099
-
1100
- return result(
1101
- `Removed from auto-register paths:\n ${cwd}\n\nAgents starting in this folder will no longer auto-join.`,
1102
- { mode: "autoRegisterPath", action: "remove", path: cwd, paths: newPaths }
1103
- );
1104
- }
1105
-
1106
- return result("Invalid action. Use: add, remove, or list", { mode: "autoRegisterPath", error: "invalid_action" });
1107
- }
1
+ /**
2
+ * Pi Messenger - Tool and Command Handlers
3
+ */
4
+
5
+ import { existsSync } from "node:fs";
6
+ import type { ExtensionContext } from "@linxiraos/zeta";
7
+ import {
8
+ type MessengerState,
9
+ type Dirs,
10
+ type AgentMailMessage,
11
+ type AgentRegistration,
12
+ type NameThemeConfig,
13
+ type SpecClaims,
14
+ type SpecCompletions,
15
+ extractFolder,
16
+ truncatePathLeft,
17
+ displaySpecPath,
18
+ resolveSpecPath,
19
+ computeStatus,
20
+ STATUS_INDICATORS,
21
+ formatDuration,
22
+ buildSelfRegistration,
23
+ agentHasTask,
24
+ } from "./lib.ts";
25
+ import * as store from "./store.ts";
26
+ import * as crewStore from "./crew/store.ts";
27
+ import { getAutoRegisterPaths, saveAutoRegisterPaths, matchesAutoRegisterPath } from "./config.ts";
28
+ import { readFeedEvents, logFeedEvent, pruneFeed, formatFeedLine, isCrewEvent, type FeedEvent } from "./feed.ts";
29
+ import { isAutonomousForCwd, isPlanningForCwd } from "./crew/state.ts";
30
+ import { loadCrewConfig } from "./crew/utils/config.ts";
31
+
32
+ let messagesSentThisSession = 0;
33
+
34
+ // =============================================================================
35
+ // Tool Result Helper
36
+ // =============================================================================
37
+
38
+ function result(text: string, details: Record<string, unknown>) {
39
+ return {
40
+ content: [{ type: "text" as const, text }],
41
+ details,
42
+ };
43
+ }
44
+
45
+ // =============================================================================
46
+ // Not Registered Error
47
+ // =============================================================================
48
+
49
+ export function notRegisteredError() {
50
+ return result('Not registered. Use pi_messenger({ action: "join" }) to join the agent mesh first.', {
51
+ mode: "error",
52
+ error: "not_registered",
53
+ });
54
+ }
55
+
56
+ // =============================================================================
57
+ // Tool Execute Functions
58
+ // =============================================================================
59
+
60
+ export function executeJoin(
61
+ state: MessengerState,
62
+ dirs: Dirs,
63
+ ctx: ExtensionContext,
64
+ deliverFn: (msg: AgentMailMessage) => void,
65
+ updateStatusFn: (ctx: ExtensionContext) => void,
66
+ specPath?: string,
67
+ nameTheme?: NameThemeConfig,
68
+ feedRetention?: number,
69
+ ) {
70
+ if (state.registered) {
71
+ const agents = store.getActiveAgents(state, dirs);
72
+ return result(
73
+ `Already joined as ${state.agentName}. ${agents.length} peer${agents.length === 1 ? "" : "s"} active.`,
74
+ { mode: "join", alreadyJoined: true, name: state.agentName, peerCount: agents.length },
75
+ );
76
+ }
77
+
78
+ state.isHuman = ctx.hasUI;
79
+ const cwd = ctx.cwd;
80
+
81
+ if (!store.register(state, dirs, ctx, nameTheme)) {
82
+ return result("Failed to join the agent mesh. Check logs for details.", {
83
+ mode: "join",
84
+ error: "registration_failed",
85
+ });
86
+ }
87
+
88
+ store.startWatcher(state, dirs, deliverFn);
89
+ updateStatusFn(ctx);
90
+ pruneFeed(cwd, feedRetention ?? 50);
91
+ logFeedEvent(cwd, state.agentName, "join");
92
+
93
+ let specWarning = "";
94
+ if (specPath) {
95
+ state.spec = resolveSpecPath(specPath, cwd);
96
+ store.updateRegistration(state, dirs, ctx);
97
+ if (!existsSync(state.spec)) {
98
+ specWarning = `\n\nWarning: Spec file not found at ${displaySpecPath(state.spec, cwd)}.`;
99
+ }
100
+ }
101
+
102
+ const agents = store.getActiveAgents(state, dirs);
103
+ const folder = extractFolder(cwd);
104
+ const locationPart = state.gitBranch ? `${folder} on ${state.gitBranch}` : folder;
105
+
106
+ let text = `Joined as ${state.agentName} in ${locationPart}. ${agents.length} peer${agents.length === 1 ? "" : "s"} active.`;
107
+
108
+ if (state.spec) {
109
+ text += `\nSpec: ${displaySpecPath(state.spec, cwd)}`;
110
+ }
111
+
112
+ if (agents.length > 0) {
113
+ text += `\n\nActive peers: ${agents.map(a => a.name).join(", ")}`;
114
+ text += `\n\nUse pi_messenger({ action: "list" }) for details, or pi_messenger({ action: "send", to: "Name", message: "..." }) to send.`;
115
+ }
116
+
117
+ if (specWarning) {
118
+ text += specWarning;
119
+ }
120
+
121
+ return result(text, {
122
+ mode: "join",
123
+ name: state.agentName,
124
+ location: locationPart,
125
+ peerCount: agents.length,
126
+ peers: agents.map(a => a.name),
127
+ spec: state.spec ? displaySpecPath(state.spec, cwd) : undefined,
128
+ });
129
+ }
130
+
131
+ export async function executeLeave(state: MessengerState, dirs: Dirs, ctx: ExtensionContext) {
132
+ if (!state.registered) {
133
+ return notRegisteredError();
134
+ }
135
+
136
+ const cwd = ctx.cwd;
137
+
138
+ if (isPlanningForCwd(cwd)) {
139
+ return result(
140
+ 'Cannot leave while Crew planning is active for this project. Cancel it first with pi_messenger({ action: "plan.cancel" }).',
141
+ { mode: "leave", error: "planning_active" },
142
+ );
143
+ }
144
+
145
+ if (isAutonomousForCwd(cwd)) {
146
+ return result(
147
+ 'Cannot leave while autonomous Crew work is active for this project. Stop it first with pi_messenger({ action: "work.stop" }).',
148
+ { mode: "leave", error: "autonomous_active" },
149
+ );
150
+ }
151
+
152
+ const inProgressTasks = crewStore
153
+ .getTasks(cwd)
154
+ .filter(task => task.status === "in_progress" && task.assigned_to === state.agentName)
155
+ .map(task => task.id);
156
+
157
+ if (inProgressTasks.length > 0) {
158
+ return result(
159
+ `Cannot leave while Crew task${inProgressTasks.length === 1 ? "" : "s"} assigned to you ${inProgressTasks.length === 1 ? "is" : "are"} still in progress: ${inProgressTasks.join(", ")}. Finish, block, or reset ${inProgressTasks.length === 1 ? "it" : "them"} first.`,
160
+ { mode: "leave", error: "crew_tasks_in_progress", taskIds: inProgressTasks },
161
+ );
162
+ }
163
+
164
+ const activeClaim = store.getAgentCurrentClaim(dirs, state.agentName);
165
+ let releasedClaim: { spec: string; taskId: string; reason?: string } | undefined;
166
+ if (activeClaim) {
167
+ const claimDisplay = displaySpecPath(activeClaim.spec, cwd);
168
+ try {
169
+ const unclaimResult = await store.unclaimTask(dirs, activeClaim.spec, activeClaim.taskId, state.agentName);
170
+ if (!store.isUnclaimSuccess(unclaimResult)) {
171
+ return result(
172
+ `Cannot leave because the active swarm claim ${activeClaim.taskId} in ${claimDisplay} could not be released. Resolve it first and retry.`,
173
+ {
174
+ mode: "leave",
175
+ error: unclaimResult.error,
176
+ activeClaim: { ...activeClaim, spec: claimDisplay },
177
+ ...(store.isUnclaimNotYours(unclaimResult) ? { claimedBy: unclaimResult.claimedBy } : {}),
178
+ },
179
+ );
180
+ }
181
+ releasedClaim = activeClaim;
182
+ } catch (error) {
183
+ const message = error instanceof Error ? error.message : String(error);
184
+ return result(
185
+ `Cannot leave because the active swarm claim ${activeClaim.taskId} in ${claimDisplay} could not be released: ${message}`,
186
+ {
187
+ mode: "leave",
188
+ error: "unclaim_failed",
189
+ message,
190
+ activeClaim: { ...activeClaim, spec: claimDisplay },
191
+ },
192
+ );
193
+ }
194
+ }
195
+
196
+ const releasedReservations = state.reservations.map(r => r.pattern);
197
+ state.reservations = [];
198
+ store.updateRegistration(state, dirs, ctx);
199
+ for (const pattern of releasedReservations) {
200
+ logFeedEvent(cwd, state.agentName, "release", pattern);
201
+ }
202
+
203
+ try {
204
+ store.unregister(state, dirs);
205
+ } catch (error) {
206
+ const message = error instanceof Error ? error.message : String(error);
207
+ return result(`Could not leave pi-messenger: ${message}`, { mode: "leave", error: "unregister_failed", message });
208
+ }
209
+
210
+ logFeedEvent(cwd, state.agentName, "leave");
211
+ store.stopWatcher(state);
212
+
213
+ if (ctx.hasUI) {
214
+ ctx.ui.setStatus("messenger", undefined);
215
+ }
216
+
217
+ const claimText = releasedClaim
218
+ ? `\nReleased claim: ${releasedClaim.taskId} in ${displaySpecPath(releasedClaim.spec, cwd)}`
219
+ : "";
220
+
221
+ return result(
222
+ `Left pi-messenger.${releasedReservations.length > 0 ? `\nReleased reservations: ${releasedReservations.join(", ")}` : ""}${claimText}`,
223
+ {
224
+ mode: "leave",
225
+ releasedReservations,
226
+ releasedClaim: releasedClaim
227
+ ? {
228
+ ...releasedClaim,
229
+ spec: displaySpecPath(releasedClaim.spec, cwd),
230
+ }
231
+ : undefined,
232
+ },
233
+ );
234
+ }
235
+
236
+ export function executeStatus(state: MessengerState, dirs: Dirs, cwd: string) {
237
+ if (!state.registered) {
238
+ return notRegisteredError();
239
+ }
240
+
241
+ const agents = store.getActiveAgents(state, dirs);
242
+ const folder = extractFolder(cwd);
243
+ const location = state.gitBranch ? `${folder} (${state.gitBranch})` : folder;
244
+ const myClaim = store.getAgentCurrentClaim(dirs, state.agentName);
245
+
246
+ let text = `You: ${state.agentName}\n`;
247
+ text += `Location: ${location}\n`;
248
+
249
+ if (state.spec) {
250
+ const specDisplay = displaySpecPath(state.spec, cwd);
251
+ text += `Spec: ${specDisplay}\n`;
252
+ if (myClaim) {
253
+ text += `Claim: ${myClaim.taskId}${myClaim.reason ? ` - ${myClaim.reason}` : ""}\n`;
254
+ }
255
+ }
256
+
257
+ text += `Peers: ${agents.length}\n`;
258
+ if (state.reservations.length > 0) {
259
+ const myRes = state.reservations.map(r => `🔒 ${truncatePathLeft(r.pattern, 40)}`);
260
+ text += `Reservations: ${myRes.join(", ")}\n`;
261
+ }
262
+ text += `\nUse pi_messenger({ action: "list" }) for details, pi_messenger({ action: "task.list" }) for tasks.`;
263
+
264
+ return result(text, {
265
+ mode: "status",
266
+ registered: true,
267
+ self: state.agentName,
268
+ folder,
269
+ gitBranch: state.gitBranch,
270
+ peerCount: agents.length,
271
+ spec: state.spec ? displaySpecPath(state.spec, cwd) : undefined,
272
+ claim: myClaim
273
+ ? {
274
+ ...myClaim,
275
+ spec: displaySpecPath(myClaim.spec, cwd),
276
+ }
277
+ : undefined,
278
+ reservations: state.reservations,
279
+ });
280
+ }
281
+
282
+ export function executeList(state: MessengerState, dirs: Dirs, cwd: string, config?: { stuckThreshold?: number }) {
283
+ if (!state.registered) {
284
+ return notRegisteredError();
285
+ }
286
+
287
+ const thresholdMs = (config?.stuckThreshold ?? 900) * 1000;
288
+ const peers = store.getActiveAgents(state, dirs);
289
+ const folder = extractFolder(cwd);
290
+ const totalCount = peers.length + 1;
291
+
292
+ const lines: string[] = [];
293
+ lines.push(`# Agents (${totalCount} online - project: ${folder})`, "");
294
+
295
+ function formatAgentLine(a: AgentRegistration, isSelf: boolean, hasTask: boolean): string {
296
+ const computed = computeStatus(
297
+ a.activity?.lastActivityAt ?? a.startedAt,
298
+ hasTask,
299
+ (a.reservations?.length ?? 0) > 0,
300
+ thresholdMs,
301
+ );
302
+ const indicator = STATUS_INDICATORS[computed.status];
303
+ const nameLabel = isSelf ? `${a.name} (you)` : a.name;
304
+
305
+ const parts: string[] = [`${indicator} ${nameLabel}`];
306
+
307
+ if (a.activity?.currentActivity) {
308
+ parts.push(a.activity.currentActivity);
309
+ } else if (computed.status === "idle" && computed.idleFor) {
310
+ parts.push(`idle ${computed.idleFor}`);
311
+ } else if (computed.status === "away" && computed.idleFor) {
312
+ parts.push(`away ${computed.idleFor}`);
313
+ } else if (computed.status === "stuck" && computed.idleFor) {
314
+ parts.push(`stuck ${computed.idleFor}`);
315
+ }
316
+
317
+ parts.push(`${a.session?.toolCalls ?? 0} tools`);
318
+
319
+ const tokens = a.session?.tokens ?? 0;
320
+ if (tokens >= 1000) {
321
+ parts.push(`${(tokens / 1000).toFixed(1)}k`);
322
+ } else {
323
+ parts.push(`${tokens}`);
324
+ }
325
+
326
+ if (a.reservations && a.reservations.length > 0) {
327
+ const resParts = a.reservations.map(r => r.pattern).join(", ");
328
+ parts.push(`\u{1F4C1} ${resParts}`);
329
+ }
330
+
331
+ if (a.statusMessage) {
332
+ parts.push(a.statusMessage);
333
+ }
334
+
335
+ return parts.join(" - ");
336
+ }
337
+
338
+ const allClaims = store.getClaims(dirs);
339
+
340
+ lines.push(
341
+ formatAgentLine(
342
+ buildSelfRegistration(state),
343
+ true,
344
+ agentHasTask(state.agentName, allClaims, crewStore.getTasks(cwd)),
345
+ ),
346
+ );
347
+
348
+ for (const a of peers) {
349
+ lines.push(formatAgentLine(a, false, agentHasTask(a.name, allClaims, crewStore.getTasks(a.cwd))));
350
+ }
351
+
352
+ const recentEvents = readFeedEvents(cwd, 5);
353
+ if (recentEvents.length > 0) {
354
+ lines.push("", "# Recent Activity", "");
355
+ for (const event of recentEvents) {
356
+ lines.push(formatFeedLine(event));
357
+ }
358
+ }
359
+
360
+ return result(lines.join("\n").trim(), {
361
+ mode: "list",
362
+ registered: true,
363
+ agents: peers,
364
+ self: state.agentName,
365
+ totalCount,
366
+ });
367
+ }
368
+
369
+ export function executeSend(
370
+ state: MessengerState,
371
+ dirs: Dirs,
372
+ cwd: string,
373
+ to: string | string[] | undefined,
374
+ broadcast: boolean | undefined,
375
+ message?: string,
376
+ replyTo?: string,
377
+ ) {
378
+ if (!state.registered) {
379
+ return notRegisteredError();
380
+ }
381
+
382
+ if (!message) {
383
+ return result("Error: message is required when sending.", { mode: "send", error: "missing_message" });
384
+ }
385
+
386
+ const crewDir = crewStore.getCrewDir(cwd);
387
+ const crewConfig = loadCrewConfig(crewDir);
388
+ const budget = crewConfig.messageBudgets?.[crewConfig.coordination] ?? 10;
389
+ if (messagesSentThisSession >= budget) {
390
+ return result(
391
+ `Message budget reached (${messagesSentThisSession}/${budget} for ${crewConfig.coordination} level). Focus on your task.`,
392
+ { mode: "send", error: "budget_exceeded" },
393
+ );
394
+ }
395
+
396
+ let recipients: string[];
397
+ if (broadcast) {
398
+ if (process.env.PI_CREW_WORKER) {
399
+ messagesSentThisSession++;
400
+ const preview = message.length > 200 ? message.slice(0, 197) + "..." : message;
401
+ logFeedEvent(cwd, state.agentName, "message", undefined, preview);
402
+ const remaining = budget - messagesSentThisSession;
403
+ return result(`Broadcast logged. (${remaining} message${remaining === 1 ? "" : "s"} remaining)`, {
404
+ mode: "send",
405
+ sent: ["feed"],
406
+ failed: [],
407
+ });
408
+ }
409
+ const agents = store.getActiveAgents(state, dirs);
410
+ recipients = agents.map(a => a.name);
411
+ if (recipients.length === 0) {
412
+ return result("No active agents to broadcast to.", { mode: "send", error: "no_recipients" });
413
+ }
414
+ } else if (to) {
415
+ recipients = [...new Set(Array.isArray(to) ? to : [to])];
416
+ if (recipients.length === 0) {
417
+ return result("Error: recipient list cannot be empty.", { mode: "send", error: "empty_recipients" });
418
+ }
419
+ } else {
420
+ return result("Error: specify 'to' or 'broadcast: true'.", { mode: "send", error: "missing_recipient" });
421
+ }
422
+
423
+ const sent: string[] = [];
424
+ const failed: Array<{ name: string; error: string }> = [];
425
+
426
+ for (const recipient of recipients) {
427
+ if (recipient === state.agentName) {
428
+ failed.push({ name: recipient, error: "cannot send to self" });
429
+ continue;
430
+ }
431
+
432
+ const validation = store.validateTargetAgent(recipient, dirs);
433
+ if (!validation.valid) {
434
+ const errorMap: Record<string, string> = {
435
+ invalid_name: "invalid name",
436
+ not_found: "not found",
437
+ not_active: "no longer active",
438
+ invalid_registration: "invalid registration",
439
+ };
440
+ const errKey = (validation as { valid: false; error: string }).error;
441
+ failed.push({ name: recipient, error: errorMap[errKey] });
442
+ continue;
443
+ }
444
+
445
+ try {
446
+ store.sendMessageToAgent(state, dirs, recipient, message, replyTo);
447
+ sent.push(recipient);
448
+ } catch (err) {
449
+ const msg = err instanceof Error ? err.message : "write failed";
450
+ failed.push({ name: recipient, error: msg });
451
+ }
452
+ }
453
+
454
+ if (sent.length === 0) {
455
+ const failedStr = failed.map(f => `${f.name} (${f.error})`).join(", ");
456
+ return result(`Failed to send: ${failedStr}`, { mode: "send", error: "all_failed", sent: [], failed });
457
+ }
458
+
459
+ messagesSentThisSession++;
460
+
461
+ const preview = message.length > 200 ? message.slice(0, 197) + "..." : message;
462
+ if (broadcast) {
463
+ logFeedEvent(cwd, state.agentName, "message", undefined, preview);
464
+ } else {
465
+ for (const name of sent) {
466
+ logFeedEvent(cwd, state.agentName, "message", name, preview);
467
+ }
468
+ }
469
+
470
+ const remaining = budget - messagesSentThisSession;
471
+ let text = `Message sent to ${sent.join(", ")}. (${remaining} message${remaining === 1 ? "" : "s"} remaining)`;
472
+ if (failed.length > 0) {
473
+ const failedStr = failed.map(f => `${f.name} (${f.error})`).join(", ");
474
+ text += ` Failed: ${failedStr}`;
475
+ }
476
+
477
+ return result(text, { mode: "send", sent, failed });
478
+ }
479
+
480
+ export function executeReserve(
481
+ state: MessengerState,
482
+ dirs: Dirs,
483
+ ctx: ExtensionContext,
484
+ patterns: string[],
485
+ reason?: string,
486
+ ) {
487
+ if (!state.registered) {
488
+ return notRegisteredError();
489
+ }
490
+
491
+ if (patterns.length === 0) {
492
+ return result("Error: at least one pattern required.", { mode: "reserve", error: "empty_patterns" });
493
+ }
494
+
495
+ const now = new Date().toISOString();
496
+
497
+ for (const pattern of patterns) {
498
+ state.reservations = state.reservations.filter(r => r.pattern !== pattern);
499
+ state.reservations.push({ pattern, reason, since: now });
500
+ }
501
+
502
+ store.updateRegistration(state, dirs, ctx);
503
+
504
+ for (const pattern of patterns) {
505
+ logFeedEvent(ctx.cwd, state.agentName, "reserve", pattern, reason);
506
+ }
507
+
508
+ return result(`Reserved: ${patterns.join(", ")}`, { mode: "reserve", patterns, reason });
509
+ }
510
+
511
+ export function executeRelease(state: MessengerState, dirs: Dirs, ctx: ExtensionContext, release: string[] | true) {
512
+ if (!state.registered) {
513
+ return notRegisteredError();
514
+ }
515
+
516
+ if (release === true) {
517
+ const released = state.reservations.map(r => r.pattern);
518
+ state.reservations = [];
519
+ store.updateRegistration(state, dirs, ctx);
520
+ for (const pattern of released) {
521
+ logFeedEvent(ctx.cwd, state.agentName, "release", pattern);
522
+ }
523
+ return result(released.length > 0 ? `Released all: ${released.join(", ")}` : "No reservations to release.", {
524
+ mode: "release",
525
+ released,
526
+ });
527
+ }
528
+
529
+ const patterns = release;
530
+ const releasedPatterns = state.reservations.filter(r => patterns.includes(r.pattern)).map(r => r.pattern);
531
+ state.reservations = state.reservations.filter(r => !patterns.includes(r.pattern));
532
+
533
+ store.updateRegistration(state, dirs, ctx);
534
+ for (const pattern of releasedPatterns) {
535
+ logFeedEvent(ctx.cwd, state.agentName, "release", pattern);
536
+ }
537
+
538
+ return result(`Released ${releasedPatterns.length} reservation(s).`, {
539
+ mode: "release",
540
+ released: releasedPatterns,
541
+ });
542
+ }
543
+
544
+ export function executeRename(
545
+ state: MessengerState,
546
+ dirs: Dirs,
547
+ ctx: ExtensionContext,
548
+ newName: string,
549
+ deliverFn: (msg: AgentMailMessage) => void,
550
+ updateStatusFn: (ctx: ExtensionContext) => void,
551
+ ) {
552
+ store.stopWatcher(state);
553
+
554
+ const renameResult = store.renameAgent(state, dirs, ctx, newName, deliverFn);
555
+
556
+ if (!renameResult.success) {
557
+ store.startWatcher(state, dirs, deliverFn);
558
+
559
+ const errCode = (renameResult as { success: false; error: string }).error;
560
+ const errorMessages: Record<string, string> = {
561
+ not_registered: "Cannot rename - not registered.",
562
+ invalid_name: `Invalid name "${newName}" - use only letters, numbers, underscore, hyphen.`,
563
+ name_taken: `Name "${newName}" is already in use by another agent.`,
564
+ same_name: `Already named "${newName}".`,
565
+ race_lost: `Name "${newName}" was claimed by another agent.`,
566
+ };
567
+ return result(`Error: ${errorMessages[errCode]}`, { mode: "rename", error: errCode });
568
+ }
569
+
570
+ state.watcherRetries = 0;
571
+ store.startWatcher(state, dirs, deliverFn);
572
+ updateStatusFn(ctx);
573
+
574
+ return result(`Renamed from "${renameResult.oldName}" to "${renameResult.newName}".`, {
575
+ mode: "rename",
576
+ oldName: renameResult.oldName,
577
+ newName: renameResult.newName,
578
+ });
579
+ }
580
+
581
+ export function executeSetSpec(state: MessengerState, dirs: Dirs, ctx: ExtensionContext, specPath: string) {
582
+ const cwd = ctx.cwd;
583
+ const absPath = resolveSpecPath(specPath, cwd);
584
+ state.spec = absPath;
585
+ store.updateRegistration(state, dirs, ctx);
586
+ const display = displaySpecPath(absPath, cwd);
587
+ const warning = existsSync(absPath) ? "" : `\n\nWarning: Spec file not found at ${display}.`;
588
+ return result(`Spec set to ${display}${warning}`, { mode: "spec", spec: display });
589
+ }
590
+
591
+ export async function executeClaim(
592
+ state: MessengerState,
593
+ dirs: Dirs,
594
+ ctx: ExtensionContext,
595
+ taskId: string,
596
+ specPath?: string,
597
+ reason?: string,
598
+ ) {
599
+ const cwd = ctx.cwd;
600
+ const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
601
+ if (!spec) {
602
+ return result("Error: No spec registered. Use `spec` parameter or join with a spec first.", {
603
+ mode: "claim",
604
+ error: "no_spec",
605
+ });
606
+ }
607
+
608
+ const warning =
609
+ specPath && !existsSync(spec) ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.` : "";
610
+
611
+ const claimResult = await store.claimTask(
612
+ dirs,
613
+ spec,
614
+ taskId,
615
+ state.agentName,
616
+ ctx.sessionManager.getSessionId(),
617
+ process.pid,
618
+ reason,
619
+ );
620
+
621
+ const display = displaySpecPath(spec, cwd);
622
+ if (store.isClaimSuccess(claimResult)) {
623
+ return result(`Claimed ${taskId} in ${display}${warning}`, {
624
+ mode: "claim",
625
+ spec: display,
626
+ taskId,
627
+ claimedAt: claimResult.claimedAt,
628
+ reason,
629
+ });
630
+ }
631
+
632
+ if (store.isClaimAlreadyHaveClaim(claimResult)) {
633
+ const existingDisplay = displaySpecPath(claimResult.existing.spec, cwd);
634
+ return result(
635
+ `Error: You already have a claim on ${claimResult.existing.taskId} in ${existingDisplay}. Complete or unclaim it first.${warning}`,
636
+ {
637
+ mode: "claim",
638
+ error: "already_have_claim",
639
+ existing: { spec: existingDisplay, taskId: claimResult.existing.taskId },
640
+ },
641
+ );
642
+ }
643
+
644
+ // isClaimAlreadyClaimed
645
+ return result(`Error: ${taskId} is already claimed by ${claimResult.conflict.agent}.${warning}`, {
646
+ mode: "claim",
647
+ error: "already_claimed",
648
+ taskId,
649
+ conflict: claimResult.conflict,
650
+ });
651
+ }
652
+
653
+ export async function executeUnclaim(
654
+ state: MessengerState,
655
+ dirs: Dirs,
656
+ cwd: string,
657
+ taskId: string,
658
+ specPath?: string,
659
+ ) {
660
+ const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
661
+ if (!spec) {
662
+ return result("Error: No spec registered.", { mode: "unclaim", error: "no_spec" });
663
+ }
664
+
665
+ const warning =
666
+ specPath && !existsSync(spec) ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.` : "";
667
+
668
+ const unclaimResult = await store.unclaimTask(dirs, spec, taskId, state.agentName);
669
+ const display = displaySpecPath(spec, cwd);
670
+
671
+ if (store.isUnclaimSuccess(unclaimResult)) {
672
+ return result(`Released claim on ${taskId}${warning}`, { mode: "unclaim", spec: display, taskId });
673
+ }
674
+
675
+ if (store.isUnclaimNotYours(unclaimResult)) {
676
+ return result(`Error: ${taskId} is claimed by ${unclaimResult.claimedBy}, not you.${warning}`, {
677
+ mode: "unclaim",
678
+ error: "not_your_claim",
679
+ taskId,
680
+ claimedBy: unclaimResult.claimedBy,
681
+ });
682
+ }
683
+
684
+ // error === "not_claimed"
685
+ return result(`Error: ${taskId} is not claimed.${warning}`, { mode: "unclaim", error: "not_claimed", taskId });
686
+ }
687
+
688
+ export async function executeComplete(
689
+ state: MessengerState,
690
+ dirs: Dirs,
691
+ cwd: string,
692
+ taskId: string,
693
+ notes?: string,
694
+ specPath?: string,
695
+ ) {
696
+ const spec = specPath ? resolveSpecPath(specPath, cwd) : state.spec;
697
+ if (!spec) {
698
+ return result("Error: No spec registered.", { mode: "complete", error: "no_spec" });
699
+ }
700
+
701
+ const warning =
702
+ specPath && !existsSync(spec) ? `\n\nWarning: Spec file not found at ${displaySpecPath(spec, cwd)}.` : "";
703
+
704
+ const completeResult = await store.completeTask(dirs, spec, taskId, state.agentName, notes);
705
+ const display = displaySpecPath(spec, cwd);
706
+
707
+ if (store.isCompleteSuccess(completeResult)) {
708
+ return result(`Completed ${taskId} in ${display}${warning}`, {
709
+ mode: "complete",
710
+ spec: display,
711
+ taskId,
712
+ completedAt: completeResult.completedAt,
713
+ });
714
+ }
715
+
716
+ if (store.isCompleteAlreadyCompleted(completeResult)) {
717
+ return result(`Error: ${taskId} was already completed by ${completeResult.completion.completedBy}.${warning}`, {
718
+ mode: "complete",
719
+ error: "already_completed",
720
+ taskId,
721
+ completion: completeResult.completion,
722
+ });
723
+ }
724
+
725
+ if (store.isCompleteNotYours(completeResult)) {
726
+ return result(`Error: ${taskId} is claimed by ${completeResult.claimedBy}, not you.${warning}`, {
727
+ mode: "complete",
728
+ error: "not_your_claim",
729
+ taskId,
730
+ claimedBy: completeResult.claimedBy,
731
+ });
732
+ }
733
+
734
+ // error === "not_claimed"
735
+ return result(`Error: ${taskId} is not claimed.${warning}`, { mode: "complete", error: "not_claimed", taskId });
736
+ }
737
+
738
+ export function executeSwarm(state: MessengerState, dirs: Dirs, cwd: string, specPath?: string) {
739
+ const claims = store.getClaims(dirs);
740
+ const completions = store.getCompletions(dirs);
741
+ const agents = store.getActiveAgents(state, dirs);
742
+
743
+ const absByDisplay = new Map<string, string>();
744
+ const addAbs = (abs: string) => {
745
+ const display = displaySpecPath(abs, cwd);
746
+ if (!absByDisplay.has(display)) absByDisplay.set(display, abs);
747
+ };
748
+
749
+ for (const abs of Object.keys(claims)) addAbs(abs);
750
+ for (const abs of Object.keys(completions)) addAbs(abs);
751
+ if (state.spec) addAbs(state.spec);
752
+ for (const agent of agents) {
753
+ if (agent.spec) addAbs(agent.spec);
754
+ }
755
+
756
+ const specAgents: Record<string, string[]> = {};
757
+ if (state.spec) {
758
+ const display = displaySpecPath(state.spec, cwd);
759
+ specAgents[display] = [state.agentName];
760
+ }
761
+ for (const agent of agents) {
762
+ if (!agent.spec) continue;
763
+ const display = displaySpecPath(agent.spec, cwd);
764
+ if (!specAgents[display]) specAgents[display] = [];
765
+ specAgents[display].push(agent.name);
766
+ }
767
+
768
+ const myClaim = store.getAgentCurrentClaim(dirs, state.agentName);
769
+ const mySpec = state.spec ? displaySpecPath(state.spec, cwd) : undefined;
770
+
771
+ if (specPath) {
772
+ const absSpec = resolveSpecPath(specPath, cwd);
773
+ const display = displaySpecPath(absSpec, cwd);
774
+ const warning = !existsSync(absSpec) ? `\n\nWarning: Spec file not found at ${display}.` : "";
775
+ const specClaims: SpecClaims = claims[absSpec] || {};
776
+ const specCompletions: SpecCompletions = completions[absSpec] || {};
777
+ const specAgentList = specAgents[display] || [];
778
+
779
+ const lines = [`Swarm: ${display}`, ""];
780
+ const completedIds = Object.keys(specCompletions);
781
+ lines.push(`Completed: ${completedIds.length > 0 ? completedIds.join(", ") : "(none)"}`);
782
+
783
+ const inProgress = Object.entries(specClaims).map(
784
+ ([tid, c]) => `${tid} (${c.agent === state.agentName ? "you" : c.agent})`,
785
+ );
786
+ lines.push(`In progress: ${inProgress.length > 0 ? inProgress.join(", ") : "(none)"}`);
787
+
788
+ const teammates = specAgentList.filter(name => name !== state.agentName);
789
+ if (teammates.length > 0) lines.push(`Teammates: ${teammates.join(", ")}`);
790
+
791
+ return result(lines.join("\n") + warning, {
792
+ mode: "swarm",
793
+ spec: display,
794
+ agents: specAgentList,
795
+ claims: specClaims,
796
+ completions: specCompletions,
797
+ });
798
+ }
799
+
800
+ const allSpecs = new Set<string>([...absByDisplay.keys(), ...Object.keys(specAgents)]);
801
+
802
+ const lines = ["Swarm Status:", ""];
803
+ const specsData: Record<string, { agents: string[]; claims: SpecClaims; completions: SpecCompletions }> = {};
804
+
805
+ for (const display of Array.from(allSpecs).sort((a, b) => a.localeCompare(b))) {
806
+ const absSpec = absByDisplay.get(display) ?? resolveSpecPath(display, cwd);
807
+ const specClaims: SpecClaims = claims[absSpec] || {};
808
+ const specCompletions: SpecCompletions = completions[absSpec] || {};
809
+ const specAgentList = specAgents[display] || [];
810
+
811
+ specsData[display] = { agents: specAgentList, claims: specClaims, completions: specCompletions };
812
+
813
+ const isMySpec = display === mySpec;
814
+ lines.push(`${display}${isMySpec ? " (your spec)" : ""}:`);
815
+
816
+ const completedIds = Object.keys(specCompletions);
817
+ lines.push(` Completed: ${completedIds.length > 0 ? completedIds.join(", ") : "(none)"}`);
818
+
819
+ const inProgress = Object.entries(specClaims).map(
820
+ ([tid, c]) => `${tid} (${c.agent === state.agentName ? "you" : c.agent})`,
821
+ );
822
+ lines.push(` In progress: ${inProgress.length > 0 ? inProgress.join(", ") : "(none)"}`);
823
+
824
+ const idle = specAgentList.filter(name => !Object.values(specClaims).some(c => c.agent === name));
825
+ if (idle.length > 0) lines.push(` Idle: ${idle.join(", ")}`);
826
+ lines.push("");
827
+ }
828
+
829
+ return result(lines.join("\n").trim(), {
830
+ mode: "swarm",
831
+ yourSpec: mySpec,
832
+ yourClaim: myClaim?.taskId,
833
+ specs: specsData,
834
+ });
835
+ }
836
+
837
+ export function executeSetStatus(state: MessengerState, dirs: Dirs, ctx: ExtensionContext, message?: string) {
838
+ if (!state.registered) {
839
+ return notRegisteredError();
840
+ }
841
+
842
+ if (!message || message.trim() === "") {
843
+ state.statusMessage = undefined;
844
+ state.customStatus = false;
845
+ store.updateRegistration(state, dirs, ctx);
846
+ return result("Custom status cleared. Auto-status will resume.", { mode: "set_status", cleared: true });
847
+ }
848
+
849
+ state.statusMessage = message.trim();
850
+ state.customStatus = true;
851
+ store.updateRegistration(state, dirs, ctx);
852
+ return result(`Status set to: ${state.statusMessage}`, { mode: "set_status", message: state.statusMessage });
853
+ }
854
+
855
+ export function executeFeed(cwd: string, limit?: number, crewEventsInFeed: boolean = true) {
856
+ const effectiveLimit = limit ?? 20;
857
+ let events: FeedEvent[];
858
+ if (!crewEventsInFeed) {
859
+ events = readFeedEvents(cwd, effectiveLimit * 2);
860
+ events = events.filter(e => !isCrewEvent(e.type));
861
+ events = events.slice(-effectiveLimit);
862
+ } else {
863
+ events = readFeedEvents(cwd, effectiveLimit);
864
+ }
865
+
866
+ if (events.length === 0) {
867
+ return result("# Activity Feed\n\nNo activity yet.", { mode: "feed", events: [] });
868
+ }
869
+
870
+ const lines: string[] = [`# Activity Feed (last ${events.length})`, ""];
871
+ for (const event of events) {
872
+ lines.push(formatFeedLine(event));
873
+ }
874
+
875
+ return result(lines.join("\n"), { mode: "feed", events });
876
+ }
877
+
878
+ export function executeWhois(
879
+ state: MessengerState,
880
+ dirs: Dirs,
881
+ cwd: string,
882
+ name: string,
883
+ config?: { stuckThreshold?: number },
884
+ ) {
885
+ if (!state.registered) {
886
+ return notRegisteredError();
887
+ }
888
+
889
+ const thresholdMs = (config?.stuckThreshold ?? 900) * 1000;
890
+
891
+ const agents = store.getActiveAgents(state, dirs);
892
+ const agent = agents.find(a => a.name === name);
893
+ if (!agent) {
894
+ if (name === state.agentName) {
895
+ return executeWhoisSelf(state, dirs, cwd, thresholdMs);
896
+ }
897
+ return result(`Agent "${name}" not found or not active.`, { mode: "whois", error: "not_found", name });
898
+ }
899
+
900
+ return formatWhoisOutput(agent, false, dirs, cwd, thresholdMs);
901
+ }
902
+
903
+ function executeWhoisSelf(state: MessengerState, dirs: Dirs, cwd: string, thresholdMs: number) {
904
+ return formatWhoisOutput(buildSelfRegistration(state), true, dirs, cwd, thresholdMs);
905
+ }
906
+
907
+ function formatWhoisOutput(agent: AgentRegistration, isSelf: boolean, dirs: Dirs, cwd: string, thresholdMs: number) {
908
+ const allClaims = store.getClaims(dirs);
909
+ const hasTask = agentHasTask(agent.name, allClaims, crewStore.getTasks(agent.cwd));
910
+
911
+ const computed = computeStatus(
912
+ agent.activity?.lastActivityAt ?? agent.startedAt,
913
+ hasTask,
914
+ (agent.reservations?.length ?? 0) > 0,
915
+ thresholdMs,
916
+ );
917
+
918
+ const indicator = STATUS_INDICATORS[computed.status];
919
+ const statusLabel = computed.status.charAt(0).toUpperCase() + computed.status.slice(1);
920
+ const idleStr = computed.idleFor ? ` for ${computed.idleFor}` : "";
921
+
922
+ const sessionAge = formatDuration(Date.now() - new Date(agent.startedAt).getTime());
923
+ const tokens = agent.session?.tokens ?? 0;
924
+ const tokenStr = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : `${tokens}`;
925
+
926
+ const lines: string[] = [];
927
+ lines.push(`# ${agent.name}${isSelf ? " (you)" : ""}`, "");
928
+ lines.push(`${indicator} ${statusLabel}${idleStr}`);
929
+ if (agent.model) lines.push(`Model: ${agent.model}`);
930
+ if (agent.gitBranch) lines.push(`Branch: ${agent.gitBranch}`);
931
+ lines.push(`Session: ${sessionAge} - ${agent.session?.toolCalls ?? 0} tool calls - ${tokenStr} tokens`);
932
+
933
+ if (agent.statusMessage) {
934
+ lines.push(`Status: ${agent.statusMessage}`);
935
+ }
936
+
937
+ if (agent.reservations && agent.reservations.length > 0) {
938
+ lines.push("", "## Reservations");
939
+ for (const r of agent.reservations) {
940
+ lines.push(`- ${r.pattern}${r.reason ? ` (${r.reason})` : ""}`);
941
+ }
942
+ }
943
+
944
+ if (agent.session?.filesModified && agent.session.filesModified.length > 0) {
945
+ lines.push("", "## Recent Files");
946
+ for (const f of agent.session.filesModified.slice(-10)) {
947
+ lines.push(`- ${f}`);
948
+ }
949
+ }
950
+
951
+ const feedCwd = isSelf ? cwd : agent.cwd;
952
+ const allFeedEvents = readFeedEvents(feedCwd, 100);
953
+ const agentEvents = allFeedEvents.filter(e => e.agent === agent.name).slice(-10);
954
+ if (agentEvents.length > 0) {
955
+ lines.push("", "## Recent Activity");
956
+ for (const e of agentEvents) {
957
+ lines.push(`- ${formatFeedLine(e)}`);
958
+ }
959
+ }
960
+
961
+ return result(lines.join("\n"), { mode: "whois", agent });
962
+ }
963
+
964
+ export function executeAutoRegisterPath(action: "add" | "remove" | "list", cwd: string) {
965
+ const paths = getAutoRegisterPaths();
966
+
967
+ if (action === "list") {
968
+ if (paths.length === 0) {
969
+ return result(
970
+ 'No auto-register paths configured.\n\nUse pi_messenger({ action: "autoRegisterPath", autoRegisterPath: "add" }) to add the current folder.',
971
+ { mode: "autoRegisterPath", action: "list", paths: [], currentFolder: cwd, isCurrentInList: false },
972
+ );
973
+ }
974
+
975
+ const isCurrentInList = matchesAutoRegisterPath(cwd, paths);
976
+ const lines = ["Auto-register paths:", ""];
977
+ for (const p of paths) {
978
+ const marker = p === cwd ? " (current)" : "";
979
+ lines.push(` ${p}${marker}`);
980
+ }
981
+ lines.push("");
982
+ lines.push(`Current folder: ${cwd}`);
983
+ lines.push(`Status: ${isCurrentInList ? "Will auto-register here" : "Will NOT auto-register here"}`);
984
+
985
+ return result(lines.join("\n"), {
986
+ mode: "autoRegisterPath",
987
+ action: "list",
988
+ paths,
989
+ currentFolder: cwd,
990
+ isCurrentInList,
991
+ });
992
+ }
993
+
994
+ if (action === "add") {
995
+ if (paths.includes(cwd)) {
996
+ return result(`Current folder already in auto-register paths:\n ${cwd}`, {
997
+ mode: "autoRegisterPath",
998
+ action: "add",
999
+ alreadyExists: true,
1000
+ path: cwd,
1001
+ });
1002
+ }
1003
+
1004
+ const newPaths = [...paths, cwd];
1005
+ saveAutoRegisterPaths(newPaths);
1006
+
1007
+ return result(
1008
+ `Added to auto-register paths:\n ${cwd}\n\nAgents starting in this folder will now auto-join the mesh.`,
1009
+ { mode: "autoRegisterPath", action: "add", path: cwd, paths: newPaths },
1010
+ );
1011
+ }
1012
+
1013
+ if (action === "remove") {
1014
+ if (!paths.includes(cwd)) {
1015
+ // Check if it matches via glob but isn't exact
1016
+ const isMatched = matchesAutoRegisterPath(cwd, paths);
1017
+ if (isMatched) {
1018
+ return result(
1019
+ `Current folder matches a glob pattern but isn't an exact entry.\nManually edit ~/.zeta/agent/pi-messenger.json to modify glob patterns.`,
1020
+ { mode: "autoRegisterPath", action: "remove", notExact: true, path: cwd },
1021
+ );
1022
+ }
1023
+ return result(`Current folder not in auto-register paths:\n ${cwd}`, {
1024
+ mode: "autoRegisterPath",
1025
+ action: "remove",
1026
+ notFound: true,
1027
+ path: cwd,
1028
+ });
1029
+ }
1030
+
1031
+ const newPaths = paths.filter(p => p !== cwd);
1032
+ saveAutoRegisterPaths(newPaths);
1033
+
1034
+ return result(
1035
+ `Removed from auto-register paths:\n ${cwd}\n\nAgents starting in this folder will no longer auto-join.`,
1036
+ { mode: "autoRegisterPath", action: "remove", path: cwd, paths: newPaths },
1037
+ );
1038
+ }
1039
+
1040
+ return result("Invalid action. Use: add, remove, or list", { mode: "autoRegisterPath", error: "invalid_action" });
1041
+ }