@leing2021/super-pi 0.21.0 → 0.22.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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +157 -357
  3. package/THIRD-PARTY-NOTICES.md +35 -0
  4. package/extensions/subagent/__tests__/async-job-tracker.test.ts +21 -0
  5. package/extensions/subagent/__tests__/execution-activity.test.ts +15 -0
  6. package/extensions/subagent/__tests__/parallel-render-stress.test.ts +82 -0
  7. package/extensions/subagent/__tests__/render-dedup.test.ts +98 -0
  8. package/extensions/subagent/__tests__/render-widget.test.ts +28 -0
  9. package/extensions/subagent/__tests__/throttle.test.ts +90 -0
  10. package/extensions/subagent/agent-management.ts +596 -0
  11. package/extensions/subagent/agent-manager-chain-detail.ts +163 -0
  12. package/extensions/subagent/agent-manager-detail.ts +232 -0
  13. package/extensions/subagent/agent-manager-edit.ts +391 -0
  14. package/extensions/subagent/agent-manager-list.ts +279 -0
  15. package/extensions/subagent/agent-manager-parallel.ts +305 -0
  16. package/extensions/subagent/agent-manager.ts +706 -0
  17. package/extensions/subagent/agent-scope.ts +9 -0
  18. package/extensions/subagent/agent-selection.ts +26 -0
  19. package/extensions/subagent/agent-serializer.ts +124 -0
  20. package/extensions/subagent/agent-templates.ts +63 -0
  21. package/extensions/subagent/agents/context-builder.md +37 -0
  22. package/extensions/subagent/agents/delegate.md +9 -0
  23. package/extensions/subagent/agents/oracle.md +73 -0
  24. package/extensions/subagent/agents/planner.md +52 -0
  25. package/extensions/subagent/agents/researcher.md +50 -0
  26. package/extensions/subagent/agents/reviewer.md +38 -0
  27. package/extensions/subagent/agents/scout.md +48 -0
  28. package/extensions/subagent/agents/worker.md +52 -0
  29. package/extensions/subagent/agents.ts +762 -0
  30. package/extensions/subagent/artifacts.ts +101 -0
  31. package/extensions/subagent/async-execution.ts +521 -0
  32. package/extensions/subagent/async-job-tracker.ts +240 -0
  33. package/extensions/subagent/async-status.ts +242 -0
  34. package/extensions/subagent/chain-clarify.ts +1365 -0
  35. package/extensions/subagent/chain-execution.ts +854 -0
  36. package/extensions/subagent/chain-serializer.ts +127 -0
  37. package/extensions/subagent/completion-dedupe.ts +66 -0
  38. package/extensions/subagent/doctor.ts +201 -0
  39. package/extensions/subagent/execution.ts +748 -0
  40. package/extensions/subagent/file-coalescer.ts +43 -0
  41. package/extensions/subagent/fork-context.ts +64 -0
  42. package/extensions/subagent/formatters.ts +123 -0
  43. package/extensions/subagent/frontmatter.ts +32 -0
  44. package/extensions/subagent/index.ts +586 -0
  45. package/extensions/subagent/intercom-bridge.ts +241 -0
  46. package/extensions/subagent/jsonl-writer.ts +84 -0
  47. package/extensions/subagent/model-fallback.ts +109 -0
  48. package/extensions/subagent/notify.ts +111 -0
  49. package/extensions/subagent/parallel-utils.ts +109 -0
  50. package/extensions/subagent/pi-args.ts +139 -0
  51. package/extensions/subagent/pi-spawn.ts +101 -0
  52. package/extensions/subagent/post-exit-stdio-guard.ts +88 -0
  53. package/extensions/subagent/prompt-template-bridge.ts +400 -0
  54. package/extensions/subagent/prompts/gather-context-and-clarify.md +13 -0
  55. package/extensions/subagent/prompts/parallel-cleanup.md +42 -0
  56. package/extensions/subagent/prompts/parallel-research.md +50 -0
  57. package/extensions/subagent/prompts/parallel-review.md +40 -0
  58. package/extensions/subagent/render-helpers.ts +83 -0
  59. package/extensions/subagent/render.ts +908 -0
  60. package/extensions/subagent/result-intercom.ts +238 -0
  61. package/extensions/subagent/result-watcher.ts +172 -0
  62. package/extensions/subagent/run-history.ts +58 -0
  63. package/extensions/subagent/run-status.ts +137 -0
  64. package/extensions/subagent/schemas.ts +165 -0
  65. package/extensions/subagent/session-tokens.ts +51 -0
  66. package/extensions/subagent/settings.ts +368 -0
  67. package/extensions/subagent/single-output.ts +98 -0
  68. package/extensions/subagent/skills.ts +627 -0
  69. package/extensions/subagent/slash-bridge.ts +177 -0
  70. package/extensions/subagent/slash-commands.ts +304 -0
  71. package/extensions/subagent/slash-live-state.ts +295 -0
  72. package/extensions/subagent/subagent-control.ts +151 -0
  73. package/extensions/subagent/subagent-executor.ts +1915 -0
  74. package/extensions/subagent/subagent-prompt-runtime.ts +76 -0
  75. package/extensions/subagent/subagent-runner.ts +1471 -0
  76. package/extensions/subagent/subagents-status.ts +473 -0
  77. package/extensions/subagent/text-editor.ts +273 -0
  78. package/extensions/subagent/throttle.ts +77 -0
  79. package/extensions/subagent/top-level-async.ts +16 -0
  80. package/extensions/subagent/types.ts +624 -0
  81. package/extensions/subagent/utils.ts +457 -0
  82. package/extensions/subagent/worktree.ts +580 -0
  83. package/extensions/super-pi-extension/index.ts +2 -55
  84. package/package.json +14 -6
  85. package/skills/pi-subagents/SKILL.md +566 -0
@@ -0,0 +1,127 @@
1
+ // SPDX-FileCopyrightText: 2025 Nico Bailon
2
+ // SPDX-License-Identifier: MIT
3
+ // Source: https://github.com/nicobailon/pi-subagents
4
+ import type { ChainConfig, ChainStepConfig } from "./agents.ts";
5
+ import { parseFrontmatter } from "./frontmatter.ts";
6
+
7
+ function parseStepBody(agent: string, sectionBody: string): ChainStepConfig {
8
+ const lines = sectionBody.split("\n");
9
+ const blankIndex = lines.findIndex((line) => line.trim() === "");
10
+ const configLines = blankIndex === -1 ? lines : lines.slice(0, blankIndex);
11
+ const task = (blankIndex === -1 ? "" : lines.slice(blankIndex + 1).join("\n")).trim();
12
+
13
+ const step: ChainStepConfig = { agent, task };
14
+ for (const line of configLines) {
15
+ const match = line.match(/^([\w-]+):\s*(.*)$/);
16
+ if (!match) continue;
17
+ const key = match[1].trim().toLowerCase();
18
+ const rawValue = match[2].trim();
19
+
20
+ if (key === "output") {
21
+ if (rawValue === "false") step.output = false;
22
+ else if (rawValue) step.output = rawValue;
23
+ continue;
24
+ }
25
+ if (key === "reads") {
26
+ if (rawValue === "false") {
27
+ step.reads = false;
28
+ } else {
29
+ const reads = rawValue
30
+ .split(",")
31
+ .map((v) => v.trim())
32
+ .filter(Boolean);
33
+ step.reads = reads.length > 0 ? reads : false;
34
+ }
35
+ continue;
36
+ }
37
+ if (key === "model") {
38
+ if (rawValue) step.model = rawValue;
39
+ continue;
40
+ }
41
+ if (key === "skills") {
42
+ if (rawValue === "false") {
43
+ step.skills = false;
44
+ } else {
45
+ const skills = rawValue
46
+ .split(",")
47
+ .map((v) => v.trim())
48
+ .filter(Boolean);
49
+ step.skills = skills.length > 0 ? skills : false;
50
+ }
51
+ continue;
52
+ }
53
+ if (key === "progress") {
54
+ if (rawValue === "true") step.progress = true;
55
+ else if (rawValue === "false") step.progress = false;
56
+ }
57
+ }
58
+
59
+ return step;
60
+ }
61
+
62
+ export function parseChain(content: string, source: "user" | "project", filePath: string): ChainConfig {
63
+ const { frontmatter, body } = parseFrontmatter(content);
64
+ if (!frontmatter.name || !frontmatter.description) {
65
+ throw new Error("Chain frontmatter must include name and description");
66
+ }
67
+
68
+ const matches = [...body.matchAll(/^##\s+(.+)[^\S\n]*$/gm)];
69
+ const steps: ChainStepConfig[] = [];
70
+
71
+ for (let i = 0; i < matches.length; i++) {
72
+ const match = matches[i]!;
73
+ const agent = match[1]!.trim();
74
+ const lineEndOffset = body[match.index! + match[0].length] === "\n" ? 1 : 0;
75
+ const sectionStart = match.index! + match[0].length + lineEndOffset;
76
+ const sectionEnd = i + 1 < matches.length ? matches[i + 1]!.index! : body.length;
77
+ const sectionBody = body.slice(sectionStart, sectionEnd).trimEnd();
78
+ steps.push(parseStepBody(agent, sectionBody));
79
+ }
80
+
81
+ const extraFields: Record<string, string> = {};
82
+ for (const [key, value] of Object.entries(frontmatter)) {
83
+ if (key === "name" || key === "description") continue;
84
+ extraFields[key] = value;
85
+ }
86
+
87
+ return {
88
+ name: frontmatter.name,
89
+ description: frontmatter.description,
90
+ source,
91
+ filePath,
92
+ steps,
93
+ extraFields: Object.keys(extraFields).length > 0 ? extraFields : undefined,
94
+ };
95
+ }
96
+
97
+ export function serializeChain(config: ChainConfig): string {
98
+ const lines: string[] = [];
99
+ lines.push("---");
100
+ lines.push(`name: ${config.name}`);
101
+ lines.push(`description: ${config.description}`);
102
+ if (config.extraFields) {
103
+ for (const [key, value] of Object.entries(config.extraFields)) {
104
+ lines.push(`${key}: ${value}`);
105
+ }
106
+ }
107
+ lines.push("---");
108
+ lines.push("");
109
+
110
+ for (let i = 0; i < config.steps.length; i++) {
111
+ const step = config.steps[i]!;
112
+ lines.push(`## ${step.agent}`);
113
+ if (step.output === false) lines.push("output: false");
114
+ else if (step.output) lines.push(`output: ${step.output}`);
115
+ if (step.reads === false) lines.push("reads: false");
116
+ else if (Array.isArray(step.reads) && step.reads.length > 0) lines.push(`reads: ${step.reads.join(", ")}`);
117
+ if (step.model) lines.push(`model: ${step.model}`);
118
+ if (step.skills === false) lines.push("skills: false");
119
+ else if (Array.isArray(step.skills) && step.skills.length > 0) lines.push(`skills: ${step.skills.join(", ")}`);
120
+ if (step.progress !== undefined) lines.push(`progress: ${step.progress ? "true" : "false"}`);
121
+ lines.push("");
122
+ lines.push(step.task ?? "");
123
+ if (i < config.steps.length - 1) lines.push("");
124
+ }
125
+
126
+ return `${lines.join("\n")}\n`;
127
+ }
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: 2025 Nico Bailon
2
+ // SPDX-License-Identifier: MIT
3
+ // Source: https://github.com/nicobailon/pi-subagents
4
+ interface CompletionDataLike {
5
+ id?: unknown;
6
+ agent?: unknown;
7
+ timestamp?: unknown;
8
+ sessionId?: unknown;
9
+ taskIndex?: unknown;
10
+ totalTasks?: unknown;
11
+ success?: unknown;
12
+ }
13
+
14
+ function asNonEmptyString(value: unknown): string | undefined {
15
+ if (typeof value !== "string") return undefined;
16
+ const trimmed = value.trim();
17
+ return trimmed.length > 0 ? trimmed : undefined;
18
+ }
19
+
20
+ function asFiniteNumber(value: unknown): number | undefined {
21
+ if (typeof value !== "number") return undefined;
22
+ return Number.isFinite(value) ? value : undefined;
23
+ }
24
+
25
+ export function buildCompletionKey(data: CompletionDataLike, fallback: string): string {
26
+ const id = asNonEmptyString(data.id);
27
+ if (id) return `id:${id}`;
28
+ const sessionId = asNonEmptyString(data.sessionId) ?? "no-session";
29
+ const agent = asNonEmptyString(data.agent) ?? "unknown";
30
+ const timestamp = asFiniteNumber(data.timestamp);
31
+ const taskIndex = asFiniteNumber(data.taskIndex);
32
+ const totalTasks = asFiniteNumber(data.totalTasks);
33
+ const success = typeof data.success === "boolean" ? (data.success ? "1" : "0") : "?";
34
+ return [
35
+ "meta",
36
+ sessionId,
37
+ agent,
38
+ timestamp !== undefined ? String(timestamp) : "no-ts",
39
+ taskIndex !== undefined ? String(taskIndex) : "-",
40
+ totalTasks !== undefined ? String(totalTasks) : "-",
41
+ success,
42
+ fallback,
43
+ ].join(":");
44
+ }
45
+
46
+ export function pruneSeenMap(seen: Map<string, number>, now: number, ttlMs: number): void {
47
+ for (const [key, ts] of seen.entries()) {
48
+ if (now - ts > ttlMs) seen.delete(key);
49
+ }
50
+ }
51
+
52
+ export function markSeenWithTtl(seen: Map<string, number>, key: string, now: number, ttlMs: number): boolean {
53
+ pruneSeenMap(seen, now, ttlMs);
54
+ if (seen.has(key)) return true;
55
+ seen.set(key, now);
56
+ return false;
57
+ }
58
+
59
+ export function getGlobalSeenMap(storeKey: string): Map<string, number> {
60
+ const globalStore = globalThis as Record<string, unknown>;
61
+ const existing = globalStore[storeKey];
62
+ if (existing instanceof Map) return existing as Map<string, number>;
63
+ const map = new Map<string, number>();
64
+ globalStore[storeKey] = map;
65
+ return map;
66
+ }
@@ -0,0 +1,201 @@
1
+ // SPDX-FileCopyrightText: 2025 Nico Bailon
2
+ // SPDX-License-Identifier: MIT
3
+ // Source: https://github.com/nicobailon/pi-subagents
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { discoverAgentsAll, type AgentSource } from "./agents.ts";
7
+ import { isAsyncAvailable } from "./async-execution.ts";
8
+ import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "./intercom-bridge.ts";
9
+ import { discoverAvailableSkills, type SkillSource } from "./skills.ts";
10
+ import {
11
+ ASYNC_DIR,
12
+ CHAIN_RUNS_DIR,
13
+ RESULTS_DIR,
14
+ TEMP_ROOT_DIR,
15
+ type ExtensionConfig,
16
+ type SubagentState,
17
+ } from "./types.ts";
18
+
19
+ interface DoctorPaths {
20
+ tempRootDir: string;
21
+ asyncDir: string;
22
+ resultsDir: string;
23
+ chainRunsDir: string;
24
+ }
25
+
26
+ interface DoctorDeps {
27
+ isAsyncAvailable: () => boolean;
28
+ discoverAgentsAll: typeof discoverAgentsAll;
29
+ discoverAvailableSkills: typeof discoverAvailableSkills;
30
+ diagnoseIntercomBridge: typeof diagnoseIntercomBridge;
31
+ }
32
+
33
+ export interface DoctorReportInput {
34
+ cwd: string;
35
+ config: ExtensionConfig;
36
+ state: SubagentState;
37
+ context?: "fresh" | "fork";
38
+ requestedSessionDir?: string;
39
+ currentSessionFile?: string | null;
40
+ currentSessionId?: string | null;
41
+ orchestratorTarget?: string;
42
+ sessionError?: string;
43
+ expandTilde?: (value: string) => string;
44
+ paths?: DoctorPaths;
45
+ deps?: Partial<DoctorDeps>;
46
+ }
47
+
48
+ const DEFAULT_PATHS: DoctorPaths = {
49
+ tempRootDir: TEMP_ROOT_DIR,
50
+ asyncDir: ASYNC_DIR,
51
+ resultsDir: RESULTS_DIR,
52
+ chainRunsDir: CHAIN_RUNS_DIR,
53
+ };
54
+
55
+ const DEFAULT_DEPS: DoctorDeps = {
56
+ isAsyncAvailable,
57
+ discoverAgentsAll,
58
+ discoverAvailableSkills,
59
+ diagnoseIntercomBridge,
60
+ };
61
+
62
+ function errorText(error: unknown): string {
63
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
64
+ }
65
+
66
+ function lineFromCheck(label: string, check: () => string): string {
67
+ try {
68
+ return check();
69
+ } catch (error) {
70
+ return `- ${label}: failed — ${errorText(error)}`;
71
+ }
72
+ }
73
+
74
+ function formatExistingDirectory(label: string, dirPath: string): string {
75
+ try {
76
+ if (!fs.existsSync(dirPath)) return `- ${label}: missing (${dirPath})`;
77
+ const stats = fs.statSync(dirPath);
78
+ if (!stats.isDirectory()) throw new Error(`not a directory: ${dirPath}`);
79
+ fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK);
80
+ return `- ${label}: ok (${dirPath})`;
81
+ } catch (error) {
82
+ return `- ${label}: failed (${dirPath}) — ${errorText(error)}`;
83
+ }
84
+ }
85
+
86
+ function formatSourceCounts(counts: Record<AgentSource, number>): string {
87
+ return `builtin ${counts.builtin}, user ${counts.user}, project ${counts.project}`;
88
+ }
89
+
90
+ function formatSkillSourceCounts(skills: Array<{ source: SkillSource }>): string {
91
+ const counts = new Map<SkillSource, number>();
92
+ for (const skill of skills) counts.set(skill.source, (counts.get(skill.source) ?? 0) + 1);
93
+ const ordered: SkillSource[] = [
94
+ "project",
95
+ "project-settings",
96
+ "project-package",
97
+ "user",
98
+ "user-settings",
99
+ "user-package",
100
+ "extension",
101
+ "builtin",
102
+ "unknown",
103
+ ];
104
+ const parts = ordered
105
+ .map((source) => `${source} ${counts.get(source) ?? 0}`)
106
+ .filter((part) => !part.endsWith(" 0"));
107
+ return parts.length > 0 ? parts.join(", ") : "none";
108
+ }
109
+
110
+ function formatConfiguredSessionDir(input: DoctorReportInput): string {
111
+ if (input.requestedSessionDir) {
112
+ return path.resolve(input.expandTilde?.(input.requestedSessionDir) ?? input.requestedSessionDir);
113
+ }
114
+ if (input.config.defaultSessionDir) {
115
+ return path.resolve(input.expandTilde?.(input.config.defaultSessionDir) ?? input.config.defaultSessionDir);
116
+ }
117
+ return "not configured";
118
+ }
119
+
120
+ function formatSessionLines(input: DoctorReportInput): string[] {
121
+ const sessionFile = input.currentSessionFile ?? null;
122
+ const lines = [
123
+ lineFromCheck("configured session dir", () => `- configured session dir: ${formatConfiguredSessionDir(input)}`),
124
+ `- current session file: ${sessionFile ?? "not available"}`,
125
+ `- current session dir: ${sessionFile ? path.dirname(sessionFile) : "not available"}`,
126
+ `- current session id: ${input.currentSessionId ?? input.state.currentSessionId ?? "not available"}`,
127
+ ];
128
+ if (input.sessionError) lines.push(`- session manager: failed — ${input.sessionError}`);
129
+ return lines;
130
+ }
131
+
132
+ function formatDiscovery(input: DoctorReportInput, deps: DoctorDeps): string[] {
133
+ return [
134
+ lineFromCheck("agents/chains", () => {
135
+ const discovered = deps.discoverAgentsAll(input.cwd);
136
+ const agentCounts = {
137
+ builtin: discovered.builtin.length,
138
+ user: discovered.user.length,
139
+ project: discovered.project.length,
140
+ };
141
+ const chainCounts = discovered.chains.reduce<Record<AgentSource, number>>((counts, chain) => {
142
+ counts[chain.source] += 1;
143
+ return counts;
144
+ }, { builtin: 0, user: 0, project: 0 });
145
+ return [
146
+ `- agents: total ${agentCounts.builtin + agentCounts.user + agentCounts.project} (${formatSourceCounts(agentCounts)})`,
147
+ `- chains: total ${discovered.chains.length} (${formatSourceCounts(chainCounts)})`,
148
+ ].join("\n");
149
+ }),
150
+ lineFromCheck("skills", () => {
151
+ const skills = deps.discoverAvailableSkills(input.cwd);
152
+ return `- skills: total ${skills.length} (${formatSkillSourceCounts(skills)})`;
153
+ }),
154
+ ];
155
+ }
156
+
157
+ function formatIntercomDiagnostic(diagnostic: IntercomBridgeDiagnostic, context: "fresh" | "fork" | undefined): string[] {
158
+ const lines = [
159
+ `- bridge: ${diagnostic.active ? "active" : "inactive"}${diagnostic.reason ? ` (${diagnostic.reason})` : ""}`,
160
+ `- mode: ${diagnostic.mode}; context: ${context ?? "unspecified"}`,
161
+ `- orchestrator target: ${diagnostic.orchestratorTarget ?? "not available"}`,
162
+ `- pi-intercom: ${diagnostic.piIntercomAvailable ? "available" : "unavailable"} at ${diagnostic.extensionDir}`,
163
+ ];
164
+ if (diagnostic.configPath && diagnostic.intercomConfigEnabled !== undefined) {
165
+ lines.push(`- intercom config: ${diagnostic.intercomConfigEnabled === false ? "disabled" : "enabled or absent"} (${diagnostic.configPath})`);
166
+ }
167
+ if (diagnostic.intercomConfigError) {
168
+ lines.push(`- intercom config warning: ${diagnostic.intercomConfigError}; runtime assumes enabled`);
169
+ }
170
+ return lines;
171
+ }
172
+
173
+ export function buildDoctorReport(input: DoctorReportInput): string {
174
+ const paths = input.paths ?? DEFAULT_PATHS;
175
+ const deps = { ...DEFAULT_DEPS, ...input.deps };
176
+ const lines = [
177
+ "Subagents doctor report",
178
+ "",
179
+ "Runtime",
180
+ `- cwd: ${input.cwd}`,
181
+ lineFromCheck("async support", () => `- async support: ${deps.isAsyncAvailable() ? "available" : "unavailable"}`),
182
+ ...formatSessionLines(input),
183
+ "",
184
+ "Filesystem",
185
+ formatExistingDirectory("temp root", paths.tempRootDir),
186
+ formatExistingDirectory("async runs", paths.asyncDir),
187
+ formatExistingDirectory("results", paths.resultsDir),
188
+ formatExistingDirectory("chain runs", paths.chainRunsDir),
189
+ "",
190
+ "Discovery",
191
+ ...formatDiscovery(input, deps),
192
+ "",
193
+ "Intercom bridge",
194
+ ...lineFromCheck("intercom bridge", () => formatIntercomDiagnostic(deps.diagnoseIntercomBridge({
195
+ config: input.config.intercomBridge,
196
+ context: input.context,
197
+ orchestratorTarget: input.orchestratorTarget,
198
+ }), input.context).join("\n")).split("\n"),
199
+ ];
200
+ return lines.join("\n");
201
+ }