@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
|
@@ -0,0 +1,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 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
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Progress Tracking
|
|
3
|
+
*
|
|
4
|
+
* Real-time visibility into agent execution via --mode json event parsing.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface ToolEntry {
|
|
8
|
+
tool: string;
|
|
9
|
+
args: string;
|
|
10
|
+
startMs: number;
|
|
11
|
+
endMs: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface AgentProgress {
|
|
15
|
+
agent: string;
|
|
16
|
+
status: "pending" | "running" | "completed" | "failed";
|
|
17
|
+
currentTool?: string;
|
|
18
|
+
currentToolArgs?: string;
|
|
19
|
+
currentToolStartMs?: number;
|
|
20
|
+
recentTools: ToolEntry[];
|
|
21
|
+
toolCallCount: number;
|
|
22
|
+
tokens: number;
|
|
23
|
+
durationMs: number;
|
|
24
|
+
error?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Event types from pi's --mode json output
|
|
28
|
+
export interface PiEvent {
|
|
29
|
+
type: string;
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
toolName?: string;
|
|
32
|
+
args?: Record<string, unknown>;
|
|
33
|
+
message?: {
|
|
34
|
+
role: string;
|
|
35
|
+
usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
|
|
36
|
+
model?: string;
|
|
37
|
+
content?: Array<{ type: string; text?: string }>;
|
|
38
|
+
errorMessage?: string;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createProgress(agent: string): AgentProgress {
|
|
43
|
+
return {
|
|
44
|
+
agent,
|
|
45
|
+
status: "pending",
|
|
46
|
+
recentTools: [],
|
|
47
|
+
toolCallCount: 0,
|
|
48
|
+
tokens: 0,
|
|
49
|
+
durationMs: 0,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function parseJsonlLine(line: string): PiEvent | null {
|
|
54
|
+
if (!line.trim()) return null;
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(line);
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function updateProgress(progress: AgentProgress, event: PiEvent, startTime: number): void {
|
|
63
|
+
progress.durationMs = Date.now() - startTime;
|
|
64
|
+
|
|
65
|
+
switch (event.type) {
|
|
66
|
+
case "tool_execution_start":
|
|
67
|
+
progress.status = "running";
|
|
68
|
+
progress.currentTool = event.toolName;
|
|
69
|
+
progress.currentToolArgs = extractArgsPreview(event.args);
|
|
70
|
+
progress.currentToolStartMs = Date.now();
|
|
71
|
+
break;
|
|
72
|
+
|
|
73
|
+
case "tool_execution_end":
|
|
74
|
+
progress.toolCallCount++;
|
|
75
|
+
if (progress.currentTool) {
|
|
76
|
+
progress.recentTools.push({
|
|
77
|
+
tool: progress.currentTool,
|
|
78
|
+
args: progress.currentToolArgs ?? "",
|
|
79
|
+
startMs: progress.currentToolStartMs ?? Date.now(),
|
|
80
|
+
endMs: Date.now(),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
progress.currentTool = undefined;
|
|
84
|
+
progress.currentToolArgs = undefined;
|
|
85
|
+
progress.currentToolStartMs = undefined;
|
|
86
|
+
break;
|
|
87
|
+
|
|
88
|
+
case "message_end":
|
|
89
|
+
if (event.message?.usage) {
|
|
90
|
+
progress.tokens += (event.message.usage.input ?? 0) + (event.message.usage.output ?? 0);
|
|
91
|
+
}
|
|
92
|
+
if (event.message?.errorMessage) {
|
|
93
|
+
progress.error = event.message.errorMessage;
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function extractArgsPreview(args?: Record<string, unknown>): string {
|
|
100
|
+
if (!args) return "";
|
|
101
|
+
const previewKeys = ["command", "path", "file_path", "pattern", "query"];
|
|
102
|
+
for (const key of previewKeys) {
|
|
103
|
+
if (args[key] && typeof args[key] === "string") {
|
|
104
|
+
const value = (args[key] as string).replaceAll("\n", " ").replaceAll("\r", "");
|
|
105
|
+
return value.length > 60 ? `${value.slice(0, 57)}...` : value;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return "";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function getAssistantText(event: PiEvent): string {
|
|
112
|
+
if (event.type !== "message_end" || event.message?.role !== "assistant") return "";
|
|
113
|
+
for (const part of event.message.content ?? []) {
|
|
114
|
+
if (part.type === "text" && part.text) return part.text;
|
|
115
|
+
}
|
|
116
|
+
return "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function getFinalOutput(messages: PiEvent[]): string {
|
|
120
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
121
|
+
const text = getAssistantText(messages[i]);
|
|
122
|
+
if (text) return text;
|
|
123
|
+
}
|
|
124
|
+
return "";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function compactEventForArtifact(event: PiEvent): Record<string, unknown> {
|
|
128
|
+
if (event.type !== "message_update") return event as Record<string, unknown>;
|
|
129
|
+
|
|
130
|
+
const compact: Record<string, unknown> = { ...event };
|
|
131
|
+
delete compact.message;
|
|
132
|
+
|
|
133
|
+
const assistantMessageEvent = compact.assistantMessageEvent;
|
|
134
|
+
if (assistantMessageEvent && typeof assistantMessageEvent === "object") {
|
|
135
|
+
const nested = { ...(assistantMessageEvent as Record<string, unknown>) };
|
|
136
|
+
delete nested.partial;
|
|
137
|
+
compact.assistantMessageEvent = nested;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return compact;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function getTerminalProviderError(event: PiEvent): string | null {
|
|
144
|
+
const status = findStatusCode(event);
|
|
145
|
+
if (status === undefined || ![400, 401, 402, 403, 429].includes(status)) return null;
|
|
146
|
+
|
|
147
|
+
const text = collectStrings(event).join(" ");
|
|
148
|
+
const normalized = text.toLowerCase();
|
|
149
|
+
if (!/(usage|quota|credit|billing|auth|unauthor|forbidden|rate limit|invalid_request|add more|plan limits|third-party apps)/.test(normalized)) {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const message = firstUsefulMessage(event) ?? text;
|
|
154
|
+
const concise = message.replace(/\s+/g, " ").trim().slice(0, 500);
|
|
155
|
+
return `Provider error ${status}: ${concise || "non-retryable provider error"}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function findStatusCode(value: unknown): number | undefined {
|
|
159
|
+
if (!value || typeof value !== "object") return undefined;
|
|
160
|
+
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
|
161
|
+
if (["status", "statusCode", "httpStatus", "code"].includes(key) && typeof child === "number") return child;
|
|
162
|
+
const nested = findStatusCode(child);
|
|
163
|
+
if (nested !== undefined) return nested;
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function collectStrings(value: unknown, depth = 0): string[] {
|
|
169
|
+
if (depth > 5 || value === null || value === undefined) return [];
|
|
170
|
+
if (typeof value === "string") return [value];
|
|
171
|
+
if (Array.isArray(value)) return value.flatMap(item => collectStrings(item, depth + 1));
|
|
172
|
+
if (typeof value !== "object") return [];
|
|
173
|
+
return Object.values(value as Record<string, unknown>).flatMap(item => collectStrings(item, depth + 1));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function firstUsefulMessage(value: unknown, depth = 0): string | undefined {
|
|
177
|
+
if (depth > 5 || !value || typeof value !== "object") return undefined;
|
|
178
|
+
const record = value as Record<string, unknown>;
|
|
179
|
+
for (const key of ["message", "errorMessage", "detail", "details"]) {
|
|
180
|
+
if (typeof record[key] === "string") return record[key] as string;
|
|
181
|
+
}
|
|
182
|
+
for (const child of Object.values(record)) {
|
|
183
|
+
const nested = firstUsefulMessage(child, depth + 1);
|
|
184
|
+
if (nested) return nested;
|
|
185
|
+
}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Result Formatter
|
|
3
|
+
*
|
|
4
|
+
* Helper for consistent tool result formatting.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Format a tool result with text content and structured details.
|
|
9
|
+
* Matches the pattern used throughout pi-messenger handlers.
|
|
10
|
+
*/
|
|
11
|
+
export function result(text: string, details: Record<string, unknown>) {
|
|
12
|
+
return {
|
|
13
|
+
content: [{ type: "text" as const, text }],
|
|
14
|
+
details
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function normalizeRiskLabels(labels: string[] | undefined): string[] | undefined {
|
|
2
|
+
if (!labels) return undefined;
|
|
3
|
+
const normalized = labels
|
|
4
|
+
.map(label => label.trim().toLowerCase())
|
|
5
|
+
.filter(Boolean);
|
|
6
|
+
return normalized.length > 0 ? Array.from(new Set(normalized)) : undefined;
|
|
7
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Task } from "../types.ts";
|
|
2
|
+
|
|
3
|
+
export function taskMetadataMarkers(task: Task): string {
|
|
4
|
+
const markers = [
|
|
5
|
+
task.role ? `[${task.role}]` : null,
|
|
6
|
+
task.risk_labels && task.risk_labels.length > 0 ? `[risk: ${task.risk_labels.join(", ")}]` : null,
|
|
7
|
+
task.approval?.required ? `[approval: ${task.approval.status}]` : null,
|
|
8
|
+
].filter(Boolean);
|
|
9
|
+
return markers.length > 0 ? ` ${markers.join(" ")}` : "";
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function approvalTaskSummaries(tasks: Task[]): { id: string; title: string; approval: Task["approval"] }[] {
|
|
13
|
+
return tasks.map(task => ({ id: task.id, title: task.title, approval: task.approval }));
|
|
14
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const PACKAGED_TEAM_ROLES = ["context-builder", "delegate", "oracle", "planner", "researcher", "reviewer", "scout", "worker"] as const;
|
|
2
|
+
|
|
3
|
+
export const NON_EDITING_TEAM_ROLES = new Set(["context-builder", "oracle", "planner", "researcher", "reviewer", "scout"]);
|
|
4
|
+
|
|
5
|
+
const PACKAGED_ROLE_NAMES = new Set<string>(PACKAGED_TEAM_ROLES);
|
|
6
|
+
const RESERVED_TEAM_NAMES = new Set(["__proto__", "constructor", "prototype"]);
|
|
7
|
+
|
|
8
|
+
export function canonicalPackagedTeamRole(role: string | undefined): string | undefined {
|
|
9
|
+
const trimmed = role?.trim();
|
|
10
|
+
if (!trimmed) return undefined;
|
|
11
|
+
const lower = trimmed.toLowerCase();
|
|
12
|
+
return PACKAGED_ROLE_NAMES.has(lower) ? lower : trimmed;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isReservedTeamName(name: string): boolean {
|
|
16
|
+
return RESERVED_TEAM_NAMES.has(name) || Object.hasOwn(Object.prototype, name);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function isValidTeamName(name: string): boolean {
|
|
20
|
+
if (!name || name.length > 80) return false;
|
|
21
|
+
if (isReservedTeamName(name)) return false;
|
|
22
|
+
return /^[a-zA-Z0-9_][a-zA-Z0-9_-]*$/.test(name);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isNonEditingTeamRole(role: string | undefined): boolean {
|
|
26
|
+
const canonical = canonicalPackagedTeamRole(role);
|
|
27
|
+
return !!canonical && NON_EDITING_TEAM_ROLES.has(canonical);
|
|
28
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Output Truncation
|
|
3
|
+
*
|
|
4
|
+
* Prevents token explosion from verbose agent outputs.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface MaxOutputConfig {
|
|
8
|
+
bytes?: number;
|
|
9
|
+
lines?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface TruncationResult {
|
|
13
|
+
text: string;
|
|
14
|
+
truncated: boolean;
|
|
15
|
+
originalBytes?: number;
|
|
16
|
+
originalLines?: number;
|
|
17
|
+
artifactPath?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_MAX_OUTPUT: Required<MaxOutputConfig> = {
|
|
21
|
+
bytes: 200 * 1024, // 200KB
|
|
22
|
+
lines: 5000,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function formatBytes(bytes: number): string {
|
|
26
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
27
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
28
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Truncate output to fit within limits.
|
|
33
|
+
*/
|
|
34
|
+
export function truncateOutput(
|
|
35
|
+
output: string,
|
|
36
|
+
config: MaxOutputConfig,
|
|
37
|
+
artifactPath?: string
|
|
38
|
+
): TruncationResult {
|
|
39
|
+
const maxBytes = config.bytes ?? DEFAULT_MAX_OUTPUT.bytes;
|
|
40
|
+
const maxLines = config.lines ?? DEFAULT_MAX_OUTPUT.lines;
|
|
41
|
+
|
|
42
|
+
const lines = output.split("\n");
|
|
43
|
+
const bytes = Buffer.byteLength(output, "utf-8");
|
|
44
|
+
|
|
45
|
+
if (bytes <= maxBytes && lines.length <= maxLines) {
|
|
46
|
+
return { text: output, truncated: false };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Truncate by lines first
|
|
50
|
+
let truncatedLines = lines.length > maxLines ? lines.slice(0, maxLines) : lines;
|
|
51
|
+
let result = truncatedLines.join("\n");
|
|
52
|
+
|
|
53
|
+
// Then truncate by bytes if still too large
|
|
54
|
+
if (Buffer.byteLength(result, "utf-8") > maxBytes) {
|
|
55
|
+
// Binary search for the right cut point
|
|
56
|
+
let low = 0, high = result.length;
|
|
57
|
+
while (low < high) {
|
|
58
|
+
const mid = Math.floor((low + high + 1) / 2);
|
|
59
|
+
if (Buffer.byteLength(result.slice(0, mid), "utf-8") <= maxBytes) {
|
|
60
|
+
low = mid;
|
|
61
|
+
} else {
|
|
62
|
+
high = mid - 1;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
result = result.slice(0, low);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const keptLines = result.split("\n").length;
|
|
69
|
+
const fullOutputHint = artifactPath ? ` - full output at ${artifactPath}` : "";
|
|
70
|
+
const marker = `[TRUNCATED: ${keptLines}/${lines.length} lines, ${formatBytes(Buffer.byteLength(result))}/${formatBytes(bytes)}${fullOutputHint}]\n`;
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
text: marker + result,
|
|
74
|
+
truncated: true,
|
|
75
|
+
originalBytes: bytes,
|
|
76
|
+
originalLines: lines.length,
|
|
77
|
+
artifactPath,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crew - Review Verdict Parsing
|
|
3
|
+
*
|
|
4
|
+
* Shared verdict parsing utility for reviewer outputs.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface ParsedReview {
|
|
8
|
+
verdict: "SHIP" | "NEEDS_WORK" | "MAJOR_RETHINK";
|
|
9
|
+
summary: string;
|
|
10
|
+
issues: string[];
|
|
11
|
+
suggestions: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function parseVerdict(output: string): ParsedReview {
|
|
15
|
+
const result: ParsedReview = {
|
|
16
|
+
verdict: "NEEDS_WORK",
|
|
17
|
+
summary: "",
|
|
18
|
+
issues: [],
|
|
19
|
+
suggestions: []
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// Extract verdict
|
|
23
|
+
const verdictMatch = output.match(/##\s*Verdict:\s*(SHIP|NEEDS_WORK|MAJOR_RETHINK)/i);
|
|
24
|
+
if (verdictMatch) {
|
|
25
|
+
result.verdict = verdictMatch[1].toUpperCase() as ParsedReview["verdict"];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Extract summary (text between Verdict and next ##)
|
|
29
|
+
const summaryMatch = output.match(/##\s*Verdict:.*?\n([\s\S]*?)(?=\n##|$)/i);
|
|
30
|
+
if (summaryMatch) {
|
|
31
|
+
result.summary = summaryMatch[1].trim();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Extract issues
|
|
35
|
+
const issuesMatch = output.match(/##\s*Issues?\s*\n([\s\S]*?)(?=\n##|$)/i);
|
|
36
|
+
if (issuesMatch) {
|
|
37
|
+
result.issues = issuesMatch[1]
|
|
38
|
+
.split("\n")
|
|
39
|
+
.filter(line => line.trim().startsWith("-") || line.trim().startsWith("*"))
|
|
40
|
+
.map(line => line.replace(/^[\s\-*]+/, "").trim())
|
|
41
|
+
.filter(Boolean);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Extract suggestions
|
|
45
|
+
const suggestionsMatch = output.match(/##\s*Suggestions?\s*\n([\s\S]*?)(?=\n##|$)/i);
|
|
46
|
+
if (suggestionsMatch) {
|
|
47
|
+
result.suggestions = suggestionsMatch[1]
|
|
48
|
+
.split("\n")
|
|
49
|
+
.filter(line => line.trim().startsWith("-") || line.trim().startsWith("*"))
|
|
50
|
+
.map(line => line.replace(/^[\s\-*]+/, "").trim())
|
|
51
|
+
.filter(Boolean);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return result;
|
|
55
|
+
}
|