pi-herdsman 0.43.0 → 0.45.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
@@ -1293,6 +1293,19 @@ function validate(value2, kind) {
1293
1293
  "evidenceAssignmentId",
1294
1294
  "taskEvidenceId",
1295
1295
  "createdAt"
1296
+ ] : kind === "ownerMessage" ? [
1297
+ "version",
1298
+ "messageId",
1299
+ "requestId",
1300
+ "runId",
1301
+ "ownerSessionId",
1302
+ "workspaceId",
1303
+ "agentLabel",
1304
+ "paneId",
1305
+ "piSessionId",
1306
+ "text",
1307
+ "resultBindings",
1308
+ "createdAt"
1296
1309
  ] : kind === "ask" ? [
1297
1310
  "version",
1298
1311
  "askId",
@@ -1334,6 +1347,15 @@ function validate(value2, kind) {
1334
1347
  "paneId",
1335
1348
  "piSessionId",
1336
1349
  "cwd"
1350
+ ] : kind === "ownerMessage" ? [
1351
+ "messageId",
1352
+ "requestId",
1353
+ "runId",
1354
+ "ownerSessionId",
1355
+ "workspaceId",
1356
+ "agentLabel",
1357
+ "paneId",
1358
+ "piSessionId"
1337
1359
  ] : kind === "ask" ? [
1338
1360
  "askId",
1339
1361
  "requestId",
@@ -1354,7 +1376,7 @@ function validate(value2, kind) {
1354
1376
  for (const field of required)
1355
1377
  if (typeof v[field] !== "string" || !v[field].trim())
1356
1378
  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))
1379
+ if (!UUID2.test(v.runId) || kind !== "state" && !UUID2.test(v.requestId) || kind === "ask" && !UUID2.test(v.askId) || kind === "ownerMessage" && !UUID2.test(v.messageId))
1358
1380
  throw new Error("Invalid mailbox UUID");
1359
1381
  const finite = (field) => {
1360
1382
  if (typeof v[field] !== "number" || !Number.isFinite(v[field]) || v[field] < 0)
@@ -1473,6 +1495,12 @@ function validate(value2, kind) {
1473
1495
  if (hasProjectAssignmentId && (typeof v.projectAssignmentId !== "string" || !UUID2.test(v.projectAssignmentId)) || hasEvidenceAssignmentId && (typeof v.evidenceAssignmentId !== "string" || !UUID2.test(v.evidenceAssignmentId)))
1474
1496
  throw new Error("Invalid request evidence assignment identity");
1475
1497
  finite("createdAt");
1498
+ } else if (kind === "ownerMessage") {
1499
+ if (typeof v.text !== "string" || !v.text.trim())
1500
+ throw new Error("Invalid owner message text");
1501
+ if (v.resultBindings !== void 0 && (!Array.isArray(v.resultBindings) || !v.resultBindings.every(isResultBinding)))
1502
+ throw new Error("Invalid owner message result bindings");
1503
+ finite("createdAt");
1476
1504
  } else if (kind === "ask") {
1477
1505
  if (typeof v.question !== "string" || !v.question.trim())
1478
1506
  throw new Error("Invalid ask question");
@@ -1579,7 +1607,7 @@ function resetAgentMailbox(path) {
1579
1607
  "ask.json",
1580
1608
  "bootstrap.json",
1581
1609
  ...readdirSync3(path).filter(
1582
- (x) => /^(request|result)-.*\.json$/.test(x)
1610
+ (x) => /^(request|result|owner-message)-.*\.json$/.test(x)
1583
1611
  )
1584
1612
  ]) {
1585
1613
  try {
@@ -1734,6 +1762,36 @@ function removeAsk(path) {
1734
1762
  if (e.code !== "ENOENT") throw e;
1735
1763
  }
1736
1764
  }
1765
+ function writeOwnerMessage(path, message) {
1766
+ assertFileId(message.messageId);
1767
+ atomic(
1768
+ file(path, `owner-message-${message.messageId}.json`),
1769
+ message,
1770
+ "ownerMessage"
1771
+ );
1772
+ }
1773
+ function readOwnerMessages(path) {
1774
+ return readdirSync3(path).filter((name) => name.startsWith("owner-message-")).map((name) => {
1775
+ if (!/^owner-message-[0-9a-f-]+\.json$/iu.test(name))
1776
+ throw new Error(`Malformed owner message filename: ${name}`);
1777
+ const record = read(file(path, name), "ownerMessage");
1778
+ if (!record) throw new Error("Owner message disappeared while reading");
1779
+ validate(record, "ownerMessage");
1780
+ if (name !== `owner-message-${record.messageId}.json`)
1781
+ throw new Error("Owner message filename identity mismatch");
1782
+ return record;
1783
+ }).sort(
1784
+ (a, b) => a.createdAt - b.createdAt || a.messageId.localeCompare(b.messageId)
1785
+ );
1786
+ }
1787
+ function removeOwnerMessage(path, messageId) {
1788
+ assertFileId(messageId);
1789
+ try {
1790
+ unlinkSync3(file(path, `owner-message-${messageId}.json`));
1791
+ } catch (error2) {
1792
+ if (error2.code !== "ENOENT") throw error2;
1793
+ }
1794
+ }
1737
1795
  function writeResult(path, result) {
1738
1796
  assertFileId(result.requestId);
1739
1797
  atomic(file(path, `result-${result.requestId}.json`), result, "result");
@@ -1845,6 +1903,7 @@ var init_mailbox = __esm({
1845
1903
  state: 64 * 1024,
1846
1904
  request: MAILBOX_PROTOCOL_LIMIT_BYTES,
1847
1905
  ask: MAILBOX_PROTOCOL_LIMIT_BYTES,
1906
+ ownerMessage: MAILBOX_PROTOCOL_LIMIT_BYTES,
1848
1907
  result: 4 * 1024 * 1024
1849
1908
  };
1850
1909
  root = join3(herdsmanDataRoot(), "runtime", "mailboxes-v5");
@@ -2490,6 +2549,12 @@ function configuredToolPolicy(definition, requiredTools) {
2490
2549
  excluded
2491
2550
  };
2492
2551
  }
2552
+ function toolPolicyAllowsName(policy, requiredTools, name) {
2553
+ if (requiredTools.has(name)) return true;
2554
+ if (policy.excluded.some((pattern) => matchesToolPattern(pattern, name)))
2555
+ return false;
2556
+ return !policy.explicit || policy.tools.some((pattern) => matchesToolPattern(pattern, name));
2557
+ }
2493
2558
  function readOptionalAgentDefinitions(root2, category, onWarning) {
2494
2559
  const stats = statSync3(root2, { throwIfNoEntry: false });
2495
2560
  if (!stats) return [];
@@ -3152,10 +3217,11 @@ function agentLaunchArgs(agent, options) {
3152
3217
  const requiredTools = [
3153
3218
  ...managedAgent ? agentDefinitionDelegationEnabled(agent) ? [
3154
3219
  ...AGENT_COORDINATION_TOOLS,
3155
- "ask_owner",
3220
+ "await_owner",
3221
+ "notify_owner",
3156
3222
  "read_evidence",
3157
3223
  "attach_handoff"
3158
- ] : ["ask_owner", "read_evidence", "attach_handoff"] : [],
3224
+ ] : ["await_owner", "notify_owner", "read_evidence", "attach_handoff"] : [],
3159
3225
  ...options.requiredTools ?? []
3160
3226
  ].filter((tool, index, all) => all.indexOf(tool) === index);
3161
3227
  const policy = configuredToolPolicy(agent, requiredTools);
@@ -6151,6 +6217,8 @@ async function drainCoordinationInbox(options) {
6151
6217
  let delivered = 0;
6152
6218
  let examined = 0;
6153
6219
  for (const path of allChiefMessagePaths(options.runtime, options.sessionId)) {
6220
+ if (options.maxDeliveries !== void 0 && delivered >= options.maxDeliveries)
6221
+ break;
6154
6222
  if (examined >= COORDINATION_INBOX_SCAN_LIMIT) break;
6155
6223
  if (options.signal?.aborted) break;
6156
6224
  const id = basename5(path, ".json");
@@ -6322,7 +6390,7 @@ async function drainCoordinationInbox(options) {
6322
6390
  },
6323
6391
  {
6324
6392
  deliverAs: deliverAs ?? "followUp",
6325
- triggerTurn: record.kind !== "project_assignment" || !hasResumeInstruction
6393
+ triggerTurn: options.forceNonTriggering ? false : record.kind !== "project_assignment" || !hasResumeInstruction
6326
6394
  },
6327
6395
  record
6328
6396
  );
@@ -7504,7 +7572,7 @@ function writeProjectMessageUnlocked(record, runtime) {
7504
7572
  }
7505
7573
  if (cleanupFailed) throw cleanupError;
7506
7574
  }
7507
- function listProjectMessageHeaders(runtime, repoKey, branch) {
7575
+ function listProjectMessageHeaders(runtime, repoKey, branch, onReadError) {
7508
7576
  const directory2 = projectMessageDirectory(runtime, repoKey, branch);
7509
7577
  let entries;
7510
7578
  try {
@@ -7524,6 +7592,10 @@ function listProjectMessageHeaders(runtime, repoKey, branch) {
7524
7592
  } catch (error2) {
7525
7593
  if (error2 instanceof Error && error2.cause?.code === "ENOENT")
7526
7594
  return [];
7595
+ if (onReadError) {
7596
+ onReadError(error2);
7597
+ return [];
7598
+ }
7527
7599
  throw error2;
7528
7600
  }
7529
7601
  }).sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id));
@@ -8072,6 +8144,46 @@ var init_supervision = __esm({
8072
8144
  }
8073
8145
  });
8074
8146
 
8147
+ // extension/recipient-fan-in.ts
8148
+ function recipientFanInBudget() {
8149
+ return { count: 0, bytes: 0 };
8150
+ }
8151
+ function includeFanInMessage(budget, content, maximumBytes = MAX_BYTES) {
8152
+ const bytes = Buffer.byteLength(content, "utf8");
8153
+ if (budget.count >= COORDINATION_INBOX_SCAN_LIMIT || budget.count > 0 && budget.bytes + bytes > maximumBytes)
8154
+ return false;
8155
+ budget.count++;
8156
+ budget.bytes += bytes;
8157
+ return true;
8158
+ }
8159
+ function releaseFanInMessage(budget, content) {
8160
+ budget.count = Math.max(0, budget.count - 1);
8161
+ budget.bytes = Math.max(0, budget.bytes - Buffer.byteLength(content, "utf8"));
8162
+ }
8163
+ function registerRecipientFanIn(pi, drain) {
8164
+ pi.on("before_agent_start", async (event, ctx) => {
8165
+ await drain(ctx, "startup", recipientFanInBudget());
8166
+ });
8167
+ pi.on("turn_end", async (event, ctx) => {
8168
+ if (event?.outcome !== "completed") return;
8169
+ const count = await drain(ctx, "turn", recipientFanInBudget());
8170
+ if (count > 0) return { continue: true };
8171
+ });
8172
+ pi.on("agent_before_settle", async (event, ctx) => {
8173
+ if (event?.outcome !== "completed") return;
8174
+ const count = await drain(ctx, "settle", recipientFanInBudget());
8175
+ if (count > 0) return { continue: true };
8176
+ });
8177
+ }
8178
+ var MAX_BYTES;
8179
+ var init_recipient_fan_in = __esm({
8180
+ "extension/recipient-fan-in.ts"() {
8181
+ "use strict";
8182
+ init_supervision();
8183
+ MAX_BYTES = 256 * 1024;
8184
+ }
8185
+ });
8186
+
8075
8187
  // extension/presentation.ts
8076
8188
  import {
8077
8189
  DynamicBorder,
@@ -11038,6 +11150,44 @@ function renderAgentAskMessage(message, options, theme) {
11038
11150
  }
11039
11151
  return renderMessageBox(content, theme, options.outputPad ?? 0);
11040
11152
  }
11153
+ function renderAgentOwnerMessage(message, options, theme) {
11154
+ const details = isRecord2(message.details) ? message.details : {};
11155
+ const agentLabel = value(details.agentLabel);
11156
+ const label = /^[a-z][a-z0-9_-]{0,31}$/u.test(agentLabel) ? agentLabel : "agent";
11157
+ const heading = `${humanText(theme, "accent", "\u2709")} ${theme.bold(label)} notified owner`;
11158
+ const rawBody = contentText(message.content ?? "");
11159
+ const body = rawBody.startsWith(`Agent ${label} notification:
11160
+
11161
+ `) ? rawBody.slice(`Agent ${label} notification:
11162
+
11163
+ `.length) : label === "agent" ? rawBody.replace(/^Agent [^\n]+ notification:\n\n/u, "") : rawBody;
11164
+ const content = new Container();
11165
+ content.addChild(new Text(heading, 0, 0));
11166
+ if (options.expanded) {
11167
+ if (body) {
11168
+ content.addChild(new Spacer(1));
11169
+ content.addChild(new Markdown(body, 0, 0, getMarkdownTheme()));
11170
+ }
11171
+ const metadata = [
11172
+ ...value(details.messageId) ? [`message: ${value(details.messageId)}`] : [],
11173
+ ...value(details.requestId) ? [`request: ${value(details.requestId)}`] : [],
11174
+ ...value(details.piSessionId) ? [`session: ${value(details.piSessionId)}`] : []
11175
+ ];
11176
+ if (metadata.length) {
11177
+ content.addChild(new Spacer(1));
11178
+ content.addChild(new WidthSafeText(metadata.join("\n"), 0, 0));
11179
+ }
11180
+ } else {
11181
+ const preview = collapseDisplayText(body, 200);
11182
+ if (preview)
11183
+ content.addChild(
11184
+ new Markdown(` ${preview}`, 0, 0, getMarkdownTheme(), {
11185
+ color: (text) => humanText(theme, "muted", text)
11186
+ })
11187
+ );
11188
+ }
11189
+ return renderMessageBox(content, theme, options.outputPad ?? 0);
11190
+ }
11041
11191
  function renderAgentAttentionMessage(message, options, theme) {
11042
11192
  const details = message.details && typeof message.details === "object" ? message.details : {};
11043
11193
  const label = value(details.agentLabel) || "agent";
@@ -13845,7 +13995,12 @@ function createAgentStatusRuntime() {
13845
13995
  statusRefresh = false;
13846
13996
  statusInFlight = false;
13847
13997
  onStatusChange = void 0;
13848
- presentedStatus = { agents: [], stale: false, unavailable: true };
13998
+ lastValidStatus = {
13999
+ agents: [],
14000
+ stale: false,
14001
+ unavailable: true
14002
+ };
14003
+ presentedStatus = lastValidStatus;
13849
14004
  },
13850
14005
  prepareSession: (ctx, beforeActivate) => {
13851
14006
  clearTimer();
@@ -14818,6 +14973,13 @@ function hasDeliveredAsk(entries, ask) {
14818
14973
  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;
14819
14974
  });
14820
14975
  }
14976
+ function hasDeliveredOwnerMessage(entries, ownerMessage) {
14977
+ return entries.some((entry) => {
14978
+ const message = entry?.message;
14979
+ const details = entry?.details ?? message?.details;
14980
+ 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;
14981
+ });
14982
+ }
14821
14983
  function canonicalSessionPath(path) {
14822
14984
  try {
14823
14985
  return realpathSync4(path);
@@ -15990,8 +16152,11 @@ function createAgentController(pi, options) {
15990
16152
  const pendingStarts = /* @__PURE__ */ new Map();
15991
16153
  const resultWatchers = /* @__PURE__ */ new Map();
15992
16154
  const askWatchers = /* @__PURE__ */ new Map();
16155
+ const ownerMessageWatchers = /* @__PURE__ */ new Map();
15993
16156
  const resultDeliveryInFlight = /* @__PURE__ */ new Set();
15994
16157
  const askDeliveryInFlight = /* @__PURE__ */ new Set();
16158
+ const ownerMessageDeliveryInFlight = /* @__PURE__ */ new Set();
16159
+ const submittedOwnerMessages = /* @__PURE__ */ new Set();
15995
16160
  const resultDeliveryRetries = /* @__PURE__ */ new Map();
15996
16161
  const resultCleanupRetries = /* @__PURE__ */ new Map();
15997
16162
  const askDeliveryRetries = /* @__PURE__ */ new Map();
@@ -16806,6 +16971,8 @@ function createAgentController(pi, options) {
16806
16971
  watchResult(runtime, context, signal);
16807
16972
  if (runtime.activeRequestId === requestId)
16808
16973
  watchAsk(runtime, context, signal);
16974
+ if (runtime.activeRequestId === requestId)
16975
+ watchOwnerMessages(runtime, context, signal);
16809
16976
  }
16810
16977
  return requestId;
16811
16978
  } finally {
@@ -16906,7 +17073,7 @@ function createAgentController(pi, options) {
16906
17073
  if (kind === "steer" && agent.steerable !== true) {
16907
17074
  const current = readAgentState(runtime.mailboxPath);
16908
17075
  const pendingRequest = current ? readUnacknowledgedRequest(runtime.mailboxPath, current) : void 0;
16909
- 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.";
17076
+ 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.";
16910
17077
  fail(
16911
17078
  "agent_busy",
16912
17079
  `Agent is not currently accepting steering: ${controlState}`,
@@ -16945,7 +17112,7 @@ function createAgentController(pi, options) {
16945
17112
  }
16946
17113
  if (!current?.activeRequestId || !askId || !ask)
16947
17114
  fail("agent_busy", "Agent is not waiting for an owner reply", "reply", {
16948
- nextAction: "Use reply_agent only for an outstanding ask_owner question; otherwise continue normal control or refresh with list_agents."
17115
+ nextAction: "Use reply_agent only for an outstanding await_owner question; otherwise continue normal control or refresh with list_agents."
16949
17116
  });
16950
17117
  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)
16951
17118
  fail("target_not_found", "Agent ask identity did not match", "reply");
@@ -17289,6 +17456,8 @@ function createAgentController(pi, options) {
17289
17456
  ].some((id) => !!id && id !== requestId);
17290
17457
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17291
17458
  throw new Error("Managed agent changed before result cleanup");
17459
+ if (!clearConfirmedOwnerMessages(mailbox, current, context))
17460
+ throw new Error("Owner notification receipt is still unconfirmed");
17292
17461
  const presence = managedAgentPresence(
17293
17462
  current,
17294
17463
  await herdrSessionSnapshot(pi, context, signal)
@@ -17327,16 +17496,21 @@ function createAgentController(pi, options) {
17327
17496
  current = readAgentState(mailbox);
17328
17497
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17329
17498
  throw new Error("Managed agent changed during result cleanup");
17499
+ if (!clearConfirmedOwnerMessages(mailbox, current, context))
17500
+ throw new Error("Owner notification receipt is still unconfirmed");
17330
17501
  removeResult(mailbox, requestId);
17331
17502
  const after = readAgentState(mailbox);
17332
- if (sameIdentity2(after) && !after.activeRequestId && after.completedRequestId === requestId && !hasNewerWork(after))
17503
+ if (sameIdentity2(after) && !after.activeRequestId && after.completedRequestId === requestId && !hasNewerWork(after)) {
17504
+ if (!clearConfirmedOwnerMessages(mailbox, after, context))
17505
+ throw new Error("Owner notification receipt is still unconfirmed");
17333
17506
  removeAgentMailbox(mailbox);
17507
+ }
17334
17508
  invalidateRuntime(state.agentLabel);
17335
17509
  } finally {
17336
17510
  release?.();
17337
17511
  }
17338
17512
  };
17339
- const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false) => {
17513
+ const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false, preserveOwnerMessages = false) => {
17340
17514
  const state = snapshot2.state;
17341
17515
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
17342
17516
  const release = assignmentLockHeld ? void 0 : claimAssignmentLock3(mailbox, "close", {
@@ -17353,6 +17527,8 @@ function createAgentController(pi, options) {
17353
17527
  let current = readAgentState(mailbox);
17354
17528
  if (!current || !sameIdentity(current, state))
17355
17529
  fail("target_ambiguous", "Managed agent changed before close", "close");
17530
+ if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
17531
+ throw new Error("Owner notification receipt is still unconfirmed");
17356
17532
  if (hasDurableResult(mailbox, current))
17357
17533
  fail(
17358
17534
  "target_ambiguous",
@@ -17419,6 +17595,8 @@ function createAgentController(pi, options) {
17419
17595
  );
17420
17596
  }
17421
17597
  try {
17598
+ if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
17599
+ throw new Error("Owner notification receipt is still unconfirmed");
17422
17600
  removeAgentMailbox(mailbox);
17423
17601
  } catch (error2) {
17424
17602
  const message = `Agent pane closed but mailbox cleanup failed: ${String(error2)}`;
@@ -17490,7 +17668,14 @@ function createAgentController(pi, options) {
17490
17668
  deliveredRootResultId
17491
17669
  );
17492
17670
  try {
17493
- await closeSnapshot(context, child, signal, report);
17671
+ await closeSnapshot(
17672
+ context,
17673
+ child,
17674
+ signal,
17675
+ report,
17676
+ false,
17677
+ deliveredRootResultId !== void 0
17678
+ );
17494
17679
  if (readAgentState(
17495
17680
  agentMailboxPath(child.state.workspaceId, child.state.agentLabel)
17496
17681
  ))
@@ -17698,12 +17883,20 @@ function createAgentController(pi, options) {
17698
17883
  askWatchers.get(path)?.();
17699
17884
  askWatchers.delete(path);
17700
17885
  };
17886
+ const stopOwnerMessageWatcher = (runtime) => {
17887
+ ownerMessageWatchers.get(runtime.mailboxPath)?.();
17888
+ ownerMessageWatchers.delete(runtime.mailboxPath);
17889
+ };
17701
17890
  const invalidateRuntime = (label, workspaceId) => {
17702
17891
  const runtime = runtimes.get(label);
17703
17892
  if (!runtime || workspaceId !== void 0 && runtime.workspaceId !== workspaceId)
17704
17893
  return;
17705
17894
  stopResultWatcher(runtime);
17706
17895
  stopAskWatcher(runtime);
17896
+ stopOwnerMessageWatcher(runtime);
17897
+ for (const key of submittedOwnerMessages)
17898
+ if (key.startsWith(`${runtime.mailboxPath}:`))
17899
+ submittedOwnerMessages.delete(key);
17707
17900
  cancelAskRetries(runtime);
17708
17901
  for (const requestId of [
17709
17902
  runtime.activeRequestId,
@@ -17723,7 +17916,7 @@ function createAgentController(pi, options) {
17723
17916
  const path = join9(runtime.mailboxPath, filename);
17724
17917
  stopResultWatcher(runtime, requestId);
17725
17918
  const check = () => {
17726
- if (active && runtimes.get(runtime.label) === runtime)
17919
+ if (active && context.isIdle() && runtimes.get(runtime.label) === runtime)
17727
17920
  try {
17728
17921
  const result = readResult(runtime.mailboxPath, requestId);
17729
17922
  if (result) void deliverResult(runtime, context, result, signal);
@@ -17744,6 +17937,7 @@ function createAgentController(pi, options) {
17744
17937
  stopAskWatcher(runtime);
17745
17938
  const check = () => {
17746
17939
  if (!active || runtimes.get(runtime.label) !== runtime) return;
17940
+ if (!context.isIdle()) return;
17747
17941
  try {
17748
17942
  deliverPendingAsk(runtime, context, signal);
17749
17943
  } catch (error2) {
@@ -17761,6 +17955,26 @@ function createAgentController(pi, options) {
17761
17955
  askWatchers.set(path, stop);
17762
17956
  check();
17763
17957
  };
17958
+ const watchOwnerMessages = (runtime, context, signal) => {
17959
+ stopOwnerMessageWatcher(runtime);
17960
+ const check = () => {
17961
+ if (!active || runtimes.get(runtime.label) !== runtime) return;
17962
+ if (!context.isIdle()) return;
17963
+ try {
17964
+ deliverOwnerMessages(runtime, context, signal);
17965
+ } catch (error2) {
17966
+ options.reportWatcherError(context, error2);
17967
+ }
17968
+ };
17969
+ const stop = observeMailbox(
17970
+ runtime.mailboxPath,
17971
+ (name) => name.startsWith("owner-message-") && name.endsWith(".json"),
17972
+ check,
17973
+ (error2) => options.reportWatcherError(context, error2)
17974
+ );
17975
+ ownerMessageWatchers.set(runtime.mailboxPath, stop);
17976
+ check();
17977
+ };
17764
17978
  const resultIdentity = (runtime, requestId) => ({
17765
17979
  runId: runtime.runId,
17766
17980
  requestId,
@@ -17839,6 +18053,7 @@ function createAgentController(pi, options) {
17839
18053
  } else validateIdentity(runtime, state);
17840
18054
  if (signal.aborted) return;
17841
18055
  runtimes.set(runtime.label, runtime);
18056
+ watchOwnerMessages(runtime, context, signal);
17842
18057
  if (runtime.activeRequestId) {
17843
18058
  watchResult(runtime, context, signal);
17844
18059
  watchAsk(runtime, context, signal);
@@ -18000,9 +18215,9 @@ function createAgentController(pi, options) {
18000
18215
  }, 250)
18001
18216
  );
18002
18217
  };
18003
- const deliverPendingAsk = (runtime, context, signal) => {
18218
+ const deliverPendingAsk = (runtime, context, signal, triggerTurn = true, budget) => {
18004
18219
  const state = readAgentState(runtime.mailboxPath);
18005
- if (!state?.pendingAskId) return;
18220
+ if (!state?.pendingAskId) return false;
18006
18221
  try {
18007
18222
  requireCompatibleBuild(
18008
18223
  options.build,
@@ -18022,36 +18237,149 @@ function createAgentController(pi, options) {
18022
18237
  options.onChanged();
18023
18238
  }
18024
18239
  const ask = readPendingAsk(runtime.mailboxPath, state);
18025
- if (!ask || !active) return;
18240
+ if (!ask || !active) return false;
18241
+ const content = `Agent ${ask.agentLabel} needs your input:
18242
+
18243
+ ${ask.question}
18244
+
18245
+ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18026
18246
  const key = `${runtime.mailboxPath}:${ask.askId}`;
18027
- if (askDeliveryInFlight.has(key)) return;
18247
+ if (askDeliveryInFlight.has(key)) return false;
18028
18248
  askDeliveryInFlight.add(key);
18029
18249
  try {
18030
- if (!context.isIdle() || runtimes.get(runtime.label) !== runtime || context.sessionManager.getSessionId() !== runtime.ownerSessionId || 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 || !sameSessionPath3(state.piSessionFile, runtime.piSessionFile) || ask.askId !== state.pendingAskId || ask.requestId !== state.activeRequestId || ask.runId !== state.runId || ask.ownerSessionId !== state.ownerSessionId || ask.workspaceId !== state.workspaceId || ask.agentLabel !== state.agentLabel || ask.paneId !== state.paneId || ask.piSessionId !== state.piSessionId)
18031
- return;
18250
+ if (triggerTurn && !context.isIdle() || runtimes.get(runtime.label) !== runtime || context.sessionManager.getSessionId() !== runtime.ownerSessionId || 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 || !sameSessionPath3(state.piSessionFile, runtime.piSessionFile) || ask.askId !== state.pendingAskId || ask.requestId !== state.activeRequestId || ask.runId !== state.runId || ask.ownerSessionId !== state.ownerSessionId || ask.workspaceId !== state.workspaceId || ask.agentLabel !== state.agentLabel || ask.paneId !== state.paneId || ask.piSessionId !== state.piSessionId)
18251
+ return false;
18032
18252
  const delivered = hasDeliveredAsk(
18033
18253
  context.sessionManager.getBranch(),
18034
18254
  ask
18035
18255
  );
18036
18256
  if (!delivered) {
18037
- importResultBindings(pi, context, ask.resultBindings, "ask_owner");
18038
- options.sendAskMessage(context, ask);
18257
+ if (budget && !includeFanInMessage({ ...budget }, content))
18258
+ return false;
18259
+ importResultBindings(pi, context, ask.resultBindings, "await_owner");
18260
+ options.sendAskMessage(context, ask, triggerTurn);
18261
+ if (budget) includeFanInMessage(budget, content);
18039
18262
  }
18040
18263
  cancelAskRetry(runtime, ask.askId);
18041
18264
  clearCleanupError(runtime, "Ask delivery failed");
18265
+ return !delivered;
18042
18266
  } catch (error2) {
18043
18267
  if (error2 instanceof OperationError && error2.detail.category === "incompatible_build")
18044
- return;
18268
+ return false;
18045
18269
  scheduleAskRetry(runtime, context, ask, signal, error2);
18270
+ return false;
18046
18271
  } finally {
18047
18272
  askDeliveryInFlight.delete(key);
18048
18273
  }
18049
18274
  };
18275
+ const deliverOwnerMessages = (runtime, context, signal, triggerTurn = true, budget, receiptsOnly = false, retryMessageIds) => {
18276
+ if (!active || runtimes.get(runtime.label) !== runtime) return false;
18277
+ let submitted = false;
18278
+ let shouldTriggerTurn = triggerTurn;
18279
+ try {
18280
+ const state = readAgentState(runtime.mailboxPath);
18281
+ if (!state) return false;
18282
+ requireCompatibleBuild(
18283
+ options.build,
18284
+ state.build,
18285
+ "notify_owner",
18286
+ `Agent ${state.agentLabel}`
18287
+ );
18288
+ validateIdentity(runtime, state);
18289
+ if (context.sessionManager.getSessionId() !== runtime.ownerSessionId)
18290
+ return false;
18291
+ for (const ownerMessage of readOwnerMessages(runtime.mailboxPath)) {
18292
+ 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)
18293
+ throw new Error(
18294
+ `Owner notification identity did not match Agent ${runtime.label}`
18295
+ );
18296
+ const messageKey = `${runtime.mailboxPath}:${ownerMessage.messageId}`;
18297
+ if (ownerMessageDeliveryInFlight.has(messageKey)) continue;
18298
+ ownerMessageDeliveryInFlight.add(messageKey);
18299
+ try {
18300
+ const entries = context.sessionManager.getEntries();
18301
+ if (hasDeliveredOwnerMessage(entries, ownerMessage)) {
18302
+ const release = claimAssignmentLock3(
18303
+ runtime.mailboxPath,
18304
+ "notify_owner",
18305
+ {
18306
+ label: runtime.label,
18307
+ paneId: runtime.paneId
18308
+ }
18309
+ );
18310
+ try {
18311
+ const current = readAgentState(runtime.mailboxPath);
18312
+ const matching = readOwnerMessages(runtime.mailboxPath).find(
18313
+ (record) => record.messageId === ownerMessage.messageId
18314
+ );
18315
+ if (!current || !sameIdentity(current, state) || !matching || !isDeepStrictEqual2(matching, ownerMessage))
18316
+ throw new Error(
18317
+ "Owner notification changed before receipt cleanup"
18318
+ );
18319
+ removeOwnerMessage(runtime.mailboxPath, ownerMessage.messageId);
18320
+ } finally {
18321
+ release();
18322
+ }
18323
+ submittedOwnerMessages.delete(messageKey);
18324
+ continue;
18325
+ }
18326
+ if (receiptsOnly) continue;
18327
+ if (retryMessageIds && !retryMessageIds.has(ownerMessage.messageId))
18328
+ continue;
18329
+ if (submittedOwnerMessages.has(messageKey)) continue;
18330
+ const content = `Agent ${ownerMessage.agentLabel} notification:
18331
+
18332
+ ${ownerMessage.text}`;
18333
+ if (budget && !includeFanInMessage({ ...budget }, content)) continue;
18334
+ importResultBindings(
18335
+ pi,
18336
+ context,
18337
+ ownerMessage.resultBindings,
18338
+ "notify_owner"
18339
+ );
18340
+ options.sendOwnerMessage(context, ownerMessage, shouldTriggerTurn);
18341
+ shouldTriggerTurn = false;
18342
+ submittedOwnerMessages.add(messageKey);
18343
+ if (budget) includeFanInMessage(budget, content);
18344
+ submitted = true;
18345
+ } finally {
18346
+ ownerMessageDeliveryInFlight.delete(messageKey);
18347
+ }
18348
+ }
18349
+ } catch (error2) {
18350
+ if (!(error2 instanceof OperationError) || error2.detail.category !== "incompatible_build")
18351
+ options.reportWatcherError(context, error2);
18352
+ }
18353
+ return submitted;
18354
+ };
18355
+ const clearConfirmedOwnerMessages = (mailbox, state, context) => {
18356
+ const ownerMessages = readOwnerMessages(mailbox);
18357
+ if (!ownerMessages.length) return true;
18358
+ if (context.sessionManager.getSessionId() !== state.ownerSessionId)
18359
+ throw new Error("Owner session changed before notification cleanup");
18360
+ const entries = context.sessionManager.getEntries();
18361
+ for (const ownerMessage of ownerMessages) {
18362
+ 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(
18363
+ ownerMessage.requestId
18364
+ ))
18365
+ throw new Error("Owner notification identity changed before cleanup");
18366
+ if (!hasDeliveredOwnerMessage(entries, ownerMessage)) return false;
18367
+ removeOwnerMessage(mailbox, ownerMessage.messageId);
18368
+ submittedOwnerMessages.delete(`${mailbox}:${ownerMessage.messageId}`);
18369
+ }
18370
+ return true;
18371
+ };
18050
18372
  const resultCleanupReady = (runtime, requestId, entries) => {
18051
18373
  if (!hasDeliveredResult(entries, resultIdentity(runtime, requestId)))
18052
18374
  return false;
18053
18375
  const state = readAgentState(runtime.mailboxPath);
18054
- 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;
18376
+ let notifications;
18377
+ try {
18378
+ notifications = readOwnerMessages(runtime.mailboxPath);
18379
+ } catch {
18380
+ return false;
18381
+ }
18382
+ 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;
18055
18383
  };
18056
18384
  const sameSessionPath3 = (left, right) => {
18057
18385
  if (left === right) return true;
@@ -18093,6 +18421,8 @@ function createAgentController(pi, options) {
18093
18421
  const ownsDescendants = listAgentStates().some(
18094
18422
  ({ state: candidate }) => candidate.workspaceId === state.workspaceId && candidate.ownerSessionId === state.piSessionId
18095
18423
  );
18424
+ deliverOwnerMessages(runtime, context, signal, false);
18425
+ if (readOwnerMessages(runtime.mailboxPath).length) return false;
18096
18426
  if (managedAgent && !ownsDescendants && listAgentStateIssues().length === 0)
18097
18427
  await finalizeDeliveredRoot(context, state, result.requestId, signal);
18098
18428
  else await closeCascade(context, state, signal, result.requestId);
@@ -18161,6 +18491,7 @@ function createAgentController(pi, options) {
18161
18491
  setTimeout(() => {
18162
18492
  resultDeliveryRetries.delete(key);
18163
18493
  if (!active || runtimes.get(runtime.label) !== runtime) return;
18494
+ if (!context.isIdle()) return;
18164
18495
  try {
18165
18496
  const current = readResult(runtime.mailboxPath, result.requestId);
18166
18497
  if (current) void deliverResult(runtime, context, current, signal);
@@ -18182,16 +18513,18 @@ function createAgentController(pi, options) {
18182
18513
  if (timer) clearTimeout(timer);
18183
18514
  map.delete(key);
18184
18515
  };
18185
- const deliverResult = async (runtime, context, result, signal) => {
18186
- if (!active) return;
18516
+ const deliverResult = async (runtime, context, result, signal, triggerTurn = true, budget) => {
18517
+ if (!active) return false;
18187
18518
  const key = `${runtime.mailboxPath}:${result.requestId}`;
18188
- if (resultDeliveryInFlight.has(key)) return;
18519
+ if (resultDeliveryInFlight.has(key)) return false;
18189
18520
  resultDeliveryInFlight.add(key);
18521
+ let submitted = false;
18190
18522
  try {
18191
18523
  const expected = resultIdentity(runtime, result.requestId);
18192
18524
  const persistedState = readAgentState(runtime.mailboxPath);
18193
18525
  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);
18194
- if (identityMismatch) return;
18526
+ if (identityMismatch) return false;
18527
+ deliverOwnerMessages(runtime, context, signal, false, budget);
18195
18528
  let entries = context.sessionManager.getEntries();
18196
18529
  const evidenceKey = JSON.stringify(Object.values(expected));
18197
18530
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
@@ -18301,10 +18634,21 @@ function createAgentController(pi, options) {
18301
18634
  } : {},
18302
18635
  error: result.error
18303
18636
  };
18304
- options.sendResultMessage(context, runtime, result, content, details);
18637
+ if (budget && !includeFanInMessage({ ...budget }, content))
18638
+ return false;
18639
+ options.sendResultMessage(
18640
+ context,
18641
+ runtime,
18642
+ result,
18643
+ content,
18644
+ details,
18645
+ triggerTurn
18646
+ );
18647
+ if (budget) includeFanInMessage(budget, content);
18648
+ submitted = true;
18305
18649
  resultDeliveryEvidence.add(evidenceKey);
18306
18650
  }
18307
- if (!active || runtimes.get(runtime.label) !== runtime) return;
18651
+ if (!active || runtimes.get(runtime.label) !== runtime) return false;
18308
18652
  stopResultWatcher(runtime, result.requestId);
18309
18653
  stopAskWatcher(runtime);
18310
18654
  cancelAskRetries(runtime);
@@ -18319,8 +18663,10 @@ function createAgentController(pi, options) {
18319
18663
  scheduleResultCleanupRetry(runtime, result, context, signal);
18320
18664
  clearCleanupError(runtime, "Result delivery failed; retrying:");
18321
18665
  cancelResultRetry(resultDeliveryRetries, runtime, result.requestId);
18666
+ return submitted;
18322
18667
  } catch (error2) {
18323
18668
  scheduleResultDeliveryRetry(runtime, result, context, signal, error2);
18669
+ return false;
18324
18670
  } finally {
18325
18671
  resultDeliveryInFlight.delete(key);
18326
18672
  }
@@ -18365,6 +18711,47 @@ function createAgentController(pi, options) {
18365
18711
  await deliverResult(runtime, context, result, signal);
18366
18712
  }
18367
18713
  };
18714
+ const drainReadyOwnerNotifications = async (context, phase, budget) => {
18715
+ if (!active) return 0;
18716
+ let ownerId;
18717
+ try {
18718
+ ownerId = context.sessionManager.getSessionId();
18719
+ } catch {
18720
+ return 0;
18721
+ }
18722
+ let submitted = 0;
18723
+ for (const runtime of runtimes.values()) {
18724
+ if (runtime.ownerSessionId !== ownerId || !active) continue;
18725
+ if (deliverOwnerMessages(runtime, context, context.signal, false, budget))
18726
+ submitted++;
18727
+ const requestId = runtime.activeRequestId ?? runtime.completedRequestId;
18728
+ if (requestId) {
18729
+ try {
18730
+ const result = readResult(runtime.mailboxPath, requestId);
18731
+ if (result && await deliverResult(
18732
+ runtime,
18733
+ context,
18734
+ result,
18735
+ context.signal,
18736
+ false,
18737
+ budget
18738
+ ))
18739
+ submitted++;
18740
+ } catch (error2) {
18741
+ options.reportWatcherError(context, error2);
18742
+ }
18743
+ }
18744
+ if (phase === "settle")
18745
+ try {
18746
+ if (deliverPendingAsk(runtime, context, context.signal, false, budget))
18747
+ submitted++;
18748
+ } catch (error2) {
18749
+ if (!(error2 instanceof OperationError && error2.detail.category === "incompatible_build"))
18750
+ options.reportWatcherError(context, error2);
18751
+ }
18752
+ }
18753
+ return submitted;
18754
+ };
18368
18755
  const actionUnsafe = async (ctx, p, signal) => {
18369
18756
  if (p.action === "delegate") p.retentionPersisted = false;
18370
18757
  const scope = options.scope;
@@ -18569,6 +18956,21 @@ function createAgentController(pi, options) {
18569
18956
  ctx.sessionManager.getSessionId(),
18570
18957
  resumed
18571
18958
  );
18959
+ const ownerEntries = ctx.sessionManager.getBranch();
18960
+ const latestAccepted = acceptedAssignmentReceipts(
18961
+ ownerEntries,
18962
+ ctx.sessionManager.getSessionId(),
18963
+ resumed
18964
+ ).at(-1);
18965
+ const terminalResults = latestAccepted ? ownerEntries.flatMap((entry, index) => {
18966
+ const details = agentResultDetails(entry);
18967
+ return details?.requestId === latestAccepted.requestId ? [{ index, details }] : [];
18968
+ }) : [];
18969
+ const terminal = terminalResults[0];
18970
+ 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(
18971
+ terminal.details.piSessionFile,
18972
+ resumed.path
18973
+ ) && 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;
18572
18974
  for (const agent of snapshot2.liveAgents)
18573
18975
  if (herdrSessionsMatch(
18574
18976
  agent,
@@ -18578,6 +18980,27 @@ function createAgentController(pi, options) {
18578
18980
  ) && !statePanes.has(
18579
18981
  `${agent.workspace_id ?? ""}\0${agent.pane_id ?? ""}`
18580
18982
  )) {
18983
+ if (historicalTerminal && terminal.details.workspaceId === agent.workspace_id && terminal.details.paneId === agent.pane_id && agent.name === herdrAgentAlias(
18984
+ terminal.details.workspaceId,
18985
+ resumed.label,
18986
+ terminal.details.runId
18987
+ ) && typeof agent.pane_id === "string") {
18988
+ try {
18989
+ const observed = await paneProcess(
18990
+ pi,
18991
+ ctx,
18992
+ agent.pane_id,
18993
+ signal,
18994
+ void 0,
18995
+ true
18996
+ );
18997
+ if (observed && settledShell(observed, observed)) continue;
18998
+ } catch (error2) {
18999
+ if (error2 instanceof OperationError && error2.detail.operation === "herdr pane process-info" && error2.detail.details?.herdrCode === "pane_not_found")
19000
+ continue;
19001
+ throw error2;
19002
+ }
19003
+ }
18581
19004
  if (closedReceipt && closedReceipt.workspace_id === agent.workspace_id && closedReceipt.pane_id === agent.pane_id && typeof agent.pane_id === "string") {
18582
19005
  try {
18583
19006
  await paneProcess(pi, ctx, agent.pane_id, signal);
@@ -20203,7 +20626,7 @@ ${result.stderr ?? ""}`.trim(),
20203
20626
  ...agentTool,
20204
20627
  name: "reply_agent",
20205
20628
  label: "reply agent",
20206
- description: "Answer the exact pending ask_owner question for a direct Agent.",
20629
+ description: "Answer the exact pending await_owner question for a direct Agent.",
20207
20630
  parameters: agentMessageParameters,
20208
20631
  promptSnippet: void 0,
20209
20632
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
@@ -20381,11 +20804,11 @@ ${result.stderr ?? ""}`.trim(),
20381
20804
  return [];
20382
20805
  }
20383
20806
  });
20384
- const publishAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
20807
+ const prepareAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
20385
20808
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
20386
20809
  const current = readAgentState(mailbox);
20387
20810
  if (!current || !sameIdentity(current, state) || current.ownerSessionId !== ctx.sessionManager.getSessionId())
20388
- return false;
20811
+ return void 0;
20389
20812
  const currentHandoff = readUnacknowledgedRequest(mailbox, current);
20390
20813
  const requestIds = [
20391
20814
  current.completedRequestId,
@@ -20394,12 +20817,12 @@ ${result.stderr ?? ""}`.trim(),
20394
20817
  ].filter((value2) => !!value2);
20395
20818
  try {
20396
20819
  if (requestIds.some((requestId) => readResult(mailbox, requestId)))
20397
- return false;
20820
+ return void 0;
20398
20821
  } catch {
20399
- return false;
20822
+ return void 0;
20400
20823
  }
20401
20824
  const latest = readAgentState(mailbox);
20402
- if (!latest || !sameIdentity(latest, current)) return false;
20825
+ if (!latest || !sameIdentity(latest, current)) return void 0;
20403
20826
  const latestHandoff = readUnacknowledgedRequest(mailbox, latest);
20404
20827
  const latestRequestId = latest.completedRequestId ?? latest.activeRequestId ?? latestHandoff?.requestId;
20405
20828
  const latestRequestIds = [
@@ -20409,52 +20832,43 @@ ${result.stderr ?? ""}`.trim(),
20409
20832
  ].filter((value2) => !!value2);
20410
20833
  try {
20411
20834
  if (latestRequestIds.some((requestId) => readResult(mailbox, requestId)))
20412
- return false;
20413
- } catch {
20414
- return false;
20415
- }
20416
- if (signal.aborted || !ctx.isIdle()) return false;
20417
- try {
20418
- if (signal.aborted || !ctx.isIdle()) return false;
20419
- const stopAvailable = availableActions.includes("stop");
20420
- pi.sendMessage(
20421
- {
20422
- customType: "pi-herdsman-agent-lost",
20423
- content: [
20424
- `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
20425
- ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
20426
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20427
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
20428
- "",
20429
- "Use read_agent_transcript only when persisted work materially affects the recovery decision.",
20430
- ...stopAvailable ? [
20431
- "Use stop_agent to stop this lost generation before replacing it or continuing its saved session."
20432
- ] : [
20433
- "stop_agent is not currently available; resolve the condition blocking its stop preflight before replacing or continuing it."
20434
- ],
20435
- "Physical disappearance is not task completion."
20436
- ].join("\n"),
20437
- display: true,
20438
- details: {
20439
- runId: current.runId,
20440
- ownerSessionId: current.ownerSessionId,
20441
- workspaceId: current.workspaceId,
20442
- agentLabel: current.agentLabel,
20443
- paneId: current.paneId,
20444
- piSessionId: current.piSessionId,
20445
- piSessionFile: current.piSessionFile,
20446
- agentDefinition: current.agentDefinition ?? snapshotAgentDefinition ?? "unknown",
20447
- requestId: latestRequestId,
20448
- availableActions,
20449
- nextReminderMs
20450
- }
20451
- },
20452
- { triggerTurn: true }
20453
- );
20454
- return true;
20835
+ return void 0;
20455
20836
  } catch {
20456
- return false;
20837
+ return void 0;
20457
20838
  }
20839
+ if (signal.aborted || !ctx.isIdle()) return void 0;
20840
+ const stopAvailable = availableActions.includes("stop");
20841
+ return {
20842
+ customType: "pi-herdsman-agent-lost",
20843
+ content: [
20844
+ `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
20845
+ ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
20846
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20847
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
20848
+ "",
20849
+ "Use read_agent_transcript only when persisted work materially affects the recovery decision.",
20850
+ ...stopAvailable ? [
20851
+ "Use stop_agent to stop this lost generation before replacing it or continuing its saved session."
20852
+ ] : [
20853
+ "stop_agent is not currently available; resolve the condition blocking its stop preflight before replacing or continuing it."
20854
+ ],
20855
+ "Physical disappearance is not task completion."
20856
+ ].join("\n"),
20857
+ display: true,
20858
+ details: {
20859
+ runId: current.runId,
20860
+ ownerSessionId: current.ownerSessionId,
20861
+ workspaceId: current.workspaceId,
20862
+ agentLabel: current.agentLabel,
20863
+ paneId: current.paneId,
20864
+ piSessionId: current.piSessionId,
20865
+ piSessionFile: current.piSessionFile,
20866
+ agentDefinition: current.agentDefinition ?? snapshotAgentDefinition ?? "unknown",
20867
+ requestId: latestRequestId,
20868
+ availableActions,
20869
+ nextReminderMs
20870
+ }
20871
+ };
20458
20872
  };
20459
20873
  const scanAgentHealth = async (ctx, signal, generation) => {
20460
20874
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
@@ -20474,7 +20888,14 @@ ${result.stderr ?? ""}`.trim(),
20474
20888
  );
20475
20889
  for (const runId of attentionReminders.keys())
20476
20890
  if (!ownedRuns.has(runId)) attentionReminders.delete(runId);
20477
- let published = false;
20891
+ const pending = [];
20892
+ const budget = recipientFanInBudget();
20893
+ let initialStaleInspectionUsed = false;
20894
+ const stageAttention = (item) => {
20895
+ if (!includeFanInMessage(budget, item.message.content)) return false;
20896
+ pending.push(item);
20897
+ return true;
20898
+ };
20478
20899
  for (const agent of snapshot2.agents) {
20479
20900
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20480
20901
  return;
@@ -20489,107 +20910,125 @@ ${result.stderr ?? ""}`.trim(),
20489
20910
  if (state.resultError) {
20490
20911
  const error2 = state.resultError;
20491
20912
  const episode2 = `result-error:${error2.failedAt}:${error2.requestId}`;
20492
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20913
+ if (!attentionDue(state.runId, episode2, now)) continue;
20493
20914
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20494
20915
  const current2 = currentOwnedState(state, ownerSessionId);
20495
20916
  if (!current2?.resultError || current2.resultError.failedAt !== error2.failedAt || current2.resultError.requestId !== error2.requestId || !ctx.isIdle())
20496
20917
  continue;
20497
- try {
20498
- if (!ctx.isIdle()) continue;
20499
- pi.sendMessage(
20500
- {
20501
- customType: "pi-herdsman-agent-attention",
20502
- content: [
20503
- `Agent ${current2.agentLabel} could not persist its terminal result.`,
20504
- `Request: ${error2.requestId}`,
20505
- `Failure: ${error2.message}`,
20506
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20507
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20508
- "",
20509
- error2.nextAction,
20510
- "Do not start overlapping replacement work while this assignment remains unresolved."
20511
- ].join("\n"),
20512
- display: true,
20513
- details: {
20514
- reason: "result_error",
20515
- summary: error2.message,
20516
- runId: current2.runId,
20517
- requestId: error2.requestId,
20518
- ownerSessionId: current2.ownerSessionId,
20519
- workspaceId: current2.workspaceId,
20520
- agentLabel: current2.agentLabel,
20521
- paneId: current2.paneId,
20522
- piSessionId: current2.piSessionId,
20523
- availableActions,
20524
- nextReminderMs: intervalMs2,
20525
- nextAction: error2.nextAction
20526
- }
20527
- },
20528
- { triggerTurn: true }
20529
- );
20530
- recordAttention(state.runId, episode2, intervalMs2);
20531
- published = true;
20532
- } catch {
20533
- }
20918
+ stageAttention({
20919
+ state,
20920
+ condition: "result_error",
20921
+ message: {
20922
+ customType: "pi-herdsman-agent-attention",
20923
+ content: [
20924
+ `Agent ${current2.agentLabel} could not persist its terminal result.`,
20925
+ `Request: ${error2.requestId}`,
20926
+ `Failure: ${error2.message}`,
20927
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20928
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20929
+ "",
20930
+ error2.nextAction,
20931
+ "Do not start overlapping replacement work while this assignment remains unresolved."
20932
+ ].join("\n"),
20933
+ display: true,
20934
+ details: {
20935
+ reason: "result_error",
20936
+ summary: error2.message,
20937
+ runId: current2.runId,
20938
+ requestId: error2.requestId,
20939
+ ownerSessionId: current2.ownerSessionId,
20940
+ workspaceId: current2.workspaceId,
20941
+ agentLabel: current2.agentLabel,
20942
+ paneId: current2.paneId,
20943
+ piSessionId: current2.piSessionId,
20944
+ availableActions,
20945
+ nextReminderMs: intervalMs2,
20946
+ nextAction: error2.nextAction
20947
+ }
20948
+ },
20949
+ stillEligible: () => {
20950
+ const latest2 = currentOwnedState(state, ownerSessionId);
20951
+ if (!latest2?.resultError || latest2.resultError.failedAt !== error2.failedAt || latest2.resultError.requestId !== error2.requestId)
20952
+ return false;
20953
+ try {
20954
+ return !readResult(
20955
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
20956
+ error2.requestId
20957
+ );
20958
+ } catch {
20959
+ return false;
20960
+ }
20961
+ },
20962
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
20963
+ });
20534
20964
  continue;
20535
20965
  }
20536
20966
  if (agent.presence.kind === "lost" && !state.completedRequestId) {
20537
20967
  const episode2 = "lost";
20538
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20968
+ if (!attentionDue(state.runId, episode2, now)) continue;
20539
20969
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20540
- if (publishAgentLoss(
20970
+ const message = prepareAgentLoss(
20541
20971
  ctx,
20542
20972
  state,
20543
20973
  agent.agentDefinition,
20544
20974
  availableActions,
20545
20975
  intervalMs2,
20546
20976
  signal
20547
- )) {
20548
- recordAttention(state.runId, episode2, intervalMs2);
20549
- published = true;
20550
- }
20977
+ );
20978
+ if (message)
20979
+ stageAttention({
20980
+ state,
20981
+ condition: "lost",
20982
+ message,
20983
+ stillEligible: () => !!prepareAgentLoss(
20984
+ ctx,
20985
+ state,
20986
+ agent.agentDefinition,
20987
+ availableActions,
20988
+ intervalMs2,
20989
+ signal
20990
+ ),
20991
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
20992
+ });
20551
20993
  continue;
20552
20994
  }
20553
20995
  if (agent.presence.kind === "unknown") {
20554
20996
  const episode2 = "unknown";
20555
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20997
+ if (!attentionDue(state.runId, episode2, now)) continue;
20556
20998
  const current2 = currentOwnedState(state, ownerSessionId);
20557
20999
  if (!current2 || !ctx.isIdle()) continue;
20558
- try {
20559
- if (!ctx.isIdle()) continue;
20560
- pi.sendMessage(
20561
- {
20562
- customType: "pi-herdsman-agent-attention",
20563
- content: [
20564
- `Agent ${current2.agentLabel} has unresolved physical identity.`,
20565
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20566
- "",
20567
- "No safe direct control action is currently available.",
20568
- "Do not infer loss, guess a pane or process, or target ambiguous execution.",
20569
- "Herdsman will continue reconciling physical identity automatically."
20570
- ].join("\n"),
20571
- display: true,
20572
- details: {
20573
- reason: "unknown",
20574
- runId: current2.runId,
20575
- ownerSessionId: current2.ownerSessionId,
20576
- workspaceId: current2.workspaceId,
20577
- agentLabel: current2.agentLabel,
20578
- paneId: current2.paneId,
20579
- piSessionId: current2.piSessionId,
20580
- availableActions
20581
- }
20582
- },
20583
- { triggerTurn: true }
20584
- );
20585
- attentionReminders.set(state.runId, {
21000
+ stageAttention({
21001
+ state,
21002
+ condition: "unknown",
21003
+ message: {
21004
+ customType: "pi-herdsman-agent-attention",
21005
+ content: [
21006
+ `Agent ${current2.agentLabel} has unresolved physical identity.`,
21007
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21008
+ "",
21009
+ "No safe direct control action is currently available.",
21010
+ "Do not infer loss, guess a pane or process, or target ambiguous execution.",
21011
+ "Herdsman will continue reconciling physical identity automatically."
21012
+ ].join("\n"),
21013
+ display: true,
21014
+ details: {
21015
+ reason: "unknown",
21016
+ runId: current2.runId,
21017
+ ownerSessionId: current2.ownerSessionId,
21018
+ workspaceId: current2.workspaceId,
21019
+ agentLabel: current2.agentLabel,
21020
+ paneId: current2.paneId,
21021
+ piSessionId: current2.piSessionId,
21022
+ availableActions
21023
+ }
21024
+ },
21025
+ stillEligible: () => !!currentOwnedState(state, ownerSessionId),
21026
+ onSubmitted: () => attentionReminders.set(state.runId, {
20586
21027
  episode: episode2,
20587
21028
  intervalMs: Number.POSITIVE_INFINITY,
20588
21029
  nextAt: Number.POSITIVE_INFINITY
20589
- });
20590
- published = true;
20591
- } catch {
20592
- }
21030
+ })
21031
+ });
20593
21032
  continue;
20594
21033
  }
20595
21034
  if (state.pendingAskId) {
@@ -20612,102 +21051,117 @@ ${result.stderr ?? ""}`.trim(),
20612
21051
  });
20613
21052
  continue;
20614
21053
  }
20615
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21054
+ if (!attentionDue(state.runId, episode2, now)) continue;
20616
21055
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20617
21056
  const current2 = currentOwnedState(state, ownerSessionId);
20618
21057
  if (!current2?.pendingAskId || !ctx.isIdle()) continue;
21058
+ let currentAsk;
20619
21059
  try {
20620
- const currentAsk = readPendingAsk(
21060
+ currentAsk = readPendingAsk(
20621
21061
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20622
21062
  current2
20623
21063
  );
20624
- if (!currentAsk || currentAsk.askId !== ask.askId || !hasDeliveredAsk(ctx.sessionManager.getBranch(), currentAsk))
20625
- continue;
20626
- if (!ctx.isIdle()) continue;
20627
- pi.sendMessage(
20628
- {
20629
- customType: "pi-herdsman-agent-ask",
20630
- content: [
20631
- `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
20632
- "",
20633
- currentAsk.question,
20634
- "",
20635
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20636
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20637
- "",
20638
- "Use reply_agent to reply to this exact pending ask if the required decision is available.",
20639
- "Do not delegate around or duplicate the blocked assignment."
20640
- ].join("\n"),
20641
- display: true,
20642
- details: {
20643
- askId: currentAsk.askId,
20644
- question: currentAsk.question,
20645
- requestId: currentAsk.requestId,
20646
- runId: currentAsk.runId,
20647
- agentLabel: currentAsk.agentLabel,
20648
- workspaceId: currentAsk.workspaceId,
20649
- paneId: currentAsk.paneId,
20650
- piSessionId: currentAsk.piSessionId,
20651
- availableActions,
20652
- nextReminderMs: intervalMs2
20653
- }
20654
- },
20655
- { triggerTurn: true }
20656
- );
20657
- recordAttention(state.runId, episode2, intervalMs2);
20658
- published = true;
20659
21064
  } catch {
21065
+ continue;
20660
21066
  }
20661
- } else {
20662
- attentionReminders.delete(state.runId);
20663
- }
20664
- continue;
20665
- }
20666
- if (agent.presence.kind === "live" && agent.lifecycleState === "blocked" && state.activeRequestId) {
20667
- const episode2 = `blocked:${state.activeRequestId}`;
20668
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20669
- const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20670
- const current2 = currentOwnedState(state, ownerSessionId);
20671
- if (!current2?.activeRequestId || current2.pendingAskId || !ctx.isIdle())
20672
- continue;
20673
- try {
20674
- if (!ctx.isIdle()) continue;
20675
- pi.sendMessage(
20676
- {
20677
- customType: "pi-herdsman-agent-attention",
21067
+ if (!currentAsk || currentAsk.askId !== ask.askId || !hasDeliveredAsk(ctx.sessionManager.getBranch(), currentAsk))
21068
+ continue;
21069
+ stageAttention({
21070
+ state,
21071
+ condition: "ask",
21072
+ message: {
21073
+ customType: "pi-herdsman-agent-ask",
20678
21074
  content: [
20679
- `Agent ${current2.agentLabel} is blocked in its live runtime, but no Herdsman ask_owner question exists.`,
20680
- `Request: ${current2.activeRequestId}`,
21075
+ `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
21076
+ "",
21077
+ currentAsk.question,
21078
+ "",
20681
21079
  `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20682
21080
  `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20683
21081
  "",
20684
- "Use read_agent_transcript for persisted conversation/tool evidence.",
20685
- "Use inspect_agent only when the live blocking state matters.",
20686
- "Do not invent an owner reply or send guessed terminal input.",
20687
- "Use stop_agent only when abandoning the assignment is the intended recovery."
21082
+ "Use reply_agent to reply to this exact pending ask if the required decision is available.",
21083
+ "Do not delegate around or duplicate the blocked assignment."
20688
21084
  ].join("\n"),
20689
21085
  display: true,
20690
21086
  details: {
20691
- reason: "blocked",
20692
- runId: current2.runId,
20693
- requestId: current2.activeRequestId,
20694
- ownerSessionId: current2.ownerSessionId,
20695
- workspaceId: current2.workspaceId,
20696
- agentLabel: current2.agentLabel,
20697
- paneId: current2.paneId,
20698
- piSessionId: current2.piSessionId,
21087
+ askId: currentAsk.askId,
21088
+ question: currentAsk.question,
21089
+ requestId: currentAsk.requestId,
21090
+ runId: currentAsk.runId,
21091
+ agentLabel: currentAsk.agentLabel,
21092
+ workspaceId: currentAsk.workspaceId,
21093
+ paneId: currentAsk.paneId,
21094
+ piSessionId: currentAsk.piSessionId,
20699
21095
  availableActions,
20700
21096
  nextReminderMs: intervalMs2
20701
21097
  }
20702
21098
  },
20703
- { triggerTurn: true }
20704
- );
20705
- recordAttention(state.runId, episode2, intervalMs2);
20706
- published = true;
20707
- } catch {
21099
+ stillEligible: () => {
21100
+ const latest2 = currentOwnedState(state, ownerSessionId);
21101
+ if (!latest2?.pendingAskId || latest2.pendingAskId !== ask.askId)
21102
+ return false;
21103
+ try {
21104
+ const latestAsk = readPendingAsk(
21105
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
21106
+ latest2
21107
+ );
21108
+ return !!latestAsk && latestAsk.askId === ask.askId && hasDeliveredAsk(ctx.sessionManager.getBranch(), latestAsk);
21109
+ } catch {
21110
+ return false;
21111
+ }
21112
+ },
21113
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21114
+ });
21115
+ } else {
21116
+ attentionReminders.delete(state.runId);
20708
21117
  }
20709
21118
  continue;
20710
21119
  }
21120
+ if (agent.presence.kind === "live" && agent.lifecycleState === "blocked" && state.activeRequestId) {
21121
+ const episode2 = `blocked:${state.activeRequestId}`;
21122
+ if (!attentionDue(state.runId, episode2, now)) continue;
21123
+ const intervalMs2 = nextAttentionInterval(state.runId, episode2);
21124
+ const current2 = currentOwnedState(state, ownerSessionId);
21125
+ if (!current2?.activeRequestId || current2.pendingAskId || !ctx.isIdle())
21126
+ continue;
21127
+ stageAttention({
21128
+ state,
21129
+ condition: "blocked",
21130
+ message: {
21131
+ customType: "pi-herdsman-agent-attention",
21132
+ content: [
21133
+ `Agent ${current2.agentLabel} is blocked in its live runtime, but no Herdsman await_owner question exists.`,
21134
+ `Request: ${current2.activeRequestId}`,
21135
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21136
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
21137
+ "",
21138
+ "Use read_agent_transcript for persisted conversation/tool evidence.",
21139
+ "Use inspect_agent only when the live blocking state matters.",
21140
+ "Do not invent an owner reply or send guessed terminal input.",
21141
+ "Use stop_agent only when abandoning the assignment is the intended recovery."
21142
+ ].join("\n"),
21143
+ display: true,
21144
+ details: {
21145
+ reason: "blocked",
21146
+ runId: current2.runId,
21147
+ requestId: current2.activeRequestId,
21148
+ ownerSessionId: current2.ownerSessionId,
21149
+ workspaceId: current2.workspaceId,
21150
+ agentLabel: current2.agentLabel,
21151
+ paneId: current2.paneId,
21152
+ piSessionId: current2.piSessionId,
21153
+ availableActions,
21154
+ nextReminderMs: intervalMs2
21155
+ }
21156
+ },
21157
+ stillEligible: () => {
21158
+ const latest2 = currentOwnedState(state, ownerSessionId);
21159
+ return !!latest2?.activeRequestId && latest2.activeRequestId === state.activeRequestId && !latest2.pendingAskId;
21160
+ },
21161
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21162
+ });
21163
+ continue;
21164
+ }
20711
21165
  let request;
20712
21166
  try {
20713
21167
  request = readUnacknowledgedRequest(
@@ -20719,51 +21173,65 @@ ${result.stderr ?? ""}`.trim(),
20719
21173
  }
20720
21174
  if (request && request.createdAt <= now && now - request.createdAt >= HEALTH_STALE_AFTER_MS) {
20721
21175
  const episode2 = `handoff:${request.requestId}`;
20722
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21176
+ if (!attentionDue(state.runId, episode2, now)) continue;
20723
21177
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20724
21178
  const current2 = currentOwnedState(state, ownerSessionId);
20725
21179
  if (!current2 || !ctx.isIdle()) continue;
21180
+ let currentRequest;
20726
21181
  try {
20727
- const currentRequest = readUnacknowledgedRequest(
21182
+ currentRequest = readUnacknowledgedRequest(
20728
21183
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20729
21184
  current2
20730
21185
  );
20731
- if (!currentRequest || currentRequest.requestId !== request.requestId || !ctx.isIdle())
20732
- continue;
20733
- pi.sendMessage(
20734
- {
20735
- customType: "pi-herdsman-agent-attention",
20736
- content: [
20737
- `Agent ${current2.agentLabel} still has an unacknowledged ${currentRequest.kind} request.`,
20738
- `Request: ${currentRequest.requestId}`,
20739
- `Pending for: ${formatHealthAttentionDuration(now - currentRequest.createdAt)}`,
20740
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20741
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20742
- "",
20743
- "The durable request is still retained.",
20744
- "Do not submit the same intent again: acknowledgement timeout does not prove non-delivery.",
20745
- "Herdsman will continue reconciling this exact request."
20746
- ].join("\n"),
20747
- display: true,
20748
- details: {
20749
- reason: "handoff",
20750
- runId: current2.runId,
20751
- requestId: currentRequest.requestId,
20752
- ownerSessionId: current2.ownerSessionId,
20753
- workspaceId: current2.workspaceId,
20754
- agentLabel: current2.agentLabel,
20755
- paneId: current2.paneId,
20756
- piSessionId: current2.piSessionId,
20757
- availableActions,
20758
- nextReminderMs: intervalMs2
20759
- }
20760
- },
20761
- { triggerTurn: true }
20762
- );
20763
- recordAttention(state.runId, episode2, intervalMs2);
20764
- published = true;
20765
21186
  } catch {
21187
+ continue;
20766
21188
  }
21189
+ if (!currentRequest || currentRequest.requestId !== request.requestId || !ctx.isIdle())
21190
+ continue;
21191
+ stageAttention({
21192
+ state,
21193
+ condition: "handoff",
21194
+ message: {
21195
+ customType: "pi-herdsman-agent-attention",
21196
+ content: [
21197
+ `Agent ${current2.agentLabel} still has an unacknowledged ${currentRequest.kind} request.`,
21198
+ `Request: ${currentRequest.requestId}`,
21199
+ `Pending for: ${formatHealthAttentionDuration(now - currentRequest.createdAt)}`,
21200
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21201
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
21202
+ "",
21203
+ "The durable request is still retained.",
21204
+ "Do not submit the same intent again: acknowledgement timeout does not prove non-delivery.",
21205
+ "Herdsman will continue reconciling this exact request."
21206
+ ].join("\n"),
21207
+ display: true,
21208
+ details: {
21209
+ reason: "handoff",
21210
+ runId: current2.runId,
21211
+ requestId: currentRequest.requestId,
21212
+ ownerSessionId: current2.ownerSessionId,
21213
+ workspaceId: current2.workspaceId,
21214
+ agentLabel: current2.agentLabel,
21215
+ paneId: current2.paneId,
21216
+ piSessionId: current2.piSessionId,
21217
+ availableActions,
21218
+ nextReminderMs: intervalMs2
21219
+ }
21220
+ },
21221
+ stillEligible: () => {
21222
+ const latest2 = currentOwnedState(state, ownerSessionId);
21223
+ if (!latest2) return false;
21224
+ try {
21225
+ return readUnacknowledgedRequest(
21226
+ agentMailboxPath(latest2.workspaceId, latest2.agentLabel),
21227
+ latest2
21228
+ )?.requestId === request.requestId;
21229
+ } catch {
21230
+ return false;
21231
+ }
21232
+ },
21233
+ onSubmitted: () => recordAttention(state.runId, episode2, intervalMs2)
21234
+ });
20767
21235
  continue;
20768
21236
  }
20769
21237
  if (agent.presence.kind !== "live" || listed.state !== "working" || !state.activeRequestId || state.lastActivityAt === void 0 || state.lastActivityAt > now || now - state.lastActivityAt < HEALTH_STALE_AFTER_MS) {
@@ -20771,7 +21239,7 @@ ${result.stderr ?? ""}`.trim(),
20771
21239
  continue;
20772
21240
  }
20773
21241
  const episode = `stale:${state.activeRequestId}:${state.lastActivityAt}`;
20774
- if (published || !attentionDue(state.runId, episode, now)) continue;
21242
+ if (!attentionDue(state.runId, episode, now)) continue;
20775
21243
  const firstAttention = attentionReminders.get(state.runId)?.episode !== episode;
20776
21244
  const intervalMs = HEALTH_ATTENTION_FIRST_REPEAT_MS;
20777
21245
  const current = currentOwnedState(state, ownerSessionId);
@@ -20780,7 +21248,9 @@ ${result.stderr ?? ""}`.trim(),
20780
21248
  if (signal.aborted || generation !== healthGeneration) return;
20781
21249
  let diagnostic;
20782
21250
  const attemptedDiagnostic = firstAttention && availableActions.includes("inspect");
21251
+ if (attemptedDiagnostic && initialStaleInspectionUsed) continue;
20783
21252
  if (attemptedDiagnostic) {
21253
+ initialStaleInspectionUsed = true;
20784
21254
  const diagnosticSignal = AbortSignal.any([
20785
21255
  signal,
20786
21256
  AbortSignal.timeout(HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS)
@@ -20859,56 +21329,108 @@ ${result.stderr ?? ""}`.trim(),
20859
21329
  "Do not repeat inspect_agent or read_agent_transcript solely because this reminder fired.",
20860
21330
  "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."
20861
21331
  ];
21332
+ stageAttention({
21333
+ state,
21334
+ condition: "stale",
21335
+ message: {
21336
+ customType: "pi-herdsman-agent-stale",
21337
+ content: [
21338
+ `Agent ${current.agentLabel} has had no qualifying execution progress for ${formatHealthAttentionDuration(inactiveMs)}.`,
21339
+ `Request: ${current.activeRequestId}`,
21340
+ `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
21341
+ `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs)}`,
21342
+ ...diagnosticLines,
21343
+ "",
21344
+ "This is advisory inactivity, not proof of a hang.",
21345
+ "Streaming tool output does not count as qualifying progress.",
21346
+ "steer_agent queues a cooperative correction; it does not preempt the current operation.",
21347
+ "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.",
21348
+ "Use stop_agent only to abandon the assignment or as destructive fallback."
21349
+ ].join("\n"),
21350
+ display: true,
21351
+ details: {
21352
+ runId: latest.runId,
21353
+ requestId: latest.activeRequestId,
21354
+ agentLabel: latest.agentLabel,
21355
+ ownerSessionId: latest.ownerSessionId,
21356
+ workspaceId: latest.workspaceId,
21357
+ paneId: latest.paneId,
21358
+ piSessionId: latest.piSessionId,
21359
+ lastActivityAt: latest.lastActivityAt,
21360
+ inactiveMs,
21361
+ thresholdMs: HEALTH_STALE_AFTER_MS,
21362
+ availableActions,
21363
+ nextReminderMs: intervalMs,
21364
+ ...diagnostic ? {
21365
+ captured_at: diagnostic.capturedAt,
21366
+ recent_output_truncated: diagnostic.recentOutputTruncated,
21367
+ ...diagnostic.recentOutput ? { recent_output: diagnostic.recentOutput } : {},
21368
+ ...diagnostic.process ? { process: diagnostic.process } : {}
21369
+ } : {}
21370
+ }
21371
+ },
21372
+ stillEligible: () => {
21373
+ const latest2 = currentOwnedState(state, ownerSessionId);
21374
+ return !!latest2 && latest2.activeRequestId === state.activeRequestId && latest2.lastActivityAt === state.lastActivityAt && !latest2.pendingAskId && !latest2.resultError;
21375
+ },
21376
+ onSubmitted: () => recordAttention(state.runId, episode, intervalMs)
21377
+ });
21378
+ }
21379
+ if (!pending.length) return;
21380
+ let finalSnapshot;
21381
+ try {
21382
+ finalSnapshot = await snapshots(ctx, signal, false, false);
21383
+ } catch {
21384
+ return;
21385
+ }
21386
+ if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
21387
+ return;
21388
+ const ready2 = pending.filter((item) => {
21389
+ if (!item.stillEligible()) return false;
21390
+ const latest = finalSnapshot.agents.find(
21391
+ ({ state: candidate }) => sameIdentity(candidate, item.state)
21392
+ );
21393
+ if (!latest || latest.state.ownerSessionId !== ownerSessionId)
21394
+ return false;
21395
+ switch (item.condition) {
21396
+ case "lost":
21397
+ return latest.presence.kind === "lost" && !latest.state.completedRequestId;
21398
+ case "stale":
21399
+ return latest.presence.kind === "live" && latest.listed.state === "working";
21400
+ case "ask":
21401
+ return latest.presence.kind !== "lost" && latest.presence.kind !== "unknown";
21402
+ case "unknown":
21403
+ return latest.presence.kind === "unknown";
21404
+ case "blocked":
21405
+ return latest.presence.kind === "live" && latest.lifecycleState === "blocked";
21406
+ case "handoff":
21407
+ return latest.presence.kind !== "lost" && latest.presence.kind !== "unknown";
21408
+ case "result_error":
21409
+ return true;
21410
+ }
21411
+ });
21412
+ if (!ready2.length) return;
21413
+ const submitted = [];
21414
+ let triggerSubmitted = false;
21415
+ for (const [index, item] of ready2.entries()) {
20862
21416
  try {
20863
- if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20864
- return;
20865
- pi.sendMessage(
20866
- {
20867
- customType: "pi-herdsman-agent-stale",
20868
- content: [
20869
- `Agent ${current.agentLabel} has had no qualifying execution progress for ${formatHealthAttentionDuration(inactiveMs)}.`,
20870
- `Request: ${current.activeRequestId}`,
20871
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20872
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs)}`,
20873
- ...diagnosticLines,
20874
- "",
20875
- "This is advisory inactivity, not proof of a hang.",
20876
- "Streaming tool output does not count as qualifying progress.",
20877
- "steer_agent queues a cooperative correction; it does not preempt the current operation.",
20878
- "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.",
20879
- "Use stop_agent only to abandon the assignment or as destructive fallback."
20880
- ].join("\n"),
20881
- display: true,
20882
- details: {
20883
- runId: latest.runId,
20884
- requestId: latest.activeRequestId,
20885
- agentLabel: latest.agentLabel,
20886
- ownerSessionId: latest.ownerSessionId,
20887
- workspaceId: latest.workspaceId,
20888
- paneId: latest.paneId,
20889
- piSessionId: latest.piSessionId,
20890
- lastActivityAt: latest.lastActivityAt,
20891
- inactiveMs,
20892
- thresholdMs: HEALTH_STALE_AFTER_MS,
20893
- availableActions,
20894
- nextReminderMs: intervalMs,
20895
- ...diagnostic ? {
20896
- captured_at: diagnostic.capturedAt,
20897
- recent_output_truncated: diagnostic.recentOutputTruncated,
20898
- ...diagnostic.recentOutput ? { recent_output: diagnostic.recentOutput } : {},
20899
- ...diagnostic.process ? { process: diagnostic.process } : {}
20900
- } : {}
20901
- }
20902
- },
20903
- { triggerTurn: true }
20904
- );
20905
- if (generation === healthGeneration && !signal.aborted) {
20906
- recordAttention(state.runId, episode, intervalMs);
20907
- published = true;
20908
- }
21417
+ pi.sendMessage(item.message, {
21418
+ triggerTurn: index === ready2.length - 1
21419
+ });
21420
+ submitted.push(item);
21421
+ if (index === ready2.length - 1) triggerSubmitted = true;
20909
21422
  } catch {
21423
+ if (index === ready2.length - 1) {
21424
+ try {
21425
+ pi.sendMessage(item.message, { triggerTurn: true });
21426
+ submitted.push(item);
21427
+ triggerSubmitted = true;
21428
+ } catch {
21429
+ }
21430
+ }
20910
21431
  }
20911
21432
  }
21433
+ if (triggerSubmitted) for (const item of submitted) item.onSubmitted();
20912
21434
  };
20913
21435
  const runAgentHealthScanner = (ctx, signal) => {
20914
21436
  const generation = ++healthGeneration;
@@ -20954,6 +21476,39 @@ ${result.stderr ?? ""}`.trim(),
20954
21476
  }
20955
21477
  schedule();
20956
21478
  };
21479
+ if (options.registerRecipientFanIn !== false)
21480
+ registerRecipientFanIn(
21481
+ pi,
21482
+ (ctx, phase, budget) => drainReadyOwnerNotifications(ctx, phase, budget)
21483
+ );
21484
+ pi.on("agent_settled", (_event, context) => {
21485
+ if (!active) return;
21486
+ let ownerId;
21487
+ try {
21488
+ ownerId = context.sessionManager.getSessionId();
21489
+ } catch {
21490
+ return;
21491
+ }
21492
+ for (const runtime of runtimes.values()) {
21493
+ if (runtime.ownerSessionId !== ownerId) continue;
21494
+ const prefix = `${runtime.mailboxPath}:`;
21495
+ const retryMessageIds = /* @__PURE__ */ new Set();
21496
+ for (const key of submittedOwnerMessages) {
21497
+ if (!key.startsWith(prefix)) continue;
21498
+ retryMessageIds.add(key.slice(prefix.length));
21499
+ submittedOwnerMessages.delete(key);
21500
+ }
21501
+ deliverOwnerMessages(
21502
+ runtime,
21503
+ context,
21504
+ void 0,
21505
+ true,
21506
+ void 0,
21507
+ false,
21508
+ retryMessageIds
21509
+ );
21510
+ }
21511
+ });
20957
21512
  return {
20958
21513
  listAgentStates,
20959
21514
  managedAgentSnapshots: snapshot,
@@ -21005,8 +21560,10 @@ ${result.stderr ?? ""}`.trim(),
21005
21560
  rollbackUnknownStartedAgent,
21006
21561
  watchResult,
21007
21562
  watchAsk,
21563
+ watchOwnerMessages,
21008
21564
  stopResultWatcher,
21009
21565
  stopAskWatcher,
21566
+ stopOwnerMessageWatcher,
21010
21567
  deliverResult,
21011
21568
  cleanupDeliveredResult(runtime, result, context, signal) {
21012
21569
  return finalizeDeliveredResult(runtime, result, context, signal);
@@ -21033,7 +21590,10 @@ ${result.stderr ?? ""}`.trim(),
21033
21590
  sessionTreeChanged(context, signal) {
21034
21591
  active = true;
21035
21592
  for (const runtime of runtimes.values()) {
21036
- if (runtime.activeRequestId) watchAsk(runtime, context, signal);
21593
+ if (runtime.activeRequestId) {
21594
+ watchAsk(runtime, context, signal);
21595
+ watchOwnerMessages(runtime, context, signal);
21596
+ }
21037
21597
  }
21038
21598
  },
21039
21599
  abortSession() {
@@ -21066,13 +21626,16 @@ ${result.stderr ?? ""}`.trim(),
21066
21626
  settleResults(context, signal) {
21067
21627
  return settleResults(context, signal);
21068
21628
  },
21629
+ drainReadyOwnerNotifications,
21069
21630
  shutdown() {
21070
21631
  active = false;
21071
21632
  recoveryComplete = false;
21072
21633
  for (const watcher of resultWatchers.values()) watcher();
21073
21634
  for (const watcher of askWatchers.values()) watcher();
21635
+ for (const watcher of ownerMessageWatchers.values()) watcher();
21074
21636
  resultWatchers.clear();
21075
21637
  askWatchers.clear();
21638
+ ownerMessageWatchers.clear();
21076
21639
  for (const timer of resultDeliveryRetries.values()) clearTimeout(timer);
21077
21640
  for (const timer of resultCleanupRetries.values()) clearTimeout(timer);
21078
21641
  for (const timer of askDeliveryRetries.values()) clearTimeout(timer);
@@ -21081,6 +21644,8 @@ ${result.stderr ?? ""}`.trim(),
21081
21644
  askDeliveryRetries.clear();
21082
21645
  resultDeliveryInFlight.clear();
21083
21646
  askDeliveryInFlight.clear();
21647
+ ownerMessageDeliveryInFlight.clear();
21648
+ submittedOwnerMessages.clear();
21084
21649
  resultDeliveryEvidence.clear();
21085
21650
  resultDeliverySemanticRefs.clear();
21086
21651
  runtimes.clear();
@@ -21265,6 +21830,7 @@ var init_agent_controller = __esm({
21265
21830
  "extension/agent-controller.ts"() {
21266
21831
  "use strict";
21267
21832
  init_errors();
21833
+ init_recipient_fan_in();
21268
21834
  init_mailbox();
21269
21835
  init_presentation();
21270
21836
  init_storage();
@@ -21336,10 +21902,18 @@ do not select evidence unless the owner needs it.
21336
21902
  Do not silently broaden scope or make an unapproved scope, architecture,
21337
21903
  security, protocol, repository-boundary, product, or operational decision.
21338
21904
 
21339
- Use ask_owner only when a decision from your exact direct owner is genuinely
21340
- required to continue correctly. Explicit attachments must be supported UTF-8
21905
+ Use notify_owner only for material information your direct owner needs before
21906
+ the normal final handoff, or for an explicitly requested meaningful
21907
+ checkpoint. Do not send routine progress, duplicate an imminent final result,
21908
+ or notify merely to show activity.
21909
+
21910
+ Use await_owner only for a required owner decision that prevents further
21911
+ correct progress. Complete independently safe work first. Do not ask for
21912
+ decisions already settled by the assignment, existing evidence, or your
21913
+ delegated authority. After an accepted await_owner call, end your turn;
21914
+ Herdsman retains the blocked assignment until the owner replies. Explicit attachments must be supported UTF-8
21341
21915
  text fully embedded within the applicable per-file and complete-message
21342
- budgets. Call ask_owner alone as the final tool call of the turn. Wait for the
21916
+ budgets. Call await_owner alone as the final tool call of the turn. Wait for the
21343
21917
  direct owner's reply only after the tool confirms the question was sent; if
21344
21918
  rejected, address the error or report a non-empty blocker. Keep at most one
21345
21919
  question outstanding. Do not guess the answer. The reply resumes the same
@@ -21372,7 +21946,7 @@ blockers, remaining work, and reusable paths or artifacts.`;
21372
21946
  };
21373
21947
  AGENT_DEFINITION_ENTRY = "pi-herdsman-agent-definition";
21374
21948
  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.";
21375
- 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.";
21949
+ 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.";
21376
21950
  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.";
21377
21951
  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.";
21378
21952
  LEAD_SCOPE_DESCRIPTION = `Own architecture, approved scope, acceptance of Agent outputs, integration, conflict resolution,
@@ -21399,7 +21973,7 @@ omit unrelated evidence and evidence already inherited as the same required vers
21399
21973
  but explicitly forward changed versions. Summaries do not transfer evidence.
21400
21974
  The lead retains architecture, approved scope, acceptance, and final-decision
21401
21975
  authority. Delegate only to definitions listed in your effective agents field.
21402
- ask_owner follows its normal eligibility rules when you have no unresolved
21976
+ await_owner follows its normal eligibility rules when you have no unresolved
21403
21977
  direct-agent work. If unresolved direct-agent work exists, every such agent
21404
21978
  must itself be validly waiting on an owner answer; ordinary active or
21405
21979
  pending-result agent work still blocks escalation.`;
@@ -21426,6 +22000,7 @@ __export(managed_agent_runtime_exports, {
21426
22000
  createManagedAgentExecutionState: () => createManagedAgentExecutionState,
21427
22001
  createManagedAgentLeafStatus: () => createManagedAgentLeafStatus,
21428
22002
  createManagedAgentMetadataPublisher: () => createManagedAgentMetadataPublisher,
22003
+ createManagedAgentNotifyOwnerHandler: () => createManagedAgentNotifyOwnerHandler,
21429
22004
  createManagedAgentRequestState: () => createManagedAgentRequestState,
21430
22005
  ensureManagedAgentIdentity: () => ensureManagedAgentIdentity,
21431
22006
  evidencePageContent: () => evidencePageContent,
@@ -21439,6 +22014,7 @@ __export(managed_agent_runtime_exports, {
21439
22014
  registerManagedAgentAttachHandoffTool: () => registerManagedAgentAttachHandoffTool,
21440
22015
  registerManagedAgentContextHandlers: () => registerManagedAgentContextHandlers,
21441
22016
  registerManagedAgentInputHandlers: () => registerManagedAgentInputHandlers,
22017
+ registerManagedAgentNotifyOwnerTool: () => registerManagedAgentNotifyOwnerTool,
21442
22018
  registerManagedAgentResultCapture: () => registerManagedAgentResultCapture,
21443
22019
  registerManagedAgentRuntime: () => registerManagedAgentRuntime,
21444
22020
  registerManagedAgentSessionStartHandler: () => registerManagedAgentSessionStartHandler,
@@ -22103,8 +22679,6 @@ function createManagedAgentLeafStatus(options) {
22103
22679
  let inFlight = false;
22104
22680
  let focusInFlight = false;
22105
22681
  let breadcrumb;
22106
- let ownTools;
22107
- const ownToolsSnapshot = () => ownTools ? { ownTools } : {};
22108
22682
  const reset = () => {
22109
22683
  generation++;
22110
22684
  if (timer) clearInterval(timer);
@@ -22146,7 +22720,7 @@ function createManagedAgentLeafStatus(options) {
22146
22720
  stale: false,
22147
22721
  unavailable: false,
22148
22722
  breadcrumb,
22149
- ...ownToolsSnapshot(),
22723
+ ...options.ownToolsSnapshot(),
22150
22724
  identityOnly: true,
22151
22725
  refreshedAt: Date.now()
22152
22726
  });
@@ -22166,7 +22740,7 @@ function createManagedAgentLeafStatus(options) {
22166
22740
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22167
22741
  }
22168
22742
  ],
22169
- ...ownToolsSnapshot(),
22743
+ ...options.ownToolsSnapshot(),
22170
22744
  identityOnly: true
22171
22745
  });
22172
22746
  } finally {
@@ -22178,9 +22752,6 @@ function createManagedAgentLeafStatus(options) {
22178
22752
  invalidate() {
22179
22753
  widget?.invalidate();
22180
22754
  },
22181
- captureOwnTools(tools) {
22182
- ownTools = tools;
22183
- },
22184
22755
  start(ctx) {
22185
22756
  const activeGeneration = generation;
22186
22757
  context = ctx;
@@ -22223,7 +22794,7 @@ function createManagedAgentLeafStatus(options) {
22223
22794
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22224
22795
  }
22225
22796
  ],
22226
- ...ownToolsSnapshot(),
22797
+ ...options.ownToolsSnapshot(),
22227
22798
  identityOnly: true
22228
22799
  });
22229
22800
  if (activeGeneration === generation && ctx === context) widget = next;
@@ -22241,7 +22812,7 @@ function createManagedAgentAskOwnerHandler(options) {
22241
22812
  throw new Error("Question must contain non-whitespace text");
22242
22813
  if (!options.isSoleToolCall(ctx))
22243
22814
  throw new Error(
22244
- "Call ask_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
22815
+ "Call await_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
22245
22816
  );
22246
22817
  const managed = managedAgentIdentity(ctx);
22247
22818
  const state = options.state();
@@ -22310,6 +22881,83 @@ function createManagedAgentAskOwnerHandler(options) {
22310
22881
  };
22311
22882
  };
22312
22883
  }
22884
+ function createManagedAgentNotifyOwnerHandler(options) {
22885
+ return async (_id, params, _signal, _update, ctx) => {
22886
+ if (typeof params.message !== "string" || !params.message.trim())
22887
+ throw new Error("Message must contain non-whitespace text");
22888
+ const managed = managedAgentIdentity(ctx);
22889
+ const state = options.state();
22890
+ if (!state || !options.sameIdentity(state, managed))
22891
+ throw new Error("Agent identity is not eligible to notify its owner");
22892
+ if (!options.eligible())
22893
+ throw new Error(
22894
+ `Agent cannot notify its owner: ${options.rejectionReason()}`
22895
+ );
22896
+ const messageId = randomUUID11();
22897
+ const createdAt = Date.now();
22898
+ const limits = await options.messageLimits(ctx);
22899
+ const prepared = await options.prepare(
22900
+ ctx,
22901
+ params.message,
22902
+ params.files,
22903
+ state,
22904
+ messageId,
22905
+ createdAt,
22906
+ limits
22907
+ );
22908
+ const message = {
22909
+ version: 5,
22910
+ messageId,
22911
+ requestId: state.activeRequestId,
22912
+ runId: state.runId,
22913
+ ownerSessionId: state.ownerSessionId,
22914
+ workspaceId: state.workspaceId,
22915
+ agentLabel: state.agentLabel,
22916
+ paneId: state.paneId,
22917
+ piSessionId: state.piSessionId,
22918
+ text: prepared.text,
22919
+ ...prepared.resultBindings.length ? { resultBindings: prepared.resultBindings } : {},
22920
+ createdAt
22921
+ };
22922
+ const bytes = mailboxRecordBytes(message);
22923
+ if (bytes > limits.mailbox.bytes)
22924
+ fail(
22925
+ "invalid_request",
22926
+ `Mailbox payload is ${bytes} bytes; configured limit is ${limits.mailbox.bytes} bytes`,
22927
+ "notify_owner",
22928
+ { details: { capacity: true } }
22929
+ );
22930
+ const mailbox = process.env.PI_HERDSMAN_MAILBOX;
22931
+ const release = options.claimLock(mailbox, state);
22932
+ try {
22933
+ const current = options.readState(mailbox);
22934
+ if (!current || !options.sameIdentity(current, state) || current.activeRequestId !== state.activeRequestId || current.completedRequestId || !options.eligible())
22935
+ throw new Error(
22936
+ "Agent assignment changed or began settling while notifying its owner"
22937
+ );
22938
+ const pending = options.readMessages(mailbox);
22939
+ if (pending.length >= 8)
22940
+ fail(
22941
+ "invalid_request",
22942
+ "Eight owner notifications are already awaiting confirmed delivery; continue without another notification or wait for delivery",
22943
+ "notify_owner",
22944
+ { details: { capacity: true } }
22945
+ );
22946
+ options.writeMessage(mailbox, message);
22947
+ } finally {
22948
+ release();
22949
+ }
22950
+ return {
22951
+ content: [
22952
+ {
22953
+ type: "text",
22954
+ text: "Notification queued for your direct owner. Continue your assignment."
22955
+ }
22956
+ ],
22957
+ details: { messageId, assignmentRequestId: message.requestId }
22958
+ };
22959
+ };
22960
+ }
22313
22961
  function handoffSelectionDetails(state, resultBindings) {
22314
22962
  return {
22315
22963
  version: 1,
@@ -22406,7 +23054,7 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22406
23054
  )
22407
23055
  );
22408
23056
  pi.registerTool({
22409
- name: "ask_owner",
23057
+ name: "await_owner",
22410
23058
  label: "Ask owner",
22411
23059
  exposure: "model-only",
22412
23060
  promptSnippet: "Ask this managed agent's direct owner for a required decision",
@@ -22426,6 +23074,39 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22426
23074
  execute
22427
23075
  });
22428
23076
  }
23077
+ function registerManagedAgentNotifyOwnerTool(pi, execute) {
23078
+ const files = Type2.Optional(
23079
+ Type2.Array(
23080
+ Type2.String({
23081
+ minLength: 1,
23082
+ description: "Readable regular local file path or exact result ref returned by Herdsman."
23083
+ }),
23084
+ {
23085
+ description: "File or result evidence transferred to the recipient. Copy result refs exactly. Files do not grant runtime capabilities."
23086
+ }
23087
+ )
23088
+ );
23089
+ pi.registerTool({
23090
+ name: "notify_owner",
23091
+ label: "Notify owner",
23092
+ exposure: "direct",
23093
+ promptSnippet: "Send material information to your direct owner while continuing work",
23094
+ promptGuidelines: [FILE_HANDOFF_GUIDANCE],
23095
+ description: "Notify your direct owner about material information when you can continue your assignment. This does not block your assignment or require a reply.",
23096
+ executionMode: "sequential",
23097
+ parameters: Type2.Object(
23098
+ {
23099
+ message: Type2.String({
23100
+ minLength: 1,
23101
+ description: "Non-empty material information for your direct owner."
23102
+ }),
23103
+ files
23104
+ },
23105
+ { additionalProperties: false }
23106
+ ),
23107
+ execute
23108
+ });
23109
+ }
22429
23110
  function createManagedAgentEvidenceUpdater(pi) {
22430
23111
  return async function updateManagedAgentEvidence(_id, params, _signal, _update, ctx) {
22431
23112
  const state = managedAgentIdentity(ctx);
@@ -23022,7 +23703,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
23022
23703
  } : {
23023
23704
  error: {
23024
23705
  code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
23025
- 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"
23706
+ 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"
23026
23707
  }
23027
23708
  },
23028
23709
  contextUsage: ctx.getContextUsage(),
@@ -23186,6 +23867,13 @@ function registerManagedAgentRuntime(pi, options) {
23186
23867
  const allowedAgentDefinitions = allowedAgentDefinitionsFromEnv();
23187
23868
  const agentDepth = agentDepthFromEnv();
23188
23869
  const delegationEnabled = allowedAgentDefinitions.length > 0;
23870
+ const ownToolsSnapshot = () => {
23871
+ try {
23872
+ return { ownTools: pi.getActiveTools() };
23873
+ } catch {
23874
+ return {};
23875
+ }
23876
+ };
23189
23877
  let startupDefinitionRoster;
23190
23878
  const controller = delegationEnabled ? createAgentController(pi, {
23191
23879
  ...options.controllerOptions,
@@ -23217,7 +23905,7 @@ function registerManagedAgentRuntime(pi, options) {
23217
23905
  hasPendingStart: (label) => controller.hasPendingStart(label),
23218
23906
  clearPendingStart: (label, expected) => controller.clearPendingStart(label, expected),
23219
23907
  runtimeForLabel: (label) => controller.runtimeForLabel(label),
23220
- ownToolsSnapshot: () => ({}),
23908
+ ownToolsSnapshot,
23221
23909
  focusTarget: async (ctx, intent, isCurrent) => {
23222
23910
  if (intent.kind !== "session")
23223
23911
  throw new Error("Manager navigation is unavailable from an Agent.");
@@ -23241,7 +23929,7 @@ function registerManagedAgentRuntime(pi, options) {
23241
23929
  label: process.env.PI_HERDSMAN_LABEL
23242
23930
  }),
23243
23931
  sameIdentity: sameManagedAgentIdentity,
23244
- ownToolsSnapshot: () => ({})
23932
+ ownToolsSnapshot
23245
23933
  });
23246
23934
  const currentIdentity = managedAgentEnvironmentIdentity(
23247
23935
  ctx,
@@ -23302,7 +23990,7 @@ function registerManagedAgentRuntime(pi, options) {
23302
23990
  label: process.env.PI_HERDSMAN_LABEL
23303
23991
  }),
23304
23992
  sameIdentity: sameManagedAgentIdentity,
23305
- ownToolsSnapshot: () => ({})
23993
+ ownToolsSnapshot
23306
23994
  });
23307
23995
  }
23308
23996
  });
@@ -23341,6 +24029,7 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23341
24029
  identity: (ctx) => managedAgentEnvironmentIdentity(ctx, options.build),
23342
24030
  sameIdentity: sameManagedAgentIdentity,
23343
24031
  signal: () => metadataPublisher.signal,
24032
+ ownToolsSnapshot,
23344
24033
  getLocalActivity: (ctx) => getLocalActivity(ctx),
23345
24034
  focusTarget: async (ctx, intent, isCurrent) => {
23346
24035
  if (intent.kind !== "session")
@@ -23518,13 +24207,13 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23518
24207
  sameIdentity: sameManagedAgentIdentity,
23519
24208
  eligible: requestState.eligibleToAsk,
23520
24209
  rejectionReason: requestState.askRejectionReason,
23521
- isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "ask_owner"),
24210
+ isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "await_owner"),
23522
24211
  messageLimits: options.messageLimits,
23523
24212
  prepare: async (ctx, question, files, state, askId, createdAt, limits) => prepareMessageInput(
23524
24213
  question,
23525
- options.resolveMessageFiles(ctx, files, "ask_owner"),
24214
+ options.resolveMessageFiles(ctx, files, "await_owner"),
23526
24215
  state.cwd,
23527
- "ask_owner",
24216
+ "await_owner",
23528
24217
  "Question",
23529
24218
  {
23530
24219
  inlineLimitBytes: limits.inline.bytes,
@@ -23538,11 +24227,11 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23538
24227
  fail(
23539
24228
  "invalid_request",
23540
24229
  `Mailbox payload is ${bytes} bytes; configured limit is ${limit} bytes`,
23541
- "ask_owner",
24230
+ "await_owner",
23542
24231
  { details: { capacity: true } }
23543
24232
  );
23544
24233
  },
23545
- claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "ask_owner", {
24234
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "await_owner", {
23546
24235
  label: state.agentLabel,
23547
24236
  paneId: state.paneId
23548
24237
  }),
@@ -23559,11 +24248,52 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23559
24248
  try {
23560
24249
  return await executeAskOwner(...args);
23561
24250
  } catch (error2) {
23562
- 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)
24251
+ 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)
23563
24252
  observation.askOwnerCapacityError = error2.message.slice(0, 512);
23564
24253
  throw error2;
23565
24254
  }
23566
24255
  });
24256
+ const executeNotifyOwner = createManagedAgentNotifyOwnerHandler({
24257
+ state: () => execution.assignment,
24258
+ sameIdentity: sameManagedAgentIdentity,
24259
+ eligible: requestState.eligibleToNotify,
24260
+ rejectionReason: requestState.notifyRejectionReason,
24261
+ messageLimits: options.messageLimits,
24262
+ prepare: async (ctx, message, files, state, messageId, createdAt, limits) => prepareMessageInput(
24263
+ message,
24264
+ options.resolveMessageFiles(ctx, files, "notify_owner"),
24265
+ state.cwd,
24266
+ "notify_owner",
24267
+ "Message",
24268
+ {
24269
+ inlineLimitBytes: limits.inline.bytes,
24270
+ mailboxLimitBytes: limits.mailbox.bytes,
24271
+ requireInline: true,
24272
+ serializedBytes: (text, bindings) => mailboxRecordBytes({
24273
+ version: 5,
24274
+ messageId,
24275
+ requestId: state.activeRequestId,
24276
+ runId: state.runId,
24277
+ ownerSessionId: state.ownerSessionId,
24278
+ workspaceId: state.workspaceId,
24279
+ agentLabel: state.agentLabel,
24280
+ paneId: state.paneId,
24281
+ piSessionId: state.piSessionId,
24282
+ text,
24283
+ ...bindings.length ? { resultBindings: bindings } : {},
24284
+ createdAt
24285
+ })
24286
+ }
24287
+ ),
24288
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "notify_owner", {
24289
+ label: state.agentLabel,
24290
+ paneId: state.paneId
24291
+ }),
24292
+ readState: readAgentState,
24293
+ readMessages: readOwnerMessages,
24294
+ writeMessage: writeOwnerMessage
24295
+ });
24296
+ registerManagedAgentNotifyOwnerTool(pi, executeNotifyOwner);
23567
24297
  const prepareDelegatingRoster = async (ctx) => {
23568
24298
  startupDefinitionRoster = void 0;
23569
24299
  if (!delegationEnabled) return;
@@ -23595,8 +24325,6 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23595
24325
  },
23596
24326
  resetRequestPump,
23597
24327
  resetLeafStatus: leafStatus.reset,
23598
- captureOwnTools: leafStatus.captureOwnTools,
23599
- getActiveTools: () => pi.getActiveTools(),
23600
24328
  clearControllerRuntimes: clearAgentRuntimes,
23601
24329
  setControllerReady: (ready) => controller?.setReady(ready),
23602
24330
  beginMetadataSession: metadataPublisher.beginSession,
@@ -23793,6 +24521,20 @@ function createManagedAgentRequestState(pi, options) {
23793
24521
  const state = options.state();
23794
24522
  return !!state?.activeRequestId && !state.pendingAskId && !state.completedRequestId && !options.pendingResult() && !options.pendingStateTransition() && !unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state) && options.allDirectChildrenAskBlocked(state);
23795
24523
  };
24524
+ const eligibleToNotify = () => {
24525
+ const state = options.state();
24526
+ return !!state?.activeRequestId && !state.pendingAskId && !state.completedRequestId && !options.pendingResult() && !options.pendingStateTransition() && !unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state);
24527
+ };
24528
+ const notifyRejectionReason = () => {
24529
+ const state = options.state();
24530
+ if (!state?.activeRequestId) return "no active assignment";
24531
+ if (state.completedRequestId || options.pendingResult())
24532
+ return "assignment is settling";
24533
+ if (options.pendingStateTransition()) return "assignment state is settling";
24534
+ if (unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state))
24535
+ return "a control request is still pending";
24536
+ return "agent state is not eligible";
24537
+ };
23796
24538
  const askRejectionReason = () => {
23797
24539
  const state = options.state();
23798
24540
  if (!state?.activeRequestId) return "no active assignment";
@@ -23820,6 +24562,8 @@ function createManagedAgentRequestState(pi, options) {
23820
24562
  pump,
23821
24563
  eligibleToAsk,
23822
24564
  askRejectionReason,
24565
+ eligibleToNotify,
24566
+ notifyRejectionReason,
23823
24567
  reportAcknowledgementFailure,
23824
24568
  reset
23825
24569
  };
@@ -24024,7 +24768,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24024
24768
  options.startControllerSession();
24025
24769
  options.resetRequestPump();
24026
24770
  options.resetLeafStatus();
24027
- options.captureOwnTools(void 0);
24028
24771
  if (options.delegationEnabled) options.clearControllerRuntimes();
24029
24772
  execution.initialized = false;
24030
24773
  options.setControllerReady(false);
@@ -24037,8 +24780,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24037
24780
  execution.agentContext = ctx;
24038
24781
  const candidate = options.environmentIdentity(ctx);
24039
24782
  if (!candidate) throw new Error("invalid agent environment");
24040
- if (!options.delegationEnabled)
24041
- options.captureOwnTools(options.getActiveTools());
24042
24783
  options.ensureAgentIdentity(ctx);
24043
24784
  verified = candidate;
24044
24785
  const restoreModel = process.env.PI_HERDSMAN_RESTORE_MODEL;
@@ -24348,7 +25089,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
24348
25089
  // package.json
24349
25090
  var package_default = {
24350
25091
  name: "pi-herdsman",
24351
- version: "0.43.0",
25092
+ version: "0.45.0",
24352
25093
  type: "module",
24353
25094
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
24354
25095
  license: "Apache-2.0",
@@ -24397,7 +25138,7 @@ var package_default = {
24397
25138
  },
24398
25139
  piHerdsman: {
24399
25140
  runtime: {
24400
- pi: "1.5.0",
25141
+ pi: "1.5.2",
24401
25142
  herdr: {
24402
25143
  version: "0.9.5",
24403
25144
  sha256: {
@@ -24431,9 +25172,9 @@ var package_default = {
24431
25172
  typebox: "*"
24432
25173
  },
24433
25174
  devDependencies: {
24434
- "@earendil-works/pi-ai": "1.5.0",
24435
- "@earendil-works/pi-coding-agent": "1.5.0",
24436
- "@earendil-works/pi-tui": "1.5.0",
25175
+ "@earendil-works/pi-ai": "1.5.2",
25176
+ "@earendil-works/pi-coding-agent": "1.5.2",
25177
+ "@earendil-works/pi-tui": "1.5.2",
24437
25178
  "@howaboua/pi-codex-conversion": "4.0.4",
24438
25179
  "@modelcontextprotocol/sdk": "1.32.0",
24439
25180
  "@types/node": "22.19.19",
@@ -24621,6 +25362,7 @@ import {
24621
25362
  init_supervision();
24622
25363
  init_errors();
24623
25364
  init_herdr();
25365
+ init_mailbox();
24624
25366
  init_lock();
24625
25367
  init_config();
24626
25368
  init_core();
@@ -26001,6 +26743,115 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26001
26743
  );
26002
26744
  };
26003
26745
  const mergeProject = async (branch, expectedHead, ctx, signal) => {
26746
+ const completionRefusal = (reason) => ({
26747
+ content: [
26748
+ {
26749
+ type: "text",
26750
+ text: `Cannot integrate ${branch}: current Lead completion evidence is not eligible (${reason}). Assignment and checkout preserved.`
26751
+ }
26752
+ ],
26753
+ details: {
26754
+ ok: false,
26755
+ action: "merge",
26756
+ branch,
26757
+ source_head: expectedHead,
26758
+ status: "blocked",
26759
+ reason,
26760
+ integrated: false,
26761
+ checkout_removed: false,
26762
+ assignment_retired: false
26763
+ }
26764
+ });
26765
+ const completionEligibility = (target, managerBranch) => {
26766
+ const outcomes = managerBranch.filter((entry) => {
26767
+ const details = entry?.details;
26768
+ return entry?.type === "custom_message" && entry.customType === "pi-herdsman-project_message" && details?.repoKey === target.assignment.repoKey && details?.branch === target.assignment.branch && details?.fromSessionId === target.assignment.id && [
26769
+ "direct_response",
26770
+ "herd_settlement",
26771
+ "execution_failure",
26772
+ "execution_cancelled"
26773
+ ].includes(details.kind);
26774
+ });
26775
+ const report = outcomes.at(-1);
26776
+ if (!report || report.details.kind === "execution_failure" || report.details.kind === "execution_cancelled")
26777
+ return "completion_handoff_missing";
26778
+ const sender = report.details.senderEnvironment;
26779
+ if (!validSenderEnvironment(sender) || sender.git?.head !== expectedHead || sender.git?.branch !== target.checkedOutBranch || !sameDirectory(sender.git?.worktreeRoot, target.checkoutPath))
26780
+ return "completion_revision_mismatch";
26781
+ try {
26782
+ if (!target.assignment.piSessionFile)
26783
+ return "completion_evidence_unavailable";
26784
+ const session = host.SessionManager.open(
26785
+ target.assignment.piSessionFile
26786
+ );
26787
+ if (session.getSessionId() !== target.assignment.id)
26788
+ return "completion_evidence_unavailable";
26789
+ const entries = session.getBranch();
26790
+ if (!Array.isArray(entries)) return "completion_evidence_unavailable";
26791
+ const receipt = entries.findIndex(
26792
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-herd-run" && entry.data?.phase === "report_sent" && entry.data?.reportId === report.details.id && entry.data?.sessionId === target.assignment.id && entry.data?.kind === report.details.kind
26793
+ );
26794
+ if (receipt < 0) return "completion_evidence_unavailable";
26795
+ if (entries.slice(receipt + 1).some(
26796
+ (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-herd-run" && entry.data?.sessionId === target.assignment.id && [
26797
+ "lead_started",
26798
+ "lead_start_unpersisted",
26799
+ "report_pending"
26800
+ ].includes(entry.data?.phase) || entry?.type === "message" && (entry.message?.role === "user" || entry.message?.role === "assistant")
26801
+ ))
26802
+ return "completion_evidence_superseded";
26803
+ } catch {
26804
+ return "completion_evidence_unavailable";
26805
+ }
26806
+ if (target.liveLead && !["idle", "done"].includes(
26807
+ normalizeHerdrLifecycleState(target.liveLead)
26808
+ ))
26809
+ return "lead_execution_active";
26810
+ return void 0;
26811
+ };
26812
+ const currentExecutionEligibility = async (target) => {
26813
+ let managerBranch;
26814
+ try {
26815
+ managerBranch = ctx.sessionManager.getBranch();
26816
+ } catch {
26817
+ return "completion_evidence_unavailable";
26818
+ }
26819
+ const completion = completionEligibility(target, managerBranch);
26820
+ if (completion) return completion;
26821
+ const inventory = host.scanAgentStates();
26822
+ if (inventory.issues.length) return "owned_work_unresolved";
26823
+ const owned = /* @__PURE__ */ new Set([target.assignment.id]);
26824
+ let changed = true;
26825
+ while (changed) {
26826
+ changed = false;
26827
+ for (const { state } of inventory.states) {
26828
+ if ((state.projectAssignmentId === target.assignment.id || owned.has(state.ownerSessionId)) && !owned.has(state.piSessionId)) {
26829
+ owned.add(state.piSessionId);
26830
+ changed = true;
26831
+ }
26832
+ }
26833
+ }
26834
+ for (const { path, state } of inventory.states) {
26835
+ if (!owned.has(state.piSessionId) || state.piSessionId === target.assignment.id)
26836
+ continue;
26837
+ try {
26838
+ if (state.activeRequestId || state.pendingAskId || state.resultError || state.lastAck?.accepted === false || state.lastAck?.code === "delivery" || unacknowledgedRequestExists(path, state) || state.completedRequestId && readResult(path, state.completedRequestId))
26839
+ return "owned_work_unresolved";
26840
+ } catch {
26841
+ return "owned_work_unresolved";
26842
+ }
26843
+ }
26844
+ const descendants = await host.herdrSessionSnapshot(
26845
+ host.pi,
26846
+ ctx,
26847
+ operationSignal
26848
+ );
26849
+ if (descendants.agents.some(
26850
+ (agent) => agent.workspace_id === target.worktree.open_workspace_id && owned.has(host.herdrSessionId(agent) ?? "") && !["idle", "done"].includes(normalizeHerdrLifecycleState(agent))
26851
+ ))
26852
+ return "owned_work_unresolved";
26853
+ return void 0;
26854
+ };
26004
26855
  const operationSignal = signal ?? ctx.signal;
26005
26856
  operationSignal?.throwIfAborted();
26006
26857
  if (!/^[0-9a-f]{40,64}$/i.test(expectedHead))
@@ -26363,6 +27214,12 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26363
27214
  alreadyIntegrated: true
26364
27215
  };
26365
27216
  }
27217
+ const eligibility = await currentExecutionEligibility(current);
27218
+ if (eligibility)
27219
+ return {
27220
+ kind: "tool-result",
27221
+ result: completionRefusal(eligibility)
27222
+ };
26366
27223
  const preStopFastForward = await ancestry(
26367
27224
  preStopTarget,
26368
27225
  expectedHead
@@ -26463,10 +27320,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26463
27320
  };
26464
27321
  expectedMergeTree = tree;
26465
27322
  }
26466
- if (current.liveLead)
27323
+ const stopTarget = await inspectRemovalTarget(
27324
+ branch,
27325
+ ctx,
27326
+ operationSignal
27327
+ );
27328
+ if (stopTarget.assignment.id !== current.assignment.id || stopTarget.checkoutPath !== current.checkoutPath || stopTarget.checkedOutBranch !== sourceBranch || stopTarget.sourceCheckoutPath !== targetPath)
27329
+ return {
27330
+ kind: "tool-result",
27331
+ result: completionRefusal(
27332
+ "completion_evidence_superseded"
27333
+ )
27334
+ };
27335
+ assertCandidateLeadUnchanged(current, stopTarget);
27336
+ const finalEligibility = await currentExecutionEligibility(stopTarget);
27337
+ if (finalEligibility)
27338
+ return {
27339
+ kind: "tool-result",
27340
+ result: completionRefusal(finalEligibility)
27341
+ };
27342
+ if (stopTarget.liveLead)
26467
27343
  await stopExecution(
26468
- current.assignment.id,
26469
- current.liveLead,
27344
+ stopTarget.assignment.id,
27345
+ stopTarget.liveLead,
26470
27346
  ctx,
26471
27347
  operationSignal,
26472
27348
  heldLocks
@@ -30042,6 +30918,7 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
30042
30918
  init_supervision();
30043
30919
  init_supervision();
30044
30920
  init_errors();
30921
+ init_recipient_fan_in();
30045
30922
  init_herdr();
30046
30923
  init_lock();
30047
30924
  init_config();
@@ -30071,6 +30948,7 @@ import {
30071
30948
  init_supervision();
30072
30949
  init_supervision();
30073
30950
  init_errors();
30951
+ init_recipient_fan_in();
30074
30952
  init_core();
30075
30953
  init_storage();
30076
30954
  init_agent_controller();
@@ -30786,7 +31664,10 @@ function createLeadCoordinationRuntime(host) {
30786
31664
  } = host;
30787
31665
  const requireCompatibleBuild2 = host.requireCompatibleBuild;
30788
31666
  const reportedProjectMessageCleanupErrors = /* @__PURE__ */ new Set();
31667
+ const reportedProjectMessageSubmissionErrors = /* @__PURE__ */ new Set();
30789
31668
  const reportedProjectMessageReadErrors = /* @__PURE__ */ new Set();
31669
+ const projectMessageSubmissions = /* @__PURE__ */ new Map();
31670
+ let projectStartupEligibility;
30790
31671
  const reportedRetirementErrors = /* @__PURE__ */ new Set();
30791
31672
  const retirementCursors = /* @__PURE__ */ new Map();
30792
31673
  const prepareCoordinationInput = async (ctx, text, files, operation, heading, recordForInput) => {
@@ -32512,8 +33393,8 @@ ${receivedRefs.join("\n")}` : ""}`,
32512
33393
  );
32513
33394
  return pass;
32514
33395
  };
32515
- const drainProjectMessages = async (ctx) => {
32516
- if (activeRole() !== "manager" || leadRuntime.roleSuspended || !ctx.isIdle())
33396
+ const drainProjectMessages = async (ctx, phase = "idle", budget = { count: 0, bytes: 0 }) => {
33397
+ if (activeRole() !== "manager" || leadRuntime.roleSuspended || phase === "idle" && !ctx.isIdle() || phase === "turn")
32517
33398
  return 0;
32518
33399
  const lease = leadRuntime.managerLease;
32519
33400
  if (!lease) return 0;
@@ -32521,6 +33402,10 @@ ${receivedRefs.join("\n")}` : ""}`,
32521
33402
  if (!mightHaveProjectMessages(runtime, lease.descriptor.repoKey)) return 0;
32522
33403
  const manager = await currentManager(ctx);
32523
33404
  if (!manager || !sameManagerDescriptor2(manager, lease.descriptor)) return 0;
33405
+ const submissionPrefix = `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:`;
33406
+ for (const key of projectMessageSubmissions.keys())
33407
+ if (!key.startsWith(submissionPrefix))
33408
+ projectMessageSubmissions.delete(key);
32524
33409
  const hasProjectMessageReceipt = (record) => ctx.sessionManager.getEntries().some(
32525
33410
  (entry) => entry?.customType === "pi-herdsman-project_message" && entry?.details?.id === record.id && entry?.details?.repoKey === record.repoKey && entry?.details?.branch === record.branch && entry?.details?.fromSessionId === record.fromSessionId
32526
33411
  );
@@ -32528,6 +33413,7 @@ ${receivedRefs.join("\n")}` : ""}`,
32528
33413
  try {
32529
33414
  removeProjectMessage2(runtime, record.repoKey, record.branch, record.id);
32530
33415
  reportedProjectMessageCleanupErrors.delete(record.id);
33416
+ reportedProjectMessageSubmissionErrors.delete(record.id);
32531
33417
  reportedProjectMessageReadErrors.delete(record.id);
32532
33418
  } catch (error2) {
32533
33419
  if (!reportedProjectMessageCleanupErrors.has(record.id)) {
@@ -32536,13 +33422,20 @@ ${receivedRefs.join("\n")}` : ""}`,
32536
33422
  }
32537
33423
  }
32538
33424
  };
33425
+ let submitted = 0;
32539
33426
  for (const assignment of listProjectAssignments2(runtime, manager.repoKey)) {
32540
33427
  let pending;
32541
33428
  try {
32542
33429
  pending = listProjectMessageHeaders2(
32543
33430
  runtime,
32544
33431
  manager.repoKey,
32545
- assignment.branch
33432
+ assignment.branch,
33433
+ (error2) => {
33434
+ const key = `header:${String(error2)}`;
33435
+ if (reportedProjectMessageReadErrors.has(key)) return;
33436
+ reportedProjectMessageReadErrors.add(key);
33437
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
33438
+ }
32546
33439
  );
32547
33440
  } catch (error2) {
32548
33441
  appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
@@ -32550,17 +33443,29 @@ ${receivedRefs.join("\n")}` : ""}`,
32550
33443
  }
32551
33444
  for (const record of pending) {
32552
33445
  if (record.fromSessionId !== assignment.id) continue;
33446
+ if (phase === "startup" && (projectStartupEligibility?.sessionId !== ctx.sessionManager.getSessionId() || projectStartupEligibility.managerCreatedAt !== manager.createdAt || record.createdAt > projectStartupEligibility.through))
33447
+ continue;
32553
33448
  if (hasProjectMessageReceipt(record)) {
33449
+ projectMessageSubmissions.delete(
33450
+ `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:${record.id}`
33451
+ );
32554
33452
  consumeProjectMessage(record);
32555
33453
  continue;
32556
33454
  }
33455
+ const submissionKey = `${ctx.sessionManager.getSessionId()}:${manager.createdAt}:${record.id}`;
33456
+ const previousSubmission = projectMessageSubmissions.get(submissionKey);
33457
+ if (previousSubmission !== void 0) {
33458
+ if (Date.now() - previousSubmission < 3e4 || phase !== "idle")
33459
+ continue;
33460
+ projectMessageSubmissions.delete(submissionKey);
33461
+ }
32557
33462
  const current = await currentManager(ctx);
32558
33463
  const stillAssigned = readProjectAssignment2(
32559
33464
  runtime,
32560
33465
  manager.repoKey,
32561
33466
  assignment.branch
32562
33467
  );
32563
- if (!ctx.isIdle() || !current || !sameManagerDescriptor2(current, manager) || !stillAssigned || stillAssigned.id !== assignment.id)
33468
+ if (phase === "idle" && !ctx.isIdle() || !current || !sameManagerDescriptor2(current, manager) || !stillAssigned || stillAssigned.id !== assignment.id)
32564
33469
  return 0;
32565
33470
  let message;
32566
33471
  try {
@@ -32586,31 +33491,62 @@ ${receivedRefs.join("\n")}` : ""}`,
32586
33491
  );
32587
33492
  const backlog = message.createdAt < manager.createdAt;
32588
33493
  const actionableFailure = backlog && message.kind === "execution_failure";
32589
- pi.sendMessage(
32590
- {
32591
- customType: "pi-herdsman-project_message",
32592
- content: projectMessageEnvelope(
32593
- message.kind,
32594
- message.branch,
32595
- message.fromSessionId
32596
- ) + message.text + senderEnvironmentAnnotation(message.senderEnvironment),
32597
- display: true,
32598
- details: {
32599
- id: message.id,
32600
- repoKey: message.repoKey,
32601
- branch: message.branch,
32602
- fromSessionId: message.fromSessionId,
32603
- kind: message.kind,
32604
- ...message.senderEnvironment ? { senderEnvironment: message.senderEnvironment } : {}
32605
- }
32606
- },
32607
- backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
32608
- );
33494
+ const concurrentSubmission = projectMessageSubmissions.get(submissionKey);
33495
+ if (concurrentSubmission !== void 0) {
33496
+ if (phase !== "idle" || Date.now() - concurrentSubmission < 3e4)
33497
+ continue;
33498
+ projectMessageSubmissions.delete(submissionKey);
33499
+ }
33500
+ const content = projectMessageEnvelope(
33501
+ message.kind,
33502
+ message.branch,
33503
+ message.fromSessionId
33504
+ ) + message.text + senderEnvironmentAnnotation(message.senderEnvironment);
33505
+ if (!includeFanInMessage(budget, content)) continue;
33506
+ const submittedAt = Date.now();
33507
+ projectMessageSubmissions.set(submissionKey, submittedAt);
33508
+ try {
33509
+ const delivery = pi.sendMessage(
33510
+ {
33511
+ customType: "pi-herdsman-project_message",
33512
+ content,
33513
+ display: true,
33514
+ details: {
33515
+ id: message.id,
33516
+ repoKey: message.repoKey,
33517
+ branch: message.branch,
33518
+ fromSessionId: message.fromSessionId,
33519
+ kind: message.kind,
33520
+ ...message.senderEnvironment ? { senderEnvironment: message.senderEnvironment } : {}
33521
+ }
33522
+ },
33523
+ phase !== "idle" || backlog && !actionableFailure ? { triggerTurn: false } : { deliverAs: "followUp", triggerTurn: true }
33524
+ );
33525
+ if (phase !== "idle") await delivery;
33526
+ else
33527
+ void Promise.resolve(delivery).catch((error2) => {
33528
+ if (projectMessageSubmissions.get(submissionKey) === submittedAt)
33529
+ projectMessageSubmissions.delete(submissionKey);
33530
+ if (!reportedProjectMessageSubmissionErrors.has(record.id)) {
33531
+ reportedProjectMessageSubmissionErrors.add(record.id);
33532
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
33533
+ }
33534
+ });
33535
+ } catch (error2) {
33536
+ projectMessageSubmissions.delete(submissionKey);
33537
+ releaseFanInMessage(budget, content);
33538
+ if (!reportedProjectMessageSubmissionErrors.has(record.id)) {
33539
+ reportedProjectMessageSubmissionErrors.add(record.id);
33540
+ appendDurableError2(pi, ctx, "pi_herdsman_state_error", error2);
33541
+ }
33542
+ continue;
33543
+ }
32609
33544
  if (hasProjectMessageReceipt(message)) consumeProjectMessage(message);
32610
- return 1;
33545
+ submitted++;
33546
+ if (phase === "idle") return submitted;
32611
33547
  }
32612
33548
  }
32613
- return 0;
33549
+ return submitted;
32614
33550
  };
32615
33551
  return {
32616
33552
  persistCoordinatorState,
@@ -32639,6 +33575,16 @@ ${receivedRefs.join("\n")}` : ""}`,
32639
33575
  enterCoordinationPublication,
32640
33576
  drainRetirementNotices,
32641
33577
  drainProjectMessages,
33578
+ beginProjectMessageStartup: (ctx) => {
33579
+ const descriptor = leadRuntime.managerLease?.descriptor;
33580
+ if (activeRole() !== "manager" || leadRuntime.roleSuspended || !descriptor || !ctx.isIdle())
33581
+ return;
33582
+ projectStartupEligibility = {
33583
+ sessionId: ctx.sessionManager.getSessionId(),
33584
+ managerCreatedAt: descriptor.createdAt,
33585
+ through: Date.now()
33586
+ };
33587
+ },
32642
33588
  supervisorMessage: executeSupervisorMessage,
32643
33589
  peerMessage: executePeerMessage,
32644
33590
  latestCustomMessageText,
@@ -32689,14 +33635,16 @@ function createLeadToolState(getAllTools, ownedNames, leadCoordinationNames) {
32689
33635
  };
32690
33636
  const projectRoleTools = (baseline, definition, requiredTools) => {
32691
33637
  const policy = configuredToolPolicy(definition, requiredTools);
33638
+ const required = new Set(requiredTools);
32692
33639
  const selected = policy.explicit ? policy.tools.flatMap(
32693
33640
  (pattern) => [...registeredToolNames()].filter(
32694
33641
  (name) => matchesToolPattern(pattern, name)
32695
33642
  )
32696
33643
  ) : [...baseline];
32697
- const excluded = (name) => policy.excluded.some((pattern) => matchesToolPattern(pattern, name));
32698
33644
  return appendRegisteredTools(
32699
- normalizeBaseTools(selected.filter((name) => !excluded(name))),
33645
+ normalizeBaseTools(
33646
+ selected.filter((name) => toolPolicyAllowsName(policy, required, name))
33647
+ ),
32700
33648
  requiredTools
32701
33649
  );
32702
33650
  };
@@ -33954,7 +34902,10 @@ function registerLeadRuntime(pi, options) {
33954
34902
  schedulePeerPresence: (ctx) => coordinationRuntime.schedulePeerPresence(ctx),
33955
34903
  removePeerPresence: () => coordinationRuntime.removePeerPresence(),
33956
34904
  clearNormalUI: () => statusRuntime.clear(),
33957
- startNormalUI: (ctx) => statusRuntime.start(ctx),
34905
+ startNormalUI: (ctx) => {
34906
+ statusRuntime.clear();
34907
+ statusRuntime.start(ctx);
34908
+ },
33958
34909
  startSupervisionUI,
33959
34910
  clearSupervisionUI,
33960
34911
  publishLeadRole,
@@ -34017,8 +34968,13 @@ function registerLeadRuntime(pi, options) {
34017
34968
  projectAssignmentForScope: (...args) => roleTransitions.projectAssignmentForScope(...args),
34018
34969
  resolveEffectiveSupervisor: (...args) => roleTransitions.resolveEffectiveSupervisor(...args),
34019
34970
  currentPeerPresenceValid: async (ctx) => (sessionKind?.kind !== "managed" || managedLifecycle === "assigned") && await coordinationRuntime.currentPeerPresenceValid(ctx),
34020
- drainProjectMessages: (ctx) => coordinationRuntime.drainRetirementNotices(ctx).then(
34021
- async (count) => count + await coordinationRuntime.drainProjectMessages(ctx)
34971
+ beginProjectMessageStartup: (ctx) => coordinationRuntime.beginProjectMessageStartup(ctx),
34972
+ drainProjectMessages: (ctx, phase, budget) => phase && phase !== "idle" ? coordinationRuntime.drainProjectMessages(ctx, phase, budget) : coordinationRuntime.drainRetirementNotices(ctx).then(
34973
+ async (count) => count + await coordinationRuntime.drainProjectMessages(
34974
+ ctx,
34975
+ "idle",
34976
+ budget
34977
+ )
34022
34978
  ),
34023
34979
  reconcileRemotePeers: async (ctx, signal) => {
34024
34980
  if (activeLeadRole(leadRuntime) === "manager" || activeLeadRole(leadRuntime) === "lead")
@@ -34166,6 +35122,7 @@ function registerLeadRuntime(pi, options) {
34166
35122
  };
34167
35123
  const controller = createAgentController(pi, {
34168
35124
  ...options.controllerServices,
35125
+ registerRecipientFanIn: false,
34169
35126
  scope: { kind: "root" },
34170
35127
  managerEvidence,
34171
35128
  persistClosedDescendants: async (ctx, closures, selected) => {
@@ -35217,6 +36174,16 @@ function registerLeadRuntime(pi, options) {
35217
36174
  herdRun: herdRunRuntime
35218
36175
  });
35219
36176
  pi.on("turn_start", () => controller.resetAssignmentGuidance());
36177
+ registerRecipientFanIn(pi, async (ctx, phase, budget) => {
36178
+ if (isQuarantinedSession(ctx)) return 0;
36179
+ const agentNotifications = await controller.drainReadyOwnerNotifications(
36180
+ ctx,
36181
+ phase,
36182
+ budget
36183
+ );
36184
+ const inboxMessages = await inboxRuntime.drainBoundary(ctx, phase, budget);
36185
+ return agentNotifications + inboxMessages;
36186
+ });
35220
36187
  pi.on("before_agent_start", (event, ctx) => {
35221
36188
  if (!isQuarantinedSession(ctx))
35222
36189
  return agentEvents.beforeAgentStart(event, ctx);
@@ -35354,6 +36321,16 @@ function createLeadIdentityRuntime(host) {
35354
36321
  };
35355
36322
  return { liveAgent, remoteChiefAgent, liveLead };
35356
36323
  }
36324
+ function verifiedOrdinaryLead(candidate, assignments) {
36325
+ const socket = process.env.HERDR_SOCKET_PATH;
36326
+ if (!socket) return false;
36327
+ try {
36328
+ const peer = readPeerLeadRecord(peerRuntime(), candidate.sessionId);
36329
+ return !!peer && peer.socket === socket && peer.workspaceId === candidate.workspaceId && peer.paneId === candidate.paneId && peer.tabId === candidate.tabId && isRemoteOrdinaryLead(peer, assignments);
36330
+ } catch {
36331
+ return false;
36332
+ }
36333
+ }
35357
36334
  function createLeadSupervisionRuntime(host) {
35358
36335
  const loadSupervisionSnapshot = async (ctx, suppliedInventory, suppliedAgents, includeAll = false, classifyBuilds = false, knownTopology, exactSession) => {
35359
36336
  if (host.activeRole() === "chief" && !includeAll) {
@@ -35612,12 +36589,12 @@ function createLeadSupervisionRuntime(host) {
35612
36589
  for (const report of snapshot2.incompatible ?? [])
35613
36590
  if (report.role === "lead" && scope.workspaceIds.includes(report.workspaceId))
35614
36591
  incompatible?.push(report);
35615
- const assignments = host.listProjectAssignments(
36592
+ const assignments2 = host.listProjectAssignments(
35616
36593
  host.supervisionRuntime(),
35617
36594
  manager.repoKey
35618
36595
  );
35619
- const sessions = new Set(assignments.map((assignment) => assignment.id));
35620
- if (sessions.size !== assignments.length)
36596
+ const sessions = new Set(assignments2.map((assignment) => assignment.id));
36597
+ if (sessions.size !== assignments2.length)
35621
36598
  throw new Error("Multiple project assignments match a Lead session");
35622
36599
  const repoManagers = host.listManagerDescriptors(host.supervisionRuntime()).filter((candidate) => candidate.repoKey === manager.repoKey);
35623
36600
  const ordinarySupervisionAvailable = repoManagers.length === 1 && host.sameManagerDescriptor(repoManagers[0], manager);
@@ -35714,7 +36691,7 @@ function createLeadSupervisionRuntime(host) {
35714
36691
  ...lead,
35715
36692
  role: "lead",
35716
36693
  ...sessions.has(lead.lead) ? {
35717
- branch: assignments.find(
36694
+ branch: assignments2.find(
35718
36695
  (assignment) => assignment.id === lead.lead
35719
36696
  ).branch
35720
36697
  } : {},
@@ -35746,19 +36723,25 @@ function createLeadSupervisionRuntime(host) {
35746
36723
  )).agents;
35747
36724
  const managerLeadSessions = /* @__PURE__ */ new Set();
35748
36725
  const descriptors = host.listManagerDescriptors(host.supervisionRuntime());
36726
+ const assignments = globalProjectAssignmentSnapshot();
35749
36727
  for (const lead of allLeads) {
36728
+ if (!verifiedOrdinaryLead(
36729
+ {
36730
+ sessionId: lead.lead,
36731
+ workspaceId: lead.workspaceId,
36732
+ paneId: lead.paneId,
36733
+ tabId: lead.tabId
36734
+ },
36735
+ assignments
36736
+ )) {
36737
+ managerLeadSessions.add(lead.lead);
36738
+ continue;
36739
+ }
35750
36740
  try {
35751
- const scope = await host.worktreeGroupScope(
35752
- host.pi,
35753
- ctx,
35754
- lead.workspaceId,
35755
- ctx.signal
35756
- );
35757
36741
  const supervisor = await host.resolveEffectiveSupervisor(
35758
36742
  ctx,
35759
36743
  lead.lead,
35760
- lead.workspaceId,
35761
- scope
36744
+ lead.workspaceId
35762
36745
  );
35763
36746
  if (supervisor.kind !== "chief") managerLeadSessions.add(lead.lead);
35764
36747
  } catch {
@@ -35768,17 +36751,10 @@ function createLeadSupervisionRuntime(host) {
35768
36751
  for (const lead of allLeadSnapshot.incompatible ?? []) {
35769
36752
  if (lead.role !== "lead") continue;
35770
36753
  try {
35771
- const scope = await host.worktreeGroupScope(
35772
- host.pi,
35773
- ctx,
35774
- lead.workspaceId,
35775
- ctx.signal
35776
- );
35777
36754
  const supervisor = await host.resolveEffectiveSupervisor(
35778
36755
  ctx,
35779
36756
  lead.session,
35780
- lead.workspaceId,
35781
- scope
36757
+ lead.workspaceId
35782
36758
  );
35783
36759
  if (supervisor.kind === "manager") {
35784
36760
  managerLeadSessions.add(lead.session);
@@ -37623,6 +38599,7 @@ function createLeadInboxRuntime(host) {
37623
38599
  let remoteReconciliationInFlight = false;
37624
38600
  let currentSubmittedAt;
37625
38601
  let settledSubmissions = /* @__PURE__ */ new Set();
38602
+ let runBoundaryDrain;
37626
38603
  const chiefStartPreflights = [];
37627
38604
  const {
37628
38605
  leadRuntime,
@@ -37827,12 +38804,23 @@ function createLeadInboxRuntime(host) {
37827
38804
  if (record.kind === "lead_message") {
37828
38805
  const leads = await liveLead(ctx, record.fromSessionId);
37829
38806
  if (leads.length !== 1) return false;
38807
+ const sender = leads[0];
38808
+ if (!verifiedOrdinaryLead(
38809
+ {
38810
+ sessionId: record.fromSessionId,
38811
+ workspaceId: sender.workspace_id,
38812
+ paneId: sender.pane_id,
38813
+ tabId: sender.tab_id
38814
+ },
38815
+ globalProjectAssignmentSnapshot()
38816
+ ))
38817
+ return false;
37830
38818
  let scope2;
37831
38819
  try {
37832
38820
  scope2 = await worktreeGroupScope2(
37833
38821
  pi,
37834
38822
  ctx,
37835
- leads[0].workspace_id,
38823
+ sender.workspace_id,
37836
38824
  ctx.signal
37837
38825
  );
37838
38826
  } catch (error2) {
@@ -37846,7 +38834,7 @@ function createLeadInboxRuntime(host) {
37846
38834
  const supervisor = await host.resolveEffectiveSupervisor(
37847
38835
  ctx,
37848
38836
  record.fromSessionId,
37849
- leads[0].workspace_id,
38837
+ sender.workspace_id,
37850
38838
  scope2
37851
38839
  );
37852
38840
  return !!state2 && (state2.role ?? "lead") === "lead" && supervisor.kind === "chief" && supervisor.chief.piSessionId === chief.piSessionId && supervisor.chief.leaseId === chief.leaseId;
@@ -37910,6 +38898,8 @@ function createLeadInboxRuntime(host) {
37910
38898
  }
37911
38899
  if (activeRole() !== "lead" || leadRuntime.roleSuspended) return false;
37912
38900
  if (record.kind === "chief_message") {
38901
+ if (readSessionKind(ctx.sessionManager.getEntries(), sessionId)?.kind !== "ordinary")
38902
+ return false;
37913
38903
  const chief = await currentChiefAuthority(ctx);
37914
38904
  const workspaceId2 = host.workspaceId();
37915
38905
  if (!workspaceId2) return false;
@@ -38020,6 +39010,7 @@ function createLeadInboxRuntime(host) {
38020
39010
  }
38021
39011
  };
38022
39012
  const startChiefInbox = (ctx) => {
39013
+ runBoundaryDrain = void 0;
38023
39014
  const generation = ++chiefInboxGeneration;
38024
39015
  const socket = process.env.HERDR_SOCKET_PATH;
38025
39016
  if (!socket) return;
@@ -38050,7 +39041,7 @@ function createLeadInboxRuntime(host) {
38050
39041
  if (transaction.role === "inactive" && activeRole() !== "manager")
38051
39042
  assertCurrentLeadCoordination(ctx);
38052
39043
  };
38053
- const inboxOptions = (verifyLease, inboxRuntime = runtime) => {
39044
+ const inboxOptions = (verifyLease, inboxRuntime = runtime, phase, budget) => {
38054
39045
  if (!isCurrent()) throw new Error("Stale inbox transaction (options)");
38055
39046
  return {
38056
39047
  runtime: inboxRuntime,
@@ -38069,6 +39060,13 @@ function createLeadInboxRuntime(host) {
38069
39060
  return void 0;
38070
39061
  }
38071
39062
  const role2 = activeRole();
39063
+ if (phase === "turn") {
39064
+ if (role2 === "lead" && record.kind === "manager_message" && await authorizeChiefRecord(record, ctx))
39065
+ return "steer";
39066
+ if ((role2 === "lead" || role2 === "manager") && record.kind === "chief_message")
39067
+ return "steer";
39068
+ return void 0;
39069
+ }
38072
39070
  if (role2 === "lead" && record.kind === "manager_message") {
38073
39071
  let authorized;
38074
39072
  try {
@@ -38077,11 +39075,15 @@ function createLeadInboxRuntime(host) {
38077
39075
  return void 0;
38078
39076
  }
38079
39077
  if (!authorized) return "followUp";
39078
+ if (!phase && !ctx.isIdle()) return void 0;
38080
39079
  return "steer";
38081
39080
  }
38082
39081
  const supervisorDownlink = role2 === "lead" && record.kind === "chief_message" || role2 === "manager" && record.kind === "chief_message";
38083
- if (supervisorDownlink) return "steer";
38084
- return ctx.isIdle() ? "followUp" : void 0;
39082
+ if (supervisorDownlink && phase !== "settle") {
39083
+ if (!phase && !ctx.isIdle()) return void 0;
39084
+ return "steer";
39085
+ }
39086
+ return phase === "settle" || phase === "startup" || ctx.isIdle() ? "followUp" : void 0;
38085
39087
  },
38086
39088
  senderTarget: (record) => {
38087
39089
  if (record.kind === "peer_message") {
@@ -38143,6 +39145,7 @@ function createLeadInboxRuntime(host) {
38143
39145
  }
38144
39146
  },
38145
39147
  sendMessage: async (message, options, record) => {
39148
+ let reservedContent;
38146
39149
  const projectAssignment = typeof message === "object" && message !== null && "customType" in message && message.customType === "pi-herdsman-project_assignment";
38147
39150
  try {
38148
39151
  let payload = message;
@@ -38212,6 +39215,14 @@ function createLeadInboxRuntime(host) {
38212
39215
  if (messageDelivered(ctx, record)) return;
38213
39216
  if (record.kind === "peer_message" && !await authorizePeerRecord(record, ctx))
38214
39217
  throw new Error("Peer eligibility changed before delivery");
39218
+ if (phase) options = { ...options, triggerTurn: false };
39219
+ const reservePayload = () => {
39220
+ if (!phase || !budget || typeof payload.content !== "string")
39221
+ return;
39222
+ if (!includeFanInMessage(budget, payload.content))
39223
+ throw new Error("Recipient fan-in budget exhausted");
39224
+ reservedContent = payload.content;
39225
+ };
38215
39226
  let result;
38216
39227
  try {
38217
39228
  if (record.kind === "peer_message") {
@@ -38257,6 +39268,7 @@ function createLeadInboxRuntime(host) {
38257
39268
  if (!current || !samePeerLeadAuthority(current, recipient) || current.group?.repoKey !== recipient.group?.repoKey || current.group?.primaryWorkspaceId !== recipient.group?.primaryWorkspaceId || !contextCurrent || (remoteOrdinarySource ? recipientContext.role !== "lead" || !snapshot || !isRemoteOrdinaryLead(current, snapshot) : !localSource || !canMessagePeer(localSource, recipientContext)))
38258
39269
  throw new Error("Peer eligibility changed before delivery");
38259
39270
  importResultBindings2(pi, ctx, resultBindings, record.kind);
39271
+ reservePayload();
38260
39272
  submitted = pi.sendMessage(payload, options);
38261
39273
  };
38262
39274
  if (source.role === "manager" && recipientContext.role === "manager")
@@ -38265,6 +39277,7 @@ function createLeadInboxRuntime(host) {
38265
39277
  result = submitted;
38266
39278
  } else {
38267
39279
  importResultBindings2(pi, ctx, resultBindings, record.kind);
39280
+ reservePayload();
38268
39281
  result = pi.sendMessage(payload, options);
38269
39282
  }
38270
39283
  } catch (error2) {
@@ -38292,6 +39305,8 @@ function createLeadInboxRuntime(host) {
38292
39305
  }
38293
39306
  return;
38294
39307
  } catch (error2) {
39308
+ if (reservedContent && budget)
39309
+ releaseFanInMessage(budget, reservedContent);
38295
39310
  managerDiagnostic("inbox_catch", { category: "send" });
38296
39311
  if (projectAssignment)
38297
39312
  managerDiagnostic("project_assignment_send", {
@@ -38303,6 +39318,8 @@ function createLeadInboxRuntime(host) {
38303
39318
  },
38304
39319
  transaction: {
38305
39320
  begin: (record) => {
39321
+ if (transactions.has(record.id))
39322
+ throw new Error("Inbox record already has an active drain");
38306
39323
  const token = {
38307
39324
  id: record.id,
38308
39325
  record,
@@ -38315,9 +39332,9 @@ function createLeadInboxRuntime(host) {
38315
39332
  transactions.set(record.id, token);
38316
39333
  return token;
38317
39334
  },
38318
- revalidate: (token, phase) => {
39335
+ revalidate: (token, phase2) => {
38319
39336
  try {
38320
- revalidateTransaction(token, phase);
39337
+ revalidateTransaction(token, phase2);
38321
39338
  } catch (error2) {
38322
39339
  managerDiagnostic("inbox_catch", { category: "transaction" });
38323
39340
  throw error2;
@@ -38330,6 +39347,8 @@ function createLeadInboxRuntime(host) {
38330
39347
  }
38331
39348
  }
38332
39349
  },
39350
+ forceNonTriggering: !!phase,
39351
+ maxDeliveries: budget ? Math.max(0, COORDINATION_INBOX_SCAN_LIMIT - budget.count) : void 0,
38333
39352
  accepted: async (record) => {
38334
39353
  if (record.kind === "peer_message")
38335
39354
  writePeerDeliveryReceipt(peerInboxRuntime, record);
@@ -38348,7 +39367,7 @@ function createLeadInboxRuntime(host) {
38348
39367
  }
38349
39368
  };
38350
39369
  };
38351
- const drainInbox = async (initial = false) => {
39370
+ const drainInbox = async (initial = false, phase, budget) => {
38352
39371
  if (initial) managerDiagnostic("initial_inbox_drain_start");
38353
39372
  const sessionId = ctx.sessionManager.getSessionId();
38354
39373
  const complete = (count) => {
@@ -38361,7 +39380,8 @@ function createLeadInboxRuntime(host) {
38361
39380
  const held = chiefStartPreflightHeld(ctx);
38362
39381
  managerDiagnostic("inbox_preflight", { reason: held ? "held" : "pass" });
38363
39382
  if (held) return complete(0);
38364
- if ((leadRuntime.chiefMode === "active" || activeRole() === "manager") && ctx.isIdle() && listChiefMessagePaths2(runtime, sessionId).some(
39383
+ if (!phase && ctx.isIdle()) host.beginProjectMessageStartup?.(ctx);
39384
+ if (!phase && (leadRuntime.chiefMode === "active" || activeRole() === "manager") && ctx.isIdle() && listChiefMessagePaths2(runtime, sessionId).some(
38365
39385
  (path) => !chiefMessageQuarantined2(
38366
39386
  runtime,
38367
39387
  sessionId,
@@ -38391,27 +39411,38 @@ function createLeadInboxRuntime(host) {
38391
39411
  }
38392
39412
  }
38393
39413
  if (initial) {
38394
- const chief2 = await drainCoordinationInbox2(inboxOptions(false));
39414
+ const chief2 = await drainCoordinationInbox2(
39415
+ inboxOptions(false, runtime, phase, budget)
39416
+ );
38395
39417
  const peerPresent2 = await currentPeerPresenceValid(ctx);
38396
39418
  managerDiagnostic("inbox_peer_presence", {
38397
39419
  reason: peerPresent2 ? "pass" : "missing"
38398
39420
  });
38399
39421
  const peer2 = await drainCoordinationInbox2(
38400
- inboxOptions(false, peerInboxRuntime)
39422
+ inboxOptions(false, peerInboxRuntime, phase, budget)
38401
39423
  );
38402
- return complete(chief2 + peer2 + await drainProjectMessages(ctx));
39424
+ const project2 = await drainProjectMessages(
39425
+ ctx,
39426
+ phase ?? "idle",
39427
+ budget
39428
+ );
39429
+ return complete(phase ? budget?.count ?? 0 : chief2 + peer2 + project2);
38403
39430
  }
38404
39431
  const active = leadRuntime.chiefMode === "active" || activeRole() === "manager";
38405
- const chief = await drainCoordinationInbox2(inboxOptions(active));
39432
+ const chief = await drainCoordinationInbox2(
39433
+ inboxOptions(active, runtime, phase, budget)
39434
+ );
38406
39435
  const peerPresent = await currentPeerPresenceValid(ctx);
38407
39436
  managerDiagnostic("inbox_peer_presence", {
38408
39437
  reason: peerPresent ? "pass" : "missing"
38409
39438
  });
38410
39439
  const peer = await drainCoordinationInbox2(
38411
- inboxOptions(active, peerInboxRuntime)
39440
+ inboxOptions(active, peerInboxRuntime, phase, budget)
38412
39441
  );
38413
- return complete(chief + peer + await drainProjectMessages(ctx));
39442
+ const project = await drainProjectMessages(ctx, phase ?? "idle", budget);
39443
+ return complete(phase ? budget?.count ?? 0 : chief + peer + project);
38414
39444
  };
39445
+ runBoundaryDrain = (boundaryCtx, phase, budget) => boundaryCtx.sessionManager.getSessionId() === ctx.sessionManager.getSessionId() ? drainInbox(false, phase, budget) : Promise.resolve(0);
38415
39446
  const schedule = () => {
38416
39447
  if (generation !== chiefInboxGeneration || chiefInboxAbortController?.signal.aborted)
38417
39448
  return;
@@ -38455,6 +39486,7 @@ function createLeadInboxRuntime(host) {
38455
39486
  };
38456
39487
  return {
38457
39488
  start: startChiefInbox,
39489
+ drainBoundary: (ctx, phase, budget) => runBoundaryDrain?.(ctx, phase, budget) ?? Promise.resolve(0),
38458
39490
  cleanupManagedPeerInbox,
38459
39491
  isStartPreflightHeld: chiefStartPreflightHeld,
38460
39492
  clearStartPreflight,
@@ -40694,6 +41726,13 @@ function registerExtensionImpl(pi, lockHooks) {
40694
41726
  (expanded) => renderAgentAskMessage(message, { ...options, expanded }, theme)
40695
41727
  )
40696
41728
  );
41729
+ pi.registerMessageRenderer(
41730
+ "pi-herdsman-agent-owner-message",
41731
+ (message, options, theme) => expandablePresentation(
41732
+ options.expanded,
41733
+ (expanded) => renderAgentOwnerMessage(message, { ...options, expanded }, theme)
41734
+ )
41735
+ );
40697
41736
  pi.registerMessageRenderer(
40698
41737
  "pi-herdsman-agent-stale",
40699
41738
  (message, options, theme) => expandablePresentation(
@@ -40822,7 +41861,9 @@ If needed, install the Pi integration once:
40822
41861
  }
40823
41862
  ),
40824
41863
  workspaceId: () => process.env.PI_HERDSMAN_WORKSPACE_ID ?? process.env.HERDR_WORKSPACE_ID,
40825
- sendResultMessage: (ctx, _runtime, _result, content, details) => {
41864
+ sendResultMessage: (ctx, _runtime, _result, content, details, triggerTurn = true) => {
41865
+ if (triggerTurn && !ctx.isIdle())
41866
+ throw new Error("Agent result owner is no longer idle");
40826
41867
  pi.sendMessage(
40827
41868
  {
40828
41869
  customType: "pi-herdsman-agent-result",
@@ -40830,10 +41871,15 @@ If needed, install the Pi integration once:
40830
41871
  display: true,
40831
41872
  details
40832
41873
  },
40833
- { triggerTurn: true, deliverAs: "steer" }
41874
+ {
41875
+ triggerTurn,
41876
+ ...triggerTurn ? { deliverAs: "steer" } : {}
41877
+ }
40834
41878
  );
40835
41879
  },
40836
- sendAskMessage: (_ctx, ask) => {
41880
+ sendAskMessage: (ctx, ask, triggerTurn = true) => {
41881
+ if (triggerTurn && !ctx.isIdle())
41882
+ throw new Error("Agent ask owner is no longer idle");
40837
41883
  pi.sendMessage(
40838
41884
  {
40839
41885
  customType: "pi-herdsman-agent-ask",
@@ -40854,7 +41900,34 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
40854
41900
  piSessionId: ask.piSessionId
40855
41901
  }
40856
41902
  },
40857
- { triggerTurn: true }
41903
+ { triggerTurn }
41904
+ );
41905
+ },
41906
+ sendOwnerMessage: (ctx, ownerMessage, triggerTurn = true) => {
41907
+ if (ctx.sessionManager.getSessionId() !== ownerMessage.ownerSessionId)
41908
+ throw new Error("Owner notification recipient session changed");
41909
+ pi.sendMessage(
41910
+ {
41911
+ customType: "pi-herdsman-agent-owner-message",
41912
+ content: `Agent ${ownerMessage.agentLabel} notification:
41913
+
41914
+ ${ownerMessage.text}`,
41915
+ display: true,
41916
+ details: {
41917
+ messageId: ownerMessage.messageId,
41918
+ requestId: ownerMessage.requestId,
41919
+ runId: ownerMessage.runId,
41920
+ ownerSessionId: ownerMessage.ownerSessionId,
41921
+ workspaceId: ownerMessage.workspaceId,
41922
+ agentLabel: ownerMessage.agentLabel,
41923
+ paneId: ownerMessage.paneId,
41924
+ piSessionId: ownerMessage.piSessionId
41925
+ }
41926
+ },
41927
+ {
41928
+ triggerTurn,
41929
+ ...triggerTurn ? { deliverAs: "steer" } : {}
41930
+ }
40858
41931
  );
40859
41932
  },
40860
41933
  sessionRetired: (ctx, runtime) => {
@@ -41814,7 +42887,7 @@ ${summary}`,
41814
42887
  ...staffTool,
41815
42888
  name: "integrate_branch",
41816
42889
  label: "integrate branch",
41817
- description: "Integrate an assigned local branch into the verified primary branch using fast-forward Git, or a clean divergent merge when explicitly authorized. Supply the exact full source SHA accepted after validation. A divergent merge may create a merge commit; actual conflicts are distinguished from divergent ancestry. Merge preflight failure/conflict occurs before stopping the Lead. If a later step fails after execution stops, it is not automatically restarted. Git integration does not prove tests or semantic acceptance. Verified integration triggers separately guarded cleanup; integration and cleanup can complete separately, so do not treat integration alone as full finalization.",
42890
+ description: "Integrate an assigned local branch into the verified primary branch using fast-forward Git, or a clean divergent merge when explicitly authorized. Supply the exact full source SHA accepted after validation. New integration requires a matching completed Lead handoff for that revision and no unresolved assigned execution; a visible SHA, idle status, or interim supervisor message is insufficient. If the handoff is missing or stale, wait for the normal completion handoff or request a fresh completion report; do not poll staff or integration tools. A completed handoff is not proof that tests passed or that the work is acceptable. A divergent merge may create a merge commit; actual conflicts are distinguished from divergent ancestry. Merge preflight failure/conflict occurs before stopping the Lead. If a later step fails after execution stops, it is not automatically restarted. Git integration does not prove tests or semantic acceptance. Verified integration triggers separately guarded cleanup; integration and cleanup can complete separately, so do not treat integration alone as full finalization. An already-integrated accepted SHA follows the existing guarded cleanup-recovery path.",
41818
42891
  parameters: Type3.Object(
41819
42892
  {
41820
42893
  branch: Type3.String({