brl-subagent 2.6.0 → 2.8.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.
@@ -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";
@@ -63,6 +64,13 @@ export interface InflightRun {
63
64
  // run record, so a post-crash retry restores the same 17-field shape a
64
65
  // same-session retry does (including `force`; decision 2026-10-11).
65
66
  originalParams?: SubagentRun["originalParams"];
67
+ /**
68
+ * Issue #447: the acceptance marker, mirrored from the run record.
69
+ * `null` = tracked but never accepted (never reached `session.prompt()`),
70
+ * ISO string = accepted, absent = legacy entry written before the field.
71
+ * The boot scan classifies on this tri-state (`recoverInflightRuns`).
72
+ */
73
+ acceptedAt?: string | null;
66
74
  startedAt: string;
67
75
  cwd: string;
68
76
  interruptedAt?: string;
@@ -82,6 +90,7 @@ export interface InflightRunInput {
82
90
  model?: string;
83
91
  thinkingLevel?: string;
84
92
  originalParams?: SubagentRun["originalParams"];
93
+ acceptedAt?: string | null;
85
94
  startedAt: string;
86
95
  cwd?: string;
87
96
  }
@@ -126,7 +135,9 @@ function resolvePath(id: string): string | null {
126
135
  }
127
136
 
128
137
  function ensureDir(): void {
129
- fs.mkdirSync(REGISTRY_DIR, { recursive: true, mode: 0o700 });
138
+ // Issue #408: `mode` only applies on CREATE — repair a pre-existing registry
139
+ // dir on every write so the entries stay untraversable by other local users.
140
+ ensureOwnerOnlyDir(REGISTRY_DIR);
130
141
  }
131
142
 
132
143
  /** True when `value` looks like a registry entry (id + kind + startedAt). */
@@ -158,6 +169,14 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
158
169
  } else {
159
170
  delete entry.originalParams;
160
171
  }
172
+ // Issue #447: keep the tri-state intact and treat anything else as LEGACY
173
+ // (absent) rather than inventing a fourth state. A mistyped marker must
174
+ // never downgrade a real run into the never-started class.
175
+ if (raw.acceptedAt === null || typeof raw.acceptedAt === "string") {
176
+ entry.acceptedAt = raw.acceptedAt;
177
+ } else {
178
+ delete entry.acceptedAt;
179
+ }
161
180
  return entry;
162
181
  }
163
182
 
@@ -202,6 +221,9 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
202
221
  if (input.model !== undefined) next.model = input.model;
203
222
  if (input.thinkingLevel !== undefined) next.thinkingLevel = input.thinkingLevel;
204
223
  if (input.originalParams !== undefined) next.originalParams = input.originalParams;
224
+ // Issue #447: `null` MUST copy (it is the never-started sentinel); only
225
+ // `undefined` is skipped, so a refresh without the marker cannot erase it.
226
+ if (input.acceptedAt !== undefined) next.acceptedAt = input.acceptedAt;
205
227
  return next;
206
228
  }
207
229
 
@@ -306,6 +328,7 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
306
328
  model: run.model,
307
329
  thinkingLevel: run.thinkingLevel,
308
330
  originalParams: run.originalParams,
331
+ acceptedAt: run.acceptedAt,
309
332
  startedAt: run.startedAt,
310
333
  cwd: process.cwd(),
311
334
  };
package/src/runner.ts CHANGED
@@ -45,7 +45,9 @@ import {
45
45
  } from "./kill-escalation";
46
46
  import { findByMarker, pidAlive, pidHasMarker, pidGone, groupHasMembers, killProcessGroup } from "./proc";
47
47
  import { getSafeEnv, DEPTH_ENV_KEY, CHILD_MARKER_ENV_KEY, sanitizeErrorMessage } from "./sanitize";
48
+ import { createLogger } from "./logging";
48
49
  import type { Logger } from "./logging";
50
+ import { buildEngineeringBarSection } from "./engineering-bar";
49
51
  import type { Intercom } from "./messaging";
50
52
  import { extractMessages, formatPendingMessages } from "./messaging";
51
53
  import type {
@@ -53,6 +55,16 @@ import type {
53
55
  TranscriptContentBlock,
54
56
  TranscriptToolCallBlock,
55
57
  } from "./transcript-tail";
58
+
59
+ /**
60
+ * The logger for diagnostics a CALLER did not instrument. `runSubagent`'s `log`
61
+ * is optional (its sweep/shutdown callers pass one; the foreground dispatch in
62
+ * `index.ts` passes one too), but the engineering bar's read failure (#421)
63
+ * must never be silent — so the bar's warning falls back to this sink instead of
64
+ * being dropped when `log` is absent.
65
+ */
66
+ const fallbackLog = createLogger("runner");
67
+
56
68
  // ---------------------------------------------------------------------------
57
69
  // In-flight child registry (Option B U1)
58
70
  // ---------------------------------------------------------------------------
@@ -478,7 +490,17 @@ export function buildSubagentArgs(
478
490
  "--thinking",
479
491
  thinkingLevel,
480
492
  ];
481
- if (toolOptions?.noBuiltinTools) {
493
+ // Issue #442: an EXPLICITLY empty allowlist means "no child tools", which is
494
+ // neither of the two states pi already expresses. Omitted keeps pi's
495
+ // defaults (no restriction flag at all), and `--no-builtin-tools` keeps
496
+ // extension and custom tools. `tools !== undefined` is therefore the
497
+ // emptiness test, not `.length > 0`: `[]` must reach pi's blanket
498
+ // `--no-tools`, and it must win over `noBuiltinTools` so an empty allowlist
499
+ // can never widen into "built-ins off, extension tools on". `--exclude-tools`
500
+ // stays additive below — it only disables, so it cannot re-enable a tool.
501
+ if (toolOptions?.tools !== undefined && toolOptions.tools.length === 0) {
502
+ args.push("--no-tools");
503
+ } else if (toolOptions?.noBuiltinTools) {
482
504
  args.push("--no-builtin-tools");
483
505
  } else if (toolOptions?.tools && toolOptions.tools.length > 0) {
484
506
  args.push("--tools", toolOptions.tools.join(","));
@@ -1078,11 +1100,19 @@ ${msgBlock}`;
1078
1100
 
1079
1101
  const args = buildSubagentArgs(model, thinkingLevel, toolOptions);
1080
1102
 
1103
+ // Issue #421: the project's engineering bar rides the same
1104
+ // --append-system-prompt channel as the caller's prompt, appended last.
1105
+ // Injected HERE (the foreground chokepoint all callers share) rather than
1106
+ // in each caller, so no preset selection can drop it; gated by the project
1107
+ // flag (ADR 0019), and `engineering-bar.ts` owns the read + its warning.
1108
+ const barSection = buildEngineeringBarSection(cwd, log ?? fallbackLog);
1109
+ const childSystemPrompt = barSection ? `${systemPrompt}${barSection}` : systemPrompt;
1110
+
1081
1111
  let tmpDir: string | null = null;
1082
1112
  let tmpFilePath: string | null = null;
1083
1113
 
1084
- if (systemPrompt.trim()) {
1085
- const tmp = await writeToTempFile(cwd, "system", systemPrompt);
1114
+ if (childSystemPrompt.trim()) {
1115
+ const tmp = await writeToTempFile(cwd, "system", childSystemPrompt);
1086
1116
  tmpDir = tmp.dir;
1087
1117
  tmpFilePath = tmp.filePath;
1088
1118
  args.push("--append-system-prompt", tmpFilePath);
@@ -1105,7 +1135,7 @@ ${msgBlock}`;
1105
1135
  thinkingLevel,
1106
1136
  cwd,
1107
1137
  taskPreview: task.slice(0, 80),
1108
- hasSystemPrompt: systemPrompt.trim().length > 0,
1138
+ hasSystemPrompt: childSystemPrompt.trim().length > 0,
1109
1139
  timeout,
1110
1140
  });
1111
1141
 
package/src/schema.ts CHANGED
@@ -5,7 +5,77 @@
5
5
  * Static<typeof delegateTaskParamsSchema>, so schema and types cannot drift.
6
6
  */
7
7
  import { Type } from "typebox";
8
- import { MAX_CHAIN_STEPS, MAX_PARALLEL_TASKS, MAX_GRAPH_TASKS } from "./types";
8
+ import { MAX_CHAIN_STEPS, MAX_PARALLEL_TASKS, MAX_GRAPH_TASKS, THINKING_LEVELS } from "./types";
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
+ /**
28
+ * Issue #443: the accepted thinking levels as a schema `enum`, derived from
29
+ * `THINKING_LEVELS` so the declaration cannot drift from the runtime guard
30
+ * (`isThinkingLevel`).
31
+ *
32
+ * The EMPTY STRING is a member on purpose: it is an existing declaration with a
33
+ * meaning (call level → the configured maximum, per unit → inherit the global
34
+ * level), so the enum must not turn it into a validation failure. An `enum`
35
+ * beats a union of literals here because pi-schema's error names the whole set
36
+ * (`thinkingLevel: expected one of [...]`) instead of only the first branch.
37
+ *
38
+ * This is the FIRST line of defence only: pi validates raw tool arguments, so
39
+ * a preset object, a restored `retryRunId` value, the transport retry's rebuilt
40
+ * params and every per-unit declaration reach the handler WITHOUT passing here.
41
+ * `invalidThinkingLevelRejection` (prelude.ts) is the runtime guard.
42
+ */
43
+ const THINKING_LEVEL_ENUM = [...THINKING_LEVELS, ""];
44
+
45
+ const STEP_THINKING_LEVEL_FIELD = {
46
+ thinkingLevel: Type.Optional(
47
+ Type.String({
48
+ enum: THINKING_LEVEL_ENUM,
49
+ description:
50
+ "Thinking level override for this subtask. Same values and rules as the call-level thinkingLevel: " +
51
+ `${THINKING_LEVELS.join(", ")} (exact match). An unknown value rejects the whole batch before anything starts. ` +
52
+ "Empty inherits the call-level level.",
53
+ }),
54
+ ),
55
+ };
56
+
57
+ /** Per-unit concurrency priority — tasks[] and graph[] only (issue #114). */
58
+ const STEP_PRIORITY_FIELD = {
59
+ priority: Type.Optional(
60
+ Type.Union([
61
+ Type.Literal("critical"),
62
+ Type.Literal("high"),
63
+ Type.Literal("normal"),
64
+ Type.Literal("low"),
65
+ ], { description: "Concurrency priority for this subtask (overrides the call-level default)." }),
66
+ ),
67
+ };
68
+
69
+ const STEP_TAIL_FIELDS = {
70
+ cwd: Type.Optional(Type.String({})),
71
+ timeout: Type.Optional(Type.Number({})),
72
+ outputFile: Type.Optional(Type.String({})),
73
+ tools: Type.Optional(Type.Array(Type.String({}))),
74
+ excludeTools: Type.Optional(Type.Array(Type.String({}))),
75
+ noBuiltinTools: Type.Optional(Type.Boolean({})),
76
+ systemPrompt: Type.Optional(Type.String({})),
77
+ inheritSystemPrompt: Type.Optional(Type.Boolean({})),
78
+ };
9
79
 
10
80
  export const delegateTaskParamsSchema = Type.Object({
11
81
  task: Type.Optional(Type.String({
@@ -29,10 +99,12 @@ export const delegateTaskParamsSchema = Type.Object({
29
99
  ),
30
100
  thinkingLevel: Type.Optional(
31
101
  Type.String({
102
+ enum: THINKING_LEVEL_ENUM,
32
103
  description:
33
104
  "Requested thinking level for this subagent call. " +
34
- "One of: off, minimal, low, medium, high, xhigh. " +
35
- "Capped at the user's configured maximum. If omitted, the user's configured level is used.",
105
+ `One of: ${THINKING_LEVELS.join(", ")} — matched exactly, so case and whitespace matter. ` +
106
+ "An unknown value is rejected (pi's own `max` is not a delegated level). " +
107
+ "Capped at the user's configured maximum. If omitted, or an empty string, the user's configured level is used.",
36
108
  }),
37
109
  ),
38
110
  outputFile: Type.Optional(
@@ -70,7 +142,8 @@ export const delegateTaskParamsSchema = Type.Object({
70
142
  tools: Type.Optional(
71
143
  Type.Array(Type.String(), {
72
144
  description:
73
- "Explicit allowlist of tool names for the subagent. Maps to pi's --tools flag.",
145
+ "Explicit allowlist of tool names for the subagent. Maps to pi's --tools flag. " +
146
+ "An EMPTY array means no child tools (pi --no-tools); omitting the field keeps pi's defaults.",
74
147
  }),
75
148
  ),
76
149
  excludeTools: Type.Optional(
@@ -143,7 +216,7 @@ export const delegateTaskParamsSchema = Type.Object({
143
216
  description:
144
217
  "If true and a FOREGROUND subagent times out, automatically retry with the same parameters. " +
145
218
  "Only retries once — the second timeout is treated as a final failure. " +
146
- "Background runs are not auto-retried; re-dispatch with retryRunId.",
219
+ "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
220
  }),
148
221
  ),
149
222
  approvalMode: Type.Optional(
@@ -162,6 +235,17 @@ export const delegateTaskParamsSchema = Type.Object({
162
235
  "Warnings are surfaced either way. force never suppresses outputFile-without-write conflicts.",
163
236
  }),
164
237
  ),
238
+ noJev: Type.Optional(
239
+ Type.String({
240
+ minLength: 1,
241
+ description:
242
+ "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). " +
243
+ "A reason string that states WHY the line is missing: the dispatch proceeds and the reason is surfaced as a warning in the result, so the bypass is never silent. " +
244
+ "The reason is validated when the dispatch is handled, not by this schema: the argument validator coerces loosely typed input, so a boolean or a number arrives as its text (`true` becomes \"true\") and is REFUSED exactly like an absent bypass. " +
245
+ "It bypasses ONLY the line check — capability conflicts still reject (unlike force). " +
246
+ "Append `jev: unavailable` to the task instead when the classifier did not run.",
247
+ }),
248
+ ),
165
249
  background: Type.Optional(
166
250
  Type.Boolean({
167
251
  description:
@@ -170,7 +254,7 @@ export const delegateTaskParamsSchema = Type.Object({
170
254
  "The conductor is woken with a completion message; use get_subagent_result for post-wake retrieval and stall checks. " +
171
255
  "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
256
  "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. " +
173
- "Pass background: false for a quick probe whose answer the next step needs inline. Explicit true/false always wins. " +
257
+ "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 that resolves FOREGROUND and carries an explicit timeout loses that timeout, because a foreground run persists nothing and a deadline there loses all its work. The shape it lands in depends on the effective approvalMode (call param, else config), in two outcomes: when a background run is possible (explicit background: false with 'auto'/'writes') the dispatch is switched to background, where the 30-minute default applies; when it is not (an effective 'always', which background cannot present a dialog for, or an omitted background whose approval mode keeps it foreground) the run STAYS FOREGROUND with NO deadline at all, so the call blocks until the child settles instead of being killed. Either outcome is announced to the conductor and the user; pass force: true to keep the explicit timeout. The same judgement is made PER BATCH UNIT: a tasks/chain/graph unit that declares its own high/xhigh thinking level with a positive timeout has that unit's timeout dropped before it runs, while a background fan-out unit keeps its own — there the deadline is the budget. Without that project opt-in the explicit shape and its timeout stand. " +
174
258
  "A background run defaults to a 30-minute deadline when no timeout is given.",
175
259
  }),
176
260
  ),
@@ -189,67 +273,29 @@ export const delegateTaskParamsSchema = Type.Object({
189
273
  // duration); array order IS the priority.
190
274
  chain: Type.Optional(Type.Array(Type.Object({
191
275
  task: Type.String({ description: "Task description. Use {previous} to reference the previous step output." }),
192
- label: Type.Optional(Type.String({})),
193
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
194
- thinkingLevel: Type.Optional(Type.String({})),
195
- cwd: Type.Optional(Type.String({})),
196
- timeout: Type.Optional(Type.Number({})),
197
- outputFile: Type.Optional(Type.String({})),
198
- tools: Type.Optional(Type.Array(Type.String({}))),
199
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
200
- noBuiltinTools: Type.Optional(Type.Boolean({})),
201
- systemPrompt: Type.Optional(Type.String({})),
202
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
276
+ ...STEP_HEAD_FIELDS,
277
+ ...STEP_THINKING_LEVEL_FIELD,
278
+ ...STEP_TAIL_FIELDS,
203
279
  }), {
204
280
  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."
205
281
  })),
206
282
  tasks: Type.Optional(Type.Array(Type.Object({
207
283
  task: Type.String({ description: "Task description for this parallel subtask" }),
208
- label: Type.Optional(Type.String({})),
209
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
210
- thinkingLevel: Type.Optional(Type.String({})),
211
- priority: Type.Optional(
212
- Type.Union([
213
- Type.Literal("critical"),
214
- Type.Literal("high"),
215
- Type.Literal("normal"),
216
- Type.Literal("low"),
217
- ], { description: "Concurrency priority for this subtask (overrides the call-level default)." })
218
- ),
219
- cwd: Type.Optional(Type.String({})),
220
- timeout: Type.Optional(Type.Number({})),
221
- outputFile: Type.Optional(Type.String({})),
222
- tools: Type.Optional(Type.Array(Type.String({}))),
223
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
224
- noBuiltinTools: Type.Optional(Type.Boolean({})),
225
- systemPrompt: Type.Optional(Type.String({})),
226
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
284
+ ...STEP_HEAD_FIELDS,
285
+ ...STEP_THINKING_LEVEL_FIELD,
286
+ ...STEP_PRIORITY_FIELD,
287
+ ...STEP_TAIL_FIELDS,
227
288
  }), {
228
289
  description: "Parallel tasks to execute concurrently. All tasks run regardless of individual failures. Max " + MAX_PARALLEL_TASKS + " tasks."
229
290
  })),
230
291
  graph: Type.Optional(Type.Array(Type.Object({
231
292
  id: Type.String({ description: "Unique identifier for this task node" }),
232
293
  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)." }),
233
- label: Type.Optional(Type.String({})),
234
- model: Type.Optional(Type.String({ description: "Model override for this step (provider/model-id). Defaults to the global subagent model." })),
294
+ ...STEP_HEAD_FIELDS,
235
295
  dependsOn: Type.Optional(Type.Array(Type.String({}), { description: "IDs of tasks that must complete before this one starts" })),
236
- thinkingLevel: Type.Optional(Type.String({})),
237
- priority: Type.Optional(
238
- Type.Union([
239
- Type.Literal("critical"),
240
- Type.Literal("high"),
241
- Type.Literal("normal"),
242
- Type.Literal("low"),
243
- ], { description: "Concurrency priority for this subtask (overrides the call-level default)." })
244
- ),
245
- cwd: Type.Optional(Type.String({})),
246
- timeout: Type.Optional(Type.Number({})),
247
- outputFile: Type.Optional(Type.String({})),
248
- tools: Type.Optional(Type.Array(Type.String({}))),
249
- excludeTools: Type.Optional(Type.Array(Type.String({}))),
250
- noBuiltinTools: Type.Optional(Type.Boolean({})),
251
- systemPrompt: Type.Optional(Type.String({})),
252
- inheritSystemPrompt: Type.Optional(Type.Boolean({})),
296
+ ...STEP_THINKING_LEVEL_FIELD,
297
+ ...STEP_PRIORITY_FIELD,
298
+ ...STEP_TAIL_FIELDS,
253
299
  }), {
254
300
  description: "Declare tasks with dependencies. The scheduler parallelizes independent tasks and sequences dependent ones. Max " + MAX_GRAPH_TASKS + " tasks."
255
301
  })),