pi-herdsman 0.44.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();
@@ -1293,6 +1296,19 @@ function validate(value2, kind) {
1293
1296
  "evidenceAssignmentId",
1294
1297
  "taskEvidenceId",
1295
1298
  "createdAt"
1299
+ ] : kind === "ownerMessage" ? [
1300
+ "version",
1301
+ "messageId",
1302
+ "requestId",
1303
+ "runId",
1304
+ "ownerSessionId",
1305
+ "workspaceId",
1306
+ "agentLabel",
1307
+ "paneId",
1308
+ "piSessionId",
1309
+ "text",
1310
+ "resultBindings",
1311
+ "createdAt"
1296
1312
  ] : kind === "ask" ? [
1297
1313
  "version",
1298
1314
  "askId",
@@ -1334,6 +1350,15 @@ function validate(value2, kind) {
1334
1350
  "paneId",
1335
1351
  "piSessionId",
1336
1352
  "cwd"
1353
+ ] : kind === "ownerMessage" ? [
1354
+ "messageId",
1355
+ "requestId",
1356
+ "runId",
1357
+ "ownerSessionId",
1358
+ "workspaceId",
1359
+ "agentLabel",
1360
+ "paneId",
1361
+ "piSessionId"
1337
1362
  ] : kind === "ask" ? [
1338
1363
  "askId",
1339
1364
  "requestId",
@@ -1354,7 +1379,7 @@ function validate(value2, kind) {
1354
1379
  for (const field of required)
1355
1380
  if (typeof v[field] !== "string" || !v[field].trim())
1356
1381
  throw new Error(`Invalid mailbox field: ${field}`);
1357
- if (!UUID2.test(v.runId) || kind !== "state" && !UUID2.test(v.requestId) || kind === "ask" && !UUID2.test(v.askId))
1382
+ if (!UUID2.test(v.runId) || kind !== "state" && !UUID2.test(v.requestId) || kind === "ask" && !UUID2.test(v.askId) || kind === "ownerMessage" && !UUID2.test(v.messageId))
1358
1383
  throw new Error("Invalid mailbox UUID");
1359
1384
  const finite = (field) => {
1360
1385
  if (typeof v[field] !== "number" || !Number.isFinite(v[field]) || v[field] < 0)
@@ -1473,6 +1498,12 @@ function validate(value2, kind) {
1473
1498
  if (hasProjectAssignmentId && (typeof v.projectAssignmentId !== "string" || !UUID2.test(v.projectAssignmentId)) || hasEvidenceAssignmentId && (typeof v.evidenceAssignmentId !== "string" || !UUID2.test(v.evidenceAssignmentId)))
1474
1499
  throw new Error("Invalid request evidence assignment identity");
1475
1500
  finite("createdAt");
1501
+ } else if (kind === "ownerMessage") {
1502
+ if (typeof v.text !== "string" || !v.text.trim())
1503
+ throw new Error("Invalid owner message text");
1504
+ if (v.resultBindings !== void 0 && (!Array.isArray(v.resultBindings) || !v.resultBindings.every(isResultBinding)))
1505
+ throw new Error("Invalid owner message result bindings");
1506
+ finite("createdAt");
1476
1507
  } else if (kind === "ask") {
1477
1508
  if (typeof v.question !== "string" || !v.question.trim())
1478
1509
  throw new Error("Invalid ask question");
@@ -1517,10 +1548,10 @@ function validate(value2, kind) {
1517
1548
  function atomic(path, value2, kind, createDirectory = true) {
1518
1549
  validate(value2, kind);
1519
1550
  if (createDirectory)
1520
- mkdirSync3(dirname3(path), { recursive: true, mode: 448 });
1521
- chmodSync3(dirname3(path), 448);
1551
+ mkdirSync3(dirname4(path), { recursive: true, mode: 448 });
1552
+ chmodSync3(dirname4(path), 448);
1522
1553
  const temporary = join3(
1523
- dirname3(path),
1554
+ dirname4(path),
1524
1555
  `.${basename3(path)}.${randomUUID3()}.tmp`
1525
1556
  );
1526
1557
  let fd;
@@ -1579,7 +1610,7 @@ function resetAgentMailbox(path) {
1579
1610
  "ask.json",
1580
1611
  "bootstrap.json",
1581
1612
  ...readdirSync3(path).filter(
1582
- (x) => /^(request|result)-.*\.json$/.test(x)
1613
+ (x) => /^(request|result|owner-message)-.*\.json$/.test(x)
1583
1614
  )
1584
1615
  ]) {
1585
1616
  try {
@@ -1734,6 +1765,36 @@ function removeAsk(path) {
1734
1765
  if (e.code !== "ENOENT") throw e;
1735
1766
  }
1736
1767
  }
1768
+ function writeOwnerMessage(path, message) {
1769
+ assertFileId(message.messageId);
1770
+ atomic(
1771
+ file(path, `owner-message-${message.messageId}.json`),
1772
+ message,
1773
+ "ownerMessage"
1774
+ );
1775
+ }
1776
+ function readOwnerMessages(path) {
1777
+ return readdirSync3(path).filter((name) => name.startsWith("owner-message-")).map((name) => {
1778
+ if (!/^owner-message-[0-9a-f-]+\.json$/iu.test(name))
1779
+ throw new Error(`Malformed owner message filename: ${name}`);
1780
+ const record = read(file(path, name), "ownerMessage");
1781
+ if (!record) throw new Error("Owner message disappeared while reading");
1782
+ validate(record, "ownerMessage");
1783
+ if (name !== `owner-message-${record.messageId}.json`)
1784
+ throw new Error("Owner message filename identity mismatch");
1785
+ return record;
1786
+ }).sort(
1787
+ (a, b) => a.createdAt - b.createdAt || a.messageId.localeCompare(b.messageId)
1788
+ );
1789
+ }
1790
+ function removeOwnerMessage(path, messageId) {
1791
+ assertFileId(messageId);
1792
+ try {
1793
+ unlinkSync3(file(path, `owner-message-${messageId}.json`));
1794
+ } catch (error2) {
1795
+ if (error2.code !== "ENOENT") throw error2;
1796
+ }
1797
+ }
1737
1798
  function writeResult(path, result) {
1738
1799
  assertFileId(result.requestId);
1739
1800
  atomic(file(path, `result-${result.requestId}.json`), result, "result");
@@ -1845,6 +1906,7 @@ var init_mailbox = __esm({
1845
1906
  state: 64 * 1024,
1846
1907
  request: MAILBOX_PROTOCOL_LIMIT_BYTES,
1847
1908
  ask: MAILBOX_PROTOCOL_LIMIT_BYTES,
1909
+ ownerMessage: MAILBOX_PROTOCOL_LIMIT_BYTES,
1848
1910
  result: 4 * 1024 * 1024
1849
1911
  };
1850
1912
  root = join3(herdsmanDataRoot(), "runtime", "mailboxes-v5");
@@ -1864,7 +1926,7 @@ import {
1864
1926
  realpathSync,
1865
1927
  statSync as statSync2
1866
1928
  } from "node:fs";
1867
- import { basename as basename4, resolve } from "node:path";
1929
+ import { basename as basename4, resolve as resolve2 } from "node:path";
1868
1930
  import { TextDecoder as TextDecoder2 } from "node:util";
1869
1931
  import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
1870
1932
  function currentTurnIsSoleToolCall(ctx, name) {
@@ -1892,7 +1954,7 @@ function resolveRegularFiles(inputs, cwd, operation, skipCanonicalPaths = []) {
1892
1954
  let canonicalPath;
1893
1955
  try {
1894
1956
  resolvedResultPath = resolveResultRef(target);
1895
- path = resolvedResultPath ?? resolve(cwd, target);
1957
+ path = resolvedResultPath ?? resolve2(cwd, target);
1896
1958
  canonicalPath = realpathSync(path);
1897
1959
  if (skipped.has(canonicalPath)) return [];
1898
1960
  const existing = seen.get(canonicalPath);
@@ -2321,7 +2383,7 @@ import {
2321
2383
  import { execFileSync } from "node:child_process";
2322
2384
  import { randomUUID as randomUUID5 } from "node:crypto";
2323
2385
  import { homedir as homedir2 } from "node:os";
2324
- 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";
2325
2387
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2326
2388
  import {
2327
2389
  CONFIG_DIR_NAME,
@@ -2357,7 +2419,7 @@ function readAgentDefinitions(root2, category, onWarning) {
2357
2419
  const name = parsed.frontmatter.name;
2358
2420
  if (category && typeof name === "string" && name.length > 0 && isReservedRoleDefinition(name) !== (category === "role")) {
2359
2421
  const destination = join4(
2360
- dirname4(root2),
2422
+ dirname5(root2),
2361
2423
  category === "agent" ? "coordinators" : "agents",
2362
2424
  relative(root2, path)
2363
2425
  );
@@ -2392,8 +2454,8 @@ function readAgentDefinitions(root2, category, onWarning) {
2392
2454
  function resolveBodyFileReferences(body, definitionPath) {
2393
2455
  return body.replace(BODY_FILE_REFERENCE, (_match, input) => {
2394
2456
  const homeRelative = input.startsWith("~/") || input.startsWith(`~${sep}`);
2395
- const expanded = homeRelative ? resolve2(homedir2(), input.slice(2)) : input;
2396
- 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)}`;
2397
2459
  });
2398
2460
  }
2399
2461
  function isPlainObject(value2) {
@@ -2401,8 +2463,78 @@ function isPlainObject(value2) {
2401
2463
  const prototype = Object.getPrototypeOf(value2);
2402
2464
  return prototype === Object.prototype || prototype === null;
2403
2465
  }
2404
- function mergeFrontmatter(base, override) {
2405
- 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;
2406
2538
  }
2407
2539
  function validateDefinition(definition, options = {}) {
2408
2540
  const { frontmatter, name } = definition;
@@ -2422,18 +2554,7 @@ function validateDefinition(definition, options = {}) {
2422
2554
  for (const field of BOOLEAN_CAPABILITY_FIELDS)
2423
2555
  if (frontmatter[field] !== void 0 && typeof frontmatter[field] !== "boolean")
2424
2556
  invalid(field, "must be a boolean");
2425
- for (const field of ARRAY_FIELDS) {
2426
- const value2 = frontmatter[field];
2427
- if (value2 !== void 0 && (!Array.isArray(value2) || value2.some(
2428
- (entry) => typeof entry !== "string" || entry.trim().length === 0
2429
- ) || field === "agents" && new Set(value2).size !== value2.length))
2430
- invalid(
2431
- field,
2432
- field === "agents" ? "must be an array of unique non-empty strings" : "must be an array of non-empty strings"
2433
- );
2434
- }
2435
- if (frontmatter.tools !== void 0 && normalizedToolNames(frontmatter.tools).some((tool) => /^[+-]/u.test(tool)))
2436
- invalid("tools", "must be an allowlist without +name/-name modifiers");
2557
+ validateArrayFields(frontmatter, invalid);
2437
2558
  if (frontmatter.model !== void 0) {
2438
2559
  if (typeof frontmatter.model !== "string" || !frontmatter.model)
2439
2560
  invalid("model", "must be a non-empty string");
@@ -2472,8 +2593,25 @@ function matchesToolPattern(pattern, name) {
2472
2593
  }
2473
2594
  function configuredToolPolicy(definition, requiredTools) {
2474
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";
2475
2598
  const required = new Set(requiredTools);
2476
- 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);
2477
2615
  for (const pattern of excluded) {
2478
2616
  if (!pattern.includes("*")) continue;
2479
2617
  const matched = requiredTools.find(
@@ -2485,8 +2623,11 @@ function configuredToolPolicy(definition, requiredTools) {
2485
2623
  );
2486
2624
  }
2487
2625
  return {
2488
- explicit: definition.frontmatter.tools !== void 0,
2489
- 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
+ ),
2490
2631
  excluded
2491
2632
  };
2492
2633
  }
@@ -2494,7 +2635,7 @@ function toolPolicyAllowsName(policy, requiredTools, name) {
2494
2635
  if (requiredTools.has(name)) return true;
2495
2636
  if (policy.excluded.some((pattern) => matchesToolPattern(pattern, name)))
2496
2637
  return false;
2497
- return !policy.explicit || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2638
+ return policy.mode !== "explicit" || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2498
2639
  }
2499
2640
  function readOptionalAgentDefinitions(root2, category, onWarning) {
2500
2641
  const stats = statSync3(root2, { throwIfNoEntry: false });
@@ -2556,13 +2697,36 @@ function privateRepositoryRoot(projectRoot) {
2556
2697
  throw new Error(`Invalid Git common-directory result for ${projectRoot}`);
2557
2698
  return join4(realpathSync2(commonDir), "pi-herdsman");
2558
2699
  }
2559
- 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) {
2560
2704
  for (const definition of layer) {
2561
2705
  const base = definitions.get(definition.name);
2562
2706
  if (!base) {
2563
- definition[sourceField] = definition.path;
2564
- validateDefinition(definition);
2565
- 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);
2566
2730
  continue;
2567
2731
  }
2568
2732
  const mode = overrideBodyMode(definition);
@@ -2570,7 +2734,11 @@ function applyDefinitionLayer(definitions, layer, sourceField) {
2570
2734
  const effective = {
2571
2735
  name: base.name,
2572
2736
  path: definition.path,
2573
- frontmatter: mergeFrontmatter(base.frontmatter, overrideFrontmatter),
2737
+ frontmatter: composeFrontmatter(
2738
+ base.frontmatter,
2739
+ overrideFrontmatter,
2740
+ definition.name
2741
+ ),
2574
2742
  body: mergeDefinitionBody(base.body, definition.body, mode),
2575
2743
  extensionSource: base.extensionSource,
2576
2744
  projectSource: base.projectSource,
@@ -2579,6 +2747,24 @@ function applyDefinitionLayer(definitions, layer, sourceField) {
2579
2747
  [sourceField]: definition.path
2580
2748
  };
2581
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
+ }
2582
2768
  definitions.set(effective.name, effective);
2583
2769
  }
2584
2770
  }
@@ -2629,7 +2815,7 @@ function validateRuntimeRoleLayer(definition) {
2629
2815
  `${definition.path} ${definition.name} field ${field}: is not supported`
2630
2816
  );
2631
2817
  }
2632
- function discoverEffectiveDefinitions(options = {}, category = "agent", validateReferences = true) {
2818
+ function discoverEffectiveDefinitions(options = {}, category = "agent", validateReferences = true, trace) {
2633
2819
  const role2 = category === "role";
2634
2820
  const bundled = readAgentDefinitions(
2635
2821
  role2 ? BUILTIN_ROLE_DIR : BUILTIN_AGENT_DIR
@@ -2680,6 +2866,17 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2680
2866
  if (!definition.extensionSource)
2681
2867
  definition.extensionSource = definition.path;
2682
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
+ }
2683
2880
  }
2684
2881
  for (const definition of [
2685
2882
  ...bundled,
@@ -2704,12 +2901,13 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2704
2901
  throw new Error(
2705
2902
  `${privateChief.path} chief definition: private repository overrides are not supported; configure chief globally instead`
2706
2903
  );
2707
- applyDefinitionLayer(definitions, user, "overrideSource");
2708
- applyDefinitionLayer(definitions, project, "projectSource");
2904
+ applyDefinitionLayer(definitions, user, "overrideSource", trace);
2905
+ applyDefinitionLayer(definitions, project, "projectSource", trace);
2709
2906
  applyDefinitionLayer(
2710
2907
  definitions,
2711
2908
  privateRepository,
2712
- "privateRepositorySource"
2909
+ "privateRepositorySource",
2910
+ trace
2713
2911
  );
2714
2912
  const effective = [...definitions.values()].sort(
2715
2913
  (left, right) => left.name.localeCompare(right.name)
@@ -2717,6 +2915,44 @@ function discoverEffectiveDefinitions(options = {}, category = "agent", validate
2717
2915
  if (!role2 && validateReferences) validateEffectiveAgentReferences(effective);
2718
2916
  return effective;
2719
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
+ }
2720
2956
  function discoverAgentDefinitions(options = {}) {
2721
2957
  return discoverEffectiveDefinitions(options).filter(({ name }) => !isReservedRoleDefinition(name)).map((definition) => withDefaultEnabled(definition));
2722
2958
  }
@@ -2927,7 +3163,7 @@ function updateAgentOverride(definition, field, value2, options = {}) {
2927
3163
  );
2928
3164
  mode = exists.mode & 511;
2929
3165
  } else {
2930
- mkdirSync4(dirname4(path), { recursive: true });
3166
+ mkdirSync4(dirname5(path), { recursive: true });
2931
3167
  content = `---
2932
3168
  name: ${JSON.stringify(definition.name)}
2933
3169
  ---
@@ -2974,7 +3210,7 @@ name: ${JSON.stringify(definition.name)}
2974
3210
  if (value2 === void 0 && !hadField)
2975
3211
  return { path, changed: false, content: readFileSync5(path, "utf8") };
2976
3212
  const temporary = join4(
2977
- dirname4(path),
3213
+ dirname5(path),
2978
3214
  `.${encodeURIComponent(definition.name)}.${randomUUID5()}.tmp`
2979
3215
  );
2980
3216
  try {
@@ -3062,24 +3298,47 @@ function writePrivatePromptSnapshots(contents) {
3062
3298
  throw error2;
3063
3299
  }
3064
3300
  }
3065
- function expandAgentBodyFiles(body, skipCanonicalPaths, operation) {
3066
- const references = [...body.matchAll(BODY_FILE_REFERENCE)].map(
3067
- (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])
3068
3304
  );
3069
- if (references.length === 0) return body;
3070
- const snapshots = snapshotTextFiles(references, process.cwd(), operation, {
3305
+ const snapshots = references.length ? snapshotTextFiles(references, process.cwd(), operation, {
3071
3306
  skipCanonicalPaths
3072
- });
3307
+ }) : [];
3073
3308
  const remaining = new Map(
3074
- snapshots.map((snapshot) => [snapshot.input, snapshot.text])
3309
+ snapshots.map((snapshot) => [snapshot.input, snapshot])
3075
3310
  );
3076
- return body.replace(BODY_FILE_REFERENCE, (_match, input) => {
3077
- const text = remaining.get(input);
3078
- if (text === void 0) return "";
3079
- remaining.delete(input);
3080
- 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;
3081
3326
  });
3082
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
+ }
3083
3342
  function agentDefinitionDelegationEnabled(definition) {
3084
3343
  const {
3085
3344
  agents,
@@ -3090,8 +3349,27 @@ function agentDefinitionDelegationEnabled(definition) {
3090
3349
  if ((agents?.length ?? 0) === 0) return false;
3091
3350
  const tools = normalizedToolNames(configured);
3092
3351
  if (normalizedToolNames(excludeTools).includes("agent")) return false;
3093
- if (noTools === true && !tools.includes("agent")) return false;
3094
- 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
+ });
3095
3373
  }
3096
3374
  function agentLaunchArgs(agent, options) {
3097
3375
  const {
@@ -3141,27 +3419,25 @@ function agentLaunchArgs(agent, options) {
3141
3419
  mode === "append" ? "--append-system-prompt" : "--system-prompt",
3142
3420
  bodyPromptPathForLaunch
3143
3421
  );
3144
- const inheritProjectContext = frontmatter.inheritProjectContext ?? agent.name === "delegate";
3145
- const inheritGlobalContext = frontmatter.inheritGlobalContext ?? inheritProjectContext;
3146
- if (inheritProjectContext !== true || inheritGlobalContext !== true) {
3422
+ const inheritance = contextInheritance(agent);
3423
+ if (!inheritance.global || !inheritance.project) {
3147
3424
  args.push("--no-context-files");
3148
- if (inheritProjectContext === true || inheritGlobalContext === true) {
3149
- const agentDir = getAgentDir();
3150
- for (const context of (options.loadProjectContextFiles ?? loadProjectContextFiles)({ cwd, agentDir })) {
3151
- const isGlobal = resolve2(dirname4(context.path)) === resolve2(agentDir);
3152
- if (isGlobal && inheritGlobalContext === true || !isGlobal && inheritProjectContext === true)
3153
- args.push("--append-system-prompt", context.path);
3154
- }
3155
- }
3425
+ for (const context of selectedAgentContextFiles(
3426
+ agent,
3427
+ cwd,
3428
+ options.loadProjectContextFiles ?? loadProjectContextFiles
3429
+ ))
3430
+ args.push("--append-system-prompt", context.path);
3156
3431
  }
3157
3432
  if (sharedPromptPath) args.push("--append-system-prompt", sharedPromptPath);
3158
3433
  const requiredTools = [
3159
3434
  ...managedAgent ? agentDefinitionDelegationEnabled(agent) ? [
3160
3435
  ...AGENT_COORDINATION_TOOLS,
3161
- "ask_owner",
3436
+ "await_owner",
3437
+ "notify_owner",
3162
3438
  "read_evidence",
3163
3439
  "attach_handoff"
3164
- ] : ["ask_owner", "read_evidence", "attach_handoff"] : [],
3440
+ ] : ["await_owner", "notify_owner", "read_evidence", "attach_handoff"] : [],
3165
3441
  ...options.requiredTools ?? []
3166
3442
  ].filter((tool, index, all) => all.indexOf(tool) === index);
3167
3443
  const policy = configuredToolPolicy(agent, requiredTools);
@@ -3169,7 +3445,16 @@ function agentLaunchArgs(agent, options) {
3169
3445
  if (noTools) args.push("--no-tools");
3170
3446
  if (frontmatter.noBuiltinTools) args.push("--no-builtin-tools");
3171
3447
  const excluded = policy.excluded;
3172
- 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") {
3173
3458
  const configured = policy.tools.filter(
3174
3459
  (tool) => !managedAgent || tool !== "agent"
3175
3460
  );
@@ -3194,7 +3479,7 @@ function agentLaunchArgs(agent, options) {
3194
3479
  args.push("--append-system-prompt", `<active_agent name="${agent.name}"/>`);
3195
3480
  return args;
3196
3481
  }
3197
- 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;
3198
3483
  var init_agent_definitions = __esm({
3199
3484
  "extension/agent-definitions.ts"() {
3200
3485
  "use strict";
@@ -3284,6 +3569,7 @@ var init_agent_definitions = __esm({
3284
3569
  "inspect_agent",
3285
3570
  "read_agent_transcript"
3286
3571
  ];
3572
+ isArrayModifier = (entry) => entry.startsWith("+") || entry.startsWith("-");
3287
3573
  definitionWarningSessions = /* @__PURE__ */ new WeakMap();
3288
3574
  }
3289
3575
  });
@@ -3302,7 +3588,7 @@ import {
3302
3588
  statSync as statSync4
3303
3589
  } from "node:fs";
3304
3590
  import { createConnection } from "node:net";
3305
- 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";
3306
3592
  import { StringDecoder } from "node:string_decoder";
3307
3593
  import { setTimeout as sleep } from "node:timers/promises";
3308
3594
  function parseHerdrVersion(value2) {
@@ -3646,7 +3932,7 @@ function herdrAgentAlias(workspaceId, label, runId) {
3646
3932
  return alias(workspaceId, label, runId);
3647
3933
  }
3648
3934
  function canonicalCwd(value2) {
3649
- const resolved = resolve3(value2);
3935
+ const resolved = resolve4(value2);
3650
3936
  try {
3651
3937
  return realpathSync3.native(resolved);
3652
3938
  } catch {
@@ -3732,7 +4018,7 @@ async function lockLifecycle(ctx, signal) {
3732
4018
  "locks",
3733
4019
  createHash7("sha256").update(id).digest("hex")
3734
4020
  );
3735
- mkdirSync5(resolve3(path, ".."), { recursive: true, mode: 448 });
4021
+ mkdirSync5(resolve4(path, ".."), { recursive: true, mode: 448 });
3736
4022
  const deadline = Date.now() + 3e4;
3737
4023
  while (true) {
3738
4024
  if (signal?.aborted) throw signal.reason ?? new Error("operation aborted");
@@ -5433,7 +5719,7 @@ import {
5433
5719
  writeFileSync as writeFileSync3
5434
5720
  } from "node:fs";
5435
5721
  import { createHash as createHash8, randomUUID as randomUUID7 } from "node:crypto";
5436
- 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";
5437
5723
  import { isDeepStrictEqual } from "node:util";
5438
5724
  function readSessionKind(entries, sessionId) {
5439
5725
  let identity;
@@ -5632,7 +5918,7 @@ function writePeerDeliveryReceipt(runtime, record) {
5632
5918
  if (record.kind !== "peer_message")
5633
5919
  throw new Error("Peer delivery receipt requires a peer message");
5634
5920
  const path = peerDeliveryReceiptPath(runtime, record.toSessionId, record.id);
5635
- const directory2 = dirname5(path);
5921
+ const directory2 = dirname6(path);
5636
5922
  mkdirSync6(directory2, { recursive: true, mode: 448 });
5637
5923
  const receipt = {
5638
5924
  sessionId: record.toSessionId,
@@ -5650,7 +5936,7 @@ function writePeerDeliveryReceipt(runtime, record) {
5650
5936
  if (error2.code !== "ENOENT") throw error2;
5651
5937
  }
5652
5938
  publishRecord(path, content);
5653
- fsyncDirectory(dirname5(directory2));
5939
+ fsyncDirectory(dirname6(directory2));
5654
5940
  }
5655
5941
  function fsyncDirectory(directory2) {
5656
5942
  if (process.platform === "win32") return;
@@ -5662,7 +5948,7 @@ function fsyncDirectory(directory2) {
5662
5948
  }
5663
5949
  }
5664
5950
  function publishRecord(path, content) {
5665
- const directory2 = dirname5(path);
5951
+ const directory2 = dirname6(path);
5666
5952
  const temporary = join6(directory2, `.${basename5(path)}.${randomUUID7()}.tmp`);
5667
5953
  let fd;
5668
5954
  let cleanupError;
@@ -5807,18 +6093,18 @@ function removeMalformedChiefMessageUnlocked(runtime, toSessionId, id) {
5807
6093
  }
5808
6094
  try {
5809
6095
  const claimed = join6(
5810
- dirname5(path),
6096
+ dirname6(path),
5811
6097
  `.${basename5(path, ".json")}.${randomUUID7()}.cleanup`
5812
6098
  );
5813
6099
  renameSync5(path, claimed);
5814
- fsyncDirectory(dirname5(path));
6100
+ fsyncDirectory(dirname6(path));
5815
6101
  try {
5816
6102
  unlinkSync5(claimed);
5817
- fsyncDirectory(dirname5(path));
6103
+ fsyncDirectory(dirname6(path));
5818
6104
  } catch (error2) {
5819
6105
  try {
5820
6106
  renameSync5(claimed, path);
5821
- fsyncDirectory(dirname5(path));
6107
+ fsyncDirectory(dirname6(path));
5822
6108
  } catch {
5823
6109
  }
5824
6110
  throw error2;
@@ -5867,7 +6153,7 @@ function removeChiefMessageQuarantineUnlocked(runtime, toSessionId, id) {
5867
6153
  const path = chiefMessagePath(runtime, toSessionId, id);
5868
6154
  try {
5869
6155
  unlinkSync5(`${path}.quarantine`);
5870
- fsyncDirectory(dirname5(path));
6156
+ fsyncDirectory(dirname6(path));
5871
6157
  } catch (error2) {
5872
6158
  if (error2.code === "ENOENT") return;
5873
6159
  try {
@@ -6060,7 +6346,7 @@ function removeChiefMessage(runtime, toSessionId, id, expected) {
6060
6346
  }
6061
6347
  function removeChiefMessageUnlocked(runtime, toSessionId, id, expected) {
6062
6348
  const path = chiefMessagePath(runtime, toSessionId, id);
6063
- const directory2 = dirname5(path);
6349
+ const directory2 = dirname6(path);
6064
6350
  const matchesExpected = () => {
6065
6351
  if (!expected) return true;
6066
6352
  try {
@@ -6132,7 +6418,7 @@ function quarantineChiefMessageUnlocked(runtime, toSessionId, id) {
6132
6418
  fsyncSync3(fd);
6133
6419
  closeSync6(fd);
6134
6420
  fd = void 0;
6135
- fsyncDirectory(dirname5(quarantine));
6421
+ fsyncDirectory(dirname6(quarantine));
6136
6422
  } finally {
6137
6423
  if (fd !== void 0) closeSync6(fd);
6138
6424
  }
@@ -6607,7 +6893,7 @@ function removePeerLeadRecord(runtime, piSessionId, expected) {
6607
6893
  if (!current || !samePeerLeadRecord(current, expected)) return;
6608
6894
  }
6609
6895
  unlinkSync5(path);
6610
- fsyncDirectory(dirname5(path));
6896
+ fsyncDirectory(dirname6(path));
6611
6897
  } catch (error2) {
6612
6898
  if (error2.code !== "ENOENT") throw error2;
6613
6899
  }
@@ -6679,7 +6965,7 @@ function chiefLeaseIsHeld(runtime) {
6679
6965
  }
6680
6966
  function writeDescriptor(path, descriptor) {
6681
6967
  const temporary = join6(
6682
- dirname5(path),
6968
+ dirname6(path),
6683
6969
  `.${basename5(path)}.${randomUUID7()}.tmp`
6684
6970
  );
6685
6971
  const content = `${JSON.stringify(descriptor)}
@@ -6696,7 +6982,7 @@ function writeDescriptor(path, descriptor) {
6696
6982
  chmodSync5(temporary, 384);
6697
6983
  renameSync5(temporary, path);
6698
6984
  chmodSync5(path, 384);
6699
- fsyncDirectory(dirname5(path));
6985
+ fsyncDirectory(dirname6(path));
6700
6986
  } finally {
6701
6987
  if (fd !== void 0) closeSync6(fd);
6702
6988
  try {
@@ -6989,7 +7275,7 @@ function writeProjectAssignmentUnlocked(runtime, assignment) {
6989
7275
  assignment.repoKey,
6990
7276
  assignment.branch
6991
7277
  );
6992
- const directory2 = dirname5(path);
7278
+ const directory2 = dirname6(path);
6993
7279
  mkdirSync6(directory2, { recursive: true, mode: 448 });
6994
7280
  chmodSync5(runtime.root, 448);
6995
7281
  chmodSync5(runtime.assignments, 448);
@@ -7086,7 +7372,7 @@ function readProjectAssignmentFile(path, repoKey, branch, pending = false) {
7086
7372
  }
7087
7373
  if (projectAssignmentBytes(value2) > PROJECT_ASSIGNMENT_MAX_BYTES)
7088
7374
  throw projectAssignmentReadError(path, "assignment payload is too large");
7089
- 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`)
7090
7376
  throw projectAssignmentReadError(path, "assignment identity mismatch");
7091
7377
  return value2;
7092
7378
  }
@@ -7098,7 +7384,7 @@ function projectAssignmentReadError(path, reason) {
7098
7384
  return new Error(`Unable to read project assignment ${path}: ${reason}`);
7099
7385
  }
7100
7386
  function listProjectAssignments(runtime, repoKey) {
7101
- const directory2 = dirname5(projectAssignmentPath(runtime, repoKey, "lookup"));
7387
+ const directory2 = dirname6(projectAssignmentPath(runtime, repoKey, "lookup"));
7102
7388
  let entries;
7103
7389
  try {
7104
7390
  entries = readdirSync5(directory2);
@@ -7128,11 +7414,11 @@ function retireProjectAssignment(runtime, expected) {
7128
7414
  return withProjectAssignmentLock(() => {
7129
7415
  for (const directory2 of [
7130
7416
  herdsmanDataRoot(),
7131
- dirname5(dirname5(runtime.root)),
7132
- dirname5(runtime.root),
7417
+ dirname6(dirname6(runtime.root)),
7418
+ dirname6(runtime.root),
7133
7419
  runtime.root,
7134
7420
  runtime.assignments,
7135
- dirname5(
7421
+ dirname6(
7136
7422
  projectAssignmentPath(runtime, expected.repoKey, expected.branch)
7137
7423
  )
7138
7424
  ])
@@ -7150,7 +7436,7 @@ function retireProjectAssignment(runtime, expected) {
7150
7436
  );
7151
7437
  const destination = pendingRetirementPath(runtime, current);
7152
7438
  const root2 = join6(runtime.root, "retirements");
7153
- for (const directory2 of [root2, dirname5(destination)]) {
7439
+ for (const directory2 of [root2, dirname6(destination)]) {
7154
7440
  try {
7155
7441
  mkdirSync6(directory2, { mode: 448 });
7156
7442
  } catch (error2) {
@@ -7161,8 +7447,8 @@ function retireProjectAssignment(runtime, expected) {
7161
7447
  if (lstatSync4(destination, { throwIfNoEntry: false }))
7162
7448
  throw new Error("Pending retirement already exists");
7163
7449
  renameSync5(source, destination);
7164
- fsyncDirectory(dirname5(source));
7165
- fsyncDirectory(dirname5(destination));
7450
+ fsyncDirectory(dirname6(source));
7451
+ fsyncDirectory(dirname6(destination));
7166
7452
  fsyncDirectory(root2);
7167
7453
  fsyncDirectory(runtime.root);
7168
7454
  return true;
@@ -7179,13 +7465,13 @@ function pendingRetirementPath(runtime, expected) {
7179
7465
  return join6(
7180
7466
  runtime.root,
7181
7467
  "retirements",
7182
- basename5(dirname5(active)),
7468
+ basename5(dirname6(active)),
7183
7469
  `${basename5(active, ".json")}.${expected.id}.json`
7184
7470
  );
7185
7471
  }
7186
7472
  function listPendingRetirements(runtime, repoKey, options = {}) {
7187
7473
  const repository = basename5(
7188
- dirname5(projectAssignmentPath(runtime, repoKey, "lookup"))
7474
+ dirname6(projectAssignmentPath(runtime, repoKey, "lookup"))
7189
7475
  );
7190
7476
  const root2 = join6(runtime.root, "retirements");
7191
7477
  const directory2 = join6(root2, repository);
@@ -7193,8 +7479,8 @@ function listPendingRetirements(runtime, repoKey, options = {}) {
7193
7479
  try {
7194
7480
  for (const parent of [
7195
7481
  herdsmanDataRoot(),
7196
- dirname5(dirname5(runtime.root)),
7197
- dirname5(runtime.root),
7482
+ dirname6(dirname6(runtime.root)),
7483
+ dirname6(runtime.root),
7198
7484
  runtime.root,
7199
7485
  root2,
7200
7486
  directory2
@@ -7244,11 +7530,11 @@ function removePendingRetirement(runtime, expected) {
7244
7530
  const root2 = join6(runtime.root, "retirements");
7245
7531
  for (const directory2 of [
7246
7532
  herdsmanDataRoot(),
7247
- dirname5(dirname5(runtime.root)),
7248
- dirname5(runtime.root),
7533
+ dirname6(dirname6(runtime.root)),
7534
+ dirname6(runtime.root),
7249
7535
  runtime.root,
7250
7536
  root2,
7251
- dirname5(path)
7537
+ dirname6(path)
7252
7538
  ])
7253
7539
  assignmentDirectory(directory2);
7254
7540
  const record = readProjectAssignmentFile(
@@ -7261,7 +7547,7 @@ function removePendingRetirement(runtime, expected) {
7261
7547
  if (record.id !== expected.id)
7262
7548
  throw new Error("Pending retirement identity mismatch");
7263
7549
  unlinkSync5(path);
7264
- fsyncDirectory(dirname5(path));
7550
+ fsyncDirectory(dirname6(path));
7265
7551
  });
7266
7552
  }
7267
7553
  function assignmentDirectory(path) {
@@ -7393,7 +7679,7 @@ function projectMessageEnvelope(kind, branch, sessionId) {
7393
7679
  }
7394
7680
  function projectMessageDirectory(runtime, repoKey, branch) {
7395
7681
  const assignment = projectAssignmentPath(runtime, repoKey, branch);
7396
- return join6(dirname5(assignment), `${basename5(assignment, ".json")}.messages`);
7682
+ return join6(dirname6(assignment), `${basename5(assignment, ".json")}.messages`);
7397
7683
  }
7398
7684
  function validProjectMessage(value2) {
7399
7685
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return false;
@@ -7455,7 +7741,7 @@ function writeProjectMessageUnlocked(record, runtime) {
7455
7741
  mkdirSync6(directory2, { recursive: true, mode: 448 });
7456
7742
  chmodSync5(runtime.root, 448);
7457
7743
  chmodSync5(runtime.assignments, 448);
7458
- chmodSync5(dirname5(directory2), 448);
7744
+ chmodSync5(dirname6(directory2), 448);
7459
7745
  chmodSync5(directory2, 448);
7460
7746
  const path = join6(directory2, `${record.id}.json`);
7461
7747
  let stored = record;
@@ -7622,7 +7908,7 @@ function removeProjectMessagesForAssignment(runtime, assignment) {
7622
7908
  }
7623
7909
  function recoverStaleProjectMessages(runtime, repoKey) {
7624
7910
  withProjectAssignmentLock(() => {
7625
- const directory2 = dirname5(
7911
+ const directory2 = dirname6(
7626
7912
  projectAssignmentPath(runtime, repoKey, "lookup")
7627
7913
  );
7628
7914
  let entries;
@@ -7669,7 +7955,7 @@ function recoverStaleProjectMessages(runtime, repoKey) {
7669
7955
  });
7670
7956
  }
7671
7957
  function mightHaveProjectMessages(runtime, repoKey) {
7672
- const directory2 = dirname5(projectAssignmentPath(runtime, repoKey, "lookup"));
7958
+ const directory2 = dirname6(projectAssignmentPath(runtime, repoKey, "lookup"));
7673
7959
  let entries;
7674
7960
  try {
7675
7961
  entries = readdirSync5(directory2, { withFileTypes: true });
@@ -7904,7 +8190,7 @@ function invalidateLeadCoordinationState(runtime, piSessionId, expectedInstanceI
7904
8190
  if (error2.code !== "ENOENT") throw error2;
7905
8191
  return;
7906
8192
  }
7907
- fsyncDirectory(dirname5(path));
8193
+ fsyncDirectory(dirname6(path));
7908
8194
  }
7909
8195
  function normalizeHerdrLifecycleState(agent) {
7910
8196
  const state = agent?.agent_status;
@@ -8155,7 +8441,69 @@ import {
8155
8441
  writeFileSync as writeFileSync4
8156
8442
  } from "node:fs";
8157
8443
  import { homedir as homedir3 } from "node:os";
8158
- 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
+ }
8159
8507
  function populateMenuFrame(container, theme, title, body, footer, help) {
8160
8508
  container.clear();
8161
8509
  container.addChild(new DynamicBorder((line) => theme.fg("border", line)));
@@ -9640,7 +9988,7 @@ function displayHomePath(path) {
9640
9988
  function displaySkillName(skill) {
9641
9989
  const file2 = basename6(skill);
9642
9990
  if (file2 === "SKILL.md") {
9643
- const parent = basename6(dirname6(skill));
9991
+ const parent = basename6(dirname7(skill));
9644
9992
  if (parent && parent !== "." && parent !== "..") return parent;
9645
9993
  }
9646
9994
  return file2 || skill;
@@ -9711,6 +10059,8 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9711
10059
  const lines = definitions.length > 1 ? [
9712
10060
  `${theme.bold(theme.fg("customMessageLabel", "Definitions"))}${theme.fg("muted", ` \xB7 ${definitions.length}`)}`
9713
10061
  ] : [];
10062
+ if (options.expanded === true && options.inspector?.sections)
10063
+ lines.push(theme.fg("accent", theme.bold("METADATA")));
9714
10064
  definitions.forEach((definition) => {
9715
10065
  const name = value(definition.name ?? definition.agent);
9716
10066
  if (!name) return;
@@ -9768,7 +10118,10 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9768
10118
  )
9769
10119
  );
9770
10120
  });
9771
- 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) {
9772
10125
  const characters = Array.from(options.instructions).length;
9773
10126
  lines.push(
9774
10127
  humanRow(theme, "instructions", `${characters} chars \xB7 Ctrl+O to expand`)
@@ -9780,7 +10133,51 @@ function renderAgentDefinitionsOverview(definitions, theme, options = {}) {
9780
10133
  (line) => theme.bg("customMessageBg", line)
9781
10134
  );
9782
10135
  box.addChild(new WidthSafeText(lines.join("\n"), 0, 0));
9783
- 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) {
9784
10181
  box.addChild(new Spacer(1));
9785
10182
  box.addChild(
9786
10183
  new Text(
@@ -10772,7 +11169,7 @@ function savePrivateOutput(text, sessionId, key, kind) {
10772
11169
  hash(sessionId),
10773
11170
  `${hash(key)}.txt`
10774
11171
  );
10775
- const root2 = dirname6(path);
11172
+ const root2 = dirname7(path);
10776
11173
  mkdirSync7(root2, { recursive: true, mode: 448 });
10777
11174
  chmodSync6(root2, 448);
10778
11175
  temp = `${path}.${process.pid}.${randomUUID8()}.tmp`;
@@ -11090,6 +11487,44 @@ function renderAgentAskMessage(message, options, theme) {
11090
11487
  }
11091
11488
  return renderMessageBox(content, theme, options.outputPad ?? 0);
11092
11489
  }
11490
+ function renderAgentOwnerMessage(message, options, theme) {
11491
+ const details = isRecord2(message.details) ? message.details : {};
11492
+ const agentLabel = value(details.agentLabel);
11493
+ const label = /^[a-z][a-z0-9_-]{0,31}$/u.test(agentLabel) ? agentLabel : "agent";
11494
+ const heading = `${humanText(theme, "accent", "\u2709")} ${theme.bold(label)} notified owner`;
11495
+ const rawBody = contentText(message.content ?? "");
11496
+ const body = rawBody.startsWith(`Agent ${label} notification:
11497
+
11498
+ `) ? rawBody.slice(`Agent ${label} notification:
11499
+
11500
+ `.length) : label === "agent" ? rawBody.replace(/^Agent [^\n]+ notification:\n\n/u, "") : rawBody;
11501
+ const content = new Container();
11502
+ content.addChild(new Text(heading, 0, 0));
11503
+ if (options.expanded) {
11504
+ if (body) {
11505
+ content.addChild(new Spacer(1));
11506
+ content.addChild(new Markdown(body, 0, 0, getMarkdownTheme()));
11507
+ }
11508
+ const metadata = [
11509
+ ...value(details.messageId) ? [`message: ${value(details.messageId)}`] : [],
11510
+ ...value(details.requestId) ? [`request: ${value(details.requestId)}`] : [],
11511
+ ...value(details.piSessionId) ? [`session: ${value(details.piSessionId)}`] : []
11512
+ ];
11513
+ if (metadata.length) {
11514
+ content.addChild(new Spacer(1));
11515
+ content.addChild(new WidthSafeText(metadata.join("\n"), 0, 0));
11516
+ }
11517
+ } else {
11518
+ const preview = collapseDisplayText(body, 200);
11519
+ if (preview)
11520
+ content.addChild(
11521
+ new Markdown(` ${preview}`, 0, 0, getMarkdownTheme(), {
11522
+ color: (text) => humanText(theme, "muted", text)
11523
+ })
11524
+ );
11525
+ }
11526
+ return renderMessageBox(content, theme, options.outputPad ?? 0);
11527
+ }
11093
11528
  function renderAgentAttentionMessage(message, options, theme) {
11094
11529
  const details = message.details && typeof message.details === "object" ? message.details : {};
11095
11530
  const label = value(details.agentLabel) || "agent";
@@ -13069,7 +13504,7 @@ import {
13069
13504
  writeFileSync as writeFileSync5
13070
13505
  } from "node:fs";
13071
13506
  import { randomUUID as randomUUID9 } from "node:crypto";
13072
- 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";
13073
13508
  function validManagerMergeSetting(value2) {
13074
13509
  return typeof value2 === "boolean" || value2 === "divergent";
13075
13510
  }
@@ -13350,7 +13785,7 @@ function updateProjectOverride(ctx, key, value2) {
13350
13785
  const path = projectSettingsFile(ctx);
13351
13786
  let mode = assertRegularProjectSettings(path);
13352
13787
  if (value2 === void 0 && mode === void 0) return;
13353
- mkdirSync8(dirname7(path), { recursive: true, mode: 448 });
13788
+ mkdirSync8(dirname8(path), { recursive: true, mode: 448 });
13354
13789
  const release = acquireProjectSettingsLock(path);
13355
13790
  let changed = false;
13356
13791
  try {
@@ -13399,7 +13834,7 @@ function readEffectiveConfig(ctx) {
13399
13834
  return { ...readConfig(), ...readProjectOverrides(ctx) };
13400
13835
  }
13401
13836
  function writeConfigAtomically(path, content, mode = 384) {
13402
- const directory2 = dirname7(path);
13837
+ const directory2 = dirname8(path);
13403
13838
  const temporaryPath = join8(
13404
13839
  directory2,
13405
13840
  `.${basename7(path)}.${randomUUID9()}.tmp`
@@ -13540,7 +13975,7 @@ import { unlinkSync as unlinkSync8 } from "node:fs";
13540
13975
  import { createHash as createHash10, randomUUID as randomUUID10 } from "node:crypto";
13541
13976
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
13542
13977
  import { homedir as homedir4 } from "node:os";
13543
- 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";
13544
13979
  import { setTimeout as delay } from "node:timers/promises";
13545
13980
  import { StringEnum } from "@earendil-works/pi-ai";
13546
13981
  import { Type } from "typebox";
@@ -14875,6 +15310,13 @@ function hasDeliveredAsk(entries, ask) {
14875
15310
  return (entry?.customType === "pi-herdsman-agent-ask" || message?.customType === "pi-herdsman-agent-ask") && details?.askId === ask.askId && details?.requestId === ask.requestId && details?.runId === ask.runId && details?.agentLabel === ask.agentLabel && details?.workspaceId === ask.workspaceId && details?.paneId === ask.paneId && details?.piSessionId === ask.piSessionId;
14876
15311
  });
14877
15312
  }
15313
+ function hasDeliveredOwnerMessage(entries, ownerMessage) {
15314
+ return entries.some((entry) => {
15315
+ const message = entry?.message;
15316
+ const details = entry?.details ?? message?.details;
15317
+ return (entry?.customType === "pi-herdsman-agent-owner-message" || message?.customType === "pi-herdsman-agent-owner-message") && details?.messageId === ownerMessage.messageId && details?.requestId === ownerMessage.requestId && details?.runId === ownerMessage.runId && details?.ownerSessionId === ownerMessage.ownerSessionId && details?.agentLabel === ownerMessage.agentLabel && details?.workspaceId === ownerMessage.workspaceId && details?.paneId === ownerMessage.paneId && details?.piSessionId === ownerMessage.piSessionId;
15318
+ });
15319
+ }
14878
15320
  function canonicalSessionPath(path) {
14879
15321
  try {
14880
15322
  return realpathSync4(path);
@@ -15183,7 +15625,7 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
15183
15625
  );
15184
15626
  selector = { kind: "id", value: value2 };
15185
15627
  } else {
15186
- 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);
15187
15629
  try {
15188
15630
  selector = { kind: "path", value: canonicalSessionPath(path) };
15189
15631
  } catch (error2) {
@@ -15737,13 +16179,13 @@ function validateAssignmentCwd(definition, agentCwd, controllerCwd, scope, opera
15737
16179
  if (definition.projectSource && !sameCwd(agentCwd, controllerCwd))
15738
16180
  fail(
15739
16181
  "invalid_request",
15740
- `Project agent ${definition.name} belongs to ${resolve4(controllerCwd)}`,
16182
+ `Project agent ${definition.name} belongs to ${resolve5(controllerCwd)}`,
15741
16183
  operation
15742
16184
  );
15743
16185
  if (scope.kind === "managed-agent" && !sameCwd(agentCwd, controllerCwd))
15744
16186
  fail(
15745
16187
  "invalid_request",
15746
- `Delegated agents must use the delegating agent cwd ${resolve4(controllerCwd)}`,
16188
+ `Delegated agents must use the delegating agent cwd ${resolve5(controllerCwd)}`,
15747
16189
  operation
15748
16190
  );
15749
16191
  }
@@ -16047,8 +16489,11 @@ function createAgentController(pi, options) {
16047
16489
  const pendingStarts = /* @__PURE__ */ new Map();
16048
16490
  const resultWatchers = /* @__PURE__ */ new Map();
16049
16491
  const askWatchers = /* @__PURE__ */ new Map();
16492
+ const ownerMessageWatchers = /* @__PURE__ */ new Map();
16050
16493
  const resultDeliveryInFlight = /* @__PURE__ */ new Set();
16051
16494
  const askDeliveryInFlight = /* @__PURE__ */ new Set();
16495
+ const ownerMessageDeliveryInFlight = /* @__PURE__ */ new Set();
16496
+ const submittedOwnerMessages = /* @__PURE__ */ new Set();
16052
16497
  const resultDeliveryRetries = /* @__PURE__ */ new Map();
16053
16498
  const resultCleanupRetries = /* @__PURE__ */ new Map();
16054
16499
  const askDeliveryRetries = /* @__PURE__ */ new Map();
@@ -16863,6 +17308,8 @@ function createAgentController(pi, options) {
16863
17308
  watchResult(runtime, context, signal);
16864
17309
  if (runtime.activeRequestId === requestId)
16865
17310
  watchAsk(runtime, context, signal);
17311
+ if (runtime.activeRequestId === requestId)
17312
+ watchOwnerMessages(runtime, context, signal);
16866
17313
  }
16867
17314
  return requestId;
16868
17315
  } finally {
@@ -16963,7 +17410,7 @@ function createAgentController(pi, options) {
16963
17410
  if (kind === "steer" && agent.steerable !== true) {
16964
17411
  const current = readAgentState(runtime.mailboxPath);
16965
17412
  const pendingRequest = current ? readUnacknowledgedRequest(runtime.mailboxPath, current) : void 0;
16966
- const nextAction = current?.pendingAskId ? "Answer the pending ask_owner question with reply_agent." : controlState === "settling" || pendingRequest ? "Allow the current control or completion transition to finish." : controlState === "unknown" ? "Diagnose or recover the exact managed session before steering." : "Refresh list_agents after the underlying state changes and use steer_agent only when available_tools includes it.";
17413
+ const nextAction = current?.pendingAskId ? "Answer the pending await_owner question with reply_agent." : controlState === "settling" || pendingRequest ? "Allow the current control or completion transition to finish." : controlState === "unknown" ? "Diagnose or recover the exact managed session before steering." : "Refresh list_agents after the underlying state changes and use steer_agent only when available_tools includes it.";
16967
17414
  fail(
16968
17415
  "agent_busy",
16969
17416
  `Agent is not currently accepting steering: ${controlState}`,
@@ -17002,7 +17449,7 @@ function createAgentController(pi, options) {
17002
17449
  }
17003
17450
  if (!current?.activeRequestId || !askId || !ask)
17004
17451
  fail("agent_busy", "Agent is not waiting for an owner reply", "reply", {
17005
- nextAction: "Use reply_agent only for an outstanding ask_owner question; otherwise continue normal control or refresh with list_agents."
17452
+ nextAction: "Use reply_agent only for an outstanding await_owner question; otherwise continue normal control or refresh with list_agents."
17006
17453
  });
17007
17454
  if (ask.askId !== askId || ask.requestId !== current.activeRequestId || ask.runId !== current.runId || ask.ownerSessionId !== current.ownerSessionId || ask.workspaceId !== current.workspaceId || ask.agentLabel !== current.agentLabel || ask.paneId !== current.paneId || ask.piSessionId !== current.piSessionId)
17008
17455
  fail("target_not_found", "Agent ask identity did not match", "reply");
@@ -17346,6 +17793,8 @@ function createAgentController(pi, options) {
17346
17793
  ].some((id) => !!id && id !== requestId);
17347
17794
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17348
17795
  throw new Error("Managed agent changed before result cleanup");
17796
+ if (!clearConfirmedOwnerMessages(mailbox, current, context))
17797
+ throw new Error("Owner notification receipt is still unconfirmed");
17349
17798
  const presence = managedAgentPresence(
17350
17799
  current,
17351
17800
  await herdrSessionSnapshot(pi, context, signal)
@@ -17384,16 +17833,21 @@ function createAgentController(pi, options) {
17384
17833
  current = readAgentState(mailbox);
17385
17834
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17386
17835
  throw new Error("Managed agent changed during result cleanup");
17836
+ if (!clearConfirmedOwnerMessages(mailbox, current, context))
17837
+ throw new Error("Owner notification receipt is still unconfirmed");
17387
17838
  removeResult(mailbox, requestId);
17388
17839
  const after = readAgentState(mailbox);
17389
- if (sameIdentity2(after) && !after.activeRequestId && after.completedRequestId === requestId && !hasNewerWork(after))
17840
+ if (sameIdentity2(after) && !after.activeRequestId && after.completedRequestId === requestId && !hasNewerWork(after)) {
17841
+ if (!clearConfirmedOwnerMessages(mailbox, after, context))
17842
+ throw new Error("Owner notification receipt is still unconfirmed");
17390
17843
  removeAgentMailbox(mailbox);
17844
+ }
17391
17845
  invalidateRuntime(state.agentLabel);
17392
17846
  } finally {
17393
17847
  release?.();
17394
17848
  }
17395
17849
  };
17396
- const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false) => {
17850
+ const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false, preserveOwnerMessages = false) => {
17397
17851
  const state = snapshot2.state;
17398
17852
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
17399
17853
  const release = assignmentLockHeld ? void 0 : claimAssignmentLock3(mailbox, "close", {
@@ -17410,6 +17864,8 @@ function createAgentController(pi, options) {
17410
17864
  let current = readAgentState(mailbox);
17411
17865
  if (!current || !sameIdentity(current, state))
17412
17866
  fail("target_ambiguous", "Managed agent changed before close", "close");
17867
+ if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
17868
+ throw new Error("Owner notification receipt is still unconfirmed");
17413
17869
  if (hasDurableResult(mailbox, current))
17414
17870
  fail(
17415
17871
  "target_ambiguous",
@@ -17476,6 +17932,8 @@ function createAgentController(pi, options) {
17476
17932
  );
17477
17933
  }
17478
17934
  try {
17935
+ if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
17936
+ throw new Error("Owner notification receipt is still unconfirmed");
17479
17937
  removeAgentMailbox(mailbox);
17480
17938
  } catch (error2) {
17481
17939
  const message = `Agent pane closed but mailbox cleanup failed: ${String(error2)}`;
@@ -17547,7 +18005,14 @@ function createAgentController(pi, options) {
17547
18005
  deliveredRootResultId
17548
18006
  );
17549
18007
  try {
17550
- await closeSnapshot(context, child, signal, report);
18008
+ await closeSnapshot(
18009
+ context,
18010
+ child,
18011
+ signal,
18012
+ report,
18013
+ false,
18014
+ deliveredRootResultId !== void 0
18015
+ );
17551
18016
  if (readAgentState(
17552
18017
  agentMailboxPath(child.state.workspaceId, child.state.agentLabel)
17553
18018
  ))
@@ -17755,12 +18220,20 @@ function createAgentController(pi, options) {
17755
18220
  askWatchers.get(path)?.();
17756
18221
  askWatchers.delete(path);
17757
18222
  };
18223
+ const stopOwnerMessageWatcher = (runtime) => {
18224
+ ownerMessageWatchers.get(runtime.mailboxPath)?.();
18225
+ ownerMessageWatchers.delete(runtime.mailboxPath);
18226
+ };
17758
18227
  const invalidateRuntime = (label, workspaceId) => {
17759
18228
  const runtime = runtimes.get(label);
17760
18229
  if (!runtime || workspaceId !== void 0 && runtime.workspaceId !== workspaceId)
17761
18230
  return;
17762
18231
  stopResultWatcher(runtime);
17763
18232
  stopAskWatcher(runtime);
18233
+ stopOwnerMessageWatcher(runtime);
18234
+ for (const key of submittedOwnerMessages)
18235
+ if (key.startsWith(`${runtime.mailboxPath}:`))
18236
+ submittedOwnerMessages.delete(key);
17764
18237
  cancelAskRetries(runtime);
17765
18238
  for (const requestId of [
17766
18239
  runtime.activeRequestId,
@@ -17819,6 +18292,26 @@ function createAgentController(pi, options) {
17819
18292
  askWatchers.set(path, stop);
17820
18293
  check();
17821
18294
  };
18295
+ const watchOwnerMessages = (runtime, context, signal) => {
18296
+ stopOwnerMessageWatcher(runtime);
18297
+ const check = () => {
18298
+ if (!active || runtimes.get(runtime.label) !== runtime) return;
18299
+ if (!context.isIdle()) return;
18300
+ try {
18301
+ deliverOwnerMessages(runtime, context, signal);
18302
+ } catch (error2) {
18303
+ options.reportWatcherError(context, error2);
18304
+ }
18305
+ };
18306
+ const stop = observeMailbox(
18307
+ runtime.mailboxPath,
18308
+ (name) => name.startsWith("owner-message-") && name.endsWith(".json"),
18309
+ check,
18310
+ (error2) => options.reportWatcherError(context, error2)
18311
+ );
18312
+ ownerMessageWatchers.set(runtime.mailboxPath, stop);
18313
+ check();
18314
+ };
17822
18315
  const resultIdentity = (runtime, requestId) => ({
17823
18316
  runId: runtime.runId,
17824
18317
  requestId,
@@ -17897,6 +18390,7 @@ function createAgentController(pi, options) {
17897
18390
  } else validateIdentity(runtime, state);
17898
18391
  if (signal.aborted) return;
17899
18392
  runtimes.set(runtime.label, runtime);
18393
+ watchOwnerMessages(runtime, context, signal);
17900
18394
  if (runtime.activeRequestId) {
17901
18395
  watchResult(runtime, context, signal);
17902
18396
  watchAsk(runtime, context, signal);
@@ -18099,7 +18593,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18099
18593
  if (!delivered) {
18100
18594
  if (budget && !includeFanInMessage({ ...budget }, content))
18101
18595
  return false;
18102
- importResultBindings(pi, context, ask.resultBindings, "ask_owner");
18596
+ importResultBindings(pi, context, ask.resultBindings, "await_owner");
18103
18597
  options.sendAskMessage(context, ask, triggerTurn);
18104
18598
  if (budget) includeFanInMessage(budget, content);
18105
18599
  }
@@ -18115,11 +18609,114 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18115
18609
  askDeliveryInFlight.delete(key);
18116
18610
  }
18117
18611
  };
18612
+ const deliverOwnerMessages = (runtime, context, signal, triggerTurn = true, budget, receiptsOnly = false, retryMessageIds) => {
18613
+ if (!active || runtimes.get(runtime.label) !== runtime) return false;
18614
+ let submitted = false;
18615
+ let shouldTriggerTurn = triggerTurn;
18616
+ try {
18617
+ const state = readAgentState(runtime.mailboxPath);
18618
+ if (!state) return false;
18619
+ requireCompatibleBuild(
18620
+ options.build,
18621
+ state.build,
18622
+ "notify_owner",
18623
+ `Agent ${state.agentLabel}`
18624
+ );
18625
+ validateIdentity(runtime, state);
18626
+ if (context.sessionManager.getSessionId() !== runtime.ownerSessionId)
18627
+ return false;
18628
+ for (const ownerMessage of readOwnerMessages(runtime.mailboxPath)) {
18629
+ if (ownerMessage.runId !== runtime.runId || ownerMessage.ownerSessionId !== runtime.ownerSessionId || ownerMessage.workspaceId !== runtime.workspaceId || ownerMessage.agentLabel !== runtime.label || ownerMessage.paneId !== runtime.paneId || ownerMessage.piSessionId !== runtime.piSessionId || ownerMessage.requestId !== runtime.activeRequestId && ownerMessage.requestId !== runtime.completedRequestId)
18630
+ throw new Error(
18631
+ `Owner notification identity did not match Agent ${runtime.label}`
18632
+ );
18633
+ const messageKey = `${runtime.mailboxPath}:${ownerMessage.messageId}`;
18634
+ if (ownerMessageDeliveryInFlight.has(messageKey)) continue;
18635
+ ownerMessageDeliveryInFlight.add(messageKey);
18636
+ try {
18637
+ const entries = context.sessionManager.getEntries();
18638
+ if (hasDeliveredOwnerMessage(entries, ownerMessage)) {
18639
+ const release = claimAssignmentLock3(
18640
+ runtime.mailboxPath,
18641
+ "notify_owner",
18642
+ {
18643
+ label: runtime.label,
18644
+ paneId: runtime.paneId
18645
+ }
18646
+ );
18647
+ try {
18648
+ const current = readAgentState(runtime.mailboxPath);
18649
+ const matching = readOwnerMessages(runtime.mailboxPath).find(
18650
+ (record) => record.messageId === ownerMessage.messageId
18651
+ );
18652
+ if (!current || !sameIdentity(current, state) || !matching || !isDeepStrictEqual2(matching, ownerMessage))
18653
+ throw new Error(
18654
+ "Owner notification changed before receipt cleanup"
18655
+ );
18656
+ removeOwnerMessage(runtime.mailboxPath, ownerMessage.messageId);
18657
+ } finally {
18658
+ release();
18659
+ }
18660
+ submittedOwnerMessages.delete(messageKey);
18661
+ continue;
18662
+ }
18663
+ if (receiptsOnly) continue;
18664
+ if (retryMessageIds && !retryMessageIds.has(ownerMessage.messageId))
18665
+ continue;
18666
+ if (submittedOwnerMessages.has(messageKey)) continue;
18667
+ const content = `Agent ${ownerMessage.agentLabel} notification:
18668
+
18669
+ ${ownerMessage.text}`;
18670
+ if (budget && !includeFanInMessage({ ...budget }, content)) continue;
18671
+ importResultBindings(
18672
+ pi,
18673
+ context,
18674
+ ownerMessage.resultBindings,
18675
+ "notify_owner"
18676
+ );
18677
+ options.sendOwnerMessage(context, ownerMessage, shouldTriggerTurn);
18678
+ shouldTriggerTurn = false;
18679
+ submittedOwnerMessages.add(messageKey);
18680
+ if (budget) includeFanInMessage(budget, content);
18681
+ submitted = true;
18682
+ } finally {
18683
+ ownerMessageDeliveryInFlight.delete(messageKey);
18684
+ }
18685
+ }
18686
+ } catch (error2) {
18687
+ if (!(error2 instanceof OperationError) || error2.detail.category !== "incompatible_build")
18688
+ options.reportWatcherError(context, error2);
18689
+ }
18690
+ return submitted;
18691
+ };
18692
+ const clearConfirmedOwnerMessages = (mailbox, state, context) => {
18693
+ const ownerMessages = readOwnerMessages(mailbox);
18694
+ if (!ownerMessages.length) return true;
18695
+ if (context.sessionManager.getSessionId() !== state.ownerSessionId)
18696
+ throw new Error("Owner session changed before notification cleanup");
18697
+ const entries = context.sessionManager.getEntries();
18698
+ for (const ownerMessage of ownerMessages) {
18699
+ if (ownerMessage.runId !== state.runId || ownerMessage.ownerSessionId !== state.ownerSessionId || ownerMessage.workspaceId !== state.workspaceId || ownerMessage.agentLabel !== state.agentLabel || ownerMessage.paneId !== state.paneId || ownerMessage.piSessionId !== state.piSessionId || ![state.activeRequestId, state.completedRequestId].includes(
18700
+ ownerMessage.requestId
18701
+ ))
18702
+ throw new Error("Owner notification identity changed before cleanup");
18703
+ if (!hasDeliveredOwnerMessage(entries, ownerMessage)) return false;
18704
+ removeOwnerMessage(mailbox, ownerMessage.messageId);
18705
+ submittedOwnerMessages.delete(`${mailbox}:${ownerMessage.messageId}`);
18706
+ }
18707
+ return true;
18708
+ };
18118
18709
  const resultCleanupReady = (runtime, requestId, entries) => {
18119
18710
  if (!hasDeliveredResult(entries, resultIdentity(runtime, requestId)))
18120
18711
  return false;
18121
18712
  const state = readAgentState(runtime.mailboxPath);
18122
- return !!state && state.runId === runtime.runId && state.ownerSessionId === runtime.ownerSessionId && state.workspaceId === runtime.workspaceId && state.agentLabel === runtime.label && state.paneId === runtime.paneId && sameCwd(state.cwd, runtime.cwd) && state.piSessionId === runtime.piSessionId && state.piSessionFile === runtime.piSessionFile && !state.activeRequestId && state.completedRequestId === requestId;
18713
+ let notifications;
18714
+ try {
18715
+ notifications = readOwnerMessages(runtime.mailboxPath);
18716
+ } catch {
18717
+ return false;
18718
+ }
18719
+ return notifications.length === 0 && !!state && state.runId === runtime.runId && state.ownerSessionId === runtime.ownerSessionId && state.workspaceId === runtime.workspaceId && state.agentLabel === runtime.label && state.paneId === runtime.paneId && sameCwd(state.cwd, runtime.cwd) && state.piSessionId === runtime.piSessionId && state.piSessionFile === runtime.piSessionFile && !state.activeRequestId && state.completedRequestId === requestId;
18123
18720
  };
18124
18721
  const sameSessionPath3 = (left, right) => {
18125
18722
  if (left === right) return true;
@@ -18161,6 +18758,8 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18161
18758
  const ownsDescendants = listAgentStates().some(
18162
18759
  ({ state: candidate }) => candidate.workspaceId === state.workspaceId && candidate.ownerSessionId === state.piSessionId
18163
18760
  );
18761
+ deliverOwnerMessages(runtime, context, signal, false);
18762
+ if (readOwnerMessages(runtime.mailboxPath).length) return false;
18164
18763
  if (managedAgent && !ownsDescendants && listAgentStateIssues().length === 0)
18165
18764
  await finalizeDeliveredRoot(context, state, result.requestId, signal);
18166
18765
  else await closeCascade(context, state, signal, result.requestId);
@@ -18262,6 +18861,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18262
18861
  const persistedState = readAgentState(runtime.mailboxPath);
18263
18862
  const identityMismatch = runtimes.get(runtime.label) !== runtime || result.runId !== runtime.runId || result.ownerSessionId !== runtime.ownerSessionId || result.workspaceId !== runtime.workspaceId || result.agentLabel !== runtime.label || result.paneId !== runtime.paneId || result.rootSessionId !== runtime.rootSessionId || result.rootSessionId !== persistedState?.rootSessionId || result.requestId !== (runtime.activeRequestId ?? runtime.completedRequestId);
18264
18863
  if (identityMismatch) return false;
18864
+ deliverOwnerMessages(runtime, context, signal, false, budget);
18265
18865
  let entries = context.sessionManager.getEntries();
18266
18866
  const evidenceKey = JSON.stringify(Object.values(expected));
18267
18867
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
@@ -18459,6 +19059,8 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18459
19059
  let submitted = 0;
18460
19060
  for (const runtime of runtimes.values()) {
18461
19061
  if (runtime.ownerSessionId !== ownerId || !active) continue;
19062
+ if (deliverOwnerMessages(runtime, context, context.signal, false, budget))
19063
+ submitted++;
18462
19064
  const requestId = runtime.activeRequestId ?? runtime.completedRequestId;
18463
19065
  if (requestId) {
18464
19066
  try {
@@ -18691,6 +19293,21 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18691
19293
  ctx.sessionManager.getSessionId(),
18692
19294
  resumed
18693
19295
  );
19296
+ const ownerEntries = ctx.sessionManager.getBranch();
19297
+ const latestAccepted = acceptedAssignmentReceipts(
19298
+ ownerEntries,
19299
+ ctx.sessionManager.getSessionId(),
19300
+ resumed
19301
+ ).at(-1);
19302
+ const terminalResults = latestAccepted ? ownerEntries.flatMap((entry, index) => {
19303
+ const details = agentResultDetails(entry);
19304
+ return details?.requestId === latestAccepted.requestId ? [{ index, details }] : [];
19305
+ }) : [];
19306
+ const terminal = terminalResults[0];
19307
+ const historicalTerminal = states.length === 0 && latestAccepted !== void 0 && terminalResults.length === 1 && terminal.index > latestAccepted.index && terminal.details.status === "failed" && terminal.details.error?.code === "aborted" && terminal.details.ownerSessionId === ctx.sessionManager.getSessionId() && terminal.details.piSessionId === resumed.id && typeof terminal.details.piSessionFile === "string" && samePersistedSessionPath(
19308
+ terminal.details.piSessionFile,
19309
+ resumed.path
19310
+ ) && terminal.details.agentLabel === resumed.label && terminal.details.agentDefinition === resumed.definition && validId(terminal.details.runId) && typeof terminal.details.workspaceId === "string" && terminal.details.workspaceId.length > 0 && typeof terminal.details.paneId === "string" && terminal.details.paneId.length > 0;
18694
19311
  for (const agent of snapshot2.liveAgents)
18695
19312
  if (herdrSessionsMatch(
18696
19313
  agent,
@@ -18700,6 +19317,27 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18700
19317
  ) && !statePanes.has(
18701
19318
  `${agent.workspace_id ?? ""}\0${agent.pane_id ?? ""}`
18702
19319
  )) {
19320
+ if (historicalTerminal && terminal.details.workspaceId === agent.workspace_id && terminal.details.paneId === agent.pane_id && agent.name === herdrAgentAlias(
19321
+ terminal.details.workspaceId,
19322
+ resumed.label,
19323
+ terminal.details.runId
19324
+ ) && typeof agent.pane_id === "string") {
19325
+ try {
19326
+ const observed = await paneProcess(
19327
+ pi,
19328
+ ctx,
19329
+ agent.pane_id,
19330
+ signal,
19331
+ void 0,
19332
+ true
19333
+ );
19334
+ if (observed && settledShell(observed, observed)) continue;
19335
+ } catch (error2) {
19336
+ if (error2 instanceof OperationError && error2.detail.operation === "herdr pane process-info" && error2.detail.details?.herdrCode === "pane_not_found")
19337
+ continue;
19338
+ throw error2;
19339
+ }
19340
+ }
18703
19341
  if (closedReceipt && closedReceipt.workspace_id === agent.workspace_id && closedReceipt.pane_id === agent.pane_id && typeof agent.pane_id === "string") {
18704
19342
  try {
18705
19343
  await paneProcess(pi, ctx, agent.pane_id, signal);
@@ -18850,7 +19488,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18850
19488
  const existingPaths = new Set(
18851
19489
  requiredEvidence.filter(
18852
19490
  (entry) => !("result" in entry)
18853
- ).map((entry) => resolve4(entry.path))
19491
+ ).map((entry) => resolve5(entry.path))
18854
19492
  );
18855
19493
  const existingRefs = new Set(
18856
19494
  requiredEvidence.filter(
@@ -18864,7 +19502,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18864
19502
  if (typeof file2 === "string") {
18865
19503
  let canonicalPath;
18866
19504
  try {
18867
- canonicalPath = realpathSync4(resolve4(ctx.cwd, file2));
19505
+ canonicalPath = realpathSync4(resolve5(ctx.cwd, file2));
18868
19506
  } catch {
18869
19507
  }
18870
19508
  if (canonicalPath && (existingPaths.has(canonicalPath) || retainedPaths.has(canonicalPath)))
@@ -18992,7 +19630,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18992
19630
  )).map((file2) => {
18993
19631
  if (typeof file2 !== "string") return file2;
18994
19632
  try {
18995
- const path = realpathSync4(resolve4(ctx.cwd, file2));
19633
+ const path = realpathSync4(resolve5(ctx.cwd, file2));
18996
19634
  const result = requiredEvidence.find((entry) => {
18997
19635
  if (!("result" in entry)) return false;
18998
19636
  const resultPath2 = resolveResultRef(entry.result.canonicalRef);
@@ -19340,57 +19978,71 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19340
19978
  }
19341
19979
  if (!ownerDisplay)
19342
19980
  throw new Error("Verified direct owner role is unavailable");
19981
+ let reservedChildSessionId;
19343
19982
  if (p.action === "delegate") {
19344
19983
  const registrations = /* @__PURE__ */ new Map();
19345
19984
  let open = true;
19985
+ let preparing = true;
19346
19986
  let registrationError;
19347
- pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
19348
- protocol: 1,
19349
- phase: "prepare",
19350
- context: ctx,
19351
- agent: label,
19352
- register(id, prepare) {
19353
- if (!open)
19354
- throw new Error(
19355
- "Managed-agent bootstrap registration is closed"
19356
- );
19357
- if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(id)) {
19358
- registrationError ??= new Error(
19359
- "Invalid managed-agent bootstrap participant ID"
19360
- );
19361
- return;
19362
- }
19363
- if (registrations.has(id)) {
19364
- registrationError ??= new Error(
19365
- `Duplicate managed-agent bootstrap participant ID: ${id}`
19366
- );
19367
- 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);
19368
20025
  }
19369
- if (typeof prepare !== "function") {
19370
- registrationError ??= new Error(
19371
- "Invalid managed-agent bootstrap prepare callback"
19372
- );
19373
- 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
+ });
19374
20041
  }
19375
- registrations.set(id, prepare);
19376
- }
19377
- });
19378
- open = false;
19379
- if (registrationError) throw registrationError;
19380
- const participants = [];
19381
- for (const [id, prepare] of registrations) {
19382
- const result = await prepare();
19383
- if (result !== void 0) {
19384
- if (!result || typeof result.payload !== "string" || result.commit !== void 0 && typeof result.commit !== "function")
19385
- throw new Error(
19386
- `Invalid preparation from managed-agent bootstrap participant "${id}"`
19387
- );
19388
- participants.push({ id, payload: result.payload });
19389
- preparedBootstrap.push({
19390
- id,
19391
- ...result.commit ? { commit: result.commit } : {}
19392
- });
19393
20042
  }
20043
+ } finally {
20044
+ open = false;
20045
+ preparing = false;
19394
20046
  }
19395
20047
  if (participants.length)
19396
20048
  writeAgentBootstrap(mailbox, {
@@ -19400,6 +20052,7 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19400
20052
  ownerSessionId: owner,
19401
20053
  workspaceId,
19402
20054
  agentLabel: label,
20055
+ ...reservedChildSessionId ? { childSessionId: reservedChildSessionId } : {},
19403
20056
  participants
19404
20057
  });
19405
20058
  }
@@ -19458,7 +20111,11 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
19458
20111
  extensionPath: options.extensionPath,
19459
20112
  placement,
19460
20113
  ...placementRevalidator ? { placementRevalidator } : {},
19461
- agentArgs: [...launchArgs, ...sessionArgs],
20114
+ agentArgs: [
20115
+ ...launchArgs,
20116
+ ...reservedChildSessionId && preparedBootstrap.length ? ["--session-id", reservedChildSessionId] : [],
20117
+ ...sessionArgs
20118
+ ],
19462
20119
  env,
19463
20120
  signal
19464
20121
  });
@@ -19567,6 +20224,12 @@ ${result.stderr ?? ""}`.trim(),
19567
20224
  "Managed Agent state identity did not match startup",
19568
20225
  p.action
19569
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
+ );
19570
20233
  requireCompatibleBuild(
19571
20234
  options.build,
19572
20235
  state.build,
@@ -20325,7 +20988,7 @@ ${result.stderr ?? ""}`.trim(),
20325
20988
  ...agentTool,
20326
20989
  name: "reply_agent",
20327
20990
  label: "reply agent",
20328
- description: "Answer the exact pending ask_owner question for a direct Agent.",
20991
+ description: "Answer the exact pending await_owner question for a direct Agent.",
20329
20992
  parameters: agentMessageParameters,
20330
20993
  promptSnippet: void 0,
20331
20994
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
@@ -20503,11 +21166,11 @@ ${result.stderr ?? ""}`.trim(),
20503
21166
  return [];
20504
21167
  }
20505
21168
  });
20506
- const publishAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
21169
+ const prepareAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
20507
21170
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
20508
21171
  const current = readAgentState(mailbox);
20509
21172
  if (!current || !sameIdentity(current, state) || current.ownerSessionId !== ctx.sessionManager.getSessionId())
20510
- return false;
21173
+ return void 0;
20511
21174
  const currentHandoff = readUnacknowledgedRequest(mailbox, current);
20512
21175
  const requestIds = [
20513
21176
  current.completedRequestId,
@@ -20516,12 +21179,12 @@ ${result.stderr ?? ""}`.trim(),
20516
21179
  ].filter((value2) => !!value2);
20517
21180
  try {
20518
21181
  if (requestIds.some((requestId) => readResult(mailbox, requestId)))
20519
- return false;
21182
+ return void 0;
20520
21183
  } catch {
20521
- return false;
21184
+ return void 0;
20522
21185
  }
20523
21186
  const latest = readAgentState(mailbox);
20524
- if (!latest || !sameIdentity(latest, current)) return false;
21187
+ if (!latest || !sameIdentity(latest, current)) return void 0;
20525
21188
  const latestHandoff = readUnacknowledgedRequest(mailbox, latest);
20526
21189
  const latestRequestId = latest.completedRequestId ?? latest.activeRequestId ?? latestHandoff?.requestId;
20527
21190
  const latestRequestIds = [
@@ -20531,52 +21194,43 @@ ${result.stderr ?? ""}`.trim(),
20531
21194
  ].filter((value2) => !!value2);
20532
21195
  try {
20533
21196
  if (latestRequestIds.some((requestId) => readResult(mailbox, requestId)))
20534
- return false;
20535
- } catch {
20536
- return false;
20537
- }
20538
- if (signal.aborted || !ctx.isIdle()) return false;
20539
- try {
20540
- if (signal.aborted || !ctx.isIdle()) return false;
20541
- const stopAvailable = availableActions.includes("stop");
20542
- pi.sendMessage(
20543
- {
20544
- customType: "pi-herdsman-agent-lost",
20545
- content: [
20546
- `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
20547
- ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
20548
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20549
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
20550
- "",
20551
- "Use read_agent_transcript only when persisted work materially affects the recovery decision.",
20552
- ...stopAvailable ? [
20553
- "Use stop_agent to stop this lost generation before replacing it or continuing its saved session."
20554
- ] : [
20555
- "stop_agent is not currently available; resolve the condition blocking its stop preflight before replacing or continuing it."
20556
- ],
20557
- "Physical disappearance is not task completion."
20558
- ].join("\n"),
20559
- display: true,
20560
- details: {
20561
- runId: current.runId,
20562
- ownerSessionId: current.ownerSessionId,
20563
- workspaceId: current.workspaceId,
20564
- agentLabel: current.agentLabel,
20565
- paneId: current.paneId,
20566
- piSessionId: current.piSessionId,
20567
- piSessionFile: current.piSessionFile,
20568
- agentDefinition: current.agentDefinition ?? snapshotAgentDefinition ?? "unknown",
20569
- requestId: latestRequestId,
20570
- availableActions,
20571
- nextReminderMs
20572
- }
20573
- },
20574
- { triggerTurn: true }
20575
- );
20576
- return true;
21197
+ return void 0;
20577
21198
  } catch {
20578
- return false;
21199
+ return void 0;
20579
21200
  }
21201
+ if (signal.aborted || !ctx.isIdle()) return void 0;
21202
+ const stopAvailable = availableActions.includes("stop");
21203
+ return {
21204
+ customType: "pi-herdsman-agent-lost",
21205
+ content: [
21206
+ `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
21207
+ ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
21208
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21209
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
21210
+ "",
21211
+ "Use read_agent_transcript only when persisted work materially affects the recovery decision.",
21212
+ ...stopAvailable ? [
21213
+ "Use stop_agent to stop this lost generation before replacing it or continuing its saved session."
21214
+ ] : [
21215
+ "stop_agent is not currently available; resolve the condition blocking its stop preflight before replacing or continuing it."
21216
+ ],
21217
+ "Physical disappearance is not task completion."
21218
+ ].join("\n"),
21219
+ display: true,
21220
+ details: {
21221
+ runId: current.runId,
21222
+ ownerSessionId: current.ownerSessionId,
21223
+ workspaceId: current.workspaceId,
21224
+ agentLabel: current.agentLabel,
21225
+ paneId: current.paneId,
21226
+ piSessionId: current.piSessionId,
21227
+ piSessionFile: current.piSessionFile,
21228
+ agentDefinition: current.agentDefinition ?? snapshotAgentDefinition ?? "unknown",
21229
+ requestId: latestRequestId,
21230
+ availableActions,
21231
+ nextReminderMs
21232
+ }
21233
+ };
20580
21234
  };
20581
21235
  const scanAgentHealth = async (ctx, signal, generation) => {
20582
21236
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
@@ -20596,7 +21250,14 @@ ${result.stderr ?? ""}`.trim(),
20596
21250
  );
20597
21251
  for (const runId of attentionReminders.keys())
20598
21252
  if (!ownedRuns.has(runId)) attentionReminders.delete(runId);
20599
- let published = false;
21253
+ const pending = [];
21254
+ const budget = recipientFanInBudget();
21255
+ let initialStaleInspectionUsed = false;
21256
+ const stageAttention = (item) => {
21257
+ if (!includeFanInMessage(budget, item.message.content)) return false;
21258
+ pending.push(item);
21259
+ return true;
21260
+ };
20600
21261
  for (const agent of snapshot2.agents) {
20601
21262
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20602
21263
  return;
@@ -20611,107 +21272,125 @@ ${result.stderr ?? ""}`.trim(),
20611
21272
  if (state.resultError) {
20612
21273
  const error2 = state.resultError;
20613
21274
  const episode2 = `result-error:${error2.failedAt}:${error2.requestId}`;
20614
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21275
+ if (!attentionDue(state.runId, episode2, now)) continue;
20615
21276
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20616
21277
  const current2 = currentOwnedState(state, ownerSessionId);
20617
21278
  if (!current2?.resultError || current2.resultError.failedAt !== error2.failedAt || current2.resultError.requestId !== error2.requestId || !ctx.isIdle())
20618
21279
  continue;
20619
- try {
20620
- if (!ctx.isIdle()) continue;
20621
- pi.sendMessage(
20622
- {
20623
- customType: "pi-herdsman-agent-attention",
20624
- content: [
20625
- `Agent ${current2.agentLabel} could not persist its terminal result.`,
20626
- `Request: ${error2.requestId}`,
20627
- `Failure: ${error2.message}`,
20628
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20629
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20630
- "",
20631
- error2.nextAction,
20632
- "Do not start overlapping replacement work while this assignment remains unresolved."
20633
- ].join("\n"),
20634
- display: true,
20635
- details: {
20636
- reason: "result_error",
20637
- summary: error2.message,
20638
- runId: current2.runId,
20639
- requestId: error2.requestId,
20640
- ownerSessionId: current2.ownerSessionId,
20641
- workspaceId: current2.workspaceId,
20642
- agentLabel: current2.agentLabel,
20643
- paneId: current2.paneId,
20644
- piSessionId: current2.piSessionId,
20645
- availableActions,
20646
- nextReminderMs: intervalMs2,
20647
- nextAction: error2.nextAction
20648
- }
20649
- },
20650
- { triggerTurn: true }
20651
- );
20652
- recordAttention(state.runId, episode2, intervalMs2);
20653
- published = true;
20654
- } catch {
20655
- }
21280
+ stageAttention({
21281
+ state,
21282
+ condition: "result_error",
21283
+ message: {
21284
+ customType: "pi-herdsman-agent-attention",
21285
+ content: [
21286
+ `Agent ${current2.agentLabel} could not persist its terminal result.`,
21287
+ `Request: ${error2.requestId}`,
21288
+ `Failure: ${error2.message}`,
21289
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21290
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
21291
+ "",
21292
+ error2.nextAction,
21293
+ "Do not start overlapping replacement work while this assignment remains unresolved."
21294
+ ].join("\n"),
21295
+ display: true,
21296
+ details: {
21297
+ reason: "result_error",
21298
+ summary: error2.message,
21299
+ runId: current2.runId,
21300
+ requestId: error2.requestId,
21301
+ ownerSessionId: current2.ownerSessionId,
21302
+ workspaceId: current2.workspaceId,
21303
+ agentLabel: current2.agentLabel,
21304
+ paneId: current2.paneId,
21305
+ piSessionId: current2.piSessionId,
21306
+ availableActions,
21307
+ nextReminderMs: intervalMs2,
21308
+ nextAction: error2.nextAction
21309
+ }
21310
+ },
21311
+ stillEligible: () => {
21312
+ const latest2 = currentOwnedState(state, ownerSessionId);
21313
+ if (!latest2?.resultError || latest2.resultError.failedAt !== error2.failedAt || latest2.resultError.requestId !== error2.requestId)
21314
+ return false;
21315
+ try {
21316
+ return !readResult(
21317
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
21318
+ error2.requestId
21319
+ );
21320
+ } catch {
21321
+ return false;
21322
+ }
21323
+ },
21324
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21325
+ });
20656
21326
  continue;
20657
21327
  }
20658
21328
  if (agent.presence.kind === "lost" && !state.completedRequestId) {
20659
21329
  const episode2 = "lost";
20660
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21330
+ if (!attentionDue(state.runId, episode2, now)) continue;
20661
21331
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20662
- if (publishAgentLoss(
21332
+ const message = prepareAgentLoss(
20663
21333
  ctx,
20664
21334
  state,
20665
21335
  agent.agentDefinition,
20666
21336
  availableActions,
20667
21337
  intervalMs2,
20668
21338
  signal
20669
- )) {
20670
- recordAttention(state.runId, episode2, intervalMs2);
20671
- published = true;
20672
- }
21339
+ );
21340
+ if (message)
21341
+ stageAttention({
21342
+ state,
21343
+ condition: "lost",
21344
+ message,
21345
+ stillEligible: () => !!prepareAgentLoss(
21346
+ ctx,
21347
+ state,
21348
+ agent.agentDefinition,
21349
+ availableActions,
21350
+ intervalMs2,
21351
+ signal
21352
+ ),
21353
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21354
+ });
20673
21355
  continue;
20674
21356
  }
20675
21357
  if (agent.presence.kind === "unknown") {
20676
21358
  const episode2 = "unknown";
20677
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21359
+ if (!attentionDue(state.runId, episode2, now)) continue;
20678
21360
  const current2 = currentOwnedState(state, ownerSessionId);
20679
21361
  if (!current2 || !ctx.isIdle()) continue;
20680
- try {
20681
- if (!ctx.isIdle()) continue;
20682
- pi.sendMessage(
20683
- {
20684
- customType: "pi-herdsman-agent-attention",
20685
- content: [
20686
- `Agent ${current2.agentLabel} has unresolved physical identity.`,
20687
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20688
- "",
20689
- "No safe direct control action is currently available.",
20690
- "Do not infer loss, guess a pane or process, or target ambiguous execution.",
20691
- "Herdsman will continue reconciling physical identity automatically."
20692
- ].join("\n"),
20693
- display: true,
20694
- details: {
20695
- reason: "unknown",
20696
- runId: current2.runId,
20697
- ownerSessionId: current2.ownerSessionId,
20698
- workspaceId: current2.workspaceId,
20699
- agentLabel: current2.agentLabel,
20700
- paneId: current2.paneId,
20701
- piSessionId: current2.piSessionId,
20702
- availableActions
20703
- }
20704
- },
20705
- { triggerTurn: true }
20706
- );
20707
- attentionReminders.set(state.runId, {
21362
+ stageAttention({
21363
+ state,
21364
+ condition: "unknown",
21365
+ message: {
21366
+ customType: "pi-herdsman-agent-attention",
21367
+ content: [
21368
+ `Agent ${current2.agentLabel} has unresolved physical identity.`,
21369
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21370
+ "",
21371
+ "No safe direct control action is currently available.",
21372
+ "Do not infer loss, guess a pane or process, or target ambiguous execution.",
21373
+ "Herdsman will continue reconciling physical identity automatically."
21374
+ ].join("\n"),
21375
+ display: true,
21376
+ details: {
21377
+ reason: "unknown",
21378
+ runId: current2.runId,
21379
+ ownerSessionId: current2.ownerSessionId,
21380
+ workspaceId: current2.workspaceId,
21381
+ agentLabel: current2.agentLabel,
21382
+ paneId: current2.paneId,
21383
+ piSessionId: current2.piSessionId,
21384
+ availableActions
21385
+ }
21386
+ },
21387
+ stillEligible: () => !!currentOwnedState(state, ownerSessionId),
21388
+ onSubmitted: () => attentionReminders.set(state.runId, {
20708
21389
  episode: episode2,
20709
21390
  intervalMs: Number.POSITIVE_INFINITY,
20710
21391
  nextAt: Number.POSITIVE_INFINITY
20711
- });
20712
- published = true;
20713
- } catch {
20714
- }
21392
+ })
21393
+ });
20715
21394
  continue;
20716
21395
  }
20717
21396
  if (state.pendingAskId) {
@@ -20734,102 +21413,117 @@ ${result.stderr ?? ""}`.trim(),
20734
21413
  });
20735
21414
  continue;
20736
21415
  }
20737
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21416
+ if (!attentionDue(state.runId, episode2, now)) continue;
20738
21417
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20739
21418
  const current2 = currentOwnedState(state, ownerSessionId);
20740
21419
  if (!current2?.pendingAskId || !ctx.isIdle()) continue;
21420
+ let currentAsk;
20741
21421
  try {
20742
- const currentAsk = readPendingAsk(
21422
+ currentAsk = readPendingAsk(
20743
21423
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20744
21424
  current2
20745
21425
  );
20746
- if (!currentAsk || currentAsk.askId !== ask.askId || !hasDeliveredAsk(ctx.sessionManager.getBranch(), currentAsk))
20747
- continue;
20748
- if (!ctx.isIdle()) continue;
20749
- pi.sendMessage(
20750
- {
20751
- customType: "pi-herdsman-agent-ask",
20752
- content: [
20753
- `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
20754
- "",
20755
- currentAsk.question,
20756
- "",
20757
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20758
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20759
- "",
20760
- "Use reply_agent to reply to this exact pending ask if the required decision is available.",
20761
- "Do not delegate around or duplicate the blocked assignment."
20762
- ].join("\n"),
20763
- display: true,
20764
- details: {
20765
- askId: currentAsk.askId,
20766
- question: currentAsk.question,
20767
- requestId: currentAsk.requestId,
20768
- runId: currentAsk.runId,
20769
- agentLabel: currentAsk.agentLabel,
20770
- workspaceId: currentAsk.workspaceId,
20771
- paneId: currentAsk.paneId,
20772
- piSessionId: currentAsk.piSessionId,
20773
- availableActions,
20774
- nextReminderMs: intervalMs2
20775
- }
20776
- },
20777
- { triggerTurn: true }
20778
- );
20779
- recordAttention(state.runId, episode2, intervalMs2);
20780
- published = true;
20781
21426
  } catch {
21427
+ continue;
20782
21428
  }
20783
- } else {
20784
- attentionReminders.delete(state.runId);
20785
- }
20786
- continue;
20787
- }
20788
- if (agent.presence.kind === "live" && agent.lifecycleState === "blocked" && state.activeRequestId) {
20789
- const episode2 = `blocked:${state.activeRequestId}`;
20790
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20791
- const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20792
- const current2 = currentOwnedState(state, ownerSessionId);
20793
- if (!current2?.activeRequestId || current2.pendingAskId || !ctx.isIdle())
20794
- continue;
20795
- try {
20796
- if (!ctx.isIdle()) continue;
20797
- pi.sendMessage(
20798
- {
20799
- customType: "pi-herdsman-agent-attention",
21429
+ if (!currentAsk || currentAsk.askId !== ask.askId || !hasDeliveredAsk(ctx.sessionManager.getBranch(), currentAsk))
21430
+ continue;
21431
+ stageAttention({
21432
+ state,
21433
+ condition: "ask",
21434
+ message: {
21435
+ customType: "pi-herdsman-agent-ask",
20800
21436
  content: [
20801
- `Agent ${current2.agentLabel} is blocked in its live runtime, but no Herdsman ask_owner question exists.`,
20802
- `Request: ${current2.activeRequestId}`,
21437
+ `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
21438
+ "",
21439
+ currentAsk.question,
21440
+ "",
20803
21441
  `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20804
21442
  `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20805
21443
  "",
20806
- "Use read_agent_transcript for persisted conversation/tool evidence.",
20807
- "Use inspect_agent only when the live blocking state matters.",
20808
- "Do not invent an owner reply or send guessed terminal input.",
20809
- "Use stop_agent only when abandoning the assignment is the intended recovery."
21444
+ "Use reply_agent to reply to this exact pending ask if the required decision is available.",
21445
+ "Do not delegate around or duplicate the blocked assignment."
20810
21446
  ].join("\n"),
20811
21447
  display: true,
20812
21448
  details: {
20813
- reason: "blocked",
20814
- runId: current2.runId,
20815
- requestId: current2.activeRequestId,
20816
- ownerSessionId: current2.ownerSessionId,
20817
- workspaceId: current2.workspaceId,
20818
- agentLabel: current2.agentLabel,
20819
- paneId: current2.paneId,
20820
- piSessionId: current2.piSessionId,
21449
+ askId: currentAsk.askId,
21450
+ question: currentAsk.question,
21451
+ requestId: currentAsk.requestId,
21452
+ runId: currentAsk.runId,
21453
+ agentLabel: currentAsk.agentLabel,
21454
+ workspaceId: currentAsk.workspaceId,
21455
+ paneId: currentAsk.paneId,
21456
+ piSessionId: currentAsk.piSessionId,
20821
21457
  availableActions,
20822
21458
  nextReminderMs: intervalMs2
20823
21459
  }
20824
21460
  },
20825
- { triggerTurn: true }
20826
- );
20827
- recordAttention(state.runId, episode2, intervalMs2);
20828
- published = true;
20829
- } catch {
21461
+ stillEligible: () => {
21462
+ const latest2 = currentOwnedState(state, ownerSessionId);
21463
+ if (!latest2?.pendingAskId || latest2.pendingAskId !== ask.askId)
21464
+ return false;
21465
+ try {
21466
+ const latestAsk = readPendingAsk(
21467
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
21468
+ latest2
21469
+ );
21470
+ return !!latestAsk && latestAsk.askId === ask.askId && hasDeliveredAsk(ctx.sessionManager.getBranch(), latestAsk);
21471
+ } catch {
21472
+ return false;
21473
+ }
21474
+ },
21475
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21476
+ });
21477
+ } else {
21478
+ attentionReminders.delete(state.runId);
20830
21479
  }
20831
21480
  continue;
20832
21481
  }
21482
+ if (agent.presence.kind === "live" && agent.lifecycleState === "blocked" && state.activeRequestId) {
21483
+ const episode2 = `blocked:${state.activeRequestId}`;
21484
+ if (!attentionDue(state.runId, episode2, now)) continue;
21485
+ const intervalMs2 = nextAttentionInterval(state.runId, episode2);
21486
+ const current2 = currentOwnedState(state, ownerSessionId);
21487
+ if (!current2?.activeRequestId || current2.pendingAskId || !ctx.isIdle())
21488
+ continue;
21489
+ stageAttention({
21490
+ state,
21491
+ condition: "blocked",
21492
+ message: {
21493
+ customType: "pi-herdsman-agent-attention",
21494
+ content: [
21495
+ `Agent ${current2.agentLabel} is blocked in its live runtime, but no Herdsman await_owner question exists.`,
21496
+ `Request: ${current2.activeRequestId}`,
21497
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21498
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
21499
+ "",
21500
+ "Use read_agent_transcript for persisted conversation/tool evidence.",
21501
+ "Use inspect_agent only when the live blocking state matters.",
21502
+ "Do not invent an owner reply or send guessed terminal input.",
21503
+ "Use stop_agent only when abandoning the assignment is the intended recovery."
21504
+ ].join("\n"),
21505
+ display: true,
21506
+ details: {
21507
+ reason: "blocked",
21508
+ runId: current2.runId,
21509
+ requestId: current2.activeRequestId,
21510
+ ownerSessionId: current2.ownerSessionId,
21511
+ workspaceId: current2.workspaceId,
21512
+ agentLabel: current2.agentLabel,
21513
+ paneId: current2.paneId,
21514
+ piSessionId: current2.piSessionId,
21515
+ availableActions,
21516
+ nextReminderMs: intervalMs2
21517
+ }
21518
+ },
21519
+ stillEligible: () => {
21520
+ const latest2 = currentOwnedState(state, ownerSessionId);
21521
+ return !!latest2?.activeRequestId && latest2.activeRequestId === state.activeRequestId && !latest2.pendingAskId;
21522
+ },
21523
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21524
+ });
21525
+ continue;
21526
+ }
20833
21527
  let request;
20834
21528
  try {
20835
21529
  request = readUnacknowledgedRequest(
@@ -20841,51 +21535,65 @@ ${result.stderr ?? ""}`.trim(),
20841
21535
  }
20842
21536
  if (request && request.createdAt <= now && now - request.createdAt >= HEALTH_STALE_AFTER_MS) {
20843
21537
  const episode2 = `handoff:${request.requestId}`;
20844
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21538
+ if (!attentionDue(state.runId, episode2, now)) continue;
20845
21539
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20846
21540
  const current2 = currentOwnedState(state, ownerSessionId);
20847
21541
  if (!current2 || !ctx.isIdle()) continue;
21542
+ let currentRequest;
20848
21543
  try {
20849
- const currentRequest = readUnacknowledgedRequest(
21544
+ currentRequest = readUnacknowledgedRequest(
20850
21545
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20851
21546
  current2
20852
21547
  );
20853
- if (!currentRequest || currentRequest.requestId !== request.requestId || !ctx.isIdle())
20854
- continue;
20855
- pi.sendMessage(
20856
- {
20857
- customType: "pi-herdsman-agent-attention",
20858
- content: [
20859
- `Agent ${current2.agentLabel} still has an unacknowledged ${currentRequest.kind} request.`,
20860
- `Request: ${currentRequest.requestId}`,
20861
- `Pending for: ${formatHealthAttentionDuration(now - currentRequest.createdAt)}`,
20862
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20863
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20864
- "",
20865
- "The durable request is still retained.",
20866
- "Do not submit the same intent again: acknowledgement timeout does not prove non-delivery.",
20867
- "Herdsman will continue reconciling this exact request."
20868
- ].join("\n"),
20869
- display: true,
20870
- details: {
20871
- reason: "handoff",
20872
- runId: current2.runId,
20873
- requestId: currentRequest.requestId,
20874
- ownerSessionId: current2.ownerSessionId,
20875
- workspaceId: current2.workspaceId,
20876
- agentLabel: current2.agentLabel,
20877
- paneId: current2.paneId,
20878
- piSessionId: current2.piSessionId,
20879
- availableActions,
20880
- nextReminderMs: intervalMs2
20881
- }
20882
- },
20883
- { triggerTurn: true }
20884
- );
20885
- recordAttention(state.runId, episode2, intervalMs2);
20886
- published = true;
20887
21548
  } catch {
21549
+ continue;
20888
21550
  }
21551
+ if (!currentRequest || currentRequest.requestId !== request.requestId || !ctx.isIdle())
21552
+ continue;
21553
+ stageAttention({
21554
+ state,
21555
+ condition: "handoff",
21556
+ message: {
21557
+ customType: "pi-herdsman-agent-attention",
21558
+ content: [
21559
+ `Agent ${current2.agentLabel} still has an unacknowledged ${currentRequest.kind} request.`,
21560
+ `Request: ${currentRequest.requestId}`,
21561
+ `Pending for: ${formatHealthAttentionDuration(now - currentRequest.createdAt)}`,
21562
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21563
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
21564
+ "",
21565
+ "The durable request is still retained.",
21566
+ "Do not submit the same intent again: acknowledgement timeout does not prove non-delivery.",
21567
+ "Herdsman will continue reconciling this exact request."
21568
+ ].join("\n"),
21569
+ display: true,
21570
+ details: {
21571
+ reason: "handoff",
21572
+ runId: current2.runId,
21573
+ requestId: currentRequest.requestId,
21574
+ ownerSessionId: current2.ownerSessionId,
21575
+ workspaceId: current2.workspaceId,
21576
+ agentLabel: current2.agentLabel,
21577
+ paneId: current2.paneId,
21578
+ piSessionId: current2.piSessionId,
21579
+ availableActions,
21580
+ nextReminderMs: intervalMs2
21581
+ }
21582
+ },
21583
+ stillEligible: () => {
21584
+ const latest2 = currentOwnedState(state, ownerSessionId);
21585
+ if (!latest2) return false;
21586
+ try {
21587
+ return readUnacknowledgedRequest(
21588
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
21589
+ latest2
21590
+ )?.requestId === request.requestId;
21591
+ } catch {
21592
+ return false;
21593
+ }
21594
+ },
21595
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21596
+ });
20889
21597
  continue;
20890
21598
  }
20891
21599
  if (agent.presence.kind !== "live" || listed.state !== "working" || !state.activeRequestId || state.lastActivityAt === void 0 || state.lastActivityAt > now || now - state.lastActivityAt < HEALTH_STALE_AFTER_MS) {
@@ -20893,7 +21601,7 @@ ${result.stderr ?? ""}`.trim(),
20893
21601
  continue;
20894
21602
  }
20895
21603
  const episode = `stale:${state.activeRequestId}:${state.lastActivityAt}`;
20896
- if (published || !attentionDue(state.runId, episode, now)) continue;
21604
+ if (!attentionDue(state.runId, episode, now)) continue;
20897
21605
  const firstAttention = attentionReminders.get(state.runId)?.episode !== episode;
20898
21606
  const intervalMs = HEALTH_ATTENTION_FIRST_REPEAT_MS;
20899
21607
  const current = currentOwnedState(state, ownerSessionId);
@@ -20902,7 +21610,9 @@ ${result.stderr ?? ""}`.trim(),
20902
21610
  if (signal.aborted || generation !== healthGeneration) return;
20903
21611
  let diagnostic;
20904
21612
  const attemptedDiagnostic = firstAttention && availableActions.includes("inspect");
21613
+ if (attemptedDiagnostic && initialStaleInspectionUsed) continue;
20905
21614
  if (attemptedDiagnostic) {
21615
+ initialStaleInspectionUsed = true;
20906
21616
  const diagnosticSignal = AbortSignal.any([
20907
21617
  signal,
20908
21618
  AbortSignal.timeout(HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS)
@@ -20981,56 +21691,108 @@ ${result.stderr ?? ""}`.trim(),
20981
21691
  "Do not repeat inspect_agent or read_agent_transcript solely because this reminder fired.",
20982
21692
  "Continue waiting only while existing evidence still positively supports a legitimate long-running operation; otherwise use interrupt_agent to stop the current operation and continue the same assignment."
20983
21693
  ];
21694
+ stageAttention({
21695
+ state,
21696
+ condition: "stale",
21697
+ message: {
21698
+ customType: "pi-herdsman-agent-stale",
21699
+ content: [
21700
+ `Agent ${current.agentLabel} has had no qualifying execution progress for ${formatHealthAttentionDuration(inactiveMs)}.`,
21701
+ `Request: ${current.activeRequestId}`,
21702
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21703
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs)}`,
21704
+ ...diagnosticLines,
21705
+ "",
21706
+ "This is advisory inactivity, not proof of a hang.",
21707
+ "Streaming tool output does not count as qualifying progress.",
21708
+ "steer_agent queues a cooperative correction; it does not preempt the current operation.",
21709
+ "Use interrupt_agent only when the current operation itself must be abandoned; interrupt_agent cancels that operation, supersedes earlier steering Pi has not yet delivered, and continues the same assignment.",
21710
+ "Use stop_agent only to abandon the assignment or as destructive fallback."
21711
+ ].join("\n"),
21712
+ display: true,
21713
+ details: {
21714
+ runId: latest.runId,
21715
+ requestId: latest.activeRequestId,
21716
+ agentLabel: latest.agentLabel,
21717
+ ownerSessionId: latest.ownerSessionId,
21718
+ workspaceId: latest.workspaceId,
21719
+ paneId: latest.paneId,
21720
+ piSessionId: latest.piSessionId,
21721
+ lastActivityAt: latest.lastActivityAt,
21722
+ inactiveMs,
21723
+ thresholdMs: HEALTH_STALE_AFTER_MS,
21724
+ availableActions,
21725
+ nextReminderMs: intervalMs,
21726
+ ...diagnostic ? {
21727
+ captured_at: diagnostic.capturedAt,
21728
+ recent_output_truncated: diagnostic.recentOutputTruncated,
21729
+ ...diagnostic.recentOutput ? { recent_output: diagnostic.recentOutput } : {},
21730
+ ...diagnostic.process ? { process: diagnostic.process } : {}
21731
+ } : {}
21732
+ }
21733
+ },
21734
+ stillEligible: () => {
21735
+ const latest2 = currentOwnedState(state, ownerSessionId);
21736
+ return !!latest2 && latest2.activeRequestId === state.activeRequestId && latest2.lastActivityAt === state.lastActivityAt && !latest2.pendingAskId && !latest2.resultError;
21737
+ },
21738
+ onSubmitted: () => recordAttention(state.runId, episode, intervalMs)
21739
+ });
21740
+ }
21741
+ if (!pending.length) return;
21742
+ let finalSnapshot;
21743
+ try {
21744
+ finalSnapshot = await snapshots(ctx, signal, false, false);
21745
+ } catch {
21746
+ return;
21747
+ }
21748
+ if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
21749
+ return;
21750
+ const ready2 = pending.filter((item) => {
21751
+ if (!item.stillEligible()) return false;
21752
+ const latest = finalSnapshot.agents.find(
21753
+ ({ state: candidate }) => sameIdentity(candidate, item.state)
21754
+ );
21755
+ if (!latest || latest.state.ownerSessionId !== ownerSessionId)
21756
+ return false;
21757
+ switch (item.condition) {
21758
+ case "lost":
21759
+ return latest.presence.kind === "lost" && !latest.state.completedRequestId;
21760
+ case "stale":
21761
+ return latest.presence.kind === "live" && latest.listed.state === "working";
21762
+ case "ask":
21763
+ return latest.presence.kind !== "lost" && latest.presence.kind !== "unknown";
21764
+ case "unknown":
21765
+ return latest.presence.kind === "unknown";
21766
+ case "blocked":
21767
+ return latest.presence.kind === "live" && latest.lifecycleState === "blocked";
21768
+ case "handoff":
21769
+ return latest.presence.kind !== "lost" && latest.presence.kind !== "unknown";
21770
+ case "result_error":
21771
+ return true;
21772
+ }
21773
+ });
21774
+ if (!ready2.length) return;
21775
+ const submitted = [];
21776
+ let triggerSubmitted = false;
21777
+ for (const [index, item] of ready2.entries()) {
20984
21778
  try {
20985
- if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20986
- return;
20987
- pi.sendMessage(
20988
- {
20989
- customType: "pi-herdsman-agent-stale",
20990
- content: [
20991
- `Agent ${current.agentLabel} has had no qualifying execution progress for ${formatHealthAttentionDuration(inactiveMs)}.`,
20992
- `Request: ${current.activeRequestId}`,
20993
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20994
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs)}`,
20995
- ...diagnosticLines,
20996
- "",
20997
- "This is advisory inactivity, not proof of a hang.",
20998
- "Streaming tool output does not count as qualifying progress.",
20999
- "steer_agent queues a cooperative correction; it does not preempt the current operation.",
21000
- "Use interrupt_agent only when the current operation itself must be abandoned; interrupt_agent cancels that operation, supersedes earlier steering Pi has not yet delivered, and continues the same assignment.",
21001
- "Use stop_agent only to abandon the assignment or as destructive fallback."
21002
- ].join("\n"),
21003
- display: true,
21004
- details: {
21005
- runId: latest.runId,
21006
- requestId: latest.activeRequestId,
21007
- agentLabel: latest.agentLabel,
21008
- ownerSessionId: latest.ownerSessionId,
21009
- workspaceId: latest.workspaceId,
21010
- paneId: latest.paneId,
21011
- piSessionId: latest.piSessionId,
21012
- lastActivityAt: latest.lastActivityAt,
21013
- inactiveMs,
21014
- thresholdMs: HEALTH_STALE_AFTER_MS,
21015
- availableActions,
21016
- nextReminderMs: intervalMs,
21017
- ...diagnostic ? {
21018
- captured_at: diagnostic.capturedAt,
21019
- recent_output_truncated: diagnostic.recentOutputTruncated,
21020
- ...diagnostic.recentOutput ? { recent_output: diagnostic.recentOutput } : {},
21021
- ...diagnostic.process ? { process: diagnostic.process } : {}
21022
- } : {}
21023
- }
21024
- },
21025
- { triggerTurn: true }
21026
- );
21027
- if (generation === healthGeneration && !signal.aborted) {
21028
- recordAttention(state.runId, episode, intervalMs);
21029
- published = true;
21030
- }
21779
+ pi.sendMessage(item.message, {
21780
+ triggerTurn: index === ready2.length - 1
21781
+ });
21782
+ submitted.push(item);
21783
+ if (index === ready2.length - 1) triggerSubmitted = true;
21031
21784
  } catch {
21785
+ if (index === ready2.length - 1) {
21786
+ try {
21787
+ pi.sendMessage(item.message, { triggerTurn: true });
21788
+ submitted.push(item);
21789
+ triggerSubmitted = true;
21790
+ } catch {
21791
+ }
21792
+ }
21032
21793
  }
21033
21794
  }
21795
+ if (triggerSubmitted) for (const item of submitted) item.onSubmitted();
21034
21796
  };
21035
21797
  const runAgentHealthScanner = (ctx, signal) => {
21036
21798
  const generation = ++healthGeneration;
@@ -21081,6 +21843,34 @@ ${result.stderr ?? ""}`.trim(),
21081
21843
  pi,
21082
21844
  (ctx, phase, budget) => drainReadyOwnerNotifications(ctx, phase, budget)
21083
21845
  );
21846
+ pi.on("agent_settled", (_event, context) => {
21847
+ if (!active) return;
21848
+ let ownerId;
21849
+ try {
21850
+ ownerId = context.sessionManager.getSessionId();
21851
+ } catch {
21852
+ return;
21853
+ }
21854
+ for (const runtime of runtimes.values()) {
21855
+ if (runtime.ownerSessionId !== ownerId) continue;
21856
+ const prefix = `${runtime.mailboxPath}:`;
21857
+ const retryMessageIds = /* @__PURE__ */ new Set();
21858
+ for (const key of submittedOwnerMessages) {
21859
+ if (!key.startsWith(prefix)) continue;
21860
+ retryMessageIds.add(key.slice(prefix.length));
21861
+ submittedOwnerMessages.delete(key);
21862
+ }
21863
+ deliverOwnerMessages(
21864
+ runtime,
21865
+ context,
21866
+ void 0,
21867
+ true,
21868
+ void 0,
21869
+ false,
21870
+ retryMessageIds
21871
+ );
21872
+ }
21873
+ });
21084
21874
  return {
21085
21875
  listAgentStates,
21086
21876
  managedAgentSnapshots: snapshot,
@@ -21132,8 +21922,10 @@ ${result.stderr ?? ""}`.trim(),
21132
21922
  rollbackUnknownStartedAgent,
21133
21923
  watchResult,
21134
21924
  watchAsk,
21925
+ watchOwnerMessages,
21135
21926
  stopResultWatcher,
21136
21927
  stopAskWatcher,
21928
+ stopOwnerMessageWatcher,
21137
21929
  deliverResult,
21138
21930
  cleanupDeliveredResult(runtime, result, context, signal) {
21139
21931
  return finalizeDeliveredResult(runtime, result, context, signal);
@@ -21160,7 +21952,10 @@ ${result.stderr ?? ""}`.trim(),
21160
21952
  sessionTreeChanged(context, signal) {
21161
21953
  active = true;
21162
21954
  for (const runtime of runtimes.values()) {
21163
- if (runtime.activeRequestId) watchAsk(runtime, context, signal);
21955
+ if (runtime.activeRequestId) {
21956
+ watchAsk(runtime, context, signal);
21957
+ watchOwnerMessages(runtime, context, signal);
21958
+ }
21164
21959
  }
21165
21960
  },
21166
21961
  abortSession() {
@@ -21199,8 +21994,10 @@ ${result.stderr ?? ""}`.trim(),
21199
21994
  recoveryComplete = false;
21200
21995
  for (const watcher of resultWatchers.values()) watcher();
21201
21996
  for (const watcher of askWatchers.values()) watcher();
21997
+ for (const watcher of ownerMessageWatchers.values()) watcher();
21202
21998
  resultWatchers.clear();
21203
21999
  askWatchers.clear();
22000
+ ownerMessageWatchers.clear();
21204
22001
  for (const timer of resultDeliveryRetries.values()) clearTimeout(timer);
21205
22002
  for (const timer of resultCleanupRetries.values()) clearTimeout(timer);
21206
22003
  for (const timer of askDeliveryRetries.values()) clearTimeout(timer);
@@ -21209,6 +22006,8 @@ ${result.stderr ?? ""}`.trim(),
21209
22006
  askDeliveryRetries.clear();
21210
22007
  resultDeliveryInFlight.clear();
21211
22008
  askDeliveryInFlight.clear();
22009
+ ownerMessageDeliveryInFlight.clear();
22010
+ submittedOwnerMessages.clear();
21212
22011
  resultDeliveryEvidence.clear();
21213
22012
  resultDeliverySemanticRefs.clear();
21214
22013
  runtimes.clear();
@@ -21465,10 +22264,18 @@ do not select evidence unless the owner needs it.
21465
22264
  Do not silently broaden scope or make an unapproved scope, architecture,
21466
22265
  security, protocol, repository-boundary, product, or operational decision.
21467
22266
 
21468
- Use ask_owner only when a decision from your exact direct owner is genuinely
21469
- required to continue correctly. Explicit attachments must be supported UTF-8
22267
+ Use notify_owner only for material information your direct owner needs before
22268
+ the normal final handoff, or for an explicitly requested meaningful
22269
+ checkpoint. Do not send routine progress, duplicate an imminent final result,
22270
+ or notify merely to show activity.
22271
+
22272
+ Use await_owner only for a required owner decision that prevents further
22273
+ correct progress. Complete independently safe work first. Do not ask for
22274
+ decisions already settled by the assignment, existing evidence, or your
22275
+ delegated authority. After an accepted await_owner call, end your turn;
22276
+ Herdsman retains the blocked assignment until the owner replies. Explicit attachments must be supported UTF-8
21470
22277
  text fully embedded within the applicable per-file and complete-message
21471
- budgets. Call ask_owner alone as the final tool call of the turn. Wait for the
22278
+ budgets. Call await_owner alone as the final tool call of the turn. Wait for the
21472
22279
  direct owner's reply only after the tool confirms the question was sent; if
21473
22280
  rejected, address the error or report a non-empty blocker. Keep at most one
21474
22281
  question outstanding. Do not guess the answer. The reply resumes the same
@@ -21501,7 +22308,7 @@ blockers, remaining work, and reusable paths or artifacts.`;
21501
22308
  };
21502
22309
  AGENT_DEFINITION_ENTRY = "pi-herdsman-agent-definition";
21503
22310
  AGENT_EXECUTION_OWNERSHIP_GUIDANCE = "Each unresolved unit of work has one executor. Using delegate_agent transfers that assignment's execution ownership to the Agent until it resolves. After delegation succeeds, stop executing, inspecting, or analyzing that delegated scope locally; do not assign overlapping work. Continue only concrete, necessary work clearly outside the delegated scope that you still own.";
21504
- AGENT_UNRESOLVED_GUIDANCE = "Use list_agents when fresh Agent state or ownership is materially needed for a control or recovery decision, or to refresh the definition roster; do not use it for progress polling. Follow current available_tools and revalidation: steer_agent queues a cooperative correction for Pi to deliver after the current assistant turn and its tool calls reach a steering boundary; it does not preempt the current operation. interrupt_agent cancels the current operation and replaces its direction. Use reply_agent only to answer that Agent's exact pending ask_owner question. stop_agent abandons an eligible Agent generation and its unfinished assignment. inspect_agent provides bounded live terminal/process evidence; read_agent_transcript provides bounded persisted conversation/tool evidence. When Agent work is unresolved, handle required control, then continue only necessary work you still own or end the turn without concluding; results or attention resume the session automatically. Do not poll with status requests, sleep, or other waiting mechanisms. Stale health attention is diagnosis, not progress polling: use attached evidence first and, when absent or insufficient, perform at most one bounded diagnostic read before passive waiting. A repeated reminder for the same stale episode is additional recovery evidence: unchanged qualifying activity means the Agent has not crossed an execution boundary since the previous reminder. A steer queued during that unchanged episode cannot have taken effect yet. Do not repeat diagnostic reads solely because a reminder fired. Continue waiting only while existing evidence still positively supports a legitimate long-running operation; otherwise use interrupt_agent to stop the current operation and continue the same assignment. A proven lost Agent remains unresolved; physical disappearance is not completion. A physically unknown Agent remains fail-closed: do not control, close, replace, or infer completion of that generation. Unknown Agent identity does not by itself prove a currently active competing writer. For a concrete recovery decision, use available current evidence and at most one bounded diagnostic read when necessary; distinguish historical Agent identity from current execution and delegated scope. Continue necessary independent work that remains authorized and has no unresolved execution conflict. Do not take over the Agent's unresolved assignment. Do not take over or replace unresolved delegated work until the current generation is resolved or explicitly closed. If evidence is insufficient to exclude competing execution, preserve the affected scope and identify the specific missing evidence or external action. Do not repeat the same identity investigation without new evidence.";
22311
+ AGENT_UNRESOLVED_GUIDANCE = "Use list_agents when fresh Agent state or ownership is materially needed for a control or recovery decision, or to refresh the definition roster; do not use it for progress polling. Follow current available_tools and revalidation: steer_agent queues a cooperative correction for Pi to deliver after the current assistant turn and its tool calls reach a steering boundary; it does not preempt the current operation. interrupt_agent cancels the current operation and replaces its direction. Use reply_agent only to answer that Agent's exact pending await_owner question. stop_agent abandons an eligible Agent generation and its unfinished assignment. inspect_agent provides bounded live terminal/process evidence; read_agent_transcript provides bounded persisted conversation/tool evidence. When Agent work is unresolved, handle required control, then continue only necessary work you still own or end the turn without concluding; results or attention resume the session automatically. Do not poll with status requests, sleep, or other waiting mechanisms. Stale health attention is diagnosis, not progress polling: use attached evidence first and, when absent or insufficient, perform at most one bounded diagnostic read before passive waiting. A repeated reminder for the same stale episode is additional recovery evidence: unchanged qualifying activity means the Agent has not crossed an execution boundary since the previous reminder. A steer queued during that unchanged episode cannot have taken effect yet. Do not repeat diagnostic reads solely because a reminder fired. Continue waiting only while existing evidence still positively supports a legitimate long-running operation; otherwise use interrupt_agent to stop the current operation and continue the same assignment. A proven lost Agent remains unresolved; physical disappearance is not completion. A physically unknown Agent remains fail-closed: do not control, close, replace, or infer completion of that generation. Unknown Agent identity does not by itself prove a currently active competing writer. For a concrete recovery decision, use available current evidence and at most one bounded diagnostic read when necessary; distinguish historical Agent identity from current execution and delegated scope. Continue necessary independent work that remains authorized and has no unresolved execution conflict. Do not take over the Agent's unresolved assignment. Do not take over or replace unresolved delegated work until the current generation is resolved or explicitly closed. If evidence is insufficient to exclude competing execution, preserve the affected scope and identify the specific missing evidence or external action. Do not repeat the same identity investigation without new evidence.";
21505
22312
  AGENT_DELEGATION_GUIDANCE = "Delegate bounded execution work when an Agent can reasonably own it and delegation is useful. Keep work local when it is trivial, inseparable from work you must own, otherwise unsuitable for an Agent, or delegation would add more coordination than value.";
21506
22313
  AGENT_HANDOFF_GUIDANCE = "When delegating a bounded task, prefer continue_agent if a known exact historical managed-Agent Pi session carries substantial context relevant to that task and remains eligible; otherwise use delegate_agent to start fresh from a definition. When a result ref is shown, prefer it to the exact session UUID or path. Retired sessions cannot be continued while context retirement is enabled. If further work is needed, delegate a fresh Agent with the prior handoff and relevant files. Each live Agent generation exists for one assignment; after its terminal result is delivered, Herdsman cleans up that generation. Agent labels identify the current live generation; exact Pi sessions identify historical context and continuation. For new or updated assignments, `task`/`message` and `files` carry assignment evidence. Accepted managed-Agent tasks are retained for descendants as context, not authority; ordinary attachments remain per handoff unless retained. Complete strict UTF-8 text may be embedded; other files remain canonical local references and are not copied or snapshotted. Do not attach or mention agent instruction files such as AGENTS.md, CLAUDE.md, GEMINI.md, or equivalents merely because they exist. Rely on normal project or runtime discovery when it supplies those instructions. Attach such a file only when the task itself requires inspecting, modifying, comparing, or transmitting it, the user explicitly requests it, or required instructions would not otherwise reach the target. Skills are separate; attach SKILL.md only when the task needs it and the selected definition does not already provide that skill.";
21507
22314
  LEAD_SCOPE_DESCRIPTION = `Own architecture, approved scope, acceptance of Agent outputs, integration, conflict resolution,
@@ -21528,7 +22335,7 @@ omit unrelated evidence and evidence already inherited as the same required vers
21528
22335
  but explicitly forward changed versions. Summaries do not transfer evidence.
21529
22336
  The lead retains architecture, approved scope, acceptance, and final-decision
21530
22337
  authority. Delegate only to definitions listed in your effective agents field.
21531
- ask_owner follows its normal eligibility rules when you have no unresolved
22338
+ await_owner follows its normal eligibility rules when you have no unresolved
21532
22339
  direct-agent work. If unresolved direct-agent work exists, every such agent
21533
22340
  must itself be validly waiting on an owner answer; ordinary active or
21534
22341
  pending-result agent work still blocks escalation.`;
@@ -21555,6 +22362,7 @@ __export(managed_agent_runtime_exports, {
21555
22362
  createManagedAgentExecutionState: () => createManagedAgentExecutionState,
21556
22363
  createManagedAgentLeafStatus: () => createManagedAgentLeafStatus,
21557
22364
  createManagedAgentMetadataPublisher: () => createManagedAgentMetadataPublisher,
22365
+ createManagedAgentNotifyOwnerHandler: () => createManagedAgentNotifyOwnerHandler,
21558
22366
  createManagedAgentRequestState: () => createManagedAgentRequestState,
21559
22367
  ensureManagedAgentIdentity: () => ensureManagedAgentIdentity,
21560
22368
  evidencePageContent: () => evidencePageContent,
@@ -21568,6 +22376,7 @@ __export(managed_agent_runtime_exports, {
21568
22376
  registerManagedAgentAttachHandoffTool: () => registerManagedAgentAttachHandoffTool,
21569
22377
  registerManagedAgentContextHandlers: () => registerManagedAgentContextHandlers,
21570
22378
  registerManagedAgentInputHandlers: () => registerManagedAgentInputHandlers,
22379
+ registerManagedAgentNotifyOwnerTool: () => registerManagedAgentNotifyOwnerTool,
21571
22380
  registerManagedAgentResultCapture: () => registerManagedAgentResultCapture,
21572
22381
  registerManagedAgentRuntime: () => registerManagedAgentRuntime,
21573
22382
  registerManagedAgentSessionStartHandler: () => registerManagedAgentSessionStartHandler,
@@ -21579,7 +22388,7 @@ __export(managed_agent_runtime_exports, {
21579
22388
  sessionContextRetired: () => sessionContextRetired,
21580
22389
  validateManagedAgentIdentity: () => validateManagedAgentIdentity
21581
22390
  });
21582
- 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";
21583
22392
  import { existsSync as existsSync2, realpathSync as realpathSync5 } from "node:fs";
21584
22393
  import { buildSessionProjection as buildSessionProjection2 } from "@earendil-works/pi-coding-agent";
21585
22394
  import { contentText as contentText3 } from "@earendil-works/pi-ai";
@@ -21939,7 +22748,7 @@ function validateManagedAgentIdentity(input) {
21939
22748
  ids: { label: env.PI_HERDSMAN_LABEL, paneId: env.HERDR_PANE_ID }
21940
22749
  }
21941
22750
  );
21942
- 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)
21943
22752
  fail(
21944
22753
  "target_not_found",
21945
22754
  "Delegation controller identity is not a valid managed agent",
@@ -22232,8 +23041,6 @@ function createManagedAgentLeafStatus(options) {
22232
23041
  let inFlight = false;
22233
23042
  let focusInFlight = false;
22234
23043
  let breadcrumb;
22235
- let ownTools;
22236
- const ownToolsSnapshot = () => ownTools ? { ownTools } : {};
22237
23044
  const reset = () => {
22238
23045
  generation++;
22239
23046
  if (timer) clearInterval(timer);
@@ -22275,7 +23082,7 @@ function createManagedAgentLeafStatus(options) {
22275
23082
  stale: false,
22276
23083
  unavailable: false,
22277
23084
  breadcrumb,
22278
- ...ownToolsSnapshot(),
23085
+ ...options.ownToolsSnapshot(),
22279
23086
  identityOnly: true,
22280
23087
  refreshedAt: Date.now()
22281
23088
  });
@@ -22295,7 +23102,7 @@ function createManagedAgentLeafStatus(options) {
22295
23102
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22296
23103
  }
22297
23104
  ],
22298
- ...ownToolsSnapshot(),
23105
+ ...options.ownToolsSnapshot(),
22299
23106
  identityOnly: true
22300
23107
  });
22301
23108
  } finally {
@@ -22307,9 +23114,6 @@ function createManagedAgentLeafStatus(options) {
22307
23114
  invalidate() {
22308
23115
  widget?.invalidate();
22309
23116
  },
22310
- captureOwnTools(tools) {
22311
- ownTools = tools;
22312
- },
22313
23117
  start(ctx) {
22314
23118
  const activeGeneration = generation;
22315
23119
  context = ctx;
@@ -22352,7 +23156,7 @@ function createManagedAgentLeafStatus(options) {
22352
23156
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22353
23157
  }
22354
23158
  ],
22355
- ...ownToolsSnapshot(),
23159
+ ...options.ownToolsSnapshot(),
22356
23160
  identityOnly: true
22357
23161
  });
22358
23162
  if (activeGeneration === generation && ctx === context) widget = next;
@@ -22370,7 +23174,7 @@ function createManagedAgentAskOwnerHandler(options) {
22370
23174
  throw new Error("Question must contain non-whitespace text");
22371
23175
  if (!options.isSoleToolCall(ctx))
22372
23176
  throw new Error(
22373
- "Call ask_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
23177
+ "Call await_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
22374
23178
  );
22375
23179
  const managed = managedAgentIdentity(ctx);
22376
23180
  const state = options.state();
@@ -22439,6 +23243,83 @@ function createManagedAgentAskOwnerHandler(options) {
22439
23243
  };
22440
23244
  };
22441
23245
  }
23246
+ function createManagedAgentNotifyOwnerHandler(options) {
23247
+ return async (_id, params, _signal, _update, ctx) => {
23248
+ if (typeof params.message !== "string" || !params.message.trim())
23249
+ throw new Error("Message must contain non-whitespace text");
23250
+ const managed = managedAgentIdentity(ctx);
23251
+ const state = options.state();
23252
+ if (!state || !options.sameIdentity(state, managed))
23253
+ throw new Error("Agent identity is not eligible to notify its owner");
23254
+ if (!options.eligible())
23255
+ throw new Error(
23256
+ `Agent cannot notify its owner: ${options.rejectionReason()}`
23257
+ );
23258
+ const messageId = randomUUID11();
23259
+ const createdAt = Date.now();
23260
+ const limits = await options.messageLimits(ctx);
23261
+ const prepared = await options.prepare(
23262
+ ctx,
23263
+ params.message,
23264
+ params.files,
23265
+ state,
23266
+ messageId,
23267
+ createdAt,
23268
+ limits
23269
+ );
23270
+ const message = {
23271
+ version: 5,
23272
+ messageId,
23273
+ requestId: state.activeRequestId,
23274
+ runId: state.runId,
23275
+ ownerSessionId: state.ownerSessionId,
23276
+ workspaceId: state.workspaceId,
23277
+ agentLabel: state.agentLabel,
23278
+ paneId: state.paneId,
23279
+ piSessionId: state.piSessionId,
23280
+ text: prepared.text,
23281
+ ...prepared.resultBindings.length ? { resultBindings: prepared.resultBindings } : {},
23282
+ createdAt
23283
+ };
23284
+ const bytes = mailboxRecordBytes(message);
23285
+ if (bytes > limits.mailbox.bytes)
23286
+ fail(
23287
+ "invalid_request",
23288
+ `Mailbox payload is ${bytes} bytes; configured limit is ${limits.mailbox.bytes} bytes`,
23289
+ "notify_owner",
23290
+ { details: { capacity: true } }
23291
+ );
23292
+ const mailbox = process.env.PI_HERDSMAN_MAILBOX;
23293
+ const release = options.claimLock(mailbox, state);
23294
+ try {
23295
+ const current = options.readState(mailbox);
23296
+ if (!current || !options.sameIdentity(current, state) || current.activeRequestId !== state.activeRequestId || current.completedRequestId || !options.eligible())
23297
+ throw new Error(
23298
+ "Agent assignment changed or began settling while notifying its owner"
23299
+ );
23300
+ const pending = options.readMessages(mailbox);
23301
+ if (pending.length >= 8)
23302
+ fail(
23303
+ "invalid_request",
23304
+ "Eight owner notifications are already awaiting confirmed delivery; continue without another notification or wait for delivery",
23305
+ "notify_owner",
23306
+ { details: { capacity: true } }
23307
+ );
23308
+ options.writeMessage(mailbox, message);
23309
+ } finally {
23310
+ release();
23311
+ }
23312
+ return {
23313
+ content: [
23314
+ {
23315
+ type: "text",
23316
+ text: "Notification queued for your direct owner. Continue your assignment."
23317
+ }
23318
+ ],
23319
+ details: { messageId, assignmentRequestId: message.requestId }
23320
+ };
23321
+ };
23322
+ }
22442
23323
  function handoffSelectionDetails(state, resultBindings) {
22443
23324
  return {
22444
23325
  version: 1,
@@ -22535,7 +23416,7 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22535
23416
  )
22536
23417
  );
22537
23418
  pi.registerTool({
22538
- name: "ask_owner",
23419
+ name: "await_owner",
22539
23420
  label: "Ask owner",
22540
23421
  exposure: "model-only",
22541
23422
  promptSnippet: "Ask this managed agent's direct owner for a required decision",
@@ -22555,6 +23436,39 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22555
23436
  execute
22556
23437
  });
22557
23438
  }
23439
+ function registerManagedAgentNotifyOwnerTool(pi, execute) {
23440
+ const files = Type2.Optional(
23441
+ Type2.Array(
23442
+ Type2.String({
23443
+ minLength: 1,
23444
+ description: "Readable regular local file path or exact result ref returned by Herdsman."
23445
+ }),
23446
+ {
23447
+ description: "File or result evidence transferred to the recipient. Copy result refs exactly. Files do not grant runtime capabilities."
23448
+ }
23449
+ )
23450
+ );
23451
+ pi.registerTool({
23452
+ name: "notify_owner",
23453
+ label: "Notify owner",
23454
+ exposure: "direct",
23455
+ promptSnippet: "Send material information to your direct owner while continuing work",
23456
+ promptGuidelines: [FILE_HANDOFF_GUIDANCE],
23457
+ description: "Notify your direct owner about material information when you can continue your assignment. This does not block your assignment or require a reply.",
23458
+ executionMode: "sequential",
23459
+ parameters: Type2.Object(
23460
+ {
23461
+ message: Type2.String({
23462
+ minLength: 1,
23463
+ description: "Non-empty material information for your direct owner."
23464
+ }),
23465
+ files
23466
+ },
23467
+ { additionalProperties: false }
23468
+ ),
23469
+ execute
23470
+ });
23471
+ }
22558
23472
  function createManagedAgentEvidenceUpdater(pi) {
22559
23473
  return async function updateManagedAgentEvidence(_id, params, _signal, _update, ctx) {
22560
23474
  const state = managedAgentIdentity(ctx);
@@ -23151,7 +24065,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
23151
24065
  } : {
23152
24066
  error: {
23153
24067
  code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
23154
- message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : observation?.requestId === state.activeRequestId && observation.askOwnerCapacityError ? `Agent produced no assistant text. Earlier in this execution, ask_owner rejected its attachments: ${observation.askOwnerCapacityError}. The question was not sent.` : "Agent produced no assistant text"
24068
+ message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : observation?.requestId === state.activeRequestId && observation.askOwnerCapacityError ? `Agent produced no assistant text. Earlier in this execution, await_owner rejected its attachments: ${observation.askOwnerCapacityError}. The question was not sent.` : "Agent produced no assistant text"
23155
24069
  }
23156
24070
  },
23157
24071
  contextUsage: ctx.getContextUsage(),
@@ -23315,6 +24229,13 @@ function registerManagedAgentRuntime(pi, options) {
23315
24229
  const allowedAgentDefinitions = allowedAgentDefinitionsFromEnv();
23316
24230
  const agentDepth = agentDepthFromEnv();
23317
24231
  const delegationEnabled = allowedAgentDefinitions.length > 0;
24232
+ const ownToolsSnapshot = () => {
24233
+ try {
24234
+ return { ownTools: pi.getActiveTools() };
24235
+ } catch {
24236
+ return {};
24237
+ }
24238
+ };
23318
24239
  let startupDefinitionRoster;
23319
24240
  const controller = delegationEnabled ? createAgentController(pi, {
23320
24241
  ...options.controllerOptions,
@@ -23346,7 +24267,7 @@ function registerManagedAgentRuntime(pi, options) {
23346
24267
  hasPendingStart: (label) => controller.hasPendingStart(label),
23347
24268
  clearPendingStart: (label, expected) => controller.clearPendingStart(label, expected),
23348
24269
  runtimeForLabel: (label) => controller.runtimeForLabel(label),
23349
- ownToolsSnapshot: () => ({}),
24270
+ ownToolsSnapshot,
23350
24271
  focusTarget: async (ctx, intent, isCurrent) => {
23351
24272
  if (intent.kind !== "session")
23352
24273
  throw new Error("Manager navigation is unavailable from an Agent.");
@@ -23370,7 +24291,7 @@ function registerManagedAgentRuntime(pi, options) {
23370
24291
  label: process.env.PI_HERDSMAN_LABEL
23371
24292
  }),
23372
24293
  sameIdentity: sameManagedAgentIdentity,
23373
- ownToolsSnapshot: () => ({})
24294
+ ownToolsSnapshot
23374
24295
  });
23375
24296
  const currentIdentity = managedAgentEnvironmentIdentity(
23376
24297
  ctx,
@@ -23431,7 +24352,7 @@ function registerManagedAgentRuntime(pi, options) {
23431
24352
  label: process.env.PI_HERDSMAN_LABEL
23432
24353
  }),
23433
24354
  sameIdentity: sameManagedAgentIdentity,
23434
- ownToolsSnapshot: () => ({})
24355
+ ownToolsSnapshot
23435
24356
  });
23436
24357
  }
23437
24358
  });
@@ -23470,6 +24391,7 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23470
24391
  identity: (ctx) => managedAgentEnvironmentIdentity(ctx, options.build),
23471
24392
  sameIdentity: sameManagedAgentIdentity,
23472
24393
  signal: () => metadataPublisher.signal,
24394
+ ownToolsSnapshot,
23473
24395
  getLocalActivity: (ctx) => getLocalActivity(ctx),
23474
24396
  focusTarget: async (ctx, intent, isCurrent) => {
23475
24397
  if (intent.kind !== "session")
@@ -23647,13 +24569,13 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23647
24569
  sameIdentity: sameManagedAgentIdentity,
23648
24570
  eligible: requestState.eligibleToAsk,
23649
24571
  rejectionReason: requestState.askRejectionReason,
23650
- isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "ask_owner"),
24572
+ isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "await_owner"),
23651
24573
  messageLimits: options.messageLimits,
23652
24574
  prepare: async (ctx, question, files, state, askId, createdAt, limits) => prepareMessageInput(
23653
24575
  question,
23654
- options.resolveMessageFiles(ctx, files, "ask_owner"),
24576
+ options.resolveMessageFiles(ctx, files, "await_owner"),
23655
24577
  state.cwd,
23656
- "ask_owner",
24578
+ "await_owner",
23657
24579
  "Question",
23658
24580
  {
23659
24581
  inlineLimitBytes: limits.inline.bytes,
@@ -23667,11 +24589,11 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23667
24589
  fail(
23668
24590
  "invalid_request",
23669
24591
  `Mailbox payload is ${bytes} bytes; configured limit is ${limit} bytes`,
23670
- "ask_owner",
24592
+ "await_owner",
23671
24593
  { details: { capacity: true } }
23672
24594
  );
23673
24595
  },
23674
- claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "ask_owner", {
24596
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "await_owner", {
23675
24597
  label: state.agentLabel,
23676
24598
  paneId: state.paneId
23677
24599
  }),
@@ -23688,11 +24610,52 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23688
24610
  try {
23689
24611
  return await executeAskOwner(...args);
23690
24612
  } catch (error2) {
23691
- if (error2 instanceof OperationError && error2.detail.operation === "ask_owner" && error2.detail.details?.capacity === true && observation?.requestId && observation === execution.observation && execution.assignment?.activeRequestId === observation.requestId && !execution.assignment.pendingAskId)
24613
+ if (error2 instanceof OperationError && error2.detail.operation === "await_owner" && error2.detail.details?.capacity === true && observation?.requestId && observation === execution.observation && execution.assignment?.activeRequestId === observation.requestId && !execution.assignment.pendingAskId)
23692
24614
  observation.askOwnerCapacityError = error2.message.slice(0, 512);
23693
24615
  throw error2;
23694
24616
  }
23695
24617
  });
24618
+ const executeNotifyOwner = createManagedAgentNotifyOwnerHandler({
24619
+ state: () => execution.assignment,
24620
+ sameIdentity: sameManagedAgentIdentity,
24621
+ eligible: requestState.eligibleToNotify,
24622
+ rejectionReason: requestState.notifyRejectionReason,
24623
+ messageLimits: options.messageLimits,
24624
+ prepare: async (ctx, message, files, state, messageId, createdAt, limits) => prepareMessageInput(
24625
+ message,
24626
+ options.resolveMessageFiles(ctx, files, "notify_owner"),
24627
+ state.cwd,
24628
+ "notify_owner",
24629
+ "Message",
24630
+ {
24631
+ inlineLimitBytes: limits.inline.bytes,
24632
+ mailboxLimitBytes: limits.mailbox.bytes,
24633
+ requireInline: true,
24634
+ serializedBytes: (text, bindings) => mailboxRecordBytes({
24635
+ version: 5,
24636
+ messageId,
24637
+ requestId: state.activeRequestId,
24638
+ runId: state.runId,
24639
+ ownerSessionId: state.ownerSessionId,
24640
+ workspaceId: state.workspaceId,
24641
+ agentLabel: state.agentLabel,
24642
+ paneId: state.paneId,
24643
+ piSessionId: state.piSessionId,
24644
+ text,
24645
+ ...bindings.length ? { resultBindings: bindings } : {},
24646
+ createdAt
24647
+ })
24648
+ }
24649
+ ),
24650
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "notify_owner", {
24651
+ label: state.agentLabel,
24652
+ paneId: state.paneId
24653
+ }),
24654
+ readState: readAgentState,
24655
+ readMessages: readOwnerMessages,
24656
+ writeMessage: writeOwnerMessage
24657
+ });
24658
+ registerManagedAgentNotifyOwnerTool(pi, executeNotifyOwner);
23696
24659
  const prepareDelegatingRoster = async (ctx) => {
23697
24660
  startupDefinitionRoster = void 0;
23698
24661
  if (!delegationEnabled) return;
@@ -23724,8 +24687,6 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23724
24687
  },
23725
24688
  resetRequestPump,
23726
24689
  resetLeafStatus: leafStatus.reset,
23727
- captureOwnTools: leafStatus.captureOwnTools,
23728
- getActiveTools: () => pi.getActiveTools(),
23729
24690
  clearControllerRuntimes: clearAgentRuntimes,
23730
24691
  setControllerReady: (ready) => controller?.setReady(ready),
23731
24692
  beginMetadataSession: metadataPublisher.beginSession,
@@ -23922,6 +24883,20 @@ function createManagedAgentRequestState(pi, options) {
23922
24883
  const state = options.state();
23923
24884
  return !!state?.activeRequestId && !state.pendingAskId && !state.completedRequestId && !options.pendingResult() && !options.pendingStateTransition() && !unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state) && options.allDirectChildrenAskBlocked(state);
23924
24885
  };
24886
+ const eligibleToNotify = () => {
24887
+ const state = options.state();
24888
+ return !!state?.activeRequestId && !state.pendingAskId && !state.completedRequestId && !options.pendingResult() && !options.pendingStateTransition() && !unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state);
24889
+ };
24890
+ const notifyRejectionReason = () => {
24891
+ const state = options.state();
24892
+ if (!state?.activeRequestId) return "no active assignment";
24893
+ if (state.completedRequestId || options.pendingResult())
24894
+ return "assignment is settling";
24895
+ if (options.pendingStateTransition()) return "assignment state is settling";
24896
+ if (unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state))
24897
+ return "a control request is still pending";
24898
+ return "agent state is not eligible";
24899
+ };
23925
24900
  const askRejectionReason = () => {
23926
24901
  const state = options.state();
23927
24902
  if (!state?.activeRequestId) return "no active assignment";
@@ -23949,6 +24924,8 @@ function createManagedAgentRequestState(pi, options) {
23949
24924
  pump,
23950
24925
  eligibleToAsk,
23951
24926
  askRejectionReason,
24927
+ eligibleToNotify,
24928
+ notifyRejectionReason,
23952
24929
  reportAcknowledgementFailure,
23953
24930
  reset
23954
24931
  };
@@ -24145,6 +25122,7 @@ function registerManagedAgentContextHandlers(pi, options) {
24145
25122
  pi.on("session_before_fork", () => ({ cancel: true }));
24146
25123
  }
24147
25124
  function registerManagedAgentSessionStartHandler(pi, execution, options) {
25125
+ let pendingStartup;
24148
25126
  pi.on("session_start", async (_event, ctx) => {
24149
25127
  let verified;
24150
25128
  let startupStage = "definition";
@@ -24153,7 +25131,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24153
25131
  options.startControllerSession();
24154
25132
  options.resetRequestPump();
24155
25133
  options.resetLeafStatus();
24156
- options.captureOwnTools(void 0);
24157
25134
  if (options.delegationEnabled) options.clearControllerRuntimes();
24158
25135
  execution.initialized = false;
24159
25136
  options.setControllerReady(false);
@@ -24166,8 +25143,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24166
25143
  execution.agentContext = ctx;
24167
25144
  const candidate = options.environmentIdentity(ctx);
24168
25145
  if (!candidate) throw new Error("invalid agent environment");
24169
- if (!options.delegationEnabled)
24170
- options.captureOwnTools(options.getActiveTools());
24171
25146
  options.ensureAgentIdentity(ctx);
24172
25147
  verified = candidate;
24173
25148
  const restoreModel = process.env.PI_HERDSMAN_RESTORE_MODEL;
@@ -24188,7 +25163,7 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24188
25163
  );
24189
25164
  if (selection.kind === "unresolved")
24190
25165
  throw new Error(
24191
- `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"}.`
24192
25167
  );
24193
25168
  const expected = selection.model;
24194
25169
  const available = ctx.modelRegistry.find(
@@ -24239,150 +25214,243 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24239
25214
  }
24240
25215
  }
24241
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;
24242
25238
  if (!existing) {
24243
25239
  startupStage = "definition";
24244
25240
  validateManagedAgentDefinition(await options.getAgentDefinitions(ctx));
24245
25241
  startupStage = "bootstrap";
24246
- const bootstrap = readAgentBootstrap(mailbox);
25242
+ bootstrap = readAgentBootstrap(mailbox);
24247
25243
  if (bootstrap) {
24248
25244
  if (bootstrap.runId !== candidate.runId || bootstrap.ownerSessionId !== candidate.ownerSessionId || bootstrap.workspaceId !== candidate.workspaceId || bootstrap.agentLabel !== candidate.agentLabel)
24249
25245
  throw new Error("Managed-agent bootstrap identity mismatch");
24250
25246
  if (!sameRuntimeBuild(options.build, bootstrap.build))
24251
25247
  throw new Error("Managed-agent bootstrap Herdsman build mismatch");
24252
- for (const participant of bootstrap.participants) {
24253
- let initializer;
24254
- let acceptCount = 0;
24255
- let invalidInitializer = false;
24256
- pi.events.emit(MANAGED_AGENT_BOOTSTRAP_EVENT, {
24257
- protocol: 1,
24258
- phase: "initialize",
24259
- context: ctx,
24260
- agent: candidate.agentLabel,
24261
- participant: { id: participant.id, payload: participant.payload },
24262
- accept(callback) {
24263
- acceptCount++;
24264
- if (typeof callback !== "function") {
24265
- invalidInitializer = true;
24266
- return;
24267
- }
24268
- if (acceptCount === 1) initializer = callback;
24269
- }
24270
- });
24271
- if (acceptCount === 0 || invalidInitializer)
24272
- throw new Error(
24273
- `Managed-agent bootstrap participant "${participant.id}" is unavailable or invalid`
24274
- );
24275
- if (acceptCount > 1)
25248
+ if (bootstrap.childSessionId) {
25249
+ const nativeSessionId = ctx.sessionManager.getSessionId();
25250
+ if (nativeSessionId !== bootstrap.childSessionId || candidate.piSessionId !== bootstrap.childSessionId)
24276
25251
  throw new Error(
24277
- `Managed-agent bootstrap participant "${participant.id}" has multiple initializers`
25252
+ "Managed-agent bootstrap child session identity mismatch"
24278
25253
  );
24279
- try {
24280
- await initializer();
24281
- } catch (error2) {
25254
+ if (!reservedSessionIsFresh())
24282
25255
  throw new Error(
24283
- `Managed-agent bootstrap participant "${participant.id}" failed: ${String(error2)}`,
24284
- { cause: error2 }
25256
+ "Managed-agent bootstrap child session is not fresh"
24285
25257
  );
24286
- }
24287
25258
  }
24288
- removeAgentBootstrap(mailbox);
24289
25259
  }
24290
25260
  }
24291
- startupStage = "mailbox_state";
24292
- const release = options.claimAssignmentLock(mailbox, "session_start", {
24293
- label: execution.assignment.agentLabel,
24294
- paneId: execution.assignment.paneId
24295
- });
24296
- try {
24297
- const current = readAgentState(mailbox);
24298
- if (current && !options.sameIdentity(current, execution.assignment))
24299
- throw new Error("agent session identity changed while state existed");
24300
- if (existing !== void 0 && current === void 0)
24301
- throw new Error("agent mailbox disappeared while state existed");
24302
- if (existing !== void 0 && current !== void 0 && !options.sameDurableState(current, existing))
24303
- throw new Error(
24304
- "agent mailbox changed while session start was preparing"
24305
- );
24306
- if (existing === void 0 && current !== void 0)
24307
- execution.assignment = {
24308
- ...candidate,
24309
- ...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,
24310
25350
  build: options.build,
24311
- updatedAt: Date.now()
24312
- };
24313
- writeAgentState(mailbox, execution.assignment);
24314
- } finally {
24315
- release();
24316
- }
24317
- if (options.delegationEnabled) {
24318
- startupStage = "controller_recovery";
24319
- managedAgentControllerIdentity(ctx);
24320
- await options.recoverControllerRuntimes(ctx, metadataSignal);
24321
- options.setControllerReady(true);
24322
- }
24323
- if (execution.assignment.activeRequestId)
24324
- options.touchActivity(Date.now(), forceActivityTouch);
24325
- if (options.delegationEnabled)
24326
- options.startControllerHealthScanner(ctx, metadataSignal);
24327
- execution.initialized = true;
24328
- const definition = process.env.PI_HERDSMAN_AGENT_DEFINITION;
24329
- const label = execution.assignment.agentLabel;
24330
- nameSessionIfUnset(
24331
- pi,
24332
- ctx,
24333
- definition === label ? label : `${definition} \xB7 ${label}`
24334
- );
24335
- startupStage = "request_observer";
24336
- execution.stopRequestObserver = observeMailbox(
24337
- mailbox,
24338
- (name) => /^request-.*\.json$/.test(name),
24339
- () => options.pumpRequest(ctx),
24340
- (error2) => options.appendError(ctx, error2)
24341
- );
24342
- options.pumpRequest(ctx);
24343
- if (!options.delegationEnabled && ctx.mode === "tui" && ctx.hasUI)
24344
- options.startLeafStatus(ctx);
24345
- startupStage = "metadata";
24346
- const model = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : void 0;
24347
- const thinking = ctx.thinkingLevel;
24348
- options.reportMetadata(
24349
- execution.assignment,
24350
- ctx,
24351
- {
24352
- activity: null,
24353
- context: null,
24354
- model: model || null,
24355
- thinking: thinking || null
24356
- },
24357
- true
24358
- );
24359
- const releaseStartup = options.claimAssignmentLock(
24360
- mailbox,
24361
- "session_start",
24362
- {
24363
- label: candidate.agentLabel,
24364
- 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();
24365
25360
  }
24366
- );
24367
- try {
24368
- const current = readAgentState(mailbox);
24369
- if (!current || !options.sameIdentity(current, candidate))
24370
- throw new Error(
24371
- "agent session identity changed before startup outcome"
24372
- );
24373
- writeAgentStartupOutcome(mailbox, {
24374
- version: 5,
24375
- build: options.build,
24376
- runId: candidate.runId,
24377
- ownerSessionId: candidate.ownerSessionId,
24378
- workspaceId: candidate.workspaceId,
24379
- agentLabel: candidate.agentLabel,
24380
- paneId: candidate.paneId,
24381
- status: "ready"
24382
- });
24383
- } finally {
24384
- 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;
24385
25452
  }
25453
+ await finishStartup();
24386
25454
  } catch (error2) {
24387
25455
  if (verified) {
24388
25456
  try {
@@ -24427,6 +25495,11 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24427
25495
  ctx.ui.notify(`pi_herdsman_state_error: ${String(error2)}`, "error");
24428
25496
  }
24429
25497
  });
25498
+ pi.on("resources_discover", async () => {
25499
+ const pending = pendingStartup;
25500
+ pendingStartup = void 0;
25501
+ if (pending) await pending();
25502
+ });
24430
25503
  }
24431
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;
24432
25505
  var init_managed_agent_runtime = __esm({
@@ -24470,14 +25543,36 @@ import {
24470
25543
  SessionManager as SessionManager3
24471
25544
  } from "@earendil-works/pi-coding-agent";
24472
25545
  import { readFileSync as readFileSync11, statSync as statSync9, unlinkSync as unlinkSync12 } from "node:fs";
24473
- 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
24474
25569
  import { setTimeout as delay2 } from "node:timers/promises";
24475
25570
  import { fileURLToPath as fileURLToPath3 } from "node:url";
24476
25571
 
24477
25572
  // package.json
24478
25573
  var package_default = {
24479
25574
  name: "pi-herdsman",
24480
- version: "0.44.0",
25575
+ version: "0.46.0",
24481
25576
  type: "module",
24482
25577
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
24483
25578
  license: "Apache-2.0",
@@ -24526,7 +25621,7 @@ var package_default = {
24526
25621
  },
24527
25622
  piHerdsman: {
24528
25623
  runtime: {
24529
- pi: "1.5.0",
25624
+ pi: "1.5.2",
24530
25625
  herdr: {
24531
25626
  version: "0.9.5",
24532
25627
  sha256: {
@@ -24539,6 +25634,8 @@ var package_default = {
24539
25634
  }
24540
25635
  },
24541
25636
  scripts: {
25637
+ setup: "npm run setup:hooks && npm ci",
25638
+ "setup:hooks": "node scripts/setup-hooks.mjs",
24542
25639
  test: "node --experimental-test-module-mocks --import=./scripts/test-env.mjs --test --test-timeout=10000",
24543
25640
  smoke: "node scripts/smoke.mjs",
24544
25641
  format: "prettier . --write",
@@ -24556,20 +25653,18 @@ var package_default = {
24556
25653
  "@earendil-works/pi-ai": "*",
24557
25654
  "@earendil-works/pi-coding-agent": "*",
24558
25655
  "@earendil-works/pi-tui": "*",
24559
- "@howaboua/pi-codex-conversion": "^3.0.45 || ^4.0.0",
24560
25656
  typebox: "*"
24561
25657
  },
24562
25658
  devDependencies: {
24563
- "@earendil-works/pi-ai": "1.5.0",
24564
- "@earendil-works/pi-coding-agent": "1.5.0",
24565
- "@earendil-works/pi-tui": "1.5.0",
24566
- "@howaboua/pi-codex-conversion": "4.0.4",
24567
- "@modelcontextprotocol/sdk": "1.32.0",
24568
- "@types/node": "22.19.19",
25659
+ "@earendil-works/pi-ai": "1.5.2",
25660
+ "@earendil-works/pi-coding-agent": "1.5.2",
25661
+ "@earendil-works/pi-tui": "1.5.2",
25662
+ "@modelcontextprotocol/sdk": "1.32.2",
25663
+ "@types/node": "22.20.5",
24569
25664
  "@types/proper-lockfile": "4.1.4",
24570
25665
  esbuild: "^0.28.2",
24571
- oxlint: "1.90.0",
24572
- prettier: "3.9.10",
25666
+ oxlint: "1.93.0",
25667
+ prettier: "3.10.1",
24573
25668
  typebox: "^1.3.7",
24574
25669
  typescript: "7.0.2"
24575
25670
  },
@@ -24591,11 +25686,6 @@ var package_default = {
24591
25686
  publishConfig: {
24592
25687
  registry: "https://registry.npmjs.org/"
24593
25688
  },
24594
- peerDependenciesMeta: {
24595
- "@howaboua/pi-codex-conversion": {
24596
- optional: true
24597
- }
24598
- },
24599
25689
  dependencies: {
24600
25690
  "proper-lockfile": "4.1.2"
24601
25691
  }
@@ -24759,7 +25849,7 @@ init_agent_controller();
24759
25849
  init_agent_definitions();
24760
25850
  import { randomUUID as randomUUID12 } from "node:crypto";
24761
25851
  import { realpathSync as realpathSync6, statSync as statSync7, unlinkSync as unlinkSync9 } from "node:fs";
24762
- import { isAbsolute as isAbsolute6, resolve as resolve6 } from "node:path";
25852
+ import { isAbsolute as isAbsolute6, resolve as resolve7 } from "node:path";
24763
25853
  function isFreshLeadStartupAttestation(state, sessionId, previousInstanceId, startedAt) {
24764
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(
24765
25855
  state.startupAttestation.result
@@ -25119,7 +26209,7 @@ function createLeadProjectRuntime(host) {
25119
26209
  const worktree = placement.worktree;
25120
26210
  if (typeof worktree.path !== "string" || !worktree.path || !isAbsolute6(worktree.path) || worktree.is_linked_worktree !== true)
25121
26211
  throw new Error("Herdr worktree checkout path is unavailable");
25122
- const checkoutPath = resolve6(worktree.path);
26212
+ const checkoutPath = resolve7(worktree.path);
25123
26213
  if (sameDirectory(checkoutPath, topology.source.source_checkout_path))
25124
26214
  throw new Error("The Manager's primary checkout cannot be removed");
25125
26215
  if (worktree.open_workspace_id === manager.workspaceId)
@@ -26319,12 +27409,12 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26319
27409
  try {
26320
27410
  const session = host.SessionManager.open(assignment.piSessionFile);
26321
27411
  if (session.getSessionId() !== assignment.id) throw new Error();
26322
- sourcePath = resolve6(session.getCwd());
27412
+ sourcePath = resolve7(session.getCwd());
26323
27413
  } catch {
26324
27414
  throw sourceError;
26325
27415
  }
26326
27416
  if (gitPathStatus(sourcePath) !== "absent" || topology.worktrees.some(
26327
- (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
26328
27418
  ))
26329
27419
  throw sourceError;
26330
27420
  const inventory = await host.pi.exec(
@@ -26336,7 +27426,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26336
27426
  String(inventory.stdout ?? "")
26337
27427
  );
26338
27428
  if (inventory.code !== 0 || inventory.killed || !parsedInventory || parsedInventory.some(
26339
- (worktree) => worktree.branch === branch || resolve6(worktree.path) === sourcePath
27429
+ (worktree) => worktree.branch === branch || resolve7(worktree.path) === sourcePath
26340
27430
  ))
26341
27431
  throw sourceError;
26342
27432
  const finalManager = await host.currentManager(ctx);
@@ -26458,7 +27548,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26458
27548
  if (probe.code !== 0 || probe.killed || probe.stderr?.trim())
26459
27549
  throw new Error("Git operation state is unverifiable");
26460
27550
  try {
26461
- statSync7(resolve6(path, String(probe.stdout ?? "").trim()));
27551
+ statSync7(resolve7(path, String(probe.stdout ?? "").trim()));
26462
27552
  throw new Error(`Git operation ${state} is in progress`);
26463
27553
  } catch (error2) {
26464
27554
  if (error2.code !== "ENOENT" && !(error2 instanceof Error && error2.message.startsWith("Git operation ")))
@@ -26909,7 +27999,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26909
27999
  }
26910
28000
  try {
26911
28001
  statSync7(
26912
- resolve6(targetPath, String(path.stdout ?? "").trim())
28002
+ resolve7(targetPath, String(path.stdout ?? "").trim())
26913
28003
  );
26914
28004
  operationStates.push(state);
26915
28005
  } catch (error2) {
@@ -29049,6 +30139,7 @@ init_config();
29049
30139
  init_agent_definitions();
29050
30140
  init_core();
29051
30141
  init_presentation();
30142
+ import { basename as basename9 } from "node:path";
29052
30143
  import {
29053
30144
  getSupportedThinkingLevels
29054
30145
  } from "@earendil-works/pi-ai";
@@ -29389,15 +30480,219 @@ function createLeadCommandRuntime(host) {
29389
30480
  definition = current;
29390
30481
  const metadata = host.agentDefinitionMetadata(current);
29391
30482
  if (ctx.mode === "tui") {
29392
- const instructions = host.expandAgentBodyFiles(
29393
- current.body,
29394
- [],
29395
- "definition details"
29396
- );
29397
- host.appendDefinitionsEntry({
29398
- definitions: [metadata],
29399
- instructions
29400
- });
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
+ }
29401
30696
  } else {
29402
30697
  ctx.ui.notify(
29403
30698
  host.formatAgentDefinitions([metadata]).join("\n")
@@ -30325,10 +31620,10 @@ init_storage();
30325
31620
  import { createHash as createHash14, randomUUID as randomUUID16 } from "node:crypto";
30326
31621
  import { lstatSync as lstatSync7, realpathSync as realpathSync7, statSync as statSync8 } from "node:fs";
30327
31622
  import {
30328
- dirname as dirname8,
31623
+ dirname as dirname9,
30329
31624
  isAbsolute as isAbsolute7,
30330
31625
  join as join13,
30331
- resolve as resolve7,
31626
+ resolve as resolve8,
30332
31627
  toNamespacedPath
30333
31628
  } from "node:path";
30334
31629
 
@@ -31025,7 +32320,7 @@ function createLeadCoordinationRuntime(host) {
31025
32320
  contentText: contentText6,
31026
32321
  supervisorStateType,
31027
32322
  workspacePresentationProvenance: workspacePresentationProvenance2,
31028
- basename: basename10,
32323
+ basename: basename11,
31029
32324
  readPeerLeadRecord: readPeerLeadRecord2,
31030
32325
  samePeerLeadRecord: samePeerLeadRecord2,
31031
32326
  writePeerLeadRecord: writePeerLeadRecord2,
@@ -31263,7 +32558,7 @@ function createLeadCoordinationRuntime(host) {
31263
32558
  return;
31264
32559
  }
31265
32560
  if (!isCurrent() || peerPresenceRecord !== verified) return;
31266
- 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);
31267
32562
  const enriched = {
31268
32563
  ...verified,
31269
32564
  ...provenance.repoName ? { repo: provenance.repoName } : {},
@@ -33024,11 +34319,21 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
33024
34319
  const projectRoleTools = (baseline, definition, requiredTools) => {
33025
34320
  const policy = configuredToolPolicy(definition, requiredTools);
33026
34321
  const required = new Set(requiredTools);
33027
- const selected = policy.explicit ? policy.tools.flatMap(
34322
+ const selected = policy.mode === "explicit" ? policy.tools.flatMap(
33028
34323
  (pattern) => [...registeredToolNames()].filter(
33029
34324
  (name) => matchesToolPattern(pattern, name)
33030
34325
  )
33031
- ) : [...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];
33032
34337
  return appendRegisteredTools(
33033
34338
  normalizeBaseTools(
33034
34339
  selected.filter((name) => toolPolicyAllowsName(policy, required, name))
@@ -33097,7 +34402,7 @@ async function readGitWorktreeState(git, cwd) {
33097
34402
  }
33098
34403
  async function observeGitChangeSummary(git, checkoutPath, repoKey, comparisonHead) {
33099
34404
  const root2 = (await git(checkoutPath, ["rev-parse", "--show-toplevel"])).trim();
33100
- const common = resolve7(
34405
+ const common = resolve8(
33101
34406
  checkoutPath,
33102
34407
  (await git(checkoutPath, ["rev-parse", "--git-common-dir"])).trim()
33103
34408
  );
@@ -33524,7 +34829,7 @@ function createLeadAgentEventRuntime(host) {
33524
34829
  return;
33525
34830
  }
33526
34831
  try {
33527
- if (host.currentLeadAllowedTools?.() !== void 0)
34832
+ if (host.currentLeadAllowedTools?.() !== void 0 || host.currentLeadRelativePolicy?.() !== void 0)
33528
34833
  host.reconcileRoleTools?.();
33529
34834
  } catch (error2) {
33530
34835
  host.setActiveTools([]);
@@ -33581,6 +34886,22 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
33581
34886
  }
33582
34887
  if (!host.isActiveManager()) {
33583
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
+ }
33584
34905
  const allowed = host.currentLeadAllowedTools?.();
33585
34906
  if (!allowed || allowed.includes(event.toolName)) return void 0;
33586
34907
  } catch {
@@ -33830,6 +35151,15 @@ function registerLeadRuntime(pi, options) {
33830
35151
  leadTools: [...tools]
33831
35152
  });
33832
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
+ };
33833
35163
  const captureInheritedTools = () => {
33834
35164
  const projection = inheritedProjection;
33835
35165
  if (!projection) return;
@@ -33839,7 +35169,7 @@ function registerLeadRuntime(pi, options) {
33839
35169
  }
33840
35170
  const saved = leadToolState.getLeadTools() ?? [];
33841
35171
  const excluded = (name) => projection.excluded.some((pattern) => matchesToolPattern(pattern, name));
33842
- 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));
33843
35173
  const next = leadToolState.normalizeBaseTools([
33844
35174
  ...active,
33845
35175
  ...saved.filter(excluded)
@@ -34225,7 +35555,7 @@ function registerLeadRuntime(pi, options) {
34225
35555
  if (managedLifecycle !== "assigned" || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || leadExecutionPending || !leadExecution?.valid || !leadExecution.managed)
34226
35556
  return managedRecoveryTools();
34227
35557
  const definition = leadExecution.definition;
34228
- const managedBaseline = definition.frontmatter.noTools === true && definition.frontmatter.tools === void 0 ? [] : baseline;
35558
+ const managedBaseline = definition.frontmatter.noTools === true ? [] : baseline;
34229
35559
  return restrict(
34230
35560
  leadToolState.appendRegisteredTools(
34231
35561
  leadToolState.projectLeadTools(managedBaseline, definition),
@@ -34267,10 +35597,12 @@ function registerLeadRuntime(pi, options) {
34267
35597
  setCoordinationHealthy: (healthy) => coordinationRuntime.setCoordinationHealthy(healthy),
34268
35598
  normalizeBaseTools: leadToolState.normalizeBaseTools,
34269
35599
  captureInheritedTools,
34270
- inheritedProjection: () => sessionKind?.kind === "ordinary" && !leadExecutionPending && leadExecution?.valid && !leadExecution.managed && leadExecution.definition.frontmatter.tools === void 0 ? {
34271
- mode: leadExecution.mode,
34272
- excluded: configuredToolPolicy(leadExecution.definition, []).excluded
34273
- } : 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,
34274
35606
  setInheritedProjection: (projection) => {
34275
35607
  inheritedProjection = projection;
34276
35608
  },
@@ -35391,19 +36723,18 @@ function registerLeadRuntime(pi, options) {
35391
36723
  persistLeadExecution(mode, baseline);
35392
36724
  leadToolState.setLeadTools(baseline);
35393
36725
  leadExecution = { mode, definition, valid: true, managed: false };
35394
- inheritedProjection = shouldActivate && definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), targetTools) ? {
35395
- mode,
35396
- excluded: configuredToolPolicy(definition, []).excluded
35397
- } : void 0;
36726
+ inheritedProjection = shouldActivate && sameToolSelection(pi.getActiveTools(), targetTools) ? inheritedProjectionFor(mode, definition, baseline, targetTools) : void 0;
35398
36727
  statusRuntime.requestRefresh();
35399
36728
  } catch (error2) {
35400
36729
  leadExecution = previousExecution;
35401
36730
  try {
35402
36731
  if (shouldActivate) pi.setActiveTools(previousTools);
35403
- inheritedProjection = shouldActivate && previousExecution?.valid && !previousExecution.managed && previousExecution.definition.frontmatter.tools === void 0 && sameToolSelection(pi.getActiveTools(), previousTools) ? {
35404
- mode: previousExecution.mode,
35405
- excluded: configuredToolPolicy(previousExecution.definition, []).excluded
35406
- } : 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;
35407
36738
  } catch {
35408
36739
  inheritedProjection = void 0;
35409
36740
  leadExecution = { mode, valid: false, managed: false };
@@ -35449,18 +36780,30 @@ function registerLeadRuntime(pi, options) {
35449
36780
  };
35450
36781
  const agentEvents = createLeadAgentEventRuntime({
35451
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
+ },
35452
36795
  currentLeadAllowedTools: () => {
35453
36796
  if (sessionKind?.kind === "managed") {
35454
36797
  if (managedLifecycle !== "assigned" || leadExecutionPending || leadRuntime.roleSuspended || leadRuntime.chiefMode === "suspended" || !leadExecution?.valid || !leadExecution.managed)
35455
36798
  return executionTools();
35456
36799
  const policy2 = leadExecution.definition.frontmatter;
35457
- 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;
35458
36801
  }
35459
36802
  if (activeLeadRole(leadRuntime) !== "lead" || leadRuntime.roleSuspended || !leadExecution || leadExecution.managed)
35460
36803
  return void 0;
35461
36804
  if (!leadExecution.valid) return executionTools();
35462
36805
  const policy = leadExecution.definition.frontmatter;
35463
- 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;
35464
36807
  },
35465
36808
  executionPrompt: () => leadExecution && !leadExecution.managed && leadExecution.valid ? leadExecution.definition.body : void 0,
35466
36809
  leadInboxRuntime: inboxRuntime,
@@ -35665,6 +37008,8 @@ This session belongs to a managed Agent restored without its authorized launch c
35665
37008
  liveLead,
35666
37009
  setLeadExecutionMode,
35667
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,
35668
37013
  leadExecutionPresentation: () => sessionKind?.kind === "managed" ? {
35669
37014
  managed: true,
35670
37015
  mode: leadExecution?.mode ?? "orchestrate",
@@ -35709,6 +37054,16 @@ function createLeadIdentityRuntime(host) {
35709
37054
  };
35710
37055
  return { liveAgent, remoteChiefAgent, liveLead };
35711
37056
  }
37057
+ function verifiedOrdinaryLead(candidate, assignments) {
37058
+ const socket = process.env.HERDR_SOCKET_PATH;
37059
+ if (!socket) return false;
37060
+ try {
37061
+ const peer = readPeerLeadRecord(peerRuntime(), candidate.sessionId);
37062
+ return !!peer && peer.socket === socket && peer.workspaceId === candidate.workspaceId && peer.paneId === candidate.paneId && peer.tabId === candidate.tabId && isRemoteOrdinaryLead(peer, assignments);
37063
+ } catch {
37064
+ return false;
37065
+ }
37066
+ }
35712
37067
  function createLeadSupervisionRuntime(host) {
35713
37068
  const loadSupervisionSnapshot = async (ctx, suppliedInventory, suppliedAgents, includeAll = false, classifyBuilds = false, knownTopology, exactSession) => {
35714
37069
  if (host.activeRole() === "chief" && !includeAll) {
@@ -35967,12 +37322,12 @@ function createLeadSupervisionRuntime(host) {
35967
37322
  for (const report of snapshot2.incompatible ?? [])
35968
37323
  if (report.role === "lead" && scope.workspaceIds.includes(report.workspaceId))
35969
37324
  incompatible?.push(report);
35970
- const assignments = host.listProjectAssignments(
37325
+ const assignments2 = host.listProjectAssignments(
35971
37326
  host.supervisionRuntime(),
35972
37327
  manager.repoKey
35973
37328
  );
35974
- const sessions = new Set(assignments.map((assignment) => assignment.id));
35975
- if (sessions.size !== assignments.length)
37329
+ const sessions = new Set(assignments2.map((assignment) => assignment.id));
37330
+ if (sessions.size !== assignments2.length)
35976
37331
  throw new Error("Multiple project assignments match a Lead session");
35977
37332
  const repoManagers = host.listManagerDescriptors(host.supervisionRuntime()).filter((candidate) => candidate.repoKey === manager.repoKey);
35978
37333
  const ordinarySupervisionAvailable = repoManagers.length === 1 && host.sameManagerDescriptor(repoManagers[0], manager);
@@ -36069,7 +37424,7 @@ function createLeadSupervisionRuntime(host) {
36069
37424
  ...lead,
36070
37425
  role: "lead",
36071
37426
  ...sessions.has(lead.lead) ? {
36072
- branch: assignments.find(
37427
+ branch: assignments2.find(
36073
37428
  (assignment) => assignment.id === lead.lead
36074
37429
  ).branch
36075
37430
  } : {},
@@ -36101,19 +37456,25 @@ function createLeadSupervisionRuntime(host) {
36101
37456
  )).agents;
36102
37457
  const managerLeadSessions = /* @__PURE__ */ new Set();
36103
37458
  const descriptors = host.listManagerDescriptors(host.supervisionRuntime());
37459
+ const assignments = globalProjectAssignmentSnapshot();
36104
37460
  for (const lead of allLeads) {
37461
+ if (!verifiedOrdinaryLead(
37462
+ {
37463
+ sessionId: lead.lead,
37464
+ workspaceId: lead.workspaceId,
37465
+ paneId: lead.paneId,
37466
+ tabId: lead.tabId
37467
+ },
37468
+ assignments
37469
+ )) {
37470
+ managerLeadSessions.add(lead.lead);
37471
+ continue;
37472
+ }
36105
37473
  try {
36106
- const scope = await host.worktreeGroupScope(
36107
- host.pi,
36108
- ctx,
36109
- lead.workspaceId,
36110
- ctx.signal
36111
- );
36112
37474
  const supervisor = await host.resolveEffectiveSupervisor(
36113
37475
  ctx,
36114
37476
  lead.lead,
36115
- lead.workspaceId,
36116
- scope
37477
+ lead.workspaceId
36117
37478
  );
36118
37479
  if (supervisor.kind !== "chief") managerLeadSessions.add(lead.lead);
36119
37480
  } catch {
@@ -36123,17 +37484,10 @@ function createLeadSupervisionRuntime(host) {
36123
37484
  for (const lead of allLeadSnapshot.incompatible ?? []) {
36124
37485
  if (lead.role !== "lead") continue;
36125
37486
  try {
36126
- const scope = await host.worktreeGroupScope(
36127
- host.pi,
36128
- ctx,
36129
- lead.workspaceId,
36130
- ctx.signal
36131
- );
36132
37487
  const supervisor = await host.resolveEffectiveSupervisor(
36133
37488
  ctx,
36134
37489
  lead.session,
36135
- lead.workspaceId,
36136
- scope
37490
+ lead.workspaceId
36137
37491
  );
36138
37492
  if (supervisor.kind === "manager") {
36139
37493
  managerLeadSessions.add(lead.session);
@@ -36391,7 +37745,7 @@ function createLeadSupervisionRuntime(host) {
36391
37745
  const identity = async (cwd, expectedCommon) => {
36392
37746
  const root2 = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
36393
37747
  const commonValue = (await git(cwd, ["rev-parse", "--git-common-dir"])).trim();
36394
- const common = resolve7(cwd, commonValue);
37748
+ const common = resolve8(cwd, commonValue);
36395
37749
  return sameDirectory(root2, cwd) && sameDirectory(common, expectedCommon);
36396
37750
  };
36397
37751
  try {
@@ -38019,7 +39373,7 @@ function createLeadInboxRuntime(host) {
38019
39373
  drainCoordinationInbox: drainCoordinationInbox2,
38020
39374
  currentPeerPresenceValid,
38021
39375
  drainProjectMessages,
38022
- basename: basename10,
39376
+ basename: basename11,
38023
39377
  managerDiagnosticEvents
38024
39378
  } = host;
38025
39379
  const chiefStartPreflightHeld = (ctx) => {
@@ -38183,12 +39537,23 @@ function createLeadInboxRuntime(host) {
38183
39537
  if (record.kind === "lead_message") {
38184
39538
  const leads = await liveLead(ctx, record.fromSessionId);
38185
39539
  if (leads.length !== 1) return false;
39540
+ const sender = leads[0];
39541
+ if (!verifiedOrdinaryLead(
39542
+ {
39543
+ sessionId: record.fromSessionId,
39544
+ workspaceId: sender.workspace_id,
39545
+ paneId: sender.pane_id,
39546
+ tabId: sender.tab_id
39547
+ },
39548
+ globalProjectAssignmentSnapshot()
39549
+ ))
39550
+ return false;
38186
39551
  let scope2;
38187
39552
  try {
38188
39553
  scope2 = await worktreeGroupScope2(
38189
39554
  pi,
38190
39555
  ctx,
38191
- leads[0].workspace_id,
39556
+ sender.workspace_id,
38192
39557
  ctx.signal
38193
39558
  );
38194
39559
  } catch (error2) {
@@ -38202,7 +39567,7 @@ function createLeadInboxRuntime(host) {
38202
39567
  const supervisor = await host.resolveEffectiveSupervisor(
38203
39568
  ctx,
38204
39569
  record.fromSessionId,
38205
- leads[0].workspace_id,
39570
+ sender.workspace_id,
38206
39571
  scope2
38207
39572
  );
38208
39573
  return !!state2 && (state2.role ?? "lead") === "lead" && supervisor.kind === "chief" && supervisor.chief.piSessionId === chief.piSessionId && supervisor.chief.leaseId === chief.leaseId;
@@ -38266,6 +39631,8 @@ function createLeadInboxRuntime(host) {
38266
39631
  }
38267
39632
  if (activeRole() !== "lead" || leadRuntime.roleSuspended) return false;
38268
39633
  if (record.kind === "chief_message") {
39634
+ if (readSessionKind(ctx.sessionManager.getEntries(), sessionId)?.kind !== "ordinary")
39635
+ return false;
38269
39636
  const chief = await currentChiefAuthority(ctx);
38270
39637
  const workspaceId2 = host.workspaceId();
38271
39638
  if (!workspaceId2) return false;
@@ -38751,7 +40118,7 @@ function createLeadInboxRuntime(host) {
38751
40118
  (path) => !chiefMessageQuarantined2(
38752
40119
  runtime,
38753
40120
  sessionId,
38754
- basename10(path, ".json")
40121
+ basename11(path, ".json")
38755
40122
  )
38756
40123
  )) {
38757
40124
  const message = await prepareSupervisionMessage(ctx);
@@ -39543,13 +40910,13 @@ function createLeadRoleTransitions(state, host) {
39543
40910
  try {
39544
40911
  const session = host.SessionManager.open(assignment.piSessionFile);
39545
40912
  if (session.getSessionId() !== assignment.id) return void 0;
39546
- return resolve7(session.getCwd());
40913
+ return resolve8(session.getCwd());
39547
40914
  } catch {
39548
40915
  return void 0;
39549
40916
  }
39550
40917
  };
39551
40918
  const checkoutProvenance = (assignment) => {
39552
- const recorded = assignment.checkoutPath ? resolve7(assignment.checkoutPath) : void 0;
40919
+ const recorded = assignment.checkoutPath ? resolve8(assignment.checkoutPath) : void 0;
39553
40920
  const session = knownSessionCheckoutPath(assignment);
39554
40921
  return {
39555
40922
  path: recorded ?? session,
@@ -39559,10 +40926,10 @@ function createLeadRoleTransitions(state, host) {
39559
40926
  const checkoutMaySurvive = (assignment, inventory, checkoutPath = checkoutProvenance(assignment).path) => {
39560
40927
  if (checkoutPath)
39561
40928
  return gitPathStatus(checkoutPath) !== "absent" || inventory.some(
39562
- (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")
39563
40930
  );
39564
40931
  return inventory.some(
39565
- (worktree) => resolve7(worktree.path) !== resolve7(sourceCheckoutPath) && gitPathStatus(worktree.path) !== "absent"
40932
+ (worktree) => resolve8(worktree.path) !== resolve8(sourceCheckoutPath) && gitPathStatus(worktree.path) !== "absent"
39566
40933
  );
39567
40934
  };
39568
40935
  for (const observed of assignments) {
@@ -40003,7 +41370,7 @@ function createLeadRoleTransitions(state, host) {
40003
41370
  throw new Error(
40004
41371
  "/manager requires interactive confirmation to initialize Git"
40005
41372
  );
40006
- const target = realpathSync7(resolve7(ctx.cwd));
41373
+ const target = realpathSync7(resolve8(ctx.cwd));
40007
41374
  const targetStat = statSync8(target, { bigint: true });
40008
41375
  if (!targetStat.isDirectory() || targetStat.dev === 0n || targetStat.ino === 0n)
40009
41376
  throw new Error("Manager Git target is not a directory");
@@ -40040,7 +41407,7 @@ function createLeadRoleTransitions(state, host) {
40040
41407
  ))
40041
41408
  throw new Error("Manager activation cancelled.");
40042
41409
  await verifyHerdrTarget();
40043
- 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) || (() => {
40044
41411
  const current = statSync8(target, { bigint: true });
40045
41412
  return current.dev !== targetStat.dev || current.ino !== targetStat.ino;
40046
41413
  })())
@@ -40083,13 +41450,13 @@ function createLeadRoleTransitions(state, host) {
40083
41450
  let directory2 = target;
40084
41451
  while (true) {
40085
41452
  try {
40086
- lstatSync7(resolve7(directory2, ".git"));
41453
+ lstatSync7(resolve8(directory2, ".git"));
40087
41454
  return true;
40088
41455
  } catch (error3) {
40089
41456
  if (error3.code !== "ENOENT")
40090
41457
  throw error3;
40091
41458
  }
40092
- const parent = dirname8(directory2);
41459
+ const parent = dirname9(directory2);
40093
41460
  if (parent === directory2) return false;
40094
41461
  directory2 = parent;
40095
41462
  }
@@ -41035,12 +42402,23 @@ function registerExtensionImpl(pi, lockHooks) {
41035
42402
  ))
41036
42403
  return void 0;
41037
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;
41038
42415
  return expandablePresentation(
41039
42416
  options.expanded,
41040
42417
  (expanded) => renderAgentDefinitionsOverview(definitions, theme, {
41041
42418
  ...options,
41042
42419
  expanded,
41043
- instructions
42420
+ instructions,
42421
+ inspector
41044
42422
  })
41045
42423
  );
41046
42424
  });
@@ -41092,6 +42470,13 @@ function registerExtensionImpl(pi, lockHooks) {
41092
42470
  (expanded) => renderAgentAskMessage(message, { ...options, expanded }, theme)
41093
42471
  )
41094
42472
  );
42473
+ pi.registerMessageRenderer(
42474
+ "pi-herdsman-agent-owner-message",
42475
+ (message, options, theme) => expandablePresentation(
42476
+ options.expanded,
42477
+ (expanded) => renderAgentOwnerMessage(message, { ...options, expanded }, theme)
42478
+ )
42479
+ );
41095
42480
  pi.registerMessageRenderer(
41096
42481
  "pi-herdsman-agent-stale",
41097
42482
  (message, options, theme) => expandablePresentation(
@@ -41262,6 +42647,33 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
41262
42647
  { triggerTurn }
41263
42648
  );
41264
42649
  },
42650
+ sendOwnerMessage: (ctx, ownerMessage, triggerTurn = true) => {
42651
+ if (ctx.sessionManager.getSessionId() !== ownerMessage.ownerSessionId)
42652
+ throw new Error("Owner notification recipient session changed");
42653
+ pi.sendMessage(
42654
+ {
42655
+ customType: "pi-herdsman-agent-owner-message",
42656
+ content: `Agent ${ownerMessage.agentLabel} notification:
42657
+
42658
+ ${ownerMessage.text}`,
42659
+ display: true,
42660
+ details: {
42661
+ messageId: ownerMessage.messageId,
42662
+ requestId: ownerMessage.requestId,
42663
+ runId: ownerMessage.runId,
42664
+ ownerSessionId: ownerMessage.ownerSessionId,
42665
+ workspaceId: ownerMessage.workspaceId,
42666
+ agentLabel: ownerMessage.agentLabel,
42667
+ paneId: ownerMessage.paneId,
42668
+ piSessionId: ownerMessage.piSessionId
42669
+ }
42670
+ },
42671
+ {
42672
+ triggerTurn,
42673
+ ...triggerTurn ? { deliverAs: "steer" } : {}
42674
+ }
42675
+ );
42676
+ },
41265
42677
  sessionRetired: (ctx, runtime) => {
41266
42678
  if (!runtime.piSessionFile) return void 0;
41267
42679
  try {
@@ -41477,20 +42889,22 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
41477
42889
  const normalizeLeadTools = (tools) => leadToolState.normalizeLeadTools(tools);
41478
42890
  let roleTransitions;
41479
42891
  const isCurrentChief = (ctx) => leadRuntime.chiefMode === "active" && !!leadRuntime.chiefLease && leadRuntime.chiefLease.descriptor.piSessionId === ctx.sessionManager.getSessionId();
41480
- const chiefSystemPrompt = (options, body) => {
41481
- const agentDir = resolve8(getAgentDir3());
41482
- const globalInstructions = (options?.contextFiles ?? []).filter(
41483
- ({ path, content }) => typeof path === "string" && typeof content === "string" && resolve8(dirname9(path)) === agentDir && content.length > 0
41484
- ).map(({ content }) => content).join("\n\n");
41485
- return [
41486
- CHIEF_ROLE_CONTRACT,
41487
- body || void 0,
41488
- 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}
41489
42901
 
41490
- <global_instructions>
41491
- ${globalInstructions}
41492
- </global_instructions>` : void 0
41493
- ].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.`;
41494
42908
  };
41495
42909
  const markLeadCoordinationUnhealthy = (ctx) => leadRuntimes.coordinationRuntime.markLeadCoordinationUnhealthy(ctx);
41496
42910
  const schedulePeerPresence = (ctx) => leadRuntimes.coordinationRuntime.schedulePeerPresence(ctx);
@@ -41647,22 +43061,8 @@ ${globalInstructions}
41647
43061
  setActiveTools: (tools) => pi.setActiveTools(tools),
41648
43062
  prepareSupervisionMessage,
41649
43063
  sendMessage: (message) => pi.sendMessage(message, { triggerTurn: false }),
41650
- chiefSystemPrompt,
41651
- roleCharter: (ctx) => {
41652
- const role2 = activeRole();
41653
- if (leadRuntime.roleSuspended || role2 === "chief" && !isCurrentChief(ctx) || role2 === "manager" && !leadRuntime.managerLease)
41654
- return `## Herdsman role
41655
- No active Herdsman role is verified for this Pi session.`;
41656
- if (role2 === "manager")
41657
- return `${MANAGER_ROLE_CONTRACT}
41658
-
41659
- ${leadRuntimes.supervisoryProfileBody(ctx, "manager")}`;
41660
- const kind = leadRuntimes.sessionKindForPrompt(ctx);
41661
- if (kind === "ordinary") return ORDINARY_LEAD_CHARTER;
41662
- if (kind === "managed") return MANAGED_LEAD_CHARTER;
41663
- return `## Herdsman role
41664
- No active Herdsman role is verified for this Pi session.`;
41665
- },
43064
+ chiefSystemPrompt: chiefSystemPrompt2,
43065
+ roleCharter,
41666
43066
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
41667
43067
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
41668
43068
  currentManagerAllowedTools: (ctx) => leadRuntimes.currentManagerAllowedTools(ctx),
@@ -41841,11 +43241,24 @@ ${summary}`,
41841
43241
  updateProjectOverride,
41842
43242
  contextAgentDefinitions,
41843
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,
41844
43258
  setLeadExecutionMode: (ctx, mode) => leadRuntimes.setLeadExecutionMode(ctx, mode),
41845
43259
  leadExecutionPresentation: () => leadRuntimes.leadExecutionPresentation(),
41846
43260
  agentDefinitionEnabled,
41847
43261
  agentDefinitionMetadata,
41848
- expandAgentBodyFiles,
41849
43262
  appendDefinitionsEntry: (data) => pi.appendEntry(AGENT_DEFINITIONS_ENTRY, data),
41850
43263
  formatAgentDefinitions,
41851
43264
  validThinkingLevels: VALID_THINKING_LEVELS,
@@ -42380,7 +43793,7 @@ ${summary}`,
42380
43793
  peerLeadLockPath,
42381
43794
  worktreeGroupScope,
42382
43795
  workspacePresentationProvenance,
42383
- basename: basename9,
43796
+ basename: basename10,
42384
43797
  readPeerLeadRecord,
42385
43798
  samePeerLeadRecord,
42386
43799
  writePeerLeadRecord,
@@ -42446,7 +43859,7 @@ ${summary}`,
42446
43859
  listChiefMessagePaths,
42447
43860
  chiefMessageQuarantined,
42448
43861
  drainCoordinationInbox,
42449
- basename: basename9
43862
+ basename: basename10
42450
43863
  },
42451
43864
  agentEventOptions: leadAgentEventOptions,
42452
43865
  sessionStartOptions,