@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Reads `enabledModels` from pi's settings (global `<agentDir>/settings.json`
3
+ * + project-local `<cwd>/.pi/settings.json`, project wins) and resolves
4
+ * entries to concrete `provider/modelId` keys for scope validation.
5
+ *
6
+ * **Project overrides global**, mirroring pi's own `SettingsManager`
7
+ * deep-merge behavior and matching the precedence we use for our own
8
+ * `subagents.json` settings (see `src/settings.ts:loadSettings`). If
9
+ * project file has `enabledModels` set, it wholly replaces global's
10
+ * (array fields are replaced, not concatenated).
11
+ *
12
+ * **Limited subset of upstream's resolveModelScope.** We support exact
13
+ * `provider/modelId` matching only. Upstream (pi-coding-agent's
14
+ * `core/model-resolver.ts`) additionally supports glob patterns
15
+ * (`*sonnet*`, `anthropic/*`), bare model IDs without provider, and
16
+ * thinking-level suffixes (`provider/*:high`). Those forms are silently
17
+ * ignored here.
18
+ *
19
+ * In practice, pi's `/scoped-models` picker writes exact `provider/modelId`
20
+ * entries, so the limitation is invisible for users who configure scope
21
+ * through pi's UI. Hand-edited settings using globs or bare IDs will
22
+ * produce an empty allowed set (scope check becomes a no-op).
23
+ *
24
+ * Example:
25
+ * enabledModels = ["anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6"]
26
+ * → resolves to { "anthropic/claude-sonnet-4-6", "anthropic/claude-opus-4-6" }
27
+ */
28
+ import { existsSync, readFileSync, statSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
31
+ /** Paths to pi's settings.json files: [project, global] (project takes precedence). */
32
+ function settingsPaths(cwd) {
33
+ return [
34
+ join(cwd, ".pi", "settings.json"),
35
+ join(getAgentDir(), "settings.json"),
36
+ ];
37
+ }
38
+ /** Read `enabledModels` from a single settings.json file. Undefined when missing or absent. */
39
+ function readField(path) {
40
+ if (!existsSync(path))
41
+ return undefined;
42
+ try {
43
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
44
+ if (Array.isArray(raw?.enabledModels))
45
+ return raw.enabledModels;
46
+ }
47
+ catch {
48
+ /* corrupt file — silent */
49
+ }
50
+ return undefined;
51
+ }
52
+ /**
53
+ * Read enabledModels from pi's settings — project-local overrides global.
54
+ * Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
55
+ * (and matches our own loadSettings precedence in src/settings.ts).
56
+ * Returns undefined when neither file has the field.
57
+ */
58
+ export function readEnabledModels(cwd) {
59
+ const [project, global] = settingsPaths(cwd);
60
+ return readField(project) ?? readField(global);
61
+ }
62
+ /**
63
+ * Resolve enabledModels patterns → Set<"provider/modelId"> (lowercase keys).
64
+ *
65
+ * Only exact `provider/modelId` patterns are matched (case-insensitive).
66
+ * Patterns without a slash, with glob characters, or with a `:thinking`
67
+ * suffix are silently dropped. See module-level docstring for rationale.
68
+ *
69
+ * Cache: keyed on JSON.stringify(patterns) + mtime/size of *both*
70
+ * project and global settings.json files. Re-resolves when either file
71
+ * changes or the patterns argument differs.
72
+ *
73
+ * Returns undefined when no patterns are provided or no patterns match
74
+ * (scope check becomes a no-op at the call site).
75
+ */
76
+ // Module-level cache — invalidated when either settings.json changes or patterns differ.
77
+ let cachedAllowed;
78
+ let cachedHash = "";
79
+ let cachedPatternsKey = "";
80
+ /** mtime+size hash of one file, or "missing" if absent. */
81
+ function hashOf(path) {
82
+ try {
83
+ const s = statSync(path);
84
+ return `${s.mtimeMs}-${s.size}`;
85
+ }
86
+ catch {
87
+ return "missing";
88
+ }
89
+ }
90
+ export function resolveEnabledModels(patterns, registry, cwd = process.cwd()) {
91
+ // Fast path: check cache (stat both project and global settings.json files)
92
+ const patternsKey = JSON.stringify(patterns);
93
+ const [project, global] = settingsPaths(cwd);
94
+ const fileHash = `${hashOf(project)};${hashOf(global)}`;
95
+ if (fileHash === cachedHash && patternsKey === cachedPatternsKey) {
96
+ return cachedAllowed;
97
+ }
98
+ // Cache miss — resolve
99
+ if (!patterns || patterns.length === 0) {
100
+ cachedHash = fileHash;
101
+ cachedPatternsKey = patternsKey;
102
+ cachedAllowed = undefined;
103
+ return undefined;
104
+ }
105
+ const available = (registry.getAvailable?.() ?? registry.getAll());
106
+ const allowed = new Set();
107
+ for (const pattern of patterns) {
108
+ const trimmed = pattern.trim();
109
+ if (!trimmed)
110
+ continue; // skip empty/whitespace
111
+ resolveExact(trimmed, available, allowed);
112
+ }
113
+ const result = allowed.size > 0 ? allowed : undefined;
114
+ cachedHash = fileHash;
115
+ cachedPatternsKey = patternsKey;
116
+ cachedAllowed = result;
117
+ return result;
118
+ }
119
+ /**
120
+ * True when `model` is in the allowed set. Centralizes the key format
121
+ * (`provider/id` lowercase) so callers don't have to reproduce it —
122
+ * both set-building (resolveExact) and lookup go through `modelKey`.
123
+ */
124
+ export function isModelInScope(model, allowed) {
125
+ return allowed.has(modelKey(model));
126
+ }
127
+ /** Canonical lowercase `provider/id` key for the allowed set. */
128
+ function modelKey(model) {
129
+ return `${model.provider}/${model.id}`.toLowerCase();
130
+ }
131
+ /**
132
+ * Resolve exact model pattern. Example: "google/gemma-4-31b-it".
133
+ */
134
+ function resolveExact(pattern, available, allowed) {
135
+ // "provider/modelId" — exact (colon is part of id, not split)
136
+ const slashIdx = pattern.indexOf("/");
137
+ if (slashIdx === -1)
138
+ return; // bare modelId not supported
139
+ const provider = pattern.slice(0, slashIdx).toLowerCase();
140
+ const modelId = pattern.slice(slashIdx + 1).toLowerCase();
141
+ const exact = available.find(m => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId);
142
+ if (exact) {
143
+ allowed.add(modelKey(exact));
144
+ }
145
+ }
package/dist/env.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
+ */
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+ import type { EnvInfo } from "./types.js";
6
+ export declare function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo>;
package/dist/env.js ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
+ */
4
+ export async function detectEnv(pi, cwd) {
5
+ let isGitRepo = false;
6
+ let branch = "";
7
+ try {
8
+ const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
9
+ isGitRepo = result.code === 0 && result.stdout.trim() === "true";
10
+ }
11
+ catch {
12
+ // Not a git repo or git not installed
13
+ }
14
+ if (isGitRepo) {
15
+ try {
16
+ const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
17
+ branch = result.code === 0 ? result.stdout.trim() : "unknown";
18
+ }
19
+ catch {
20
+ branch = "unknown";
21
+ }
22
+ }
23
+ return {
24
+ isGitRepo,
25
+ branch,
26
+ platform: process.platform,
27
+ };
28
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * error-log.ts — Persistent cross-session aggregate log for pi-subagents issues.
3
+ *
4
+ * The per-agent `.output` transcripts (temp dir, cleared on reboot) record
5
+ * per-attempt diagnostics for one session. This module complements them with
6
+ * ONE durable JSONL file that aggregates issue events from every session, so
7
+ * recurring provider failures, spawn rejections, and fallback switches can be
8
+ * tracked over time:
9
+ *
10
+ * <agentDir>/pi-subagents/agent-errors.jsonl
11
+ *
12
+ * The base is the GLOBAL agentDir (getAgentDir(), honoring $PI_CODING_AGENT_DIR),
13
+ * deliberately not configCwd-scoped: sessions span projects, and a per-project
14
+ * log would fragment exactly the cross-session history this file exists for.
15
+ *
16
+ * One JSON object per line, `ts` (ISO 8601) first. Every free-text field is
17
+ * sanitized through sanitizeDiagnosticText (imported, not duplicated — it owns
18
+ * credential/URL/header redaction). Raw prompts are never logged: prompt text
19
+ * belongs to the per-session transcript, not this aggregate.
20
+ */
21
+ export type SubagentIssueKind = "attempt_error" | "retry_start" | "retry_end" | "standalone_fallback" | "spawn_rejected";
22
+ export interface SubagentIssueRecord {
23
+ kind: SubagentIssueKind;
24
+ agentId?: string;
25
+ agentType?: string;
26
+ /** Correlation id used where no agentId exists at the call site (recovery layer). */
27
+ sessionId?: string;
28
+ provider?: string;
29
+ model?: string;
30
+ responseModel?: string;
31
+ stopReason?: string;
32
+ messageTimestamp?: number;
33
+ attempt?: number;
34
+ maxAttempts?: number;
35
+ delayMs?: number;
36
+ success?: boolean;
37
+ errorMessage?: string;
38
+ finalError?: string;
39
+ requestedType?: string;
40
+ outcome?: "success" | "blocked" | "failed";
41
+ reason?: string;
42
+ from?: {
43
+ provider?: string;
44
+ model?: string;
45
+ };
46
+ to?: {
47
+ provider?: string;
48
+ model?: string;
49
+ };
50
+ }
51
+ /**
52
+ * Append one issue event. Best-effort and off the event loop: the record is
53
+ * built synchronously, then written through the serialized chain — the trim
54
+ * check never blocks the session, and every failure (unwritable dir, full
55
+ * disk, locked file) is swallowed without even console noise. Resolves once
56
+ * the record is on disk; callers may ignore the promise.
57
+ */
58
+ export declare function logSubagentIssue(record: SubagentIssueRecord): Promise<void>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * error-log.ts — Persistent cross-session aggregate log for pi-subagents issues.
3
+ *
4
+ * The per-agent `.output` transcripts (temp dir, cleared on reboot) record
5
+ * per-attempt diagnostics for one session. This module complements them with
6
+ * ONE durable JSONL file that aggregates issue events from every session, so
7
+ * recurring provider failures, spawn rejections, and fallback switches can be
8
+ * tracked over time:
9
+ *
10
+ * <agentDir>/pi-subagents/agent-errors.jsonl
11
+ *
12
+ * The base is the GLOBAL agentDir (getAgentDir(), honoring $PI_CODING_AGENT_DIR),
13
+ * deliberately not configCwd-scoped: sessions span projects, and a per-project
14
+ * log would fragment exactly the cross-session history this file exists for.
15
+ *
16
+ * One JSON object per line, `ts` (ISO 8601) first. Every free-text field is
17
+ * sanitized through sanitizeDiagnosticText (imported, not duplicated — it owns
18
+ * credential/URL/header redaction). Raw prompts are never logged: prompt text
19
+ * belongs to the per-session transcript, not this aggregate.
20
+ */
21
+ import { randomBytes } from "node:crypto";
22
+ import { chmodSync, mkdirSync } from "node:fs";
23
+ import { appendFile, open, rename, stat, unlink, writeFile } from "node:fs/promises";
24
+ import { join } from "node:path";
25
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
26
+ import { sanitizeDiagnosticText } from "./output-diagnostics.js";
27
+ /** Prose that can carry prover payloads: full treatment (header/body/URL redaction). */
28
+ const FREE_TEXT = ["errorMessage", "finalError", "reason"];
29
+ /** Short identifiers/labels: bounded but not free prose. */
30
+ const SHORT_TEXT = ["provider", "model", "responseModel", "agentType", "requestedType"];
31
+ const MAX_BYTES = 10 * 1024 * 1024; // ~10MB: start of the trim check
32
+ const KEEP_BYTES = 5 * 1024 * 1024; // retain the most recent ~5MB on trim
33
+ // Rename hardening mirrors schedule-store: Windows reports EPERM/EBUSY/EACCES
34
+ // while AV or an indexer holds the target.
35
+ const RENAME_RETRIES = 5;
36
+ const RENAME_RETRY_MS = 20;
37
+ // Resolved lazily on first use and prepared (mkdir + chmod) once per agentDir.
38
+ // Keyed on the resolved dir — not cached unconditionally — because tests
39
+ // redirect $PI_CODING_AGENT_DIR between cases; a real process never changes it.
40
+ let prepared;
41
+ function errorLogPath() {
42
+ const agentDir = getAgentDir();
43
+ if (!agentDir)
44
+ throw new Error("agent dir unavailable");
45
+ if (prepared?.agentDir === agentDir)
46
+ return prepared.path;
47
+ const dir = join(agentDir, "pi-subagents");
48
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
49
+ // Same perms pattern as sessionTaskDir in output-file.ts: owner-only past
50
+ // umask; chmod throws on some Windows filesystems and is a no-op there.
51
+ // Failure lands in the swallowed catch of logSubagentIssue either way.
52
+ try {
53
+ chmodSync(dir, 0o700);
54
+ }
55
+ catch (err) {
56
+ if (process.platform !== "win32")
57
+ throw err;
58
+ }
59
+ const path = join(dir, "agent-errors.jsonl");
60
+ prepared = { agentDir, path };
61
+ return path;
62
+ }
63
+ /** Trim an oversized log to its most recent ~5MB, reading only the kept tail. */
64
+ function errorCode(e) {
65
+ const code = e?.code;
66
+ return typeof code === "string" ? code : undefined;
67
+ }
68
+ /** rename with a bounded retry: Windows reports EPERM/EBUSY/EACCES while AV or an indexer holds the target. */
69
+ async function renameWithRetry(from, to) {
70
+ for (let attempt = 0;; attempt++) {
71
+ try {
72
+ await rename(from, to);
73
+ return;
74
+ }
75
+ catch (e) {
76
+ const code = errorCode(e);
77
+ const transient = code === "EPERM" || code === "EBUSY" || code === "EACCES";
78
+ if (!transient || attempt >= RENAME_RETRIES) {
79
+ try {
80
+ await unlink(from);
81
+ }
82
+ catch { /* best effort: the rename error below is the one that matters */ }
83
+ throw e;
84
+ }
85
+ await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_MS * (attempt + 1)));
86
+ }
87
+ }
88
+ }
89
+ /**
90
+ * Trim an oversized log to its most recent ~5MB. Reads only the tail it keeps
91
+ * — never the whole file — and replaces the log via temp+rename, so a failure
92
+ * leaves the original intact rather than a torn half-rotated file.
93
+ */
94
+ async function trimIfOversized(path) {
95
+ let size;
96
+ try {
97
+ size = (await stat(path)).size;
98
+ }
99
+ catch {
100
+ return; // No file yet (first write) — nothing to trim.
101
+ }
102
+ if (size <= MAX_BYTES)
103
+ return;
104
+ // "~" because the keep window is cut at a byte boundary, mid-line. Drop
105
+ // everything through the first newline of the kept slice so the remainder
106
+ // stays valid JSONL.
107
+ const readLen = Math.min(size, KEEP_BYTES);
108
+ const buffer = Buffer.alloc(readLen);
109
+ const handle = await open(path, "r");
110
+ try {
111
+ await handle.read(buffer, 0, readLen, size - readLen);
112
+ }
113
+ finally {
114
+ await handle.close();
115
+ }
116
+ const firstBreak = buffer.indexOf(0x0a);
117
+ const tail = firstBreak >= 0 ? buffer.subarray(firstBreak + 1) : buffer;
118
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
119
+ await writeFile(tmp, tail);
120
+ await renameWithRetry(tmp, path);
121
+ }
122
+ /** Serialized write chain: appends and the (rare) trim never interleave. */
123
+ let writeChain = Promise.resolve();
124
+ async function appendIssueLine(path, line) {
125
+ try {
126
+ await trimIfOversized(path);
127
+ await appendFile(path, line, "utf8");
128
+ }
129
+ catch { /* diagnostics must never break a session */ }
130
+ }
131
+ /**
132
+ * Append one issue event. Best-effort and off the event loop: the record is
133
+ * built synchronously, then written through the serialized chain — the trim
134
+ * check never blocks the session, and every failure (unwritable dir, full
135
+ * disk, locked file) is swallowed without even console noise. Resolves once
136
+ * the record is on disk; callers may ignore the promise.
137
+ */
138
+ export function logSubagentIssue(record) {
139
+ let line;
140
+ let path;
141
+ try {
142
+ const entry = { ts: new Date().toISOString(), ...record };
143
+ for (const key of FREE_TEXT) {
144
+ if (typeof record[key] === "string")
145
+ entry[key] = sanitizeDiagnosticText(record[key]);
146
+ }
147
+ for (const key of SHORT_TEXT) {
148
+ if (typeof record[key] === "string")
149
+ entry[key] = sanitizeDiagnosticText(record[key], 256);
150
+ }
151
+ for (const side of ["from", "to"]) {
152
+ const model = record[side];
153
+ if (!model)
154
+ continue;
155
+ entry[side] = {
156
+ ...(typeof model.provider === "string" ? { provider: sanitizeDiagnosticText(model.provider, 256) } : {}),
157
+ ...(typeof model.model === "string" ? { model: sanitizeDiagnosticText(model.model, 256) } : {}),
158
+ };
159
+ }
160
+ path = errorLogPath();
161
+ line = JSON.stringify(entry) + "\n";
162
+ }
163
+ catch { /* diagnostics must never break a session */
164
+ return Promise.resolve();
165
+ }
166
+ writeChain = writeChain.then(() => appendIssueLine(path, line));
167
+ return writeChain;
168
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * group-join.ts — Manages grouped background agent completion notifications.
3
+ *
4
+ * Instead of each agent individually nudging the main agent on completion,
5
+ * agents in a group are held until all complete (or a timeout fires),
6
+ * then a single consolidated notification is sent.
7
+ */
8
+ import type { AgentRecord } from "./types.js";
9
+ export type DeliveryCallback = (records: AgentRecord[], partial: boolean) => void;
10
+ export declare class GroupJoinManager {
11
+ private deliverCb;
12
+ private groupTimeout;
13
+ private groups;
14
+ private agentToGroup;
15
+ constructor(deliverCb: DeliveryCallback, groupTimeout?: number);
16
+ /** Register a group of agent IDs that should be joined. */
17
+ registerGroup(groupId: string, agentIds: string[]): void;
18
+ /**
19
+ * Called when an agent completes.
20
+ * Returns:
21
+ * - 'pass' — agent is not grouped, caller should send individual nudge
22
+ * - 'held' — result held, waiting for group completion
23
+ * - 'delivered' — this completion triggered the group notification
24
+ */
25
+ onAgentComplete(record: AgentRecord): 'delivered' | 'held' | 'pass';
26
+ private onTimeout;
27
+ private deliver;
28
+ private cleanupGroup;
29
+ /** Check if an agent is in a group. */
30
+ isGrouped(agentId: string): boolean;
31
+ dispose(): void;
32
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * group-join.ts — Manages grouped background agent completion notifications.
3
+ *
4
+ * Instead of each agent individually nudging the main agent on completion,
5
+ * agents in a group are held until all complete (or a timeout fires),
6
+ * then a single consolidated notification is sent.
7
+ */
8
+ /** Default timeout: 30s after first completion in a group. */
9
+ const DEFAULT_TIMEOUT = 30_000;
10
+ /** Straggler re-batch timeout: 15s. */
11
+ const STRAGGLER_TIMEOUT = 15_000;
12
+ export class GroupJoinManager {
13
+ deliverCb;
14
+ groupTimeout;
15
+ groups = new Map();
16
+ agentToGroup = new Map();
17
+ constructor(deliverCb, groupTimeout = DEFAULT_TIMEOUT) {
18
+ this.deliverCb = deliverCb;
19
+ this.groupTimeout = groupTimeout;
20
+ }
21
+ /** Register a group of agent IDs that should be joined. */
22
+ registerGroup(groupId, agentIds) {
23
+ const group = {
24
+ groupId,
25
+ agentIds: new Set(agentIds),
26
+ completedRecords: new Map(),
27
+ delivered: false,
28
+ isStraggler: false,
29
+ };
30
+ this.groups.set(groupId, group);
31
+ for (const id of agentIds) {
32
+ this.agentToGroup.set(id, groupId);
33
+ }
34
+ }
35
+ /**
36
+ * Called when an agent completes.
37
+ * Returns:
38
+ * - 'pass' — agent is not grouped, caller should send individual nudge
39
+ * - 'held' — result held, waiting for group completion
40
+ * - 'delivered' — this completion triggered the group notification
41
+ */
42
+ onAgentComplete(record) {
43
+ const groupId = this.agentToGroup.get(record.id);
44
+ if (!groupId)
45
+ return 'pass';
46
+ const group = this.groups.get(groupId);
47
+ if (!group || group.delivered)
48
+ return 'pass';
49
+ group.completedRecords.set(record.id, record);
50
+ // All done — deliver immediately
51
+ if (group.completedRecords.size >= group.agentIds.size) {
52
+ this.deliver(group, false);
53
+ return 'delivered';
54
+ }
55
+ // First completion in this batch — start timeout
56
+ if (!group.timeoutHandle) {
57
+ const timeout = group.isStraggler ? STRAGGLER_TIMEOUT : this.groupTimeout;
58
+ group.timeoutHandle = setTimeout(() => {
59
+ this.onTimeout(group);
60
+ }, timeout);
61
+ }
62
+ return 'held';
63
+ }
64
+ onTimeout(group) {
65
+ if (group.delivered)
66
+ return;
67
+ group.timeoutHandle = undefined;
68
+ // Partial delivery — some agents still running
69
+ const remaining = new Set();
70
+ for (const id of group.agentIds) {
71
+ if (!group.completedRecords.has(id))
72
+ remaining.add(id);
73
+ }
74
+ // Clean up agentToGroup for delivered agents (they won't complete again)
75
+ for (const id of group.completedRecords.keys()) {
76
+ this.agentToGroup.delete(id);
77
+ }
78
+ // Deliver what we have
79
+ this.deliverCb([...group.completedRecords.values()], true);
80
+ // Set up straggler group for remaining agents
81
+ group.completedRecords.clear();
82
+ group.agentIds = remaining;
83
+ group.isStraggler = true;
84
+ // Timeout will be started when the next straggler completes
85
+ }
86
+ deliver(group, partial) {
87
+ if (group.timeoutHandle) {
88
+ clearTimeout(group.timeoutHandle);
89
+ group.timeoutHandle = undefined;
90
+ }
91
+ group.delivered = true;
92
+ this.deliverCb([...group.completedRecords.values()], partial);
93
+ this.cleanupGroup(group.groupId);
94
+ }
95
+ cleanupGroup(groupId) {
96
+ const group = this.groups.get(groupId);
97
+ if (!group)
98
+ return;
99
+ for (const id of group.agentIds) {
100
+ this.agentToGroup.delete(id);
101
+ }
102
+ this.groups.delete(groupId);
103
+ }
104
+ /** Check if an agent is in a group. */
105
+ isGrouped(agentId) {
106
+ return this.agentToGroup.has(agentId);
107
+ }
108
+ dispose() {
109
+ for (const group of this.groups.values()) {
110
+ if (group.timeoutHandle)
111
+ clearTimeout(group.timeoutHandle);
112
+ }
113
+ this.groups.clear();
114
+ this.agentToGroup.clear();
115
+ }
116
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * pi-agents — A pi extension providing Claude Code-style autonomous sub-agents.
3
+ *
4
+ * Tools:
5
+ * Agent — LLM-callable: spawn a sub-agent
6
+ * get_subagent_result — LLM-callable: check background agent status/result
7
+ * steer_subagent — LLM-callable: send a steering message to a running agent
8
+ * stop_subagent — LLM-callable: stop (cancel) a running or queued agent
9
+ *
10
+ * Commands:
11
+ * /agents — Interactive agent management menu
12
+ */
13
+ import { type ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
+ import { Container } from "@earendil-works/pi-tui";
15
+ import { type AdvisorStatus } from "./advisor-status.js";
16
+ import { type AgentConfig } from "./types.js";
17
+ import { type Theme } from "./ui/agent-widget.js";
18
+ import { FOREIGN_WORKFLOW_TOOL_NAMES } from "./workflow/collisions.js";
19
+ import { WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData } from "./workflow/entry.js";
20
+ export declare function renderRunningAgentStatus(frame: string, statsText: string, activity: string, theme: Pick<Theme, "fg">, advisorStatus?: AdvisorStatus): Container;
21
+ /**
22
+ * Format an agent's tool scope for the Agent tool description.
23
+ *
24
+ * This suffix describes BUILT-IN scope only — extension tools are resolved when
25
+ * the agent runs (extensions can register asynchronously), so they cannot be
26
+ * enumerated while the description is being built. That is why an agent with
27
+ * `tools: "*, ext:mcp/search"` renders "*" and always has.
28
+ *
29
+ * Two distinctions matter, both of them capability claims the orchestrator acts on:
30
+ *
31
+ * - absent vs empty. `builtinToolNames: undefined` means the agent never narrowed
32
+ * its tools (the shipped defaults); `[]` is what `tools: none` and an `ext:`-only
33
+ * `tools:` parse to, and the runtime really does hand those agents no built-ins.
34
+ * Rendering both "*" tells the orchestrator a tool-less agent can run `bash`.
35
+ * - empty-with-extensions vs empty-without. Zero built-ins does NOT imply zero
36
+ * tools: `tools: none` alongside `extensions:` still surfaces every extension
37
+ * tool (see test/fixtures/.pi/agents/tools-none.md, which expects three). Calling
38
+ * that "none" understates the agent instead of overstating it — better, but still
39
+ * wrong, and it would route work away from the only agent able to do it. "none"
40
+ * is therefore reserved for agents that genuinely can call nothing: `isolated`
41
+ * agents and those with `extensions: false`.
42
+ */
43
+ export declare function formatToolsSuffix(cfg: AgentConfig | undefined): string;
44
+ /** CLI flag that runs a workflow script at session start. */
45
+ export declare const WORKFLOW_FILE_FLAG = "subagents-workflow-file";
46
+ /**
47
+ * Re-exported from where they now live, because this is where they were
48
+ * defined and a consumer (or a test) that matched a session entry on
49
+ * {@link WORKFLOW_ENTRY_TYPE} imports it from here.
50
+ */
51
+ export { FOREIGN_WORKFLOW_TOOL_NAMES, WORKFLOW_ENTRY_TYPE, type WorkflowEntryData, workflowEntryData };
52
+ export default function (pi: ExtensionAPI): void;