@linxiraos/pi-messenger 1.1.1 → 1.3.1

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 +743 -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
@@ -1,219 +1,221 @@
1
- /**
2
- * Crew - Agent & Skill Discovery
3
- *
4
- * Discovers agent definitions and skill files from extension,
5
- * project, and user directories.
6
- */
7
-
8
- import * as fs from "node:fs";
9
- import * as os from "node:os";
10
- import * as path from "node:path";
11
- import { fileURLToPath } from "node:url";
12
- import type { MaxOutputConfig } from "./truncate.ts";
13
-
14
- const __filename = fileURLToPath(import.meta.url);
15
- const __dirname = path.dirname(__filename);
16
- const DEFAULT_EXTENSION_AGENTS_DIR = path.resolve(__dirname, "..", "agents");
17
- const DEFAULT_EXTENSION_SKILLS_DIR = path.resolve(__dirname, "..", "skills");
18
-
19
- export type CrewRole = "planner" | "worker" | "reviewer" | "analyst";
20
-
21
- export interface CrewAgentConfig {
22
- name: string;
23
- description: string;
24
- tools?: string[];
25
- model?: string;
26
- thinking?: string;
27
- systemPrompt: string;
28
- source: "extension" | "project";
29
- filePath: string;
30
- crewRole?: CrewRole;
31
- maxOutput?: MaxOutputConfig;
32
- parallel?: boolean;
33
- retryable?: boolean;
34
- }
35
-
36
- function parseFrontmatter(content: string): { frontmatter: Record<string, unknown>; body: string } {
37
- const normalized = content.replace(/\r\n/g, "\n");
38
- if (!normalized.startsWith("---")) {
39
- return { frontmatter: {}, body: normalized };
40
- }
41
- const endIndex = normalized.indexOf("\n---", 3);
42
- if (endIndex === -1) {
43
- return { frontmatter: {}, body: normalized };
44
- }
45
- const frontmatterBlock = normalized.slice(4, endIndex);
46
- const body = normalized.slice(endIndex + 4).trim();
47
-
48
- const frontmatter: Record<string, unknown> = {};
49
- for (const line of frontmatterBlock.split("\n")) {
50
- const match = line.match(/^([\w-]+):\s*(.*)$/);
51
- if (match) {
52
- let value: unknown = match[2].trim();
53
- if ((value as string).startsWith("\"") || (value as string).startsWith("'")) {
54
- value = (value as string).slice(1, -1);
55
- }
56
- if ((value as string).startsWith("{") && (value as string).endsWith("}")) {
57
- try {
58
- const jsonStr = (value as string).replace(/(\w+):/g, "\"$1\":");
59
- value = JSON.parse(jsonStr);
60
- } catch {
61
- // Keep as string if parse fails
62
- }
63
- }
64
- if (value === "true") value = true;
65
- if (value === "false") value = false;
66
- frontmatter[match[1]] = value;
67
- }
68
- }
69
-
70
- return { frontmatter, body };
71
- }
72
-
73
- function loadAgentsFromDir(dir: string, source: "extension" | "project"): CrewAgentConfig[] {
74
- if (!fs.existsSync(dir)) return [];
75
- const agents: CrewAgentConfig[] = [];
76
-
77
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
78
- if (!entry.name.endsWith(".md")) continue;
79
- if (!entry.isFile() && !entry.isSymbolicLink()) continue;
80
-
81
- const filePath = path.join(dir, entry.name);
82
- let content: string;
83
- try {
84
- content = fs.readFileSync(filePath, "utf-8");
85
- } catch {
86
- continue;
87
- }
88
-
89
- const { frontmatter, body } = parseFrontmatter(content);
90
- if (!frontmatter.name || !frontmatter.description) continue;
91
-
92
- const tools = (frontmatter.tools as string)
93
- ?.split(",")
94
- .map(t => t.trim())
95
- .filter(Boolean);
96
-
97
- agents.push({
98
- name: frontmatter.name as string,
99
- description: frontmatter.description as string,
100
- tools: tools && tools.length > 0 ? tools : undefined,
101
- model: frontmatter.model as string | undefined,
102
- thinking: frontmatter.thinking as string | undefined,
103
- systemPrompt: body,
104
- source,
105
- filePath,
106
- crewRole: frontmatter.crewRole as CrewRole | undefined,
107
- maxOutput: frontmatter.maxOutput as MaxOutputConfig | undefined,
108
- parallel: (frontmatter.parallel as boolean | undefined) ?? true,
109
- retryable: (frontmatter.retryable as boolean | undefined) ?? true,
110
- });
111
- }
112
-
113
- return agents;
114
- }
115
-
116
- export function discoverCrewAgents(cwd: string, extensionAgentsDir?: string): CrewAgentConfig[] {
117
- const extDir = extensionAgentsDir ?? DEFAULT_EXTENSION_AGENTS_DIR;
118
- const projectAgentsDir = path.join(cwd, ".pi", "messenger", "crew", "agents");
119
-
120
- const extensionAgents = loadAgentsFromDir(extDir, "extension");
121
- const projectAgents = loadAgentsFromDir(projectAgentsDir, "project");
122
-
123
- const agentMap = new Map<string, CrewAgentConfig>();
124
- for (const agent of extensionAgents) agentMap.set(agent.name, agent);
125
- for (const agent of projectAgents) agentMap.set(agent.name, agent);
126
-
127
- return Array.from(agentMap.values());
128
- }
129
-
130
- // =============================================================================
131
- // Skill Discovery
132
- // =============================================================================
133
-
134
- export interface CrewSkillInfo {
135
- name: string;
136
- description: string;
137
- path: string;
138
- source: "user" | "extension" | "project";
139
- }
140
-
141
- function loadSkillsFromFlatDir(dir: string, source: "extension" | "project"): CrewSkillInfo[] {
142
- if (!fs.existsSync(dir)) return [];
143
- const skills: CrewSkillInfo[] = [];
144
-
145
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
146
- if (!entry.name.endsWith(".md")) continue;
147
- if (!entry.isFile() && !entry.isSymbolicLink()) continue;
148
-
149
- const filePath = path.join(dir, entry.name);
150
- let content: string;
151
- try {
152
- content = fs.readFileSync(filePath, "utf-8");
153
- } catch {
154
- continue;
155
- }
156
-
157
- const { frontmatter } = parseFrontmatter(content);
158
- if (!frontmatter.name || !frontmatter.description) continue;
159
-
160
- skills.push({
161
- name: frontmatter.name as string,
162
- description: (frontmatter.description as string).split("\n")[0].trim(),
163
- path: filePath,
164
- source,
165
- });
166
- }
167
-
168
- return skills;
169
- }
170
-
171
- function loadSkillsFromUserDir(dir: string): CrewSkillInfo[] {
172
- if (!fs.existsSync(dir)) return [];
173
- const skills: CrewSkillInfo[] = [];
174
-
175
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
176
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
177
-
178
- const skillFile = path.join(dir, entry.name, "SKILL.md");
179
- let content: string;
180
- try {
181
- content = fs.readFileSync(skillFile, "utf-8");
182
- } catch {
183
- continue;
184
- }
185
-
186
- const { frontmatter } = parseFrontmatter(content);
187
- if (!frontmatter.name || !frontmatter.description) continue;
188
-
189
- skills.push({
190
- name: frontmatter.name as string,
191
- description: (frontmatter.description as string).split("\n")[0].trim(),
192
- path: skillFile,
193
- source: "user",
194
- });
195
- }
196
-
197
- return skills;
198
- }
199
-
200
- export function discoverCrewSkills(
201
- cwd: string,
202
- extensionSkillsDir?: string,
203
- userSkillsDir?: string,
204
- ): CrewSkillInfo[] {
205
- const extDir = extensionSkillsDir ?? DEFAULT_EXTENSION_SKILLS_DIR;
206
- const projectSkillsDir = path.join(cwd, ".pi", "messenger", "crew", "skills");
207
- const userDir = userSkillsDir ?? path.join(os.homedir(), ".pi", "agent", "skills");
208
-
209
- const userSkills = loadSkillsFromUserDir(userDir);
210
- const extensionSkills = loadSkillsFromFlatDir(extDir, "extension");
211
- const projectSkills = loadSkillsFromFlatDir(projectSkillsDir, "project");
212
-
213
- const skillMap = new Map<string, CrewSkillInfo>();
214
- for (const skill of userSkills) skillMap.set(skill.name, skill);
215
- for (const skill of extensionSkills) skillMap.set(skill.name, skill);
216
- for (const skill of projectSkills) skillMap.set(skill.name, skill);
217
-
218
- return Array.from(skillMap.values());
219
- }
1
+ /**
2
+ * Crew - Agent & Skill Discovery
3
+ *
4
+ * Discovers agent definitions and skill files from extension,
5
+ * project, and user directories.
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import * as path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import type { MaxOutputConfig } from "./truncate.ts";
12
+ import { getAgentDir } from "@linxiraos/pi-utils/dirs";
13
+ import { getProjectCrewDir } from "../../paths.ts";
14
+ import { isProjectAgentsTrusted } from "../../config.ts";
15
+
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+ const DEFAULT_EXTENSION_AGENTS_DIR = path.resolve(__dirname, "..", "agents");
19
+ const DEFAULT_EXTENSION_SKILLS_DIR = path.resolve(__dirname, "..", "skills");
20
+
21
+ export type CrewRole = "planner" | "worker" | "reviewer" | "analyst";
22
+
23
+ export interface CrewAgentConfig {
24
+ name: string;
25
+ description: string;
26
+ tools?: string[];
27
+ model?: string;
28
+ thinking?: string;
29
+ systemPrompt: string;
30
+ source: "extension" | "project";
31
+ filePath: string;
32
+ crewRole?: CrewRole;
33
+ maxOutput?: MaxOutputConfig;
34
+ parallel?: boolean;
35
+ retryable?: boolean;
36
+ }
37
+
38
+ function parseFrontmatter(content: string): { frontmatter: Record<string, unknown>; body: string } {
39
+ const normalized = content.replace(/\r\n/g, "\n");
40
+ if (!normalized.startsWith("---")) {
41
+ return { frontmatter: {}, body: normalized };
42
+ }
43
+ const endIndex = normalized.indexOf("\n---", 3);
44
+ if (endIndex === -1) {
45
+ return { frontmatter: {}, body: normalized };
46
+ }
47
+ const frontmatterBlock = normalized.slice(4, endIndex);
48
+ const body = normalized.slice(endIndex + 4).trim();
49
+
50
+ const frontmatter: Record<string, unknown> = {};
51
+ for (const line of frontmatterBlock.split("\n")) {
52
+ const match = line.match(/^([\w-]+):\s*(.*)$/);
53
+ if (match) {
54
+ let value: unknown = match[2].trim();
55
+ if ((value as string).startsWith('"') || (value as string).startsWith("'")) {
56
+ value = (value as string).slice(1, -1);
57
+ }
58
+ if ((value as string).startsWith("{") && (value as string).endsWith("}")) {
59
+ try {
60
+ const jsonStr = (value as string).replace(/(\w+):/g, '"$1":');
61
+ value = JSON.parse(jsonStr);
62
+ } catch {
63
+ // Keep as string if parse fails
64
+ }
65
+ }
66
+ if (value === "true") value = true;
67
+ if (value === "false") value = false;
68
+ frontmatter[match[1]] = value;
69
+ }
70
+ }
71
+
72
+ return { frontmatter, body };
73
+ }
74
+
75
+ function loadAgentsFromDir(dir: string, source: "extension" | "project"): CrewAgentConfig[] {
76
+ if (!fs.existsSync(dir)) return [];
77
+ const agents: CrewAgentConfig[] = [];
78
+
79
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
80
+ if (!entry.name.endsWith(".md")) continue;
81
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
82
+
83
+ const filePath = path.join(dir, entry.name);
84
+ let content: string;
85
+ try {
86
+ content = fs.readFileSync(filePath, "utf-8");
87
+ } catch {
88
+ continue;
89
+ }
90
+
91
+ const { frontmatter, body } = parseFrontmatter(content);
92
+ if (!frontmatter.name || !frontmatter.description) continue;
93
+
94
+ const tools = (frontmatter.tools as string)
95
+ ?.split(",")
96
+ .map(t => t.trim())
97
+ .filter(Boolean);
98
+
99
+ agents.push({
100
+ name: frontmatter.name as string,
101
+ description: frontmatter.description as string,
102
+ tools: tools && tools.length > 0 ? tools : undefined,
103
+ model: frontmatter.model as string | undefined,
104
+ thinking: frontmatter.thinking as string | undefined,
105
+ systemPrompt: body,
106
+ source,
107
+ filePath,
108
+ crewRole: frontmatter.crewRole as CrewRole | undefined,
109
+ maxOutput: frontmatter.maxOutput as MaxOutputConfig | undefined,
110
+ parallel: (frontmatter.parallel as boolean | undefined) ?? true,
111
+ retryable: (frontmatter.retryable as boolean | undefined) ?? true,
112
+ });
113
+ }
114
+
115
+ return agents;
116
+ }
117
+
118
+ export function discoverCrewAgents(cwd: string, extensionAgentsDir?: string): CrewAgentConfig[] {
119
+ const extDir = extensionAgentsDir ?? DEFAULT_EXTENSION_AGENTS_DIR;
120
+ // Project-supplied agent overrides load only when the project explicitly
121
+ // opted in (trustProjectAgents) — see isProjectAgentsTrusted.
122
+ const projectAgentsDir = path.join(getProjectCrewDir(cwd), "agents");
123
+
124
+ const extensionAgents = loadAgentsFromDir(extDir, "extension");
125
+ const projectAgents = isProjectAgentsTrusted(cwd) ? loadAgentsFromDir(projectAgentsDir, "project") : [];
126
+
127
+ const agentMap = new Map<string, CrewAgentConfig>();
128
+ for (const agent of extensionAgents) agentMap.set(agent.name, agent);
129
+ for (const agent of projectAgents) agentMap.set(agent.name, agent);
130
+
131
+ return Array.from(agentMap.values());
132
+ }
133
+
134
+ // =============================================================================
135
+ // Skill Discovery
136
+ // =============================================================================
137
+
138
+ export interface CrewSkillInfo {
139
+ name: string;
140
+ description: string;
141
+ path: string;
142
+ source: "user" | "extension" | "project";
143
+ }
144
+
145
+ function loadSkillsFromFlatDir(dir: string, source: "extension" | "project"): CrewSkillInfo[] {
146
+ if (!fs.existsSync(dir)) return [];
147
+ const skills: CrewSkillInfo[] = [];
148
+
149
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
150
+ if (!entry.name.endsWith(".md")) continue;
151
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue;
152
+
153
+ const filePath = path.join(dir, entry.name);
154
+ let content: string;
155
+ try {
156
+ content = fs.readFileSync(filePath, "utf-8");
157
+ } catch {
158
+ continue;
159
+ }
160
+
161
+ const { frontmatter } = parseFrontmatter(content);
162
+ if (!frontmatter.name || !frontmatter.description) continue;
163
+
164
+ skills.push({
165
+ name: frontmatter.name as string,
166
+ description: (frontmatter.description as string).split("\n")[0].trim(),
167
+ path: filePath,
168
+ source,
169
+ });
170
+ }
171
+
172
+ return skills;
173
+ }
174
+
175
+ function loadSkillsFromUserDir(dir: string): CrewSkillInfo[] {
176
+ if (!fs.existsSync(dir)) return [];
177
+ const skills: CrewSkillInfo[] = [];
178
+
179
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
180
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
181
+
182
+ const skillFile = path.join(dir, entry.name, "SKILL.md");
183
+ let content: string;
184
+ try {
185
+ content = fs.readFileSync(skillFile, "utf-8");
186
+ } catch {
187
+ continue;
188
+ }
189
+
190
+ const { frontmatter } = parseFrontmatter(content);
191
+ if (!frontmatter.name || !frontmatter.description) continue;
192
+
193
+ skills.push({
194
+ name: frontmatter.name as string,
195
+ description: (frontmatter.description as string).split("\n")[0].trim(),
196
+ path: skillFile,
197
+ source: "user",
198
+ });
199
+ }
200
+
201
+ return skills;
202
+ }
203
+
204
+ export function discoverCrewSkills(cwd: string, extensionSkillsDir?: string, userSkillsDir?: string): CrewSkillInfo[] {
205
+ const extDir = extensionSkillsDir ?? DEFAULT_EXTENSION_SKILLS_DIR;
206
+ // Project-supplied skills load only when the project explicitly opted in
207
+ // (trustProjectAgents) — see isProjectAgentsTrusted.
208
+ const projectSkillsDir = path.join(getProjectCrewDir(cwd), "skills");
209
+ const userDir = userSkillsDir ?? path.join(getAgentDir(), "skills");
210
+
211
+ const userSkills = loadSkillsFromUserDir(userDir);
212
+ const extensionSkills = loadSkillsFromFlatDir(extDir, "extension");
213
+ const projectSkills = isProjectAgentsTrusted(cwd) ? loadSkillsFromFlatDir(projectSkillsDir, "project") : [];
214
+
215
+ const skillMap = new Map<string, CrewSkillInfo>();
216
+ for (const skill of userSkills) skillMap.set(skill.name, skill);
217
+ for (const skill of extensionSkills) skillMap.set(skill.name, skill);
218
+ for (const skill of projectSkills) skillMap.set(skill.name, skill);
219
+
220
+ return Array.from(skillMap.values());
221
+ }
@@ -1,85 +1,94 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { homedir } from "node:os";
4
-
5
- const CREW_AGENTS = [
6
- "crew-planner.md",
7
- "crew-plan-sync.md",
8
- "crew-worker.md",
9
- "crew-reviewer.md",
10
- ];
11
-
12
- const DEPRECATED_AGENTS = [
13
- "crew-repo-scout.md",
14
- "crew-practice-scout.md",
15
- "crew-docs-scout.md",
16
- "crew-web-scout.md",
17
- "crew-github-scout.md",
18
- "crew-gap-analyst.md",
19
- "crew-interview-generator.md",
20
- ];
21
-
22
- const DEFAULT_MIGRATION_MARKER = "legacy-crew-agent-cleanup-v1.json";
23
-
24
- export interface InstallOptions {
25
- homeDir?: string;
26
- migrationMarker?: string;
27
- }
28
-
29
- function getTargetAgentsDir(homeDir: string): string {
30
- return path.join(homeDir, ".pi", "agent", "agents");
31
- }
32
-
33
- function getMigrationMarkerPath(homeDir: string, marker: string): string {
34
- return path.join(homeDir, ".pi", "agent", "messenger", "migrations", marker);
35
- }
36
-
37
- export function uninstallAgents(options: InstallOptions = {}): { removed: string[]; errors: string[] } {
38
- const homeDir = options.homeDir ?? homedir();
39
- const targetAgentsDir = getTargetAgentsDir(homeDir);
40
- const removed: string[] = [];
41
- const errors: string[] = [];
42
-
43
- for (const agent of [...CREW_AGENTS, ...DEPRECATED_AGENTS]) {
44
- const target = path.join(targetAgentsDir, agent);
45
- try {
46
- if (fs.existsSync(target)) {
47
- fs.unlinkSync(target);
48
- removed.push(agent);
49
- }
50
- } catch (err) {
51
- errors.push(`Failed to remove ${agent}: ${err}`);
52
- }
53
- }
54
-
55
- return { removed, errors };
56
- }
57
-
58
- export function runLegacyAgentCleanupMigration(options: InstallOptions = {}): {
59
- ran: boolean;
60
- removed: string[];
61
- errors: string[];
62
- } {
63
- const homeDir = options.homeDir ?? homedir();
64
- const migrationMarker = options.migrationMarker ?? DEFAULT_MIGRATION_MARKER;
65
- const markerPath = getMigrationMarkerPath(homeDir, migrationMarker);
66
-
67
- if (fs.existsSync(markerPath)) {
68
- return { ran: false, removed: [], errors: [] };
69
- }
70
-
71
- const uninstallResult = uninstallAgents({ homeDir });
72
-
73
- try {
74
- fs.mkdirSync(path.dirname(markerPath), { recursive: true });
75
- fs.writeFileSync(markerPath, JSON.stringify({
76
- migratedAt: new Date().toISOString(),
77
- removed: uninstallResult.removed,
78
- errors: uninstallResult.errors,
79
- }, null, 2));
80
- } catch (err) {
81
- uninstallResult.errors.push(`Failed to persist migration marker: ${err}`);
82
- }
83
-
84
- return { ran: true, removed: uninstallResult.removed, errors: uninstallResult.errors };
85
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { getAgentDir } from "@linxiraos/pi-utils/dirs";
5
+
6
+ const CREW_AGENTS = ["crew-planner.md", "crew-plan-sync.md", "crew-worker.md", "crew-reviewer.md"];
7
+
8
+ const DEPRECATED_AGENTS = [
9
+ "crew-repo-scout.md",
10
+ "crew-practice-scout.md",
11
+ "crew-docs-scout.md",
12
+ "crew-web-scout.md",
13
+ "crew-github-scout.md",
14
+ "crew-gap-analyst.md",
15
+ "crew-interview-generator.md",
16
+ ];
17
+
18
+ const DEFAULT_MIGRATION_MARKER = "legacy-crew-agent-cleanup-v1.json";
19
+
20
+ export interface InstallOptions {
21
+ homeDir?: string;
22
+ migrationMarker?: string;
23
+ }
24
+
25
+ function getTargetAgentsDir(homeDir: string): string {
26
+ // The legacy ~/.pi/agent/agents directory is exactly what this migration
27
+ // cleans up, so it intentionally stays in the pi tree.
28
+ return path.join(homeDir, ".pi", "agent", "agents");
29
+ }
30
+
31
+ function getMigrationMarkerPath(homeDir: string, marker: string): string {
32
+ // Markers live in the current messenger tree; pre-existing markers migrate
33
+ // together with the rest of ~/.pi/agent/messenger (crew/utils/migrations.ts).
34
+ const messengerDir =
35
+ homeDir === homedir() ? path.join(getAgentDir(), "messenger") : path.join(homeDir, ".zeta", "agent", "messenger");
36
+ return path.join(messengerDir, "migrations", marker);
37
+ }
38
+
39
+ export function uninstallAgents(options: InstallOptions = {}): { removed: string[]; errors: string[] } {
40
+ const homeDir = options.homeDir ?? homedir();
41
+ const targetAgentsDir = getTargetAgentsDir(homeDir);
42
+ const removed: string[] = [];
43
+ const errors: string[] = [];
44
+
45
+ for (const agent of [...CREW_AGENTS, ...DEPRECATED_AGENTS]) {
46
+ const target = path.join(targetAgentsDir, agent);
47
+ try {
48
+ if (fs.existsSync(target)) {
49
+ fs.unlinkSync(target);
50
+ removed.push(agent);
51
+ }
52
+ } catch (err) {
53
+ errors.push(`Failed to remove ${agent}: ${err}`);
54
+ }
55
+ }
56
+
57
+ return { removed, errors };
58
+ }
59
+
60
+ export function runLegacyAgentCleanupMigration(options: InstallOptions = {}): {
61
+ ran: boolean;
62
+ removed: string[];
63
+ errors: string[];
64
+ } {
65
+ const homeDir = options.homeDir ?? homedir();
66
+ const migrationMarker = options.migrationMarker ?? DEFAULT_MIGRATION_MARKER;
67
+ const markerPath = getMigrationMarkerPath(homeDir, migrationMarker);
68
+
69
+ if (fs.existsSync(markerPath)) {
70
+ return { ran: false, removed: [], errors: [] };
71
+ }
72
+
73
+ const uninstallResult = uninstallAgents({ homeDir });
74
+
75
+ try {
76
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
77
+ fs.writeFileSync(
78
+ markerPath,
79
+ JSON.stringify(
80
+ {
81
+ migratedAt: new Date().toISOString(),
82
+ removed: uninstallResult.removed,
83
+ errors: uninstallResult.errors,
84
+ },
85
+ null,
86
+ 2,
87
+ ),
88
+ );
89
+ } catch (err) {
90
+ uninstallResult.errors.push(`Failed to persist migration marker: ${err}`);
91
+ }
92
+
93
+ return { ran: true, removed: uninstallResult.removed, errors: uninstallResult.errors };
94
+ }