@narumitw/pi-subagents 0.53.0 → 0.54.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 (64) hide show
  1. package/README.md +75 -6
  2. package/package.json +1 -1
  3. package/src/agents/built-ins.ts +124 -0
  4. package/src/agents/catalog.ts +224 -0
  5. package/src/agents/discovery.ts +249 -0
  6. package/src/agents/types.ts +98 -0
  7. package/src/agents.ts +47 -670
  8. package/src/auto-transport.ts +2 -1
  9. package/src/automation.ts +7 -2
  10. package/src/capability-router.ts +1 -1
  11. package/src/completion-delivery.ts +2 -3
  12. package/src/config-status.ts +2 -2
  13. package/src/config-ui.ts +8 -8
  14. package/src/consult-resources.ts +1 -1
  15. package/src/consult.ts +9 -7
  16. package/src/create-stateful-transport.ts +2 -1
  17. package/src/cwd-policy.ts +1 -1
  18. package/src/execution/budget.ts +56 -0
  19. package/src/execution/runtime-policy.ts +19 -0
  20. package/src/execution-plan.ts +1 -1
  21. package/src/execution-profiles.ts +1 -1
  22. package/src/execution-ui.ts +1 -1
  23. package/src/execution.ts +269 -100
  24. package/src/in-process-transport.ts +3 -2
  25. package/src/inspect.ts +35 -8
  26. package/src/limits.ts +1 -0
  27. package/src/orchestration-metrics.ts +12 -5
  28. package/src/panel-execution.ts +1 -1
  29. package/src/panel-planning.ts +1 -1
  30. package/src/params.ts +3 -1
  31. package/src/persistence.ts +1 -1
  32. package/src/registry-types.ts +1 -1
  33. package/src/registry.ts +1 -1
  34. package/src/render.ts +1 -1
  35. package/src/retained-semantic-state.ts +1 -1
  36. package/src/rpc-transport-metadata.ts +1 -1
  37. package/src/rpc-transport.ts +2 -1
  38. package/src/runner.ts +6 -1
  39. package/src/settings/inspection.ts +275 -0
  40. package/src/settings/schema.ts +186 -0
  41. package/src/settings.ts +72 -420
  42. package/src/spawn-idempotency.ts +1 -1
  43. package/src/stateful-agent-view.ts +87 -0
  44. package/src/stateful-config.ts +1 -1
  45. package/src/stateful-guidance.ts +1 -1
  46. package/src/stateful-limits.ts +1 -1
  47. package/src/stateful-prompt.ts +2 -2
  48. package/src/stateful-safety.ts +2 -1
  49. package/src/stateful.ts +23 -103
  50. package/src/subagents.ts +8 -9
  51. package/src/subprocess-transport.ts +2 -6
  52. package/src/transport-types.ts +1 -1
  53. package/src/transport-ui.ts +1 -1
  54. package/src/verification-harness.ts +516 -0
  55. package/src/verification-receipt.ts +275 -0
  56. package/src/verified-execution-benchmark.ts +86 -0
  57. package/src/verified-execution-contract.ts +219 -0
  58. package/src/work-item-ledger.ts +510 -37
  59. package/src/work-item-persistence.ts +31 -0
  60. package/src/workflow-completion-controller.ts +397 -0
  61. package/src/workflow-plan-compiler.ts +1 -1
  62. package/src/workflow-plan-patch.ts +1 -1
  63. package/src/workflow-planning.ts +11 -1
  64. package/src/workflow-ui.ts +1 -1
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Filesystem and frontmatter discovery for user and trusted project agents.
3
+ */
4
+
5
+ import * as fs from "node:fs";
6
+ import * as path from "node:path";
7
+ import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
8
+ import { normalizeCapabilityManifest } from "../capabilities.js";
9
+ import { BUILT_IN_AGENTS } from "./built-ins.js";
10
+ import type { AgentConfig, AgentScope, SubagentSettings } from "./types.js";
11
+ import { isThinkingLevel } from "./types.js";
12
+
13
+ export interface AgentDiscoveryResult {
14
+ agents: AgentConfig[];
15
+ projectAgentsDir: string | null;
16
+ omittedAgentDefinitions?: number;
17
+ metadataDiscoveryIncomplete?: boolean;
18
+ }
19
+
20
+ export interface AgentDiscoveryOptions {
21
+ maxFiles?: number;
22
+ maxFileBytes?: number;
23
+ maxTotalBytes?: number;
24
+ }
25
+
26
+ interface LoadedAgents {
27
+ agents: AgentConfig[];
28
+ omittedAgentDefinitions: number;
29
+ metadataDiscoveryIncomplete: boolean;
30
+ }
31
+
32
+ function readFileBoundedSync(
33
+ filePath: string,
34
+ maxBytes: number | undefined,
35
+ ): { content?: string; bytes: number; limited: boolean } {
36
+ if (maxBytes === undefined) {
37
+ try {
38
+ const content = fs.readFileSync(filePath, "utf-8");
39
+ return { content, bytes: Buffer.byteLength(content), limited: false };
40
+ } catch {
41
+ return { bytes: 0, limited: false };
42
+ }
43
+ }
44
+
45
+ const readLimit = Math.max(0, maxBytes);
46
+ let fd: number | undefined;
47
+ try {
48
+ fd = fs.openSync(filePath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK);
49
+ if (!fs.fstatSync(fd).isFile()) return { bytes: 0, limited: false };
50
+ const buffer = Buffer.allocUnsafe(readLimit + 1);
51
+ let offset = 0;
52
+ while (offset < buffer.length) {
53
+ const bytesRead = fs.readSync(fd, buffer, offset, buffer.length - offset, null);
54
+ if (bytesRead === 0) break;
55
+ offset += bytesRead;
56
+ }
57
+ if (offset > readLimit) return { bytes: offset, limited: true };
58
+ return { content: buffer.subarray(0, offset).toString("utf-8"), bytes: offset, limited: false };
59
+ } catch {
60
+ return { bytes: 0, limited: false };
61
+ } finally {
62
+ if (fd !== undefined) fs.closeSync(fd);
63
+ }
64
+ }
65
+
66
+ function loadAgentsFromDir(
67
+ dir: string,
68
+ source: "user" | "project",
69
+ options: AgentDiscoveryOptions = {},
70
+ ): LoadedAgents {
71
+ const agents: AgentConfig[] = [];
72
+ let omittedAgentDefinitions = 0;
73
+
74
+ let entries: fs.Dirent[];
75
+ try {
76
+ entries = fs.readdirSync(dir, { withFileTypes: true });
77
+ } catch (error) {
78
+ return {
79
+ agents,
80
+ omittedAgentDefinitions,
81
+ metadataDiscoveryIncomplete: (error as NodeJS.ErrnoException).code !== "ENOENT",
82
+ };
83
+ }
84
+
85
+ const agentEntries = entries
86
+ .filter((entry) => entry.name.endsWith(".md"))
87
+ .filter((entry) => entry.isFile() || entry.isSymbolicLink());
88
+ let totalBytes = 0;
89
+
90
+ for (const [index, entry] of agentEntries.entries()) {
91
+ if (options.maxFiles !== undefined && index >= options.maxFiles) {
92
+ omittedAgentDefinitions += agentEntries.length - index;
93
+ break;
94
+ }
95
+ const filePath = path.join(dir, entry.name);
96
+ const remainingBytes =
97
+ options.maxTotalBytes === undefined ? undefined : options.maxTotalBytes - totalBytes;
98
+ if (remainingBytes !== undefined && remainingBytes <= 0) {
99
+ omittedAgentDefinitions++;
100
+ continue;
101
+ }
102
+ const maxBytes =
103
+ options.maxFileBytes === undefined
104
+ ? remainingBytes
105
+ : remainingBytes === undefined
106
+ ? options.maxFileBytes
107
+ : Math.min(options.maxFileBytes, remainingBytes);
108
+ const loaded = readFileBoundedSync(filePath, maxBytes);
109
+ totalBytes += Math.min(loaded.bytes, maxBytes ?? loaded.bytes);
110
+ if (loaded.limited || loaded.content === undefined) {
111
+ if (loaded.limited) omittedAgentDefinitions++;
112
+ continue;
113
+ }
114
+
115
+ const { frontmatter, body } = parseFrontmatter<Record<string, unknown>>(loaded.content);
116
+
117
+ if (typeof frontmatter.name !== "string" || typeof frontmatter.description !== "string") {
118
+ continue;
119
+ }
120
+
121
+ const hasTools = hasOwn(frontmatter, "tools");
122
+ const rawTools = frontmatter.tools;
123
+ let tools: string[] | undefined;
124
+ if (hasTools) {
125
+ if (rawTools === null) {
126
+ tools = [];
127
+ } else if (Array.isArray(rawTools)) {
128
+ if (!rawTools.every((tool): tool is string => typeof tool === "string")) continue;
129
+ tools = rawTools.map((tool) => tool.trim()).filter(Boolean);
130
+ } else if (typeof rawTools === "string") {
131
+ tools = rawTools
132
+ .split(",")
133
+ .map((tool) => tool.trim())
134
+ .filter(Boolean);
135
+ } else {
136
+ continue;
137
+ }
138
+ }
139
+
140
+ agents.push({
141
+ name: frontmatter.name,
142
+ description: frontmatter.description,
143
+ ...(hasTools ? { tools: tools ?? [] } : {}),
144
+ model: typeof frontmatter.model === "string" ? frontmatter.model : undefined,
145
+ thinkingLevel: isThinkingLevel(frontmatter.thinkingLevel)
146
+ ? frontmatter.thinkingLevel
147
+ : undefined,
148
+ capabilityManifest: normalizeCapabilityManifest(frontmatter.capabilityManifest),
149
+ systemPrompt: body,
150
+ source,
151
+ filePath,
152
+ });
153
+ }
154
+
155
+ return { agents, omittedAgentDefinitions, metadataDiscoveryIncomplete: false };
156
+ }
157
+
158
+ function isDirectory(p: string): boolean {
159
+ try {
160
+ return fs.statSync(p).isDirectory();
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
165
+
166
+ function findNearestProjectAgentsDir(cwd: string): string | null {
167
+ let currentDir = cwd;
168
+ while (true) {
169
+ const candidate = path.join(currentDir, CONFIG_DIR_NAME, "agents");
170
+ if (isDirectory(candidate)) return candidate;
171
+
172
+ const parentDir = path.dirname(currentDir);
173
+ if (parentDir === currentDir) return null;
174
+ currentDir = parentDir;
175
+ }
176
+ }
177
+
178
+ function hasOwn(obj: object, key: PropertyKey): boolean {
179
+ return Object.hasOwn(obj, key);
180
+ }
181
+
182
+ export function discoverAgents(
183
+ cwd: string,
184
+ scope: AgentScope,
185
+ config?: SubagentSettings,
186
+ options: AgentDiscoveryOptions = {},
187
+ ): AgentDiscoveryResult {
188
+ const userDir = path.join(getAgentDir(), "agents");
189
+ const projectAgentsDir = findNearestProjectAgentsDir(cwd);
190
+
191
+ const userLoaded =
192
+ scope === "project"
193
+ ? { agents: [], omittedAgentDefinitions: 0, metadataDiscoveryIncomplete: false }
194
+ : loadAgentsFromDir(userDir, "user", options);
195
+ const projectLoaded =
196
+ scope === "user" || !projectAgentsDir
197
+ ? { agents: [], omittedAgentDefinitions: 0, metadataDiscoveryIncomplete: false }
198
+ : loadAgentsFromDir(projectAgentsDir, "project", options);
199
+ const userAgents = userLoaded.agents;
200
+ const projectAgents = projectLoaded.agents;
201
+
202
+ const agentMap = new Map<string, AgentConfig>();
203
+
204
+ // Lowest priority: built-ins are always available, then user agents, then
205
+ // trusted project agents if requested. This mirrors the subagent boundary
206
+ // pattern in ./src: stable built-ins plus overridable local definitions.
207
+ for (const agent of BUILT_IN_AGENTS) agentMap.set(agent.name, agent);
208
+
209
+ if (scope === "both") {
210
+ for (const agent of userAgents) agentMap.set(agent.name, agent);
211
+ for (const agent of projectAgents) agentMap.set(agent.name, agent);
212
+ } else if (scope === "user") {
213
+ for (const agent of userAgents) agentMap.set(agent.name, agent);
214
+ } else {
215
+ for (const agent of projectAgents) agentMap.set(agent.name, agent);
216
+ }
217
+
218
+ // Apply user-configured overrides (from /subagents → Agent tool settings) on top of
219
+ // the final resolved agent map, regardless of agent source.
220
+ for (const [name, override] of Object.entries(config?.agents ?? {})) {
221
+ const agent = agentMap.get(name);
222
+ if (!agent) continue;
223
+
224
+ const nextAgent: AgentConfig = { ...agent };
225
+ if (hasOwn(override, "tools")) nextAgent.tools = override.tools;
226
+ if (hasOwn(override, "model")) {
227
+ nextAgent.model = override.model === null ? undefined : override.model;
228
+ }
229
+ if (hasOwn(override, "thinkingLevel")) {
230
+ nextAgent.thinkingLevel =
231
+ override.thinkingLevel === null ? undefined : override.thinkingLevel;
232
+ }
233
+ if (hasOwn(override, "timeoutMs")) {
234
+ nextAgent.timeoutMs = override.timeoutMs === null ? undefined : override.timeoutMs;
235
+ }
236
+ agentMap.set(name, nextAgent);
237
+ }
238
+
239
+ const omittedAgentDefinitions =
240
+ userLoaded.omittedAgentDefinitions + projectLoaded.omittedAgentDefinitions;
241
+ const metadataDiscoveryIncomplete =
242
+ userLoaded.metadataDiscoveryIncomplete || projectLoaded.metadataDiscoveryIncomplete;
243
+ return {
244
+ agents: Array.from(agentMap.values()),
245
+ projectAgentsDir,
246
+ ...(omittedAgentDefinitions > 0 ? { omittedAgentDefinitions } : {}),
247
+ ...(metadataDiscoveryIncomplete ? { metadataDiscoveryIncomplete } : {}),
248
+ };
249
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Foundational agent and settings types with dependency-light validation helpers.
3
+ */
4
+
5
+ import type { AgentCapabilityManifest } from "../capabilities.js";
6
+
7
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
8
+
9
+ export type SubagentThinkingLevel = (typeof THINKING_LEVELS)[number];
10
+
11
+ export function isThinkingLevel(value: unknown): value is SubagentThinkingLevel {
12
+ return typeof value === "string" && THINKING_LEVELS.includes(value as SubagentThinkingLevel);
13
+ }
14
+
15
+ export type AgentScope = "user" | "project" | "both";
16
+
17
+ export type AgentSource = "built-in" | "user" | "project";
18
+
19
+ export const DEFAULT_PI_TOOL_NAMES = ["read", "bash", "edit", "write"] as const;
20
+
21
+ export function resolveAgentToolNames(tools: readonly string[] | undefined): string[] {
22
+ return [...new Set(tools ?? DEFAULT_PI_TOOL_NAMES)];
23
+ }
24
+
25
+ export interface AgentConfig {
26
+ name: string;
27
+ description: string;
28
+ tools?: string[];
29
+ model?: string;
30
+ thinkingLevel?: SubagentThinkingLevel;
31
+ timeoutMs?: number;
32
+ capabilityManifest?: AgentCapabilityManifest;
33
+ systemPrompt: string;
34
+ source: AgentSource;
35
+ filePath: string;
36
+ }
37
+
38
+ export interface SubagentAgentConfig {
39
+ tools?: string[];
40
+ model?: string | null;
41
+ thinkingLevel?: SubagentThinkingLevel | null;
42
+ timeoutMs?: number | null;
43
+ }
44
+
45
+ export type SubagentTransportKind = "subprocess" | "in-process" | "rpc" | "auto";
46
+
47
+ export type CompletionDelivery = "next-turn" | "auto-resume";
48
+
49
+ export const CONSULT_RESOURCE_POLICIES = ["project-context", "none", "all"] as const;
50
+
51
+ export type ConsultResourcePolicy = (typeof CONSULT_RESOURCE_POLICIES)[number];
52
+
53
+ export interface SubagentConsultSettings {
54
+ resources?: ConsultResourcePolicy;
55
+ }
56
+
57
+ export const CONSULTATION_CWD_POLICIES = ["anywhere", "current-workspace"] as const;
58
+ export type ConsultationCwdPolicy = (typeof CONSULTATION_CWD_POLICIES)[number];
59
+
60
+ export const DELEGATION_CWD_POLICIES = [
61
+ "trusted-targets",
62
+ "current-workspace",
63
+ "anywhere",
64
+ ] as const;
65
+ export type DelegationCwdPolicy = (typeof DELEGATION_CWD_POLICIES)[number];
66
+
67
+ export interface SubagentCwdPolicySettings {
68
+ consultation?: ConsultationCwdPolicy;
69
+ delegation?: DelegationCwdPolicy;
70
+ }
71
+
72
+ export interface SubagentBlockingSettings {
73
+ enabled?: boolean;
74
+ maxParallelTasks?: number;
75
+ }
76
+
77
+ export interface SubagentRuntimeSettings {
78
+ enabled?: boolean;
79
+ transport?: SubagentTransportKind;
80
+ completionDelivery?: CompletionDelivery;
81
+ maxAgents?: number;
82
+ maxActiveTurns?: number;
83
+ maxDepth?: number;
84
+ maxChildrenPerAgent?: number;
85
+ maxMailboxMessages?: number;
86
+ maxMailboxMessageBytes?: number;
87
+ idleTtlMs?: number;
88
+ retentionDays?: number;
89
+ maxStoredAgents?: number;
90
+ }
91
+
92
+ export interface SubagentSettings {
93
+ agents?: Record<string, SubagentAgentConfig>;
94
+ blocking?: SubagentBlockingSettings;
95
+ stateful?: SubagentRuntimeSettings;
96
+ consult?: SubagentConsultSettings;
97
+ cwdPolicy?: SubagentCwdPolicySettings;
98
+ }