@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
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Crew - Worker Coordination
3
+ *
4
+ * Builds dependency sections, coordination context (concurrent tasks,
5
+ * recent activity, ready tasks), and coordination instructions for
6
+ * worker prompts. All functions use static data available at prompt-build
7
+ * time — no runtime worker state.
8
+ */
9
+
10
+ import type { Task } from "../types.ts";
11
+ import type { CrewConfig } from "../utils/config.ts";
12
+ import { readFeedEvents, type FeedEvent } from "../../feed.ts";
13
+ import * as store from "../store.ts";
14
+ import * as teamStore from "../team/store.ts";
15
+
16
+ interface CoordinationPromptOptions {
17
+ readOnly?: boolean;
18
+ }
19
+
20
+ // =============================================================================
21
+ // Dependency Section
22
+ // =============================================================================
23
+
24
+ export function buildDependencySection(cwd: string, task: Task, config: CrewConfig, options: CoordinationPromptOptions = {}): string {
25
+ if (config.dependencies === "advisory") {
26
+ const lines: string[] = [
27
+ "## Dependency Status\n",
28
+ "Your task has dependencies on other tasks. Some may not be complete yet — this is expected. Use the coordination system to work through it.",
29
+ "",
30
+ ];
31
+
32
+ for (const depId of task.depends_on) {
33
+ const dep = store.getTask(cwd, depId);
34
+ if (!dep) {
35
+ lines.push(`- ○ ${depId} — not yet started`);
36
+ continue;
37
+ }
38
+
39
+ if (dep.status === "done") {
40
+ const summary = dep.summary ? ` ${dep.summary}` : "";
41
+ lines.push(`- ✓ ${dep.id} (${dep.title}) — done${summary ? `.${summary}` : ""}`);
42
+ } else if (dep.status === "in_progress") {
43
+ const worker = dep.assigned_to ? `, worker: ${dep.assigned_to}` : "";
44
+ lines.push(`- ⟳ ${dep.id} (${dep.title}) — in progress${worker}`);
45
+ } else {
46
+ lines.push(`- ○ ${dep.id} (${dep.title}) — not yet started`);
47
+ }
48
+ }
49
+
50
+ lines.push(
51
+ "",
52
+ "**Working with pending dependencies:**",
53
+ "- Check if the dependency's output files exist. If yes, import and use them.",
54
+ "- If not, define what you need locally based on your task spec. Your spec describes the interfaces.",
55
+ );
56
+ if (config.coordination !== "none") {
57
+ lines.push("- DM in-progress workers for API details they're building.");
58
+ }
59
+ if (!options.readOnly) lines.push("- Reserve your files before editing to prevent conflicts.");
60
+ lines.push(
61
+ "- Do NOT block yourself because a dependency isn't done. Work around it.",
62
+ options.readOnly
63
+ ? "- Log findings, assumptions, and handoff notes in your progress for later reconciliation."
64
+ : "- Log any local definitions in your progress for later reconciliation.",
65
+ );
66
+
67
+ return lines.join("\n") + "\n\n";
68
+ }
69
+
70
+ const level = config.coordination;
71
+ const lines: string[] = ["## Dependencies\n", "Your task depends on these completed tasks:"];
72
+
73
+ for (const depId of task.depends_on) {
74
+ const dep = store.getTask(cwd, depId);
75
+ if (!dep) {
76
+ lines.push(`- ${depId}`);
77
+ continue;
78
+ }
79
+
80
+ if (level === "minimal") {
81
+ lines.push(`- ${depId}: ${dep.title}`);
82
+ } else {
83
+ const summary = dep.summary || "(no summary)";
84
+ lines.push(`- ${depId} (${dep.title}): ${summary}`);
85
+ }
86
+ }
87
+
88
+ return lines.join("\n") + "\n\n";
89
+ }
90
+
91
+ // =============================================================================
92
+ // Coordination Context (concurrent tasks, recent activity, ready tasks)
93
+ // =============================================================================
94
+
95
+ const ACTIVITY_EVENT_TYPES = new Set<string>([
96
+ "task.start", "task.done", "task.block", "task.reset",
97
+ "reserve", "release", "message",
98
+ ]);
99
+
100
+ function formatFeedTime(isoTs: string): string {
101
+ const d = new Date(isoTs);
102
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
103
+ }
104
+
105
+ function formatFeedVerb(type: string): string {
106
+ switch (type) {
107
+ case "task.start": return "started";
108
+ case "task.done": return "completed";
109
+ case "task.block": return "blocked";
110
+ case "task.reset": return "reset";
111
+ case "reserve": return "reserved";
112
+ case "release": return "released";
113
+ default: return type;
114
+ }
115
+ }
116
+
117
+ function formatActivityLine(event: FeedEvent): string {
118
+ const time = formatFeedTime(event.ts);
119
+ if (event.type === "message") {
120
+ if (event.target) {
121
+ return event.preview
122
+ ? `${time} ${event.agent} → ${event.target}: ${event.preview}`
123
+ : `${time} ${event.agent} → ${event.target}`;
124
+ }
125
+ return event.preview
126
+ ? `${time} ${event.agent} ✦ ${event.preview}`
127
+ : `${time} ${event.agent} ✦`;
128
+ }
129
+ const verb = formatFeedVerb(event.type);
130
+ const target = event.target ? ` ${event.target}` : "";
131
+ const preview = event.preview ? ` — ${event.preview}` : "";
132
+ return `${time} ${event.agent} ${verb}${target}${preview}`;
133
+ }
134
+
135
+ export function buildCoordinationContext(
136
+ cwd: string,
137
+ task: Task,
138
+ config: CrewConfig,
139
+ concurrentTasks: Task[],
140
+ options: CoordinationPromptOptions = {},
141
+ ): string {
142
+ if (config.coordination === "none") return "";
143
+
144
+ const level = config.coordination;
145
+ let out = "";
146
+
147
+ if (concurrentTasks.length > 0) {
148
+ out += `## Concurrent Tasks
149
+
150
+ These tasks are being worked on by other workers in this wave. Discover their agent names after joining the mesh via \`pi_messenger({ action: "list" })\`.
151
+
152
+ `;
153
+ for (const t of concurrentTasks) {
154
+ out += `- ${t.id}: ${t.title}\n`;
155
+ }
156
+ out += "\n";
157
+ }
158
+
159
+ if (level === "moderate" || level === "chatty") {
160
+ const events = readFeedEvents(cwd, 20);
161
+ const signal = events.filter(e => ACTIVITY_EVENT_TYPES.has(e.type)).slice(-8);
162
+ if (signal.length > 0) {
163
+ out += "## Recent Activity\n\n";
164
+ for (const e of signal) {
165
+ out += formatActivityLine(e) + "\n";
166
+ }
167
+ out += "\n";
168
+ }
169
+ }
170
+
171
+ if (level === "chatty") {
172
+ const concurrentIds = new Set(concurrentTasks.map(t => t.id));
173
+ const ready = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" })
174
+ .filter(t => t.id !== task.id && !concurrentIds.has(t.id));
175
+ const claimable = ready.filter(t => !teamStore.taskNeedsApproval(t));
176
+ const needsApproval = ready.filter(teamStore.taskPendingApproval);
177
+ const rejected = ready.filter(teamStore.taskNeedsRevision);
178
+ if (claimable.length > 0) {
179
+ out += `## Ready Tasks
180
+
181
+ ${options.readOnly ? "After completing your current task, only claim one of these if it fits your read-only assignment:" : "After completing your current task, you can claim one of these:"}
182
+ `;
183
+ for (const t of claimable) {
184
+ const deps = t.depends_on.length > 0 ? ` (deps: ${t.depends_on.join(", ")})` : "";
185
+ out += `- ${t.id}: ${t.title}${deps}\n`;
186
+ }
187
+ out += "\n";
188
+ }
189
+ if (needsApproval.length > 0) {
190
+ out += `## Ready Tasks Needing Approval
191
+
192
+ These tasks are ready but require lead approval before anyone can claim them:
193
+ `;
194
+ for (const t of needsApproval) out += `- ${t.id}: ${t.title} — approve with \`pi_messenger({ action: "task.approve", id: "${t.id}" })\`\n`;
195
+ out += "\n";
196
+ }
197
+ if (rejected.length > 0) {
198
+ out += `## Rejected Tasks Needing Revision
199
+
200
+ These tasks need revision before they can be approved or claimed:
201
+ `;
202
+ for (const t of rejected) out += `- ${t.id}: ${t.title}${t.approval?.feedback ? ` — ${t.approval.feedback}` : ""} — revise with \`pi_messenger({ action: "task.revise", id: "${t.id}", prompt: "Address approval feedback" })\`\n`;
203
+ out += "\n";
204
+ }
205
+ }
206
+
207
+ return out;
208
+ }
209
+
210
+ // =============================================================================
211
+ // Coordination Instructions
212
+ // =============================================================================
213
+
214
+ export function buildCoordinationInstructions(config: CrewConfig, options: CoordinationPromptOptions = {}): string {
215
+ const level = config.coordination;
216
+ if (level === "none") return "";
217
+
218
+ const budget = config.messageBudgets?.[level] ?? (level === "chatty" ? 10 : 5);
219
+
220
+ if (level === "minimal") {
221
+ if (options.readOnly) {
222
+ return `## Coordination
223
+
224
+ **Message budget: ${budget} messages this session.** The system enforces this.
225
+
226
+ Use \`pi_messenger({ action: "list" })\` to see active workers if your investigation overlaps with their work. Message a worker only when you need concrete context or a handoff detail.
227
+
228
+ `;
229
+ }
230
+
231
+ return `## Coordination
232
+
233
+ **Message budget: ${budget} messages this session.** The system enforces this.
234
+
235
+ Before editing files, check if another worker has reserved them by running:
236
+
237
+ \`\`\`typescript
238
+ pi_messenger({ action: "list" })
239
+ \`\`\`
240
+
241
+ If a file you need is reserved by another worker, message them to coordinate:
242
+
243
+ \`\`\`typescript
244
+ pi_messenger({ action: "send", to: "<their-name>", message: "I need to modify <file> for my task, can we coordinate?" })
245
+ \`\`\`
246
+
247
+ Do NOT edit files reserved by another worker without coordinating first.
248
+
249
+ `;
250
+ }
251
+
252
+ let out = `## Coordination
253
+
254
+ **Message budget: ${budget} messages this session.** The system enforces this — sends are rejected after the limit.
255
+
256
+ **Broadcasts go to the team feed — only the user sees them live.** Other workers see your broadcasts in their initial context only. Use DMs for time-sensitive peer coordination.
257
+
258
+ `;
259
+
260
+ out += options.readOnly
261
+ ? `### Announce yourself
262
+ After joining the mesh and starting your task, announce what you are investigating:
263
+
264
+ \`\`\`typescript
265
+ pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — investigating <scope>" })
266
+ \`\`\`
267
+
268
+ `
269
+ : `### Announce yourself
270
+ After joining the mesh and starting your task, announce what you're working on:
271
+
272
+ \`\`\`typescript
273
+ pi_messenger({ action: "broadcast", message: "Starting <task-id> (<title>) — will create <files>" })
274
+ \`\`\`
275
+
276
+ `;
277
+
278
+ if (level === "chatty") {
279
+ out += `### Coordinate with peers
280
+ If a concurrent task involves files or interfaces related to yours, send a brief DM. Only message when there's a concrete coordination need — shared files, interfaces, or blocking questions.
281
+
282
+ \`\`\`typescript
283
+ pi_messenger({ action: "send", to: "<peer-name>", message: "I'm exporting FormatOptions from types.ts — will you need it?" })
284
+ \`\`\`
285
+
286
+ ### Responding to messages
287
+ If a peer asks you a direct question, reply briefly. Ignore messages that don't require a response. Do NOT start casual conversations.
288
+
289
+ `;
290
+ }
291
+
292
+ out += options.readOnly
293
+ ? `### On completion
294
+ Announce what you found or recommend:
295
+
296
+ \`\`\`typescript
297
+ pi_messenger({ action: "broadcast", message: "Completed <task-id>: found <summary>" })
298
+ \`\`\`
299
+
300
+ `
301
+ : `### On completion
302
+ Announce what you built:
303
+
304
+ \`\`\`typescript
305
+ pi_messenger({ action: "broadcast", message: "Completed <task-id>: <file> exports <symbols>" })
306
+ \`\`\`
307
+
308
+ ### Reservations
309
+ Before editing files, check if another worker has reserved them via \`pi_messenger({ action: "list" })\`. If a file you need is reserved, message the owner to coordinate. Do NOT edit reserved files without coordinating first.
310
+
311
+ `;
312
+
313
+ out += `### Questions about dependencies
314
+ If your task depends on a completed task and something about its implementation is unclear, read the code and the task's progress log at \`.pi/messenger/crew/tasks/<task-id>.progress.md\`. Dependency authors are from previous waves and are no longer in the mesh.
315
+
316
+ `;
317
+
318
+ if (level === "chatty") {
319
+ out += `### Claim next task
320
+ After completing your assigned task, check if there are ready tasks you can pick up:
321
+
322
+ \`\`\`typescript
323
+ pi_messenger({ action: "task.ready" })
324
+ \`\`\`
325
+
326
+ If a task is ready, claim it only if it matches your assignment mode. If \`task.start\` fails (another worker claimed it first or the task needs approval), check for other ready tasks. Only claim if your current task completed cleanly and quickly.
327
+
328
+ `;
329
+ }
330
+
331
+ return out;
332
+ }