pi-herdsman 0.45.0 → 0.46.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/dist/index.js CHANGED
@@ -133,7 +133,7 @@ import {
133
133
  writeFileSync
134
134
  } from "node:fs";
135
135
  import { createHash as createHash3, randomUUID } from "node:crypto";
136
- import { basename, dirname, join } from "node:path";
136
+ import { basename, dirname as dirname2, join } from "node:path";
137
137
  import { fileURLToPath } from "node:url";
138
138
  function isIncidentalMetadata(entry) {
139
139
  return entry.isFile() && INCIDENTAL_METADATA.has(entry.name.toLowerCase());
@@ -428,8 +428,8 @@ function peerAttachmentPath(name, text) {
428
428
  function persistPeerAttachment(name, text) {
429
429
  const path = peerAttachmentPath(name, text);
430
430
  const bytes = Buffer.from(text, "utf8");
431
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
432
- chmodSync(dirname(path), 448);
431
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
432
+ chmodSync(dirname2(path), 448);
433
433
  try {
434
434
  writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
435
435
  } catch (error2) {
@@ -443,8 +443,8 @@ function persistPeerResultArtifact(canonicalRef, text) {
443
443
  if (!isCanonicalResultRef(canonicalRef) || typeof text !== "string")
444
444
  throw new Error("invalid peer result artifact");
445
445
  const path = resultPath(canonicalRef.slice(RESULT_PREFIX.length));
446
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
447
- chmodSync(dirname(path), 448);
446
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
447
+ chmodSync(dirname2(path), 448);
448
448
  const bytes = Buffer.from(text, "utf8");
449
449
  try {
450
450
  writeFileSync(path, bytes, { flag: "wx", mode: 384, flush: true });
@@ -472,7 +472,7 @@ function publishScopedResult(agentLabel, minimumIndex, canonicalRef, rootSession
472
472
  const directory2 = join(reservationRoot, agentLabel);
473
473
  mkdirSync(directory2, { recursive: true, mode: 448 });
474
474
  if (process.platform !== "win32") {
475
- const dataParentFd = openSync(dirname(dataRoot), "r");
475
+ const dataParentFd = openSync(dirname2(dataRoot), "r");
476
476
  try {
477
477
  fsyncSync(dataParentFd);
478
478
  } finally {
@@ -615,7 +615,7 @@ var init_storage = __esm({
615
615
  // extension/lock.ts
616
616
  import * as fs from "node:fs";
617
617
  import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
618
- import { basename as basename2, dirname as dirname2, join as join2 } from "node:path";
618
+ import { basename as basename2, dirname as dirname3, join as join2 } from "node:path";
619
619
  function assignmentLockPath(mailbox) {
620
620
  return join2(
621
621
  herdsmanTempRoot(),
@@ -789,7 +789,7 @@ function acquireProcessLock(path, options = {}) {
789
789
  const verifyMessage = `Unable to verify ${name}`;
790
790
  const occupiedMessage = options.occupiedMessage ?? `${name[0].toUpperCase()}${name.slice(1)} is in progress`;
791
791
  const recoverMessage = `Unable to recover ${name}`;
792
- const parent = dirname2(path);
792
+ const parent = dirname3(path);
793
793
  fs.mkdirSync(parent, { recursive: true, mode: 448 });
794
794
  fs.chmodSync(parent, 448);
795
795
  const claimDir = path;
@@ -950,7 +950,7 @@ function releaseProcessLock(claimDir, ownerPath, claim, name) {
950
950
  `${name[0].toUpperCase()}${name.slice(1)} ownership changed`
951
951
  );
952
952
  const retired = join2(
953
- dirname2(claimDir),
953
+ dirname3(claimDir),
954
954
  `.${basename2(claimDir)}.${randomUUID2()}.released`
955
955
  );
956
956
  fs.renameSync(claimDir, retired);
@@ -1013,7 +1013,7 @@ import {
1013
1013
  watch,
1014
1014
  writeSync as writeSync2
1015
1015
  } from "node:fs";
1016
- import { basename as basename3, dirname as dirname3, join as join3 } from "node:path";
1016
+ import { basename as basename3, dirname as dirname4, join as join3 } from "node:path";
1017
1017
  function mailboxRecordBytes(record) {
1018
1018
  return Buffer.byteLength(JSON.stringify(record), "utf8");
1019
1019
  }
@@ -1224,6 +1224,7 @@ function validate(value2, kind) {
1224
1224
  "ownerSessionId",
1225
1225
  "workspaceId",
1226
1226
  "agentLabel",
1227
+ "childSessionId",
1227
1228
  "participants"
1228
1229
  ];
1229
1230
  if (Object.keys(v).some((key) => !allowed2.includes(key)))
@@ -1239,6 +1240,8 @@ function validate(value2, kind) {
1239
1240
  if (typeof v[field] !== "string" || !v[field].trim())
1240
1241
  throw new Error(`Invalid mailbox field: ${field}`);
1241
1242
  if (!UUID2.test(v.runId)) throw new Error("Invalid mailbox UUID");
1243
+ if (v.childSessionId !== void 0 && !UUID2.test(v.childSessionId))
1244
+ throw new Error("Invalid bootstrap child session UUID");
1242
1245
  if (!Array.isArray(v.participants) || !v.participants.length)
1243
1246
  throw new Error("Invalid bootstrap participants");
1244
1247
  const ids = /* @__PURE__ */ new Set();
@@ -1545,10 +1548,10 @@ function validate(value2, kind) {
1545
1548
  function atomic(path, value2, kind, createDirectory = true) {
1546
1549
  validate(value2, kind);
1547
1550
  if (createDirectory)
1548
- mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1549
- chmodSync3(dirname3(path), 448);
1551
+ mkdirSync3(dirname4(path), { recursive: true, mode: 448 });
1552
+ chmodSync3(dirname4(path), 448);
1550
1553
  const temporary = join3(
1551
- dirname3(path),
1554
+ dirname4(path),
1552
1555
  `.${basename3(path)}.${randomUUID3()}.tmp`
1553
1556
  );
1554
1557
  let fd;
@@ -1923,7 +1926,7 @@ import {
1923
1926
  realpathSync,
1924
1927
  statSync as statSync2
1925
1928
  } from "node:fs";
1926
- import { basename as basename4, resolve } from "node:path";
1929
+ import { basename as basename4, resolve as resolve2 } from "node:path";
1927
1930
  import { TextDecoder as TextDecoder2 } from "node:util";
1928
1931
  import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
1929
1932
  function currentTurnIsSoleToolCall(ctx, name) {
@@ -1951,7 +1954,7 @@ function resolveRegularFiles(inputs, cwd, operation, skipCanonicalPaths = []) {
1951
1954
  let canonicalPath;
1952
1955
  try {
1953
1956
  resolvedResultPath = resolveResultRef(target);
1954
- path = resolvedResultPath ?? resolve(cwd, target);
1957
+ path = resolvedResultPath ?? resolve2(cwd, target);
1955
1958
  canonicalPath = realpathSync(path);
1956
1959
  if (skipped.has(canonicalPath)) return [];
1957
1960
  const existing = seen.get(canonicalPath);
@@ -2380,7 +2383,7 @@ import {
2380
2383
  import { execFileSync } from "node:child_process";
2381
2384
  import { randomUUID as randomUUID5 } from "node:crypto";
2382
2385
  import { homedir as homedir2 } from "node:os";
2383
- import { dirname as dirname4, isAbsolute, join as join4, relative, resolve as resolve2, sep } from "node:path";
2386
+ import { dirname as dirname5, isAbsolute, join as join4, relative, resolve as resolve3, sep } from "node:path";
2384
2387
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2385
2388
  import {
2386
2389
  CONFIG_DIR_NAME,
@@ -2416,7 +2419,7 @@ function readAgentDefinitions(root2, category, onWarning) {
2416
2419
  const name = parsed.frontmatter.name;
2417
2420
  if (category && typeof name === "string" && name.length > 0 && isReservedRoleDefinition(name) !== (category === "role")) {
2418
2421
  const destination = join4(
2419
- dirname4(root2),
2422
+ dirname5(root2),
2420
2423
  category === "agent" ? "coordinators" : "agents",
2421
2424
  relative(root2, path)
2422
2425
  );
@@ -2451,8 +2454,8 @@ function readAgentDefinitions(root2, category, onWarning) {
2451
2454
  function resolveBodyFileReferences(body, definitionPath) {
2452
2455
  return body.replace(BODY_FILE_REFERENCE, (_match, input) => {
2453
2456
  const homeRelative = input.startsWith("~/") || input.startsWith(`~${sep}`);
2454
- const expanded = homeRelative ? resolve2(homedir2(), input.slice(2)) : input;
2455
- return `@${isAbsolute(expanded) ? expanded : resolve2(dirname4(definitionPath), expanded)}`;
2457
+ const expanded = homeRelative ? resolve3(homedir2(), input.slice(2)) : input;
2458
+ return `@${isAbsolute(expanded) ? expanded : resolve3(dirname5(definitionPath), expanded)}`;
2456
2459
  });
2457
2460
  }
2458
2461
  function isPlainObject(value2) {
@@ -2460,8 +2463,78 @@ function isPlainObject(value2) {
2460
2463
  const prototype = Object.getPrototypeOf(value2);
2461
2464
  return prototype === Object.prototype || prototype === null;
2462
2465
  }
2463
- function mergeFrontmatter(base, override) {
2464
- return { ...base, ...override };
2466
+ function validateArrayFields(frontmatter, invalid) {
2467
+ for (const field of ARRAY_FIELDS) {
2468
+ const value2 = frontmatter[field];
2469
+ if (value2 !== void 0 && (!Array.isArray(value2) || value2.some(
2470
+ (entry) => typeof entry !== "string" || entry.trim().length === 0
2471
+ ) || field === "agents" && new Set(value2.filter((entry) => !isArrayModifier(entry))).size !== value2.filter((entry) => !isArrayModifier(entry)).length))
2472
+ invalid(
2473
+ field,
2474
+ field === "agents" ? "must be an array with unique explicit names and non-empty modifiers" : "must be an array of non-empty strings"
2475
+ );
2476
+ if (Array.isArray(value2)) {
2477
+ const entries = field === "tools" ? normalizedToolNames(value2) : value2;
2478
+ for (const entry of entries)
2479
+ if (isArrayModifier(entry) && (!entry.slice(1).trim() || field === "tools" && entry.slice(1).trim().includes("*")))
2480
+ invalid(
2481
+ field,
2482
+ field === "tools" ? "modifiers require exact tool names without wildcards" : "modifiers require a non-empty name"
2483
+ );
2484
+ }
2485
+ }
2486
+ }
2487
+ function applyArrayModifiers(base, entries) {
2488
+ const plain = entries.filter((entry) => !isArrayModifier(entry));
2489
+ const result = plain.length > 0 || entries.length === 0 ? [...new Set(plain)] : [...base];
2490
+ for (const entry of entries) {
2491
+ if (!isArrayModifier(entry)) continue;
2492
+ const value2 = entry.slice(1);
2493
+ const index = result.indexOf(value2);
2494
+ if (entry[0] === "+" && index < 0) result.push(value2);
2495
+ if (entry[0] === "-" && index >= 0) result.splice(index, 1);
2496
+ }
2497
+ return result;
2498
+ }
2499
+ function composeFrontmatter(base, override, definitionName) {
2500
+ validateArrayFields(override, (field, reason) => {
2501
+ throw new Error(`agent ${definitionName} field ${field}: ${reason}`);
2502
+ });
2503
+ const effective = { ...base, ...override };
2504
+ for (const field of ARRAY_FIELDS) {
2505
+ const rawEntries = override[field];
2506
+ if (!Array.isArray(rawEntries)) continue;
2507
+ const entries = field === "tools" ? normalizedToolNames(rawEntries) : rawEntries;
2508
+ const baseEntries = base?.[field];
2509
+ if (!entries.some((entry) => isArrayModifier(entry))) continue;
2510
+ if (field === "tools") {
2511
+ const normalized2 = normalizedToolNames(entries);
2512
+ if (baseEntries === void 0) {
2513
+ effective.tools = normalized2.length > 0 && normalized2.every(isArrayModifier) ? normalized2 : applyArrayModifiers([], normalized2);
2514
+ continue;
2515
+ }
2516
+ const inheritedTools = normalizedToolNames(baseEntries);
2517
+ const inheritedRelative = inheritedTools.length > 0 && inheritedTools.every(isArrayModifier);
2518
+ if (inheritedRelative && normalized2.length > 0 && normalized2.every(isArrayModifier)) {
2519
+ effective.tools = [...inheritedTools, ...normalized2];
2520
+ continue;
2521
+ }
2522
+ }
2523
+ if (field === "agents" && baseEntries === void 0 && [
2524
+ FLEXIBLE_LEAD_DEFINITION_NAME,
2525
+ ORCHESTRATOR_LEAD_DEFINITION_NAME,
2526
+ MANAGED_LEAD_DEFINITION_NAME
2527
+ ].includes(
2528
+ definitionName
2529
+ ) && entries.every((entry) => isArrayModifier(entry)))
2530
+ throw new Error(
2531
+ `agent ${definitionName} field agents: modifier-only overlays require an explicit agents allowlist`
2532
+ );
2533
+ const inherited = field === "tools" ? normalizedToolNames(baseEntries) : baseEntries ?? [];
2534
+ const normalized = field === "tools" ? normalizedToolNames(entries) : entries;
2535
+ effective[field] = applyArrayModifiers(inherited, normalized);
2536
+ }
2537
+ return effective;
2465
2538
  }
2466
2539
  function validateDefinition(definition, options = {}) {
2467
2540
  const { frontmatter, name } = definition;
@@ -2481,18 +2554,7 @@ function validateDefinition(definition, options = {}) {
2481
2554
  for (const field of BOOLEAN_CAPABILITY_FIELDS)
2482
2555
  if (frontmatter[field] !== void 0 && typeof frontmatter[field] !== "boolean")
2483
2556
  invalid(field, "must be a boolean");
2484
- for (const field of ARRAY_FIELDS) {
2485
- const value2 = frontmatter[field];
2486
- if (value2 !== void 0 && (!Array.isArray(value2) || value2.some(
2487
- (entry) => typeof entry !== "string" || entry.trim().length === 0
2488
- ) || field === "agents" && new Set(value2).size !== value2.length))
2489
- invalid(
2490
- field,
2491
- field === "agents" ? "must be an array of unique non-empty strings" : "must be an array of non-empty strings"
2492
- );
2493
- }
2494
- if (frontmatter.tools !== void 0 && normalizedToolNames(frontmatter.tools).some((tool) => /^[+-]/u.test(tool)))
2495
- invalid("tools", "must be an allowlist without +name/-name modifiers");
2557
+ validateArrayFields(frontmatter, invalid);
2496
2558
  if (frontmatter.model !== void 0) {
2497
2559
  if (typeof frontmatter.model !== "string" || !frontmatter.model)
2498
2560
  invalid("model", "must be a non-empty string");
@@ -2531,8 +2593,25 @@ function matchesToolPattern(pattern, name) {
2531
2593
  }
2532
2594
  function configuredToolPolicy(definition, requiredTools) {
2533
2595
  const configured = normalizedToolNames(definition.frontmatter.tools);
2596
+ const relative3 = definition.frontmatter.tools !== void 0 && configured.length > 0 && configured.every(isArrayModifier);
2597
+ const mode = definition.frontmatter.tools === void 0 ? "inherit" : relative3 ? "relative" : "explicit";
2534
2598
  const required = new Set(requiredTools);
2535
- const excluded = normalizedToolNames(definition.frontmatter.excludeTools).filter((pattern) => !required.has(pattern)).filter((pattern, index, all) => all.indexOf(pattern) === index);
2599
+ const terminal = /* @__PURE__ */ new Map();
2600
+ if (relative3)
2601
+ for (const operation of configured) {
2602
+ const name = operation.slice(1);
2603
+ terminal.set(name, operation[0] === "-");
2604
+ }
2605
+ const removed = [...terminal].filter(([, isRemoved]) => isRemoved).map(([name]) => name);
2606
+ const forbiddenRequired = removed.find((name) => required.has(name));
2607
+ if (forbiddenRequired)
2608
+ throw new Error(
2609
+ `agent ${definition.name} tools modifier cannot remove required tool ${JSON.stringify(forbiddenRequired)}`
2610
+ );
2611
+ const excluded = [
2612
+ ...normalizedToolNames(definition.frontmatter.excludeTools),
2613
+ ...removed
2614
+ ].filter((pattern) => !required.has(pattern)).filter((pattern, index, all) => all.indexOf(pattern) === index);
2536
2615
  for (const pattern of excluded) {
2537
2616
  if (!pattern.includes("*")) continue;
2538
2617
  const matched = requiredTools.find(
@@ -2544,8 +2623,11 @@ function configuredToolPolicy(definition, requiredTools) {
2544
2623
  );
2545
2624
  }
2546
2625
  return {
2547
- explicit: definition.frontmatter.tools !== void 0,
2548
- tools: configured.filter((tool) => !required.has(tool)),
2626
+ mode,
2627
+ explicit: mode === "explicit",
2628
+ tools: configured.filter(
2629
+ (tool) => !isArrayModifier(tool) && !required.has(tool)
2630
+ ),
2549
2631
  excluded
2550
2632
  };
2551
2633
  }
@@ -2553,7 +2635,7 @@ function toolPolicyAllowsName(policy, requiredTools, name) {
2553
2635
  if (requiredTools.has(name)) return true;
2554
2636
  if (policy.excluded.some((pattern) => matchesToolPattern(pattern, name)))
2555
2637
  return false;
2556
- return !policy.explicit || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2638
+ return policy.mode !== "explicit" || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2557
2639
  }
2558
2640
  function readOptionalAgentDefinitions(root2, category, onWarning) {
2559
2641
  const stats = statSync3(root2, { throwIfNoEntry: false });
@@ -2615,13 +2697,36 @@ function privateRepositoryRoot(projectRoot) {
2615
2697
  throw new Error(`Invalid Git common-directory result for ${projectRoot}`);
2616
2698
  return join4(realpathSync2(commonDir), "pi-herdsman");
2617
2699
  }
2618
- function applyDefinitionLayer(definitions, layer, sourceField) {
2700
+ function sourceScope(field) {
2701
+ return field === "projectSource" ? "project" : field === "overrideSource" ? "global" : "private";
2702
+ }
2703
+ function applyDefinitionLayer(definitions, layer, sourceField, trace) {
2619
2704
  for (const definition of layer) {
2620
2705
  const base = definitions.get(definition.name);
2621
2706
  if (!base) {
2622
- definition[sourceField] = definition.path;
2623
- validateDefinition(definition);
2624
- definitions.set(definition.name, definition);
2707
+ const standalone = {
2708
+ ...definition,
2709
+ frontmatter: composeFrontmatter(
2710
+ void 0,
2711
+ definition.frontmatter,
2712
+ definition.name
2713
+ ),
2714
+ [sourceField]: definition.path
2715
+ };
2716
+ validateDefinition(standalone);
2717
+ if (trace?.name === definition.name) {
2718
+ const scope = sourceScope(sourceField);
2719
+ trace.layers.push({
2720
+ scope,
2721
+ path: definition.path,
2722
+ supplied: definition.frontmatter,
2723
+ after: standalone.frontmatter,
2724
+ body: definition.body,
2725
+ bodyAction: "base"
2726
+ });
2727
+ trace.bodyFragments = definition.body ? [{ path: definition.path, scope, body: definition.body }] : [];
2728
+ }
2729
+ definitions.set(definition.name, standalone);
2625
2730
  continue;
2626
2731
  }
2627
2732
  const mode = overrideBodyMode(definition);
@@ -2629,7 +2734,11 @@ function applyDefinitionLayer(definitions, layer, sourceField) {
2629
2734
  const effective = {
2630
2735
  name: base.name,
2631
2736
  path: definition.path,
2632
- frontmatter: mergeFrontmatter(base.frontmatter, overrideFrontmatter),
2737
+ frontmatter: composeFrontmatter(
2738
+ base.frontmatter,
2739
+ overrideFrontmatter,
2740
+ definition.name
2741
+ ),
2633
2742
  body: mergeDefinitionBody(base.body, definition.body, mode),
2634
2743
  extensionSource: base.extensionSource,
2635
2744
  projectSource: base.projectSource,
@@ -2638,6 +2747,24 @@ function applyDefinitionLayer(definitions, layer, sourceField) {
2638
2747
  [sourceField]: definition.path
2639
2748
  };
2640
2749
  validateDefinition(effective);
2750
+ if (trace?.name === definition.name) {
2751
+ const scope = sourceScope(sourceField);
2752
+ trace.layers.push({
2753
+ scope,
2754
+ path: definition.path,
2755
+ supplied: definition.frontmatter,
2756
+ before: base.frontmatter,
2757
+ after: effective.frontmatter,
2758
+ body: definition.body,
2759
+ bodyAction: definition.body ? mode : "inherit"
2760
+ });
2761
+ if (definition.body) {
2762
+ trace.bodyFragments = mode === "append" && trace.bodyFragments.length ? [
2763
+ ...trace.bodyFragments,
2764
+ { path: definition.path, scope, body: definition.body }
2765
+ ] : [{ path: definition.path, scope, body: definition.body }];
2766
+ }
2767
+ }
2641
2768
  definitions.set(effective.name, effective);
2642
2769
  }
2643
2770
  }
@@ -2688,7 +2815,7 @@ function validateRuntimeRoleLayer(definition) {
2688
2815
  `${definition.path} ${definition.name} field ${field}: is not supported`
2689
2816
  );
2690
2817
  }
2691
- function discoverEffectiveDefinitions(options = {}, category = "agent", validateReferences = true) {
2818
+ function discoverEffectiveDefinitions(options = {}, category = "agent", validateReferences = true, trace) {
2692
2819
  const role2 = category === "role";
2693
2820
  const bundled = readAgentDefinitions(
2694
2821
  role2 ? BUILTIN_ROLE_DIR : BUILTIN_AGENT_DIR
@@ -2739,6 +2866,17 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2739
2866
  if (!definition.extensionSource)
2740
2867
  definition.extensionSource = definition.path;
2741
2868
  validateDefinition(definition);
2869
+ if (trace?.name === definition.name) {
2870
+ trace.layers.push({
2871
+ scope: "bundled",
2872
+ path: definition.path,
2873
+ supplied: definition.frontmatter,
2874
+ after: definition.frontmatter,
2875
+ body: definition.body,
2876
+ bodyAction: "base"
2877
+ });
2878
+ trace.bodyFragments = definition.body ? [{ path: definition.path, scope: "bundled", body: definition.body }] : [];
2879
+ }
2742
2880
  }
2743
2881
  for (const definition of [
2744
2882
  ...bundled,
@@ -2763,12 +2901,13 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2763
2901
  throw new Error(
2764
2902
  `${privateChief.path} chief definition: private repository overrides are not supported; configure chief globally instead`
2765
2903
  );
2766
- applyDefinitionLayer(definitions, user, "overrideSource");
2767
- applyDefinitionLayer(definitions, project, "projectSource");
2904
+ applyDefinitionLayer(definitions, user, "overrideSource", trace);
2905
+ applyDefinitionLayer(definitions, project, "projectSource", trace);
2768
2906
  applyDefinitionLayer(
2769
2907
  definitions,
2770
2908
  privateRepository,
2771
- "privateRepositorySource"
2909
+ "privateRepositorySource",
2910
+ trace
2772
2911
  );
2773
2912
  const effective = [...definitions.values()].sort(
2774
2913
  (left, right) => left.name.localeCompare(right.name)
@@ -2776,6 +2915,44 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2776
2915
  if (!role2 && validateReferences) validateEffectiveAgentReferences(effective);
2777
2916
  return effective;
2778
2917
  }
2918
+ function inspectAgentDefinition(name, options = {}) {
2919
+ const trace = { name, layers: [], bodyFragments: [] };
2920
+ const definition = discoverEffectiveDefinitions(options, "agent", true, trace).filter((candidate) => !isReservedRoleDefinition(candidate.name)).map(withDefaultEnabled).find((candidate) => candidate.name === name);
2921
+ if (!definition) throw new Error(`agent ${name} not found`);
2922
+ if (trace.bodyFragments.map((fragment) => fragment.body).join("\n\n") !== definition.body)
2923
+ throw new Error(
2924
+ `Definition body trace did not reproduce effective body for ${name}`
2925
+ );
2926
+ return {
2927
+ definition,
2928
+ layers: trace.layers,
2929
+ bodyFragments: trace.bodyFragments
2930
+ };
2931
+ }
2932
+ function inspectRoleDefinition(name, options = {}) {
2933
+ const trace = { name, layers: [], bodyFragments: [] };
2934
+ const definition = discoverEffectiveDefinitions(
2935
+ options,
2936
+ "role",
2937
+ true,
2938
+ trace
2939
+ ).find((candidate) => candidate.name === name);
2940
+ if (!definition) throw new Error(`role definition ${name} not found`);
2941
+ if (definition.frontmatter.agents?.length)
2942
+ validateRoleAgentDefinitionReferences(
2943
+ definition,
2944
+ discoverAgentDefinitions(options)
2945
+ );
2946
+ if (trace.bodyFragments.map((fragment) => fragment.body).join("\n\n") !== definition.body)
2947
+ throw new Error(
2948
+ `Definition body trace did not reproduce effective body for ${name}`
2949
+ );
2950
+ return {
2951
+ definition,
2952
+ layers: trace.layers,
2953
+ bodyFragments: trace.bodyFragments
2954
+ };
2955
+ }
2779
2956
  function discoverAgentDefinitions(options = {}) {
2780
2957
  return discoverEffectiveDefinitions(options).filter(({ name }) => !isReservedRoleDefinition(name)).map((definition) => withDefaultEnabled(definition));
2781
2958
  }
@@ -2986,7 +3163,7 @@ function updateAgentOverride(definition, field, value2, options = {}) {
2986
3163
  );
2987
3164
  mode = exists.mode & 511;
2988
3165
  } else {
2989
- mkdirSync4(dirname4(path), { recursive: true });
3166
+ mkdirSync4(dirname5(path), { recursive: true });
2990
3167
  content = `---
2991
3168
  name: ${JSON.stringify(definition.name)}
2992
3169
  ---
@@ -3033,7 +3210,7 @@ name: ${JSON.stringify(definition.name)}
3033
3210
  if (value2 === void 0 && !hadField)
3034
3211
  return { path, changed: false, content: readFileSync5(path, "utf8") };
3035
3212
  const temporary = join4(
3036
- dirname4(path),
3213
+ dirname5(path),
3037
3214
  `.${encodeURIComponent(definition.name)}.${randomUUID5()}.tmp`
3038
3215
  );
3039
3216
  try {
@@ -3121,24 +3298,47 @@ function writePrivatePromptSnapshots(contents) {
3121
3298
  throw error2;
3122
3299
  }
3123
3300
  }
3124
- function expandAgentBodyFiles(body, skipCanonicalPaths, operation) {
3125
- const references = [...body.matchAll(BODY_FILE_REFERENCE)].map(
3126
- (match) => match[1]
3301
+ function expandDefinitionBodyFragmentsWithSources(fragments, skipCanonicalPaths, operation) {
3302
+ const references = fragments.flatMap(
3303
+ ({ body }) => [...body.matchAll(BODY_FILE_REFERENCE)].map((match) => match[1])
3127
3304
  );
3128
- if (references.length === 0) return body;
3129
- const snapshots = snapshotTextFiles(references, process.cwd(), operation, {
3305
+ const snapshots = references.length ? snapshotTextFiles(references, process.cwd(), operation, {
3130
3306
  skipCanonicalPaths
3131
- });
3307
+ }) : [];
3132
3308
  const remaining = new Map(
3133
- snapshots.map((snapshot) => [snapshot.input, snapshot.text])
3309
+ snapshots.map((snapshot) => [snapshot.input, snapshot])
3134
3310
  );
3135
- return body.replace(BODY_FILE_REFERENCE, (_match, input) => {
3136
- const text = remaining.get(input);
3137
- if (text === void 0) return "";
3138
- remaining.delete(input);
3139
- return text;
3311
+ return fragments.map(({ body }) => {
3312
+ const parts = [];
3313
+ let cursor = 0;
3314
+ for (const match of body.matchAll(BODY_FILE_REFERENCE)) {
3315
+ const index = match.index;
3316
+ if (index > cursor) parts.push({ text: body.slice(cursor, index) });
3317
+ const snapshot = remaining.get(match[1]);
3318
+ if (snapshot) {
3319
+ parts.push({ text: snapshot.text, filePath: snapshot.path });
3320
+ remaining.delete(match[1]);
3321
+ }
3322
+ cursor = index + match[0].length;
3323
+ }
3324
+ if (cursor < body.length) parts.push({ text: body.slice(cursor) });
3325
+ return parts;
3140
3326
  });
3141
3327
  }
3328
+ function expandDefinitionBodyFragments(fragments, skipCanonicalPaths, operation) {
3329
+ return expandDefinitionBodyFragmentsWithSources(
3330
+ fragments,
3331
+ skipCanonicalPaths,
3332
+ operation
3333
+ ).map((parts) => parts.map(({ text }) => text).join(""));
3334
+ }
3335
+ function expandAgentBodyFiles(body, skipCanonicalPaths, operation) {
3336
+ return expandDefinitionBodyFragments(
3337
+ [{ path: "", scope: "bundled", body }],
3338
+ skipCanonicalPaths,
3339
+ operation
3340
+ )[0];
3341
+ }
3142
3342
  function agentDefinitionDelegationEnabled(definition) {
3143
3343
  const {
3144
3344
  agents,
@@ -3149,8 +3349,27 @@ function agentDefinitionDelegationEnabled(definition) {
3149
3349
  if ((agents?.length ?? 0) === 0) return false;
3150
3350
  const tools = normalizedToolNames(configured);
3151
3351
  if (normalizedToolNames(excludeTools).includes("agent")) return false;
3152
- if (noTools === true && !tools.includes("agent")) return false;
3153
- return configured === void 0 || tools.length > 0;
3352
+ if (noTools === true && !tools.includes("+agent") && !tools.includes("agent"))
3353
+ return false;
3354
+ if (configured === void 0) return true;
3355
+ const policy = configuredToolPolicy(definition, []);
3356
+ if (policy.mode === "relative")
3357
+ return toolPolicyAllowsName(policy, /* @__PURE__ */ new Set(), "agent");
3358
+ return tools.length > 0;
3359
+ }
3360
+ function contextInheritance(definition) {
3361
+ const project = definition.frontmatter.inheritProjectContext === true || definition.frontmatter.inheritProjectContext === void 0 && definition.name === "delegate";
3362
+ const global2 = definition.frontmatter.inheritGlobalContext === true || definition.frontmatter.inheritGlobalContext === void 0 && project;
3363
+ return { global: global2, project };
3364
+ }
3365
+ function selectedAgentContextFiles(definition, cwd, loader = loadProjectContextFiles) {
3366
+ const inheritance = contextInheritance(definition);
3367
+ if (!inheritance.global && !inheritance.project) return [];
3368
+ const agentDir = getAgentDir();
3369
+ return loader({ cwd, agentDir }).filter((context) => {
3370
+ const isGlobal = resolve3(dirname5(context.path)) === resolve3(agentDir);
3371
+ return isGlobal ? inheritance.global : inheritance.project;
3372
+ });
3154
3373
  }
3155
3374
  function agentLaunchArgs(agent, options) {
3156
3375
  const {
@@ -3200,18 +3419,15 @@ function agentLaunchArgs(agent, options) {
3200
3419
  mode === "append" ? "--append-system-prompt" : "--system-prompt",
3201
3420
  bodyPromptPathForLaunch
3202
3421
  );
3203
- const inheritProjectContext = frontmatter.inheritProjectContext ?? agent.name === "delegate";
3204
- const inheritGlobalContext = frontmatter.inheritGlobalContext ?? inheritProjectContext;
3205
- if (inheritProjectContext !== true || inheritGlobalContext !== true) {
3422
+ const inheritance = contextInheritance(agent);
3423
+ if (!inheritance.global || !inheritance.project) {
3206
3424
  args.push("--no-context-files");
3207
- if (inheritProjectContext === true || inheritGlobalContext === true) {
3208
- const agentDir = getAgentDir();
3209
- for (const context of (options.loadProjectContextFiles ?? loadProjectContextFiles)({ cwd, agentDir })) {
3210
- const isGlobal = resolve2(dirname4(context.path)) === resolve2(agentDir);
3211
- if (isGlobal && inheritGlobalContext === true || !isGlobal && inheritProjectContext === true)
3212
- args.push("--append-system-prompt", context.path);
3213
- }
3214
- }
3425
+ for (const context of selectedAgentContextFiles(
3426
+ agent,
3427
+ cwd,
3428
+ options.loadProjectContextFiles ?? loadProjectContextFiles
3429
+ ))
3430
+ args.push("--append-system-prompt", context.path);
3215
3431
  }
3216
3432
  if (sharedPromptPath) args.push("--append-system-prompt", sharedPromptPath);
3217
3433
  const requiredTools = [
@@ -3229,7 +3445,16 @@ function agentLaunchArgs(agent, options) {
3229
3445
  if (noTools) args.push("--no-tools");
3230
3446
  if (frontmatter.noBuiltinTools) args.push("--no-builtin-tools");
3231
3447
  const excluded = policy.excluded;
3232
- if (noTools || policy.explicit) {
3448
+ if (policy.mode === "relative") {
3449
+ const operations = [...normalizedToolNames(frontmatter.tools)];
3450
+ for (const tool of requiredTools)
3451
+ if (!operations.includes(`+${tool}`)) operations.push(`+${tool}`);
3452
+ if (noTools && !operations.some((operation) => operation.startsWith("+mcp__"))) {
3453
+ operations.push("+mcp__");
3454
+ if (!excluded.includes("mcp__")) excluded.push("mcp__");
3455
+ }
3456
+ if (operations.length) args.push("--tools", operations.join(","));
3457
+ } else if (noTools || policy.mode === "explicit") {
3233
3458
  const configured = policy.tools.filter(
3234
3459
  (tool) => !managedAgent || tool !== "agent"
3235
3460
  );
@@ -3254,7 +3479,7 @@ function agentLaunchArgs(agent, options) {
3254
3479
  args.push("--append-system-prompt", `<active_agent name="${agent.name}"/>`);
3255
3480
  return args;
3256
3481
  }
3257
- var VALID_THINKING_LEVELS, THINKING_LEVELS, SYSTEM_PROMPT_MODES, BODY_MODES, STRING_FIELDS, BOOLEAN_CAPABILITY_FIELDS, ARRAY_FIELDS, SUPPORTED_FIELDS, BODY_FILE_REFERENCE, BUILTIN_AGENT_DIR, BUILTIN_ROLE_DIR, FLEXIBLE_LEAD_DEFINITION_NAME, ORCHESTRATOR_LEAD_DEFINITION_NAME, MANAGED_LEAD_DEFINITION_NAME, MANAGER_DEFINITION_NAME, CHIEF_DEFINITION_NAME, RESERVED_ROLE_DEFINITION_NAMES, RESERVED_ROLE_DEFINITION_NAME_SET, RUNTIME_LEAD_FIELDS, AGENT_COORDINATION_TOOLS, definitionWarningSessions;
3482
+ var VALID_THINKING_LEVELS, THINKING_LEVELS, SYSTEM_PROMPT_MODES, BODY_MODES, STRING_FIELDS, BOOLEAN_CAPABILITY_FIELDS, ARRAY_FIELDS, SUPPORTED_FIELDS, BODY_FILE_REFERENCE, BUILTIN_AGENT_DIR, BUILTIN_ROLE_DIR, FLEXIBLE_LEAD_DEFINITION_NAME, ORCHESTRATOR_LEAD_DEFINITION_NAME, MANAGED_LEAD_DEFINITION_NAME, MANAGER_DEFINITION_NAME, CHIEF_DEFINITION_NAME, RESERVED_ROLE_DEFINITION_NAMES, RESERVED_ROLE_DEFINITION_NAME_SET, RUNTIME_LEAD_FIELDS, AGENT_COORDINATION_TOOLS, isArrayModifier, definitionWarningSessions;
3258
3483
  var init_agent_definitions = __esm({
3259
3484
  "extension/agent-definitions.ts"() {
3260
3485
  "use strict";
@@ -3344,6 +3569,7 @@ var init_agent_definitions = __esm({
3344
3569
  "inspect_agent",
3345
3570
  "read_agent_transcript"
3346
3571
  ];
3572
+ isArrayModifier = (entry) => entry.startsWith("+") || entry.startsWith("-");
3347
3573
  definitionWarningSessions = /* @__PURE__ */ new WeakMap();
3348
3574
  }
3349
3575
  });
@@ -3362,7 +3588,7 @@ import {
3362
3588
  statSync as statSync4
3363
3589
  } from "node:fs";
3364
3590
  import { createConnection } from "node:net";
3365
- import { isAbsolute as isAbsolute2, join as join5, resolve as resolve3 } from "node:path";
3591
+ import { isAbsolute as isAbsolute2, join as join5, resolve as resolve4 } from "node:path";
3366
3592
  import { StringDecoder } from "node:string_decoder";
3367
3593
  import { setTimeout as sleep } from "node:timers/promises";
3368
3594
  function parseHerdrVersion(value2) {
@@ -3706,7 +3932,7 @@ function herdrAgentAlias(workspaceId, label, runId) {
3706
3932
  return alias(workspaceId, label, runId);
3707
3933
  }
3708
3934
  function canonicalCwd(value2) {
3709
- const resolved = resolve3(value2);
3935
+ const resolved = resolve4(value2);
3710
3936
  try {
3711
3937
  return realpathSync3.native(resolved);
3712
3938
  } catch {
@@ -3792,7 +4018,7 @@ async function lockLifecycle(ctx, signal) {
3792
4018
  "locks",
3793
4019
  createHash7("sha256").update(id).digest("hex")
3794
4020
  );
3795
- mkdirSync5(resolve3(path, ".."), { recursive: true, mode: 448 });
4021
+ mkdirSync5(resolve4(path, ".."), { recursive: true, mode: 448 });
3796
4022
  const deadline = Date.now() + 3e4;
3797
4023
  while (true) {
3798
4024
  if (signal?.aborted) throw signal.reason ?? new Error("operation aborted");
@@ -5493,7 +5719,7 @@ import {
5493
5719
  writeFileSync as writeFileSync3
5494
5720
  } from "node:fs";
5495
5721
  import { createHash as createHash8, randomUUID as randomUUID7 } from "node:crypto";
5496
- import { basename as basename5, dirname as dirname5, isAbsolute as isAbsolute3, join as join6, normalize } from "node:path";
5722
+ import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute3, join as join6, normalize } from "node:path";
5497
5723
  import { isDeepStrictEqual } from "node:util";
5498
5724
  function readSessionKind(entries, sessionId) {
5499
5725
  let identity;
@@ -5692,7 +5918,7 @@ function writePeerDeliveryReceipt(runtime, record) {
5692
5918
  if (record.kind !== "peer_message")
5693
5919
  throw new Error("Peer delivery receipt requires a peer message");
5694
5920
  const path = peerDeliveryReceiptPath(runtime, record.toSessionId, record.id);
5695
- const directory2 = dirname5(path);
5921
+ const directory2 = dirname6(path);
5696
5922
  mkdirSync6(directory2, { recursive: true, mode: 448 });
5697
5923
  const receipt = {
5698
5924
  sessionId: record.toSessionId,
@@ -5710,7 +5936,7 @@ function writePeerDeliveryReceipt(runtime, record) {
5710
5936
  if (error2.code !== "ENOENT") throw error2;
5711
5937
  }
5712
5938
  publishRecord(path, content);
5713
- fsyncDirectory(dirname5(directory2));
5939
+ fsyncDirectory(dirname6(directory2));
5714
5940
  }
5715
5941
  function fsyncDirectory(directory2) {
5716
5942
  if (process.platform === "win32") return;
@@ -5722,7 +5948,7 @@ function fsyncDirectory(directory2) {
5722
5948
  }
5723
5949
  }
5724
5950
  function publishRecord(path, content) {
5725
- const directory2 = dirname5(path);
5951
+ const directory2 = dirname6(path);
5726
5952
  const temporary = join6(directory2, `.${basename5(path)}.${randomUUID7()}.tmp`);
5727
5953
  let fd;
5728
5954
  let cleanupError;
@@ -5867,18 +6093,18 @@ function removeMalformedChiefMessageUnlocked(runtime, toSessionId, id) {
5867
6093
  }
5868
6094
  try {
5869
6095
  const claimed = join6(
5870
- dirname5(path),
6096
+ dirname6(path),
5871
6097
  `.${basename5(path, ".json")}.${randomUUID7()}.cleanup`
5872
6098
  );
5873
6099
  renameSync5(path, claimed);
5874
- fsyncDirectory(dirname5(path));
6100
+ fsyncDirectory(dirname6(path));
5875
6101
  try {
5876
6102
  unlinkSync5(claimed);
5877
- fsyncDirectory(dirname5(path));
6103
+ fsyncDirectory(dirname6(path));
5878
6104
  } catch (error2) {
5879
6105
  try {
5880
6106
  renameSync5(claimed, path);
5881
- fsyncDirectory(dirname5(path));
6107
+ fsyncDirectory(dirname6(path));
5882
6108
  } catch {
5883
6109
  }
5884
6110
  throw error2;
@@ -5927,7 +6153,7 @@ function removeChiefMessageQuarantineUnlocked(runtime, toSessionId, id) {
5927
6153
  const path = chiefMessagePath(runtime, toSessionId, id);
5928
6154
  try {
5929
6155
  unlinkSync5(`${path}.quarantine`);
5930
- fsyncDirectory(dirname5(path));
6156
+ fsyncDirectory(dirname6(path));
5931
6157
  } catch (error2) {
5932
6158
  if (error2.code === "ENOENT") return;
5933
6159
  try {
@@ -6120,7 +6346,7 @@ function removeChiefMessage(runtime, toSessionId, id, expected) {
6120
6346
  }
6121
6347
  function removeChiefMessageUnlocked(runtime, toSessionId, id, expected) {
6122
6348
  const path = chiefMessagePath(runtime, toSessionId, id);
6123
- const directory2 = dirname5(path);
6349
+ const directory2 = dirname6(path);
6124
6350
  const matchesExpected = () => {
6125
6351
  if (!expected) return true;
6126
6352
  try {
@@ -6192,7 +6418,7 @@ function quarantineChiefMessageUnlocked(runtime, toSessionId, id) {
6192
6418
  fsyncSync3(fd);
6193
6419
  closeSync6(fd);
6194
6420
  fd = void 0;
6195
- fsyncDirectory(dirname5(quarantine));
6421
+ fsyncDirectory(dirname6(quarantine));
6196
6422
  } finally {
6197
6423
  if (fd !== void 0) closeSync6(fd);
6198
6424
  }
@@ -6667,7 +6893,7 @@ function removePeerLeadRecord(runtime, piSessionId, expected) {
6667
6893
  if (!current || !samePeerLeadRecord(current, expected)) return;
6668
6894
  }
6669
6895
  unlinkSync5(path);
6670
- fsyncDirectory(dirname5(path));
6896
+ fsyncDirectory(dirname6(path));
6671
6897
  } catch (error2) {
6672
6898
  if (error2.code !== "ENOENT") throw error2;
6673
6899
  }
@@ -6739,7 +6965,7 @@ function chiefLeaseIsHeld(runtime) {
6739
6965
  }
6740
6966
  function writeDescriptor(path, descriptor) {
6741
6967
  const temporary = join6(
6742
- dirname5(path),
6968
+ dirname6(path),
6743
6969
  `.${basename5(path)}.${randomUUID7()}.tmp`
6744
6970
  );
6745
6971
  const content = `${JSON.stringify(descriptor)}
@@ -6756,7 +6982,7 @@ function writeDescriptor(path, descriptor) {
6756
6982
  chmodSync5(temporary, 384);
6757
6983
  renameSync5(temporary, path);
6758
6984
  chmodSync5(path, 384);
6759
- fsyncDirectory(dirname5(path));
6985
+ fsyncDirectory(dirname6(path));
6760
6986
  } finally {
6761
6987
  if (fd !== void 0) closeSync6(fd);
6762
6988
  try {
@@ -7049,7 +7275,7 @@ function writeProjectAssignmentUnlocked(runtime, assignment) {
7049
7275
  assignment.repoKey,
7050
7276
  assignment.branch
7051
7277
  );
7052
- const directory2 = dirname5(path);
7278
+ const directory2 = dirname6(path);
7053
7279
  mkdirSync6(directory2, { recursive: true, mode: 448 });
7054
7280
  chmodSync5(runtime.root, 448);
7055
7281
  chmodSync5(runtime.assignments, 448);
@@ -7146,7 +7372,7 @@ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
7146
7372
  }
7147
7373
  if (projectAssignmentBytes(value2) > PROJECT_ASSIGNMENT_MAX_BYTES)
7148
7374
  throw projectAssignmentReadError(path, "assignment payload is too large");
7149
- if (repoKey !== void 0 && value2.repoKey !== repoKey || basename5(dirname5(path)) !== createHash8("sha256").update(value2.repoKey).digest("hex") || branch !== void 0 && value2.branch !== branch || basename5(path) !== `${createHash8("sha256").update(value2.branch).digest("hex")}${pending ? `.${value2.id}` : ""}.json`)
7375
+ if (repoKey !== void 0 && value2.repoKey !== repoKey || basename5(dirname6(path)) !== createHash8("sha256").update(value2.repoKey).digest("hex") || branch !== void 0 && value2.branch !== branch || basename5(path) !== `${createHash8("sha256").update(value2.branch).digest("hex")}${pending ? `.${value2.id}` : ""}.json`)
7150
7376
  throw projectAssignmentReadError(path, "assignment identity mismatch");
7151
7377
  return value2;
7152
7378
  }
@@ -7158,7 +7384,7 @@ function projectAssignmentReadError(path, reason) {
7158
7384
  return new Error(`Unable to read project assignment ${path}: ${reason}`);
7159
7385
  }
7160
7386
  function listProjectAssignments(runtime, repoKey) {
7161
- const directory2 = dirname5(projectAssignmentPath(runtime, repoKey, "lookup"));
7387
+ const directory2 = dirname6(projectAssignmentPath(runtime, repoKey, "lookup"));
7162
7388
  let entries;
7163
7389
  try {
7164
7390
  entries = readdirSync5(directory2);
@@ -7188,11 +7414,11 @@ function retireProjectAssignment(runtime, expected) {
7188
7414
  return withProjectAssignmentLock(() => {
7189
7415
  for (const directory2 of [
7190
7416
  herdsmanDataRoot(),
7191
- dirname5(dirname5(runtime.root)),
7192
- dirname5(runtime.root),
7417
+ dirname6(dirname6(runtime.root)),
7418
+ dirname6(runtime.root),
7193
7419
  runtime.root,
7194
7420
  runtime.assignments,
7195
- dirname5(
7421
+ dirname6(
7196
7422
  projectAssignmentPath(runtime, expected.repoKey, expected.branch)
7197
7423
  )
7198
7424
  ])
@@ -7210,7 +7436,7 @@ function retireProjectAssignment(runtime, expected) {
7210
7436
  );
7211
7437
  const destination = pendingRetirementPath(runtime, current);
7212
7438
  const root2 = join6(runtime.root, "retirements");
7213
- for (const directory2 of [root2, dirname5(destination)]) {
7439
+ for (const directory2 of [root2, dirname6(destination)]) {
7214
7440
  try {
7215
7441
  mkdirSync6(directory2, { mode: 448 });
7216
7442
  } catch (error2) {
@@ -7221,8 +7447,8 @@ function retireProjectAssignment(runtime, expected) {
7221
7447
  if (lstatSync4(destination, { throwIfNoEntry: false }))
7222
7448
  throw new Error("Pending retirement already exists");
7223
7449
  renameSync5(source, destination);
7224
- fsyncDirectory(dirname5(source));
7225
- fsyncDirectory(dirname5(destination));
7450
+ fsyncDirectory(dirname6(source));
7451
+ fsyncDirectory(dirname6(destination));
7226
7452
  fsyncDirectory(root2);
7227
7453
  fsyncDirectory(runtime.root);
7228
7454
  return true;
@@ -7239,13 +7465,13 @@ function pendingRetirementPath(runtime, expected) {
7239
7465
  return join6(
7240
7466
  runtime.root,
7241
7467
  "retirements",
7242
- basename5(dirname5(active)),
7468
+ basename5(dirname6(active)),
7243
7469
  `${basename5(active, ".json")}.${expected.id}.json`
7244
7470
  );
7245
7471
  }
7246
7472
  function listPendingRetirements(runtime, repoKey, options = {}) {
7247
7473
  const repository = basename5(
7248
- dirname5(projectAssignmentPath(runtime, repoKey, "lookup"))
7474
+ dirname6(projectAssignmentPath(runtime, repoKey, "lookup"))
7249
7475
  );
7250
7476
  const root2 = join6(runtime.root, "retirements");
7251
7477
  const directory2 = join6(root2, repository);
@@ -7253,8 +7479,8 @@ function listPendingRetirements(runtime, repoKey, options = {}) {
7253
7479
  try {
7254
7480
  for (const parent of [
7255
7481
  herdsmanDataRoot(),
7256
- dirname5(dirname5(runtime.root)),
7257
- dirname5(runtime.root),
7482
+ dirname6(dirname6(runtime.root)),
7483
+ dirname6(runtime.root),
7258
7484
  runtime.root,
7259
7485
  root2,
7260
7486
  directory2
@@ -7304,11 +7530,11 @@ function removePendingRetirement(runtime, expected) {
7304
7530
  const root2 = join6(runtime.root, "retirements");
7305
7531
  for (const directory2 of [
7306
7532
  herdsmanDataRoot(),
7307
- dirname5(dirname5(runtime.root)),
7308
- dirname5(runtime.root),
7533
+ dirname6(dirname6(runtime.root)),
7534
+ dirname6(runtime.root),
7309
7535
  runtime.root,
7310
7536
  root2,
7311
- dirname5(path)
7537
+ dirname6(path)
7312
7538
  ])
7313
7539
  assignmentDirectory(directory2);
7314
7540
  const record = readProjectAssignmentFile(
@@ -7321,7 +7547,7 @@ function removePendingRetirement(runtime, expected) {
7321
7547
  if (record.id !== expected.id)
7322
7548
  throw new Error("Pending retirement identity mismatch");
7323
7549
  unlinkSync5(path);
7324
- fsyncDirectory(dirname5(path));
7550
+ fsyncDirectory(dirname6(path));
7325
7551
  });
7326
7552
  }
7327
7553
  function assignmentDirectory(path) {
@@ -7453,7 +7679,7 @@ function projectMessageEnvelope(kind, branch, sessionId) {
7453
7679
  }
7454
7680
  function projectMessageDirectory(runtime, repoKey, branch) {
7455
7681
  const assignment = projectAssignmentPath(runtime, repoKey, branch);
7456
- return join6(dirname5(assignment), `${basename5(assignment, ".json")}.messages`);
7682
+ return join6(dirname6(assignment), `${basename5(assignment, ".json")}.messages`);
7457
7683
  }
7458
7684
  function validProjectMessage(value2) {
7459
7685
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
@@ -7515,7 +7741,7 @@ function writeProjectMessageUnlocked(record, runtime) {
7515
7741
  mkdirSync6(directory2, { recursive: true, mode: 448 });
7516
7742
  chmodSync5(runtime.root, 448);
7517
7743
  chmodSync5(runtime.assignments, 448);
7518
- chmodSync5(dirname5(directory2), 448);
7744
+ chmodSync5(dirname6(directory2), 448);
7519
7745
  chmodSync5(directory2, 448);
7520
7746
  const path = join6(directory2, `${record.id}.json`);
7521
7747
  let stored = record;
@@ -7682,7 +7908,7 @@ function removeProjectMessagesForAssignment(runtime, assignment) {
7682
7908
  }
7683
7909
  function recoverStaleProjectMessages(runtime, repoKey) {
7684
7910
  withProjectAssignmentLock(() => {
7685
- const directory2 = dirname5(
7911
+ const directory2 = dirname6(
7686
7912
  projectAssignmentPath(runtime, repoKey, "lookup")
7687
7913
  );
7688
7914
  let entries;
@@ -7729,7 +7955,7 @@ function recoverStaleProjectMessages(runtime, repoKey) {
7729
7955
  });
7730
7956
  }
7731
7957
  function mightHaveProjectMessages(runtime, repoKey) {
7732
- const directory2 = dirname5(projectAssignmentPath(runtime, repoKey, "lookup"));
7958
+ const directory2 = dirname6(projectAssignmentPath(runtime, repoKey, "lookup"));
7733
7959
  let entries;
7734
7960
  try {
7735
7961
  entries = readdirSync5(directory2, { withFileTypes: true });
@@ -7964,7 +8190,7 @@ function invalidateLeadCoordinationState(runtime, piSessionId, expectedInstanceI
7964
8190
  if (error2.code !== "ENOENT") throw error2;
7965
8191
  return;
7966
8192
  }
7967
- fsyncDirectory(dirname5(path));
8193
+ fsyncDirectory(dirname6(path));
7968
8194
  }
7969
8195
  function normalizeHerdrLifecycleState(agent) {
7970
8196
  const state = agent?.agent_status;
@@ -8215,7 +8441,69 @@ import {
8215
8441
  writeFileSync as writeFileSync4
8216
8442
  } from "node:fs";
8217
8443
  import { homedir as homedir3 } from "node:os";
8218
- import { basename as basename6, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative as relative2, sep as sep2 } from "node:path";
8444
+ import { basename as basename6, dirname as dirname7, isAbsolute as isAbsolute4, join as join7, relative as relative2, sep as sep2 } from "node:path";
8445
+ function summarizeDefinitionLayerChanges(layer) {
8446
+ const fields = [
8447
+ "enabled",
8448
+ "description",
8449
+ "model",
8450
+ "thinking",
8451
+ "systemPromptMode",
8452
+ "bodyMode",
8453
+ "noTools",
8454
+ "noBuiltinTools",
8455
+ "tools",
8456
+ "excludeTools",
8457
+ "noSkills",
8458
+ "skills",
8459
+ "noExtensions",
8460
+ "extensions",
8461
+ "agents",
8462
+ "inheritGlobalContext",
8463
+ "inheritProjectContext",
8464
+ "inheritSkills"
8465
+ ];
8466
+ const lines = [];
8467
+ for (const field of fields) {
8468
+ const before = layer.before?.[field];
8469
+ const after = layer.after[field];
8470
+ if (JSON.stringify(before) === JSON.stringify(after)) continue;
8471
+ if (field === "tools" || field === "skills" || field === "extensions" || field === "agents" || field === "excludeTools") {
8472
+ const supplied = layer.supplied[field];
8473
+ if (field === "tools" && Array.isArray(supplied) && supplied.length > 0 && supplied.every(
8474
+ (entry) => typeof entry === "string" && /^[+-]/u.test(entry)
8475
+ )) {
8476
+ lines.push(`~ tools: relative ${supplied.join(" ")}`);
8477
+ continue;
8478
+ }
8479
+ const beforeArray = Array.isArray(before) ? before : void 0;
8480
+ const afterArray = Array.isArray(after) ? after : [];
8481
+ if (beforeArray === void 0) {
8482
+ if (afterArray.length)
8483
+ lines.push(`~ ${field}: set to ${afterArray.join(", ")}`);
8484
+ continue;
8485
+ }
8486
+ const removed = beforeArray.filter(
8487
+ (entry) => !afterArray.includes(entry)
8488
+ );
8489
+ const added = afterArray.filter((entry) => !beforeArray.includes(entry));
8490
+ if (removed.length) lines.push(`- ${field}: ${removed.join(", ")}`);
8491
+ if (added.length) lines.push(`+ ${field}: ${added.join(", ")}`);
8492
+ continue;
8493
+ }
8494
+ const next = after === void 0 ? "unset" : String(after);
8495
+ if (before === void 0) lines.push(`+ ${field}: ${next}`);
8496
+ else {
8497
+ const previous = String(before);
8498
+ lines.push(`~ ${field}: ${previous} \u2192 ${next}`);
8499
+ }
8500
+ }
8501
+ if (layer.bodyAction === "replace")
8502
+ lines.push("~ body: replaced earlier body");
8503
+ else if (layer.bodyAction === "append") lines.push("+ body: appended");
8504
+ else if (layer.bodyAction === "base") lines.push("+ body: base");
8505
+ return lines;
8506
+ }
8219
8507
  function populateMenuFrame(container, theme, title, body, footer, help) {
8220
8508
  container.clear();
8221
8509
  container.addChild(new DynamicBorder((line) => theme.fg("border", line)));
@@ -9700,7 +9988,7 @@ function displayHomePath(path) {
9700
9988
  function displaySkillName(skill) {
9701
9989
  const file2 = basename6(skill);
9702
9990
  if (file2 === "SKILL.md") {
9703
- const parent = basename6(dirname6(skill));
9991
+ const parent = basename6(dirname7(skill));
9704
9992
  if (parent && parent !== "." && parent !== "..") return parent;
9705
9993
  }
9706
9994
  return file2 || skill;
@@ -9771,6 +10059,8 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9771
10059
  const lines = definitions.length > 1 ? [
9772
10060
  `${theme.bold(theme.fg("customMessageLabel", "Definitions"))}${theme.fg("muted", ` \xB7 ${definitions.length}`)}`
9773
10061
  ] : [];
10062
+ if (options.expanded === true && options.inspector?.sections)
10063
+ lines.push(theme.fg("accent", theme.bold("METADATA")));
9774
10064
  definitions.forEach((definition) => {
9775
10065
  const name = value(definition.name ?? definition.agent);
9776
10066
  if (!name) return;
@@ -9828,7 +10118,10 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9828
10118
  )
9829
10119
  );
9830
10120
  });
9831
- if (typeof options.instructions === "string" && options.expanded !== true) {
10121
+ if (options.inspector) {
10122
+ lines.push(...options.inspector.summary);
10123
+ if (options.expanded !== true) lines.push("Ctrl+O to expand");
10124
+ } else if (typeof options.instructions === "string" && options.expanded !== true) {
9832
10125
  const characters = Array.from(options.instructions).length;
9833
10126
  lines.push(
9834
10127
  humanRow(theme, "instructions", `${characters} chars \xB7 Ctrl+O to expand`)
@@ -9840,7 +10133,51 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9840
10133
  (line) => theme.bg("customMessageBg", line)
9841
10134
  );
9842
10135
  box.addChild(new WidthSafeText(lines.join("\n"), 0, 0));
9843
- if (typeof options.instructions === "string" && options.expanded === true) {
10136
+ if (options.expanded === true && options.inspector?.sections) {
10137
+ box.addChild(new Spacer(1));
10138
+ box.addChild(new DynamicBorder((line) => theme.fg("border", line)));
10139
+ box.addChild(
10140
+ new Text(
10141
+ theme.fg("accent", theme.bold("INSTRUCTIONS \xB7 Known-input order")),
10142
+ 0,
10143
+ 0
10144
+ )
10145
+ );
10146
+ options.inspector.sections.forEach((section, index) => {
10147
+ box.addChild(new Spacer(1));
10148
+ if (index > 0)
10149
+ box.addChild(new DynamicBorder((line) => theme.fg("border", line)));
10150
+ box.addChild(
10151
+ new Text(
10152
+ theme.fg("accent", theme.bold(`${index + 1}. ${section.title}`)),
10153
+ 0,
10154
+ 0
10155
+ )
10156
+ );
10157
+ if (section.source)
10158
+ box.addChild(
10159
+ new WidthSafeText(theme.fg("muted", section.source), 0, 0)
10160
+ );
10161
+ if (section.changes?.length)
10162
+ box.addChild(
10163
+ new WidthSafeText(
10164
+ theme.fg("muted", section.changes.join("\n")),
10165
+ 0,
10166
+ 0
10167
+ )
10168
+ );
10169
+ if (section.content) {
10170
+ box.addChild(new DynamicBorder((line) => theme.fg("muted", line)));
10171
+ box.addChild(new Spacer(1));
10172
+ box.addChild(
10173
+ section.format === "markdown" ? new Markdown(section.content, 0, 0, getMarkdownTheme()) : new WidthSafeText(section.content, 0, 0)
10174
+ );
10175
+ }
10176
+ });
10177
+ } else if (options.expanded === true && options.inspector?.tree !== void 0) {
10178
+ box.addChild(new Spacer(1));
10179
+ box.addChild(new WidthSafeText(options.inspector.tree, 0, 0));
10180
+ } else if (typeof options.instructions === "string" && options.expanded === true) {
9844
10181
  box.addChild(new Spacer(1));
9845
10182
  box.addChild(
9846
10183
  new Text(
@@ -10832,7 +11169,7 @@ function savePrivateOutput(text, sessionId, key, kind) {
10832
11169
  hash(sessionId),
10833
11170
  `${hash(key)}.txt`
10834
11171
  );
10835
- const root2 = dirname6(path);
11172
+ const root2 = dirname7(path);
10836
11173
  mkdirSync7(root2, { recursive: true, mode: 448 });
10837
11174
  chmodSync6(root2, 448);
10838
11175
  temp = `${path}.${process.pid}.${randomUUID8()}.tmp`;
@@ -13167,7 +13504,7 @@ import {
13167
13504
  writeFileSync as writeFileSync5
13168
13505
  } from "node:fs";
13169
13506
  import { randomUUID as randomUUID9 } from "node:crypto";
13170
- import { basename as basename7, dirname as dirname7, join as join8 } from "node:path";
13507
+ import { basename as basename7, dirname as dirname8, join as join8 } from "node:path";
13171
13508
  function validManagerMergeSetting(value2) {
13172
13509
  return typeof value2 === "boolean" || value2 === "divergent";
13173
13510
  }
@@ -13448,7 +13785,7 @@ function updateProjectOverride(ctx, key, value2) {
13448
13785
  const path = projectSettingsFile(ctx);
13449
13786
  let mode = assertRegularProjectSettings(path);
13450
13787
  if (value2 === void 0 && mode === void 0) return;
13451
- mkdirSync8(dirname7(path), { recursive: true, mode: 448 });
13788
+ mkdirSync8(dirname8(path), { recursive: true, mode: 448 });
13452
13789
  const release = acquireProjectSettingsLock(path);
13453
13790
  let changed = false;
13454
13791
  try {
@@ -13497,7 +13834,7 @@ function readEffectiveConfig(ctx) {
13497
13834
  return { ...readConfig(), ...readProjectOverrides(ctx) };
13498
13835
  }
13499
13836
  function writeConfigAtomically(path, content, mode = 384) {
13500
- const directory2 = dirname7(path);
13837
+ const directory2 = dirname8(path);
13501
13838
  const temporaryPath = join8(
13502
13839
  directory2,
13503
13840
  `.${basename7(path)}.${randomUUID9()}.tmp`
@@ -13638,7 +13975,7 @@ import { unlinkSync as unlinkSync8 } from "node:fs";
13638
13975
  import { createHash as createHash10, randomUUID as randomUUID10 } from "node:crypto";
13639
13976
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
13640
13977
  import { homedir as homedir4 } from "node:os";
13641
- import { basename as basename8, join as join9, resolve as resolve4 } from "node:path";
13978
+ import { basename as basename8, join as join9, resolve as resolve5 } from "node:path";
13642
13979
  import { setTimeout as delay } from "node:timers/promises";
13643
13980
  import { StringEnum } from "@earendil-works/pi-ai";
13644
13981
  import { Type } from "typebox";
@@ -15288,7 +15625,7 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
15288
15625
  );
15289
15626
  selector = { kind: "id", value: value2 };
15290
15627
  } else {
15291
- const path = value2 === "~" ? homedir4() : value2.startsWith("~/") || value2.startsWith("~\\") ? resolve4(homedir4(), value2.slice(2)) : resolve4(ctx.cwd, value2);
15628
+ const path = value2 === "~" ? homedir4() : value2.startsWith("~/") || value2.startsWith("~\\") ? resolve5(homedir4(), value2.slice(2)) : resolve5(ctx.cwd, value2);
15292
15629
  try {
15293
15630
  selector = { kind: "path", value: canonicalSessionPath(path) };
15294
15631
  } catch (error2) {
@@ -15842,13 +16179,13 @@ function validateAssignmentCwd(definition, agentCwd, controllerCwd, scope, opera
15842
16179
  if (definition.projectSource && !sameCwd(agentCwd, controllerCwd))
15843
16180
  fail(
15844
16181
  "invalid_request",
15845
- `Project agent ${definition.name} belongs to ${resolve4(controllerCwd)}`,
16182
+ `Project agent ${definition.name} belongs to ${resolve5(controllerCwd)}`,
15846
16183
  operation
15847
16184
  );
15848
16185
  if (scope.kind === "managed-agent" && !sameCwd(agentCwd, controllerCwd))
15849
16186
  fail(
15850
16187
  "invalid_request",
15851
- `Delegated agents must use the delegating agent cwd ${resolve4(controllerCwd)}`,
16188
+ `Delegated agents must use the delegating agent cwd ${resolve5(controllerCwd)}`,
15852
16189
  operation
15853
16190
  );
15854
16191
  }
@@ -19151,7 +19488,7 @@ ${ownerMessage.text}`;
19151
19488
  const existingPaths = new Set(
19152
19489
  requiredEvidence.filter(
19153
19490
  (entry) => !("result" in entry)
19154
- ).map((entry) => resolve4(entry.path))
19491
+ ).map((entry) => resolve5(entry.path))
19155
19492
  );
19156
19493
  const existingRefs = new Set(
19157
19494
  requiredEvidence.filter(
@@ -19165,7 +19502,7 @@ ${ownerMessage.text}`;
19165
19502
  if (typeof file2 === "string") {
19166
19503
  let canonicalPath;
19167
19504
  try {
19168
- canonicalPath = realpathSync4(resolve4(ctx.cwd, file2));
19505
+ canonicalPath = realpathSync4(resolve5(ctx.cwd, file2));
19169
19506
  } catch {
19170
19507
  }
19171
19508
  if (canonicalPath && (existingPaths.has(canonicalPath) || retainedPaths.has(canonicalPath)))
@@ -19293,7 +19630,7 @@ ${ownerMessage.text}`;
19293
19630
  )).map((file2) => {
19294
19631
  if (typeof file2 !== "string") return file2;
19295
19632
  try {
19296
- const path = realpathSync4(resolve4(ctx.cwd, file2));
19633
+ const path = realpathSync4(resolve5(ctx.cwd, file2));
19297
19634
  const result = requiredEvidence.find((entry) => {
19298
19635
  if (!("result" in entry)) return false;
19299
19636
  const resultPath2 = resolveResultRef(entry.result.canonicalRef);
@@ -19641,57 +19978,71 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19641
19978
  }
19642
19979
  if (!ownerDisplay)
19643
19980
  throw new Error("Verified direct owner role is unavailable");
19981
+ let reservedChildSessionId;
19644
19982
  if (p.action === "delegate") {
19645
19983
  const registrations = /* @__PURE__ */ new Map();
19646
19984
  let open = true;
19985
+ let preparing = true;
19647
19986
  let registrationError;
19648
- pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
19649
- protocol: 1,
19650
- phase: "prepare",
19651
- context: ctx,
19652
- agent: label,
19653
- register(id, prepare) {
19654
- if (!open)
19655
- throw new Error(
19656
- "Managed-agent bootstrap registration is closed"
19657
- );
19658
- if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(id)) {
19659
- registrationError ??= new Error(
19660
- "Invalid managed-agent bootstrap participant ID"
19661
- );
19662
- return;
19663
- }
19664
- if (registrations.has(id)) {
19665
- registrationError ??= new Error(
19666
- `Duplicate managed-agent bootstrap participant ID: ${id}`
19667
- );
19668
- return;
19987
+ const participants = [];
19988
+ try {
19989
+ pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
19990
+ protocol: 1,
19991
+ phase: "prepare",
19992
+ context: ctx,
19993
+ agent: label,
19994
+ reserveChildSessionId() {
19995
+ if (!preparing)
19996
+ throw new Error(
19997
+ "Managed-Agent bootstrap preparation is closed"
19998
+ );
19999
+ return reservedChildSessionId ??= randomUUID10();
20000
+ },
20001
+ register(id, prepare) {
20002
+ if (!open)
20003
+ throw new Error(
20004
+ "Managed-agent bootstrap registration is closed"
20005
+ );
20006
+ if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(id)) {
20007
+ registrationError ??= new Error(
20008
+ "Invalid managed-agent bootstrap participant ID"
20009
+ );
20010
+ return;
20011
+ }
20012
+ if (registrations.has(id)) {
20013
+ registrationError ??= new Error(
20014
+ `Duplicate managed-agent bootstrap participant ID: ${id}`
20015
+ );
20016
+ return;
20017
+ }
20018
+ if (typeof prepare !== "function") {
20019
+ registrationError ??= new Error(
20020
+ "Invalid managed-agent bootstrap prepare callback"
20021
+ );
20022
+ return;
20023
+ }
20024
+ registrations.set(id, prepare);
19669
20025
  }
19670
- if (typeof prepare !== "function") {
19671
- registrationError ??= new Error(
19672
- "Invalid managed-agent bootstrap prepare callback"
19673
- );
19674
- return;
20026
+ });
20027
+ open = false;
20028
+ if (registrationError) throw registrationError;
20029
+ for (const [id, prepare] of registrations) {
20030
+ const result = await prepare();
20031
+ if (result !== void 0) {
20032
+ if (!result || typeof result.payload !== "string" || result.commit !== void 0 && typeof result.commit !== "function")
20033
+ throw new Error(
20034
+ `Invalid preparation from managed-agent bootstrap participant "${id}"`
20035
+ );
20036
+ participants.push({ id, payload: result.payload });
20037
+ preparedBootstrap.push({
20038
+ id,
20039
+ ...result.commit ? { commit: result.commit } : {}
20040
+ });
19675
20041
  }
19676
- registrations.set(id, prepare);
19677
- }
19678
- });
19679
- open = false;
19680
- if (registrationError) throw registrationError;
19681
- const participants = [];
19682
- for (const [id, prepare] of registrations) {
19683
- const result = await prepare();
19684
- if (result !== void 0) {
19685
- if (!result || typeof result.payload !== "string" || result.commit !== void 0 && typeof result.commit !== "function")
19686
- throw new Error(
19687
- `Invalid preparation from managed-agent bootstrap participant "${id}"`
19688
- );
19689
- participants.push({ id, payload: result.payload });
19690
- preparedBootstrap.push({
19691
- id,
19692
- ...result.commit ? { commit: result.commit } : {}
19693
- });
19694
20042
  }
20043
+ } finally {
20044
+ open = false;
20045
+ preparing = false;
19695
20046
  }
19696
20047
  if (participants.length)
19697
20048
  writeAgentBootstrap(mailbox, {
@@ -19701,6 +20052,7 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19701
20052
  ownerSessionId: owner,
19702
20053
  workspaceId,
19703
20054
  agentLabel: label,
20055
+ ...reservedChildSessionId ? { childSessionId: reservedChildSessionId } : {},
19704
20056
  participants
19705
20057
  });
19706
20058
  }
@@ -19759,7 +20111,11 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19759
20111
  extensionPath: options.extensionPath,
19760
20112
  placement,
19761
20113
  ...placementRevalidator ? { placementRevalidator } : {},
19762
- agentArgs: [...launchArgs, ...sessionArgs],
20114
+ agentArgs: [
20115
+ ...launchArgs,
20116
+ ...reservedChildSessionId && preparedBootstrap.length ? ["--session-id", reservedChildSessionId] : [],
20117
+ ...sessionArgs
20118
+ ],
19763
20119
  env,
19764
20120
  signal
19765
20121
  });
@@ -19868,6 +20224,12 @@ ${result.stderr ?? ""}`.trim(),
19868
20224
  "Managed Agent state identity did not match startup",
19869
20225
  p.action
19870
20226
  );
20227
+ if (reservedChildSessionId && state.piSessionId !== reservedChildSessionId)
20228
+ fail(
20229
+ "target_not_found",
20230
+ "Managed Agent started with an unexpected Pi session ID",
20231
+ p.action
20232
+ );
19871
20233
  requireCompatibleBuild(
19872
20234
  options.build,
19873
20235
  state.build,
@@ -22026,7 +22388,7 @@ __export(managed_agent_runtime_exports, {
22026
22388
  sessionContextRetired: () => sessionContextRetired,
22027
22389
  validateManagedAgentIdentity: () => validateManagedAgentIdentity
22028
22390
  });
22029
- import { isAbsolute as isAbsolute5, join as join10, resolve as resolve5 } from "node:path";
22391
+ import { isAbsolute as isAbsolute5, join as join10, resolve as resolve6 } from "node:path";
22030
22392
  import { existsSync as existsSync2, realpathSync as realpathSync5 } from "node:fs";
22031
22393
  import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent";
22032
22394
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
@@ -22386,7 +22748,7 @@ function validateManagedAgentIdentity(input) {
22386
22748
  ids: { label: env.PI_HERDSMAN_LABEL, paneId: env.HERDR_PANE_ID }
22387
22749
  }
22388
22750
  );
22389
- if (!state || !mailbox || state.workspaceId !== env.PI_HERDSMAN_WORKSPACE_ID || state.agentLabel !== env.PI_HERDSMAN_LABEL || state.paneId !== env.HERDR_PANE_ID || state.ownerSessionId !== env.PI_HERDSMAN_OWNER_SESSION_ID || state.rootSessionId !== void 0 && (!env.PI_HERDSMAN_ROOT_SESSION_ID?.trim() || state.rootSessionId !== env.PI_HERDSMAN_ROOT_SESSION_ID.trim()) || state.piSessionId !== input.sessionId || !input.sameSessionPath(state.piSessionFile, input.sessionFile) || resolve5(state.cwd) !== resolve5(input.cwd) || state.runId !== env.PI_HERDSMAN_RUN_ID)
22751
+ if (!state || !mailbox || state.workspaceId !== env.PI_HERDSMAN_WORKSPACE_ID || state.agentLabel !== env.PI_HERDSMAN_LABEL || state.paneId !== env.HERDR_PANE_ID || state.ownerSessionId !== env.PI_HERDSMAN_OWNER_SESSION_ID || state.rootSessionId !== void 0 && (!env.PI_HERDSMAN_ROOT_SESSION_ID?.trim() || state.rootSessionId !== env.PI_HERDSMAN_ROOT_SESSION_ID.trim()) || state.piSessionId !== input.sessionId || !input.sameSessionPath(state.piSessionFile, input.sessionFile) || resolve6(state.cwd) !== resolve6(input.cwd) || state.runId !== env.PI_HERDSMAN_RUN_ID)
22390
22752
  fail(
22391
22753
  "target_not_found",
22392
22754
  "Delegation controller identity is not a valid managed agent",
@@ -24760,6 +25122,7 @@ function registerManagedAgentContextHandlers(pi, options) {
24760
25122
  pi.on("session_before_fork", () => ({ cancel: true }));
24761
25123
  }
24762
25124
  function registerManagedAgentSessionStartHandler(pi, execution, options) {
25125
+ let pendingStartup;
24763
25126
  pi.on("session_start", async (_event, ctx) => {
24764
25127
  let verified;
24765
25128
  let startupStage = "definition";
@@ -24800,7 +25163,7 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24800
25163
  );
24801
25164
  if (selection.kind === "unresolved")
24802
25165
  throw new Error(
24803
- `Cannot continue Agent: saved model history is ambiguous (${selection.candidates.map((model2) => `${model2.provider}/${model2.modelId}`).join(" vs ")}). Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
25166
+ `Cannot continue Agent: saved model history is ambiguous (${selection.candidates.map((model) => `${model.provider}/${model.modelId}`).join(" vs ")}). Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
24804
25167
  );
24805
25168
  const expected = selection.model;
24806
25169
  const available = ctx.modelRegistry.find(
@@ -24851,150 +25214,243 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24851
25214
  }
24852
25215
  }
24853
25216
  }
25217
+ const reservedSessionIsFresh = () => !ctx.sessionManager.getEntries().some((entry) => {
25218
+ switch (entry.type) {
25219
+ case "message":
25220
+ return entry.message.role !== "system";
25221
+ case "custom_message":
25222
+ case "compaction":
25223
+ case "branch_summary":
25224
+ case "context_edit":
25225
+ return true;
25226
+ case "thinking_level_change":
25227
+ case "model_change":
25228
+ case "usage":
25229
+ case "custom":
25230
+ case "label":
25231
+ case "session_info":
25232
+ return false;
25233
+ default:
25234
+ return true;
25235
+ }
25236
+ });
25237
+ let bootstrap = void 0;
24854
25238
  if (!existing) {
24855
25239
  startupStage = "definition";
24856
25240
  validateManagedAgentDefinition(await options.getAgentDefinitions(ctx));
24857
25241
  startupStage = "bootstrap";
24858
- const bootstrap = readAgentBootstrap(mailbox);
25242
+ bootstrap = readAgentBootstrap(mailbox);
24859
25243
  if (bootstrap) {
24860
25244
  if (bootstrap.runId !== candidate.runId || bootstrap.ownerSessionId !== candidate.ownerSessionId || bootstrap.workspaceId !== candidate.workspaceId || bootstrap.agentLabel !== candidate.agentLabel)
24861
25245
  throw new Error("Managed-agent bootstrap identity mismatch");
24862
25246
  if (!sameRuntimeBuild(options.build, bootstrap.build))
24863
25247
  throw new Error("Managed-agent bootstrap Herdsman build mismatch");
24864
- for (const participant of bootstrap.participants) {
24865
- let initializer;
24866
- let acceptCount = 0;
24867
- let invalidInitializer = false;
24868
- pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
24869
- protocol: 1,
24870
- phase: "initialize",
24871
- context: ctx,
24872
- agent: candidate.agentLabel,
24873
- participant: { id: participant.id, payload: participant.payload },
24874
- accept(callback) {
24875
- acceptCount++;
24876
- if (typeof callback !== "function") {
24877
- invalidInitializer = true;
24878
- return;
24879
- }
24880
- if (acceptCount === 1) initializer = callback;
24881
- }
24882
- });
24883
- if (acceptCount === 0 || invalidInitializer)
24884
- throw new Error(
24885
- `Managed-agent bootstrap participant "${participant.id}" is unavailable or invalid`
24886
- );
24887
- if (acceptCount > 1)
25248
+ if (bootstrap.childSessionId) {
25249
+ const nativeSessionId = ctx.sessionManager.getSessionId();
25250
+ if (nativeSessionId !== bootstrap.childSessionId || candidate.piSessionId !== bootstrap.childSessionId)
24888
25251
  throw new Error(
24889
- `Managed-agent bootstrap participant "${participant.id}" has multiple initializers`
25252
+ "Managed-agent bootstrap child session identity mismatch"
24890
25253
  );
24891
- try {
24892
- await initializer();
24893
- } catch (error2) {
25254
+ if (!reservedSessionIsFresh())
24894
25255
  throw new Error(
24895
- `Managed-agent bootstrap participant "${participant.id}" failed: ${String(error2)}`,
24896
- { cause: error2 }
25256
+ "Managed-agent bootstrap child session is not fresh"
24897
25257
  );
24898
- }
24899
25258
  }
24900
- removeAgentBootstrap(mailbox);
24901
25259
  }
24902
25260
  }
24903
- startupStage = "mailbox_state";
24904
- const release = options.claimAssignmentLock(mailbox, "session_start", {
24905
- label: execution.assignment.agentLabel,
24906
- paneId: execution.assignment.paneId
24907
- });
24908
- try {
24909
- const current = readAgentState(mailbox);
24910
- if (current && !options.sameIdentity(current, execution.assignment))
24911
- throw new Error("agent session identity changed while state existed");
24912
- if (existing !== void 0 && current === void 0)
24913
- throw new Error("agent mailbox disappeared while state existed");
24914
- if (existing !== void 0 && current !== void 0 && !options.sameDurableState(current, existing))
24915
- throw new Error(
24916
- "agent mailbox changed while session start was preparing"
24917
- );
24918
- if (existing === void 0 && current !== void 0)
24919
- execution.assignment = {
24920
- ...candidate,
24921
- ...current,
25261
+ const finishStartup = async () => {
25262
+ if (!execution.assignment)
25263
+ throw new Error("Managed Agent startup state is unavailable");
25264
+ startupStage = "mailbox_state";
25265
+ const release = options.claimAssignmentLock(mailbox, "session_start", {
25266
+ label: execution.assignment.agentLabel,
25267
+ paneId: execution.assignment.paneId
25268
+ });
25269
+ try {
25270
+ const current = readAgentState(mailbox);
25271
+ if (current && !options.sameIdentity(current, execution.assignment))
25272
+ throw new Error(
25273
+ "agent session identity changed while state existed"
25274
+ );
25275
+ if (existing !== void 0 && current === void 0)
25276
+ throw new Error("agent mailbox disappeared while state existed");
25277
+ if (existing !== void 0 && current !== void 0 && !options.sameDurableState(current, existing))
25278
+ throw new Error(
25279
+ "agent mailbox changed while session start was preparing"
25280
+ );
25281
+ if (existing === void 0 && current !== void 0)
25282
+ execution.assignment = {
25283
+ ...candidate,
25284
+ ...current,
25285
+ build: options.build,
25286
+ updatedAt: Date.now()
25287
+ };
25288
+ writeAgentState(mailbox, execution.assignment);
25289
+ } finally {
25290
+ release();
25291
+ }
25292
+ if (options.delegationEnabled) {
25293
+ startupStage = "controller_recovery";
25294
+ managedAgentControllerIdentity(ctx);
25295
+ await options.recoverControllerRuntimes(ctx, metadataSignal);
25296
+ options.setControllerReady(true);
25297
+ }
25298
+ if (execution.assignment.activeRequestId)
25299
+ options.touchActivity(Date.now(), forceActivityTouch);
25300
+ if (options.delegationEnabled)
25301
+ options.startControllerHealthScanner(ctx, metadataSignal);
25302
+ execution.initialized = true;
25303
+ const definition = process.env.PI_HERDSMAN_AGENT_DEFINITION;
25304
+ const label = execution.assignment.agentLabel;
25305
+ nameSessionIfUnset(
25306
+ pi,
25307
+ ctx,
25308
+ definition === label ? label : `${definition} \xB7 ${label}`
25309
+ );
25310
+ startupStage = "request_observer";
25311
+ execution.stopRequestObserver = observeMailbox(
25312
+ mailbox,
25313
+ (name) => /^request-.*\.json$/.test(name),
25314
+ () => options.pumpRequest(ctx),
25315
+ (error2) => options.appendError(ctx, error2)
25316
+ );
25317
+ options.pumpRequest(ctx);
25318
+ if (!options.delegationEnabled && ctx.mode === "tui" && ctx.hasUI)
25319
+ options.startLeafStatus(ctx);
25320
+ startupStage = "metadata";
25321
+ const model = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : void 0;
25322
+ const thinking = ctx.thinkingLevel;
25323
+ options.reportMetadata(
25324
+ execution.assignment,
25325
+ ctx,
25326
+ {
25327
+ activity: null,
25328
+ context: null,
25329
+ model: model || null,
25330
+ thinking: thinking || null
25331
+ },
25332
+ true
25333
+ );
25334
+ const releaseStartup = options.claimAssignmentLock(
25335
+ mailbox,
25336
+ "session_start",
25337
+ {
25338
+ label: candidate.agentLabel,
25339
+ paneId: candidate.paneId
25340
+ }
25341
+ );
25342
+ try {
25343
+ const current = readAgentState(mailbox);
25344
+ if (!current || !options.sameIdentity(current, candidate))
25345
+ throw new Error(
25346
+ "agent session identity changed before startup outcome"
25347
+ );
25348
+ writeAgentStartupOutcome(mailbox, {
25349
+ version: 5,
24922
25350
  build: options.build,
24923
- updatedAt: Date.now()
24924
- };
24925
- writeAgentState(mailbox, execution.assignment);
24926
- } finally {
24927
- release();
24928
- }
24929
- if (options.delegationEnabled) {
24930
- startupStage = "controller_recovery";
24931
- managedAgentControllerIdentity(ctx);
24932
- await options.recoverControllerRuntimes(ctx, metadataSignal);
24933
- options.setControllerReady(true);
24934
- }
24935
- if (execution.assignment.activeRequestId)
24936
- options.touchActivity(Date.now(), forceActivityTouch);
24937
- if (options.delegationEnabled)
24938
- options.startControllerHealthScanner(ctx, metadataSignal);
24939
- execution.initialized = true;
24940
- const definition = process.env.PI_HERDSMAN_AGENT_DEFINITION;
24941
- const label = execution.assignment.agentLabel;
24942
- nameSessionIfUnset(
24943
- pi,
24944
- ctx,
24945
- definition === label ? label : `${definition} \xB7 ${label}`
24946
- );
24947
- startupStage = "request_observer";
24948
- execution.stopRequestObserver = observeMailbox(
24949
- mailbox,
24950
- (name) => /^request-.*\.json$/.test(name),
24951
- () => options.pumpRequest(ctx),
24952
- (error2) => options.appendError(ctx, error2)
24953
- );
24954
- options.pumpRequest(ctx);
24955
- if (!options.delegationEnabled && ctx.mode === "tui" && ctx.hasUI)
24956
- options.startLeafStatus(ctx);
24957
- startupStage = "metadata";
24958
- const model = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : void 0;
24959
- const thinking = ctx.thinkingLevel;
24960
- options.reportMetadata(
24961
- execution.assignment,
24962
- ctx,
24963
- {
24964
- activity: null,
24965
- context: null,
24966
- model: model || null,
24967
- thinking: thinking || null
24968
- },
24969
- true
24970
- );
24971
- const releaseStartup = options.claimAssignmentLock(
24972
- mailbox,
24973
- "session_start",
24974
- {
24975
- label: candidate.agentLabel,
24976
- paneId: candidate.paneId
25351
+ runId: candidate.runId,
25352
+ ownerSessionId: candidate.ownerSessionId,
25353
+ workspaceId: candidate.workspaceId,
25354
+ agentLabel: candidate.agentLabel,
25355
+ paneId: candidate.paneId,
25356
+ status: "ready"
25357
+ });
25358
+ } finally {
25359
+ releaseStartup();
24977
25360
  }
24978
- );
24979
- try {
24980
- const current = readAgentState(mailbox);
24981
- if (!current || !options.sameIdentity(current, candidate))
24982
- throw new Error(
24983
- "agent session identity changed before startup outcome"
24984
- );
24985
- writeAgentStartupOutcome(mailbox, {
24986
- version: 5,
24987
- build: options.build,
24988
- runId: candidate.runId,
24989
- ownerSessionId: candidate.ownerSessionId,
24990
- workspaceId: candidate.workspaceId,
24991
- agentLabel: candidate.agentLabel,
24992
- paneId: candidate.paneId,
24993
- status: "ready"
24994
- });
24995
- } finally {
24996
- releaseStartup();
25361
+ };
25362
+ const initializeBootstrap = async (value2) => {
25363
+ for (const participant of value2.participants) {
25364
+ let initializer;
25365
+ let acceptCount = 0;
25366
+ let invalidInitializer = false;
25367
+ pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
25368
+ protocol: 1,
25369
+ phase: "initialize",
25370
+ context: ctx,
25371
+ agent: candidate.agentLabel,
25372
+ participant: { id: participant.id, payload: participant.payload },
25373
+ accept(callback) {
25374
+ acceptCount++;
25375
+ if (typeof callback !== "function") invalidInitializer = true;
25376
+ else if (acceptCount === 1) initializer = callback;
25377
+ }
25378
+ });
25379
+ if (acceptCount === 0 || invalidInitializer)
25380
+ throw new Error(
25381
+ `Managed-agent bootstrap participant "${participant.id}" is unavailable or invalid`
25382
+ );
25383
+ if (acceptCount > 1)
25384
+ throw new Error(
25385
+ `Managed-agent bootstrap participant "${participant.id}" has multiple initializers`
25386
+ );
25387
+ try {
25388
+ await initializer();
25389
+ } catch (error2) {
25390
+ throw new Error(
25391
+ `Managed-agent bootstrap participant "${participant.id}" failed: ${String(error2)}`,
25392
+ { cause: error2 }
25393
+ );
25394
+ }
25395
+ }
25396
+ removeAgentBootstrap(mailbox);
25397
+ };
25398
+ if (bootstrap?.participants.length) {
25399
+ pendingStartup = async () => {
25400
+ try {
25401
+ if (bootstrap.childSessionId && ctx.sessionManager.getSessionId() !== bootstrap.childSessionId)
25402
+ throw new Error(
25403
+ "Managed-agent bootstrap child session identity changed"
25404
+ );
25405
+ if (bootstrap.childSessionId && !reservedSessionIsFresh())
25406
+ throw new Error(
25407
+ "Managed-agent bootstrap child session is not fresh"
25408
+ );
25409
+ await initializeBootstrap(bootstrap);
25410
+ await finishStartup();
25411
+ } catch (error2) {
25412
+ execution.initialized = false;
25413
+ execution.stopRequestObserver?.();
25414
+ execution.stopRequestObserver = void 0;
25415
+ options.resetRequestPump();
25416
+ options.statusRuntime.clear();
25417
+ options.setControllerReady(false);
25418
+ execution.assignment = void 0;
25419
+ if (options.delegationEnabled) options.clearControllerRuntimes();
25420
+ options.appendError(ctx, error2);
25421
+ ctx.ui.notify(`pi_herdsman_state_error: ${String(error2)}`, "error");
25422
+ try {
25423
+ const release = options.claimAssignmentLock(
25424
+ mailbox,
25425
+ "session_start",
25426
+ { label: candidate.agentLabel, paneId: candidate.paneId }
25427
+ );
25428
+ try {
25429
+ const current = readAgentState(mailbox);
25430
+ if (!current || options.sameIdentity(current, candidate))
25431
+ writeAgentStartupOutcome(mailbox, {
25432
+ version: 5,
25433
+ build: options.build,
25434
+ runId: candidate.runId,
25435
+ ownerSessionId: candidate.ownerSessionId,
25436
+ workspaceId: candidate.workspaceId,
25437
+ agentLabel: candidate.agentLabel,
25438
+ paneId: candidate.paneId,
25439
+ status: "failed",
25440
+ error: "Managed Agent initialization failed",
25441
+ stage: startupStage
25442
+ });
25443
+ } finally {
25444
+ release();
25445
+ }
25446
+ } catch (publicationError) {
25447
+ options.appendError(ctx, publicationError);
25448
+ }
25449
+ }
25450
+ };
25451
+ return;
24997
25452
  }
25453
+ await finishStartup();
24998
25454
  } catch (error2) {
24999
25455
  if (verified) {
25000
25456
  try {
@@ -25039,6 +25495,11 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
25039
25495
  ctx.ui.notify(`pi_herdsman_state_error: ${String(error2)}`, "error");
25040
25496
  }
25041
25497
  });
25498
+ pi.on("resources_discover", async () => {
25499
+ const pending = pendingStartup;
25500
+ pendingStartup = void 0;
25501
+ if (pending) await pending();
25502
+ });
25042
25503
  }
25043
25504
  var DELEGATING_AGENT_ROLE_CHARTER, AGENT_REQUIRED_EVIDENCE_ENTRY, READ_EVIDENCE_MAX_BYTES, READ_EVIDENCE_MAX_LINES, SESSION_REQUEST_ID, EVIDENCE_CONTINUATION_RESERVE, AGENT_LABEL_PATTERN2, RESERVED_PREFIX, AGENT_CONTEXT_RETIRED_ENTRY, CONTEXT_RETIREMENT_INSTRUCTION, CONTEXT_RETIREMENT_REMINDER, ATTACH_HANDOFF_TOOL;
25044
25505
  var init_managed_agent_runtime = __esm({
@@ -25082,14 +25543,36 @@ import {
25082
25543
  SessionManager as SessionManager3
25083
25544
  } from "@earendil-works/pi-coding-agent";
25084
25545
  import { readFileSync as readFileSync11, statSync as statSync9, unlinkSync as unlinkSync12 } from "node:fs";
25085
- import { basename as basename9, dirname as dirname9, resolve as resolve8 } from "node:path";
25546
+ import { basename as basename10 } from "node:path";
25547
+
25548
+ // extension/chief-prompt.ts
25549
+ import { dirname, resolve } from "node:path";
25550
+ function chiefGlobalInstructions(options, agentDir) {
25551
+ return (options?.contextFiles ?? []).filter(
25552
+ (file2) => typeof file2.path === "string" && typeof file2.content === "string" && resolve(dirname(file2.path)) === resolve(agentDir) && file2.content.length > 0
25553
+ );
25554
+ }
25555
+ function chiefSystemPrompt(options, body, roleContract, agentDir) {
25556
+ const globalInstructions = chiefGlobalInstructions(options, agentDir).map(({ content }) => content).join("\n\n");
25557
+ return [
25558
+ roleContract,
25559
+ body || void 0,
25560
+ globalInstructions ? `## global user instructions
25561
+
25562
+ <global_instructions>
25563
+ ${globalInstructions}
25564
+ </global_instructions>` : void 0
25565
+ ].filter((section) => section !== void 0).join("\n\n");
25566
+ }
25567
+
25568
+ // extension/index.ts
25086
25569
  import { setTimeout as delay2 } from "node:timers/promises";
25087
25570
  import { fileURLToPath as fileURLToPath3 } from "node:url";
25088
25571
 
25089
25572
  // package.json
25090
25573
  var package_default = {
25091
25574
  name: "pi-herdsman",
25092
- version: "0.45.0",
25575
+ version: "0.46.0",
25093
25576
  type: "module",
25094
25577
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
25095
25578
  license: "Apache-2.0",
@@ -25151,6 +25634,8 @@ var package_default = {
25151
25634
  }
25152
25635
  },
25153
25636
  scripts: {
25637
+ setup: "npm run setup:hooks && npm ci",
25638
+ "setup:hooks": "node scripts/setup-hooks.mjs",
25154
25639
  test: "node --experimental-test-module-mocks --import=./scripts/test-env.mjs --test --test-timeout=10000",
25155
25640
  smoke: "node scripts/smoke.mjs",
25156
25641
  format: "prettier . --write",
@@ -25168,20 +25653,18 @@ var package_default = {
25168
25653
  "@earendil-works/pi-ai": "*",
25169
25654
  "@earendil-works/pi-coding-agent": "*",
25170
25655
  "@earendil-works/pi-tui": "*",
25171
- "@howaboua/pi-codex-conversion": "^3.0.45 || ^4.0.0",
25172
25656
  typebox: "*"
25173
25657
  },
25174
25658
  devDependencies: {
25175
25659
  "@earendil-works/pi-ai": "1.5.2",
25176
25660
  "@earendil-works/pi-coding-agent": "1.5.2",
25177
25661
  "@earendil-works/pi-tui": "1.5.2",
25178
- "@howaboua/pi-codex-conversion": "4.0.4",
25179
- "@modelcontextprotocol/sdk": "1.32.0",
25180
- "@types/node": "22.19.19",
25662
+ "@modelcontextprotocol/sdk": "1.32.2",
25663
+ "@types/node": "22.20.5",
25181
25664
  "@types/proper-lockfile": "4.1.4",
25182
25665
  esbuild: "^0.28.2",
25183
- oxlint: "1.90.0",
25184
- prettier: "3.9.10",
25666
+ oxlint: "1.93.0",
25667
+ prettier: "3.10.1",
25185
25668
  typebox: "^1.3.7",
25186
25669
  typescript: "7.0.2"
25187
25670
  },
@@ -25203,11 +25686,6 @@ var package_default = {
25203
25686
  publishConfig: {
25204
25687
  registry: "https://registry.npmjs.org/"
25205
25688
  },
25206
- peerDependenciesMeta: {
25207
- "@howaboua/pi-codex-conversion": {
25208
- optional: true
25209
- }
25210
- },
25211
25689
  dependencies: {
25212
25690
  "proper-lockfile": "4.1.2"
25213
25691
  }
@@ -25371,7 +25849,7 @@ init_agent_controller();
25371
25849
  init_agent_definitions();
25372
25850
  import { randomUUID as randomUUID12 } from "node:crypto";
25373
25851
  import { realpathSync as realpathSync6, statSync as statSync7, unlinkSync as unlinkSync9 } from "node:fs";
25374
- import { isAbsolute as isAbsolute6, resolve as resolve6 } from "node:path";
25852
+ import { isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
25375
25853
  function isFreshLeadStartupAttestation(state, sessionId, previousInstanceId, startedAt) {
25376
25854
  return !!state && state.piSessionId === sessionId && state.instanceId !== previousInstanceId && state.updatedAt >= startedAt && state.startupAttestation?.kind === "model_restore" && state.startupAttestation.assignmentId === sessionId && state.startupAttestation.generation === state.instanceId && ["verified", "definition_override", "no_saved_model"].includes(
25377
25855
  state.startupAttestation.result
@@ -25731,7 +26209,7 @@ function createLeadProjectRuntime(host) {
25731
26209
  const worktree = placement.worktree;
25732
26210
  if (typeof worktree.path !== "string" || !worktree.path || !isAbsolute6(worktree.path) || worktree.is_linked_worktree !== true)
25733
26211
  throw new Error("Herdr worktree checkout path is unavailable");
25734
- const checkoutPath = resolve6(worktree.path);
26212
+ const checkoutPath = resolve7(worktree.path);
25735
26213
  if (sameDirectory(checkoutPath, topology.source.source_checkout_path))
25736
26214
  throw new Error("The Manager's primary checkout cannot be removed");
25737
26215
  if (worktree.open_workspace_id === manager.workspaceId)
@@ -26931,12 +27409,12 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26931
27409
  try {
26932
27410
  const session = host.SessionManager.open(assignment.piSessionFile);
26933
27411
  if (session.getSessionId() !== assignment.id) throw new Error();
26934
- sourcePath = resolve6(session.getCwd());
27412
+ sourcePath = resolve7(session.getCwd());
26935
27413
  } catch {
26936
27414
  throw sourceError;
26937
27415
  }
26938
27416
  if (gitPathStatus(sourcePath) !== "absent" || topology.worktrees.some(
26939
- (worktree) => worktree?.branch === branch || typeof worktree?.path === "string" && resolve6(worktree.path) === sourcePath
27417
+ (worktree) => worktree?.branch === branch || typeof worktree?.path === "string" && resolve7(worktree.path) === sourcePath
26940
27418
  ))
26941
27419
  throw sourceError;
26942
27420
  const inventory = await host.pi.exec(
@@ -26948,7 +27426,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26948
27426
  String(inventory.stdout ?? "")
26949
27427
  );
26950
27428
  if (inventory.code !== 0 || inventory.killed || !parsedInventory || parsedInventory.some(
26951
- (worktree) => worktree.branch === branch || resolve6(worktree.path) === sourcePath
27429
+ (worktree) => worktree.branch === branch || resolve7(worktree.path) === sourcePath
26952
27430
  ))
26953
27431
  throw sourceError;
26954
27432
  const finalManager = await host.currentManager(ctx);
@@ -27070,7 +27548,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27070
27548
  if (probe.code !== 0 || probe.killed || probe.stderr?.trim())
27071
27549
  throw new Error("Git operation state is unverifiable");
27072
27550
  try {
27073
- statSync7(resolve6(path, String(probe.stdout ?? "").trim()));
27551
+ statSync7(resolve7(path, String(probe.stdout ?? "").trim()));
27074
27552
  throw new Error(`Git operation ${state} is in progress`);
27075
27553
  } catch (error2) {
27076
27554
  if (error2.code !== "ENOENT" && !(error2 instanceof Error && error2.message.startsWith("Git operation ")))
@@ -27521,7 +27999,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
27521
27999
  }
27522
28000
  try {
27523
28001
  statSync7(
27524
- resolve6(targetPath, String(path.stdout ?? "").trim())
28002
+ resolve7(targetPath, String(path.stdout ?? "").trim())
27525
28003
  );
27526
28004
  operationStates.push(state);
27527
28005
  } catch (error2) {
@@ -29661,6 +30139,7 @@ init_config();
29661
30139
  init_agent_definitions();
29662
30140
  init_core();
29663
30141
  init_presentation();
30142
+ import { basename as basename9 } from "node:path";
29664
30143
  import {
29665
30144
  getSupportedThinkingLevels
29666
30145
  } from "@earendil-works/pi-ai";
@@ -30001,15 +30480,219 @@ function createLeadCommandRuntime(host) {
30001
30480
  definition = current;
30002
30481
  const metadata = host.agentDefinitionMetadata(current);
30003
30482
  if (ctx.mode === "tui") {
30004
- const instructions = host.expandAgentBodyFiles(
30005
- current.body,
30006
- [],
30007
- "definition details"
30008
- );
30009
- host.appendDefinitionsEntry({
30010
- definitions: [metadata],
30011
- instructions
30012
- });
30483
+ try {
30484
+ const promptOptions = isReservedRoleDefinition(current.name) ? host.getSystemPromptOptions(ctx) : void 0;
30485
+ const inspection = isReservedRoleDefinition(current.name) ? host.inspectRoleDefinition(
30486
+ current.name,
30487
+ ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
30488
+ ) : host.inspectAgentDefinition(
30489
+ current.name,
30490
+ ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
30491
+ );
30492
+ const expandedFragments = host.expandDefinitionBodyFragmentsWithSources?.(
30493
+ inspection.bodyFragments,
30494
+ [],
30495
+ "definition details"
30496
+ ) ?? host.expandDefinitionBodyFragments(
30497
+ inspection.bodyFragments,
30498
+ [],
30499
+ "definition details"
30500
+ ).map((text) => [{ text }]);
30501
+ const fragments = expandedFragments.map(
30502
+ (parts) => parts.map(({ text }) => text).join("")
30503
+ );
30504
+ const sources = inspection.layers.map(({ scope }) => scope);
30505
+ const roleProfile = isReservedRoleDefinition(current.name);
30506
+ const execution = host.leadExecutionPresentation();
30507
+ const managedLeadProfile = current.name === "managed-lead";
30508
+ let activeRole = current.name === "manager" && host.roleActive("manager") || current.name === "chief" && host.isCurrentChief(ctx) || managedLeadProfile && execution.managed || current.name === "flexible-lead" && !execution.managed && execution.mode === "flexible" && !host.roleActive("manager") && !host.roleActive("chief") || current.name === "orchestrator-lead" && !execution.managed && execution.mode === "orchestrate" && !host.roleActive("manager") && !host.roleActive("chief");
30509
+ const activeChief = current.name === "chief" && activeRole;
30510
+ const currentRoleCharter = activeRole && current.name !== "chief" ? host.roleCharter(ctx) : void 0;
30511
+ if (currentRoleCharter?.includes(
30512
+ "No active Herdsman role is verified for this Pi session."
30513
+ ))
30514
+ activeRole = false;
30515
+ const activeExecutionDefinition = activeRole ? host.leadExecutionDefinition() : void 0;
30516
+ const inheritance = !roleProfile || managedLeadProfile ? contextInheritance(current) : void 0;
30517
+ const roleContextFiles = activeRole && current.name !== "chief" ? (promptOptions?.contextFiles ?? []).map((file2) => ({
30518
+ path: file2.path,
30519
+ text: file2.content
30520
+ })) : [];
30521
+ const chiefContextFiles = current.name === "chief" ? host.chiefGlobalInstructions(promptOptions).map((file2) => ({
30522
+ path: file2.path,
30523
+ text: file2.content
30524
+ })) : [];
30525
+ const futureContextFiles = inheritance && (!roleProfile || !activeRole) ? host.selectedAgentContextFiles(current, ctx.cwd).map((file2) => ({
30526
+ path: file2.path,
30527
+ text: file2.content
30528
+ })) : [];
30529
+ const contextFiles = current.name === "chief" ? chiefContextFiles : roleProfile ? activeRole ? roleContextFiles : futureContextFiles : futureContextFiles;
30530
+ const contextCount = inheritance ? String(contextFiles.length) : current.name === "chief" ? String(chiefContextFiles.length) : activeRole ? String(roleContextFiles.length) : "session-dependent";
30531
+ const contextMode = current.name === "chief" ? "Chief forced prompt includes only global user instructions; project context excluded" : inheritance ? inheritance.global && inheritance.project ? "Pi context inherited globally and from the project" : inheritance.global ? "Selected global Pi context" : inheritance.project ? "Selected project Pi context" : "Pi context files disabled" : activeRole ? "Current Pi context from getSystemPromptOptions()" : "Coordinator profile context depends on its future session";
30532
+ const rolePreview = activeRole ? "active-session inputs" : managedLeadProfile ? "future Managed Lead launch" : "prospective Coordinator profile";
30533
+ const sections = [];
30534
+ const add = (title, content, source, format = "text", changes) => sections.push({ title, content, source, format, changes });
30535
+ const addContexts = () => {
30536
+ for (const file2 of contextFiles)
30537
+ add("Pi context", file2.text, file2.path, "markdown");
30538
+ };
30539
+ const appendDefinition = (title) => {
30540
+ const provenance = inspection.layers.flatMap((layer) => [
30541
+ `${layer.scope} \xB7 ${basename9(layer.path)}`,
30542
+ ...summarizeDefinitionLayerChanges(layer).map(
30543
+ (change) => ` ${change}`
30544
+ )
30545
+ ]);
30546
+ const fragments2 = inspection.bodyFragments;
30547
+ let provenanceAttached = false;
30548
+ fragments2.forEach((fragment, index) => {
30549
+ for (const part of expandedFragments[index] ?? []) {
30550
+ if (!part.text.length) continue;
30551
+ add(
30552
+ title,
30553
+ part.text,
30554
+ part.filePath ?? fragment.path,
30555
+ "markdown",
30556
+ provenanceAttached ? void 0 : provenance
30557
+ );
30558
+ provenanceAttached = true;
30559
+ }
30560
+ });
30561
+ if (!provenanceAttached)
30562
+ add(
30563
+ title,
30564
+ void 0,
30565
+ void 0,
30566
+ "text",
30567
+ provenance.length ? provenance : void 0
30568
+ );
30569
+ };
30570
+ const promptMode = current.frontmatter.systemPromptMode ?? "append";
30571
+ const chiefBody = activeChief ? host.supervisoryProfileBody(ctx, "chief") : fragments.join("\n\n");
30572
+ const chiefPrompt = current.name === "chief" ? host.chiefSystemPrompt(promptOptions, chiefBody) : void 0;
30573
+ if (!roleProfile) {
30574
+ add(
30575
+ promptMode === "replace" ? "Replacement prompt" : "Pi base instructions",
30576
+ promptMode === "replace" ? "Pi base prefix replaced." : "Native Pi defaults and tool guidance are not reconstructed."
30577
+ );
30578
+ appendDefinition(
30579
+ promptMode === "replace" ? "Replacement body \xB7 Herdsman definition" : "Herdsman definition"
30580
+ );
30581
+ const addGuidance = () => add("Herdsman shared guidance", "Managed launch input.");
30582
+ if (inheritance?.global && inheritance.project) {
30583
+ addGuidance();
30584
+ addContexts();
30585
+ } else {
30586
+ addContexts();
30587
+ addGuidance();
30588
+ }
30589
+ add(
30590
+ "Pi skills/extensions",
30591
+ "Configured selections; load status unknown."
30592
+ );
30593
+ add("Working directory", ctx.cwd);
30594
+ add("Runtime contributions", "Session-dependent.");
30595
+ } else if (current.name === "chief") {
30596
+ add(
30597
+ activeChief ? "Active Chief forced prompt" : "Prospective Chief forced prompt",
30598
+ chiefPrompt ?? "",
30599
+ void 0,
30600
+ "text"
30601
+ );
30602
+ appendDefinition(
30603
+ "Effective Chief profile on disk \xB7 may differ from active snapshot"
30604
+ );
30605
+ add(
30606
+ "Chief context",
30607
+ `Global user instruction files included: ${chiefContextFiles.length}; project context excluded.`
30608
+ );
30609
+ } else if (managedLeadProfile) {
30610
+ if (activeRole) {
30611
+ if (activeExecutionDefinition?.name === "managed-lead")
30612
+ add(
30613
+ "Managed Lead body",
30614
+ host.expandAgentBodyFiles(
30615
+ activeExecutionDefinition.body,
30616
+ [],
30617
+ "definition details"
30618
+ ),
30619
+ void 0,
30620
+ "text"
30621
+ );
30622
+ add("Herdsman shared guidance", "Managed launch input.");
30623
+ addContexts();
30624
+ add(
30625
+ "Runtime role contract",
30626
+ currentRoleCharter ?? "",
30627
+ void 0,
30628
+ "text"
30629
+ );
30630
+ } else {
30631
+ appendDefinition(
30632
+ "Managed Lead definition \xB7 future launch"
30633
+ );
30634
+ add(
30635
+ "Herdsman shared guidance",
30636
+ "Managed Lead launch input."
30637
+ );
30638
+ addContexts();
30639
+ }
30640
+ add("Working directory", ctx.cwd);
30641
+ add("Runtime contributions", "Managed session-dependent.");
30642
+ } else if (activeRole) {
30643
+ add("Pi base prompt", "Native and not reconstructed.");
30644
+ addContexts();
30645
+ add("Working directory", ctx.cwd);
30646
+ add(
30647
+ "Herdsman role contract/profile",
30648
+ currentRoleCharter ?? "",
30649
+ void 0,
30650
+ "text"
30651
+ );
30652
+ if (current.name === "flexible-lead" || current.name === "orchestrator-lead") {
30653
+ const activeBody = host.executionPrompt();
30654
+ if (activeBody)
30655
+ add(
30656
+ "Lead execution profile",
30657
+ activeBody,
30658
+ void 0,
30659
+ "text"
30660
+ );
30661
+ appendDefinition(
30662
+ "Effective Lead profile on disk \xB7 active prompt is a session snapshot"
30663
+ );
30664
+ } else if (current.name === "manager")
30665
+ appendDefinition(
30666
+ "Effective Manager profile on disk \xB7 active prompt is a session snapshot"
30667
+ );
30668
+ add("Runtime contributions", "Session-dependent.");
30669
+ } else {
30670
+ appendDefinition(
30671
+ "Prospective Coordinator profile contribution"
30672
+ );
30673
+ add("Runtime sections", "Depend on active role/session.");
30674
+ add("Exact future prompt", "Unavailable until launch.");
30675
+ }
30676
+ if (roleProfile && !activeRole && !managedLeadProfile && current.name !== "chief")
30677
+ add("Working directory", ctx.cwd);
30678
+ host.appendDefinitionsEntry({
30679
+ definitions: [metadata],
30680
+ inspector: {
30681
+ summary: [
30682
+ `${roleProfile ? rolePreview : "Future Agent launch"} \xB7 ${sources.length} source(s) \xB7 ${contextCount} Pi context files`,
30683
+ `Context: ${ctx.cwd} \xB7 ${contextMode}`,
30684
+ "Known-input preview only; provider/runtime transformations may add inputs."
30685
+ ],
30686
+ sections
30687
+ }
30688
+ });
30689
+ return;
30690
+ } catch (error2) {
30691
+ ctx.ui.notify(
30692
+ `Could not inspect ${current.name}: ${String(error2).replace(/^Error: /u, "")}`,
30693
+ "error"
30694
+ );
30695
+ }
30013
30696
  } else {
30014
30697
  ctx.ui.notify(
30015
30698
  host.formatAgentDefinitions([metadata]).join("\n")
@@ -30937,10 +31620,10 @@ init_storage();
30937
31620
  import { createHash as createHash14, randomUUID as randomUUID16 } from "node:crypto";
30938
31621
  import { lstatSync as lstatSync7, realpathSync as realpathSync7, statSync as statSync8 } from "node:fs";
30939
31622
  import {
30940
- dirname as dirname8,
31623
+ dirname as dirname9,
30941
31624
  isAbsolute as isAbsolute7,
30942
31625
  join as join13,
30943
- resolve as resolve7,
31626
+ resolve as resolve8,
30944
31627
  toNamespacedPath
30945
31628
  } from "node:path";
30946
31629
 
@@ -31637,7 +32320,7 @@ function createLeadCoordinationRuntime(host) {
31637
32320
  contentText: contentText6,
31638
32321
  supervisorStateType,
31639
32322
  workspacePresentationProvenance: workspacePresentationProvenance2,
31640
- basename: basename10,
32323
+ basename: basename11,
31641
32324
  readPeerLeadRecord: readPeerLeadRecord2,
31642
32325
  samePeerLeadRecord: samePeerLeadRecord2,
31643
32326
  writePeerLeadRecord: writePeerLeadRecord2,
@@ -31875,7 +32558,7 @@ function createLeadCoordinationRuntime(host) {
31875
32558
  return;
31876
32559
  }
31877
32560
  if (!isCurrent() || peerPresenceRecord !== verified) return;
31878
- const workspaceLabel = provenance.repoName && provenance.branch ? `${provenance.repoName}/${provenance.branch}` : provenance.workspaceLabel ?? (provenance.workspaceCwd ? basename10(provenance.workspaceCwd) : workspaceId2);
32561
+ const workspaceLabel = provenance.repoName && provenance.branch ? `${provenance.repoName}/${provenance.branch}` : provenance.workspaceLabel ?? (provenance.workspaceCwd ? basename11(provenance.workspaceCwd) : workspaceId2);
31879
32562
  const enriched = {
31880
32563
  ...verified,
31881
32564
  ...provenance.repoName ? { repo: provenance.repoName } : {},
@@ -33636,11 +34319,21 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
33636
34319
  const projectRoleTools = (baseline, definition, requiredTools) => {
33637
34320
  const policy = configuredToolPolicy(definition, requiredTools);
33638
34321
  const required = new Set(requiredTools);
33639
- const selected = policy.explicit ? policy.tools.flatMap(
34322
+ const selected = policy.mode === "explicit" ? policy.tools.flatMap(
33640
34323
  (pattern) => [...registeredToolNames()].filter(
33641
34324
  (name) => matchesToolPattern(pattern, name)
33642
34325
  )
33643
- ) : [...baseline];
34326
+ ) : policy.mode === "relative" ? (() => {
34327
+ const result = [...baseline];
34328
+ for (const operation of definition.frontmatter.tools ?? []) {
34329
+ const name = operation.slice(1);
34330
+ const index = result.indexOf(name);
34331
+ if (operation.startsWith("+") && index < 0) result.push(name);
34332
+ if (operation.startsWith("-") && index >= 0)
34333
+ result.splice(index, 1);
34334
+ }
34335
+ return result;
34336
+ })() : [...baseline];
33644
34337
  return appendRegisteredTools(
33645
34338
  normalizeBaseTools(
33646
34339
  selected.filter((name) => toolPolicyAllowsName(policy, required, name))
@@ -33709,7 +34402,7 @@ async function readGitWorktreeState(git, cwd) {
33709
34402
  }
33710
34403
  async function observeGitChangeSummary(git, checkoutPath, repoKey, comparisonHead) {
33711
34404
  const root2 = (await git(checkoutPath, ["rev-parse", "--show-toplevel"])).trim();
33712
- const common = resolve7(
34405
+ const common = resolve8(
33713
34406
  checkoutPath,
33714
34407
  (await git(checkoutPath, ["rev-parse", "--git-common-dir"])).trim()
33715
34408
  );
@@ -34136,7 +34829,7 @@ function createLeadAgentEventRuntime(host) {
34136
34829
  return;
34137
34830
  }
34138
34831
  try {
34139
- if (host.currentLeadAllowedTools?.() !== void 0)
34832
+ if (host.currentLeadAllowedTools?.() !== void 0 || host.currentLeadRelativePolicy?.() !== void 0)
34140
34833
  host.reconcileRoleTools?.();
34141
34834
  } catch (error2) {
34142
34835
  host.setActiveTools([]);
@@ -34193,6 +34886,22 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
34193
34886
  }
34194
34887
  if (!host.isActiveManager()) {
34195
34888
  try {
34889
+ const relative3 = host.currentLeadRelativePolicy?.();
34890
+ if (relative3) {
34891
+ if (relative3.excluded.some(
34892
+ (pattern) => matchesToolPattern(pattern, event.toolName)
34893
+ ))
34894
+ return {
34895
+ block: true,
34896
+ reason: "Tool is excluded by the active Lead profile."
34897
+ };
34898
+ if (relative3.owned.has(event.toolName) && !relative3.allowedOwned.has(event.toolName))
34899
+ return {
34900
+ block: true,
34901
+ reason: "Tool is unavailable in the active Lead profile."
34902
+ };
34903
+ return void 0;
34904
+ }
34196
34905
  const allowed = host.currentLeadAllowedTools?.();
34197
34906
  if (!allowed || allowed.includes(event.toolName)) return void 0;
34198
34907
  } catch {
@@ -34442,6 +35151,15 @@ function registerLeadRuntime(pi, options) {
34442
35151
  leadTools: [...tools]
34443
35152
  });
34444
35153
  };
35154
+ const inheritedProjectionFor = (mode, definition, baseline, projected) => {
35155
+ const policy = configuredToolPolicy(definition, []);
35156
+ if (policy.mode === "explicit") return void 0;
35157
+ return {
35158
+ mode,
35159
+ excluded: policy.excluded,
35160
+ injected: leadToolState.normalizeBaseTools(projected).filter((name) => !baseline.includes(name))
35161
+ };
35162
+ };
34445
35163
  const captureInheritedTools = () => {
34446
35164
  const projection = inheritedProjection;
34447
35165
  if (!projection) return;
@@ -34451,7 +35169,7 @@ function registerLeadRuntime(pi, options) {
34451
35169
  }
34452
35170
  const saved = leadToolState.getLeadTools() ?? [];
34453
35171
  const excluded = (name) => projection.excluded.some((pattern) => matchesToolPattern(pattern, name));
34454
- const active = leadToolState.normalizeBaseTools(pi.getActiveTools()).filter((name) => !excluded(name));
35172
+ const active = leadToolState.normalizeBaseTools(pi.getActiveTools()).filter((name) => !excluded(name) && !projection.injected.includes(name));
34455
35173
  const next = leadToolState.normalizeBaseTools([
34456
35174
  ...active,
34457
35175
  ...saved.filter(excluded)
@@ -34837,7 +35555,7 @@ function registerLeadRuntime(pi, options) {
34837
35555
  if (managedLifecycle !== "assigned" || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || leadExecutionPending || !leadExecution?.valid || !leadExecution.managed)
34838
35556
  return managedRecoveryTools();
34839
35557
  const definition = leadExecution.definition;
34840
- const managedBaseline = definition.frontmatter.noTools === true && definition.frontmatter.tools === void 0 ? [] : baseline;
35558
+ const managedBaseline = definition.frontmatter.noTools === true ? [] : baseline;
34841
35559
  return restrict(
34842
35560
  leadToolState.appendRegisteredTools(
34843
35561
  leadToolState.projectLeadTools(managedBaseline, definition),
@@ -34879,10 +35597,12 @@ function registerLeadRuntime(pi, options) {
34879
35597
  setCoordinationHealthy: (healthy) => coordinationRuntime.setCoordinationHealthy(healthy),
34880
35598
  normalizeBaseTools: leadToolState.normalizeBaseTools,
34881
35599
  captureInheritedTools,
34882
- inheritedProjection: () => sessionKind?.kind === "ordinary" && !leadExecutionPending && leadExecution?.valid && !leadExecution.managed && leadExecution.definition.frontmatter.tools === void 0 ? {
34883
- mode: leadExecution.mode,
34884
- excluded: configuredToolPolicy(leadExecution.definition, []).excluded
34885
- } : void 0,
35600
+ inheritedProjection: () => sessionKind?.kind === "ordinary" && !leadExecutionPending && leadExecution?.valid && !leadExecution.managed ? inheritedProjectionFor(
35601
+ leadExecution.mode,
35602
+ leadExecution.definition,
35603
+ leadToolState.getLeadTools() ?? [],
35604
+ executionTools()
35605
+ ) : void 0,
34886
35606
  setInheritedProjection: (projection) => {
34887
35607
  inheritedProjection = projection;
34888
35608
  },
@@ -36003,19 +36723,18 @@ function registerLeadRuntime(pi, options) {
36003
36723
  persistLeadExecution(mode, baseline);
36004
36724
  leadToolState.setLeadTools(baseline);
36005
36725
  leadExecution = { mode, definition, valid: true, managed: false };
36006
- inheritedProjection = shouldActivate && definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), targetTools) ? {
36007
- mode,
36008
- excluded: configuredToolPolicy(definition, []).excluded
36009
- } : void 0;
36726
+ inheritedProjection = shouldActivate && sameToolSelection(pi.getActiveTools(), targetTools) ? inheritedProjectionFor(mode, definition, baseline, targetTools) : void 0;
36010
36727
  statusRuntime.requestRefresh();
36011
36728
  } catch (error2) {
36012
36729
  leadExecution = previousExecution;
36013
36730
  try {
36014
36731
  if (shouldActivate) pi.setActiveTools(previousTools);
36015
- inheritedProjection = shouldActivate && previousExecution?.valid && !previousExecution.managed && previousExecution.definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), previousTools) ? {
36016
- mode: previousExecution.mode,
36017
- excluded: configuredToolPolicy(previousExecution.definition, []).excluded
36018
- } : void 0;
36732
+ inheritedProjection = shouldActivate && previousExecution?.valid && !previousExecution.managed && sameToolSelection(pi.getActiveTools(), previousTools) ? inheritedProjectionFor(
36733
+ previousExecution.mode,
36734
+ previousExecution.definition,
36735
+ leadToolState.getLeadTools() ?? [],
36736
+ previousTools
36737
+ ) : void 0;
36019
36738
  } catch {
36020
36739
  inheritedProjection = void 0;
36021
36740
  leadExecution = { mode, valid: false, managed: false };
@@ -36061,18 +36780,30 @@ function registerLeadRuntime(pi, options) {
36061
36780
  };
36062
36781
  const agentEvents = createLeadAgentEventRuntime({
36063
36782
  ...options.agentEventOptions,
36783
+ currentLeadRelativePolicy: () => {
36784
+ if (!leadExecution?.valid || configuredToolPolicy(leadExecution.definition, []).mode !== "relative" || sessionKind?.kind === "managed" && (managedLifecycle !== "assigned" || leadExecutionPending || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || !leadExecution.managed))
36785
+ return void 0;
36786
+ const required = executionTools();
36787
+ return {
36788
+ excluded: configuredToolPolicy(leadExecution.definition, []).excluded,
36789
+ owned: leadToolState.ownedTools,
36790
+ allowedOwned: new Set(
36791
+ required.filter((name) => leadToolState.ownedTools.has(name))
36792
+ )
36793
+ };
36794
+ },
36064
36795
  currentLeadAllowedTools: () => {
36065
36796
  if (sessionKind?.kind === "managed") {
36066
36797
  if (managedLifecycle !== "assigned" || leadExecutionPending || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || !leadExecution?.valid || !leadExecution.managed)
36067
36798
  return executionTools();
36068
36799
  const policy2 = leadExecution.definition.frontmatter;
36069
- return policy2.tools !== void 0 || (policy2.excludeTools?.length ?? 0) > 0 || policy2.noTools === true ? executionTools() : void 0;
36800
+ return configuredToolPolicy(leadExecution.definition, []).mode === "explicit" || (policy2.excludeTools?.length ?? 0) > 0 || policy2.noTools === true ? executionTools() : void 0;
36070
36801
  }
36071
36802
  if (activeLeadRole(leadRuntime) !== "lead" || leadRuntime.roleSuspended || !leadExecution || leadExecution.managed)
36072
36803
  return void 0;
36073
36804
  if (!leadExecution.valid) return executionTools();
36074
36805
  const policy = leadExecution.definition.frontmatter;
36075
- return policy.tools !== void 0 || (policy.excludeTools?.length ?? 0) > 0 ? executionTools() : void 0;
36806
+ return configuredToolPolicy(leadExecution.definition, []).mode === "explicit" || (policy.excludeTools?.length ?? 0) > 0 ? executionTools() : void 0;
36076
36807
  },
36077
36808
  executionPrompt: () => leadExecution && !leadExecution.managed && leadExecution.valid ? leadExecution.definition.body : void 0,
36078
36809
  leadInboxRuntime: inboxRuntime,
@@ -36277,6 +37008,8 @@ This session belongs to a managed Agent restored without its authorized launch c
36277
37008
  liveLead,
36278
37009
  setLeadExecutionMode,
36279
37010
  sessionKindForPrompt: (ctx) => sessionKind?.sessionId === ctx.sessionManager.getSessionId() ? sessionKind.kind : void 0,
37011
+ executionPrompt: () => leadExecution && !leadExecution.managed && leadExecution.valid ? leadExecution.definition.body : void 0,
37012
+ leadExecutionDefinition: () => leadExecution?.valid ? leadExecution.definition : void 0,
36280
37013
  leadExecutionPresentation: () => sessionKind?.kind === "managed" ? {
36281
37014
  managed: true,
36282
37015
  mode: leadExecution?.mode ?? "orchestrate",
@@ -37012,7 +37745,7 @@ function createLeadSupervisionRuntime(host) {
37012
37745
  const identity = async (cwd, expectedCommon) => {
37013
37746
  const root2 = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
37014
37747
  const commonValue = (await git(cwd, ["rev-parse", "--git-common-dir"])).trim();
37015
- const common = resolve7(cwd, commonValue);
37748
+ const common = resolve8(cwd, commonValue);
37016
37749
  return sameDirectory(root2, cwd) && sameDirectory(common, expectedCommon);
37017
37750
  };
37018
37751
  try {
@@ -38640,7 +39373,7 @@ function createLeadInboxRuntime(host) {
38640
39373
  drainCoordinationInbox: drainCoordinationInbox2,
38641
39374
  currentPeerPresenceValid,
38642
39375
  drainProjectMessages,
38643
- basename: basename10,
39376
+ basename: basename11,
38644
39377
  managerDiagnosticEvents
38645
39378
  } = host;
38646
39379
  const chiefStartPreflightHeld = (ctx) => {
@@ -39385,7 +40118,7 @@ function createLeadInboxRuntime(host) {
39385
40118
  (path) => !chiefMessageQuarantined2(
39386
40119
  runtime,
39387
40120
  sessionId,
39388
- basename10(path, ".json")
40121
+ basename11(path, ".json")
39389
40122
  )
39390
40123
  )) {
39391
40124
  const message = await prepareSupervisionMessage(ctx);
@@ -40177,13 +40910,13 @@ function createLeadRoleTransitions(state, host) {
40177
40910
  try {
40178
40911
  const session = host.SessionManager.open(assignment.piSessionFile);
40179
40912
  if (session.getSessionId() !== assignment.id) return void 0;
40180
- return resolve7(session.getCwd());
40913
+ return resolve8(session.getCwd());
40181
40914
  } catch {
40182
40915
  return void 0;
40183
40916
  }
40184
40917
  };
40185
40918
  const checkoutProvenance = (assignment) => {
40186
- const recorded = assignment.checkoutPath ? resolve7(assignment.checkoutPath) : void 0;
40919
+ const recorded = assignment.checkoutPath ? resolve8(assignment.checkoutPath) : void 0;
40187
40920
  const session = knownSessionCheckoutPath(assignment);
40188
40921
  return {
40189
40922
  path: recorded ?? session,
@@ -40193,10 +40926,10 @@ function createLeadRoleTransitions(state, host) {
40193
40926
  const checkoutMaySurvive = (assignment, inventory, checkoutPath = checkoutProvenance(assignment).path) => {
40194
40927
  if (checkoutPath)
40195
40928
  return gitPathStatus(checkoutPath) !== "absent" || inventory.some(
40196
- (worktree) => resolve7(worktree.path) === checkoutPath && (worktree.locked || !worktree.prunable || gitPathStatus(worktree.path) !== "absent")
40929
+ (worktree) => resolve8(worktree.path) === checkoutPath && (worktree.locked || !worktree.prunable || gitPathStatus(worktree.path) !== "absent")
40197
40930
  );
40198
40931
  return inventory.some(
40199
- (worktree) => resolve7(worktree.path) !== resolve7(sourceCheckoutPath) && gitPathStatus(worktree.path) !== "absent"
40932
+ (worktree) => resolve8(worktree.path) !== resolve8(sourceCheckoutPath) && gitPathStatus(worktree.path) !== "absent"
40200
40933
  );
40201
40934
  };
40202
40935
  for (const observed of assignments) {
@@ -40637,7 +41370,7 @@ function createLeadRoleTransitions(state, host) {
40637
41370
  throw new Error(
40638
41371
  "/manager requires interactive confirmation to initialize Git"
40639
41372
  );
40640
- const target = realpathSync7(resolve7(ctx.cwd));
41373
+ const target = realpathSync7(resolve8(ctx.cwd));
40641
41374
  const targetStat = statSync8(target, { bigint: true });
40642
41375
  if (!targetStat.isDirectory() || targetStat.dev === 0n || targetStat.ino === 0n)
40643
41376
  throw new Error("Manager Git target is not a directory");
@@ -40674,7 +41407,7 @@ function createLeadRoleTransitions(state, host) {
40674
41407
  ))
40675
41408
  throw new Error("Manager activation cancelled.");
40676
41409
  await verifyHerdrTarget();
40677
- if (ctx.sessionManager.getSessionId() !== sessionId || host.identity.workspaceId !== workspaceId || host.identity.paneId !== paneId || host.identity.tabId !== tabId || !sameDirectory(resolve7(ctx.cwd), target) || (() => {
41410
+ if (ctx.sessionManager.getSessionId() !== sessionId || host.identity.workspaceId !== workspaceId || host.identity.paneId !== paneId || host.identity.tabId !== tabId || !sameDirectory(resolve8(ctx.cwd), target) || (() => {
40678
41411
  const current = statSync8(target, { bigint: true });
40679
41412
  return current.dev !== targetStat.dev || current.ino !== targetStat.ino;
40680
41413
  })())
@@ -40717,13 +41450,13 @@ function createLeadRoleTransitions(state, host) {
40717
41450
  let directory2 = target;
40718
41451
  while (true) {
40719
41452
  try {
40720
- lstatSync7(resolve7(directory2, ".git"));
41453
+ lstatSync7(resolve8(directory2, ".git"));
40721
41454
  return true;
40722
41455
  } catch (error3) {
40723
41456
  if (error3.code !== "ENOENT")
40724
41457
  throw error3;
40725
41458
  }
40726
- const parent = dirname8(directory2);
41459
+ const parent = dirname9(directory2);
40727
41460
  if (parent === directory2) return false;
40728
41461
  directory2 = parent;
40729
41462
  }
@@ -41669,12 +42402,23 @@ function registerExtensionImpl(pi, lockHooks) {
41669
42402
  ))
41670
42403
  return void 0;
41671
42404
  const instructions = data && typeof data === "object" && "instructions" in data && typeof data.instructions === "string" ? data.instructions : void 0;
42405
+ const storedInspector = data && typeof data === "object" && "inspector" in data ? data.inspector : void 0;
42406
+ const validSections = (sections) => Array.isArray(sections) && sections.every(
42407
+ (section) => section !== null && typeof section === "object" && !Array.isArray(section) && "title" in section && typeof section.title === "string" && (!("source" in section) || section.source === void 0 || typeof section.source === "string") && (!("content" in section) || section.content === void 0 || typeof section.content === "string") && (!("format" in section) || section.format === void 0 || section.format === "markdown" || section.format === "text") && (!("changes" in section) || section.changes === void 0 || Array.isArray(section.changes) && section.changes.every(
42408
+ (change) => typeof change === "string"
42409
+ ))
42410
+ );
42411
+ const inspector = storedInspector && typeof storedInspector === "object" && !Array.isArray(storedInspector) && "summary" in storedInspector && Array.isArray(storedInspector.summary) && storedInspector.summary.every((line) => typeof line === "string") ? "sections" in storedInspector && validSections(storedInspector.sections) ? {
42412
+ summary: storedInspector.summary,
42413
+ sections: storedInspector.sections
42414
+ } : "tree" in storedInspector && typeof storedInspector.tree === "string" ? { summary: storedInspector.summary, tree: storedInspector.tree } : void 0 : void 0;
41672
42415
  return expandablePresentation(
41673
42416
  options.expanded,
41674
42417
  (expanded) => renderAgentDefinitionsOverview(definitions, theme, {
41675
42418
  ...options,
41676
42419
  expanded,
41677
- instructions
42420
+ instructions,
42421
+ inspector
41678
42422
  })
41679
42423
  );
41680
42424
  });
@@ -42145,20 +42889,22 @@ ${ownerMessage.text}`,
42145
42889
  const normalizeLeadTools = (tools) => leadToolState.normalizeLeadTools(tools);
42146
42890
  let roleTransitions;
42147
42891
  const isCurrentChief = (ctx) => leadRuntime.chiefMode === "active" && !!leadRuntime.chiefLease && leadRuntime.chiefLease.descriptor.piSessionId === ctx.sessionManager.getSessionId();
42148
- const chiefSystemPrompt = (options, body) => {
42149
- const agentDir = resolve8(getAgentDir3());
42150
- const globalInstructions = (options?.contextFiles ?? []).filter(
42151
- ({ path, content }) => typeof path === "string" && typeof content === "string" && resolve8(dirname9(path)) === agentDir && content.length > 0
42152
- ).map(({ content }) => content).join("\n\n");
42153
- return [
42154
- CHIEF_ROLE_CONTRACT,
42155
- body || void 0,
42156
- globalInstructions ? `## global user instructions
42892
+ const chiefGlobalInstructions2 = (options) => chiefGlobalInstructions(options, getAgentDir3());
42893
+ const chiefSystemPrompt2 = (options, body) => chiefSystemPrompt(options, body, CHIEF_ROLE_CONTRACT, getAgentDir3());
42894
+ const roleCharter = (ctx) => {
42895
+ const role2 = activeRole();
42896
+ if (leadRuntime.roleSuspended || role2 === "chief" && !isCurrentChief(ctx) || role2 === "manager" && !leadRuntime.managerLease)
42897
+ return `## Herdsman role
42898
+ No active Herdsman role is verified for this Pi session.`;
42899
+ if (role2 === "manager")
42900
+ return `${MANAGER_ROLE_CONTRACT}
42157
42901
 
42158
- <global_instructions>
42159
- ${globalInstructions}
42160
- </global_instructions>` : void 0
42161
- ].filter((section) => section !== void 0).join("\n\n");
42902
+ ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}`;
42903
+ const kind = leadRuntimes.sessionKindForPrompt(ctx);
42904
+ if (kind === "ordinary") return ORDINARY_LEAD_CHARTER;
42905
+ if (kind === "managed") return MANAGED_LEAD_CHARTER;
42906
+ return `## Herdsman role
42907
+ No active Herdsman role is verified for this Pi session.`;
42162
42908
  };
42163
42909
  const markLeadCoordinationUnhealthy = (ctx) => leadRuntimes.coordinationRuntime.markLeadCoordinationUnhealthy(ctx);
42164
42910
  const schedulePeerPresence = (ctx) => leadRuntimes.coordinationRuntime.schedulePeerPresence(ctx);
@@ -42315,22 +43061,8 @@ ${globalInstructions}
42315
43061
  setActiveTools: (tools) => pi.setActiveTools(tools),
42316
43062
  prepareSupervisionMessage,
42317
43063
  sendMessage: (message) => pi.sendMessage(message, { triggerTurn: false }),
42318
- chiefSystemPrompt,
42319
- roleCharter: (ctx) => {
42320
- const role2 = activeRole();
42321
- if (leadRuntime.roleSuspended || role2 === "chief" && !isCurrentChief(ctx) || role2 === "manager" && !leadRuntime.managerLease)
42322
- return `## Herdsman role
42323
- No active Herdsman role is verified for this Pi session.`;
42324
- if (role2 === "manager")
42325
- return `${MANAGER_ROLE_CONTRACT}
42326
-
42327
- ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}`;
42328
- const kind = leadRuntimes.sessionKindForPrompt(ctx);
42329
- if (kind === "ordinary") return ORDINARY_LEAD_CHARTER;
42330
- if (kind === "managed") return MANAGED_LEAD_CHARTER;
42331
- return `## Herdsman role
42332
- No active Herdsman role is verified for this Pi session.`;
42333
- },
43064
+ chiefSystemPrompt: chiefSystemPrompt2,
43065
+ roleCharter,
42334
43066
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
42335
43067
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
42336
43068
  currentManagerAllowedTools: (ctx) => leadRuntimes.currentManagerAllowedTools(ctx),
@@ -42509,11 +43241,24 @@ ${summary}`,
42509
43241
  updateProjectOverride,
42510
43242
  contextAgentDefinitions,
42511
43243
  discoverRoleDefinition,
43244
+ getSystemPromptOptions: (ctx) => ctx.getSystemPromptOptions(),
43245
+ chiefSystemPrompt: chiefSystemPrompt2,
43246
+ chiefGlobalInstructions: chiefGlobalInstructions2,
43247
+ roleCharter,
43248
+ isCurrentChief,
43249
+ supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
43250
+ executionPrompt: () => leadRuntimes.executionPrompt(),
43251
+ leadExecutionDefinition: () => leadRuntimes.leadExecutionDefinition(),
43252
+ inspectAgentDefinition,
43253
+ inspectRoleDefinition,
43254
+ expandDefinitionBodyFragments,
43255
+ expandDefinitionBodyFragmentsWithSources,
43256
+ expandAgentBodyFiles,
43257
+ selectedAgentContextFiles,
42512
43258
  setLeadExecutionMode: (ctx, mode) => leadRuntimes.setLeadExecutionMode(ctx, mode),
42513
43259
  leadExecutionPresentation: () => leadRuntimes.leadExecutionPresentation(),
42514
43260
  agentDefinitionEnabled,
42515
43261
  agentDefinitionMetadata,
42516
- expandAgentBodyFiles,
42517
43262
  appendDefinitionsEntry: (data) => pi.appendEntry(AGENT_DEFINITIONS_ENTRY, data),
42518
43263
  formatAgentDefinitions,
42519
43264
  validThinkingLevels: VALID_THINKING_LEVELS,
@@ -43048,7 +43793,7 @@ ${summary}`,
43048
43793
  peerLeadLockPath,
43049
43794
  worktreeGroupScope,
43050
43795
  workspacePresentationProvenance,
43051
- basename: basename9,
43796
+ basename: basename10,
43052
43797
  readPeerLeadRecord,
43053
43798
  samePeerLeadRecord,
43054
43799
  writePeerLeadRecord,
@@ -43114,7 +43859,7 @@ ${summary}`,
43114
43859
  listChiefMessagePaths,
43115
43860
  chiefMessageQuarantined,
43116
43861
  drainCoordinationInbox,
43117
- basename: basename9
43862
+ basename: basename10
43118
43863
  },
43119
43864
  agentEventOptions: leadAgentEventOptions,
43120
43865
  sessionStartOptions,