@leing2021/super-pi 0.22.0 → 0.23.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 (101) hide show
  1. package/README.md +38 -209
  2. package/extensions/ce-core/index.ts +190 -7
  3. package/extensions/ce-core/tools/parallel-subagent.ts +3 -3
  4. package/extensions/ce-core/tools/subagent.ts +2 -2
  5. package/package.json +4 -18
  6. package/rules/common/naming.md +154 -0
  7. package/skills/02-plan/SKILL.md +3 -2
  8. package/skills/03-work/SKILL.md +9 -6
  9. package/skills/04-review/SKILL.md +3 -2
  10. package/skills/06-next/SKILL.md +38 -10
  11. package/skills/06-next/references/recommendation-logic.md +2 -2
  12. package/skills/07-worktree/SKILL.md +9 -8
  13. package/skills/{09-help → 08-help}/SKILL.md +3 -3
  14. package/skills/{09-help → 08-help}/references/workflow-sequence.md +2 -1
  15. package/skills/references/language-detection.md +44 -0
  16. package/extensions/subagent/agent-management.ts +0 -595
  17. package/extensions/subagent/agent-manager-chain-detail.ts +0 -162
  18. package/extensions/subagent/agent-manager-detail.ts +0 -231
  19. package/extensions/subagent/agent-manager-edit.ts +0 -390
  20. package/extensions/subagent/agent-manager-list.ts +0 -278
  21. package/extensions/subagent/agent-manager-parallel.ts +0 -304
  22. package/extensions/subagent/agent-manager.ts +0 -705
  23. package/extensions/subagent/agent-scope.ts +0 -8
  24. package/extensions/subagent/agent-selection.ts +0 -25
  25. package/extensions/subagent/agent-serializer.ts +0 -123
  26. package/extensions/subagent/agent-templates.ts +0 -62
  27. package/extensions/subagent/agents/context-builder.md +0 -37
  28. package/extensions/subagent/agents/delegate.md +0 -9
  29. package/extensions/subagent/agents/oracle.md +0 -73
  30. package/extensions/subagent/agents/planner.md +0 -52
  31. package/extensions/subagent/agents/researcher.md +0 -50
  32. package/extensions/subagent/agents/reviewer.md +0 -38
  33. package/extensions/subagent/agents/scout.md +0 -48
  34. package/extensions/subagent/agents/worker.md +0 -52
  35. package/extensions/subagent/agents.ts +0 -761
  36. package/extensions/subagent/artifacts.ts +0 -100
  37. package/extensions/subagent/async-execution.ts +0 -520
  38. package/extensions/subagent/async-job-tracker.ts +0 -216
  39. package/extensions/subagent/async-status.ts +0 -241
  40. package/extensions/subagent/chain-clarify.ts +0 -1364
  41. package/extensions/subagent/chain-execution.ts +0 -853
  42. package/extensions/subagent/chain-serializer.ts +0 -126
  43. package/extensions/subagent/completion-dedupe.ts +0 -65
  44. package/extensions/subagent/doctor.ts +0 -200
  45. package/extensions/subagent/execution.ts +0 -738
  46. package/extensions/subagent/file-coalescer.ts +0 -42
  47. package/extensions/subagent/fork-context.ts +0 -63
  48. package/extensions/subagent/formatters.ts +0 -122
  49. package/extensions/subagent/frontmatter.ts +0 -31
  50. package/extensions/subagent/index.ts +0 -585
  51. package/extensions/subagent/intercom-bridge.ts +0 -240
  52. package/extensions/subagent/jsonl-writer.ts +0 -83
  53. package/extensions/subagent/model-fallback.ts +0 -108
  54. package/extensions/subagent/notify.ts +0 -110
  55. package/extensions/subagent/parallel-utils.ts +0 -108
  56. package/extensions/subagent/pi-args.ts +0 -138
  57. package/extensions/subagent/pi-spawn.ts +0 -100
  58. package/extensions/subagent/post-exit-stdio-guard.ts +0 -87
  59. package/extensions/subagent/prompt-template-bridge.ts +0 -399
  60. package/extensions/subagent/prompts/gather-context-and-clarify.md +0 -13
  61. package/extensions/subagent/prompts/parallel-cleanup.md +0 -42
  62. package/extensions/subagent/prompts/parallel-research.md +0 -50
  63. package/extensions/subagent/prompts/parallel-review.md +0 -40
  64. package/extensions/subagent/render-helpers.ts +0 -82
  65. package/extensions/subagent/render.ts +0 -836
  66. package/extensions/subagent/result-intercom.ts +0 -237
  67. package/extensions/subagent/result-watcher.ts +0 -171
  68. package/extensions/subagent/run-history.ts +0 -57
  69. package/extensions/subagent/run-status.ts +0 -136
  70. package/extensions/subagent/schemas.ts +0 -164
  71. package/extensions/subagent/session-tokens.ts +0 -50
  72. package/extensions/subagent/settings.ts +0 -367
  73. package/extensions/subagent/single-output.ts +0 -97
  74. package/extensions/subagent/skills.ts +0 -626
  75. package/extensions/subagent/slash-bridge.ts +0 -176
  76. package/extensions/subagent/slash-commands.ts +0 -303
  77. package/extensions/subagent/slash-live-state.ts +0 -294
  78. package/extensions/subagent/subagent-control.ts +0 -150
  79. package/extensions/subagent/subagent-executor.ts +0 -1899
  80. package/extensions/subagent/subagent-prompt-runtime.ts +0 -75
  81. package/extensions/subagent/subagent-runner.ts +0 -1470
  82. package/extensions/subagent/subagents-status.ts +0 -472
  83. package/extensions/subagent/text-editor.ts +0 -272
  84. package/extensions/subagent/top-level-async.ts +0 -15
  85. package/extensions/subagent/types.ts +0 -623
  86. package/extensions/subagent/utils.ts +0 -456
  87. package/extensions/subagent/worktree.ts +0 -579
  88. package/extensions/super-pi-extension/agents/ce-oracle.md +0 -109
  89. package/extensions/super-pi-extension/agents/ce-planner.md +0 -116
  90. package/extensions/super-pi-extension/agents/ce-reviewer.md +0 -99
  91. package/extensions/super-pi-extension/agents/ce-scout.md +0 -80
  92. package/extensions/super-pi-extension/agents/ce-worker.md +0 -78
  93. package/extensions/super-pi-extension/chains/ce-parallel-review.chain.md +0 -34
  94. package/extensions/super-pi-extension/chains/ce-review-only.chain.md +0 -12
  95. package/extensions/super-pi-extension/chains/ce-standard.chain.md +0 -28
  96. package/extensions/super-pi-extension/index.ts +0 -129
  97. package/extensions/super-pi-extension/model-sync.ts +0 -204
  98. package/skills/08-status/SKILL.md +0 -41
  99. package/skills/08-status/references/artifact-locations.md +0 -10
  100. package/skills/10-rules/SKILL.md +0 -76
  101. package/skills/pi-subagents/SKILL.md +0 -566
@@ -1,456 +0,0 @@
1
- // Based on pi-subagents by Nico Bailon (https://github.com/nicobailon/pi-subagents)
2
- // MIT License
3
- /**
4
- * General utility functions for the subagent extension
5
- */
6
-
7
- import * as fs from "node:fs";
8
- import * as os from "node:os";
9
- import * as path from "node:path";
10
- import type { Message } from "@mariozechner/pi-ai";
11
- import { formatToolCall } from "./formatters.ts";
12
- import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, SingleResult, ToolCallSummary } from "./types.ts";
13
-
14
- // ============================================================================
15
- // File System Utilities
16
- // ============================================================================
17
-
18
- const statusCache = new Map<string, { mtime: number; status: AsyncStatus }>();
19
-
20
- function getErrorMessage(error: unknown): string {
21
- return error instanceof Error ? error.message : String(error);
22
- }
23
-
24
- export function resolveChildCwd(baseCwd: string, childCwd: string | undefined): string {
25
- if (!childCwd) return baseCwd;
26
- return path.isAbsolute(childCwd) ? childCwd : path.resolve(baseCwd, childCwd);
27
- }
28
-
29
- function isNotFoundError(error: unknown): boolean {
30
- return typeof error === "object"
31
- && error !== null
32
- && "code" in error
33
- && (error as NodeJS.ErrnoException).code === "ENOENT";
34
- }
35
-
36
- /**
37
- * Read async job status from disk (with mtime-based caching)
38
- */
39
- export function readStatus(asyncDir: string): AsyncStatus | null {
40
- const statusPath = path.join(asyncDir, "status.json");
41
-
42
- let stat: fs.Stats;
43
- try {
44
- stat = fs.statSync(statusPath);
45
- } catch (error) {
46
- if (isNotFoundError(error)) return null;
47
- throw new Error(`Failed to inspect async status file '${statusPath}': ${getErrorMessage(error)}`, {
48
- cause: error instanceof Error ? error : undefined,
49
- });
50
- }
51
-
52
- const cached = statusCache.get(statusPath);
53
- if (cached && cached.mtime === stat.mtimeMs) {
54
- return cached.status;
55
- }
56
-
57
- let content: string;
58
- try {
59
- content = fs.readFileSync(statusPath, "utf-8");
60
- } catch (error) {
61
- if (isNotFoundError(error)) return null;
62
- throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage(error)}`, {
63
- cause: error instanceof Error ? error : undefined,
64
- });
65
- }
66
-
67
- let status: AsyncStatus;
68
- try {
69
- status = JSON.parse(content) as AsyncStatus;
70
- } catch (error) {
71
- throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage(error)}`, {
72
- cause: error instanceof Error ? error : undefined,
73
- });
74
- }
75
-
76
- statusCache.set(statusPath, { mtime: stat.mtimeMs, status });
77
- if (statusCache.size > 50) {
78
- const firstKey = statusCache.keys().next().value;
79
- if (firstKey) statusCache.delete(firstKey);
80
- }
81
- return status;
82
- }
83
-
84
- const outputTailCache = new Map<string, { mtime: number; size: number; lines: string[] }>();
85
-
86
- /**
87
- * Get the last N lines from an output file (with mtime/size-based caching)
88
- */
89
- export function getOutputTail(outputFile: string | undefined, maxLines: number = 3): string[] {
90
- if (!outputFile) return [];
91
- let fd: number | null = null;
92
- try {
93
- const stat = fs.statSync(outputFile);
94
- if (stat.size === 0) return [];
95
-
96
- const cached = outputTailCache.get(outputFile);
97
- if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) {
98
- return cached.lines;
99
- }
100
-
101
- const tailBytes = 4096;
102
- const start = Math.max(0, stat.size - tailBytes);
103
- fd = fs.openSync(outputFile, "r");
104
- const buffer = Buffer.alloc(Math.min(tailBytes, stat.size));
105
- fs.readSync(fd, buffer, 0, buffer.length, start);
106
- const content = buffer.toString("utf-8");
107
- const allLines = content.split("\n").filter((l) => l.trim());
108
- const lines = allLines.slice(-maxLines).map((l) => l.slice(0, 120) + (l.length > 120 ? "..." : ""));
109
-
110
- outputTailCache.set(outputFile, { mtime: stat.mtimeMs, size: stat.size, lines });
111
- if (outputTailCache.size > 20) {
112
- const firstKey = outputTailCache.keys().next().value;
113
- if (firstKey) outputTailCache.delete(firstKey);
114
- }
115
-
116
- return lines;
117
- } catch {
118
- // Output tails are UI-only hints; unreadable or missing files should render as no tail.
119
- return [];
120
- } finally {
121
- if (fd !== null) {
122
- try {
123
- fs.closeSync(fd);
124
- } catch {
125
- // Closing the best-effort tail file handle should not surface over the main status view.
126
- }
127
- }
128
- }
129
- }
130
-
131
- /**
132
- * Get human-readable last activity time for a file
133
- */
134
- export function getLastActivity(outputFile: string | undefined): string {
135
- if (!outputFile) return "";
136
- try {
137
- const stat = fs.statSync(outputFile);
138
- const ago = Date.now() - stat.mtimeMs;
139
- if (ago < 1000) return "active now";
140
- if (ago < 60000) return `active ${Math.floor(ago / 1000)}s ago`;
141
- return `active ${Math.floor(ago / 60000)}m ago`;
142
- } catch {
143
- // Last-activity text is best effort; missing files should simply omit the hint.
144
- return "";
145
- }
146
- }
147
-
148
- /**
149
- * Find a file/directory by prefix in a directory
150
- */
151
- export function findByPrefix(dir: string, prefix: string, suffix?: string): string | null {
152
- if (!fs.existsSync(dir)) return null;
153
- const entries = fs.readdirSync(dir).filter((entry) => entry.startsWith(prefix));
154
- if (suffix) {
155
- const withSuffix = entries.filter((entry) => entry.endsWith(suffix));
156
- return withSuffix.length > 0 ? path.join(dir, withSuffix.sort()[0]) : null;
157
- }
158
- if (entries.length === 0) return null;
159
- return path.join(dir, entries.sort()[0]);
160
- }
161
-
162
- /**
163
- * Find the latest session file in a directory
164
- */
165
- export function findLatestSessionFile(sessionDir: string): string | null {
166
- if (!fs.existsSync(sessionDir)) return null;
167
- const files = fs.readdirSync(sessionDir)
168
- .filter((f) => f.endsWith(".jsonl"))
169
- .map((f) => {
170
- const filePath = path.join(sessionDir, f);
171
- return {
172
- path: filePath,
173
- mtime: fs.statSync(filePath).mtimeMs,
174
- };
175
- })
176
- .sort((a, b) => b.mtime - a.mtime);
177
- return files.length > 0 ? files[0].path : null;
178
- }
179
-
180
- /**
181
- * Write a prompt to a temporary file
182
- */
183
- export function writePrompt(agent: string, prompt: string): { dir: string; path: string } {
184
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
185
- const p = path.join(dir, `${agent.replace(/[^\w.-]/g, "_")}.md`);
186
- fs.writeFileSync(p, prompt, { mode: 0o600 });
187
- return { dir, path: p };
188
- }
189
-
190
- // ============================================================================
191
- // Message Parsing Utilities
192
- // ============================================================================
193
-
194
- /**
195
- * Get the final text output from a list of messages
196
- */
197
- export function getFinalOutput(messages: Message[]): string {
198
- for (let i = messages.length - 1; i >= 0; i--) {
199
- const msg = messages[i];
200
- if (msg.role === "assistant") {
201
- for (const part of msg.content) {
202
- if (part.type === "text") return part.text;
203
- }
204
- }
205
- }
206
- return "";
207
- }
208
-
209
- export function getSingleResultOutput(result: Pick<SingleResult, "finalOutput" | "messages">): string {
210
- return result.finalOutput ?? getFinalOutput(result.messages ?? []);
211
- }
212
-
213
- /**
214
- * Extract display items (text and tool calls) from messages
215
- */
216
- export function getDisplayItems(messages: Message[] | undefined): DisplayItem[] {
217
- if (!messages || messages.length === 0) return [];
218
- const items: DisplayItem[] = [];
219
- for (const msg of messages) {
220
- if (msg.role === "assistant") {
221
- for (const part of msg.content) {
222
- if (part.type === "text") items.push({ type: "text", text: part.text });
223
- else if (part.type === "toolCall") items.push({ type: "tool", name: part.name, args: part.arguments });
224
- }
225
- }
226
- }
227
- return items;
228
- }
229
-
230
- function compactCompletedProgress(progress: AgentProgress): AgentProgress {
231
- if (progress.status === "running") return progress;
232
- return {
233
- index: progress.index,
234
- agent: progress.agent,
235
- status: progress.status,
236
- activityState: progress.activityState,
237
- task: progress.task,
238
- skills: progress.skills,
239
- toolCount: progress.toolCount,
240
- tokens: progress.tokens,
241
- durationMs: progress.durationMs,
242
- error: progress.error,
243
- failedTool: progress.failedTool,
244
- recentTools: [],
245
- recentOutput: [],
246
- };
247
- }
248
-
249
- export function extractToolCallSummaries(messages: Message[] | undefined): ToolCallSummary[] {
250
- if (!messages?.length) return [];
251
- const summaries: ToolCallSummary[] = [];
252
- for (const msg of messages) {
253
- if (msg.role !== "assistant") continue;
254
- for (const part of msg.content) {
255
- if (part.type !== "toolCall") continue;
256
- const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
257
- ? part.arguments
258
- : {};
259
- summaries.push({
260
- text: formatToolCall(part.name, args),
261
- expandedText: formatToolCall(part.name, args, true),
262
- });
263
- }
264
- }
265
- return summaries;
266
- }
267
-
268
- export function compactForegroundResult(result: SingleResult): SingleResult {
269
- if (result.progress?.status === "running") return result;
270
- const toolCalls = result.toolCalls?.length ? result.toolCalls : extractToolCallSummaries(result.messages);
271
- return {
272
- ...result,
273
- messages: undefined,
274
- progress: undefined,
275
- toolCalls: toolCalls.length ? toolCalls : undefined,
276
- };
277
- }
278
-
279
- export function compactForegroundDetails(details: Details): Details {
280
- return {
281
- ...details,
282
- results: details.results.map(compactForegroundResult),
283
- progress: details.progress
284
- ? details.progress.map(compactCompletedProgress)
285
- : undefined,
286
- };
287
- }
288
-
289
- /**
290
- * Detect errors in subagent execution from messages (only errors with no subsequent success)
291
- */
292
- export function detectSubagentError(messages: Message[]): ErrorInfo {
293
- let lastAssistantTextIndex = -1;
294
- for (let i = messages.length - 1; i >= 0; i--) {
295
- const msg = messages[i];
296
- if (msg.role === "assistant") {
297
- const hasText = Array.isArray(msg.content) && msg.content.some(
298
- (c) => c.type === "text" && "text" in c && typeof c.text === "string" && c.text.trim().length > 0,
299
- );
300
- if (hasText) {
301
- lastAssistantTextIndex = i;
302
- break;
303
- }
304
- }
305
- }
306
-
307
- const scanStart = lastAssistantTextIndex >= 0 ? lastAssistantTextIndex + 1 : 0;
308
-
309
- for (let i = messages.length - 1; i >= scanStart; i--) {
310
- const msg = messages[i];
311
- if (msg.role !== "toolResult") continue;
312
- const toolName = "toolName" in msg && typeof msg.toolName === "string" ? msg.toolName : undefined;
313
- const isError = "isError" in msg && msg.isError === true;
314
-
315
- if (isError) {
316
- const text = msg.content.find((c) => c.type === "text");
317
- const details = text && "text" in text ? text.text : undefined;
318
- const exitMatch = details?.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);
319
- return {
320
- hasError: true,
321
- exitCode: exitMatch ? parseInt(exitMatch[1], 10) : 1,
322
- errorType: toolName || "tool",
323
- details: details?.slice(0, 200),
324
- };
325
- }
326
-
327
- if (toolName !== "bash") continue;
328
-
329
- const text = msg.content.find((c) => c.type === "text");
330
- if (!text || !("text" in text)) continue;
331
- const output = text.text;
332
-
333
- const exitMatch = output.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);
334
- if (exitMatch) {
335
- const code = parseInt(exitMatch[1], 10);
336
- if (code !== 0) {
337
- return { hasError: true, exitCode: code, errorType: "bash", details: output.slice(0, 200) };
338
- }
339
- }
340
-
341
- // NOTE: These patterns can match legitimate output (grep results, logs,
342
- // testing). With the assistant-message check above, most false positives
343
- // are mitigated since the agent will have responded after routine errors.
344
- const fatalPatterns = [
345
- /command not found/i,
346
- /permission denied/i,
347
- /no such file or directory/i,
348
- /segmentation fault/i,
349
- /killed|terminated/i,
350
- /out of memory/i,
351
- /connection refused/i,
352
- /timeout/i,
353
- ];
354
- for (const pattern of fatalPatterns) {
355
- if (pattern.test(output)) {
356
- return { hasError: true, exitCode: 1, errorType: "bash", details: output.slice(0, 200) };
357
- }
358
- }
359
- }
360
-
361
- return { hasError: false };
362
- }
363
-
364
- /**
365
- * Extract a preview of tool arguments for display
366
- */
367
- export function extractToolArgsPreview(args: Record<string, unknown>): string {
368
- const truncatePreview = (value: string, maxLength: number): string =>
369
- value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;
370
-
371
- const stringifyPreviewValue = (value: unknown): string | undefined => {
372
- if (typeof value === "string" && value.trim().length > 0) return value;
373
- if (typeof value === "number" || typeof value === "boolean") return String(value);
374
- return undefined;
375
- };
376
-
377
- const previewArray = (value: unknown): string | undefined => {
378
- if (!Array.isArray(value) || value.length === 0) return undefined;
379
- const first = stringifyPreviewValue(value[0]);
380
- if (!first) return undefined;
381
- const suffix = value.length > 1 ? ` (+${value.length - 1} more)` : "";
382
- return `${first}${suffix}`;
383
- };
384
-
385
- // Handle MCP tool calls - show server/tool info
386
- if (args.tool && typeof args.tool === "string") {
387
- const server = args.server && typeof args.server === "string" ? `${args.server}/` : "";
388
- const toolArgs = args.args && typeof args.args === "string" ? ` ${args.args.slice(0, 40)}` : "";
389
- return `${server}${args.tool}${toolArgs}`;
390
- }
391
-
392
- const queriesPreview = previewArray(args.queries);
393
- if (queriesPreview) return truncatePreview(queriesPreview, 60);
394
- if (typeof args.query === "string" && args.query.trim().length > 0) return truncatePreview(args.query, 60);
395
- if (typeof args.workflow === "string" && args.workflow.trim().length > 0) return `workflow=${truncatePreview(args.workflow, 48)}`;
396
-
397
- if (typeof args.url === "string" && args.url.trim().length > 0) return truncatePreview(args.url, 60);
398
- const urlsPreview = previewArray(args.urls);
399
- if (urlsPreview) return truncatePreview(urlsPreview, 60);
400
- if (typeof args.prompt === "string" && args.prompt.trim().length > 0) return truncatePreview(args.prompt, 60);
401
-
402
- const previewKeys = ["command", "path", "file_path", "pattern", "query", "url", "task", "describe", "search"];
403
- for (const key of previewKeys) {
404
- if (args[key] && typeof args[key] === "string") {
405
- const value = args[key] as string;
406
- return truncatePreview(value, 60);
407
- }
408
- }
409
-
410
- // Fallback: show first string value found
411
- for (const [key, value] of Object.entries(args)) {
412
- const arrayPreview = previewArray(value);
413
- if (arrayPreview) return `${key}=${truncatePreview(arrayPreview, 50)}`;
414
- if (typeof value === "string" && value.length > 0) {
415
- const preview = truncatePreview(value, 50);
416
- return `${key}=${preview}`;
417
- }
418
- }
419
- return "";
420
- }
421
-
422
- /**
423
- * Extract text content from various message content formats
424
- */
425
- export function extractTextFromContent(content: unknown): string {
426
- if (!content) return "";
427
- // Handle string content directly
428
- if (typeof content === "string") return content;
429
- // Handle array content
430
- if (!Array.isArray(content)) return "";
431
- const texts: string[] = [];
432
- for (const part of content) {
433
- if (part && typeof part === "object") {
434
- // Handle { type: "text", text: "..." }
435
- if ("type" in part && part.type === "text" && "text" in part) {
436
- texts.push(String(part.text));
437
- }
438
- // Handle { type: "tool_result", content: "..." }
439
- else if ("type" in part && part.type === "tool_result" && "content" in part) {
440
- const inner = extractTextFromContent(part.content);
441
- if (inner) texts.push(inner);
442
- }
443
- // Handle { text: "..." } without type
444
- else if ("text" in part) {
445
- texts.push(String(part.text));
446
- }
447
- }
448
- }
449
- return texts.join("\n");
450
- }
451
-
452
- // ============================================================================
453
- // Concurrency Utilities
454
- // ============================================================================
455
-
456
- export { mapConcurrent } from "./parallel-utils.ts";