@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.
- package/CHANGELOG.md +676 -0
- package/README.md +424 -0
- package/config-overlay.ts +171 -0
- package/config.ts +209 -0
- package/crew/agents/crew-plan-sync.md +64 -0
- package/crew/agents/crew-planner.md +172 -0
- package/crew/agents/crew-reviewer.md +58 -0
- package/crew/agents/crew-worker.md +129 -0
- package/crew/agents.ts +434 -0
- package/crew/handlers/coordination.ts +332 -0
- package/crew/handlers/plan.ts +906 -0
- package/crew/handlers/review.ts +333 -0
- package/crew/handlers/revise.ts +376 -0
- package/crew/handlers/status.ts +295 -0
- package/crew/handlers/sync.ts +233 -0
- package/crew/handlers/task.ts +792 -0
- package/crew/handlers/team.ts +235 -0
- package/crew/handlers/work.ts +425 -0
- package/crew/id-allocator.ts +30 -0
- package/crew/index.ts +257 -0
- package/crew/live-progress.ts +58 -0
- package/crew/lobby.ts +473 -0
- package/crew/prompt.ts +252 -0
- package/crew/registry.ts +114 -0
- package/crew/spawn.ts +111 -0
- package/crew/state-autonomous.ts +164 -0
- package/crew/state-planning.ts +263 -0
- package/crew/state.ts +20 -0
- package/crew/store.ts +642 -0
- package/crew/task-actions.ts +131 -0
- package/crew/team/store.ts +479 -0
- package/crew/team/subagent-roles.ts +87 -0
- package/crew/team/types.ts +50 -0
- package/crew/types.ts +194 -0
- package/crew/utils/artifacts.ts +62 -0
- package/crew/utils/config.ts +156 -0
- package/crew/utils/discover.ts +219 -0
- package/crew/utils/install.ts +85 -0
- package/crew/utils/progress.ts +187 -0
- package/crew/utils/result.ts +16 -0
- package/crew/utils/risk-labels.ts +7 -0
- package/crew/utils/task-format.ts +14 -0
- package/crew/utils/team-roles.ts +28 -0
- package/crew/utils/truncate.ts +79 -0
- package/crew/utils/verdict.ts +55 -0
- package/feed.ts +268 -0
- package/handlers.ts +1107 -0
- package/index.ts +1206 -0
- package/install.mjs +189 -0
- package/lib.ts +467 -0
- package/overlay-actions.ts +511 -0
- package/overlay-coordinator.ts +150 -0
- package/overlay-render.ts +676 -0
- package/overlay.ts +830 -0
- package/package.json +62 -0
- package/skills/pi-messenger-crew/SKILL.md +347 -0
- package/store.ts +1139 -0
- package/vitest.config.ts +10 -0
package/crew/prompt.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Worker Prompt Builder
|
|
3
|
+
*
|
|
4
|
+
* Assembles the full prompt sent to a worker when it's assigned a task.
|
|
5
|
+
* Pure function: reads from store, returns a string.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Task } from "./types.ts";
|
|
9
|
+
import type { CrewConfig } from "./utils/config.ts";
|
|
10
|
+
import type { CrewSkillInfo } from "./utils/discover.ts";
|
|
11
|
+
import { TEAM_MEMORY_TYPES, type TeamMemoryType, type TeamPromptContext } from "./team/types.ts";
|
|
12
|
+
import { isNonEditingTeamRole } from "./utils/team-roles.ts";
|
|
13
|
+
import * as store from "./store.ts";
|
|
14
|
+
import { buildDependencySection, buildCoordinationContext, buildCoordinationInstructions } from "./handlers/coordination.ts";
|
|
15
|
+
|
|
16
|
+
export function buildWorkerPrompt(
|
|
17
|
+
task: Task,
|
|
18
|
+
prdPath: string,
|
|
19
|
+
cwd: string,
|
|
20
|
+
config: CrewConfig,
|
|
21
|
+
concurrentTasks: Task[],
|
|
22
|
+
skills?: CrewSkillInfo[],
|
|
23
|
+
teamContext?: TeamPromptContext,
|
|
24
|
+
): string {
|
|
25
|
+
const taskSpec = store.getTaskSpec(cwd, task.id);
|
|
26
|
+
const planSpec = store.getPlanSpec(cwd);
|
|
27
|
+
const isNonEditingRole = isNonEditingTeamRole(teamContext?.role?.name ?? task.role);
|
|
28
|
+
const mission = isNonEditingRole
|
|
29
|
+
? `Inspect this task as a read-only Team role. This overrides generic implementation protocol for this assignment:
|
|
30
|
+
1. Join the mesh
|
|
31
|
+
2. Read task spec to understand requirements
|
|
32
|
+
3. Start the task so Crew can track ownership
|
|
33
|
+
4. Inspect code, docs, and context without editing files
|
|
34
|
+
5. Record findings, plans, decisions, risks, or handoff notes in progress or Team memory
|
|
35
|
+
6. Mark complete with a concise summary of what you found or recommend`
|
|
36
|
+
: `Implement this task following the crew-worker protocol:
|
|
37
|
+
1. Join the mesh
|
|
38
|
+
2. Read task spec to understand requirements
|
|
39
|
+
3. Start task and reserve files
|
|
40
|
+
4. Implement the feature
|
|
41
|
+
5. Commit your changes
|
|
42
|
+
6. Release reservations and mark complete`;
|
|
43
|
+
|
|
44
|
+
let prompt = `# Task Assignment
|
|
45
|
+
|
|
46
|
+
**Task ID:** ${task.id}
|
|
47
|
+
**Task Title:** ${task.title}
|
|
48
|
+
**PRD:** ${prdPath}
|
|
49
|
+
${task.attempt_count >= 1 ? `**Attempt:** ${task.attempt_count + 1} (retry after previous attempt)` : ""}
|
|
50
|
+
|
|
51
|
+
## Your Mission
|
|
52
|
+
|
|
53
|
+
${mission}
|
|
54
|
+
|
|
55
|
+
`;
|
|
56
|
+
|
|
57
|
+
const teamSection = buildTeamSection(task, teamContext);
|
|
58
|
+
if (teamSection) {
|
|
59
|
+
prompt += teamSection;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (task.last_review) {
|
|
63
|
+
prompt += `## ⚠️ Previous Review Feedback
|
|
64
|
+
|
|
65
|
+
**Verdict:** ${task.last_review.verdict}
|
|
66
|
+
|
|
67
|
+
${task.last_review.summary}
|
|
68
|
+
|
|
69
|
+
${task.last_review.issues.length > 0 ? `**Issues to fix:**\n${task.last_review.issues.map(i => `- ${i}`).join("\n")}\n` : ""}
|
|
70
|
+
${task.last_review.suggestions.length > 0 ? `**Suggestions:**\n${task.last_review.suggestions.map(s => `- ${s}`).join("\n")}\n` : ""}
|
|
71
|
+
|
|
72
|
+
**You MUST address the issues above in this attempt.**
|
|
73
|
+
|
|
74
|
+
`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const progress = store.getTaskProgress(cwd, task.id);
|
|
78
|
+
if (progress) {
|
|
79
|
+
const lines = progress.trimEnd().split("\n");
|
|
80
|
+
const capped = lines.length > 30 ? lines.slice(-30) : lines;
|
|
81
|
+
const truncated = capped.join("\n");
|
|
82
|
+
const omitted = lines.length > 30 ? `(${lines.length - 30} earlier entries omitted)\n` : "";
|
|
83
|
+
prompt += `## Progress from Prior Attempts
|
|
84
|
+
|
|
85
|
+
${omitted}${truncated}
|
|
86
|
+
|
|
87
|
+
`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (task.depends_on.length > 0) {
|
|
91
|
+
if (config.dependencies === "advisory" || config.coordination !== "none") {
|
|
92
|
+
prompt += buildDependencySection(cwd, task, config, { readOnly: isNonEditingRole });
|
|
93
|
+
} else {
|
|
94
|
+
prompt += `## Dependencies
|
|
95
|
+
|
|
96
|
+
This task depends on: ${task.depends_on.join(", ")}
|
|
97
|
+
These tasks are already complete - you can reference their implementations.
|
|
98
|
+
|
|
99
|
+
`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const coordContext = buildCoordinationContext(cwd, task, config, concurrentTasks, { readOnly: isNonEditingRole });
|
|
104
|
+
if (coordContext) {
|
|
105
|
+
prompt += coordContext;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (taskSpec && !taskSpec.includes("*Spec pending*")) {
|
|
109
|
+
prompt += `## Task Specification
|
|
110
|
+
|
|
111
|
+
${taskSpec}
|
|
112
|
+
|
|
113
|
+
`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (planSpec && !planSpec.includes("*Spec pending*")) {
|
|
117
|
+
const truncatedSpec = planSpec.length > 2000
|
|
118
|
+
? planSpec.slice(0, 2000) + `\n\n[Spec truncated - read full spec from .pi/messenger/crew/plan.md]`
|
|
119
|
+
: planSpec;
|
|
120
|
+
prompt += `## Plan Context
|
|
121
|
+
|
|
122
|
+
${truncatedSpec}
|
|
123
|
+
`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const coordInstructions = buildCoordinationInstructions(config, { readOnly: isNonEditingRole });
|
|
127
|
+
if (coordInstructions) {
|
|
128
|
+
prompt += coordInstructions;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const skillsSection = buildSkillsSection(skills, task.skills, isNonEditingRole);
|
|
132
|
+
if (skillsSection) {
|
|
133
|
+
prompt += skillsSection;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return prompt;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const WORKER_HIDDEN_SKILLS = new Set(["pi-messenger-crew"]);
|
|
140
|
+
|
|
141
|
+
function buildTeamSection(task: Task, teamContext: TeamPromptContext | undefined): string | null {
|
|
142
|
+
if (!teamContext) return null;
|
|
143
|
+
|
|
144
|
+
let section = `## Team Context\n\n`;
|
|
145
|
+
if (teamContext.team) {
|
|
146
|
+
const profileText = teamContext.profile?.name && teamContext.profile.name !== teamContext.team.name
|
|
147
|
+
? ` (profile: ${teamContext.profile.name})`
|
|
148
|
+
: "";
|
|
149
|
+
section += `Active team: ${teamContext.team.name}${profileText}\n\n`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (task.role || teamContext.role) {
|
|
153
|
+
section += `### Team Role\nYou are acting as the \`${task.role ?? teamContext.role?.name}\` role for this task.\n`;
|
|
154
|
+
if (teamContext.role?.description) section += `Role description: ${teamContext.role.description}\n`;
|
|
155
|
+
if (teamContext.role?.thinking) section += `Thinking default: ${teamContext.role.thinking}\n`;
|
|
156
|
+
if (teamContext.role?.skills && teamContext.role.skills.length > 0) section += `Role skills: ${teamContext.role.skills.join(", ")}\n`;
|
|
157
|
+
if (teamContext.role && isNonEditingTeamRole(teamContext.role.name)) {
|
|
158
|
+
section += "This is a non-editing Team role. Do not edit files; report findings, plans, decisions, or handoff notes instead.\n";
|
|
159
|
+
}
|
|
160
|
+
if (teamContext.role?.prompt) {
|
|
161
|
+
const prompt = teamContext.role.prompt.length > 2000
|
|
162
|
+
? teamContext.role.prompt.slice(0, 2000) + "\n[Role prompt truncated]"
|
|
163
|
+
: teamContext.role.prompt;
|
|
164
|
+
section += `\nRole working rules:\n${prompt}\n`;
|
|
165
|
+
}
|
|
166
|
+
section += "\n";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (teamContext.charter) {
|
|
170
|
+
const charter = teamContext.charter.length > 2500
|
|
171
|
+
? teamContext.charter.slice(0, 2500) + "\n[Team charter truncated]"
|
|
172
|
+
: teamContext.charter;
|
|
173
|
+
section += `### Team Charter\n${charter}\n\n`;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const memoryText = formatMemory(teamContext.memory);
|
|
177
|
+
if (memoryText) section += memoryText;
|
|
178
|
+
|
|
179
|
+
if (task.risk_labels && task.risk_labels.length > 0) {
|
|
180
|
+
section += `### Risk Labels\n${task.risk_labels.join(", ")}\n\n`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if (task.approval?.required) {
|
|
184
|
+
section += `### Approval Policy\nLead approval required. Current status: ${task.approval.status}.\n`;
|
|
185
|
+
if (task.approval.plan) section += `Approval plan: ${task.approval.plan}\n`;
|
|
186
|
+
if (task.approval.feedback) section += `Approval feedback: ${task.approval.feedback}\n`;
|
|
187
|
+
section += "\n";
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return section;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function formatMemory(memory: TeamPromptContext["memory"]): string {
|
|
194
|
+
const labels: Record<TeamMemoryType, string> = {
|
|
195
|
+
decision: "Recent decisions",
|
|
196
|
+
interface: "Interfaces",
|
|
197
|
+
risk: "Risks",
|
|
198
|
+
handoff: "Handoffs",
|
|
199
|
+
};
|
|
200
|
+
let text = "";
|
|
201
|
+
for (const type of TEAM_MEMORY_TYPES) {
|
|
202
|
+
const entries = memory[type];
|
|
203
|
+
if (!entries || entries.length === 0) continue;
|
|
204
|
+
text += `### ${labels[type]}\n`;
|
|
205
|
+
for (const entry of entries.slice(-8)) {
|
|
206
|
+
text += `- ${entry.message}${entry.taskId ? ` (${entry.taskId})` : ""}\n`;
|
|
207
|
+
}
|
|
208
|
+
text += "\n";
|
|
209
|
+
}
|
|
210
|
+
return text ? `### Team Memory\n${text}` : "";
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function buildSkillsSection(
|
|
214
|
+
skills: CrewSkillInfo[] | undefined,
|
|
215
|
+
taskSkills: string[] | undefined,
|
|
216
|
+
readOnly: boolean,
|
|
217
|
+
): string | null {
|
|
218
|
+
if (!skills || skills.length === 0) return null;
|
|
219
|
+
|
|
220
|
+
const visibleSkills = skills.filter(skill => !WORKER_HIDDEN_SKILLS.has(skill.name));
|
|
221
|
+
if (visibleSkills.length === 0) return null;
|
|
222
|
+
|
|
223
|
+
const recommended = new Set(taskSkills ?? []);
|
|
224
|
+
const recSkills = visibleSkills.filter(s => recommended.has(s.name));
|
|
225
|
+
const otherSkills = visibleSkills.filter(s => !recommended.has(s.name));
|
|
226
|
+
|
|
227
|
+
let section = `## Available Skills
|
|
228
|
+
|
|
229
|
+
${readOnly ? "Read any skill that matches what you're investigating." : "Read any skill that matches what you're implementing."}
|
|
230
|
+
|
|
231
|
+
`;
|
|
232
|
+
|
|
233
|
+
if (recSkills.length > 0) {
|
|
234
|
+
section += "**Recommended for this task:**\n";
|
|
235
|
+
for (const s of recSkills) {
|
|
236
|
+
section += ` ${s.name} — ${s.description}\n ${s.path}\n`;
|
|
237
|
+
}
|
|
238
|
+
section += "\n";
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (otherSkills.length > 0) {
|
|
242
|
+
if (recSkills.length > 0) section += "**Also available:**\n";
|
|
243
|
+
for (const s of otherSkills) {
|
|
244
|
+
section += ` ${s.name} — ${s.description}\n ${s.path}\n`;
|
|
245
|
+
}
|
|
246
|
+
section += "\n";
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
section += `To load a skill: read({ path: "<skill-path>" })\n`;
|
|
250
|
+
|
|
251
|
+
return section;
|
|
252
|
+
}
|
package/crew/registry.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Unified Worker Registry
|
|
3
|
+
*
|
|
4
|
+
* Single registry for both regular workers and lobby workers.
|
|
5
|
+
* Replaces the separate maps in agents.ts and lobby.ts.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ChildProcess } from "node:child_process";
|
|
9
|
+
import type { CoordinationLevel } from "./utils/config.ts";
|
|
10
|
+
|
|
11
|
+
interface BaseWorkerEntry {
|
|
12
|
+
proc: ChildProcess;
|
|
13
|
+
name: string;
|
|
14
|
+
cwd: string;
|
|
15
|
+
taskId: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RegularWorker extends BaseWorkerEntry {
|
|
19
|
+
type: "worker";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LobbyWorkerEntry extends BaseWorkerEntry {
|
|
23
|
+
type: "lobby";
|
|
24
|
+
lobbyId: string;
|
|
25
|
+
assignedTaskId: string | null;
|
|
26
|
+
coordination: CoordinationLevel;
|
|
27
|
+
startedAt: number;
|
|
28
|
+
promptTmpDir: string | null;
|
|
29
|
+
aliveFile: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type WorkerEntry = RegularWorker | LobbyWorkerEntry;
|
|
33
|
+
|
|
34
|
+
const workers = new Map<string, WorkerEntry>();
|
|
35
|
+
|
|
36
|
+
function makeKey(cwd: string, taskId: string): string {
|
|
37
|
+
return `${cwd}::${taskId}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function registerWorker(entry: WorkerEntry): void {
|
|
41
|
+
workers.set(makeKey(entry.cwd, entry.taskId), entry);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function unregisterWorker(cwd: string, taskId: string): void {
|
|
45
|
+
workers.delete(makeKey(cwd, taskId));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function findWorkerByTask(cwd: string, taskId: string): WorkerEntry | null {
|
|
49
|
+
const direct = workers.get(makeKey(cwd, taskId));
|
|
50
|
+
if (direct) return direct;
|
|
51
|
+
for (const entry of workers.values()) {
|
|
52
|
+
if (entry.cwd !== cwd) continue;
|
|
53
|
+
if (entry.type === "lobby" && entry.assignedTaskId === taskId) return entry;
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function hasActiveWorker(cwd: string, taskId: string): boolean {
|
|
59
|
+
const entry = findWorkerByTask(cwd, taskId);
|
|
60
|
+
if (!entry) return false;
|
|
61
|
+
return entry.proc.exitCode === null && !entry.proc.killed;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function killWorkerByTask(cwd: string, taskId: string): boolean {
|
|
65
|
+
const entry = findWorkerByTask(cwd, taskId);
|
|
66
|
+
if (!entry) return false;
|
|
67
|
+
if (entry.proc.exitCode === null && !entry.proc.killed) {
|
|
68
|
+
entry.proc.kill("SIGTERM");
|
|
69
|
+
const ref = entry.proc;
|
|
70
|
+
const timer = setTimeout(() => {
|
|
71
|
+
if (ref.exitCode === null) ref.kill("SIGKILL");
|
|
72
|
+
}, 5000);
|
|
73
|
+
timer.unref();
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function killAll(cwd?: string): void {
|
|
80
|
+
for (const [key, entry] of workers.entries()) {
|
|
81
|
+
if (cwd && entry.cwd !== cwd) continue;
|
|
82
|
+
if (entry.proc.exitCode === null && !entry.proc.killed) {
|
|
83
|
+
entry.proc.kill("SIGTERM");
|
|
84
|
+
}
|
|
85
|
+
workers.delete(key);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function getLobbyWorkers(cwd: string): LobbyWorkerEntry[] {
|
|
90
|
+
const result: LobbyWorkerEntry[] = [];
|
|
91
|
+
for (const entry of workers.values()) {
|
|
92
|
+
if (entry.cwd === cwd && entry.type === "lobby") result.push(entry);
|
|
93
|
+
}
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function getAvailableLobbyWorkers(cwd: string): LobbyWorkerEntry[] {
|
|
98
|
+
const result: LobbyWorkerEntry[] = [];
|
|
99
|
+
for (const entry of workers.values()) {
|
|
100
|
+
if (entry.cwd !== cwd || entry.type !== "lobby") continue;
|
|
101
|
+
if (entry.assignedTaskId) continue;
|
|
102
|
+
if (entry.proc.exitCode !== null) continue;
|
|
103
|
+
result.push(entry);
|
|
104
|
+
}
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function getLobbyWorkerCount(cwd: string): number {
|
|
109
|
+
let count = 0;
|
|
110
|
+
for (const entry of workers.values()) {
|
|
111
|
+
if (entry.cwd === cwd && entry.type === "lobby" && !entry.assignedTaskId && entry.proc.exitCode === null) count++;
|
|
112
|
+
}
|
|
113
|
+
return count;
|
|
114
|
+
}
|
package/crew/spawn.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Worker Spawning Helpers
|
|
3
|
+
*
|
|
4
|
+
* Shared logic for spawning workers and assigning tasks,
|
|
5
|
+
* used by both the overlay and the work handler.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import * as store from "./store.ts";
|
|
10
|
+
import { loadCrewConfig } from "./utils/config.ts";
|
|
11
|
+
import { discoverCrewSkills } from "./utils/discover.ts";
|
|
12
|
+
import { buildWorkerPrompt } from "./prompt.ts";
|
|
13
|
+
import * as teamStore from "./team/store.ts";
|
|
14
|
+
import { logFeedEvent } from "../feed.ts";
|
|
15
|
+
import {
|
|
16
|
+
spawnWorkerForTask,
|
|
17
|
+
getAvailableLobbyWorkers,
|
|
18
|
+
assignTaskToLobbyWorker,
|
|
19
|
+
} from "./lobby.ts";
|
|
20
|
+
|
|
21
|
+
export interface SpawnResult {
|
|
22
|
+
assigned: number;
|
|
23
|
+
firstWorkerName: string | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function spawnWorkersForReadyTasks(
|
|
27
|
+
cwd: string,
|
|
28
|
+
maxWorkers: number,
|
|
29
|
+
sessionModel?: string,
|
|
30
|
+
): SpawnResult {
|
|
31
|
+
const plan = store.getPlan(cwd);
|
|
32
|
+
if (!plan) return { assigned: 0, firstWorkerName: null };
|
|
33
|
+
|
|
34
|
+
const crewDir = store.getCrewDir(cwd);
|
|
35
|
+
const config = loadCrewConfig(crewDir);
|
|
36
|
+
const workerCap = Math.min(maxWorkers, config.concurrency.max);
|
|
37
|
+
const prdLabel = store.getPlanLabel(plan);
|
|
38
|
+
const inboxDir = join(cwd, ".pi", "messenger", "inbox");
|
|
39
|
+
const skills = discoverCrewSkills(cwd);
|
|
40
|
+
|
|
41
|
+
let assigned = 0;
|
|
42
|
+
let firstWorkerName: string | null = null;
|
|
43
|
+
|
|
44
|
+
const lobby = getAvailableLobbyWorkers(cwd);
|
|
45
|
+
for (const lw of lobby) {
|
|
46
|
+
if (assigned >= workerCap) break;
|
|
47
|
+
const fresh = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" }).filter(t => !teamStore.taskNeedsApproval(t));
|
|
48
|
+
if (fresh.length === 0) break;
|
|
49
|
+
|
|
50
|
+
const task = fresh[0];
|
|
51
|
+
const others = fresh.filter(t => t.id !== task.id);
|
|
52
|
+
const prompt = buildWorkerPrompt(task, prdLabel, cwd, config, others, skills, teamStore.buildTeamPromptContext(cwd, task));
|
|
53
|
+
|
|
54
|
+
store.updateTask(cwd, task.id, {
|
|
55
|
+
status: "in_progress",
|
|
56
|
+
started_at: new Date().toISOString(),
|
|
57
|
+
base_commit: store.getBaseCommit(cwd),
|
|
58
|
+
assigned_to: lw.name,
|
|
59
|
+
attempt_count: task.attempt_count + 1,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (!assignTaskToLobbyWorker(lw, task.id, prompt, inboxDir)) {
|
|
63
|
+
store.updateTask(cwd, task.id, { status: "todo", assigned_to: undefined });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
store.appendTaskProgress(cwd, task.id, "system", `Assigned to lobby worker ${lw.name} (attempt ${task.attempt_count + 1})`);
|
|
68
|
+
logFeedEvent(cwd, lw.name, "task.start", task.id, task.title);
|
|
69
|
+
if (!firstWorkerName) firstWorkerName = lw.name;
|
|
70
|
+
assigned++;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
while (assigned < workerCap) {
|
|
74
|
+
const fresh = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" }).filter(t => !teamStore.taskNeedsApproval(t));
|
|
75
|
+
if (fresh.length === 0) break;
|
|
76
|
+
|
|
77
|
+
const task = fresh[0];
|
|
78
|
+
const others = fresh.filter(t => t.id !== task.id);
|
|
79
|
+
const prompt = buildWorkerPrompt(task, prdLabel, cwd, config, others, skills, teamStore.buildTeamPromptContext(cwd, task));
|
|
80
|
+
const worker = spawnWorkerForTask(cwd, task.id, prompt, sessionModel);
|
|
81
|
+
if (!worker) break;
|
|
82
|
+
|
|
83
|
+
if (!firstWorkerName) firstWorkerName = worker.name;
|
|
84
|
+
assigned++;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return { assigned, firstWorkerName };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function spawnSingleWorker(
|
|
91
|
+
cwd: string,
|
|
92
|
+
taskId: string,
|
|
93
|
+
sessionModel?: string,
|
|
94
|
+
): { name: string } | null {
|
|
95
|
+
const plan = store.getPlan(cwd);
|
|
96
|
+
if (!plan) return null;
|
|
97
|
+
|
|
98
|
+
const task = store.getTask(cwd, taskId);
|
|
99
|
+
if (!task) return null;
|
|
100
|
+
|
|
101
|
+
const crewDir = store.getCrewDir(cwd);
|
|
102
|
+
const config = loadCrewConfig(crewDir);
|
|
103
|
+
const prdLabel = store.getPlanLabel(plan);
|
|
104
|
+
const skills = discoverCrewSkills(cwd);
|
|
105
|
+
if (teamStore.taskNeedsApproval(task)) return null;
|
|
106
|
+
const readyTasks = store.getReadyTasks(cwd, { advisory: config.dependencies === "advisory" }).filter(t => !teamStore.taskNeedsApproval(t));
|
|
107
|
+
const others = readyTasks.filter(t => t.id !== task.id);
|
|
108
|
+
const prompt = buildWorkerPrompt(task, prdLabel, cwd, config, others, skills, teamStore.buildTeamPromptContext(cwd, task));
|
|
109
|
+
const worker = spawnWorkerForTask(cwd, taskId, prompt, sessionModel);
|
|
110
|
+
return worker ? { name: worker.name } : null;
|
|
111
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Autonomous Execution State
|
|
3
|
+
*
|
|
4
|
+
* Tracks autonomous mode, wave history, concurrency, and auto-work flag.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { normalizeCwd } from "./state.ts";
|
|
8
|
+
|
|
9
|
+
export interface WaveResult {
|
|
10
|
+
waveNumber: number;
|
|
11
|
+
tasksAttempted: string[];
|
|
12
|
+
succeeded: string[];
|
|
13
|
+
failed: string[];
|
|
14
|
+
blocked: string[];
|
|
15
|
+
timestamp: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface AutonomousState {
|
|
19
|
+
active: boolean;
|
|
20
|
+
cwd: string | null;
|
|
21
|
+
waveNumber: number;
|
|
22
|
+
waveHistory: WaveResult[];
|
|
23
|
+
startedAt: string | null;
|
|
24
|
+
stoppedAt: string | null;
|
|
25
|
+
stopReason: "completed" | "blocked" | "manual" | null;
|
|
26
|
+
concurrency: number;
|
|
27
|
+
autoOverlayPending: boolean;
|
|
28
|
+
pid: number | null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const autonomousState: AutonomousState = {
|
|
32
|
+
active: false,
|
|
33
|
+
cwd: null,
|
|
34
|
+
waveNumber: 0,
|
|
35
|
+
waveHistory: [],
|
|
36
|
+
startedAt: null,
|
|
37
|
+
stoppedAt: null,
|
|
38
|
+
stopReason: null,
|
|
39
|
+
concurrency: 2,
|
|
40
|
+
autoOverlayPending: false,
|
|
41
|
+
pid: null,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const MIN_CONCURRENCY = 1;
|
|
45
|
+
export const MAX_CONCURRENCY = 10;
|
|
46
|
+
|
|
47
|
+
function isProcessAlive(pid: number): boolean {
|
|
48
|
+
try {
|
|
49
|
+
process.kill(pid, 0);
|
|
50
|
+
return true;
|
|
51
|
+
} catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function clampConcurrency(value: number, configMax?: number): number {
|
|
57
|
+
if (!Number.isFinite(value)) return MIN_CONCURRENCY;
|
|
58
|
+
const whole = Math.trunc(value);
|
|
59
|
+
const effectiveMax = configMax != null && Number.isFinite(configMax)
|
|
60
|
+
? Math.min(configMax, MAX_CONCURRENCY)
|
|
61
|
+
: MAX_CONCURRENCY;
|
|
62
|
+
return Math.max(MIN_CONCURRENCY, Math.min(effectiveMax, whole));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let concurrencyResolve: (() => void) | null = null;
|
|
66
|
+
|
|
67
|
+
export function adjustConcurrency(delta: number, configMax?: number): number {
|
|
68
|
+
autonomousState.concurrency = clampConcurrency(autonomousState.concurrency + delta, configMax);
|
|
69
|
+
if (concurrencyResolve) {
|
|
70
|
+
const resolve = concurrencyResolve;
|
|
71
|
+
concurrencyResolve = null;
|
|
72
|
+
resolve();
|
|
73
|
+
}
|
|
74
|
+
return autonomousState.concurrency;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function waitForConcurrencyChange(): Promise<void> {
|
|
78
|
+
return new Promise(resolve => {
|
|
79
|
+
concurrencyResolve = resolve;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function startAutonomous(cwd: string, concurrency: number): void {
|
|
84
|
+
autonomousState.active = true;
|
|
85
|
+
autonomousState.cwd = normalizeCwd(cwd);
|
|
86
|
+
autonomousState.waveNumber = 1;
|
|
87
|
+
autonomousState.waveHistory = [];
|
|
88
|
+
autonomousState.startedAt = new Date().toISOString();
|
|
89
|
+
autonomousState.stoppedAt = null;
|
|
90
|
+
autonomousState.stopReason = null;
|
|
91
|
+
autonomousState.concurrency = clampConcurrency(concurrency);
|
|
92
|
+
autonomousState.autoOverlayPending = true;
|
|
93
|
+
autonomousState.pid = process.pid;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function stopAutonomous(reason: "completed" | "blocked" | "manual"): void {
|
|
97
|
+
autonomousState.active = false;
|
|
98
|
+
autonomousState.autoOverlayPending = false;
|
|
99
|
+
autonomousState.stoppedAt = new Date().toISOString();
|
|
100
|
+
autonomousState.stopReason = reason;
|
|
101
|
+
autonomousState.pid = null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function addWaveResult(result: WaveResult): void {
|
|
105
|
+
autonomousState.waveHistory.push(result);
|
|
106
|
+
autonomousState.waveNumber++;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function restoreAutonomousState(data: Partial<AutonomousState>): void {
|
|
110
|
+
if (data.active !== undefined) autonomousState.active = data.active;
|
|
111
|
+
if (data.cwd !== undefined) {
|
|
112
|
+
autonomousState.cwd = data.cwd ? normalizeCwd(data.cwd) : data.cwd;
|
|
113
|
+
}
|
|
114
|
+
if (data.waveNumber !== undefined) autonomousState.waveNumber = data.waveNumber;
|
|
115
|
+
if (data.waveHistory !== undefined) autonomousState.waveHistory = data.waveHistory;
|
|
116
|
+
if (data.startedAt !== undefined) autonomousState.startedAt = data.startedAt;
|
|
117
|
+
if (data.stoppedAt !== undefined) autonomousState.stoppedAt = data.stoppedAt;
|
|
118
|
+
if (data.stopReason !== undefined) autonomousState.stopReason = data.stopReason;
|
|
119
|
+
if (data.concurrency !== undefined) {
|
|
120
|
+
autonomousState.concurrency = clampConcurrency(Number(data.concurrency));
|
|
121
|
+
}
|
|
122
|
+
if (data.pid !== undefined) {
|
|
123
|
+
autonomousState.pid = typeof data.pid === "number" ? data.pid : null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (!autonomousState.active) return;
|
|
127
|
+
|
|
128
|
+
const ownerPid = autonomousState.pid;
|
|
129
|
+
const sameProcess = ownerPid === process.pid;
|
|
130
|
+
const ownerAlive = typeof ownerPid === "number" && isProcessAlive(ownerPid);
|
|
131
|
+
|
|
132
|
+
if (!sameProcess || !ownerAlive) {
|
|
133
|
+
autonomousState.active = false;
|
|
134
|
+
autonomousState.autoOverlayPending = false;
|
|
135
|
+
autonomousState.stopReason = autonomousState.stopReason ?? "manual";
|
|
136
|
+
autonomousState.stoppedAt = autonomousState.stoppedAt ?? new Date().toISOString();
|
|
137
|
+
autonomousState.pid = null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function isAutonomousForCwd(cwd: string): boolean {
|
|
142
|
+
if (!autonomousState.active || !autonomousState.cwd) return false;
|
|
143
|
+
return normalizeCwd(autonomousState.cwd) === normalizeCwd(cwd);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
let pendingAutoWork = false;
|
|
147
|
+
let pendingAutoWorkCwd: string | null = null;
|
|
148
|
+
|
|
149
|
+
export function isPendingAutoWork(): boolean {
|
|
150
|
+
return pendingAutoWork;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function setPendingAutoWork(cwd: string): void {
|
|
154
|
+
pendingAutoWork = true;
|
|
155
|
+
pendingAutoWorkCwd = normalizeCwd(cwd);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function consumePendingAutoWork(): { cwd: string } | null {
|
|
159
|
+
if (!pendingAutoWork || !pendingAutoWorkCwd) return null;
|
|
160
|
+
const consumed = { cwd: pendingAutoWorkCwd };
|
|
161
|
+
pendingAutoWork = false;
|
|
162
|
+
pendingAutoWorkCwd = null;
|
|
163
|
+
return consumed;
|
|
164
|
+
}
|