brl-subagent 2.5.2 → 2.7.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.
package/src/presets.ts CHANGED
@@ -12,61 +12,12 @@ import * as path from "node:path";
12
12
  import type { SubagentPreset, ThinkingLevel } from "./types";
13
13
  import { THINKING_LEVELS } from "./types";
14
14
  import type { Logger } from "./logging";
15
+ import { loadMarkdownRecords } from "./loader";
15
16
 
16
- // ---------------------------------------------------------------------------
17
- // Frontmatter parsing
18
- // ---------------------------------------------------------------------------
19
-
20
- /**
21
- * Parse YAML frontmatter from a markdown file.
22
- * Returns metadata key-value pairs and the body content.
23
- */
24
- export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
25
- const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
26
- if (!match) return { meta: {}, body: content };
27
-
28
- const meta: Record<string, unknown> = {};
29
- const lines = match[1].split("\n");
30
- let currentKey = "";
31
- let currentArray: string[] | null = null;
32
-
33
- for (const line of lines) {
34
- // Array item: starts with "- "
35
- if (line.match(/^\s+-\s+/)) {
36
- if (currentArray !== null) {
37
- currentArray.push(line.replace(/^\s+-\s+/, "").trim());
38
- }
39
- continue;
40
- }
41
-
42
- // End of array if we were in one
43
- if (currentArray !== null) {
44
- meta[currentKey] = currentArray;
45
- currentArray = null;
46
- }
47
-
48
- // Key-value pair
49
- const kvMatch = line.match(/^(\w+):\s*(.*)$/);
50
- if (kvMatch) {
51
- const key = kvMatch[1];
52
- const value = kvMatch[2].trim();
53
- // Check if next line starts an array
54
- if (value === "") {
55
- currentKey = key;
56
- currentArray = [];
57
- } else {
58
- // Strip quotes if present
59
- meta[key] = value.replace(/^["']|["']$/g, "");
60
- }
61
- }
62
- }
63
- // Close any pending array
64
- if (currentArray !== null) {
65
- meta[currentKey] = currentArray;
66
- }
67
-
68
- return { meta, body: match[2].trim() };
69
- }
17
+ // `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
18
+ // into one walk (issue #380). Re-exported so the existing import sites keep
19
+ // working unchanged.
20
+ export { parseFrontmatter } from "./loader";
70
21
 
71
22
  // ---------------------------------------------------------------------------
72
23
  // Preset validation
@@ -120,54 +71,47 @@ export function validatePreset(meta: Record<string, unknown>, fileName: string):
120
71
  // Loading
121
72
  // ---------------------------------------------------------------------------
122
73
 
74
+ /**
75
+ * Normalise validated preset frontmatter into a SubagentPreset. Shared by both
76
+ * preset tiers — the file walk and validation live in loadMarkdownRecords.
77
+ */
78
+ function presetFromFrontmatter(
79
+ meta: Record<string, unknown>,
80
+ body: string,
81
+ name: string,
82
+ ): SubagentPreset {
83
+ return {
84
+ name,
85
+ description: (meta.description as string) || undefined,
86
+ systemPrompt: body || undefined,
87
+ thinkingLevel: (meta.thinkingLevel as string) || undefined,
88
+ model: (meta.model as string) || undefined,
89
+ inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
90
+ tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
91
+ excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
92
+ noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
93
+ promptGuideline: (meta.promptGuideline as string) || undefined,
94
+ };
95
+ }
96
+
123
97
  /**
124
98
  * Load built-in presets from a directory of markdown files.
125
99
  * Files must have YAML frontmatter with at least a `name` field.
126
100
  * Invalid files are skipped with log warnings.
127
101
  */
128
102
  export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPreset[] {
129
- const presets: SubagentPreset[] = [];
130
-
131
- try {
132
- const files = fs.readdirSync(presetsDir);
133
- for (const file of files) {
134
- if (!file.endsWith(".md")) continue;
135
-
136
- try {
137
- const filePath = path.join(presetsDir, file);
138
- const content = fs.readFileSync(filePath, "utf-8");
139
- const { meta, body } = parseFrontmatter(content);
140
-
141
- const errors = validatePreset(meta, file);
142
- if (errors.length > 0) {
143
- for (const err of errors) {
144
- log?.warn("Preset validation failed", { file, error: err });
145
- }
146
- continue;
147
- }
148
-
149
- const name = meta.name as string;
150
-
151
- presets.push({
152
- name,
153
- description: (meta.description as string) || undefined,
154
- systemPrompt: body || undefined,
155
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
156
- model: (meta.model as string) || undefined,
157
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
158
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
159
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
160
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
161
- promptGuideline: (meta.promptGuideline as string) || undefined,
162
- });
163
- } catch (err) {
164
- log?.warn("Failed to load preset file", { file, error: (err as Error).message });
165
- }
166
- }
167
- } catch {
168
- // Presets directory doesn't exist or can't be read — no built-in presets
169
- log?.info("No built-in presets directory found", { dir: presetsDir });
170
- }
103
+ const presets = loadMarkdownRecords<SubagentPreset>({
104
+ dirs: [presetsDir],
105
+ validate: validatePreset,
106
+ map: presetFromFrontmatter,
107
+ log,
108
+ messages: {
109
+ invalid: "Preset validation failed",
110
+ readFailed: "Failed to load preset file",
111
+ },
112
+ // Built-in presets directory doesn't exist or can't be read — no built-in presets
113
+ onMissingDir: (dir) => log?.info("No built-in presets directory found", { dir }),
114
+ });
171
115
 
172
116
  // Validate all loaded presets
173
117
  const validationErrors = validateAllPresets(presets);
@@ -195,60 +139,24 @@ export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPr
195
139
  * 2. ~/.pi/agent/brl-subagent/presets/ (global)
196
140
  */
197
141
  export function loadCustomPresets(cwd: string, log?: Logger): SubagentPreset[] {
198
- const presets: SubagentPreset[] = [];
199
- const seenNames = new Set<string>();
200
142
  const homedir = process.env.HOME || process.env.USERPROFILE || "";
201
143
 
202
- const dirs = [
203
- path.join(cwd, ".pi", "brl-subagent", "presets"),
204
- path.join(homedir, ".pi", "agent", "brl-subagent", "presets"),
205
- ];
206
-
207
- for (const dir of dirs) {
208
- try {
209
- const files = fs.readdirSync(dir);
210
- for (const file of files) {
211
- if (!file.endsWith(".md")) continue;
212
- try {
213
- const filePath = path.join(dir, file);
214
- const content = fs.readFileSync(filePath, "utf-8");
215
- const { meta, body } = parseFrontmatter(content);
216
-
217
- const errors = validatePreset(meta, file);
218
- if (errors.length > 0) {
219
- for (const err of errors) {
220
- log?.warn("Custom preset validation failed", { file, error: err });
221
- }
222
- continue;
223
- }
224
-
225
- const name = meta.name as string;
226
- // Dedup by name: the first occurrence (project-local, scanned
227
- // first) wins; user-global duplicates are skipped.
228
- if (seenNames.has(name)) continue;
229
- seenNames.add(name);
230
- presets.push({
231
- name,
232
- description: (meta.description as string) || undefined,
233
- systemPrompt: body || undefined,
234
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
235
- model: (meta.model as string) || undefined,
236
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
237
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
238
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
239
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
240
- promptGuideline: (meta.promptGuideline as string) || undefined,
241
- });
242
- } catch (err) {
243
- log?.warn("Failed to load custom preset file", { file, error: (err as Error).message });
244
- }
245
- }
246
- } catch {
247
- // Directory doesn't exist — that's fine, no custom presets
248
- }
249
- }
250
-
251
- return presets;
144
+ return loadMarkdownRecords<SubagentPreset>({
145
+ dirs: [
146
+ path.join(cwd, ".pi", "brl-subagent", "presets"),
147
+ path.join(homedir, ".pi", "agent", "brl-subagent", "presets"),
148
+ ],
149
+ validate: validatePreset,
150
+ map: presetFromFrontmatter,
151
+ // Dedup by name: the first occurrence (project-local, scanned first) wins.
152
+ dedupeByName: true,
153
+ log,
154
+ messages: {
155
+ invalid: "Custom preset validation failed",
156
+ readFailed: "Failed to load custom preset file",
157
+ },
158
+ // A missing directory is fine — no custom presets in that tier.
159
+ });
252
160
  }
253
161
 
254
162
  // ---------------------------------------------------------------------------
@@ -0,0 +1,58 @@
1
+ // Purpose: The single reader for the project-local `brl-subagent` umbrella flags (issue #415).
2
+ /**
3
+ * The umbrella project-local flag: `{"brl-subagent": {"processChecks": true}}`.
4
+ *
5
+ * `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
6
+ * (#407/#412) and rule 2's durable-shape auto-switch (#412). It replaces the
7
+ * merged-but-unreleased `requireJevLine`: one flag, one reader, no per-rule
8
+ * fields.
9
+ *
10
+ * Why one reader (issue #415): the shape rule shipped GLOBAL, so a user's
11
+ * explicit `background: false` + timeout was overridden by our conductor
12
+ * decision rule. A conductor rule is not product behavior. Scoping both
13
+ * mechanisms behind one project-local opt-in keeps a user's dispatch exactly as
14
+ * they asked for it, and this module is the only place the manifest field is
15
+ * read (the ratchet in `project-flags.test.ts` fails a second reader).
16
+ *
17
+ * FAIL-OPEN is the product contract: a missing, unreadable or malformed
18
+ * `package.json` means `false`. A project's packaging mistake must never reject
19
+ * a user's dispatch or reshape it.
20
+ *
21
+ * The manifest read is the project's OWN `package.json` — tracked, so it exists
22
+ * in every worktree (worktrees share the repo's manifest), unlike a gitignored
23
+ * marker under `.pi/`.
24
+ */
25
+
26
+ import { readFileSync } from "node:fs";
27
+ import { join } from "node:path";
28
+
29
+ /**
30
+ * The fields this module is allowed to read from the `brl-subagent` section.
31
+ * A third field is a new mechanism, and a new mechanism needs its own ADR and
32
+ * its own line in this whitelist (the ratchet enforces both directions).
33
+ */
34
+ export const PROCESS_CHECK_KEYS = ["processChecks"] as const;
35
+
36
+ /**
37
+ * Whether the project at `cwd` opted into our process checks. Fail-open in
38
+ * every failure mode: no cwd, no manifest, unreadable manifest, malformed JSON,
39
+ * a non-object section, or a non-boolean field all read as `false`.
40
+ */
41
+ export function readProcessChecks(cwd: string | undefined): boolean {
42
+ if (cwd === undefined || cwd === "") return false;
43
+ try {
44
+ const manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8")) as {
45
+ "brl-subagent"?: { processChecks?: unknown };
46
+ };
47
+ return manifest?.["brl-subagent"]?.processChecks === true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The validation seam's name for the same read (`validatePreTask` asks "is the
55
+ * check enabled for this project?"). One implementation: this is an alias, not
56
+ * a second reader.
57
+ */
58
+ export const isProcessChecksEnabled = readProcessChecks;
@@ -35,6 +35,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
35
35
  import type { ProcessOwner, RecoveryMode, SubagentRun } from "./types";
36
36
  import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES } from "./types";
37
37
  import { assertSafeAgentId } from "./sanitize";
38
+ import { ensureOwnerOnlyDir } from "./store-permissions";
38
39
 
39
40
  /** Which execution path owns an in-flight run (drives the boot scan's mark). */
40
41
  export type InflightRunKind = "foreground" | "unit" | "background";
@@ -126,7 +127,9 @@ function resolvePath(id: string): string | null {
126
127
  }
127
128
 
128
129
  function ensureDir(): void {
129
- fs.mkdirSync(REGISTRY_DIR, { recursive: true, mode: 0o700 });
130
+ // Issue #408: `mode` only applies on CREATE — repair a pre-existing registry
131
+ // dir on every write so the entries stay untraversable by other local users.
132
+ ensureOwnerOnlyDir(REGISTRY_DIR);
130
133
  }
131
134
 
132
135
  /** True when `value` looks like a registry entry (id + kind + startedAt). */
package/src/schema.ts CHANGED
@@ -7,6 +7,50 @@
7
7
  import { Type } from "typebox";
8
8
  import { MAX_CHAIN_STEPS, MAX_PARALLEL_TASKS, MAX_GRAPH_TASKS } from "./types";
9
9
 
10
+ /**
11
+ * Issue #381 (audit D7): the per-unit fields registered for `chain[]` steps,
12
+ * `tasks[]` items and `graph[]` nodes — defined once here, spread into the
13
+ * three `Type.Object` literals below.
14
+ *
15
+ * The modes differ only in their `task` wording, whether the unit carries a
16
+ * per-unit `priority` (chain[] does not: its steps never compete for a
17
+ * concurrency slot, array order IS the priority), and graph's node-only
18
+ * `id`/`dependsOn`. Those differences are slotted at their existing positions
19
+ * because the registered key ORDER is part of the contract — the schema is the
20
+ * LLM contract, so this extraction must not reorder a single field.
21
+ */
22
+ const STEP_HEAD_FIELDS = {
23
+ label: Type.Optional(Type.String({})),
24
+ model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
25
+ };
26
+
27
+ const STEP_THINKING_LEVEL_FIELD = {
28
+ thinkingLevel: Type.Optional(Type.String({})),
29
+ };
30
+
31
+ /** Per-unit concurrency priority — tasks[] and graph[] only (issue #114). */
32
+ const STEP_PRIORITY_FIELD = {
33
+ priority: Type.Optional(
34
+ Type.Union([
35
+ Type.Literal("critical"),
36
+ Type.Literal("high"),
37
+ Type.Literal("normal"),
38
+ Type.Literal("low"),
39
+ ], { description: "Concurrency priority for this subtask (overrides the call-level default)." }),
40
+ ),
41
+ };
42
+
43
+ const STEP_TAIL_FIELDS = {
44
+ cwd: Type.Optional(Type.String({})),
45
+ timeout: Type.Optional(Type.Number({})),
46
+ outputFile: Type.Optional(Type.String({})),
47
+ tools: Type.Optional(Type.Array(Type.String({}))),
48
+ excludeTools: Type.Optional(Type.Array(Type.String({}))),
49
+ noBuiltinTools: Type.Optional(Type.Boolean({})),
50
+ systemPrompt: Type.Optional(Type.String({})),
51
+ inheritSystemPrompt: Type.Optional(Type.Boolean({})),
52
+ };
53
+
10
54
  export const delegateTaskParamsSchema = Type.Object({
11
55
  task: Type.Optional(Type.String({
12
56
  description: "Detailed description of the task for the subagent to complete (required for single mode, optional for chain/tasks/graph)",
@@ -143,7 +187,7 @@ export const delegateTaskParamsSchema = Type.Object({
143
187
  description:
144
188
  "If true and a FOREGROUND subagent times out, automatically retry with the same parameters. " +
145
189
  "Only retries once — the second timeout is treated as a final failure. " +
146
- "Background runs are not auto-retried; re-dispatch with retryRunId.",
190
+ "A background run is not retried on its deadline, but it is retried once automatically on a transport-class error; any other background failure needs an explicit retryRunId.",
147
191
  }),
148
192
  ),
149
193
  approvalMode: Type.Optional(
@@ -162,6 +206,16 @@ export const delegateTaskParamsSchema = Type.Object({
162
206
  "Warnings are surfaced either way. force never suppresses outputFile-without-write conflicts.",
163
207
  }),
164
208
  ),
209
+ noJev: Type.Optional(
210
+ Type.String({
211
+ minLength: 1,
212
+ description:
213
+ "Stated bypass for the Jev dispatch-line pre-flight, which is active ONLY in a project whose package.json sets the `brl-subagent.processChecks` field (this repository). " +
214
+ "A NON-EMPTY reason string: the dispatch proceeds and the reason is surfaced as a warning in the result, so the bypass is never silent. " +
215
+ "It bypasses ONLY the line check — capability conflicts still reject (unlike force). " +
216
+ "Append `jev: unavailable` to the task instead when the classifier did not run.",
217
+ }),
218
+ ),
165
219
  background: Type.Optional(
166
220
  Type.Boolean({
167
221
  description:
@@ -169,7 +223,9 @@ export const delegateTaskParamsSchema = Type.Object({
169
223
  "When true, the tool returns immediately with an agent ID. " +
170
224
  "The conductor is woken with a completion message; use get_subagent_result for post-wake retrieval and stall checks. " +
171
225
  "Supports a single task or the tasks array (a fan-out that starts one background agent per task; with tasks the call returns one ID per task and the conductor is woken once per agent as each finishes); combining background with chain or graph is rejected. " +
172
- "Default: false (blocking mode).",
226
+ "Default: conditional. Omitted, a single task or tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config); it stays foreground for 'writes'/'always' (a background run has no approval dialog, so the gate must stay in front of the user) and for chain/graph, which block by definition. " +
227
+ "Pass background: false for a quick probe whose answer the next step needs inline. Explicit true/false wins. ONE pre-flight exception exists, and only in a project that opted into its own process checks (package.json `brl-subagent.processChecks: true`; this repository): a high/xhigh-thinking dispatch with background: false AND an explicit timeout is switched to background and the explicit timeout is dropped, because a foreground run loses its whole work at a timeout while a background run keeps its session and is retried on a transport error; pass force: true to keep it foreground. Without that project opt-in the explicit shape and its timeout stand. " +
228
+ "A background run defaults to a 30-minute deadline when no timeout is given.",
173
229
  }),
174
230
  ),
175
231
  priority: Type.Optional(
@@ -187,67 +243,29 @@ export const delegateTaskParamsSchema = Type.Object({
187
243
  // duration); array order IS the priority.
188
244
  chain: Type.Optional(Type.Array(Type.Object({
189
245
  task: Type.String({ description: "Task description. Use {previous} to reference the previous step output." }),
190
- label: Type.Optional(Type.String({})),
191
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
192
- thinkingLevel: Type.Optional(Type.String({})),
193
- cwd: Type.Optional(Type.String({})),
194
- timeout: Type.Optional(Type.Number({})),
195
- outputFile: Type.Optional(Type.String({})),
196
- tools: Type.Optional(Type.Array(Type.String({}))),
197
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
198
- noBuiltinTools: Type.Optional(Type.Boolean({})),
199
- systemPrompt: Type.Optional(Type.String({})),
200
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
246
+ ...STEP_HEAD_FIELDS,
247
+ ...STEP_THINKING_LEVEL_FIELD,
248
+ ...STEP_TAIL_FIELDS,
201
249
  }), {
202
250
  description: "Sequential chain of tasks. Each step receives the previous step output via {previous} placeholder in the task string. Chain stops at the first failure. Max " + MAX_CHAIN_STEPS + " steps."
203
251
  })),
204
252
  tasks: Type.Optional(Type.Array(Type.Object({
205
253
  task: Type.String({ description: "Task description for this parallel subtask" }),
206
- label: Type.Optional(Type.String({})),
207
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
208
- thinkingLevel: Type.Optional(Type.String({})),
209
- priority: Type.Optional(
210
- Type.Union([
211
- Type.Literal("critical"),
212
- Type.Literal("high"),
213
- Type.Literal("normal"),
214
- Type.Literal("low"),
215
- ], { description: "Concurrency priority for this subtask (overrides the call-level default)." })
216
- ),
217
- cwd: Type.Optional(Type.String({})),
218
- timeout: Type.Optional(Type.Number({})),
219
- outputFile: Type.Optional(Type.String({})),
220
- tools: Type.Optional(Type.Array(Type.String({}))),
221
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
222
- noBuiltinTools: Type.Optional(Type.Boolean({})),
223
- systemPrompt: Type.Optional(Type.String({})),
224
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
254
+ ...STEP_HEAD_FIELDS,
255
+ ...STEP_THINKING_LEVEL_FIELD,
256
+ ...STEP_PRIORITY_FIELD,
257
+ ...STEP_TAIL_FIELDS,
225
258
  }), {
226
259
  description: "Parallel tasks to execute concurrently. All tasks run regardless of individual failures. Max " + MAX_PARALLEL_TASKS + " tasks."
227
260
  })),
228
261
  graph: Type.Optional(Type.Array(Type.Object({
229
262
  id: Type.String({ description: "Unique identifier for this task node" }),
230
263
  task: Type.String({ description: "Task description. Use {<nodeId>} to reference output from another task (the referenced node's own id, which must be a word-character id - letters, digits, underscore; ids like 'step-1' or 'node.a' are not matched and the braces are left as literal text)." }),
231
- label: Type.Optional(Type.String({})),
232
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
264
+ ...STEP_HEAD_FIELDS,
233
265
  dependsOn: Type.Optional(Type.Array(Type.String({}), { description: "IDs of tasks that must complete before this one starts" })),
234
- thinkingLevel: Type.Optional(Type.String({})),
235
- priority: Type.Optional(
236
- Type.Union([
237
- Type.Literal("critical"),
238
- Type.Literal("high"),
239
- Type.Literal("normal"),
240
- Type.Literal("low"),
241
- ], { description: "Concurrency priority for this subtask (overrides the call-level default)." })
242
- ),
243
- cwd: Type.Optional(Type.String({})),
244
- timeout: Type.Optional(Type.Number({})),
245
- outputFile: Type.Optional(Type.String({})),
246
- tools: Type.Optional(Type.Array(Type.String({}))),
247
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
248
- noBuiltinTools: Type.Optional(Type.Boolean({})),
249
- systemPrompt: Type.Optional(Type.String({})),
250
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
266
+ ...STEP_THINKING_LEVEL_FIELD,
267
+ ...STEP_PRIORITY_FIELD,
268
+ ...STEP_TAIL_FIELDS,
251
269
  }), {
252
270
  description: "Declare tasks with dependencies. The scheduler parallelizes independent tasks and sequences dependent ones. Max " + MAX_GRAPH_TASKS + " tasks."
253
271
  })),