@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/install.mjs ADDED
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * pi-messenger installer
5
+ *
6
+ * Copies the npm package contents to ~/.pi/agent/extensions/pi-messenger.
7
+ * No git dependency — the npm package IS the source.
8
+ *
9
+ * Usage:
10
+ * npx pi-messenger # Install or update extension
11
+ * npx pi-messenger --remove # Remove the extension
12
+ * npx pi-messenger --crew-install # Show crew agent info
13
+ * npx pi-messenger --crew-uninstall # Remove crew agents
14
+ */
15
+
16
+ import * as fs from "node:fs";
17
+ import * as path from "node:path";
18
+ import * as os from "node:os";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ const __filename = fileURLToPath(import.meta.url);
22
+ const PACKAGE_DIR = path.dirname(__filename);
23
+ const AGENT_DIR = path.join(os.homedir(), ".pi", "agent");
24
+ const EXTENSION_DIR = path.join(AGENT_DIR, "extensions", "pi-messenger");
25
+ const NATIVE_PACKAGE_DIR = path.join(AGENT_DIR, "npm", "node_modules", "pi-messenger");
26
+ const SETTINGS_PATH = path.join(AGENT_DIR, "settings.json");
27
+ const AGENTS_DIR = path.join(AGENT_DIR, "agents");
28
+
29
+ const CREW_AGENTS = [
30
+ "crew-planner.md",
31
+ "crew-interview-generator.md",
32
+ "crew-plan-sync.md",
33
+ "crew-worker.md",
34
+ "crew-reviewer.md",
35
+ ];
36
+
37
+ const DEPRECATED_AGENTS = [
38
+ "crew-repo-scout.md",
39
+ "crew-practice-scout.md",
40
+ "crew-docs-scout.md",
41
+ "crew-web-scout.md",
42
+ "crew-github-scout.md",
43
+ "crew-gap-analyst.md",
44
+ ];
45
+
46
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, "package.json"), "utf-8"));
47
+ const VERSION = pkg.version;
48
+
49
+ const args = process.argv.slice(2);
50
+ const isRemove = args.includes("--remove") || args.includes("-r");
51
+ const isCrewInstall = args.includes("--crew-install");
52
+ const isCrewUninstall = args.includes("--crew-uninstall");
53
+ const isHelp = args.includes("--help") || args.includes("-h");
54
+
55
+ if (isHelp) {
56
+ console.log(`
57
+ pi-messenger v${VERSION} - Multi-agent coordination for pi
58
+
59
+ Usage:
60
+ npx pi-messenger Install or update extension
61
+ npx pi-messenger --remove Remove the extension
62
+ npx pi-messenger --crew-install Show crew agent info
63
+ npx pi-messenger --crew-uninstall Remove crew agents
64
+ npx pi-messenger --help Show this help
65
+
66
+ Extension directory: ${EXTENSION_DIR}
67
+ `);
68
+ process.exit(0);
69
+ }
70
+
71
+ // ─── Crew install ────────────────────────────────────────────────────────────
72
+
73
+ if (isCrewInstall) {
74
+ const agentsDir = path.join(EXTENSION_DIR, "crew", "agents");
75
+ if (!fs.existsSync(agentsDir)) {
76
+ console.log("Extension not installed. Run: npx pi-messenger");
77
+ process.exit(1);
78
+ }
79
+
80
+ const agents = fs.readdirSync(agentsDir).filter(f => f.endsWith(".md"));
81
+ console.log(`Crew agents (${agents.length}) ship with the extension:`);
82
+ console.log(` ${agentsDir}`);
83
+ for (const agent of agents) {
84
+ console.log(` - ${agent}`);
85
+ }
86
+ console.log("\nTo customize, copy an agent to .pi/messenger/crew/agents/ and edit it.");
87
+ process.exit(0);
88
+ }
89
+
90
+ // ─── Crew uninstall ──────────────────────────────────────────────────────────
91
+
92
+ if (isCrewUninstall) {
93
+ let removed = 0;
94
+
95
+ for (const agent of [...CREW_AGENTS, ...DEPRECATED_AGENTS]) {
96
+ const target = path.join(AGENTS_DIR, agent);
97
+ if (fs.existsSync(target)) {
98
+ fs.unlinkSync(target);
99
+ removed++;
100
+ }
101
+ }
102
+
103
+ console.log(removed > 0
104
+ ? `Removed ${removed} crew agent(s) from ${AGENTS_DIR}`
105
+ : "Nothing to remove");
106
+ process.exit(0);
107
+ }
108
+
109
+ // ─── Extension remove ────────────────────────────────────────────────────────
110
+
111
+ if (isRemove) {
112
+ if (fs.existsSync(EXTENSION_DIR)) {
113
+ fs.rmSync(EXTENSION_DIR, { recursive: true });
114
+ console.log("Removed pi-messenger from " + EXTENSION_DIR);
115
+ } else {
116
+ console.log("pi-messenger is not installed");
117
+ }
118
+ process.exit(0);
119
+ }
120
+
121
+ // Already running from the extension dir (e.g. local dev)
122
+ if (path.resolve(PACKAGE_DIR) === path.resolve(EXTENSION_DIR)) {
123
+ console.log(`Already installed at ${EXTENSION_DIR} (v${VERSION})`);
124
+ process.exit(0);
125
+ }
126
+
127
+ const isUpdate = fs.existsSync(EXTENSION_DIR);
128
+
129
+ function hasNativePackageInstall() {
130
+ if (fs.existsSync(NATIVE_PACKAGE_DIR)) {
131
+ return true;
132
+ }
133
+
134
+ try {
135
+ const settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, "utf-8"));
136
+ const packages = Array.isArray(settings.packages) ? settings.packages : [];
137
+ return packages.some(pkg => pkg === "npm:pi-messenger");
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ if (hasNativePackageInstall()) {
144
+ console.log(`pi-messenger is already installed via pi's native package flow.
145
+
146
+ Keep the native install and remove any legacy copy instead:
147
+
148
+ npx pi-messenger --remove
149
+
150
+ Do not run the legacy npx installer alongside \`pi install npm:pi-messenger\`; loading both copies registers the \`pi_messenger\` tool twice.`);
151
+ process.exit(1);
152
+ }
153
+
154
+ // Warn if existing install is a git clone from the old installer
155
+ if (isUpdate && fs.existsSync(path.join(EXTENSION_DIR, ".git"))) {
156
+ console.log("Existing install is a git clone. Remove it first:\n");
157
+ console.log(" npx pi-messenger --remove && npx pi-messenger");
158
+ process.exit(1);
159
+ }
160
+
161
+ // Clean slate for updates so removed files don't linger between versions
162
+ if (isUpdate) {
163
+ fs.rmSync(EXTENSION_DIR, { recursive: true });
164
+ }
165
+
166
+ const SKIP = new Set([".git", "node_modules", ".DS_Store"]);
167
+
168
+ function copyDir(src, dest) {
169
+ fs.mkdirSync(dest, { recursive: true });
170
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
171
+ if (SKIP.has(entry.name)) continue;
172
+ const srcPath = path.join(src, entry.name);
173
+ const destPath = path.join(dest, entry.name);
174
+ if (entry.isDirectory()) {
175
+ copyDir(srcPath, destPath);
176
+ } else {
177
+ fs.copyFileSync(srcPath, destPath);
178
+ }
179
+ }
180
+ }
181
+
182
+ copyDir(PACKAGE_DIR, EXTENSION_DIR);
183
+
184
+ const action = isUpdate ? "Updated" : "Installed";
185
+ console.log(`${action} pi-messenger v${VERSION} → ${EXTENSION_DIR}
186
+
187
+ Tools: pi_messenger
188
+ Commands: /messenger, /messenger config
189
+ Docs: ${EXTENSION_DIR}/README.md`);
package/lib.ts ADDED
@@ -0,0 +1,467 @@
1
+ /**
2
+ * Pi Messenger - Types and Pure Utilities
3
+ */
4
+
5
+ import type * as fs from "node:fs";
6
+ import { basename, isAbsolute, resolve, relative } from "node:path";
7
+
8
+ // =============================================================================
9
+ // Types
10
+ // =============================================================================
11
+
12
+ export interface FileReservation {
13
+ pattern: string;
14
+ reason?: string;
15
+ since: string;
16
+ }
17
+
18
+ export interface AgentSession {
19
+ toolCalls: number;
20
+ tokens: number;
21
+ filesModified: string[];
22
+ }
23
+
24
+ export interface AgentActivity {
25
+ lastActivityAt: string;
26
+ currentActivity?: string;
27
+ lastToolCall?: string;
28
+ }
29
+
30
+ export interface AgentRegistration {
31
+ name: string;
32
+ pid: number;
33
+ sessionId: string;
34
+ cwd: string;
35
+ model: string;
36
+ startedAt: string;
37
+ reservations?: FileReservation[];
38
+ gitBranch?: string;
39
+ spec?: string;
40
+ isHuman: boolean;
41
+ session: AgentSession;
42
+ activity: AgentActivity;
43
+ statusMessage?: string;
44
+ }
45
+
46
+ export interface AgentMailMessage {
47
+ id: string;
48
+ from: string;
49
+ to: string;
50
+ text: string;
51
+ timestamp: string;
52
+ replyTo: string | null;
53
+ }
54
+
55
+ interface AgentMailMessageInput {
56
+ id?: unknown;
57
+ from?: unknown;
58
+ to?: unknown;
59
+ text?: unknown;
60
+ message?: unknown;
61
+ timestamp?: unknown;
62
+ ts?: unknown;
63
+ replyTo?: unknown;
64
+ }
65
+
66
+ function stringField(value: unknown, fallback: string): string {
67
+ return typeof value === "string" ? value : fallback;
68
+ }
69
+
70
+ export function normalizeAgentMailMessage(
71
+ input: unknown,
72
+ defaults: { id: string; from: string; to: string; timestamp: string },
73
+ ): AgentMailMessage {
74
+ const raw = input && typeof input === "object" && !Array.isArray(input)
75
+ ? input as AgentMailMessageInput
76
+ : {};
77
+
78
+ return {
79
+ id: stringField(raw.id, defaults.id),
80
+ from: stringField(raw.from, defaults.from),
81
+ to: stringField(raw.to, defaults.to),
82
+ text: stringField(raw.text, stringField(raw.message, "")),
83
+ timestamp: stringField(raw.timestamp, stringField(raw.ts, defaults.timestamp)),
84
+ replyTo: typeof raw.replyTo === "string" ? raw.replyTo : null,
85
+ };
86
+ }
87
+
88
+ export interface ReservationConflict {
89
+ path: string;
90
+ agent: string;
91
+ pattern: string;
92
+ reason?: string;
93
+ registration: AgentRegistration;
94
+ }
95
+
96
+ export interface MessengerState {
97
+ agentName: string;
98
+ registered: boolean;
99
+ watcher: fs.FSWatcher | null;
100
+ watcherRetries: number;
101
+ watcherRetryTimer: ReturnType<typeof setTimeout> | null;
102
+ watcherDebounceTimer: ReturnType<typeof setTimeout> | null;
103
+ reservations: FileReservation[];
104
+ chatHistory: Map<string, AgentMailMessage[]>;
105
+ unreadCounts: Map<string, number>;
106
+ broadcastHistory: AgentMailMessage[];
107
+ seenSenders: Map<string, string>;
108
+ model: string;
109
+ cwd: string;
110
+ gitBranch?: string;
111
+ spec?: string;
112
+ scopeToFolder: boolean;
113
+ isHuman: boolean;
114
+ session: AgentSession;
115
+ activity: AgentActivity;
116
+ statusMessage?: string;
117
+ customStatus: boolean;
118
+ registryFlushTimer: ReturnType<typeof setTimeout> | null;
119
+ sessionStartedAt: string;
120
+ }
121
+
122
+ export interface Dirs {
123
+ base: string;
124
+ registry: string;
125
+ inbox: string;
126
+ }
127
+
128
+ export interface ClaimEntry {
129
+ agent: string;
130
+ sessionId: string;
131
+ pid: number;
132
+ claimedAt: string;
133
+ reason?: string;
134
+ }
135
+
136
+ export interface CompletionEntry {
137
+ completedBy: string;
138
+ completedAt: string;
139
+ notes?: string;
140
+ }
141
+
142
+ export type SpecClaims = Record<string, ClaimEntry>;
143
+ export type SpecCompletions = Record<string, CompletionEntry>;
144
+ export type AllClaims = Record<string, SpecClaims>;
145
+ export type AllCompletions = Record<string, SpecCompletions>;
146
+
147
+ export type AgentStatus = "active" | "idle" | "away" | "stuck";
148
+
149
+ export interface ComputedStatus {
150
+ status: AgentStatus;
151
+ idleFor?: string;
152
+ }
153
+
154
+ export function computeStatus(
155
+ lastActivityAt: string,
156
+ hasTask: boolean,
157
+ hasReservation: boolean,
158
+ thresholdMs: number
159
+ ): ComputedStatus {
160
+ const elapsed = Date.now() - new Date(lastActivityAt).getTime();
161
+ if (isNaN(elapsed) || elapsed < 0) {
162
+ return { status: "active" };
163
+ }
164
+ const ACTIVE_MS = 30_000;
165
+ const IDLE_MS = 5 * 60_000;
166
+
167
+ if (elapsed < ACTIVE_MS) {
168
+ return { status: "active" };
169
+ }
170
+ if (elapsed < IDLE_MS) {
171
+ return { status: "idle", idleFor: formatDuration(elapsed) };
172
+ }
173
+ if (!hasTask && !hasReservation) {
174
+ return { status: "away", idleFor: formatDuration(elapsed) };
175
+ }
176
+ if (elapsed >= thresholdMs) {
177
+ return { status: "stuck", idleFor: formatDuration(elapsed) };
178
+ }
179
+ return { status: "idle", idleFor: formatDuration(elapsed) };
180
+ }
181
+
182
+ export function formatDuration(ms: number): string {
183
+ const seconds = Math.floor(ms / 1000);
184
+ const minutes = Math.floor(seconds / 60);
185
+ const hours = Math.floor(minutes / 60);
186
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
187
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
188
+ return `${seconds}s`;
189
+ }
190
+
191
+ export const STATUS_INDICATORS: Record<AgentStatus, string> = {
192
+ active: "\u{1F7E2}",
193
+ idle: "\u{1F7E1}",
194
+ away: "\u{1F7E0}",
195
+ stuck: "\u{1F534}",
196
+ };
197
+
198
+ export interface AutoStatusContext {
199
+ currentActivity?: string;
200
+ recentCommit: boolean;
201
+ recentTestRuns: number;
202
+ recentEdits: number;
203
+ sessionStartedAt: string;
204
+ }
205
+
206
+ export function generateAutoStatus(ctx: AutoStatusContext): string | undefined {
207
+ const sessionAge = Date.now() - new Date(ctx.sessionStartedAt).getTime();
208
+
209
+ if (sessionAge < 30_000) {
210
+ return "just arrived";
211
+ }
212
+
213
+ if (ctx.recentCommit) {
214
+ return "just shipped";
215
+ }
216
+
217
+ if (ctx.recentTestRuns >= 3) {
218
+ return "debugging...";
219
+ }
220
+
221
+ if (ctx.recentEdits >= 8) {
222
+ return "on fire \u{1F525}";
223
+ }
224
+
225
+ if (ctx.currentActivity?.startsWith("reading")) {
226
+ return "exploring the codebase";
227
+ }
228
+
229
+ if (ctx.currentActivity?.startsWith("editing")) {
230
+ return "deep in thought";
231
+ }
232
+
233
+ return undefined;
234
+ }
235
+
236
+ // =============================================================================
237
+ // Constants
238
+ // =============================================================================
239
+
240
+ export const MAX_WATCHER_RETRIES = 5;
241
+ export const MAX_CHAT_HISTORY = 50;
242
+
243
+ const AGENT_COLORS = [
244
+ "38;2;178;129;214", // purple
245
+ "38;2;215;135;175", // pink
246
+ "38;2;254;188;56", // gold
247
+ "38;2;137;210;129", // green
248
+ "38;2;0;175;175", // cyan
249
+ "38;2;23;143;185", // blue
250
+ "38;2;228;192;15", // yellow
251
+ "38;2;255;135;135", // coral
252
+ ];
253
+
254
+ const DEFAULT_ADJECTIVES = [
255
+ "Swift", "Bright", "Calm", "Dark", "Epic", "Fast", "Gold", "Happy",
256
+ "Iron", "Jade", "Keen", "Loud", "Mint", "Nice", "Oak", "Pure",
257
+ "Quick", "Red", "Sage", "True", "Ultra", "Vivid", "Wild", "Young", "Zen"
258
+ ];
259
+
260
+ const DEFAULT_NOUNS = [
261
+ "Arrow", "Bear", "Castle", "Dragon", "Eagle", "Falcon", "Grove", "Hawk",
262
+ "Ice", "Jaguar", "Knight", "Lion", "Moon", "Nova", "Owl", "Phoenix",
263
+ "Quartz", "Raven", "Storm", "Tiger", "Union", "Viper", "Wolf", "Xenon", "Yak", "Zenith"
264
+ ];
265
+
266
+ const NATURE_ADJECTIVES = [
267
+ "Oak", "River", "Mountain", "Cedar", "Storm", "Meadow", "Frost", "Coral",
268
+ "Willow", "Stone", "Ember", "Moss", "Tide", "Fern", "Cloud", "Pine"
269
+ ];
270
+ const NATURE_NOUNS = [
271
+ "Tree", "Stone", "Wind", "Brook", "Peak", "Valley", "Lake", "Ridge",
272
+ "Creek", "Glade", "Fox", "Heron", "Sage", "Thorn", "Dawn", "Dusk"
273
+ ];
274
+
275
+ const SPACE_ADJECTIVES = [
276
+ "Nova", "Lunar", "Cosmic", "Solar", "Stellar", "Astral", "Nebula", "Orbit",
277
+ "Pulse", "Quasar", "Void", "Zenith", "Aurora", "Comet", "Warp", "Ion"
278
+ ];
279
+ const SPACE_NOUNS = [
280
+ "Star", "Dust", "Ray", "Flare", "Drift", "Core", "Ring", "Gate",
281
+ "Spark", "Beam", "Wave", "Shard", "Forge", "Bolt", "Glow", "Arc"
282
+ ];
283
+
284
+ const MINIMAL_NAMES = [
285
+ "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta", "Theta",
286
+ "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi",
287
+ "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"
288
+ ];
289
+
290
+ export interface NameThemeConfig {
291
+ theme: string;
292
+ customWords?: { adjectives: string[]; nouns: string[] };
293
+ }
294
+
295
+ // =============================================================================
296
+ // Pure Utilities
297
+ // =============================================================================
298
+
299
+ export function generateMemorableName(themeConfig?: NameThemeConfig): string {
300
+ const themeName = themeConfig?.theme ?? "default";
301
+
302
+ if (themeName === "minimal") {
303
+ return MINIMAL_NAMES[Math.floor(Math.random() * MINIMAL_NAMES.length)];
304
+ }
305
+
306
+ let adjectives: string[];
307
+ let nouns: string[];
308
+
309
+ switch (themeName) {
310
+ case "nature":
311
+ adjectives = NATURE_ADJECTIVES;
312
+ nouns = NATURE_NOUNS;
313
+ break;
314
+ case "space":
315
+ adjectives = SPACE_ADJECTIVES;
316
+ nouns = SPACE_NOUNS;
317
+ break;
318
+ case "custom":
319
+ adjectives = themeConfig?.customWords?.adjectives ?? DEFAULT_ADJECTIVES;
320
+ nouns = themeConfig?.customWords?.nouns ?? DEFAULT_NOUNS;
321
+ break;
322
+ default:
323
+ adjectives = DEFAULT_ADJECTIVES;
324
+ nouns = DEFAULT_NOUNS;
325
+ break;
326
+ }
327
+
328
+ const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
329
+ const noun = nouns[Math.floor(Math.random() * nouns.length)];
330
+ return adj + noun;
331
+ }
332
+
333
+ export function isProcessAlive(pid: number): boolean {
334
+ try {
335
+ process.kill(pid, 0);
336
+ return true;
337
+ } catch {
338
+ return false;
339
+ }
340
+ }
341
+
342
+ export function isValidAgentName(name: string): boolean {
343
+ if (!name || name.length > 50) return false;
344
+ return /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/.test(name);
345
+ }
346
+
347
+ export function formatRelativeTime(timestamp: string): string {
348
+ const diff = Date.now() - new Date(timestamp).getTime();
349
+ const seconds = Math.floor(diff / 1000);
350
+ const minutes = Math.floor(seconds / 60);
351
+ const hours = Math.floor(minutes / 60);
352
+
353
+ if (hours > 0) return `${hours}h ago`;
354
+ if (minutes > 0) return `${minutes}m ago`;
355
+ return "just now";
356
+ }
357
+
358
+ export function pathMatchesReservation(filePath: string, pattern: string): boolean {
359
+ if (pattern.endsWith("/")) {
360
+ return filePath.startsWith(pattern) || filePath + "/" === pattern;
361
+ }
362
+ return filePath === pattern;
363
+ }
364
+
365
+ export function stripAnsiCodes(text: string): string {
366
+ // eslint-disable-next-line no-control-regex
367
+ return text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
368
+ }
369
+
370
+ const colorCache = new Map<string, string>();
371
+
372
+ export function agentColorCode(name: string): string {
373
+ const cached = colorCache.get(name);
374
+ if (cached) return cached;
375
+
376
+ let hash = 0;
377
+ for (const char of name) hash = ((hash << 5) - hash) + char.charCodeAt(0);
378
+ const color = AGENT_COLORS[Math.abs(hash) % AGENT_COLORS.length];
379
+ colorCache.set(name, color);
380
+ return color;
381
+ }
382
+
383
+ export function coloredAgentName(name: string): string {
384
+ return `\x1b[${agentColorCode(name)}m${name}\x1b[0m`;
385
+ }
386
+
387
+ export function extractFolder(cwd: string): string {
388
+ return basename(cwd) || cwd;
389
+ }
390
+
391
+ export function resolveSpecPath(specPath: string, cwd: string): string {
392
+ if (isAbsolute(specPath)) return specPath;
393
+ return resolve(cwd, specPath);
394
+ }
395
+
396
+ export function displaySpecPath(absPath: string, cwd: string): string {
397
+ try {
398
+ const rel = relative(cwd, absPath);
399
+ if (rel === "") return ".";
400
+ if (!rel.startsWith("..") && !isAbsolute(rel)) {
401
+ return "./" + rel;
402
+ }
403
+ } catch {
404
+ // Ignore and fall back to absolute
405
+ }
406
+ return absPath;
407
+ }
408
+
409
+ export function truncatePathLeft(filePath: string, maxLen: number): string {
410
+ if (filePath.length <= maxLen) return filePath;
411
+ if (maxLen <= 1) return '…';
412
+ const truncated = filePath.slice(-(maxLen - 1));
413
+ const slashIdx = truncated.indexOf('/');
414
+ if (slashIdx > 0) {
415
+ return '…' + truncated.slice(slashIdx);
416
+ }
417
+ return '…' + truncated;
418
+ }
419
+
420
+ export function buildSelfRegistration(state: MessengerState): AgentRegistration {
421
+ return {
422
+ name: state.agentName,
423
+ pid: process.pid,
424
+ sessionId: "",
425
+ model: state.model,
426
+ cwd: state.cwd,
427
+ startedAt: state.sessionStartedAt,
428
+ gitBranch: state.gitBranch,
429
+ spec: state.spec,
430
+ isHuman: state.isHuman,
431
+ session: { ...state.session },
432
+ activity: { ...state.activity },
433
+ reservations: state.reservations.length > 0 ? state.reservations : undefined,
434
+ statusMessage: state.statusMessage,
435
+ };
436
+ }
437
+
438
+ export function agentHasTask(
439
+ name: string,
440
+ allClaims: AllClaims,
441
+ crewTasks: Array<{ assigned_to?: string; status: string }>
442
+ ): boolean {
443
+ for (const tasks of Object.values(allClaims)) {
444
+ for (const claim of Object.values(tasks)) {
445
+ if (claim.agent === name) return true;
446
+ }
447
+ }
448
+ return crewTasks.some(t => t.assigned_to === name && t.status === "in_progress");
449
+ }
450
+
451
+ export type DisplayMode = "same-folder-branch" | "same-folder" | "different";
452
+
453
+ export function getDisplayMode(agents: AgentRegistration[]): DisplayMode {
454
+ if (agents.length === 0) return "different";
455
+
456
+ const folders = agents.map(a => extractFolder(a.cwd));
457
+ const uniqueFolders = new Set(folders);
458
+
459
+ if (uniqueFolders.size > 1) return "different";
460
+
461
+ const branches = agents.map(a => a.gitBranch).filter(Boolean);
462
+ const uniqueBranches = new Set(branches);
463
+
464
+ if (uniqueBranches.size <= 1) return "same-folder-branch";
465
+
466
+ return "same-folder";
467
+ }