pi-herdsman 0.44.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");
@@ -3158,10 +3217,11 @@ function agentLaunchArgs(agent, options) {
3158
3217
  const requiredTools = [
3159
3218
  ...managedAgent ? agentDefinitionDelegationEnabled(agent) ? [
3160
3219
  ...AGENT_COORDINATION_TOOLS,
3161
- "ask_owner",
3220
+ "await_owner",
3221
+ "notify_owner",
3162
3222
  "read_evidence",
3163
3223
  "attach_handoff"
3164
- ] : ["ask_owner", "read_evidence", "attach_handoff"] : [],
3224
+ ] : ["await_owner", "notify_owner", "read_evidence", "attach_handoff"] : [],
3165
3225
  ...options.requiredTools ?? []
3166
3226
  ].filter((tool, index, all) => all.indexOf(tool) === index);
3167
3227
  const policy = configuredToolPolicy(agent, requiredTools);
@@ -11090,6 +11150,44 @@ function renderAgentAskMessage(message, options, theme) {
11090
11150
  }
11091
11151
  return renderMessageBox(content, theme, options.outputPad ?? 0);
11092
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
+ }
11093
11191
  function renderAgentAttentionMessage(message, options, theme) {
11094
11192
  const details = message.details && typeof message.details === "object" ? message.details : {};
11095
11193
  const label = value(details.agentLabel) || "agent";
@@ -14875,6 +14973,13 @@ function hasDeliveredAsk(entries, ask) {
14875
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;
14876
14974
  });
14877
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
+ }
14878
14983
  function canonicalSessionPath(path) {
14879
14984
  try {
14880
14985
  return realpathSync4(path);
@@ -16047,8 +16152,11 @@ function createAgentController(pi, options) {
16047
16152
  const pendingStarts = /* @__PURE__ */ new Map();
16048
16153
  const resultWatchers = /* @__PURE__ */ new Map();
16049
16154
  const askWatchers = /* @__PURE__ */ new Map();
16155
+ const ownerMessageWatchers = /* @__PURE__ */ new Map();
16050
16156
  const resultDeliveryInFlight = /* @__PURE__ */ new Set();
16051
16157
  const askDeliveryInFlight = /* @__PURE__ */ new Set();
16158
+ const ownerMessageDeliveryInFlight = /* @__PURE__ */ new Set();
16159
+ const submittedOwnerMessages = /* @__PURE__ */ new Set();
16052
16160
  const resultDeliveryRetries = /* @__PURE__ */ new Map();
16053
16161
  const resultCleanupRetries = /* @__PURE__ */ new Map();
16054
16162
  const askDeliveryRetries = /* @__PURE__ */ new Map();
@@ -16863,6 +16971,8 @@ function createAgentController(pi, options) {
16863
16971
  watchResult(runtime, context, signal);
16864
16972
  if (runtime.activeRequestId === requestId)
16865
16973
  watchAsk(runtime, context, signal);
16974
+ if (runtime.activeRequestId === requestId)
16975
+ watchOwnerMessages(runtime, context, signal);
16866
16976
  }
16867
16977
  return requestId;
16868
16978
  } finally {
@@ -16963,7 +17073,7 @@ function createAgentController(pi, options) {
16963
17073
  if (kind === "steer" && agent.steerable !== true) {
16964
17074
  const current = readAgentState(runtime.mailboxPath);
16965
17075
  const pendingRequest = current ? readUnacknowledgedRequest(runtime.mailboxPath, current) : void 0;
16966
- const nextAction = current?.pendingAskId ? "Answer the pending ask_owner question with reply_agent." : controlState === "settling" || pendingRequest ? "Allow the current control or completion transition to finish." : controlState === "unknown" ? "Diagnose or recover the exact managed session before steering." : "Refresh list_agents after the underlying state changes and use steer_agent only when available_tools includes it.";
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.";
16967
17077
  fail(
16968
17078
  "agent_busy",
16969
17079
  `Agent is not currently accepting steering: ${controlState}`,
@@ -17002,7 +17112,7 @@ function createAgentController(pi, options) {
17002
17112
  }
17003
17113
  if (!current?.activeRequestId || !askId || !ask)
17004
17114
  fail("agent_busy", "Agent is not waiting for an owner reply", "reply", {
17005
- nextAction: "Use reply_agent only for an outstanding ask_owner question; otherwise continue normal control or refresh with list_agents."
17115
+ nextAction: "Use reply_agent only for an outstanding await_owner question; otherwise continue normal control or refresh with list_agents."
17006
17116
  });
17007
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)
17008
17118
  fail("target_not_found", "Agent ask identity did not match", "reply");
@@ -17346,6 +17456,8 @@ function createAgentController(pi, options) {
17346
17456
  ].some((id) => !!id && id !== requestId);
17347
17457
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17348
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");
17349
17461
  const presence = managedAgentPresence(
17350
17462
  current,
17351
17463
  await herdrSessionSnapshot(pi, context, signal)
@@ -17384,16 +17496,21 @@ function createAgentController(pi, options) {
17384
17496
  current = readAgentState(mailbox);
17385
17497
  if (!sameIdentity2(current) || current.activeRequestId || current.completedRequestId !== requestId || hasNewerWork(current))
17386
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");
17387
17501
  removeResult(mailbox, requestId);
17388
17502
  const after = readAgentState(mailbox);
17389
- 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");
17390
17506
  removeAgentMailbox(mailbox);
17507
+ }
17391
17508
  invalidateRuntime(state.agentLabel);
17392
17509
  } finally {
17393
17510
  release?.();
17394
17511
  }
17395
17512
  };
17396
- const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false) => {
17513
+ const closeSnapshot = async (context, snapshot2, signal, report, assignmentLockHeld = false, preserveOwnerMessages = false) => {
17397
17514
  const state = snapshot2.state;
17398
17515
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
17399
17516
  const release = assignmentLockHeld ? void 0 : claimAssignmentLock3(mailbox, "close", {
@@ -17410,6 +17527,8 @@ function createAgentController(pi, options) {
17410
17527
  let current = readAgentState(mailbox);
17411
17528
  if (!current || !sameIdentity(current, state))
17412
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");
17413
17532
  if (hasDurableResult(mailbox, current))
17414
17533
  fail(
17415
17534
  "target_ambiguous",
@@ -17476,6 +17595,8 @@ function createAgentController(pi, options) {
17476
17595
  );
17477
17596
  }
17478
17597
  try {
17598
+ if (preserveOwnerMessages && !clearConfirmedOwnerMessages(mailbox, current, context))
17599
+ throw new Error("Owner notification receipt is still unconfirmed");
17479
17600
  removeAgentMailbox(mailbox);
17480
17601
  } catch (error2) {
17481
17602
  const message = `Agent pane closed but mailbox cleanup failed: ${String(error2)}`;
@@ -17547,7 +17668,14 @@ function createAgentController(pi, options) {
17547
17668
  deliveredRootResultId
17548
17669
  );
17549
17670
  try {
17550
- await closeSnapshot(context, child, signal, report);
17671
+ await closeSnapshot(
17672
+ context,
17673
+ child,
17674
+ signal,
17675
+ report,
17676
+ false,
17677
+ deliveredRootResultId !== void 0
17678
+ );
17551
17679
  if (readAgentState(
17552
17680
  agentMailboxPath(child.state.workspaceId, child.state.agentLabel)
17553
17681
  ))
@@ -17755,12 +17883,20 @@ function createAgentController(pi, options) {
17755
17883
  askWatchers.get(path)?.();
17756
17884
  askWatchers.delete(path);
17757
17885
  };
17886
+ const stopOwnerMessageWatcher = (runtime) => {
17887
+ ownerMessageWatchers.get(runtime.mailboxPath)?.();
17888
+ ownerMessageWatchers.delete(runtime.mailboxPath);
17889
+ };
17758
17890
  const invalidateRuntime = (label, workspaceId) => {
17759
17891
  const runtime = runtimes.get(label);
17760
17892
  if (!runtime || workspaceId !== void 0 && runtime.workspaceId !== workspaceId)
17761
17893
  return;
17762
17894
  stopResultWatcher(runtime);
17763
17895
  stopAskWatcher(runtime);
17896
+ stopOwnerMessageWatcher(runtime);
17897
+ for (const key of submittedOwnerMessages)
17898
+ if (key.startsWith(`${runtime.mailboxPath}:`))
17899
+ submittedOwnerMessages.delete(key);
17764
17900
  cancelAskRetries(runtime);
17765
17901
  for (const requestId of [
17766
17902
  runtime.activeRequestId,
@@ -17819,6 +17955,26 @@ function createAgentController(pi, options) {
17819
17955
  askWatchers.set(path, stop);
17820
17956
  check();
17821
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
+ };
17822
17978
  const resultIdentity = (runtime, requestId) => ({
17823
17979
  runId: runtime.runId,
17824
17980
  requestId,
@@ -17897,6 +18053,7 @@ function createAgentController(pi, options) {
17897
18053
  } else validateIdentity(runtime, state);
17898
18054
  if (signal.aborted) return;
17899
18055
  runtimes.set(runtime.label, runtime);
18056
+ watchOwnerMessages(runtime, context, signal);
17900
18057
  if (runtime.activeRequestId) {
17901
18058
  watchResult(runtime, context, signal);
17902
18059
  watchAsk(runtime, context, signal);
@@ -18099,7 +18256,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18099
18256
  if (!delivered) {
18100
18257
  if (budget && !includeFanInMessage({ ...budget }, content))
18101
18258
  return false;
18102
- importResultBindings(pi, context, ask.resultBindings, "ask_owner");
18259
+ importResultBindings(pi, context, ask.resultBindings, "await_owner");
18103
18260
  options.sendAskMessage(context, ask, triggerTurn);
18104
18261
  if (budget) includeFanInMessage(budget, content);
18105
18262
  }
@@ -18115,11 +18272,114 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18115
18272
  askDeliveryInFlight.delete(key);
18116
18273
  }
18117
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
+ };
18118
18372
  const resultCleanupReady = (runtime, requestId, entries) => {
18119
18373
  if (!hasDeliveredResult(entries, resultIdentity(runtime, requestId)))
18120
18374
  return false;
18121
18375
  const state = readAgentState(runtime.mailboxPath);
18122
- return !!state && state.runId === runtime.runId && state.ownerSessionId === runtime.ownerSessionId && state.workspaceId === runtime.workspaceId && state.agentLabel === runtime.label && state.paneId === runtime.paneId && sameCwd(state.cwd, runtime.cwd) && state.piSessionId === runtime.piSessionId && state.piSessionFile === runtime.piSessionFile && !state.activeRequestId && state.completedRequestId === requestId;
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;
18123
18383
  };
18124
18384
  const sameSessionPath3 = (left, right) => {
18125
18385
  if (left === right) return true;
@@ -18161,6 +18421,8 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18161
18421
  const ownsDescendants = listAgentStates().some(
18162
18422
  ({ state: candidate }) => candidate.workspaceId === state.workspaceId && candidate.ownerSessionId === state.piSessionId
18163
18423
  );
18424
+ deliverOwnerMessages(runtime, context, signal, false);
18425
+ if (readOwnerMessages(runtime.mailboxPath).length) return false;
18164
18426
  if (managedAgent && !ownsDescendants && listAgentStateIssues().length === 0)
18165
18427
  await finalizeDeliveredRoot(context, state, result.requestId, signal);
18166
18428
  else await closeCascade(context, state, signal, result.requestId);
@@ -18262,6 +18524,7 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18262
18524
  const persistedState = readAgentState(runtime.mailboxPath);
18263
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);
18264
18526
  if (identityMismatch) return false;
18527
+ deliverOwnerMessages(runtime, context, signal, false, budget);
18265
18528
  let entries = context.sessionManager.getEntries();
18266
18529
  const evidenceKey = JSON.stringify(Object.values(expected));
18267
18530
  if (!hasDeliveredResult(entries, expected) && !resultDeliveryEvidence.has(evidenceKey)) {
@@ -18459,6 +18722,8 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18459
18722
  let submitted = 0;
18460
18723
  for (const runtime of runtimes.values()) {
18461
18724
  if (runtime.ownerSessionId !== ownerId || !active) continue;
18725
+ if (deliverOwnerMessages(runtime, context, context.signal, false, budget))
18726
+ submitted++;
18462
18727
  const requestId = runtime.activeRequestId ?? runtime.completedRequestId;
18463
18728
  if (requestId) {
18464
18729
  try {
@@ -18691,6 +18956,21 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18691
18956
  ctx.sessionManager.getSessionId(),
18692
18957
  resumed
18693
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;
18694
18974
  for (const agent of snapshot2.liveAgents)
18695
18975
  if (herdrSessionsMatch(
18696
18976
  agent,
@@ -18700,6 +18980,27 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`;
18700
18980
  ) && !statePanes.has(
18701
18981
  `${agent.workspace_id ?? ""}\0${agent.pane_id ?? ""}`
18702
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
+ }
18703
19004
  if (closedReceipt && closedReceipt.workspace_id === agent.workspace_id && closedReceipt.pane_id === agent.pane_id && typeof agent.pane_id === "string") {
18704
19005
  try {
18705
19006
  await paneProcess(pi, ctx, agent.pane_id, signal);
@@ -20325,7 +20626,7 @@ ${result.stderr ?? ""}`.trim(),
20325
20626
  ...agentTool,
20326
20627
  name: "reply_agent",
20327
20628
  label: "reply agent",
20328
- 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.",
20329
20630
  parameters: agentMessageParameters,
20330
20631
  promptSnippet: void 0,
20331
20632
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
@@ -20503,11 +20804,11 @@ ${result.stderr ?? ""}`.trim(),
20503
20804
  return [];
20504
20805
  }
20505
20806
  });
20506
- const publishAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
20807
+ const prepareAgentLoss = (ctx, state, snapshotAgentDefinition, availableActions, nextReminderMs, signal) => {
20507
20808
  const mailbox = agentMailboxPath(state.workspaceId, state.agentLabel);
20508
20809
  const current = readAgentState(mailbox);
20509
20810
  if (!current || !sameIdentity(current, state) || current.ownerSessionId !== ctx.sessionManager.getSessionId())
20510
- return false;
20811
+ return void 0;
20511
20812
  const currentHandoff = readUnacknowledgedRequest(mailbox, current);
20512
20813
  const requestIds = [
20513
20814
  current.completedRequestId,
@@ -20516,12 +20817,12 @@ ${result.stderr ?? ""}`.trim(),
20516
20817
  ].filter((value2) => !!value2);
20517
20818
  try {
20518
20819
  if (requestIds.some((requestId) => readResult(mailbox, requestId)))
20519
- return false;
20820
+ return void 0;
20520
20821
  } catch {
20521
- return false;
20822
+ return void 0;
20522
20823
  }
20523
20824
  const latest = readAgentState(mailbox);
20524
- if (!latest || !sameIdentity(latest, current)) return false;
20825
+ if (!latest || !sameIdentity(latest, current)) return void 0;
20525
20826
  const latestHandoff = readUnacknowledgedRequest(mailbox, latest);
20526
20827
  const latestRequestId = latest.completedRequestId ?? latest.activeRequestId ?? latestHandoff?.requestId;
20527
20828
  const latestRequestIds = [
@@ -20531,52 +20832,43 @@ ${result.stderr ?? ""}`.trim(),
20531
20832
  ].filter((value2) => !!value2);
20532
20833
  try {
20533
20834
  if (latestRequestIds.some((requestId) => readResult(mailbox, requestId)))
20534
- return false;
20535
- } catch {
20536
- return false;
20537
- }
20538
- if (signal.aborted || !ctx.isIdle()) return false;
20539
- try {
20540
- if (signal.aborted || !ctx.isIdle()) return false;
20541
- const stopAvailable = availableActions.includes("stop");
20542
- pi.sendMessage(
20543
- {
20544
- customType: "pi-herdsman-agent-lost",
20545
- content: [
20546
- `Agent ${current.agentLabel} is still lost and its assignment remains unresolved.`,
20547
- ...latestRequestId ? [`Request: ${latestRequestId}`] : [],
20548
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20549
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(nextReminderMs)}`,
20550
- "",
20551
- "Use read_agent_transcript only when persisted work materially affects the recovery decision.",
20552
- ...stopAvailable ? [
20553
- "Use stop_agent to stop this lost generation before replacing it or continuing its saved session."
20554
- ] : [
20555
- "stop_agent is not currently available; resolve the condition blocking its stop preflight before replacing or continuing it."
20556
- ],
20557
- "Physical disappearance is not task completion."
20558
- ].join("\n"),
20559
- display: true,
20560
- details: {
20561
- runId: current.runId,
20562
- ownerSessionId: current.ownerSessionId,
20563
- workspaceId: current.workspaceId,
20564
- agentLabel: current.agentLabel,
20565
- paneId: current.paneId,
20566
- piSessionId: current.piSessionId,
20567
- piSessionFile: current.piSessionFile,
20568
- agentDefinition: current.agentDefinition ?? snapshotAgentDefinition ?? "unknown",
20569
- requestId: latestRequestId,
20570
- availableActions,
20571
- nextReminderMs
20572
- }
20573
- },
20574
- { triggerTurn: true }
20575
- );
20576
- return true;
20835
+ return void 0;
20577
20836
  } catch {
20578
- return false;
20837
+ return void 0;
20579
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
+ };
20580
20872
  };
20581
20873
  const scanAgentHealth = async (ctx, signal, generation) => {
20582
20874
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
@@ -20596,7 +20888,14 @@ ${result.stderr ?? ""}`.trim(),
20596
20888
  );
20597
20889
  for (const runId of attentionReminders.keys())
20598
20890
  if (!ownedRuns.has(runId)) attentionReminders.delete(runId);
20599
- 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
+ };
20600
20899
  for (const agent of snapshot2.agents) {
20601
20900
  if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20602
20901
  return;
@@ -20611,107 +20910,125 @@ ${result.stderr ?? ""}`.trim(),
20611
20910
  if (state.resultError) {
20612
20911
  const error2 = state.resultError;
20613
20912
  const episode2 = `result-error:${error2.failedAt}:${error2.requestId}`;
20614
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20913
+ if (!attentionDue(state.runId, episode2, now)) continue;
20615
20914
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20616
20915
  const current2 = currentOwnedState(state, ownerSessionId);
20617
20916
  if (!current2?.resultError || current2.resultError.failedAt !== error2.failedAt || current2.resultError.requestId !== error2.requestId || !ctx.isIdle())
20618
20917
  continue;
20619
- try {
20620
- if (!ctx.isIdle()) continue;
20621
- pi.sendMessage(
20622
- {
20623
- customType: "pi-herdsman-agent-attention",
20624
- content: [
20625
- `Agent ${current2.agentLabel} could not persist its terminal result.`,
20626
- `Request: ${error2.requestId}`,
20627
- `Failure: ${error2.message}`,
20628
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20629
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20630
- "",
20631
- error2.nextAction,
20632
- "Do not start overlapping replacement work while this assignment remains unresolved."
20633
- ].join("\n"),
20634
- display: true,
20635
- details: {
20636
- reason: "result_error",
20637
- summary: error2.message,
20638
- runId: current2.runId,
20639
- requestId: error2.requestId,
20640
- ownerSessionId: current2.ownerSessionId,
20641
- workspaceId: current2.workspaceId,
20642
- agentLabel: current2.agentLabel,
20643
- paneId: current2.paneId,
20644
- piSessionId: current2.piSessionId,
20645
- availableActions,
20646
- nextReminderMs: intervalMs2,
20647
- nextAction: error2.nextAction
20648
- }
20649
- },
20650
- { triggerTurn: true }
20651
- );
20652
- recordAttention(state.runId, episode2, intervalMs2);
20653
- published = true;
20654
- } catch {
20655
- }
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
+ });
20656
20964
  continue;
20657
20965
  }
20658
20966
  if (agent.presence.kind === "lost" && !state.completedRequestId) {
20659
20967
  const episode2 = "lost";
20660
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20968
+ if (!attentionDue(state.runId, episode2, now)) continue;
20661
20969
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20662
- if (publishAgentLoss(
20970
+ const message = prepareAgentLoss(
20663
20971
  ctx,
20664
20972
  state,
20665
20973
  agent.agentDefinition,
20666
20974
  availableActions,
20667
20975
  intervalMs2,
20668
20976
  signal
20669
- )) {
20670
- recordAttention(state.runId, episode2, intervalMs2);
20671
- published = true;
20672
- }
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
+ });
20673
20993
  continue;
20674
20994
  }
20675
20995
  if (agent.presence.kind === "unknown") {
20676
20996
  const episode2 = "unknown";
20677
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20997
+ if (!attentionDue(state.runId, episode2, now)) continue;
20678
20998
  const current2 = currentOwnedState(state, ownerSessionId);
20679
20999
  if (!current2 || !ctx.isIdle()) continue;
20680
- try {
20681
- if (!ctx.isIdle()) continue;
20682
- pi.sendMessage(
20683
- {
20684
- customType: "pi-herdsman-agent-attention",
20685
- content: [
20686
- `Agent ${current2.agentLabel} has unresolved physical identity.`,
20687
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20688
- "",
20689
- "No safe direct control action is currently available.",
20690
- "Do not infer loss, guess a pane or process, or target ambiguous execution.",
20691
- "Herdsman will continue reconciling physical identity automatically."
20692
- ].join("\n"),
20693
- display: true,
20694
- details: {
20695
- reason: "unknown",
20696
- runId: current2.runId,
20697
- ownerSessionId: current2.ownerSessionId,
20698
- workspaceId: current2.workspaceId,
20699
- agentLabel: current2.agentLabel,
20700
- paneId: current2.paneId,
20701
- piSessionId: current2.piSessionId,
20702
- availableActions
20703
- }
20704
- },
20705
- { triggerTurn: true }
20706
- );
20707
- attentionReminders.set(state.runId, {
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, {
20708
21027
  episode: episode2,
20709
21028
  intervalMs: Number.POSITIVE_INFINITY,
20710
21029
  nextAt: Number.POSITIVE_INFINITY
20711
- });
20712
- published = true;
20713
- } catch {
20714
- }
21030
+ })
21031
+ });
20715
21032
  continue;
20716
21033
  }
20717
21034
  if (state.pendingAskId) {
@@ -20734,102 +21051,117 @@ ${result.stderr ?? ""}`.trim(),
20734
21051
  });
20735
21052
  continue;
20736
21053
  }
20737
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21054
+ if (!attentionDue(state.runId, episode2, now)) continue;
20738
21055
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20739
21056
  const current2 = currentOwnedState(state, ownerSessionId);
20740
21057
  if (!current2?.pendingAskId || !ctx.isIdle()) continue;
21058
+ let currentAsk;
20741
21059
  try {
20742
- const currentAsk = readPendingAsk(
21060
+ currentAsk = readPendingAsk(
20743
21061
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20744
21062
  current2
20745
21063
  );
20746
- if (!currentAsk || currentAsk.askId !== ask.askId || !hasDeliveredAsk(ctx.sessionManager.getBranch(), currentAsk))
20747
- continue;
20748
- if (!ctx.isIdle()) continue;
20749
- pi.sendMessage(
20750
- {
20751
- customType: "pi-herdsman-agent-ask",
20752
- content: [
20753
- `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
20754
- "",
20755
- currentAsk.question,
20756
- "",
20757
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20758
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20759
- "",
20760
- "Use reply_agent to reply to this exact pending ask if the required decision is available.",
20761
- "Do not delegate around or duplicate the blocked assignment."
20762
- ].join("\n"),
20763
- display: true,
20764
- details: {
20765
- askId: currentAsk.askId,
20766
- question: currentAsk.question,
20767
- requestId: currentAsk.requestId,
20768
- runId: currentAsk.runId,
20769
- agentLabel: currentAsk.agentLabel,
20770
- workspaceId: currentAsk.workspaceId,
20771
- paneId: currentAsk.paneId,
20772
- piSessionId: currentAsk.piSessionId,
20773
- availableActions,
20774
- nextReminderMs: intervalMs2
20775
- }
20776
- },
20777
- { triggerTurn: true }
20778
- );
20779
- recordAttention(state.runId, episode2, intervalMs2);
20780
- published = true;
20781
21064
  } catch {
21065
+ continue;
20782
21066
  }
20783
- } else {
20784
- attentionReminders.delete(state.runId);
20785
- }
20786
- continue;
20787
- }
20788
- if (agent.presence.kind === "live" && agent.lifecycleState === "blocked" && state.activeRequestId) {
20789
- const episode2 = `blocked:${state.activeRequestId}`;
20790
- if (published || !attentionDue(state.runId, episode2, now)) continue;
20791
- const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20792
- const current2 = currentOwnedState(state, ownerSessionId);
20793
- if (!current2?.activeRequestId || current2.pendingAskId || !ctx.isIdle())
20794
- continue;
20795
- try {
20796
- if (!ctx.isIdle()) continue;
20797
- pi.sendMessage(
20798
- {
20799
- customType: "pi-herdsman-agent-attention",
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",
20800
21074
  content: [
20801
- `Agent ${current2.agentLabel} is blocked in its live runtime, but no Herdsman ask_owner question exists.`,
20802
- `Request: ${current2.activeRequestId}`,
21075
+ `Agent ${currentAsk.agentLabel} is still waiting for your answer:`,
21076
+ "",
21077
+ currentAsk.question,
21078
+ "",
20803
21079
  `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20804
21080
  `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20805
21081
  "",
20806
- "Use read_agent_transcript for persisted conversation/tool evidence.",
20807
- "Use inspect_agent only when the live blocking state matters.",
20808
- "Do not invent an owner reply or send guessed terminal input.",
20809
- "Use stop_agent only when abandoning the assignment is the intended recovery."
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."
20810
21084
  ].join("\n"),
20811
21085
  display: true,
20812
21086
  details: {
20813
- reason: "blocked",
20814
- runId: current2.runId,
20815
- requestId: current2.activeRequestId,
20816
- ownerSessionId: current2.ownerSessionId,
20817
- workspaceId: current2.workspaceId,
20818
- agentLabel: current2.agentLabel,
20819
- paneId: current2.paneId,
20820
- piSessionId: current2.piSessionId,
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,
20821
21095
  availableActions,
20822
21096
  nextReminderMs: intervalMs2
20823
21097
  }
20824
21098
  },
20825
- { triggerTurn: true }
20826
- );
20827
- recordAttention(state.runId, episode2, intervalMs2);
20828
- published = true;
20829
- } 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);
20830
21117
  }
20831
21118
  continue;
20832
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
+ }
20833
21165
  let request;
20834
21166
  try {
20835
21167
  request = readUnacknowledgedRequest(
@@ -20841,51 +21173,65 @@ ${result.stderr ?? ""}`.trim(),
20841
21173
  }
20842
21174
  if (request && request.createdAt <= now && now - request.createdAt >= HEALTH_STALE_AFTER_MS) {
20843
21175
  const episode2 = `handoff:${request.requestId}`;
20844
- if (published || !attentionDue(state.runId, episode2, now)) continue;
21176
+ if (!attentionDue(state.runId, episode2, now)) continue;
20845
21177
  const intervalMs2 = nextAttentionInterval(state.runId, episode2);
20846
21178
  const current2 = currentOwnedState(state, ownerSessionId);
20847
21179
  if (!current2 || !ctx.isIdle()) continue;
21180
+ let currentRequest;
20848
21181
  try {
20849
- const currentRequest = readUnacknowledgedRequest(
21182
+ currentRequest = readUnacknowledgedRequest(
20850
21183
  agentMailboxPath(current2.workspaceId, current2.agentLabel),
20851
21184
  current2
20852
21185
  );
20853
- if (!currentRequest || currentRequest.requestId !== request.requestId || !ctx.isIdle())
20854
- continue;
20855
- pi.sendMessage(
20856
- {
20857
- customType: "pi-herdsman-agent-attention",
20858
- content: [
20859
- `Agent ${current2.agentLabel} still has an unacknowledged ${currentRequest.kind} request.`,
20860
- `Request: ${currentRequest.requestId}`,
20861
- `Pending for: ${formatHealthAttentionDuration(now - currentRequest.createdAt)}`,
20862
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20863
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs2)}`,
20864
- "",
20865
- "The durable request is still retained.",
20866
- "Do not submit the same intent again: acknowledgement timeout does not prove non-delivery.",
20867
- "Herdsman will continue reconciling this exact request."
20868
- ].join("\n"),
20869
- display: true,
20870
- details: {
20871
- reason: "handoff",
20872
- runId: current2.runId,
20873
- requestId: currentRequest.requestId,
20874
- ownerSessionId: current2.ownerSessionId,
20875
- workspaceId: current2.workspaceId,
20876
- agentLabel: current2.agentLabel,
20877
- paneId: current2.paneId,
20878
- piSessionId: current2.piSessionId,
20879
- availableActions,
20880
- nextReminderMs: intervalMs2
20881
- }
20882
- },
20883
- { triggerTurn: true }
20884
- );
20885
- recordAttention(state.runId, episode2, intervalMs2);
20886
- published = true;
20887
21186
  } catch {
21187
+ continue;
20888
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
+ });
20889
21235
  continue;
20890
21236
  }
20891
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) {
@@ -20893,7 +21239,7 @@ ${result.stderr ?? ""}`.trim(),
20893
21239
  continue;
20894
21240
  }
20895
21241
  const episode = `stale:${state.activeRequestId}:${state.lastActivityAt}`;
20896
- if (published || !attentionDue(state.runId, episode, now)) continue;
21242
+ if (!attentionDue(state.runId, episode, now)) continue;
20897
21243
  const firstAttention = attentionReminders.get(state.runId)?.episode !== episode;
20898
21244
  const intervalMs = HEALTH_ATTENTION_FIRST_REPEAT_MS;
20899
21245
  const current = currentOwnedState(state, ownerSessionId);
@@ -20902,7 +21248,9 @@ ${result.stderr ?? ""}`.trim(),
20902
21248
  if (signal.aborted || generation !== healthGeneration) return;
20903
21249
  let diagnostic;
20904
21250
  const attemptedDiagnostic = firstAttention && availableActions.includes("inspect");
21251
+ if (attemptedDiagnostic && initialStaleInspectionUsed) continue;
20905
21252
  if (attemptedDiagnostic) {
21253
+ initialStaleInspectionUsed = true;
20906
21254
  const diagnosticSignal = AbortSignal.any([
20907
21255
  signal,
20908
21256
  AbortSignal.timeout(HEALTH_STALE_DIAGNOSTIC_TIMEOUT_MS)
@@ -20981,56 +21329,108 @@ ${result.stderr ?? ""}`.trim(),
20981
21329
  "Do not repeat inspect_agent or read_agent_transcript solely because this reminder fired.",
20982
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."
20983
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()) {
20984
21416
  try {
20985
- if (signal.aborted || generation !== healthGeneration || !ctx.isIdle())
20986
- return;
20987
- pi.sendMessage(
20988
- {
20989
- customType: "pi-herdsman-agent-stale",
20990
- content: [
20991
- `Agent ${current.agentLabel} has had no qualifying execution progress for ${formatHealthAttentionDuration(inactiveMs)}.`,
20992
- `Request: ${current.activeRequestId}`,
20993
- `Available tools: ${availableActions.map(agentToolName).join(", ") || "none"}`,
20994
- `Next reminder if unresolved: ~${formatHealthAttentionDuration(intervalMs)}`,
20995
- ...diagnosticLines,
20996
- "",
20997
- "This is advisory inactivity, not proof of a hang.",
20998
- "Streaming tool output does not count as qualifying progress.",
20999
- "steer_agent queues a cooperative correction; it does not preempt the current operation.",
21000
- "Use interrupt_agent only when the current operation itself must be abandoned; interrupt_agent cancels that operation, supersedes earlier steering Pi has not yet delivered, and continues the same assignment.",
21001
- "Use stop_agent only to abandon the assignment or as destructive fallback."
21002
- ].join("\n"),
21003
- display: true,
21004
- details: {
21005
- runId: latest.runId,
21006
- requestId: latest.activeRequestId,
21007
- agentLabel: latest.agentLabel,
21008
- ownerSessionId: latest.ownerSessionId,
21009
- workspaceId: latest.workspaceId,
21010
- paneId: latest.paneId,
21011
- piSessionId: latest.piSessionId,
21012
- lastActivityAt: latest.lastActivityAt,
21013
- inactiveMs,
21014
- thresholdMs: HEALTH_STALE_AFTER_MS,
21015
- availableActions,
21016
- nextReminderMs: intervalMs,
21017
- ...diagnostic ? {
21018
- captured_at: diagnostic.capturedAt,
21019
- recent_output_truncated: diagnostic.recentOutputTruncated,
21020
- ...diagnostic.recentOutput ? { recent_output: diagnostic.recentOutput } : {},
21021
- ...diagnostic.process ? { process: diagnostic.process } : {}
21022
- } : {}
21023
- }
21024
- },
21025
- { triggerTurn: true }
21026
- );
21027
- if (generation === healthGeneration && !signal.aborted) {
21028
- recordAttention(state.runId, episode, intervalMs);
21029
- published = true;
21030
- }
21417
+ pi.sendMessage(item.message, {
21418
+ triggerTurn: index === ready2.length - 1
21419
+ });
21420
+ submitted.push(item);
21421
+ if (index === ready2.length - 1) triggerSubmitted = true;
21031
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
+ }
21032
21431
  }
21033
21432
  }
21433
+ if (triggerSubmitted) for (const item of submitted) item.onSubmitted();
21034
21434
  };
21035
21435
  const runAgentHealthScanner = (ctx, signal) => {
21036
21436
  const generation = ++healthGeneration;
@@ -21081,6 +21481,34 @@ ${result.stderr ?? ""}`.trim(),
21081
21481
  pi,
21082
21482
  (ctx, phase, budget) => drainReadyOwnerNotifications(ctx, phase, budget)
21083
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
+ });
21084
21512
  return {
21085
21513
  listAgentStates,
21086
21514
  managedAgentSnapshots: snapshot,
@@ -21132,8 +21560,10 @@ ${result.stderr ?? ""}`.trim(),
21132
21560
  rollbackUnknownStartedAgent,
21133
21561
  watchResult,
21134
21562
  watchAsk,
21563
+ watchOwnerMessages,
21135
21564
  stopResultWatcher,
21136
21565
  stopAskWatcher,
21566
+ stopOwnerMessageWatcher,
21137
21567
  deliverResult,
21138
21568
  cleanupDeliveredResult(runtime, result, context, signal) {
21139
21569
  return finalizeDeliveredResult(runtime, result, context, signal);
@@ -21160,7 +21590,10 @@ ${result.stderr ?? ""}`.trim(),
21160
21590
  sessionTreeChanged(context, signal) {
21161
21591
  active = true;
21162
21592
  for (const runtime of runtimes.values()) {
21163
- if (runtime.activeRequestId) watchAsk(runtime, context, signal);
21593
+ if (runtime.activeRequestId) {
21594
+ watchAsk(runtime, context, signal);
21595
+ watchOwnerMessages(runtime, context, signal);
21596
+ }
21164
21597
  }
21165
21598
  },
21166
21599
  abortSession() {
@@ -21199,8 +21632,10 @@ ${result.stderr ?? ""}`.trim(),
21199
21632
  recoveryComplete = false;
21200
21633
  for (const watcher of resultWatchers.values()) watcher();
21201
21634
  for (const watcher of askWatchers.values()) watcher();
21635
+ for (const watcher of ownerMessageWatchers.values()) watcher();
21202
21636
  resultWatchers.clear();
21203
21637
  askWatchers.clear();
21638
+ ownerMessageWatchers.clear();
21204
21639
  for (const timer of resultDeliveryRetries.values()) clearTimeout(timer);
21205
21640
  for (const timer of resultCleanupRetries.values()) clearTimeout(timer);
21206
21641
  for (const timer of askDeliveryRetries.values()) clearTimeout(timer);
@@ -21209,6 +21644,8 @@ ${result.stderr ?? ""}`.trim(),
21209
21644
  askDeliveryRetries.clear();
21210
21645
  resultDeliveryInFlight.clear();
21211
21646
  askDeliveryInFlight.clear();
21647
+ ownerMessageDeliveryInFlight.clear();
21648
+ submittedOwnerMessages.clear();
21212
21649
  resultDeliveryEvidence.clear();
21213
21650
  resultDeliverySemanticRefs.clear();
21214
21651
  runtimes.clear();
@@ -21465,10 +21902,18 @@ do not select evidence unless the owner needs it.
21465
21902
  Do not silently broaden scope or make an unapproved scope, architecture,
21466
21903
  security, protocol, repository-boundary, product, or operational decision.
21467
21904
 
21468
- Use ask_owner only when a decision from your exact direct owner is genuinely
21469
- required to continue correctly. Explicit attachments must be supported UTF-8
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
21470
21915
  text fully embedded within the applicable per-file and complete-message
21471
- budgets. Call ask_owner alone as the final tool call of the turn. Wait for the
21916
+ budgets. Call await_owner alone as the final tool call of the turn. Wait for the
21472
21917
  direct owner's reply only after the tool confirms the question was sent; if
21473
21918
  rejected, address the error or report a non-empty blocker. Keep at most one
21474
21919
  question outstanding. Do not guess the answer. The reply resumes the same
@@ -21501,7 +21946,7 @@ blockers, remaining work, and reusable paths or artifacts.`;
21501
21946
  };
21502
21947
  AGENT_DEFINITION_ENTRY = "pi-herdsman-agent-definition";
21503
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.";
21504
- AGENT_UNRESOLVED_GUIDANCE = "Use list_agents when fresh Agent state or ownership is materially needed for a control or recovery decision, or to refresh the definition roster; do not use it for progress polling. Follow current available_tools and revalidation: steer_agent queues a cooperative correction for Pi to deliver after the current assistant turn and its tool calls reach a steering boundary; it does not preempt the current operation. interrupt_agent cancels the current operation and replaces its direction. Use reply_agent only to answer that Agent's exact pending ask_owner question. stop_agent abandons an eligible Agent generation and its unfinished assignment. inspect_agent provides bounded live terminal/process evidence; read_agent_transcript provides bounded persisted conversation/tool evidence. When Agent work is unresolved, handle required control, then continue only necessary work you still own or end the turn without concluding; results or attention resume the session automatically. Do not poll with status requests, sleep, or other waiting mechanisms. Stale health attention is diagnosis, not progress polling: use attached evidence first and, when absent or insufficient, perform at most one bounded diagnostic read before passive waiting. A repeated reminder for the same stale episode is additional recovery evidence: unchanged qualifying activity means the Agent has not crossed an execution boundary since the previous reminder. A steer queued during that unchanged episode cannot have taken effect yet. Do not repeat diagnostic reads solely because a reminder fired. Continue waiting only while existing evidence still positively supports a legitimate long-running operation; otherwise use interrupt_agent to stop the current operation and continue the same assignment. A proven lost Agent remains unresolved; physical disappearance is not completion. A physically unknown Agent remains fail-closed: do not control, close, replace, or infer completion of that generation. Unknown Agent identity does not by itself prove a currently active competing writer. For a concrete recovery decision, use available current evidence and at most one bounded diagnostic read when necessary; distinguish historical Agent identity from current execution and delegated scope. Continue necessary independent work that remains authorized and has no unresolved execution conflict. Do not take over the Agent's unresolved assignment. Do not take over or replace unresolved delegated work until the current generation is resolved or explicitly closed. If evidence is insufficient to exclude competing execution, preserve the affected scope and identify the specific missing evidence or external action. Do not repeat the same identity investigation without new evidence.";
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.";
21505
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.";
21506
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.";
21507
21952
  LEAD_SCOPE_DESCRIPTION = `Own architecture, approved scope, acceptance of Agent outputs, integration, conflict resolution,
@@ -21528,7 +21973,7 @@ omit unrelated evidence and evidence already inherited as the same required vers
21528
21973
  but explicitly forward changed versions. Summaries do not transfer evidence.
21529
21974
  The lead retains architecture, approved scope, acceptance, and final-decision
21530
21975
  authority. Delegate only to definitions listed in your effective agents field.
21531
- 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
21532
21977
  direct-agent work. If unresolved direct-agent work exists, every such agent
21533
21978
  must itself be validly waiting on an owner answer; ordinary active or
21534
21979
  pending-result agent work still blocks escalation.`;
@@ -21555,6 +22000,7 @@ __export(managed_agent_runtime_exports, {
21555
22000
  createManagedAgentExecutionState: () => createManagedAgentExecutionState,
21556
22001
  createManagedAgentLeafStatus: () => createManagedAgentLeafStatus,
21557
22002
  createManagedAgentMetadataPublisher: () => createManagedAgentMetadataPublisher,
22003
+ createManagedAgentNotifyOwnerHandler: () => createManagedAgentNotifyOwnerHandler,
21558
22004
  createManagedAgentRequestState: () => createManagedAgentRequestState,
21559
22005
  ensureManagedAgentIdentity: () => ensureManagedAgentIdentity,
21560
22006
  evidencePageContent: () => evidencePageContent,
@@ -21568,6 +22014,7 @@ __export(managed_agent_runtime_exports, {
21568
22014
  registerManagedAgentAttachHandoffTool: () => registerManagedAgentAttachHandoffTool,
21569
22015
  registerManagedAgentContextHandlers: () => registerManagedAgentContextHandlers,
21570
22016
  registerManagedAgentInputHandlers: () => registerManagedAgentInputHandlers,
22017
+ registerManagedAgentNotifyOwnerTool: () => registerManagedAgentNotifyOwnerTool,
21571
22018
  registerManagedAgentResultCapture: () => registerManagedAgentResultCapture,
21572
22019
  registerManagedAgentRuntime: () => registerManagedAgentRuntime,
21573
22020
  registerManagedAgentSessionStartHandler: () => registerManagedAgentSessionStartHandler,
@@ -22232,8 +22679,6 @@ function createManagedAgentLeafStatus(options) {
22232
22679
  let inFlight = false;
22233
22680
  let focusInFlight = false;
22234
22681
  let breadcrumb;
22235
- let ownTools;
22236
- const ownToolsSnapshot = () => ownTools ? { ownTools } : {};
22237
22682
  const reset = () => {
22238
22683
  generation++;
22239
22684
  if (timer) clearInterval(timer);
@@ -22275,7 +22720,7 @@ function createManagedAgentLeafStatus(options) {
22275
22720
  stale: false,
22276
22721
  unavailable: false,
22277
22722
  breadcrumb,
22278
- ...ownToolsSnapshot(),
22723
+ ...options.ownToolsSnapshot(),
22279
22724
  identityOnly: true,
22280
22725
  refreshedAt: Date.now()
22281
22726
  });
@@ -22295,7 +22740,7 @@ function createManagedAgentLeafStatus(options) {
22295
22740
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22296
22741
  }
22297
22742
  ],
22298
- ...ownToolsSnapshot(),
22743
+ ...options.ownToolsSnapshot(),
22299
22744
  identityOnly: true
22300
22745
  });
22301
22746
  } finally {
@@ -22307,9 +22752,6 @@ function createManagedAgentLeafStatus(options) {
22307
22752
  invalidate() {
22308
22753
  widget?.invalidate();
22309
22754
  },
22310
- captureOwnTools(tools) {
22311
- ownTools = tools;
22312
- },
22313
22755
  start(ctx) {
22314
22756
  const activeGeneration = generation;
22315
22757
  context = ctx;
@@ -22352,7 +22794,7 @@ function createManagedAgentLeafStatus(options) {
22352
22794
  ...process.env.PI_HERDSMAN_AGENT_DEFINITION ? { role: process.env.PI_HERDSMAN_AGENT_DEFINITION } : {}
22353
22795
  }
22354
22796
  ],
22355
- ...ownToolsSnapshot(),
22797
+ ...options.ownToolsSnapshot(),
22356
22798
  identityOnly: true
22357
22799
  });
22358
22800
  if (activeGeneration === generation && ctx === context) widget = next;
@@ -22370,7 +22812,7 @@ function createManagedAgentAskOwnerHandler(options) {
22370
22812
  throw new Error("Question must contain non-whitespace text");
22371
22813
  if (!options.isSoleToolCall(ctx))
22372
22814
  throw new Error(
22373
- "Call ask_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
22815
+ "Call await_owner alone as the final tool call of the turn, with no other tool calls, then wait for the reply."
22374
22816
  );
22375
22817
  const managed = managedAgentIdentity(ctx);
22376
22818
  const state = options.state();
@@ -22439,6 +22881,83 @@ function createManagedAgentAskOwnerHandler(options) {
22439
22881
  };
22440
22882
  };
22441
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
+ }
22442
22961
  function handoffSelectionDetails(state, resultBindings) {
22443
22962
  return {
22444
22963
  version: 1,
@@ -22535,7 +23054,7 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22535
23054
  )
22536
23055
  );
22537
23056
  pi.registerTool({
22538
- name: "ask_owner",
23057
+ name: "await_owner",
22539
23058
  label: "Ask owner",
22540
23059
  exposure: "model-only",
22541
23060
  promptSnippet: "Ask this managed agent's direct owner for a required decision",
@@ -22555,6 +23074,39 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
22555
23074
  execute
22556
23075
  });
22557
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
+ }
22558
23110
  function createManagedAgentEvidenceUpdater(pi) {
22559
23111
  return async function updateManagedAgentEvidence(_id, params, _signal, _update, ctx) {
22560
23112
  const state = managedAgentIdentity(ctx);
@@ -23151,7 +23703,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
23151
23703
  } : {
23152
23704
  error: {
23153
23705
  code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
23154
- message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : observation?.requestId === state.activeRequestId && observation.askOwnerCapacityError ? `Agent produced no assistant text. Earlier in this execution, ask_owner rejected its attachments: ${observation.askOwnerCapacityError}. The question was not sent.` : "Agent produced no assistant text"
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"
23155
23707
  }
23156
23708
  },
23157
23709
  contextUsage: ctx.getContextUsage(),
@@ -23315,6 +23867,13 @@ function registerManagedAgentRuntime(pi, options) {
23315
23867
  const allowedAgentDefinitions = allowedAgentDefinitionsFromEnv();
23316
23868
  const agentDepth = agentDepthFromEnv();
23317
23869
  const delegationEnabled = allowedAgentDefinitions.length > 0;
23870
+ const ownToolsSnapshot = () => {
23871
+ try {
23872
+ return { ownTools: pi.getActiveTools() };
23873
+ } catch {
23874
+ return {};
23875
+ }
23876
+ };
23318
23877
  let startupDefinitionRoster;
23319
23878
  const controller = delegationEnabled ? createAgentController(pi, {
23320
23879
  ...options.controllerOptions,
@@ -23346,7 +23905,7 @@ function registerManagedAgentRuntime(pi, options) {
23346
23905
  hasPendingStart: (label) => controller.hasPendingStart(label),
23347
23906
  clearPendingStart: (label, expected) => controller.clearPendingStart(label, expected),
23348
23907
  runtimeForLabel: (label) => controller.runtimeForLabel(label),
23349
- ownToolsSnapshot: () => ({}),
23908
+ ownToolsSnapshot,
23350
23909
  focusTarget: async (ctx, intent, isCurrent) => {
23351
23910
  if (intent.kind !== "session")
23352
23911
  throw new Error("Manager navigation is unavailable from an Agent.");
@@ -23370,7 +23929,7 @@ function registerManagedAgentRuntime(pi, options) {
23370
23929
  label: process.env.PI_HERDSMAN_LABEL
23371
23930
  }),
23372
23931
  sameIdentity: sameManagedAgentIdentity,
23373
- ownToolsSnapshot: () => ({})
23932
+ ownToolsSnapshot
23374
23933
  });
23375
23934
  const currentIdentity = managedAgentEnvironmentIdentity(
23376
23935
  ctx,
@@ -23431,7 +23990,7 @@ function registerManagedAgentRuntime(pi, options) {
23431
23990
  label: process.env.PI_HERDSMAN_LABEL
23432
23991
  }),
23433
23992
  sameIdentity: sameManagedAgentIdentity,
23434
- ownToolsSnapshot: () => ({})
23993
+ ownToolsSnapshot
23435
23994
  });
23436
23995
  }
23437
23996
  });
@@ -23470,6 +24029,7 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23470
24029
  identity: (ctx) => managedAgentEnvironmentIdentity(ctx, options.build),
23471
24030
  sameIdentity: sameManagedAgentIdentity,
23472
24031
  signal: () => metadataPublisher.signal,
24032
+ ownToolsSnapshot,
23473
24033
  getLocalActivity: (ctx) => getLocalActivity(ctx),
23474
24034
  focusTarget: async (ctx, intent, isCurrent) => {
23475
24035
  if (intent.kind !== "session")
@@ -23647,13 +24207,13 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23647
24207
  sameIdentity: sameManagedAgentIdentity,
23648
24208
  eligible: requestState.eligibleToAsk,
23649
24209
  rejectionReason: requestState.askRejectionReason,
23650
- isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "ask_owner"),
24210
+ isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "await_owner"),
23651
24211
  messageLimits: options.messageLimits,
23652
24212
  prepare: async (ctx, question, files, state, askId, createdAt, limits) => prepareMessageInput(
23653
24213
  question,
23654
- options.resolveMessageFiles(ctx, files, "ask_owner"),
24214
+ options.resolveMessageFiles(ctx, files, "await_owner"),
23655
24215
  state.cwd,
23656
- "ask_owner",
24216
+ "await_owner",
23657
24217
  "Question",
23658
24218
  {
23659
24219
  inlineLimitBytes: limits.inline.bytes,
@@ -23667,11 +24227,11 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23667
24227
  fail(
23668
24228
  "invalid_request",
23669
24229
  `Mailbox payload is ${bytes} bytes; configured limit is ${limit} bytes`,
23670
- "ask_owner",
24230
+ "await_owner",
23671
24231
  { details: { capacity: true } }
23672
24232
  );
23673
24233
  },
23674
- claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "ask_owner", {
24234
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "await_owner", {
23675
24235
  label: state.agentLabel,
23676
24236
  paneId: state.paneId
23677
24237
  }),
@@ -23688,11 +24248,52 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23688
24248
  try {
23689
24249
  return await executeAskOwner(...args);
23690
24250
  } catch (error2) {
23691
- if (error2 instanceof OperationError && error2.detail.operation === "ask_owner" && error2.detail.details?.capacity === true && observation?.requestId && observation === execution.observation && execution.assignment?.activeRequestId === observation.requestId && !execution.assignment.pendingAskId)
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)
23692
24252
  observation.askOwnerCapacityError = error2.message.slice(0, 512);
23693
24253
  throw error2;
23694
24254
  }
23695
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);
23696
24297
  const prepareDelegatingRoster = async (ctx) => {
23697
24298
  startupDefinitionRoster = void 0;
23698
24299
  if (!delegationEnabled) return;
@@ -23724,8 +24325,6 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
23724
24325
  },
23725
24326
  resetRequestPump,
23726
24327
  resetLeafStatus: leafStatus.reset,
23727
- captureOwnTools: leafStatus.captureOwnTools,
23728
- getActiveTools: () => pi.getActiveTools(),
23729
24328
  clearControllerRuntimes: clearAgentRuntimes,
23730
24329
  setControllerReady: (ready) => controller?.setReady(ready),
23731
24330
  beginMetadataSession: metadataPublisher.beginSession,
@@ -23922,6 +24521,20 @@ function createManagedAgentRequestState(pi, options) {
23922
24521
  const state = options.state();
23923
24522
  return !!state?.activeRequestId && !state.pendingAskId && !state.completedRequestId && !options.pendingResult() && !options.pendingStateTransition() && !unacknowledgedRequestExists(process.env.PI_HERDSMAN_MAILBOX, state) && options.allDirectChildrenAskBlocked(state);
23924
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
+ };
23925
24538
  const askRejectionReason = () => {
23926
24539
  const state = options.state();
23927
24540
  if (!state?.activeRequestId) return "no active assignment";
@@ -23949,6 +24562,8 @@ function createManagedAgentRequestState(pi, options) {
23949
24562
  pump,
23950
24563
  eligibleToAsk,
23951
24564
  askRejectionReason,
24565
+ eligibleToNotify,
24566
+ notifyRejectionReason,
23952
24567
  reportAcknowledgementFailure,
23953
24568
  reset
23954
24569
  };
@@ -24153,7 +24768,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24153
24768
  options.startControllerSession();
24154
24769
  options.resetRequestPump();
24155
24770
  options.resetLeafStatus();
24156
- options.captureOwnTools(void 0);
24157
24771
  if (options.delegationEnabled) options.clearControllerRuntimes();
24158
24772
  execution.initialized = false;
24159
24773
  options.setControllerReady(false);
@@ -24166,8 +24780,6 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
24166
24780
  execution.agentContext = ctx;
24167
24781
  const candidate = options.environmentIdentity(ctx);
24168
24782
  if (!candidate) throw new Error("invalid agent environment");
24169
- if (!options.delegationEnabled)
24170
- options.captureOwnTools(options.getActiveTools());
24171
24783
  options.ensureAgentIdentity(ctx);
24172
24784
  verified = candidate;
24173
24785
  const restoreModel = process.env.PI_HERDSMAN_RESTORE_MODEL;
@@ -24477,7 +25089,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
24477
25089
  // package.json
24478
25090
  var package_default = {
24479
25091
  name: "pi-herdsman",
24480
- version: "0.44.0",
25092
+ version: "0.45.0",
24481
25093
  type: "module",
24482
25094
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
24483
25095
  license: "Apache-2.0",
@@ -24526,7 +25138,7 @@ var package_default = {
24526
25138
  },
24527
25139
  piHerdsman: {
24528
25140
  runtime: {
24529
- pi: "1.5.0",
25141
+ pi: "1.5.2",
24530
25142
  herdr: {
24531
25143
  version: "0.9.5",
24532
25144
  sha256: {
@@ -24560,9 +25172,9 @@ var package_default = {
24560
25172
  typebox: "*"
24561
25173
  },
24562
25174
  devDependencies: {
24563
- "@earendil-works/pi-ai": "1.5.0",
24564
- "@earendil-works/pi-coding-agent": "1.5.0",
24565
- "@earendil-works/pi-tui": "1.5.0",
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",
24566
25178
  "@howaboua/pi-codex-conversion": "4.0.4",
24567
25179
  "@modelcontextprotocol/sdk": "1.32.0",
24568
25180
  "@types/node": "22.19.19",
@@ -35709,6 +36321,16 @@ function createLeadIdentityRuntime(host) {
35709
36321
  };
35710
36322
  return { liveAgent, remoteChiefAgent, liveLead };
35711
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
+ }
35712
36334
  function createLeadSupervisionRuntime(host) {
35713
36335
  const loadSupervisionSnapshot = async (ctx, suppliedInventory, suppliedAgents, includeAll = false, classifyBuilds = false, knownTopology, exactSession) => {
35714
36336
  if (host.activeRole() === "chief" && !includeAll) {
@@ -35967,12 +36589,12 @@ function createLeadSupervisionRuntime(host) {
35967
36589
  for (const report of snapshot2.incompatible ?? [])
35968
36590
  if (report.role === "lead" && scope.workspaceIds.includes(report.workspaceId))
35969
36591
  incompatible?.push(report);
35970
- const assignments = host.listProjectAssignments(
36592
+ const assignments2 = host.listProjectAssignments(
35971
36593
  host.supervisionRuntime(),
35972
36594
  manager.repoKey
35973
36595
  );
35974
- const sessions = new Set(assignments.map((assignment) => assignment.id));
35975
- if (sessions.size !== assignments.length)
36596
+ const sessions = new Set(assignments2.map((assignment) => assignment.id));
36597
+ if (sessions.size !== assignments2.length)
35976
36598
  throw new Error("Multiple project assignments match a Lead session");
35977
36599
  const repoManagers = host.listManagerDescriptors(host.supervisionRuntime()).filter((candidate) => candidate.repoKey === manager.repoKey);
35978
36600
  const ordinarySupervisionAvailable = repoManagers.length === 1 && host.sameManagerDescriptor(repoManagers[0], manager);
@@ -36069,7 +36691,7 @@ function createLeadSupervisionRuntime(host) {
36069
36691
  ...lead,
36070
36692
  role: "lead",
36071
36693
  ...sessions.has(lead.lead) ? {
36072
- branch: assignments.find(
36694
+ branch: assignments2.find(
36073
36695
  (assignment) => assignment.id === lead.lead
36074
36696
  ).branch
36075
36697
  } : {},
@@ -36101,19 +36723,25 @@ function createLeadSupervisionRuntime(host) {
36101
36723
  )).agents;
36102
36724
  const managerLeadSessions = /* @__PURE__ */ new Set();
36103
36725
  const descriptors = host.listManagerDescriptors(host.supervisionRuntime());
36726
+ const assignments = globalProjectAssignmentSnapshot();
36104
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
+ }
36105
36740
  try {
36106
- const scope = await host.worktreeGroupScope(
36107
- host.pi,
36108
- ctx,
36109
- lead.workspaceId,
36110
- ctx.signal
36111
- );
36112
36741
  const supervisor = await host.resolveEffectiveSupervisor(
36113
36742
  ctx,
36114
36743
  lead.lead,
36115
- lead.workspaceId,
36116
- scope
36744
+ lead.workspaceId
36117
36745
  );
36118
36746
  if (supervisor.kind !== "chief") managerLeadSessions.add(lead.lead);
36119
36747
  } catch {
@@ -36123,17 +36751,10 @@ function createLeadSupervisionRuntime(host) {
36123
36751
  for (const lead of allLeadSnapshot.incompatible ?? []) {
36124
36752
  if (lead.role !== "lead") continue;
36125
36753
  try {
36126
- const scope = await host.worktreeGroupScope(
36127
- host.pi,
36128
- ctx,
36129
- lead.workspaceId,
36130
- ctx.signal
36131
- );
36132
36754
  const supervisor = await host.resolveEffectiveSupervisor(
36133
36755
  ctx,
36134
36756
  lead.session,
36135
- lead.workspaceId,
36136
- scope
36757
+ lead.workspaceId
36137
36758
  );
36138
36759
  if (supervisor.kind === "manager") {
36139
36760
  managerLeadSessions.add(lead.session);
@@ -38183,12 +38804,23 @@ function createLeadInboxRuntime(host) {
38183
38804
  if (record.kind === "lead_message") {
38184
38805
  const leads = await liveLead(ctx, record.fromSessionId);
38185
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;
38186
38818
  let scope2;
38187
38819
  try {
38188
38820
  scope2 = await worktreeGroupScope2(
38189
38821
  pi,
38190
38822
  ctx,
38191
- leads[0].workspace_id,
38823
+ sender.workspace_id,
38192
38824
  ctx.signal
38193
38825
  );
38194
38826
  } catch (error2) {
@@ -38202,7 +38834,7 @@ function createLeadInboxRuntime(host) {
38202
38834
  const supervisor = await host.resolveEffectiveSupervisor(
38203
38835
  ctx,
38204
38836
  record.fromSessionId,
38205
- leads[0].workspace_id,
38837
+ sender.workspace_id,
38206
38838
  scope2
38207
38839
  );
38208
38840
  return !!state2 && (state2.role ?? "lead") === "lead" && supervisor.kind === "chief" && supervisor.chief.piSessionId === chief.piSessionId && supervisor.chief.leaseId === chief.leaseId;
@@ -38266,6 +38898,8 @@ function createLeadInboxRuntime(host) {
38266
38898
  }
38267
38899
  if (activeRole() !== "lead" || leadRuntime.roleSuspended) return false;
38268
38900
  if (record.kind === "chief_message") {
38901
+ if (readSessionKind(ctx.sessionManager.getEntries(), sessionId)?.kind !== "ordinary")
38902
+ return false;
38269
38903
  const chief = await currentChiefAuthority(ctx);
38270
38904
  const workspaceId2 = host.workspaceId();
38271
38905
  if (!workspaceId2) return false;
@@ -41092,6 +41726,13 @@ function registerExtensionImpl(pi, lockHooks) {
41092
41726
  (expanded) => renderAgentAskMessage(message, { ...options, expanded }, theme)
41093
41727
  )
41094
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
+ );
41095
41736
  pi.registerMessageRenderer(
41096
41737
  "pi-herdsman-agent-stale",
41097
41738
  (message, options, theme) => expandablePresentation(
@@ -41262,6 +41903,33 @@ Use reply_agent with agent="${ask.agentLabel}" to answer this question.`,
41262
41903
  { triggerTurn }
41263
41904
  );
41264
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
+ }
41931
+ );
41932
+ },
41265
41933
  sessionRetired: (ctx, runtime) => {
41266
41934
  if (!runtime.piSessionFile) return void 0;
41267
41935
  try {