@linxiraos/pi-messenger 1.1.1 → 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/lib.ts CHANGED
@@ -1,467 +1,587 @@
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
- }
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) ? (input as AgentMailMessageInput) : {};
75
+
76
+ return {
77
+ id: stringField(raw.id, defaults.id),
78
+ from: stringField(raw.from, defaults.from),
79
+ to: stringField(raw.to, defaults.to),
80
+ text: stringField(raw.text, stringField(raw.message, "")),
81
+ timestamp: stringField(raw.timestamp, stringField(raw.ts, defaults.timestamp)),
82
+ replyTo: typeof raw.replyTo === "string" ? raw.replyTo : null,
83
+ };
84
+ }
85
+
86
+ export interface ReservationConflict {
87
+ path: string;
88
+ agent: string;
89
+ pattern: string;
90
+ reason?: string;
91
+ registration: AgentRegistration;
92
+ }
93
+
94
+ export interface MessengerState {
95
+ agentName: string;
96
+ registered: boolean;
97
+ watcher: fs.FSWatcher | null;
98
+ watcherRetries: number;
99
+ watcherRetryTimer: ReturnType<typeof setTimeout> | null;
100
+ watcherDebounceTimer: ReturnType<typeof setTimeout> | null;
101
+ reservations: FileReservation[];
102
+ chatHistory: Map<string, AgentMailMessage[]>;
103
+ unreadCounts: Map<string, number>;
104
+ broadcastHistory: AgentMailMessage[];
105
+ seenSenders: Map<string, string>;
106
+ model: string;
107
+ cwd: string;
108
+ gitBranch?: string;
109
+ spec?: string;
110
+ scopeToFolder: boolean;
111
+ isHuman: boolean;
112
+ session: AgentSession;
113
+ activity: AgentActivity;
114
+ statusMessage?: string;
115
+ customStatus: boolean;
116
+ registryFlushTimer: ReturnType<typeof setTimeout> | null;
117
+ sessionStartedAt: string;
118
+ }
119
+
120
+ export interface Dirs {
121
+ base: string;
122
+ registry: string;
123
+ inbox: string;
124
+ }
125
+
126
+ export interface ClaimEntry {
127
+ agent: string;
128
+ sessionId: string;
129
+ pid: number;
130
+ claimedAt: string;
131
+ reason?: string;
132
+ }
133
+
134
+ export interface CompletionEntry {
135
+ completedBy: string;
136
+ completedAt: string;
137
+ notes?: string;
138
+ }
139
+
140
+ export type SpecClaims = Record<string, ClaimEntry>;
141
+ export type SpecCompletions = Record<string, CompletionEntry>;
142
+ export type AllClaims = Record<string, SpecClaims>;
143
+ export type AllCompletions = Record<string, SpecCompletions>;
144
+
145
+ export type AgentStatus = "active" | "idle" | "away" | "stuck";
146
+
147
+ export interface ComputedStatus {
148
+ status: AgentStatus;
149
+ idleFor?: string;
150
+ }
151
+
152
+ export function computeStatus(
153
+ lastActivityAt: string,
154
+ hasTask: boolean,
155
+ hasReservation: boolean,
156
+ thresholdMs: number,
157
+ ): ComputedStatus {
158
+ const elapsed = Date.now() - new Date(lastActivityAt).getTime();
159
+ if (isNaN(elapsed) || elapsed < 0) {
160
+ return { status: "active" };
161
+ }
162
+ const ACTIVE_MS = 30_000;
163
+ const IDLE_MS = 5 * 60_000;
164
+
165
+ if (elapsed < ACTIVE_MS) {
166
+ return { status: "active" };
167
+ }
168
+ if (elapsed < IDLE_MS) {
169
+ return { status: "idle", idleFor: formatDuration(elapsed) };
170
+ }
171
+ if (!hasTask && !hasReservation) {
172
+ return { status: "away", idleFor: formatDuration(elapsed) };
173
+ }
174
+ if (elapsed >= thresholdMs) {
175
+ return { status: "stuck", idleFor: formatDuration(elapsed) };
176
+ }
177
+ return { status: "idle", idleFor: formatDuration(elapsed) };
178
+ }
179
+
180
+ export function formatDuration(ms: number): string {
181
+ const seconds = Math.floor(ms / 1000);
182
+ const minutes = Math.floor(seconds / 60);
183
+ const hours = Math.floor(minutes / 60);
184
+ if (hours > 0) return `${hours}h ${minutes % 60}m`;
185
+ if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
186
+ return `${seconds}s`;
187
+ }
188
+
189
+ export const STATUS_INDICATORS: Record<AgentStatus, string> = {
190
+ active: "\u{1F7E2}",
191
+ idle: "\u{1F7E1}",
192
+ away: "\u{1F7E0}",
193
+ stuck: "\u{1F534}",
194
+ };
195
+
196
+ export interface AutoStatusContext {
197
+ currentActivity?: string;
198
+ recentCommit: boolean;
199
+ recentTestRuns: number;
200
+ recentEdits: number;
201
+ sessionStartedAt: string;
202
+ }
203
+
204
+ export function generateAutoStatus(ctx: AutoStatusContext): string | undefined {
205
+ const sessionAge = Date.now() - new Date(ctx.sessionStartedAt).getTime();
206
+
207
+ if (sessionAge < 30_000) {
208
+ return "just arrived";
209
+ }
210
+
211
+ if (ctx.recentCommit) {
212
+ return "just shipped";
213
+ }
214
+
215
+ if (ctx.recentTestRuns >= 3) {
216
+ return "debugging...";
217
+ }
218
+
219
+ if (ctx.recentEdits >= 8) {
220
+ return "on fire \u{1F525}";
221
+ }
222
+
223
+ if (ctx.currentActivity?.startsWith("reading")) {
224
+ return "exploring the codebase";
225
+ }
226
+
227
+ if (ctx.currentActivity?.startsWith("editing")) {
228
+ return "deep in thought";
229
+ }
230
+
231
+ return undefined;
232
+ }
233
+
234
+ // =============================================================================
235
+ // Constants
236
+ // =============================================================================
237
+
238
+ export const MAX_WATCHER_RETRIES = 5;
239
+ export const MAX_CHAT_HISTORY = 50;
240
+
241
+ const AGENT_COLORS = [
242
+ "38;2;178;129;214", // purple
243
+ "38;2;215;135;175", // pink
244
+ "38;2;254;188;56", // gold
245
+ "38;2;137;210;129", // green
246
+ "38;2;0;175;175", // cyan
247
+ "38;2;23;143;185", // blue
248
+ "38;2;228;192;15", // yellow
249
+ "38;2;255;135;135", // coral
250
+ ];
251
+
252
+ const DEFAULT_ADJECTIVES = [
253
+ "Swift",
254
+ "Bright",
255
+ "Calm",
256
+ "Dark",
257
+ "Epic",
258
+ "Fast",
259
+ "Gold",
260
+ "Happy",
261
+ "Iron",
262
+ "Jade",
263
+ "Keen",
264
+ "Loud",
265
+ "Mint",
266
+ "Nice",
267
+ "Oak",
268
+ "Pure",
269
+ "Quick",
270
+ "Red",
271
+ "Sage",
272
+ "True",
273
+ "Ultra",
274
+ "Vivid",
275
+ "Wild",
276
+ "Young",
277
+ "Zen",
278
+ ];
279
+
280
+ const DEFAULT_NOUNS = [
281
+ "Arrow",
282
+ "Bear",
283
+ "Castle",
284
+ "Dragon",
285
+ "Eagle",
286
+ "Falcon",
287
+ "Grove",
288
+ "Hawk",
289
+ "Ice",
290
+ "Jaguar",
291
+ "Knight",
292
+ "Lion",
293
+ "Moon",
294
+ "Nova",
295
+ "Owl",
296
+ "Phoenix",
297
+ "Quartz",
298
+ "Raven",
299
+ "Storm",
300
+ "Tiger",
301
+ "Union",
302
+ "Viper",
303
+ "Wolf",
304
+ "Xenon",
305
+ "Yak",
306
+ "Zenith",
307
+ ];
308
+
309
+ const NATURE_ADJECTIVES = [
310
+ "Oak",
311
+ "River",
312
+ "Mountain",
313
+ "Cedar",
314
+ "Storm",
315
+ "Meadow",
316
+ "Frost",
317
+ "Coral",
318
+ "Willow",
319
+ "Stone",
320
+ "Ember",
321
+ "Moss",
322
+ "Tide",
323
+ "Fern",
324
+ "Cloud",
325
+ "Pine",
326
+ ];
327
+ const NATURE_NOUNS = [
328
+ "Tree",
329
+ "Stone",
330
+ "Wind",
331
+ "Brook",
332
+ "Peak",
333
+ "Valley",
334
+ "Lake",
335
+ "Ridge",
336
+ "Creek",
337
+ "Glade",
338
+ "Fox",
339
+ "Heron",
340
+ "Sage",
341
+ "Thorn",
342
+ "Dawn",
343
+ "Dusk",
344
+ ];
345
+
346
+ const SPACE_ADJECTIVES = [
347
+ "Nova",
348
+ "Lunar",
349
+ "Cosmic",
350
+ "Solar",
351
+ "Stellar",
352
+ "Astral",
353
+ "Nebula",
354
+ "Orbit",
355
+ "Pulse",
356
+ "Quasar",
357
+ "Void",
358
+ "Zenith",
359
+ "Aurora",
360
+ "Comet",
361
+ "Warp",
362
+ "Ion",
363
+ ];
364
+ const SPACE_NOUNS = [
365
+ "Star",
366
+ "Dust",
367
+ "Ray",
368
+ "Flare",
369
+ "Drift",
370
+ "Core",
371
+ "Ring",
372
+ "Gate",
373
+ "Spark",
374
+ "Beam",
375
+ "Wave",
376
+ "Shard",
377
+ "Forge",
378
+ "Bolt",
379
+ "Glow",
380
+ "Arc",
381
+ ];
382
+
383
+ const MINIMAL_NAMES = [
384
+ "Alpha",
385
+ "Beta",
386
+ "Gamma",
387
+ "Delta",
388
+ "Epsilon",
389
+ "Zeta",
390
+ "Eta",
391
+ "Theta",
392
+ "Iota",
393
+ "Kappa",
394
+ "Lambda",
395
+ "Mu",
396
+ "Nu",
397
+ "Xi",
398
+ "Omicron",
399
+ "Pi",
400
+ "Rho",
401
+ "Sigma",
402
+ "Tau",
403
+ "Upsilon",
404
+ "Phi",
405
+ "Chi",
406
+ "Psi",
407
+ "Omega",
408
+ ];
409
+
410
+ export interface NameThemeConfig {
411
+ theme: string;
412
+ customWords?: { adjectives: string[]; nouns: string[] };
413
+ }
414
+
415
+ // =============================================================================
416
+ // Pure Utilities
417
+ // =============================================================================
418
+
419
+ export function generateMemorableName(themeConfig?: NameThemeConfig): string {
420
+ const themeName = themeConfig?.theme ?? "default";
421
+
422
+ if (themeName === "minimal") {
423
+ return MINIMAL_NAMES[Math.floor(Math.random() * MINIMAL_NAMES.length)];
424
+ }
425
+
426
+ let adjectives: string[];
427
+ let nouns: string[];
428
+
429
+ switch (themeName) {
430
+ case "nature":
431
+ adjectives = NATURE_ADJECTIVES;
432
+ nouns = NATURE_NOUNS;
433
+ break;
434
+ case "space":
435
+ adjectives = SPACE_ADJECTIVES;
436
+ nouns = SPACE_NOUNS;
437
+ break;
438
+ case "custom":
439
+ adjectives = themeConfig?.customWords?.adjectives ?? DEFAULT_ADJECTIVES;
440
+ nouns = themeConfig?.customWords?.nouns ?? DEFAULT_NOUNS;
441
+ break;
442
+ default:
443
+ adjectives = DEFAULT_ADJECTIVES;
444
+ nouns = DEFAULT_NOUNS;
445
+ break;
446
+ }
447
+
448
+ const adj = adjectives[Math.floor(Math.random() * adjectives.length)];
449
+ const noun = nouns[Math.floor(Math.random() * nouns.length)];
450
+ return adj + noun;
451
+ }
452
+
453
+ export function isProcessAlive(pid: number): boolean {
454
+ try {
455
+ process.kill(pid, 0);
456
+ return true;
457
+ } catch {
458
+ return false;
459
+ }
460
+ }
461
+
462
+ export function isValidAgentName(name: string): boolean {
463
+ if (!name || name.length > 50) return false;
464
+ return /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/.test(name);
465
+ }
466
+
467
+ export function formatRelativeTime(timestamp: string): string {
468
+ const diff = Date.now() - new Date(timestamp).getTime();
469
+ const seconds = Math.floor(diff / 1000);
470
+ const minutes = Math.floor(seconds / 60);
471
+ const hours = Math.floor(minutes / 60);
472
+
473
+ if (hours > 0) return `${hours}h ago`;
474
+ if (minutes > 0) return `${minutes}m ago`;
475
+ return "just now";
476
+ }
477
+
478
+ export function pathMatchesReservation(filePath: string, pattern: string): boolean {
479
+ if (pattern.endsWith("/")) {
480
+ return filePath.startsWith(pattern) || filePath + "/" === pattern;
481
+ }
482
+ return filePath === pattern;
483
+ }
484
+
485
+ export function stripAnsiCodes(text: string): string {
486
+ // eslint-disable-next-line no-control-regex
487
+ return text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
488
+ }
489
+
490
+ const colorCache = new Map<string, string>();
491
+
492
+ export function agentColorCode(name: string): string {
493
+ const cached = colorCache.get(name);
494
+ if (cached) return cached;
495
+
496
+ let hash = 0;
497
+ for (const char of name) hash = (hash << 5) - hash + char.charCodeAt(0);
498
+ const color = AGENT_COLORS[Math.abs(hash) % AGENT_COLORS.length];
499
+ colorCache.set(name, color);
500
+ return color;
501
+ }
502
+
503
+ export function coloredAgentName(name: string): string {
504
+ return `\x1b[${agentColorCode(name)}m${name}\x1b[0m`;
505
+ }
506
+
507
+ export function extractFolder(cwd: string): string {
508
+ return basename(cwd) || cwd;
509
+ }
510
+
511
+ export function resolveSpecPath(specPath: string, cwd: string): string {
512
+ if (isAbsolute(specPath)) return specPath;
513
+ return resolve(cwd, specPath);
514
+ }
515
+
516
+ export function displaySpecPath(absPath: string, cwd: string): string {
517
+ try {
518
+ const rel = relative(cwd, absPath);
519
+ if (rel === "") return ".";
520
+ if (!rel.startsWith("..") && !isAbsolute(rel)) {
521
+ return "./" + rel;
522
+ }
523
+ } catch {
524
+ // Ignore and fall back to absolute
525
+ }
526
+ return absPath;
527
+ }
528
+
529
+ export function truncatePathLeft(filePath: string, maxLen: number): string {
530
+ if (filePath.length <= maxLen) return filePath;
531
+ if (maxLen <= 1) return "…";
532
+ const truncated = filePath.slice(-(maxLen - 1));
533
+ const slashIdx = truncated.indexOf("/");
534
+ if (slashIdx > 0) {
535
+ return "…" + truncated.slice(slashIdx);
536
+ }
537
+ return "…" + truncated;
538
+ }
539
+
540
+ export function buildSelfRegistration(state: MessengerState): AgentRegistration {
541
+ return {
542
+ name: state.agentName,
543
+ pid: process.pid,
544
+ sessionId: "",
545
+ model: state.model,
546
+ cwd: state.cwd,
547
+ startedAt: state.sessionStartedAt,
548
+ gitBranch: state.gitBranch,
549
+ spec: state.spec,
550
+ isHuman: state.isHuman,
551
+ session: { ...state.session },
552
+ activity: { ...state.activity },
553
+ reservations: state.reservations.length > 0 ? state.reservations : undefined,
554
+ statusMessage: state.statusMessage,
555
+ };
556
+ }
557
+
558
+ export function agentHasTask(
559
+ name: string,
560
+ allClaims: AllClaims,
561
+ crewTasks: Array<{ assigned_to?: string; status: string }>,
562
+ ): boolean {
563
+ for (const tasks of Object.values(allClaims)) {
564
+ for (const claim of Object.values(tasks)) {
565
+ if (claim.agent === name) return true;
566
+ }
567
+ }
568
+ return crewTasks.some(t => t.assigned_to === name && t.status === "in_progress");
569
+ }
570
+
571
+ export type DisplayMode = "same-folder-branch" | "same-folder" | "different";
572
+
573
+ export function getDisplayMode(agents: AgentRegistration[]): DisplayMode {
574
+ if (agents.length === 0) return "different";
575
+
576
+ const folders = agents.map(a => extractFolder(a.cwd));
577
+ const uniqueFolders = new Set(folders);
578
+
579
+ if (uniqueFolders.size > 1) return "different";
580
+
581
+ const branches = agents.map(a => a.gitBranch).filter(Boolean);
582
+ const uniqueBranches = new Set(branches);
583
+
584
+ if (uniqueBranches.size <= 1) return "same-folder-branch";
585
+
586
+ return "same-folder";
587
+ }