@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.5

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1244 -2
  3. package/package.json +75 -4
  4. package/src/abortable.ts +43 -0
  5. package/src/agent-color.ts +161 -0
  6. package/src/agent-file-toggle.ts +297 -0
  7. package/src/agent-manager.ts +1874 -0
  8. package/src/agent-runner.ts +1552 -0
  9. package/src/agent-source-badge.ts +75 -0
  10. package/src/agent-types.ts +346 -0
  11. package/src/child-context.ts +15 -0
  12. package/src/clock.ts +25 -0
  13. package/src/completion-outbox.ts +125 -0
  14. package/src/context.ts +58 -0
  15. package/src/cross-extension-rpc.ts +221 -0
  16. package/src/custom-agents.ts +436 -0
  17. package/src/default-agents.ts +126 -0
  18. package/src/detached-results.ts +134 -0
  19. package/src/enabled-models.ts +180 -0
  20. package/src/enterprise-local.ts +66 -0
  21. package/src/env.ts +33 -0
  22. package/src/group-join.ts +148 -0
  23. package/src/index.ts +4423 -0
  24. package/src/invocation-config.ts +189 -0
  25. package/src/memory.ts +179 -0
  26. package/src/mention-clone.ts +195 -0
  27. package/src/mention.ts +141 -0
  28. package/src/model-call.ts +83 -0
  29. package/src/model-resolver.ts +266 -0
  30. package/src/model-scope.ts +70 -0
  31. package/src/nested-tools.ts +448 -0
  32. package/src/output-file.ts +164 -0
  33. package/src/package-resources.ts +624 -0
  34. package/src/prompts.ts +156 -0
  35. package/src/quota-admission.ts +99 -0
  36. package/src/schedule-store.ts +153 -0
  37. package/src/schedule.ts +446 -0
  38. package/src/settings.ts +728 -0
  39. package/src/skill-loader.ts +137 -0
  40. package/src/startup-error.ts +29 -0
  41. package/src/status-note.ts +90 -0
  42. package/src/structured-output.ts +130 -0
  43. package/src/types.ts +404 -0
  44. package/src/ui/agent-mention.ts +216 -0
  45. package/src/ui/agent-row.ts +235 -0
  46. package/src/ui/agent-widget.ts +692 -0
  47. package/src/ui/conversation-viewer.ts +832 -0
  48. package/src/ui/fleet-list.ts +675 -0
  49. package/src/ui/notification-view.ts +120 -0
  50. package/src/ui/schedule-menu.ts +105 -0
  51. package/src/ui/select-item.ts +45 -0
  52. package/src/ui/viewer-keys.ts +39 -0
  53. package/src/ui/workflow-card.ts +462 -0
  54. package/src/ui/workflow-dialog.ts +1115 -0
  55. package/src/ui/workflow-menu.ts +193 -0
  56. package/src/usage.ts +167 -0
  57. package/src/workflow/collisions.ts +123 -0
  58. package/src/workflow/entry.ts +47 -0
  59. package/src/workflow/host.ts +401 -0
  60. package/src/workflow/journal.ts +164 -0
  61. package/src/workflow/json-schema.ts +129 -0
  62. package/src/workflow/meta.ts +326 -0
  63. package/src/workflow/progress.ts +549 -0
  64. package/src/workflow/runtime.ts +1216 -0
  65. package/src/workflow/saved.ts +259 -0
  66. package/src/workflow/task.ts +302 -0
  67. package/src/workflow/tool-description.ts +200 -0
  68. package/src/workflow/worker-source.ts +781 -0
  69. package/src/worktree.ts +230 -0
  70. package/src/xml.ts +13 -0
@@ -0,0 +1,126 @@
1
+ /**
2
+ * default-agents.ts — Embedded default agent configurations.
3
+ *
4
+ * These are always available but can be overridden by user .md files with the same name.
5
+ */
6
+
7
+ import type { AgentConfig } from "./types.js";
8
+
9
+ const READ_ONLY_TOOLS = ["read", "bash", "grep", "find", "ls"];
10
+
11
+ export const DEFAULT_AGENTS: Map<string, AgentConfig> = new Map([
12
+ [
13
+ "general-purpose",
14
+ {
15
+ name: "general-purpose",
16
+ displayName: "Agent",
17
+ description: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",
18
+ // builtinToolNames omitted — means "all available tools" (resolved at lookup time)
19
+ // inheritContext / runInBackground / isolated omitted — strategy fields, callers decide per-call.
20
+ // Setting them to false would lock callsite intent (see resolveAgentInvocationConfig in invocation-config.ts).
21
+ extensions: true,
22
+ skills: true,
23
+ systemPrompt: "",
24
+ promptMode: "append",
25
+ isDefault: true,
26
+ },
27
+ ],
28
+ [
29
+ "Explore",
30
+ {
31
+ name: "Explore",
32
+ displayName: "Explore",
33
+ description: "Fast read-only search agent for locating code. Use it to find files by pattern (eg. \"src/components/**/*.tsx\"), grep for symbols or keywords (eg. \"API endpoints\"), or answer \"where is X defined / which files reference Y.\" Do NOT use it for code review, design-doc auditing, cross-file consistency checks, or open-ended analysis — it reads excerpts rather than whole files and will miss content past its read window. When calling, specify search breadth: \"quick\" for a single targeted lookup, \"medium\" for moderate exploration, or \"very thorough\" to search across multiple locations and naming conventions.",
34
+ builtinToolNames: READ_ONLY_TOOLS,
35
+ extensions: true,
36
+ skills: true,
37
+ // Fast/cheap portable default for read-only search. A target-local alias
38
+ // can select its canonical provider; otherwise fuzzy resolution finds a
39
+ // matching enabled model under any provider.
40
+ model: "claude-haiku-4-5",
41
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
42
+ You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
43
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools.
44
+
45
+ You are STRICTLY PROHIBITED from:
46
+ - Creating new files
47
+ - Modifying existing files
48
+ - Deleting files
49
+ - Moving or copying files
50
+ - Creating temporary files anywhere, including /tmp
51
+ - Using redirect operators (>, >>, |) or heredocs to write to files
52
+ - Running ANY commands that change system state
53
+
54
+ Use Bash ONLY for read-only operations: ls, git status, git log, git diff, find, cat, head, tail.
55
+
56
+ # Tool Usage
57
+ - Use the find tool for file pattern matching (NOT the bash find command)
58
+ - Use the grep tool for content search (NOT bash grep/rg command)
59
+ - Use the read tool for reading files (NOT bash cat/head/tail)
60
+ - Use Bash ONLY for read-only operations
61
+ - Make independent tool calls in parallel for efficiency
62
+ - Adapt search approach based on thoroughness level specified
63
+
64
+ # Output
65
+ - Use absolute file paths in all references
66
+ - Report findings as regular messages
67
+ - Do not use emojis
68
+ - Be thorough and precise`,
69
+ promptMode: "replace",
70
+ isDefault: true,
71
+ },
72
+ ],
73
+ [
74
+ "Plan",
75
+ {
76
+ name: "Plan",
77
+ displayName: "Plan",
78
+ description: "Software architect agent for designing implementation plans. Use this when you need to plan the implementation strategy for a task. Returns step-by-step plans, identifies critical files, and considers architectural trade-offs.",
79
+ builtinToolNames: READ_ONLY_TOOLS,
80
+ extensions: true,
81
+ skills: true,
82
+ systemPrompt: `# CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS
83
+ You are a software architect and planning specialist.
84
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans.
85
+ You do NOT have access to file editing tools — attempting to edit files will fail.
86
+
87
+ You are STRICTLY PROHIBITED from:
88
+ - Creating new files
89
+ - Modifying existing files
90
+ - Deleting files
91
+ - Moving or copying files
92
+ - Creating temporary files anywhere, including /tmp
93
+ - Using redirect operators (>, >>, |) or heredocs to write to files
94
+ - Running ANY commands that change system state
95
+
96
+ # Planning Process
97
+ 1. Understand requirements
98
+ 2. Explore thoroughly (read files, find patterns, understand architecture)
99
+ 3. Design solution based on your assigned perspective
100
+ 4. Detail the plan with step-by-step implementation strategy
101
+
102
+ # Requirements
103
+ - Consider trade-offs and architectural decisions
104
+ - Identify dependencies and sequencing
105
+ - Anticipate potential challenges
106
+ - Follow existing patterns where appropriate
107
+
108
+ # Tool Usage
109
+ - Use the find tool for file pattern matching (NOT the bash find command)
110
+ - Use the grep tool for content search (NOT bash grep/rg command)
111
+ - Use the read tool for reading files (NOT bash cat/head/tail)
112
+ - Use Bash ONLY for read-only operations
113
+
114
+ # Output Format
115
+ - Use absolute file paths
116
+ - Do not use emojis
117
+ - End your response with:
118
+
119
+ ### Critical Files for Implementation
120
+ List 3-5 files most critical for implementing this plan:
121
+ - /absolute/path/to/file.ts - [Brief reason]`,
122
+ promptMode: "replace",
123
+ isDefault: true,
124
+ },
125
+ ],
126
+ ]);
@@ -0,0 +1,134 @@
1
+ /**
2
+ * detached-results.ts -- hand completed background agents back to a session
3
+ * after the extension instance that spawned them is gone.
4
+ *
5
+ * `/new`, `/resume`, `/fork` and `/reload` shut the extension down but keep the
6
+ * process alive. Background agents are allowed to finish in the orphaned
7
+ * manager, which can no longer talk to pi (its `pi` handle is stale), so each
8
+ * result is spooled to disk keyed by the PARENT session file. The extension
9
+ * instance bound to that session drains the spool on `session_start`, and while
10
+ * it is active a process-wide sink wakes it for results that land later.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+ import type { AgentRecord } from "./types.js";
17
+ import type { AgentActivity } from "./ui/agent-widget.js";
18
+
19
+ /** One finished agent, in the shape `session_start` needs to re-announce it. */
20
+ export interface DetachedResult {
21
+ id: string;
22
+ /** Pre-rendered `<task-notification>` text for the LLM. */
23
+ content: string;
24
+ /** `subagent-notification` renderer details. */
25
+ details: unknown;
26
+ /** History entry for a result that finished detached; absent if already appended. */
27
+ record?: Record<string, unknown>;
28
+ }
29
+
30
+ const SINK_KEY = Symbol.for("pi-subagents:detached-sink");
31
+
32
+ /** Per-session wake-ups, shared across every extension instance in the process. */
33
+ function sinks(): Map<string, () => void> {
34
+ const g = globalThis as Record<symbol, unknown>;
35
+ let map = g[SINK_KEY] as Map<string, () => void> | undefined;
36
+ if (!map) {
37
+ map = new Map();
38
+ g[SINK_KEY] = map;
39
+ }
40
+ return map;
41
+ }
42
+
43
+ /** Spool directory for one parent session (created on demand, owner-only). */
44
+ export function detachedDir(sessionFile: string): string {
45
+ const key = createHash("sha256").update(sessionFile).digest("hex").slice(0, 16);
46
+ const dir = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`, "detached", key);
47
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
48
+ return dir;
49
+ }
50
+
51
+ /** Persist a result for `sessionFile` and wake its live extension instance, if any. */
52
+ export function spoolDetached(sessionFile: string, result: DetachedResult): void {
53
+ const dir = detachedDir(sessionFile);
54
+ const name = `${Date.now()}-${result.id.replace(/[^\w.-]/g, "_")}.json`;
55
+ // Rename into place so a concurrent drain never reads a half-written file.
56
+ const tmp = join(dir, `.${name}.tmp`);
57
+ writeFileSync(tmp, JSON.stringify(result), { mode: 0o600 });
58
+ renameSync(tmp, join(dir, name));
59
+ try {
60
+ sinks().get(sessionFile)?.();
61
+ } catch {
62
+ // The woken instance is already shutting down; the file stays for the next drain.
63
+ }
64
+ }
65
+
66
+ /** Read and delete every spooled result for `sessionFile`, oldest first. Unreadable files are dropped. */
67
+ export function drainDetached(sessionFile: string): DetachedResult[] {
68
+ const dir = detachedDir(sessionFile);
69
+ const out: DetachedResult[] = [];
70
+ for (const name of readdirSync(dir).filter(n => n.endsWith(".json") && !n.startsWith(".")).sort()) {
71
+ const path = join(dir, name);
72
+ try {
73
+ out.push(JSON.parse(readFileSync(path, "utf8")) as DetachedResult);
74
+ } catch {
75
+ // Corrupt spool entry: nothing recoverable, and retrying it forever helps nobody.
76
+ }
77
+ rmSync(path, { force: true });
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /** Call `onSpooled` whenever a result lands for `sessionFile`. Returns the unsubscribe. */
83
+ export function watchDetached(sessionFile: string, onSpooled: () => void): () => void {
84
+ const map = sinks();
85
+ map.set(sessionFile, onSpooled);
86
+ return () => {
87
+ if (map.get(sessionFile) === onSpooled) map.delete(sessionFile);
88
+ };
89
+ }
90
+
91
+ /**
92
+ * A background agent still running in an orphaned manager. The record and
93
+ * activity are the orphan's live objects, so a reloaded session can show and
94
+ * open them; `abort` and `steer` are bound to the orphan's manager.
95
+ */
96
+ export interface RunningDetached {
97
+ record: AgentRecord;
98
+ activity?: AgentActivity;
99
+ abort(): boolean;
100
+ steer(message: string): boolean;
101
+ }
102
+
103
+ const RUNNING_KEY = Symbol.for("pi-subagents:detached-running");
104
+
105
+ /** Running orphans by parent session file then agent id, shared across every extension instance. */
106
+ function running(): Map<string, Map<string, RunningDetached>> {
107
+ const g = globalThis as Record<symbol, unknown>;
108
+ let map = g[RUNNING_KEY] as Map<string, Map<string, RunningDetached>> | undefined;
109
+ if (!map) {
110
+ map = new Map();
111
+ g[RUNNING_KEY] = map;
112
+ }
113
+ return map;
114
+ }
115
+
116
+ /** Publish an orphaned, still-running agent so the session's next extension instance can list it. */
117
+ export function registerRunningDetached(sessionFile: string, agent: RunningDetached): void {
118
+ const byId = running().get(sessionFile) ?? new Map<string, RunningDetached>();
119
+ byId.set(agent.record.id, agent);
120
+ running().set(sessionFile, byId);
121
+ }
122
+
123
+ /** Drop an orphan once it settles (its result is spooled from there on). */
124
+ export function unregisterRunningDetached(sessionFile: string, id: string): void {
125
+ const byId = running().get(sessionFile);
126
+ byId?.delete(id);
127
+ if (byId?.size === 0) running().delete(sessionFile);
128
+ }
129
+
130
+ /** Orphans still running for `sessionFile`, in registration order. */
131
+ export function listRunningDetached(sessionFile: string | undefined): RunningDetached[] {
132
+ if (sessionFile === undefined) return [];
133
+ return [...(running().get(sessionFile)?.values() ?? [])];
134
+ }
@@ -0,0 +1,180 @@
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
+
29
+ import { existsSync, readFileSync, statSync } from "node:fs";
30
+ import { join } from "node:path";
31
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
32
+ import type { ModelEntry } from "./model-resolver.js";
33
+
34
+ /** Minimal registry shape — only the methods resolveEnabledModels actually calls. */
35
+ export interface ModelRegistryRef {
36
+ getAll(): unknown[];
37
+ getAvailable?(): unknown[];
38
+ }
39
+
40
+ /** Paths to pi's settings.json files: [project, global] (project takes precedence). */
41
+ function settingsPaths(cwd: string): [project: string, global: string] {
42
+ return [
43
+ join(cwd, ".pi", "settings.json"),
44
+ join(getAgentDir(), "settings.json"),
45
+ ];
46
+ }
47
+
48
+ /** Read `enabledModels` from a single settings.json file. Undefined when missing or absent. */
49
+ function readField(path: string): string[] | undefined {
50
+ if (!existsSync(path)) return undefined;
51
+ try {
52
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
53
+ if (Array.isArray(raw?.enabledModels)) return raw.enabledModels as string[];
54
+ } catch {
55
+ /* corrupt file — silent */
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /**
61
+ * Read enabledModels from pi's settings — project-local overrides global.
62
+ * Mirrors pi's SettingsManager deep-merge for the `enabledModels` field
63
+ * (and matches our own loadSettings precedence in src/settings.ts).
64
+ * Returns undefined when neither file has the field.
65
+ */
66
+ export function readEnabledModels(cwd: string): string[] | undefined {
67
+ const [project, global] = settingsPaths(cwd);
68
+ return readField(project) ?? readField(global);
69
+ }
70
+
71
+ /**
72
+ * Resolve enabledModels patterns → Set<"provider/modelId"> (lowercase keys).
73
+ *
74
+ * Only exact `provider/modelId` patterns are matched (case-insensitive).
75
+ * Patterns without a slash, with glob characters, or with a `:thinking`
76
+ * suffix are silently dropped. See module-level docstring for rationale.
77
+ *
78
+ * Cache: keyed on JSON.stringify(patterns) + mtime/size of *both*
79
+ * project and global settings.json files. Re-resolves when either file
80
+ * changes or the patterns argument differs.
81
+ *
82
+ * Returns undefined when no patterns are provided or no patterns match
83
+ * (scope check becomes a no-op at the call site).
84
+ */
85
+
86
+ // Module-level cache — invalidated when either settings.json changes or patterns differ.
87
+ let cachedAllowed: Set<string> | undefined;
88
+ let cachedHash = "";
89
+ let cachedPatternsKey = "";
90
+
91
+ /** mtime+size hash of one file, or "missing" if absent. */
92
+ function hashOf(path: string): string {
93
+ try {
94
+ const s = statSync(path);
95
+ return `${s.mtimeMs}-${s.size}`;
96
+ } catch {
97
+ return "missing";
98
+ }
99
+ }
100
+
101
+ export function resolveEnabledModels(
102
+ patterns: string[] | undefined,
103
+ registry: ModelRegistryRef,
104
+ cwd: string = process.cwd(),
105
+ ): Set<string> | undefined {
106
+ // Fast path: check cache (stat both project and global settings.json files)
107
+ const patternsKey = JSON.stringify(patterns);
108
+ const [project, global] = settingsPaths(cwd);
109
+ const fileHash = `${hashOf(project)};${hashOf(global)}`;
110
+
111
+ if (fileHash === cachedHash && patternsKey === cachedPatternsKey) {
112
+ return cachedAllowed;
113
+ }
114
+
115
+ // Cache miss — resolve
116
+ if (!patterns || patterns.length === 0) {
117
+ cachedHash = fileHash;
118
+ cachedPatternsKey = patternsKey;
119
+ cachedAllowed = undefined;
120
+ return undefined;
121
+ }
122
+
123
+ const available = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
124
+ const allowed = new Set<string>();
125
+
126
+ for (const pattern of patterns) {
127
+ const trimmed = pattern.trim();
128
+ if (!trimmed) continue; // skip empty/whitespace
129
+ resolveExact(trimmed, available, allowed);
130
+ }
131
+
132
+ const result = allowed.size > 0 ? allowed : undefined;
133
+ cachedHash = fileHash;
134
+ cachedPatternsKey = patternsKey;
135
+ cachedAllowed = result;
136
+ return result;
137
+ }
138
+
139
+
140
+
141
+ /**
142
+ * True when `model` is in the allowed set. Centralizes the key format
143
+ * (`provider/id` lowercase) so callers don't have to reproduce it —
144
+ * both set-building (resolveExact) and lookup go through `modelKey`.
145
+ */
146
+ export function isModelInScope(
147
+ model: { provider: string; id: string },
148
+ allowed: Set<string>,
149
+ ): boolean {
150
+ return allowed.has(modelKey(model));
151
+ }
152
+
153
+ /** Canonical lowercase `provider/id` key for the allowed set. */
154
+ function modelKey(model: { provider: string; id: string }): string {
155
+ return `${model.provider}/${model.id}`.toLowerCase();
156
+ }
157
+
158
+ /**
159
+ * Resolve exact model pattern. Example: "google/gemma-4-31b-it".
160
+ */
161
+ function resolveExact(
162
+ pattern: string,
163
+ available: ModelEntry[],
164
+ allowed: Set<string>,
165
+ ): void {
166
+ // "provider/modelId" — exact (colon is part of id, not split)
167
+ const slashIdx = pattern.indexOf("/");
168
+ if (slashIdx === -1) return; // bare modelId not supported
169
+
170
+ const provider = pattern.slice(0, slashIdx).toLowerCase();
171
+ const modelId = pattern.slice(slashIdx + 1).toLowerCase();
172
+ const exact = available.find(
173
+ m => m.provider.toLowerCase() === provider && m.id.toLowerCase() === modelId,
174
+ );
175
+ if (exact) {
176
+ allowed.add(modelKey(exact));
177
+ }
178
+ }
179
+
180
+
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Optional machine-local enterprise overlay.
3
+ *
4
+ * This extension deliberately knows no enterprise provider, endpoint, model, or
5
+ * credential. A user-provisioned manifest lives beside Pi's other private state
6
+ * at `<agentDir>/enterprise.local.json`; it is never read from a project.
7
+ */
8
+
9
+ import { existsSync, readFileSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
+
13
+ const MANIFEST_VERSION = 1;
14
+ const MANIFEST_NAME = "enterprise.local.json";
15
+
16
+ export interface EnterpriseLocalManifest {
17
+ version: number;
18
+ settings?: Record<string, unknown>;
19
+ models?: { providers?: Record<string, unknown> };
20
+ subagents?: Record<string, unknown>;
21
+ }
22
+
23
+ /** Return the target-local manifest path without reading it. */
24
+ export function enterpriseLocalPath(): string {
25
+ return join(getAgentDir(), MANIFEST_NAME);
26
+ }
27
+
28
+ /**
29
+ * Read and minimally validate the machine-local manifest. It never exposes its
30
+ * contents in diagnostics: providers can include command-backed credentials.
31
+ */
32
+ export function readEnterpriseLocalManifest(): EnterpriseLocalManifest | undefined {
33
+ const path = enterpriseLocalPath();
34
+ if (!existsSync(path)) return undefined;
35
+
36
+ try {
37
+ const mode = statSync(path).mode & 0o777;
38
+ if ((mode & 0o077) !== 0) {
39
+ console.warn(`[pi-subagents] Ignoring ${path}: permissions must not grant group or other access.`);
40
+ return undefined;
41
+ }
42
+ const raw: unknown = JSON.parse(readFileSync(path, "utf-8"));
43
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
44
+ throw new Error("expected a JSON object");
45
+ }
46
+ const manifest = raw as Record<string, unknown>;
47
+ if (manifest.version !== MANIFEST_VERSION) {
48
+ throw new Error(`unsupported manifest version (expected ${MANIFEST_VERSION})`);
49
+ }
50
+ for (const section of ["settings", "models", "subagents"] as const) {
51
+ const value = manifest[section];
52
+ if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) {
53
+ throw new Error(`section "${section}" must be an object`);
54
+ }
55
+ }
56
+ const models = manifest.models as Record<string, unknown> | undefined;
57
+ if (models?.providers !== undefined && (!models.providers || typeof models.providers !== "object" || Array.isArray(models.providers))) {
58
+ throw new Error('section "models.providers" must be an object');
59
+ }
60
+ return manifest as unknown as EnterpriseLocalManifest;
61
+ } catch (error) {
62
+ const reason = error instanceof Error ? error.message : String(error);
63
+ console.warn(`[pi-subagents] Ignoring invalid ${path}: ${reason}`);
64
+ return undefined;
65
+ }
66
+ }
package/src/env.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * env.ts — Detect environment info (git, platform) for subagent system prompts.
3
+ */
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import type { EnvInfo } from "./types.js";
7
+
8
+ export async function detectEnv(pi: ExtensionAPI, cwd: string): Promise<EnvInfo> {
9
+ let isGitRepo = false;
10
+ let branch = "";
11
+
12
+ try {
13
+ const result = await pi.exec("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 5000 });
14
+ isGitRepo = result.code === 0 && result.stdout.trim() === "true";
15
+ } catch {
16
+ // Not a git repo or git not installed
17
+ }
18
+
19
+ if (isGitRepo) {
20
+ try {
21
+ const result = await pi.exec("git", ["branch", "--show-current"], { cwd, timeout: 5000 });
22
+ branch = result.code === 0 ? result.stdout.trim() : "unknown";
23
+ } catch {
24
+ branch = "unknown";
25
+ }
26
+ }
27
+
28
+ return {
29
+ isGitRepo,
30
+ branch,
31
+ platform: process.platform,
32
+ };
33
+ }
@@ -0,0 +1,148 @@
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
+
9
+ import type { AgentRecord } from "./types.js";
10
+
11
+ export type DeliveryCallback = (records: AgentRecord[], partial: boolean) => void;
12
+
13
+ interface AgentGroup {
14
+ groupId: string;
15
+ agentIds: Set<string>;
16
+ completedRecords: Map<string, AgentRecord>;
17
+ timeoutHandle?: ReturnType<typeof setTimeout>;
18
+ delivered: boolean;
19
+ /** Shorter timeout for stragglers after a partial delivery. */
20
+ isStraggler: boolean;
21
+ }
22
+
23
+ /** Default timeout: 30s after first completion in a group. */
24
+ const DEFAULT_TIMEOUT = 30_000;
25
+ /** Straggler re-batch timeout: 15s. */
26
+ const STRAGGLER_TIMEOUT = 15_000;
27
+
28
+ export class GroupJoinManager {
29
+ private groups = new Map<string, AgentGroup>();
30
+ private agentToGroup = new Map<string, string>();
31
+
32
+ constructor(
33
+ private deliverCb: DeliveryCallback,
34
+ private groupTimeout = DEFAULT_TIMEOUT,
35
+ ) {}
36
+
37
+ /** Register a group of agent IDs that should be joined. */
38
+ registerGroup(groupId: string, agentIds: string[]): void {
39
+ const group: AgentGroup = {
40
+ groupId,
41
+ agentIds: new Set(agentIds),
42
+ completedRecords: new Map(),
43
+ delivered: false,
44
+ isStraggler: false,
45
+ };
46
+ this.groups.set(groupId, group);
47
+ for (const id of agentIds) {
48
+ this.agentToGroup.set(id, groupId);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Called when an agent completes.
54
+ * Returns:
55
+ * - 'pass' — agent is not grouped, caller should send individual nudge
56
+ * - 'held' — result held, waiting for group completion
57
+ * - 'delivered' — this completion triggered the group notification
58
+ */
59
+ onAgentComplete(record: AgentRecord): 'delivered' | 'held' | 'pass' {
60
+ const groupId = this.agentToGroup.get(record.id);
61
+ if (!groupId) return 'pass';
62
+
63
+ const group = this.groups.get(groupId);
64
+ if (!group || group.delivered) return 'pass';
65
+
66
+ group.completedRecords.set(record.id, record);
67
+
68
+ // All done — deliver immediately
69
+ if (group.completedRecords.size >= group.agentIds.size) {
70
+ this.deliver(group, false);
71
+ return 'delivered';
72
+ }
73
+
74
+ // First completion in this batch — start timeout
75
+ if (!group.timeoutHandle) {
76
+ const timeout = group.isStraggler ? STRAGGLER_TIMEOUT : this.groupTimeout;
77
+ group.timeoutHandle = setTimeout(() => {
78
+ this.onTimeout(group);
79
+ }, timeout);
80
+ }
81
+
82
+ return 'held';
83
+ }
84
+
85
+ private onTimeout(group: AgentGroup): void {
86
+ if (group.delivered) return;
87
+ group.timeoutHandle = undefined;
88
+
89
+ // Partial delivery — some agents still running
90
+ const remaining = new Set<string>();
91
+ for (const id of group.agentIds) {
92
+ if (!group.completedRecords.has(id)) remaining.add(id);
93
+ }
94
+
95
+ // Clean up agentToGroup for delivered agents (they won't complete again)
96
+ for (const id of group.completedRecords.keys()) {
97
+ this.agentToGroup.delete(id);
98
+ }
99
+
100
+ // Deliver what we have
101
+ this.deliverCb([...group.completedRecords.values()], true);
102
+
103
+ // Set up straggler group for remaining agents
104
+ group.completedRecords.clear();
105
+ group.agentIds = remaining;
106
+ group.isStraggler = true;
107
+ // Timeout will be started when the next straggler completes
108
+ }
109
+
110
+ private deliver(group: AgentGroup, partial: boolean): void {
111
+ if (group.timeoutHandle) {
112
+ clearTimeout(group.timeoutHandle);
113
+ group.timeoutHandle = undefined;
114
+ }
115
+ group.delivered = true;
116
+ this.deliverCb([...group.completedRecords.values()], partial);
117
+ this.cleanupGroup(group.groupId);
118
+ }
119
+
120
+ private cleanupGroup(groupId: string): void {
121
+ const group = this.groups.get(groupId);
122
+ if (!group) return;
123
+ for (const id of group.agentIds) {
124
+ this.agentToGroup.delete(id);
125
+ }
126
+ this.groups.delete(groupId);
127
+ }
128
+
129
+ /** Check if an agent is in a group. */
130
+ isGrouped(agentId: string): boolean {
131
+ return this.agentToGroup.has(agentId);
132
+ }
133
+
134
+ /** Release held completions to the outbox before a session transfer. */
135
+ flushPending(): void {
136
+ for (const group of [...this.groups.values()]) {
137
+ this.deliver(group, true);
138
+ }
139
+ }
140
+
141
+ dispose(): void {
142
+ for (const group of this.groups.values()) {
143
+ if (group.timeoutHandle) clearTimeout(group.timeoutHandle);
144
+ }
145
+ this.groups.clear();
146
+ this.agentToGroup.clear();
147
+ }
148
+ }