@leing2021/super-pi 0.22.1 → 0.23.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 (117) hide show
  1. package/README.md +66 -293
  2. package/extensions/ce-core/index.ts +276 -48
  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 -20
  6. package/rules/common/naming.md +154 -0
  7. package/skills/01-brainstorm/SKILL.md +42 -79
  8. package/skills/01-brainstorm/references/ce-brainstorm-mode.md +47 -0
  9. package/skills/02-plan/SKILL.md +43 -61
  10. package/skills/02-plan/references/solution-search.md +46 -0
  11. package/skills/03-work/SKILL.md +34 -52
  12. package/skills/03-work/references/completion-report.md +51 -0
  13. package/skills/04-review/SKILL.md +44 -51
  14. package/skills/04-review/references/solution-search.md +46 -0
  15. package/skills/06-next/SKILL.md +35 -20
  16. package/skills/06-next/references/recommendation-logic.md +47 -2
  17. package/skills/07-worktree/SKILL.md +21 -20
  18. package/skills/08-help/SKILL.md +46 -0
  19. package/skills/08-help/references/workflow-sequence.md +135 -0
  20. package/skills/references/language-detection.md +44 -0
  21. package/LICENSE +0 -21
  22. package/THIRD-PARTY-NOTICES.md +0 -35
  23. package/extensions/subagent/__tests__/async-job-tracker.test.ts +0 -21
  24. package/extensions/subagent/__tests__/execution-activity.test.ts +0 -15
  25. package/extensions/subagent/__tests__/parallel-render-stress.test.ts +0 -82
  26. package/extensions/subagent/__tests__/render-dedup.test.ts +0 -98
  27. package/extensions/subagent/__tests__/render-widget.test.ts +0 -28
  28. package/extensions/subagent/__tests__/throttle.test.ts +0 -90
  29. package/extensions/subagent/agent-management.ts +0 -596
  30. package/extensions/subagent/agent-manager-chain-detail.ts +0 -163
  31. package/extensions/subagent/agent-manager-detail.ts +0 -232
  32. package/extensions/subagent/agent-manager-edit.ts +0 -391
  33. package/extensions/subagent/agent-manager-list.ts +0 -279
  34. package/extensions/subagent/agent-manager-parallel.ts +0 -305
  35. package/extensions/subagent/agent-manager.ts +0 -706
  36. package/extensions/subagent/agent-scope.ts +0 -9
  37. package/extensions/subagent/agent-selection.ts +0 -26
  38. package/extensions/subagent/agent-serializer.ts +0 -124
  39. package/extensions/subagent/agent-templates.ts +0 -63
  40. package/extensions/subagent/agents/context-builder.md +0 -37
  41. package/extensions/subagent/agents/delegate.md +0 -9
  42. package/extensions/subagent/agents/oracle.md +0 -73
  43. package/extensions/subagent/agents/planner.md +0 -52
  44. package/extensions/subagent/agents/researcher.md +0 -50
  45. package/extensions/subagent/agents/reviewer.md +0 -38
  46. package/extensions/subagent/agents/scout.md +0 -48
  47. package/extensions/subagent/agents/worker.md +0 -52
  48. package/extensions/subagent/agents.ts +0 -762
  49. package/extensions/subagent/artifacts.ts +0 -101
  50. package/extensions/subagent/async-execution.ts +0 -521
  51. package/extensions/subagent/async-job-tracker.ts +0 -240
  52. package/extensions/subagent/async-status.ts +0 -242
  53. package/extensions/subagent/chain-clarify.ts +0 -1365
  54. package/extensions/subagent/chain-execution.ts +0 -854
  55. package/extensions/subagent/chain-serializer.ts +0 -127
  56. package/extensions/subagent/completion-dedupe.ts +0 -66
  57. package/extensions/subagent/doctor.ts +0 -201
  58. package/extensions/subagent/execution.ts +0 -748
  59. package/extensions/subagent/file-coalescer.ts +0 -43
  60. package/extensions/subagent/fork-context.ts +0 -64
  61. package/extensions/subagent/formatters.ts +0 -123
  62. package/extensions/subagent/frontmatter.ts +0 -32
  63. package/extensions/subagent/index.ts +0 -586
  64. package/extensions/subagent/intercom-bridge.ts +0 -241
  65. package/extensions/subagent/jsonl-writer.ts +0 -84
  66. package/extensions/subagent/model-fallback.ts +0 -109
  67. package/extensions/subagent/notify.ts +0 -111
  68. package/extensions/subagent/parallel-utils.ts +0 -109
  69. package/extensions/subagent/pi-args.ts +0 -139
  70. package/extensions/subagent/pi-spawn.ts +0 -101
  71. package/extensions/subagent/post-exit-stdio-guard.ts +0 -88
  72. package/extensions/subagent/prompt-template-bridge.ts +0 -400
  73. package/extensions/subagent/prompts/gather-context-and-clarify.md +0 -13
  74. package/extensions/subagent/prompts/parallel-cleanup.md +0 -42
  75. package/extensions/subagent/prompts/parallel-research.md +0 -50
  76. package/extensions/subagent/prompts/parallel-review.md +0 -40
  77. package/extensions/subagent/render-helpers.ts +0 -83
  78. package/extensions/subagent/render.ts +0 -908
  79. package/extensions/subagent/result-intercom.ts +0 -238
  80. package/extensions/subagent/result-watcher.ts +0 -172
  81. package/extensions/subagent/run-history.ts +0 -58
  82. package/extensions/subagent/run-status.ts +0 -137
  83. package/extensions/subagent/schemas.ts +0 -165
  84. package/extensions/subagent/session-tokens.ts +0 -51
  85. package/extensions/subagent/settings.ts +0 -368
  86. package/extensions/subagent/single-output.ts +0 -98
  87. package/extensions/subagent/skills.ts +0 -627
  88. package/extensions/subagent/slash-bridge.ts +0 -177
  89. package/extensions/subagent/slash-commands.ts +0 -304
  90. package/extensions/subagent/slash-live-state.ts +0 -295
  91. package/extensions/subagent/subagent-control.ts +0 -151
  92. package/extensions/subagent/subagent-executor.ts +0 -1915
  93. package/extensions/subagent/subagent-prompt-runtime.ts +0 -76
  94. package/extensions/subagent/subagent-runner.ts +0 -1471
  95. package/extensions/subagent/subagents-status.ts +0 -473
  96. package/extensions/subagent/text-editor.ts +0 -273
  97. package/extensions/subagent/throttle.ts +0 -77
  98. package/extensions/subagent/top-level-async.ts +0 -16
  99. package/extensions/subagent/types.ts +0 -624
  100. package/extensions/subagent/utils.ts +0 -457
  101. package/extensions/subagent/worktree.ts +0 -580
  102. package/extensions/super-pi-extension/agents/ce-oracle.md +0 -109
  103. package/extensions/super-pi-extension/agents/ce-planner.md +0 -116
  104. package/extensions/super-pi-extension/agents/ce-reviewer.md +0 -99
  105. package/extensions/super-pi-extension/agents/ce-scout.md +0 -80
  106. package/extensions/super-pi-extension/agents/ce-worker.md +0 -78
  107. package/extensions/super-pi-extension/chains/ce-parallel-review.chain.md +0 -34
  108. package/extensions/super-pi-extension/chains/ce-review-only.chain.md +0 -12
  109. package/extensions/super-pi-extension/chains/ce-standard.chain.md +0 -28
  110. package/extensions/super-pi-extension/index.ts +0 -129
  111. package/extensions/super-pi-extension/model-sync.ts +0 -204
  112. package/skills/08-status/SKILL.md +0 -41
  113. package/skills/08-status/references/artifact-locations.md +0 -10
  114. package/skills/09-help/SKILL.md +0 -37
  115. package/skills/09-help/references/workflow-sequence.md +0 -9
  116. package/skills/10-rules/SKILL.md +0 -76
  117. package/skills/pi-subagents/SKILL.md +0 -566
@@ -1,238 +0,0 @@
1
- // SPDX-FileCopyrightText: 2025 Nico Bailon
2
- // SPDX-License-Identifier: MIT
3
- // Source: https://github.com/nicobailon/pi-subagents
4
- import { randomUUID } from "node:crypto";
5
- import {
6
- type Details,
7
- type IntercomEventBus,
8
- type SingleResult,
9
- type SubagentResultIntercomChild,
10
- type SubagentResultIntercomPayload,
11
- type SubagentResultStatus,
12
- SUBAGENT_RESULT_INTERCOM_DELIVERY_EVENT,
13
- SUBAGENT_RESULT_INTERCOM_EVENT,
14
- } from "./types.ts";
15
-
16
- export function resolveSubagentResultStatus(input: {
17
- exitCode?: number;
18
- success?: boolean;
19
- state?: string;
20
- interrupted?: boolean;
21
- detached?: boolean;
22
- }): SubagentResultStatus {
23
- if (input.detached) return "detached";
24
- if (input.interrupted || input.state === "paused") return "paused";
25
- if (typeof input.success === "boolean") return input.success ? "completed" : "failed";
26
- if (input.state === "complete") return "completed";
27
- if (input.state === "failed") return "failed";
28
- if (typeof input.exitCode === "number") return input.exitCode === 0 ? "completed" : "failed";
29
- return "failed";
30
- }
31
-
32
- function countStatuses(children: SubagentResultIntercomChild[]): Record<SubagentResultStatus, number> {
33
- const counts: Record<SubagentResultStatus, number> = {
34
- completed: 0,
35
- failed: 0,
36
- paused: 0,
37
- detached: 0,
38
- };
39
- for (const child of children) {
40
- counts[child.status] += 1;
41
- }
42
- return counts;
43
- }
44
-
45
- function formatStatusCounts(counts: Record<SubagentResultStatus, number>): string {
46
- const parts = [
47
- counts.completed ? `${counts.completed} completed` : undefined,
48
- counts.failed ? `${counts.failed} failed` : undefined,
49
- counts.paused ? `${counts.paused} paused` : undefined,
50
- counts.detached ? `${counts.detached} detached` : undefined,
51
- ].filter((part): part is string => Boolean(part));
52
- return parts.length ? parts.join(", ") : "0 results";
53
- }
54
-
55
- function resolveGroupedStatus(children: SubagentResultIntercomChild[]): SubagentResultStatus {
56
- const counts = countStatuses(children);
57
- if (counts.failed > 0) return "failed";
58
- if (counts.paused > 0) return "paused";
59
- if (counts.completed > 0) return "completed";
60
- if (counts.detached > 0) return "detached";
61
- return "failed";
62
- }
63
-
64
- export interface GroupedResultIntercomMessageInput {
65
- to: string;
66
- runId: string;
67
- mode: "single" | "parallel" | "chain";
68
- source: "foreground" | "async";
69
- children: SubagentResultIntercomChild[];
70
- asyncId?: string;
71
- asyncDir?: string;
72
- chainSteps?: number;
73
- }
74
-
75
- export function formatSubagentResultIntercomMessage(input: {
76
- runId: string;
77
- mode: "single" | "parallel" | "chain";
78
- status: SubagentResultStatus;
79
- children: SubagentResultIntercomChild[];
80
- asyncId?: string;
81
- asyncDir?: string;
82
- chainSteps?: number;
83
- }): string {
84
- const counts = countStatuses(input.children);
85
- const lines: string[] = [
86
- "subagent results",
87
- "",
88
- `Run: ${input.runId}`,
89
- `Mode: ${input.mode}`,
90
- `Status: ${input.status}`,
91
- `Children: ${formatStatusCounts(counts)}`,
92
- ];
93
- if (input.mode === "chain" && typeof input.chainSteps === "number") {
94
- lines.push(`Chain steps: ${input.chainSteps}`);
95
- }
96
- if (input.asyncId) lines.push(`Async id: ${input.asyncId}`);
97
- if (input.asyncDir) lines.push(`Async dir: ${input.asyncDir}`);
98
- if (input.children.some((child) => child.intercomTarget)) {
99
- lines.push("");
100
- lines.push("For clarification, message a listed subagent at its Intercom target.");
101
- }
102
-
103
- for (let index = 0; index < input.children.length; index++) {
104
- const child = input.children[index]!;
105
- lines.push("");
106
- lines.push(`${index + 1}. ${child.agent} — ${child.status}`);
107
- if (child.intercomTarget) lines.push(`Intercom target: ${child.intercomTarget}`);
108
- if (child.artifactPath) lines.push(`Output artifact: ${child.artifactPath}`);
109
- if (child.sessionPath) lines.push(`Session: ${child.sessionPath}`);
110
- lines.push("Summary:");
111
- lines.push(child.summary);
112
- }
113
-
114
- return lines.join("\n");
115
- }
116
-
117
- export function buildSubagentResultIntercomPayload(input: GroupedResultIntercomMessageInput): SubagentResultIntercomPayload {
118
- const children = input.children.map((child) => ({
119
- ...child,
120
- summary: child.summary.trim() || "(no output)",
121
- }));
122
- const status = resolveGroupedStatus(children);
123
- const summary = formatStatusCounts(countStatuses(children));
124
- const firstChild = children[0];
125
- const payload: SubagentResultIntercomPayload = {
126
- to: input.to,
127
- runId: input.runId,
128
- mode: input.mode,
129
- status,
130
- summary,
131
- source: input.source,
132
- children,
133
- ...(input.asyncId ? { asyncId: input.asyncId } : {}),
134
- ...(input.asyncDir ? { asyncDir: input.asyncDir } : {}),
135
- ...(typeof input.chainSteps === "number" ? { chainSteps: input.chainSteps } : {}),
136
- ...(firstChild?.agent ? { agent: firstChild.agent } : {}),
137
- ...(firstChild?.index !== undefined ? { index: firstChild.index } : {}),
138
- ...(firstChild?.artifactPath ? { artifactPath: firstChild.artifactPath } : {}),
139
- ...(firstChild?.sessionPath ? { sessionPath: firstChild.sessionPath } : {}),
140
- message: "",
141
- };
142
- payload.message = formatSubagentResultIntercomMessage(payload);
143
- return payload;
144
- }
145
-
146
- export async function deliverSubagentResultIntercomEvent(
147
- events: IntercomEventBus,
148
- payload: SubagentResultIntercomPayload,
149
- timeoutMs = 500,
150
- ): Promise<boolean> {
151
- if (typeof events.on !== "function" || typeof events.emit !== "function") return false;
152
- const requestId = payload.requestId ?? randomUUID();
153
- return new Promise((resolve) => {
154
- let settled = false;
155
- let unsubscribe: (() => void) | undefined;
156
- let timer: ReturnType<typeof setTimeout> | undefined;
157
- const finish = (delivered: boolean) => {
158
- if (settled) return;
159
- settled = true;
160
- if (timer) clearTimeout(timer);
161
- unsubscribe?.();
162
- resolve(delivered);
163
- };
164
- unsubscribe = events.on(SUBAGENT_RESULT_INTERCOM_DELIVERY_EVENT, (data) => {
165
- if (!data || typeof data !== "object") return;
166
- const delivery = data as { requestId?: unknown; delivered?: unknown };
167
- if (delivery.requestId !== requestId) return;
168
- finish(delivery.delivered === true);
169
- });
170
- timer = setTimeout(() => finish(false), timeoutMs);
171
- try {
172
- events.emit(SUBAGENT_RESULT_INTERCOM_EVENT, { ...payload, requestId });
173
- } catch {
174
- finish(false);
175
- }
176
- });
177
- }
178
-
179
- function stripSingleResultOutputs(result: SingleResult): SingleResult {
180
- return {
181
- ...result,
182
- messages: undefined,
183
- finalOutput: undefined,
184
- truncation: undefined,
185
- };
186
- }
187
-
188
- export function stripDetailsOutputsForIntercomReceipt(details: Details): Details {
189
- return {
190
- ...details,
191
- results: details.results.map(stripSingleResultOutputs),
192
- };
193
- }
194
-
195
- export function formatSubagentResultReceipt(input: {
196
- mode: "single" | "parallel" | "chain";
197
- runId: string;
198
- payload: SubagentResultIntercomPayload;
199
- }): string {
200
- const counts = countStatuses(input.payload.children);
201
- const modeLabel = input.mode === "single"
202
- ? "single subagent result"
203
- : input.mode === "parallel"
204
- ? "parallel subagent results"
205
- : "chain subagent results";
206
- const lines = [
207
- `Delivered ${modeLabel} via intercom.`,
208
- `Run: ${input.runId}`,
209
- `Children: ${formatStatusCounts(counts)}`,
210
- ];
211
-
212
- const artifacts = input.payload.children.filter((child) => typeof child.artifactPath === "string");
213
- if (artifacts.length > 0) {
214
- lines.push("Artifacts:");
215
- for (const child of artifacts) {
216
- lines.push(`- ${child.agent} [${child.status}]: ${child.artifactPath}`);
217
- }
218
- }
219
-
220
- const intercomTargets = input.payload.children.filter((child) => typeof child.intercomTarget === "string");
221
- if (intercomTargets.length > 0) {
222
- lines.push("Intercom targets:");
223
- for (const child of intercomTargets) {
224
- lines.push(`- ${child.agent} [${child.status}]: ${child.intercomTarget}`);
225
- }
226
- }
227
-
228
- const sessions = input.payload.children.filter((child) => typeof child.sessionPath === "string");
229
- if (sessions.length > 0) {
230
- lines.push("Sessions:");
231
- for (const child of sessions) {
232
- lines.push(`- ${child.agent} [${child.status}]: ${child.sessionPath}`);
233
- }
234
- }
235
-
236
- lines.push("Full grouped output was sent over intercom.");
237
- return lines.join("\n");
238
- }
@@ -1,172 +0,0 @@
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 type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
7
- import { buildCompletionKey, markSeenWithTtl } from "./completion-dedupe.ts";
8
- import { createFileCoalescer } from "./file-coalescer.ts";
9
- import {
10
- SUBAGENT_ASYNC_COMPLETE_EVENT,
11
- type SubagentState,
12
- } from "./types.ts";
13
- import {
14
- buildSubagentResultIntercomPayload,
15
- deliverSubagentResultIntercomEvent,
16
- resolveSubagentResultStatus,
17
- } from "./result-intercom.ts";
18
-
19
- function isNotFoundError(error: unknown): boolean {
20
- return typeof error === "object"
21
- && error !== null
22
- && "code" in error
23
- && (error as NodeJS.ErrnoException).code === "ENOENT";
24
- }
25
-
26
- export function createResultWatcher(
27
- pi: ExtensionAPI,
28
- state: SubagentState,
29
- resultsDir: string,
30
- completionTtlMs: number,
31
- ): {
32
- startResultWatcher: () => void;
33
- primeExistingResults: () => void;
34
- stopResultWatcher: () => void;
35
- } {
36
- const handleResult = async (file: string) => {
37
- const resultPath = path.join(resultsDir, file);
38
- if (!fs.existsSync(resultPath)) return;
39
- try {
40
- const data = JSON.parse(fs.readFileSync(resultPath, "utf-8")) as {
41
- id?: string;
42
- runId?: string;
43
- agent?: string;
44
- success?: boolean;
45
- state?: string;
46
- mode?: string;
47
- summary?: string;
48
- results?: Array<{
49
- agent?: string;
50
- output?: string;
51
- success?: boolean;
52
- artifactPaths?: { outputPath?: string };
53
- intercomTarget?: string;
54
- }>;
55
- sessionId?: string;
56
- cwd?: string;
57
- sessionFile?: string;
58
- asyncDir?: string;
59
- intercomTarget?: string;
60
- };
61
- if (data.sessionId && data.sessionId !== state.currentSessionId) return;
62
- if (!data.sessionId && data.cwd && data.cwd !== state.baseCwd) return;
63
-
64
- const now = Date.now();
65
- const completionKey = buildCompletionKey(data, `result:${file}`);
66
- if (markSeenWithTtl(state.completionSeen, completionKey, now, completionTtlMs)) {
67
- fs.unlinkSync(resultPath);
68
- return;
69
- }
70
-
71
- const intercomTarget = data.intercomTarget?.trim();
72
- if (intercomTarget) {
73
- const childResults = Array.isArray(data.results) && data.results.length > 0
74
- ? data.results
75
- : [{
76
- agent: data.agent,
77
- output: data.summary,
78
- success: data.success,
79
- }];
80
- const runId = data.runId ?? data.id ?? file.replace(/\.json$/i, "");
81
- const mode = data.mode === "single" || data.mode === "parallel" || data.mode === "chain"
82
- ? data.mode
83
- : childResults.length > 1 ? "chain" : "single";
84
- const payload = buildSubagentResultIntercomPayload({
85
- to: intercomTarget,
86
- runId,
87
- mode,
88
- source: "async",
89
- children: childResults.map((result = {}, index) => ({
90
- agent: result.agent ?? data.agent ?? `step-${index + 1}`,
91
- status: resolveSubagentResultStatus({
92
- success: result.success,
93
- state: data.state === "paused" || typeof result.success !== "boolean" ? data.state : undefined,
94
- }),
95
- summary: result.output ?? data.summary ?? "(no output)",
96
- index,
97
- artifactPath: result.artifactPaths?.outputPath,
98
- sessionPath: data.sessionFile,
99
- intercomTarget: result.intercomTarget,
100
- })),
101
- asyncId: data.id,
102
- asyncDir: data.asyncDir,
103
- });
104
- const delivered = await deliverSubagentResultIntercomEvent(pi.events, payload);
105
- if (!delivered) {
106
- console.error(`Subagent async grouped result intercom delivery was not acknowledged for '${resultPath}'.`);
107
- }
108
- }
109
-
110
- pi.events.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, data);
111
- fs.unlinkSync(resultPath);
112
- } catch (error) {
113
- if (isNotFoundError(error)) return;
114
- console.error(`Failed to process subagent result file '${resultPath}':`, error);
115
- }
116
- };
117
-
118
- state.resultFileCoalescer = createFileCoalescer((file) => {
119
- void handleResult(file);
120
- }, 50);
121
-
122
- const scheduleRestart = () => {
123
- state.watcherRestartTimer = setTimeout(() => {
124
- try {
125
- fs.mkdirSync(resultsDir, { recursive: true });
126
- startResultWatcher();
127
- } catch (error) {
128
- console.error(`Failed to restart subagent result watcher for '${resultsDir}':`, error);
129
- }
130
- }, 3000);
131
- };
132
-
133
- const startResultWatcher = () => {
134
- state.watcherRestartTimer = null;
135
- try {
136
- state.watcher = fs.watch(resultsDir, (ev, file) => {
137
- if (ev !== "rename" || !file) return;
138
- const fileName = file.toString();
139
- if (!fileName.endsWith(".json")) return;
140
- state.resultFileCoalescer.schedule(fileName);
141
- });
142
- state.watcher.on("error", (error) => {
143
- console.error(`Subagent result watcher failed for '${resultsDir}':`, error);
144
- state.watcher = null;
145
- scheduleRestart();
146
- });
147
- state.watcher.unref?.();
148
- } catch (error) {
149
- console.error(`Failed to start subagent result watcher for '${resultsDir}':`, error);
150
- state.watcher = null;
151
- scheduleRestart();
152
- }
153
- };
154
-
155
- const primeExistingResults = () => {
156
- fs.readdirSync(resultsDir)
157
- .filter((f) => f.endsWith(".json"))
158
- .forEach((file) => state.resultFileCoalescer.schedule(file, 0));
159
- };
160
-
161
- const stopResultWatcher = () => {
162
- state.watcher?.close();
163
- state.watcher = null;
164
- if (state.watcherRestartTimer) {
165
- clearTimeout(state.watcherRestartTimer);
166
- }
167
- state.watcherRestartTimer = null;
168
- state.resultFileCoalescer.clear();
169
- };
170
-
171
- return { startResultWatcher, primeExistingResults, stopResultWatcher };
172
- }
@@ -1,58 +0,0 @@
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 os from "node:os";
6
- import * as path from "node:path";
7
-
8
- export interface RunEntry {
9
- agent: string;
10
- task: string;
11
- ts: number;
12
- status: "ok" | "error";
13
- duration: number;
14
- exit?: number;
15
- }
16
-
17
- const HISTORY_PATH = path.join(os.homedir(), ".pi", "agent", "run-history.jsonl");
18
- const ROTATE_READ_THRESHOLD = 1200;
19
- const ROTATE_KEEP = 1000;
20
-
21
- export function recordRun(agent: string, task: string, exitCode: number, durationMs: number): void {
22
- try {
23
- const entry: RunEntry = {
24
- agent,
25
- task: task.slice(0, 200),
26
- ts: Math.floor(Date.now() / 1000),
27
- status: exitCode === 0 ? "ok" : "error",
28
- duration: durationMs,
29
- ...(exitCode !== 0 ? { exit: exitCode } : {}),
30
- };
31
- fs.mkdirSync(path.dirname(HISTORY_PATH), { recursive: true });
32
- fs.appendFileSync(HISTORY_PATH, `${JSON.stringify(entry)}\n`);
33
- } catch {
34
- // Best-effort — never crash the execution flow for history recording
35
- }
36
- }
37
-
38
- export function loadRunsForAgent(agent: string): RunEntry[] {
39
- if (!fs.existsSync(HISTORY_PATH)) return [];
40
- let raw: string;
41
- try {
42
- raw = fs.readFileSync(HISTORY_PATH, "utf-8");
43
- } catch {
44
- return [];
45
- }
46
-
47
- let lines = raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
48
-
49
- if (lines.length > ROTATE_READ_THRESHOLD) {
50
- lines = lines.slice(-ROTATE_KEEP);
51
- try { fs.writeFileSync(HISTORY_PATH, `${lines.join("\n")}\n`, "utf-8"); } catch {}
52
- }
53
-
54
- return lines
55
- .map((line) => { try { return JSON.parse(line) as RunEntry; } catch { return undefined; } })
56
- .filter((entry): entry is RunEntry => Boolean(entry) && entry.agent === agent)
57
- .reverse();
58
- }
@@ -1,137 +0,0 @@
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 type { AgentToolResult } from "@mariozechner/pi-agent-core";
7
- import { formatAsyncRunList, listAsyncRuns } from "./async-status.ts";
8
- import { ASYNC_DIR, RESULTS_DIR, type Details } from "./types.ts";
9
- import { findByPrefix, readStatus } from "./utils.ts";
10
-
11
- export interface RunStatusParams {
12
- action?: "status";
13
- id?: string;
14
- runId?: string;
15
- dir?: string;
16
- }
17
-
18
- function activityText(activityState: unknown, lastActivityAt: unknown): string | undefined {
19
- if (typeof lastActivityAt !== "number") return undefined;
20
- const seconds = Math.floor(Math.max(0, Date.now() - lastActivityAt) / 1000);
21
- return activityState === "needs_attention" ? `no activity for ${seconds}s` : `active ${seconds}s ago`;
22
- }
23
-
24
- export function inspectSubagentStatus(params: RunStatusParams): AgentToolResult<Details> {
25
- if (!params.id && !params.runId && !params.dir) {
26
- try {
27
- const runs = listAsyncRuns(ASYNC_DIR, { states: ["queued", "running"] });
28
- return {
29
- content: [{ type: "text", text: formatAsyncRunList(runs) }],
30
- details: { mode: "single", results: [] },
31
- };
32
- } catch (error) {
33
- const message = error instanceof Error ? error.message : String(error);
34
- return {
35
- content: [{ type: "text", text: message }],
36
- isError: true,
37
- details: { mode: "single", results: [] },
38
- };
39
- }
40
- }
41
-
42
- let asyncDir: string | null = null;
43
- let resolvedId = params.id ?? params.runId;
44
-
45
- if (params.dir) {
46
- asyncDir = path.resolve(params.dir);
47
- } else if (resolvedId) {
48
- const direct = path.join(ASYNC_DIR, resolvedId);
49
- if (fs.existsSync(direct)) {
50
- asyncDir = direct;
51
- } else {
52
- const match = findByPrefix(ASYNC_DIR, resolvedId);
53
- if (match) {
54
- asyncDir = match;
55
- resolvedId = path.basename(match);
56
- }
57
- }
58
- }
59
-
60
- const resultPath = resolvedId && !asyncDir ? findByPrefix(RESULTS_DIR, resolvedId, ".json") : null;
61
-
62
- if (!asyncDir && !resultPath) {
63
- return {
64
- content: [{ type: "text", text: "Async run not found. Provide id or dir." }],
65
- isError: true,
66
- details: { mode: "single", results: [] },
67
- };
68
- }
69
-
70
- if (asyncDir) {
71
- let status;
72
- try {
73
- status = readStatus(asyncDir);
74
- } catch (error) {
75
- const message = error instanceof Error ? error.message : String(error);
76
- return {
77
- content: [{ type: "text", text: message }],
78
- isError: true,
79
- details: { mode: "single", results: [] },
80
- };
81
- }
82
- const logPath = path.join(asyncDir, `subagent-log-${resolvedId ?? "unknown"}.md`);
83
- const eventsPath = path.join(asyncDir, "events.jsonl");
84
- if (status) {
85
- const stepsTotal = status.steps?.length ?? 1;
86
- const current = status.currentStep !== undefined ? status.currentStep + 1 : undefined;
87
- const stepLine = current !== undefined ? `Step: ${current}/${stepsTotal}` : `Steps: ${stepsTotal}`;
88
- const started = new Date(status.startedAt).toISOString();
89
- const updated = status.lastUpdate ? new Date(status.lastUpdate).toISOString() : "n/a";
90
- const statusActivityText = status.state === "running" ? activityText(status.activityState, status.lastActivityAt) : undefined;
91
-
92
- const lines = [
93
- `Run: ${status.runId}`,
94
- `State: ${status.state}`,
95
- statusActivityText ? `Activity: ${statusActivityText}` : undefined,
96
- `Mode: ${status.mode}`,
97
- stepLine,
98
- `Started: ${started}`,
99
- `Updated: ${updated}`,
100
- `Dir: ${asyncDir}`,
101
- ].filter((line): line is string => Boolean(line));
102
- for (const [index, step] of (status.steps ?? []).entries()) {
103
- const stepActivityText = step.status === "running" ? activityText(step.activityState, step.lastActivityAt) : undefined;
104
- lines.push(`Step ${index + 1}: ${step.agent} ${step.status}${stepActivityText ? `, ${stepActivityText}` : ""}`);
105
- }
106
- if (status.sessionFile) lines.push(`Session: ${status.sessionFile}`);
107
- if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
108
- if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
109
-
110
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [] } };
111
- }
112
- }
113
-
114
- if (resultPath) {
115
- try {
116
- const raw = fs.readFileSync(resultPath, "utf-8");
117
- const data = JSON.parse(raw) as { id?: string; success?: boolean; summary?: string; exitCode?: number; state?: string };
118
- const status = data.success ? "complete" : data.state === "paused" || data.exitCode === 0 ? "paused" : "failed";
119
- const lines = [`Run: ${data.id ?? resolvedId}`, `State: ${status}`, `Result: ${resultPath}`];
120
- if (data.summary) lines.push("", data.summary);
121
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [] } };
122
- } catch (error) {
123
- const message = error instanceof Error ? error.message : String(error);
124
- return {
125
- content: [{ type: "text", text: `Failed to read async result file: ${message}` }],
126
- isError: true,
127
- details: { mode: "single", results: [] },
128
- };
129
- }
130
- }
131
-
132
- return {
133
- content: [{ type: "text", text: "Status file not found." }],
134
- isError: true,
135
- details: { mode: "single", results: [] },
136
- };
137
- }