pi-herdsman 0.41.0 → 0.42.1

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
@@ -1075,6 +1075,39 @@ function observeMailbox(directory2, relevant, reconcile, onError) {
1075
1075
  watcher = void 0;
1076
1076
  };
1077
1077
  }
1078
+ function observeNewAgentStates(onNew, onError) {
1079
+ let known = /* @__PURE__ */ new Set();
1080
+ const scan = () => {
1081
+ const present = /* @__PURE__ */ new Set();
1082
+ let names2 = [];
1083
+ try {
1084
+ names2 = readdirSync3(root);
1085
+ } catch (error2) {
1086
+ if (error2.code !== "ENOENT") throw error2;
1087
+ }
1088
+ for (const name of names2)
1089
+ if (MAILBOX_DIRECTORY.test(name) && existsSync(file(join3(root, name), "state.json")))
1090
+ present.add(name);
1091
+ return present;
1092
+ };
1093
+ try {
1094
+ known = scan();
1095
+ } catch (error2) {
1096
+ onError(error2);
1097
+ }
1098
+ return observeMailbox(
1099
+ root,
1100
+ (name) => MAILBOX_DIRECTORY.test(name),
1101
+ () => {
1102
+ const previous = known;
1103
+ known = scan();
1104
+ if ([...known].some((name) => !previous.has(name))) onNew();
1105
+ },
1106
+ (error2) => {
1107
+ if (error2?.code !== "ENOENT") onError(error2);
1108
+ }
1109
+ );
1110
+ }
1078
1111
  function agentMailboxPath(workspaceId, agentLabel) {
1079
1112
  return join3(
1080
1113
  root,
@@ -1176,6 +1209,7 @@ function validate(value2, kind) {
1176
1209
  "bootstrap",
1177
1210
  "mailbox_state",
1178
1211
  "controller_recovery",
1212
+ "model_restore",
1179
1213
  "request_observer",
1180
1214
  "metadata"
1181
1215
  ].includes(v.stage))
@@ -2046,6 +2080,7 @@ function prepareMessageInput(text, files, cwd, operation, heading, options = {})
2046
2080
  ${text}`, ...sections] : [...sections, `${heading}:
2047
2081
  ${text}`]).join("\n\n");
2048
2082
  const fits = options.fits ?? ((value2, bindings) => (options.serializedBytes ? options.serializedBytes(value2, bindings) : Buffer.byteLength(value2, "utf8")) <= (options.mailboxLimitBytes ?? MAILBOX_PROTOCOL_LIMIT_BYTES));
2083
+ const capacityMessage = (file2) => file2.bytes > (options.inlineLimitBytes ?? MAILBOX_PROTOCOL_LIMIT_BYTES) ? `Attachment is ${file2.bytes} bytes; per-file inline limit is ${options.inlineLimitBytes ?? MAILBOX_PROTOCOL_LIMIT_BYTES} bytes: ${file2.input}` : `Attachment could not fit within the configured message limit: ${file2.input}`;
2049
2084
  if (!fits(rendered(), resultBindings))
2050
2085
  fail(
2051
2086
  "invalid_request",
@@ -2086,7 +2121,7 @@ ${text}`]).join("\n\n");
2086
2121
  if (options.requireInline)
2087
2122
  fail(
2088
2123
  "invalid_request",
2089
- `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
2124
+ `Attachment changed between validation and reading: ${file2.input}`,
2090
2125
  operation
2091
2126
  );
2092
2127
  continue;
@@ -2109,12 +2144,9 @@ ${text}`
2109
2144
  );
2110
2145
  if (cannotInline && !verified) {
2111
2146
  if (options.requireInline)
2112
- fail(
2113
- "invalid_request",
2114
- `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
2115
- operation,
2116
- { details: { capacity: true } }
2117
- );
2147
+ fail("invalid_request", capacityMessage(file2), operation, {
2148
+ details: { capacity: true }
2149
+ });
2118
2150
  continue;
2119
2151
  }
2120
2152
  bytes = Buffer.allocUnsafe(current.size);
@@ -2149,12 +2181,9 @@ ${text}`
2149
2181
  );
2150
2182
  if (cannotInline) {
2151
2183
  if (options.requireInline)
2152
- fail(
2153
- "invalid_request",
2154
- `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
2155
- operation,
2156
- { details: { capacity: true } }
2157
- );
2184
+ fail("invalid_request", capacityMessage(file2), operation, {
2185
+ details: { capacity: true }
2186
+ });
2158
2187
  continue;
2159
2188
  }
2160
2189
  } catch (error2) {
@@ -2200,11 +2229,12 @@ ${text}`
2200
2229
  transportSections[index] = renderMessageFile(file2, markers[index]);
2201
2230
  attachmentTexts[index] = content;
2202
2231
  if (!fits(rendered(), resultBindings)) {
2232
+ const actualBytes = options.fits ? void 0 : options.serializedBytes ? options.serializedBytes(rendered(), resultBindings) : Buffer.byteLength(rendered(), "utf8");
2203
2233
  sections[index] = prior;
2204
2234
  if (options.requireInline)
2205
2235
  fail(
2206
2236
  "invalid_request",
2207
- `Attachment could not be fully embedded within the configured limits: ${file2.input}`,
2237
+ actualBytes === void 0 ? `Attachment could not fit within the configured message limit: ${file2.input}` : `Mailbox payload is ${actualBytes} bytes; configured limit is ${options.mailboxLimitBytes ?? MAILBOX_PROTOCOL_LIMIT_BYTES} bytes while embedding ${file2.input}`,
2208
2238
  operation,
2209
2239
  { details: { capacity: true } }
2210
2240
  );
@@ -2742,6 +2772,9 @@ function withoutDelegationCapability(definition) {
2742
2772
  frontmatter
2743
2773
  };
2744
2774
  }
2775
+ function agentScopeAtDepth(depth, maxAgentDepth) {
2776
+ return depth >= maxAgentDepth ? "leaf" : "delegating";
2777
+ }
2745
2778
  function projectAgentDefinition(agent, scope) {
2746
2779
  return scope === "leaf" ? withoutDelegationCapability(agent) : agent;
2747
2780
  }
@@ -2932,7 +2965,13 @@ function configuredModel(frontmatter) {
2932
2965
  function resolveChildModel(input) {
2933
2966
  if (input.configured !== void 0 && input.configured.trim() !== "")
2934
2967
  return { kind: "use", model: input.configured, extensionDiscovery: false };
2935
- if (input.inherited === void 0) return { kind: "none" };
2968
+ if (input.inherited === void 0) {
2969
+ const saved = input.saved;
2970
+ return {
2971
+ kind: "none",
2972
+ extensionDiscovery: input.savedUnresolved === true || !!saved && (input.isForeignProvider(saved.provider) || input.isKnownModel !== void 0 && !input.isKnownModel(saved.provider, saved.modelId))
2973
+ };
2974
+ }
2936
2975
  return {
2937
2976
  kind: "use",
2938
2977
  model: input.inherited.token,
@@ -3034,7 +3073,7 @@ function agentLaunchArgs(agent, options) {
3034
3073
  if (approveProject === true) args.push("--approve");
3035
3074
  else if (approveProject === false) args.push("--no-approve");
3036
3075
  const requestedModel = configuredModel(frontmatter) ?? inheritedModel;
3037
- const decision = options.modelDecision ?? (requestedModel === void 0 ? { kind: "none" } : {
3076
+ const decision = options.modelDecision ?? (requestedModel === void 0 ? { kind: "none", extensionDiscovery: false } : {
3038
3077
  kind: "use",
3039
3078
  model: requestedModel,
3040
3079
  extensionDiscovery: false
@@ -3099,8 +3138,7 @@ function agentLaunchArgs(agent, options) {
3099
3138
  const noSkills = frontmatter.noSkills ?? frontmatter.inheritSkills !== true;
3100
3139
  if (noSkills) args.push("--no-skills");
3101
3140
  for (const skill of frontmatter.skills ?? []) args.push("--skill", skill);
3102
- const extensionDiscovery = decision.kind === "use" && decision.extensionDiscovery;
3103
- if (frontmatter.noExtensions && !extensionDiscovery)
3141
+ if (frontmatter.noExtensions && !decision.extensionDiscovery)
3104
3142
  args.push("--no-extensions");
3105
3143
  for (const extension of frontmatter.extensions ?? [])
3106
3144
  args.push("--extension", extension);
@@ -7730,10 +7768,14 @@ function validLeadState(value2) {
7730
7768
  const r = value2;
7731
7769
  const keys = ["version", "instanceId", "piSessionId", "updatedAt"];
7732
7770
  if (Object.keys(r).some(
7733
- (k) => !keys.includes(k) && k !== "role" && k !== "build"
7771
+ (k) => !keys.includes(k) && k !== "role" && k !== "build" && k !== "startupAttestation"
7734
7772
  ) || keys.some((k) => !Object.hasOwn(r, k)))
7735
7773
  return false;
7736
- return r.version === 1 && (r.build === void 0 || isRuntimeBuild(r.build)) && (r.role === void 0 || r.role === "lead" || r.role === "manager") && UUID3.test(String(r.instanceId)) && validSession(r.piSessionId) && Number.isInteger(r.updatedAt) && r.updatedAt >= 0;
7774
+ const attestation = r.startupAttestation;
7775
+ const validAttestation = attestation === void 0 || !!attestation && typeof attestation === "object" && !Array.isArray(attestation) && Object.keys(attestation).length === 4 && attestation.kind === "model_restore" && attestation.assignmentId === r.piSessionId && attestation.generation === r.instanceId && ["verified", "definition_override", "no_saved_model"].includes(
7776
+ attestation.result
7777
+ );
7778
+ return r.version === 1 && (r.build === void 0 || isRuntimeBuild(r.build)) && (r.role === void 0 || r.role === "lead" || r.role === "manager") && UUID3.test(String(r.instanceId)) && validSession(r.piSessionId) && Number.isInteger(r.updatedAt) && r.updatedAt >= 0 && validAttestation;
7737
7779
  }
7738
7780
  function readLeadCoordinationState(runtime, piSessionId) {
7739
7781
  const path = leadCoordinationStatePath(runtime, piSessionId);
@@ -9695,17 +9737,19 @@ function formatToolModelResult(action, v) {
9695
9737
  ];
9696
9738
  };
9697
9739
  const rendered = /* @__PURE__ */ new Set();
9698
- const renderedAgents = roots.flatMap((root2) => {
9699
- const directChildren = children(root2);
9700
- rendered.add(root2);
9701
- directChildren.forEach((child) => rendered.add(child));
9740
+ const renderTree = (agent, depth) => {
9741
+ rendered.add(agent);
9742
+ const nested = children(agent).filter((child) => !rendered.has(child));
9702
9743
  return [
9703
- ...agentLines(root2),
9704
- ...directChildren.length ? [" agents:"] : [],
9705
- ...directChildren.flatMap((child) => agentLines(child, " ")),
9706
- ""
9744
+ ...agentLines(agent, " ".repeat(depth)),
9745
+ ...nested.length ? [`${" ".repeat(depth)} agents:`] : [],
9746
+ ...nested.flatMap((child) => renderTree(child, depth + 1))
9707
9747
  ];
9708
- });
9748
+ };
9749
+ const renderedAgents = roots.flatMap((root2) => [
9750
+ ...renderTree(root2, 0),
9751
+ ""
9752
+ ]);
9709
9753
  const fallbackAgents = agents.filter((agent) => !rendered.has(agent));
9710
9754
  return [
9711
9755
  `Agents: ${agents.length}`,
@@ -12742,6 +12786,14 @@ function validByteLimit(value2) {
12742
12786
  function validStatusWidgetMaxRows(value2) {
12743
12787
  return typeof value2 === "number" && Number.isInteger(value2) && value2 >= 1 && value2 <= 100;
12744
12788
  }
12789
+ function validMaxAgentDepth(value2) {
12790
+ return typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 1;
12791
+ }
12792
+ function invalidMaxAgentDepth(value2) {
12793
+ return new Error(
12794
+ `Invalid Pi Herdsman config field maxAgentDepth: expected a positive integer (1 = Agents never delegate, 2 = one delegating level), got ${JSON.stringify(value2) ?? String(value2)}. Edit ${herdsmanConfigPath()} or remove the field to use the default of ${DEFAULT_MAX_AGENT_DEPTH}.`
12795
+ );
12796
+ }
12745
12797
  function validRepoIdentity(value2) {
12746
12798
  return typeof value2 === "string" && !!value2.trim() && value2 === value2.trim() && value2.length <= 4096 && value2 !== "__proto__" && value2 !== "constructor" && value2 !== "prototype" && !containsControlCharacter(value2);
12747
12799
  }
@@ -12778,6 +12830,11 @@ function parseRawConfig(content) {
12778
12830
  throw new Error("Invalid Pi Herdsman config field statusWidgetMaxRows");
12779
12831
  result.statusWidgetMaxRows = record.statusWidgetMaxRows;
12780
12832
  }
12833
+ if ("maxAgentDepth" in record) {
12834
+ if (!validMaxAgentDepth(record.maxAgentDepth))
12835
+ throw invalidMaxAgentDepth(record.maxAgentDepth);
12836
+ result.maxAgentDepth = record.maxAgentDepth;
12837
+ }
12781
12838
  if ("spawnPlacement" in record) {
12782
12839
  if (!isSpawnPlacement(record.spawnPlacement))
12783
12840
  throw new Error("Invalid Pi Herdsman config field spawnPlacement");
@@ -13083,6 +13140,8 @@ function updateConfig(key, value2) {
13083
13140
  if (value2 !== void 0) {
13084
13141
  if (key === "statusWidgetMaxRows" && !validStatusWidgetMaxRows(value2))
13085
13142
  throw new Error("Invalid Pi Herdsman config field statusWidgetMaxRows");
13143
+ if (key === "maxAgentDepth" && !validMaxAgentDepth(value2))
13144
+ throw invalidMaxAgentDepth(value2);
13086
13145
  if (key === "spawnPlacement" && !isSpawnPlacement(value2))
13087
13146
  throw new Error("Invalid Pi Herdsman config field spawnPlacement");
13088
13147
  if (key === "defaultLeadExecution" && !isLeadExecutionMode(value2))
@@ -13107,7 +13166,7 @@ function updateConfig(key, value2) {
13107
13166
  throw new Error(
13108
13167
  "Invalid Pi Herdsman config field worktreeRemovalPreapprovedRepos"
13109
13168
  );
13110
- if (key !== "spawnPlacement" && key !== "statusWidgetMaxRows" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerGitBootstrapWithoutConfirmation" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
13169
+ if (key !== "spawnPlacement" && key !== "statusWidgetMaxRows" && key !== "maxAgentDepth" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerGitBootstrapWithoutConfirmation" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
13111
13170
  throw new Error(`Invalid Pi Herdsman config field ${key}`);
13112
13171
  current[key] = value2;
13113
13172
  } else delete current[key];
@@ -13125,7 +13184,7 @@ function updateConfig(key, value2) {
13125
13184
  release();
13126
13185
  }
13127
13186
  }
13128
- var import_proper_lockfile, DEFAULT_BYTE_LIMIT, MIN_BYTE_LIMIT, MAX_BYTE_LIMIT, DEFAULT_STATUS_WIDGET_MAX_ROWS, DEFAULT_CONFIG, CONFIG_KEYS;
13187
+ var import_proper_lockfile, DEFAULT_BYTE_LIMIT, MIN_BYTE_LIMIT, MAX_BYTE_LIMIT, DEFAULT_STATUS_WIDGET_MAX_ROWS, DEFAULT_MAX_AGENT_DEPTH, DEFAULT_CONFIG, CONFIG_KEYS;
13129
13188
  var init_config = __esm({
13130
13189
  "extension/config.ts"() {
13131
13190
  "use strict";
@@ -13137,8 +13196,10 @@ var init_config = __esm({
13137
13196
  MIN_BYTE_LIMIT = 1024;
13138
13197
  MAX_BYTE_LIMIT = 1024 * 1024;
13139
13198
  DEFAULT_STATUS_WIDGET_MAX_ROWS = 8;
13199
+ DEFAULT_MAX_AGENT_DEPTH = 2;
13140
13200
  DEFAULT_CONFIG = {
13141
13201
  statusWidgetMaxRows: DEFAULT_STATUS_WIDGET_MAX_ROWS,
13202
+ maxAgentDepth: DEFAULT_MAX_AGENT_DEPTH,
13142
13203
  spawnPlacement: "subtree",
13143
13204
  defaultLeadExecution: "flexible",
13144
13205
  contextRetirement: true,
@@ -13152,6 +13213,7 @@ var init_config = __esm({
13152
13213
  };
13153
13214
  CONFIG_KEYS = /* @__PURE__ */ new Set([
13154
13215
  "statusWidgetMaxRows",
13216
+ "maxAgentDepth",
13155
13217
  "spawnPlacement",
13156
13218
  "defaultLeadExecution",
13157
13219
  "contextRetirement",
@@ -13258,6 +13320,7 @@ function createAgentStatusRuntime() {
13258
13320
  }
13259
13321
  };
13260
13322
  let statusTimer;
13323
+ let stopNewAgentWatch;
13261
13324
  let statusContext;
13262
13325
  let statusGeneration = 0;
13263
13326
  let statusWidgetGeneration = 0;
@@ -13329,6 +13392,7 @@ function createAgentStatusRuntime() {
13329
13392
  lastValidStatus = snapshot;
13330
13393
  reconcilePendingStarts(snapshot);
13331
13394
  publishStatus(snapshot);
13395
+ syncNewAgentWatch(ctx, generation);
13332
13396
  } catch {
13333
13397
  if (generation === statusGeneration && ctx === statusContext)
13334
13398
  publishStatus(
@@ -13357,6 +13421,34 @@ function createAgentStatusRuntime() {
13357
13421
  const clearTimer = () => {
13358
13422
  if (statusTimer) clearInterval(statusTimer);
13359
13423
  statusTimer = void 0;
13424
+ stopNewAgentWatch?.();
13425
+ stopNewAgentWatch = void 0;
13426
+ };
13427
+ const syncNewAgentWatch = (ctx, generation) => {
13428
+ if (!presentedStatus.agents.length || !statusTimer) {
13429
+ stopNewAgentWatch?.();
13430
+ stopNewAgentWatch = void 0;
13431
+ return;
13432
+ }
13433
+ if (stopNewAgentWatch) return;
13434
+ let lastError;
13435
+ stopNewAgentWatch = observeNewAgentStates(
13436
+ () => {
13437
+ lastError = void 0;
13438
+ void refresh(ctx, generation);
13439
+ },
13440
+ (error2) => {
13441
+ const message = String(error2).replace(/^Error: /u, "");
13442
+ if (message === lastError) return;
13443
+ lastError = message;
13444
+ if (generation === statusGeneration && ctx === statusContext)
13445
+ ctx.ui.notify(
13446
+ `Agent status cannot watch for new agents (${message}); the view refreshes every 10 seconds instead`,
13447
+ "warning"
13448
+ );
13449
+ }
13450
+ );
13451
+ void refresh(ctx, generation);
13360
13452
  };
13361
13453
  const removeWidget = () => {
13362
13454
  if (statusWidget) {
@@ -13389,6 +13481,7 @@ function createAgentStatusRuntime() {
13389
13481
  requestActive = true;
13390
13482
  statusTimer = setInterval(() => void refresh(ctx, generation), 1e4);
13391
13483
  statusTimer.unref?.();
13484
+ syncNewAgentWatch(ctx, generation);
13392
13485
  statusPrimed = false;
13393
13486
  publishStatus(presentedStatus);
13394
13487
  if (!primed) void refresh(ctx, generation);
@@ -13442,6 +13535,7 @@ function createAgentStatusRuntime() {
13442
13535
  requestActive = true;
13443
13536
  statusTimer = setInterval(() => void refresh(ctx, generation), 1e4);
13444
13537
  statusTimer.unref?.();
13538
+ syncNewAgentWatch(ctx, generation);
13445
13539
  statusPrimed = false;
13446
13540
  if (!primed) void refresh(ctx, generation);
13447
13541
  },
@@ -13704,6 +13798,53 @@ function agentToolName(action) {
13704
13798
  return action;
13705
13799
  }
13706
13800
  }
13801
+ function resolveSavedSessionModelSelection(manager, catalogModel) {
13802
+ const contextModel = manager.buildSessionContext?.().model ?? void 0;
13803
+ if (typeof manager.getBranch !== "function")
13804
+ return contextModel ? { kind: "resolved", model: contextModel } : { kind: "none" };
13805
+ const branch = manager.getBranch();
13806
+ let change;
13807
+ let changeIndex = -1;
13808
+ let response;
13809
+ let responseIndex = -1;
13810
+ for (let index = 0; index < branch.length; index++) {
13811
+ const entry = branch[index];
13812
+ if (entry.type === "model_change") {
13813
+ change = entry;
13814
+ changeIndex = index;
13815
+ } else if (entry.type === "message" && entry.message?.role === "assistant" && entry.message?.stopReason !== "error" && typeof entry.message?.provider === "string" && typeof entry.message?.model === "string") {
13816
+ response = {
13817
+ provider: entry.message.provider,
13818
+ modelId: entry.message.model
13819
+ };
13820
+ responseIndex = index;
13821
+ }
13822
+ }
13823
+ if (!change && !response)
13824
+ return contextModel ? { kind: "resolved", model: contextModel } : { kind: "none" };
13825
+ if (change && changeIndex > responseIndex)
13826
+ return {
13827
+ kind: "resolved",
13828
+ model: { provider: change.provider, modelId: change.modelId }
13829
+ };
13830
+ if (change && response && (change.provider !== response.provider || change.modelId !== response.modelId)) {
13831
+ const catalog = catalogModel(change.provider, change.modelId);
13832
+ if (catalog?.api === "pi-virtual")
13833
+ return {
13834
+ kind: "resolved",
13835
+ model: { provider: change.provider, modelId: change.modelId }
13836
+ };
13837
+ if (!catalog)
13838
+ return {
13839
+ kind: "unresolved",
13840
+ candidates: [
13841
+ { provider: change.provider, modelId: change.modelId },
13842
+ response
13843
+ ]
13844
+ };
13845
+ }
13846
+ return response ? { kind: "resolved", model: response } : change ? { kind: "resolved", model: change } : { kind: "none" };
13847
+ }
13707
13848
  function requiredEvidenceEntriesForRequest(entries, requestId) {
13708
13849
  return entries.filter(
13709
13850
  (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence" && entry.data?.requestId === requestId
@@ -14930,6 +15071,13 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
14930
15071
  definition: child.definition,
14931
15072
  label: child.label,
14932
15073
  cwd: manager.getCwd(),
15074
+ ...(() => {
15075
+ const selection = resolveSavedSessionModelSelection(
15076
+ manager,
15077
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
15078
+ );
15079
+ return selection.kind === "resolved" ? { savedModel: selection.model } : selection.kind === "unresolved" ? { savedModelUnresolved: true } : {};
15080
+ })(),
14933
15081
  ...evidence ? { evidence } : {}
14934
15082
  };
14935
15083
  }
@@ -14957,13 +15105,49 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
14957
15105
  );
14958
15106
  return resolved;
14959
15107
  }
15108
+ function childAgentDepth(scope) {
15109
+ return scope.kind === "managed-agent" ? scope.depth + 1 : 1;
15110
+ }
15111
+ function durableAgentDepth(states, agent) {
15112
+ const seen = /* @__PURE__ */ new Set([agent.piSessionId]);
15113
+ let depth = 1;
15114
+ let current = agent;
15115
+ for (; ; ) {
15116
+ const owners = states.filter(
15117
+ (candidate) => candidate.workspaceId === agent.workspaceId && candidate.piSessionId === current.ownerSessionId
15118
+ );
15119
+ if (owners.length > 1)
15120
+ throw new Error(
15121
+ `owner session ${current.ownerSessionId} has ${owners.length} ownership records, so the chain is ambiguous`
15122
+ );
15123
+ const owner = owners[0];
15124
+ if (!owner) {
15125
+ if (!agent.rootSessionId?.trim())
15126
+ throw new Error(
15127
+ "its record has no verified root session, so the ownership chain cannot be checked"
15128
+ );
15129
+ if (current.ownerSessionId !== agent.rootSessionId)
15130
+ throw new Error(
15131
+ `the ownership chain does not reach its verified root: owner session ${current.ownerSessionId} has no ownership record and is not root session ${agent.rootSessionId}`
15132
+ );
15133
+ return depth;
15134
+ }
15135
+ if (seen.has(owner.piSessionId))
15136
+ throw new Error("Managed Agent ownership records form a cycle");
15137
+ seen.add(owner.piSessionId);
15138
+ depth++;
15139
+ current = owner;
15140
+ }
15141
+ }
14960
15142
  function sameRootDelegationGeneration(a, b) {
14961
15143
  return !!b && a.sessionId === b.sessionId && a.roleGeneration === b.roleGeneration && a.role === b.role && a.authority === b.authority && a.profile === b.profile;
14962
15144
  }
14963
15145
  function permitsRootDelegation(policy, definition) {
14964
15146
  return policy === "all" || policy.has(definition);
14965
15147
  }
14966
- function visibleAgentCapabilities(definitions, scope, rootPolicy = "all") {
15148
+ function visibleAgentCapabilities(definitions, scope, rootPolicy = "all", maxAgentDepth = readConfig().maxAgentDepth) {
15149
+ if (scope.kind === "managed-agent" && scope.depth >= maxAgentDepth) return [];
15150
+ const childScope = agentScopeAtDepth(childAgentDepth(scope), maxAgentDepth);
14967
15151
  const availableNames = new Set(
14968
15152
  definitions.filter(agentDefinitionEnabled).map(({ name }) => name)
14969
15153
  );
@@ -14980,14 +15164,14 @@ function visibleAgentCapabilities(definitions, scope, rootPolicy = "all") {
14980
15164
  return available.map((definition) => {
14981
15165
  const metadata = agentDefinitionMetadata(
14982
15166
  definition,
14983
- scope.kind === "managed-agent" ? "leaf" : "delegating"
15167
+ childScope
14984
15168
  );
14985
15169
  return {
14986
15170
  name: definition.name,
14987
15171
  ...typeof metadata.description === "string" ? { description: metadata.description } : {},
14988
15172
  tools: formatTools(metadata),
14989
15173
  skills: formatSkills(metadata),
14990
- ...scope.kind === "root" && agentDefinitionDelegationEnabled(definition) && definition.frontmatter.agents?.length ? { agents: [...definition.frontmatter.agents] } : {}
15174
+ ...childScope === "delegating" && agentDefinitionDelegationEnabled(definition) && definition.frontmatter.agents?.length ? { agents: [...definition.frontmatter.agents] } : {}
14991
15175
  };
14992
15176
  });
14993
15177
  }
@@ -15386,14 +15570,9 @@ function listedAgentRecord(view, snapshot, ownerSessionId, scope, unresolvedMail
15386
15570
  let closeAvailable = false;
15387
15571
  if (direct && (presence.kind === "live" || presence.kind === "lost")) {
15388
15572
  try {
15389
- if (scope?.kind === "root") {
15390
- if (!unresolvedMailboxState) {
15391
- const plan = dependencies.cascadePlan(view, state);
15392
- dependencies.assertCascadeSafe([plan.parent, ...plan.descendants]);
15393
- closeAvailable = true;
15394
- }
15395
- } else {
15396
- dependencies.assertCascadeSafe([snapshot]);
15573
+ if (!unresolvedMailboxState) {
15574
+ const plan = dependencies.cascadePlan(view, state);
15575
+ dependencies.assertCascadeSafe([plan.parent, ...plan.descendants]);
15397
15576
  closeAvailable = true;
15398
15577
  }
15399
15578
  } catch {
@@ -17475,7 +17654,10 @@ function createAgentController(pi, options) {
17475
17654
  ].filter((id) => !!id);
17476
17655
  if (requestIds.some((id) => id !== result.requestId))
17477
17656
  throw new Error("agent has newer mailbox work");
17478
- if (managedAgent)
17657
+ const ownsDescendants = listAgentStates().some(
17658
+ ({ state: candidate }) => candidate.workspaceId === state.workspaceId && candidate.ownerSessionId === state.piSessionId
17659
+ );
17660
+ if (managedAgent && !ownsDescendants && listAgentStateIssues().length === 0)
17479
17661
  await finalizeDeliveredRoot(context, state, result.requestId, signal);
17480
17662
  else await closeCascade(context, state, signal, result.requestId);
17481
17663
  return true;
@@ -17790,6 +17972,36 @@ function createAgentController(pi, options) {
17790
17972
  "Only a Herdr controller may start agent assignments",
17791
17973
  p.action
17792
17974
  );
17975
+ const maxAgentDepth = readConfig().maxAgentDepth;
17976
+ if (scope.kind === "managed-agent") {
17977
+ let durableDepth;
17978
+ try {
17979
+ const own = options.managedAgentState?.(ctx);
17980
+ if (!own) throw new Error("its own ownership record is unavailable");
17981
+ durableDepth = durableAgentDepth(
17982
+ listAgentStates().map(({ state }) => state),
17983
+ own
17984
+ );
17985
+ } catch (error2) {
17986
+ fail(
17987
+ "invalid_request",
17988
+ `This Agent's depth could not be verified against the durable ownership records (${String(error2 instanceof Error ? error2.message : error2).replace(/^Error: /, "")}), so it cannot start another Agent; restart it from its owner or do the work directly`,
17989
+ p.action
17990
+ );
17991
+ }
17992
+ if (durableDepth !== scope.depth)
17993
+ fail(
17994
+ "invalid_request",
17995
+ `This Agent's PI_HERDSMAN_DEPTH is ${scope.depth} but the durable ownership records place it at depth ${durableDepth}; the records are authoritative, so it cannot start another Agent. Restart it from its owner instead of editing its environment`,
17996
+ p.action
17997
+ );
17998
+ if (childAgentDepth(scope) > maxAgentDepth)
17999
+ fail(
18000
+ "invalid_request",
18001
+ `This Agent is at depth ${scope.depth} and maxAgentDepth is ${maxAgentDepth}, so it cannot start another Agent; do the work directly or ask the owner to raise maxAgentDepth in the Herdsman config`,
18002
+ p.action
18003
+ );
18004
+ }
17793
18005
  const resumed = p.action === "continue" ? resolveAssignmentSession(ctx, p.session, {
17794
18006
  isContextRetired: options.isContextRetired,
17795
18007
  contextRetirementForSession: (context, manager) => sameCwd(context.cwd, manager.getCwd()) ? readEffectiveConfig(context).contextRetirement : void 0
@@ -18426,9 +18638,10 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18426
18638
  p.action
18427
18639
  );
18428
18640
  const preparedDefinition = preparedBody === definition.body ? definition : { ...definition, body: preparedBody };
18641
+ const childDepth = childAgentDepth(scope);
18429
18642
  const effectiveDefinition = projectAgentDefinition(
18430
18643
  preparedDefinition,
18431
- scope.kind === "managed-agent" ? "leaf" : "delegating"
18644
+ agentScopeAtDepth(childDepth, maxAgentDepth)
18432
18645
  );
18433
18646
  const delegationEnabled = agentDefinitionDelegationEnabled(effectiveDefinition);
18434
18647
  const runId = assignment.runId;
@@ -18642,6 +18855,7 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18642
18855
  `PI_HERDSMAN_LABEL=${label}`,
18643
18856
  `PI_HERDSMAN_WORKSPACE_ID=${workspaceId}`,
18644
18857
  `PI_HERDSMAN_AGENT_DEFINITION=${agentDefinition}`,
18858
+ `PI_HERDSMAN_DEPTH=${childDepth}`,
18645
18859
  `PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS=${JSON.stringify(
18646
18860
  delegationEnabled ? effectiveDefinition.frontmatter.agents : []
18647
18861
  )}`,
@@ -18654,8 +18868,13 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18654
18868
  const childModel = resolveChildModel({
18655
18869
  configured: configuredModel(effectiveDefinition.frontmatter),
18656
18870
  inherited: !resumed && ctx.model ? { provider: ctx.model.provider, token: modelToken(ctx.model) } : void 0,
18657
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId)
18871
+ saved: resumed?.savedModel,
18872
+ savedUnresolved: resumed?.savedModelUnresolved,
18873
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
18874
+ isKnownModel: (provider, id) => ctx.modelRegistry.find(provider, id) !== void 0
18658
18875
  });
18876
+ if ((resumed?.savedModel || resumed?.savedModelUnresolved) && !configuredModel(effectiveDefinition.frontmatter))
18877
+ env.push("PI_HERDSMAN_RESTORE_MODEL=saved-session");
18659
18878
  const launchArgs = agentLaunchArgs(effectiveDefinition, {
18660
18879
  ...effectiveDefinition.body ? { bodyPromptPath: promptPaths[0] } : {},
18661
18880
  sharedPromptPath: promptPaths[effectiveDefinition.body ? 1 : 0],
@@ -18666,6 +18885,12 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18666
18885
  modelDecision: childModel
18667
18886
  });
18668
18887
  assertRootDelegationAllowed();
18888
+ if (readConfig().maxAgentDepth !== maxAgentDepth)
18889
+ fail(
18890
+ "invalid_request",
18891
+ `maxAgentDepth changed from ${maxAgentDepth} to ${readConfig().maxAgentDepth} while this Agent was being prepared, so it was not started; retry the delegation under the new limit`,
18892
+ p.action
18893
+ );
18669
18894
  started = await startHerdrAgent(pi, ctx, {
18670
18895
  label,
18671
18896
  runId,
@@ -20644,12 +20869,13 @@ Do not silently broaden scope or make an unapproved scope, architecture,
20644
20869
  security, protocol, repository-boundary, product, or operational decision.
20645
20870
 
20646
20871
  Use ask_owner only when a decision from your exact direct owner is genuinely
20647
- required to continue correctly. ask_owner may include files for supporting
20648
- evidence; complete strict UTF-8 text may be embedded and other files remain
20649
- canonical local references. ask_owner must be the only tool call and final
20650
- tool call of that turn. Keep at most one question outstanding. Stop while
20651
- blocked, wait for the exact owner reply, do not guess the answer, and do not
20652
- complete the assignment while blocked. The reply resumes the same assignment.
20872
+ required to continue correctly. Explicit attachments must be supported UTF-8
20873
+ text fully embedded within the applicable per-file and complete-message
20874
+ budgets. Call ask_owner alone as the final tool call of the turn. Wait for the
20875
+ direct owner's reply only after the tool confirms the question was sent; if
20876
+ rejected, address the error or report a non-empty blocker. Keep at most one
20877
+ question outstanding. Do not guess the answer. The reply resumes the same
20878
+ assignment.
20653
20879
 
20654
20880
  Treat inactivity as advisory, not proof of a hang. Preserve exact identity and
20655
20881
  cleanup evidence on failure. Do not blindly retry destructive cleanup or
@@ -20693,7 +20919,8 @@ Your herd is your internal team: you and your recursively owned Agents.
20693
20919
  Any review conducted within the herd is internal feedback, not user or supervisor
20694
20920
  review or approval.`;
20695
20921
  DELEGATING_AGENT_SCOPE_DESCRIPTION = `Own the assigned objective and your direct permitted agents. While direct assignments are unresolved, your execution scope is limited to the non-delegated remainder. Agent-started
20696
- agents are leaves. Delegate bounded execution work when an Agent can reasonably
20922
+ agents delegate further only within the configured maximum nesting depth and
20923
+ are leaves beyond it. Delegate bounded execution work when an Agent can reasonably
20697
20924
  own it and delegation is useful. Keep work local when it is trivial,
20698
20925
  inseparable, otherwise unsuitable for an Agent, or delegation would add more
20699
20926
  coordination than value. Reuse adequate supplied evidence rather than
@@ -20722,6 +20949,7 @@ __export(managed_agent_runtime_exports, {
20722
20949
  AGENT_REQUIRED_EVIDENCE_ENTRY: () => AGENT_REQUIRED_EVIDENCE_ENTRY,
20723
20950
  READ_EVIDENCE_MAX_BYTES: () => READ_EVIDENCE_MAX_BYTES,
20724
20951
  READ_EVIDENCE_MAX_LINES: () => READ_EVIDENCE_MAX_LINES,
20952
+ agentDepthFromEnv: () => agentDepthFromEnv,
20725
20953
  allowedAgentDefinitionsFromEnv: () => allowedAgentDefinitionsFromEnv,
20726
20954
  authorizedScopedResult: () => authorizedScopedResult,
20727
20955
  createManagedAgentAskOwnerHandler: () => createManagedAgentAskOwnerHandler,
@@ -21707,7 +21935,7 @@ function registerManagedAgentAskOwnerTool(pi, execute) {
21707
21935
  exposure: "model-only",
21708
21936
  promptSnippet: "Ask this managed agent's direct owner for a required decision",
21709
21937
  promptGuidelines: [FILE_HANDOFF_GUIDANCE],
21710
- description: "Ask your direct owner for a decision that is required to continue. Call this alone as the final tool call of the turn, then stop and wait for the reply. Only one question may be outstanding.",
21938
+ description: "Ask your direct owner for a decision that is required to continue. Call this alone as the final tool call of the turn. Wait for the reply only after the tool confirms the question was sent; if rejected, address the error or report a non-empty blocker. Only one question may be outstanding.",
21711
21939
  executionMode: "sequential",
21712
21940
  parameters: Type2.Object(
21713
21941
  {
@@ -22318,7 +22546,7 @@ function registerManagedAgentSettlementHandlers(pi, execution, options) {
22318
22546
  } : {
22319
22547
  error: {
22320
22548
  code: aborted ? "aborted" : handoffSelectionError || outcome === "error" ? "execution_error" : "empty_result",
22321
- message: aborted ? "Agent execution was cancelled" : handoffSelectionError ? "Selected handoff evidence could not be verified" : outcome === "error" ? "Agent model execution failed" : "Agent produced no assistant text"
22549
+ 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"
22322
22550
  }
22323
22551
  },
22324
22552
  contextUsage: ctx.getContextUsage(),
@@ -22478,6 +22706,7 @@ function registerManagedAgentRuntime(pi, options) {
22478
22706
  event.input.timeout = options.shellTimeoutSeconds;
22479
22707
  });
22480
22708
  const allowedAgentDefinitions = allowedAgentDefinitionsFromEnv();
22709
+ const agentDepth = agentDepthFromEnv();
22481
22710
  const delegationEnabled = allowedAgentDefinitions.length > 0;
22482
22711
  let startupDefinitionRoster;
22483
22712
  const controller = delegationEnabled ? createAgentController(pi, {
@@ -22490,16 +22719,19 @@ function registerManagedAgentRuntime(pi, options) {
22490
22719
  );
22491
22720
  return rootSessionId;
22492
22721
  },
22722
+ managedAgentState: (ctx) => managedAgentControllerIdentity(ctx),
22493
22723
  scope: {
22494
22724
  kind: "managed-agent",
22495
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
22725
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
22726
+ depth: agentDepth
22496
22727
  },
22497
22728
  build: options.build
22498
22729
  }) : void 0;
22499
22730
  if (controller) {
22500
22731
  const scope = {
22501
22732
  kind: "managed-agent",
22502
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
22733
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
22734
+ depth: agentDepth
22503
22735
  };
22504
22736
  options.statusRuntime.configure({
22505
22737
  pendingStartEntries: () => controller.pendingStartEntries(),
@@ -22798,52 +23030,60 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
22798
23030
  };
22799
23031
  }
22800
23032
  );
22801
- registerManagedAgentAskOwnerTool(
22802
- pi,
22803
- createManagedAgentAskOwnerHandler({
22804
- state: () => execution.assignment,
22805
- setState: (state) => {
22806
- execution.assignment = state;
22807
- },
22808
- sameIdentity: sameManagedAgentIdentity,
22809
- eligible: requestState.eligibleToAsk,
22810
- rejectionReason: requestState.askRejectionReason,
22811
- isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "ask_owner"),
22812
- messageLimits: options.messageLimits,
22813
- prepare: async (ctx, question, files, state, askId, createdAt, limits) => prepareMessageInput(
22814
- question,
22815
- options.resolveMessageFiles(ctx, files, "ask_owner"),
22816
- state.cwd,
22817
- "ask_owner",
22818
- "Question",
22819
- {
22820
- inlineLimitBytes: limits.inline.bytes,
22821
- mailboxLimitBytes: limits.mailbox.bytes,
22822
- requireInline: true,
22823
- serializedBytes: (text, bindings) => askRecordBytes(state, askId, text, createdAt, bindings)
22824
- }
22825
- ),
22826
- checkMailboxSize: (bytes, limit) => {
22827
- if (bytes > limit)
22828
- fail(
22829
- "invalid_request",
22830
- `Mailbox payload is ${bytes} bytes; configured limit is ${limit} bytes`,
22831
- "ask_owner"
22832
- );
22833
- },
22834
- claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "ask_owner", {
22835
- label: state.agentLabel,
22836
- paneId: state.paneId
22837
- }),
22838
- readState: readAgentState,
22839
- writeState: writeAgentState,
22840
- writeAsk,
22841
- removeAsk,
22842
- latest: (value2) => {
22843
- execution.latest = value2;
23033
+ const executeAskOwner = createManagedAgentAskOwnerHandler({
23034
+ state: () => execution.assignment,
23035
+ setState: (state) => {
23036
+ execution.assignment = state;
23037
+ },
23038
+ sameIdentity: sameManagedAgentIdentity,
23039
+ eligible: requestState.eligibleToAsk,
23040
+ rejectionReason: requestState.askRejectionReason,
23041
+ isSoleToolCall: (ctx) => currentTurnIsSoleToolCall(ctx, "ask_owner"),
23042
+ messageLimits: options.messageLimits,
23043
+ prepare: async (ctx, question, files, state, askId, createdAt, limits) => prepareMessageInput(
23044
+ question,
23045
+ options.resolveMessageFiles(ctx, files, "ask_owner"),
23046
+ state.cwd,
23047
+ "ask_owner",
23048
+ "Question",
23049
+ {
23050
+ inlineLimitBytes: limits.inline.bytes,
23051
+ mailboxLimitBytes: limits.mailbox.bytes,
23052
+ requireInline: true,
23053
+ serializedBytes: (text, bindings) => askRecordBytes(state, askId, text, createdAt, bindings)
22844
23054
  }
22845
- })
22846
- );
23055
+ ),
23056
+ checkMailboxSize: (bytes, limit) => {
23057
+ if (bytes > limit)
23058
+ fail(
23059
+ "invalid_request",
23060
+ `Mailbox payload is ${bytes} bytes; configured limit is ${limit} bytes`,
23061
+ "ask_owner",
23062
+ { details: { capacity: true } }
23063
+ );
23064
+ },
23065
+ claimLock: (mailbox, state) => options.claimAssignmentLock(mailbox, "ask_owner", {
23066
+ label: state.agentLabel,
23067
+ paneId: state.paneId
23068
+ }),
23069
+ readState: readAgentState,
23070
+ writeState: writeAgentState,
23071
+ writeAsk,
23072
+ removeAsk,
23073
+ latest: (value2) => {
23074
+ execution.latest = value2;
23075
+ }
23076
+ });
23077
+ registerManagedAgentAskOwnerTool(pi, async (...args) => {
23078
+ const observation = execution.observation;
23079
+ try {
23080
+ return await executeAskOwner(...args);
23081
+ } catch (error2) {
23082
+ 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)
23083
+ observation.askOwnerCapacityError = error2.message.slice(0, 512);
23084
+ throw error2;
23085
+ }
23086
+ });
22847
23087
  const prepareDelegatingRoster = async (ctx) => {
22848
23088
  startupDefinitionRoster = void 0;
22849
23089
  if (!delegationEnabled) return;
@@ -22854,7 +23094,8 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
22854
23094
  await options.getAgentDefinitions(ctx),
22855
23095
  {
22856
23096
  kind: "managed-agent",
22857
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
23097
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
23098
+ depth: agentDepth
22858
23099
  }
22859
23100
  )
22860
23101
  };
@@ -23110,6 +23351,17 @@ function parseAllowedAgentDefinitions(raw) {
23110
23351
  );
23111
23352
  return value2;
23112
23353
  }
23354
+ function parseAgentDepth(raw) {
23355
+ if (raw === void 0) return 1;
23356
+ if (!/^[1-9][0-9]{0,8}$/.test(raw))
23357
+ throw new Error(
23358
+ "PI_HERDSMAN_DEPTH must be a positive integer; it is set by the launching Herdsman controller, so restart this Agent from its owner instead of editing the environment"
23359
+ );
23360
+ return Number(raw);
23361
+ }
23362
+ function agentDepthFromEnv() {
23363
+ return parseAgentDepth(process.env.PI_HERDSMAN_DEPTH);
23364
+ }
23113
23365
  function allowedAgentDefinitionsFromEnv() {
23114
23366
  return parseAllowedAgentDefinitions(
23115
23367
  process.env.PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS
@@ -23136,6 +23388,7 @@ function managedAgentEnvironmentError() {
23136
23388
  if (!e.HERDR_PANE_ID?.trim()) return "HERDR_PANE_ID missing";
23137
23389
  try {
23138
23390
  parseAllowedAgentDefinitions(e.PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS);
23391
+ parseAgentDepth(e.PI_HERDSMAN_DEPTH);
23139
23392
  } catch (error2) {
23140
23393
  return String(error2).replace(/^Error: /, "");
23141
23394
  }
@@ -23297,6 +23550,36 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
23297
23550
  options.captureOwnTools(options.getActiveTools());
23298
23551
  options.ensureAgentIdentity(ctx);
23299
23552
  verified = candidate;
23553
+ const restoreModel = process.env.PI_HERDSMAN_RESTORE_MODEL;
23554
+ if (restoreModel) {
23555
+ startupStage = "model_restore";
23556
+ if (restoreModel !== "saved-session")
23557
+ throw new Error(
23558
+ "Cannot continue Agent: saved model expectation is invalid"
23559
+ );
23560
+ const selection = resolveSavedSessionModelSelection(
23561
+ ctx.sessionManager,
23562
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
23563
+ );
23564
+ const actual = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
23565
+ if (selection.kind === "none")
23566
+ throw new Error(
23567
+ `Cannot continue Agent: saved model selection could not be recovered. Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
23568
+ );
23569
+ if (selection.kind === "unresolved")
23570
+ throw new Error(
23571
+ `Cannot continue Agent: saved model history is ambiguous (${selection.candidates.map((model2) => `${model2.provider}/${model2.modelId}`).join(" vs ")}). Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
23572
+ );
23573
+ const expected = selection.model;
23574
+ const available = ctx.modelRegistry.find(
23575
+ expected.provider,
23576
+ expected.modelId
23577
+ );
23578
+ if (!available || !actual || actual.provider !== expected.provider || actual.modelId !== expected.modelId)
23579
+ throw new Error(
23580
+ `Cannot continue Agent: saved model ${expected.provider}/${expected.modelId} was not restored${available ? "" : " (unavailable in the loaded model registry)"}. Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
23581
+ );
23582
+ }
23300
23583
  const mailbox = process.env.PI_HERDSMAN_MAILBOX;
23301
23584
  const existing = readAgentState(mailbox);
23302
23585
  if (existing && !options.sameIdentity(existing, candidate))
@@ -23504,7 +23787,7 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
23504
23787
  agentLabel: verified.agentLabel,
23505
23788
  paneId: verified.paneId,
23506
23789
  status: "failed",
23507
- error: "Managed Agent initialization failed",
23790
+ error: startupStage === "model_restore" ? String(error2).slice(0, 256) : "Managed Agent initialization failed",
23508
23791
  stage: startupStage
23509
23792
  });
23510
23793
  } finally {
@@ -23574,7 +23857,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
23574
23857
  // package.json
23575
23858
  var package_default = {
23576
23859
  name: "pi-herdsman",
23577
- version: "0.41.0",
23860
+ version: "0.42.1",
23578
23861
  type: "module",
23579
23862
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
23580
23863
  license: "Apache-2.0",
@@ -23856,6 +24139,11 @@ init_agent_definitions();
23856
24139
  import { randomUUID as randomUUID12 } from "node:crypto";
23857
24140
  import { realpathSync as realpathSync6, statSync as statSync7, unlinkSync as unlinkSync9 } from "node:fs";
23858
24141
  import { isAbsolute as isAbsolute6, resolve as resolve6 } from "node:path";
24142
+ function isFreshLeadStartupAttestation(state, sessionId, previousInstanceId, startedAt) {
24143
+ return !!state && state.piSessionId === sessionId && state.instanceId !== previousInstanceId && state.updatedAt >= startedAt && state.startupAttestation?.kind === "model_restore" && state.startupAttestation.assignmentId === sessionId && state.startupAttestation.generation === state.instanceId && ["verified", "definition_override", "no_saved_model"].includes(
24144
+ state.startupAttestation.result
24145
+ );
24146
+ }
23859
24147
  function hasManagerEvidenceSelectors(refs) {
23860
24148
  return refs.some(
23861
24149
  (ref) => ref.startsWith("result:") || ref.startsWith("evidence:")
@@ -26021,16 +26309,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26021
26309
  }
26022
26310
  resumeMessageQueued = true;
26023
26311
  };
26312
+ const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
26313
+ if (live.length === 1 && currentAssignment.piSessionFile)
26314
+ await bindLeadSessionFile(currentAssignment, live[0]);
26024
26315
  let savedSessionCwd;
26316
+ let savedModel;
26025
26317
  if (operation.action === "resume" && currentAssignment.piSessionFile) {
26318
+ let saved;
26026
26319
  try {
26027
- const saved = host.SessionManager.open(
26028
- currentAssignment.piSessionFile
26320
+ saved = host.SessionManager.open(currentAssignment.piSessionFile);
26321
+ } catch (error2) {
26322
+ throw new Error(
26323
+ `Saved Lead session restoration failed for ${currentAssignment.id}: recorded session history is unavailable or unreadable; existing work was preserved. ${error2 instanceof Error ? error2.message : String(error2)}`
26029
26324
  );
26030
- if (saved.getSessionId() === currentAssignment.id)
26031
- savedSessionCwd = saved.getCwd();
26032
- } catch {
26033
26325
  }
26326
+ if (saved.getSessionId() !== currentAssignment.id)
26327
+ throw new Error(
26328
+ `Saved Lead session restoration failed for ${currentAssignment.id}: recorded session history has a mismatched session ID; existing work was preserved.`
26329
+ );
26330
+ savedSessionCwd = saved.getCwd();
26331
+ savedModel = resolveSavedSessionModelSelection(
26332
+ saved,
26333
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
26334
+ );
26034
26335
  }
26035
26336
  const placement = operation.action === "resume" ? resolveAssignmentCheckout(
26036
26337
  currentAssignment,
@@ -26073,7 +26374,6 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26073
26374
  };
26074
26375
  if (branchWorktrees.length > 1)
26075
26376
  throw new Error(`Multiple Herdr worktrees match branch ${branch}`);
26076
- const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
26077
26377
  if (live.length > 1)
26078
26378
  throw new Error(`Assignment ${id} has ambiguous live Lead identity`);
26079
26379
  if (live.length === 1) {
@@ -26423,6 +26723,9 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26423
26723
  await assertUnoccupied(workspaceId);
26424
26724
  let lead;
26425
26725
  let startedLead = false;
26726
+ let previousLeadInstanceId;
26727
+ let leadStartupStartedAt;
26728
+ let freshRestorationAttestation = false;
26426
26729
  const verifyLeadCandidate = (candidate) => {
26427
26730
  const reported = sessionIdentity2(candidate?.agent_session);
26428
26731
  if (!reported) return false;
@@ -26449,6 +26752,15 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26449
26752
  throw new Error(
26450
26753
  "Existing session in new worktree has a conflicting role or identity"
26451
26754
  );
26755
+ if (startedLead) {
26756
+ freshRestorationAttestation = leadStartupStartedAt !== void 0 && isFreshLeadStartupAttestation(
26757
+ state,
26758
+ assignment.id,
26759
+ previousLeadInstanceId,
26760
+ leadStartupStartedAt
26761
+ );
26762
+ if (!freshRestorationAttestation) return false;
26763
+ }
26452
26764
  return state?.role === "lead" && state.piSessionId === assignment.id;
26453
26765
  };
26454
26766
  const currentInventory = await herdrSessionSnapshot2(pi, ctx, signal);
@@ -26525,7 +26837,10 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26525
26837
  provider: ctx.model.provider,
26526
26838
  token: `${ctx.model.provider}/${ctx.model.id}`
26527
26839
  } : void 0,
26528
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId)
26840
+ saved: operation.action === "resume" && savedModel?.kind === "resolved" ? savedModel.model : void 0,
26841
+ savedUnresolved: operation.action === "resume" && (savedModel === void 0 || savedModel.kind === "unresolved"),
26842
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
26843
+ isKnownModel: (provider, modelId) => ctx.modelRegistry.find(provider, modelId) !== void 0
26529
26844
  });
26530
26845
  const launchArgs = agentLaunchArgs(effectiveDefinition, {
26531
26846
  ...body ? { bodyPromptPath: promptPaths.at(-1) } : {},
@@ -26535,6 +26850,11 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26535
26850
  ...operation.action === "delegate" ? { inheritedThinking: pi.getThinkingLevel() } : {},
26536
26851
  modelDecision
26537
26852
  });
26853
+ previousLeadInstanceId = readLeadCoordinationState2(
26854
+ supervisionRuntime2(),
26855
+ assignment.id
26856
+ )?.instanceId;
26857
+ leadStartupStartedAt = Date.now();
26538
26858
  await startHerdrAgentInPane2(pi, ctx, {
26539
26859
  primaryWorkspaceId,
26540
26860
  workspaceId,
@@ -26555,6 +26875,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26555
26875
  let herdrSessionReported = false;
26556
26876
  let sessionIdResolved = false;
26557
26877
  let leadStateObserved = false;
26878
+ let leadIdentityObserved = false;
26558
26879
  while (!lead && Date.now() < deadline) {
26559
26880
  const inventory = await herdrSessionSnapshot2(pi, ctx, signal);
26560
26881
  const candidates = inventory.agents.filter(
@@ -26572,6 +26893,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26572
26893
  assignment.id
26573
26894
  );
26574
26895
  leadStateObserved = Boolean(candidateState);
26896
+ leadIdentityObserved = candidateState?.role === "lead" && candidateState.piSessionId === assignment.id;
26575
26897
  if (candidateState)
26576
26898
  requireCompatibleBuild2(
26577
26899
  HERDSMAN_BUILD2,
@@ -26602,7 +26924,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26602
26924
  }
26603
26925
  const leadSessionId = lead && assignment.id;
26604
26926
  if (!leadSessionId) {
26605
- const readiness = !piProcessSeen ? "No Pi process or exact-pane Herdr session was observed" : !herdrSessionReported ? "Pi process seen in the exact pane, but Herdr never reported a Pi session identity" : !leadStateObserved ? "Herdr session reported, but Herdsman Lead coordination state was never published" : !sessionIdResolved ? "Lead state was present but Herdr's session path is not yet materialized" : "Lead coordination state was present but not a valid Lead identity";
26927
+ const readiness = !piProcessSeen ? "No Pi process or exact-pane Herdr session was observed" : !herdrSessionReported ? "Pi process seen in the exact pane, but Herdr never reported a Pi session identity" : !leadStateObserved ? "Herdr session reported, but Herdsman Lead coordination state was never published" : !sessionIdResolved ? "Lead state was present but Herdr's session path is not yet materialized" : !leadIdentityObserved ? "Lead coordination state was present but not a valid Lead identity" : startedLead && !freshRestorationAttestation ? "Lead model restoration attestation was absent or stale for the new startup generation" : "Lead coordination state was present but not a valid Lead identity";
26606
26928
  let processInfo = "unavailable";
26607
26929
  try {
26608
26930
  const process2 = await runHerdr3(
@@ -28455,6 +28777,12 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28455
28777
  description: String(config.statusWidgetMaxRows),
28456
28778
  help: "Maximum ambient widget lines, including header and overflow (1\u2013100)."
28457
28779
  },
28780
+ {
28781
+ value: "max-agent-depth",
28782
+ label: "Max Agent depth",
28783
+ description: String(config.maxAgentDepth),
28784
+ help: "Longest chain of nested Agents below the Lead, Manager or Chief (1 = Agents never delegate). Global only; checked at each launch. Existing Agents stay manageable when it is lowered."
28785
+ },
28458
28786
  {
28459
28787
  value: "message-limits",
28460
28788
  label: "Message limits",
@@ -28515,6 +28843,49 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28515
28843
  );
28516
28844
  }
28517
28845
  }
28846
+ } else if (selected === "max-agent-depth") {
28847
+ while (true) {
28848
+ const choice = await host.selectMenu(ctx, "Max Agent depth", [
28849
+ {
28850
+ value: "default",
28851
+ label: `Default (${DEFAULT_MAX_AGENT_DEPTH})`
28852
+ },
28853
+ ...[1, 2, 3, 4, 5].map((depth) => ({
28854
+ value: String(depth),
28855
+ label: String(depth)
28856
+ })),
28857
+ { value: "custom", label: "Custom\u2026" },
28858
+ { value: "reset", label: "Reset" }
28859
+ ]);
28860
+ if (!choice) break;
28861
+ let value2;
28862
+ if (choice === "reset") value2 = void 0;
28863
+ else if (choice === "custom") {
28864
+ const input = await host.input(
28865
+ ctx,
28866
+ "Custom max Agent depth (positive integer)"
28867
+ );
28868
+ if (input === void 0) continue;
28869
+ value2 = Number(input.trim());
28870
+ if (!/^\d+$/u.test(input.trim()) || !host.validMaxAgentDepth(value2)) {
28871
+ ctx.ui.notify("Enter a positive integer", "error");
28872
+ continue;
28873
+ }
28874
+ } else
28875
+ value2 = choice === "default" ? DEFAULT_MAX_AGENT_DEPTH : Number(choice);
28876
+ try {
28877
+ host.updateConfig("maxAgentDepth", value2);
28878
+ ctx.ui.notify(
28879
+ `Max Agent depth: ${value2 === void 0 ? "reset" : value2}`
28880
+ );
28881
+ break;
28882
+ } catch (error2) {
28883
+ ctx.ui.notify(
28884
+ `Could not update max Agent depth: ${String(error2)}`,
28885
+ "error"
28886
+ );
28887
+ }
28888
+ }
28518
28889
  } else if (selected === "message-limits")
28519
28890
  await this.openMessageLimitsMenu(ctx);
28520
28891
  else if (selected === "default-lead-execution") {
@@ -29629,6 +30000,7 @@ function readRootOwners(inventory, mailboxes, workspaceId, dependencies) {
29629
30000
  }
29630
30001
  function createLeadCoordinationRuntime(host) {
29631
30002
  let leadCoordinationHealthy = true;
30003
+ let startupAttestation;
29632
30004
  let peerPresenceLease;
29633
30005
  let peerPresenceRecord;
29634
30006
  let peerPresenceGeneration = 0;
@@ -29697,12 +30069,13 @@ function createLeadCoordinationRuntime(host) {
29697
30069
  }
29698
30070
  });
29699
30071
  };
29700
- const persistCoordinatorState = () => {
30072
+ const persistCoordinatorState = (attestation) => {
29701
30073
  try {
30074
+ if (attestation) startupAttestation = attestation;
29702
30075
  pi.appendEntry("pi-herdsman-lead-state", {
29703
30076
  instanceId: host.leadInstanceId()
29704
30077
  });
29705
- return persistLeadCoordination();
30078
+ return persistLeadCoordination(startupAttestation);
29706
30079
  } catch (error2) {
29707
30080
  markLeadCoordinationUnhealthy();
29708
30081
  if (leadRuntime.leadContext)
@@ -29715,7 +30088,7 @@ function createLeadCoordinationRuntime(host) {
29715
30088
  return false;
29716
30089
  }
29717
30090
  };
29718
- const persistLeadCoordination = () => {
30091
+ const persistLeadCoordination = (attestation = startupAttestation) => {
29719
30092
  if (controllerScope?.kind !== "root" || leadRuntime.chiefMode !== "inactive" || leadRuntime.roleSuspended)
29720
30093
  return true;
29721
30094
  const wasHealthy = leadCoordinationHealthy;
@@ -29726,7 +30099,8 @@ function createLeadCoordinationRuntime(host) {
29726
30099
  role: activeRole() === "manager" ? "manager" : "lead",
29727
30100
  instanceId: host.leadInstanceId(),
29728
30101
  piSessionId: leadRuntime.leadContext?.sessionManager.getSessionId() ?? "",
29729
- updatedAt: Date.now()
30102
+ updatedAt: Date.now(),
30103
+ ...attestation && attestation.assignmentId === leadRuntime.leadContext?.sessionManager.getSessionId() && attestation.generation === host.leadInstanceId() ? { startupAttestation: attestation } : {}
29730
30104
  });
29731
30105
  leadCoordinationHealthy = true;
29732
30106
  if (!wasHealthy && leadRuntime.leadContext)
@@ -31498,6 +31872,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31498
31872
  return {
31499
31873
  persistCoordinatorState,
31500
31874
  persistLeadCoordination,
31875
+ invalidateStartupCoordinationState: (sessionId) => host.invalidateLeadCoordinationState(supervisionRuntime2(), sessionId),
31501
31876
  removePeerPresence,
31502
31877
  markLeadCoordinationUnhealthy,
31503
31878
  schedulePeerPresence,
@@ -31531,6 +31906,13 @@ ${receivedRefs.join("\n")}` : ""}`,
31531
31906
 
31532
31907
  // extension/lead-runtime.ts
31533
31908
  var LEAD_INSTANCE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
31909
+ function assertManagedLeadModelRestored(saved, actual, explicitModelOverride = false) {
31910
+ if (explicitModelOverride) return;
31911
+ if (!actual || actual.provider !== saved.provider || actual.modelId !== saved.modelId)
31912
+ throw new Error(
31913
+ `Managed Lead model restoration failed: saved model ${saved.provider}/${saved.modelId} was not restored; Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
31914
+ );
31915
+ }
31534
31916
  function createLeadRuntimeState() {
31535
31917
  return {
31536
31918
  instanceId: randomUUID16(),
@@ -31782,6 +32164,14 @@ function createLeadSessionStartRuntime(host) {
31782
32164
  host.roleTransitions.finalizeOptionalManagerStartup(ctx);
31783
32165
  if (!leadStateRestored && !malformedRole && host.roleTransitions.canRestoreChiefState() && !host.roleTransitions.restoreChiefState(ctx))
31784
32166
  malformedRole = true;
32167
+ try {
32168
+ await host.verifyManagedLeadModelRestoration?.(ctx, sessionSignal);
32169
+ } catch (error2) {
32170
+ await host.failClosedRole(ctx, error2);
32171
+ host.setLeadExecutionPending(false);
32172
+ return;
32173
+ }
32174
+ if (sessionSignal.aborted) return;
31785
32175
  if (malformedRole) host.roleTransitions.suspendMalformedRole(ctx);
31786
32176
  if (host.roleTransitions.shouldRestoreChief(persistedRole)) {
31787
32177
  try {
@@ -31935,6 +32325,13 @@ function createLeadAgentEventRuntime(host) {
31935
32325
  const message = await host.prepareSupervisionMessage(ctx);
31936
32326
  if (message) host.sendMessage(message);
31937
32327
  await host.drainRetirementNotices(ctx, true);
32328
+ try {
32329
+ host.reconcileRoleTools?.();
32330
+ } catch (error2) {
32331
+ host.setActiveTools([]);
32332
+ throw error2;
32333
+ }
32334
+ sections.pi_herdsman_role = host.roleCharter(ctx);
31938
32335
  return;
31939
32336
  }
31940
32337
  const activeLead = host.isActiveLead() && !host.isRoleSuspended();
@@ -31966,14 +32363,39 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
31966
32363
  });
31967
32364
  }
31968
32365
  },
32366
+ turnEnd() {
32367
+ if (!host.isActiveManager() || host.isRoleSuspended()) return;
32368
+ try {
32369
+ host.reconcileRoleTools?.();
32370
+ } catch (error2) {
32371
+ host.setActiveTools([]);
32372
+ throw error2;
32373
+ }
32374
+ },
31969
32375
  toolCall(event, ctx) {
31970
- if (!host.isCurrentChief(ctx) || (host.currentChiefAllowedTools(ctx) ?? host.chiefTools).includes(
31971
- event.toolName
31972
- ))
31973
- return void 0;
32376
+ if (host.isCurrentChief(ctx)) {
32377
+ if ((host.currentChiefAllowedTools(ctx) ?? host.chiefTools).includes(
32378
+ event.toolName
32379
+ ))
32380
+ return void 0;
32381
+ return {
32382
+ block: true,
32383
+ reason: "Tool is unavailable in the active Chief profile."
32384
+ };
32385
+ }
32386
+ if (!host.isActiveManager()) return void 0;
32387
+ try {
32388
+ if ((host.currentManagerAllowedTools?.(ctx) ?? host.managerTools ?? []).includes(event.toolName))
32389
+ return void 0;
32390
+ } catch {
32391
+ return {
32392
+ block: true,
32393
+ reason: "Manager tool authorization is unavailable."
32394
+ };
32395
+ }
31974
32396
  return {
31975
32397
  block: true,
31976
- reason: "Tool is unavailable in the active Chief profile."
32398
+ reason: "Tool is unavailable in the active Manager profile."
31977
32399
  };
31978
32400
  }
31979
32401
  };
@@ -32014,10 +32436,7 @@ function registerLeadRuntime(pi, options) {
32014
32436
  return {
32015
32437
  role: role2,
32016
32438
  definition: prepared,
32017
- tools: leadToolState.projectRoleTools(baseline, prepared, [
32018
- ...role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools,
32019
- ...supervisoryAgentTools(ctx, prepared)
32020
- ]),
32439
+ baseline,
32021
32440
  sessionId: ctx.sessionManager.getSessionId(),
32022
32441
  valid: true
32023
32442
  };
@@ -32030,10 +32449,7 @@ function registerLeadRuntime(pi, options) {
32030
32449
  frontmatter: {},
32031
32450
  body: ""
32032
32451
  },
32033
- tools: leadToolState.appendRegisteredTools(
32034
- [],
32035
- role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools
32036
- ),
32452
+ baseline: [],
32037
32453
  sessionId: ctx.sessionManager.getSessionId(),
32038
32454
  valid: false
32039
32455
  });
@@ -32167,7 +32583,16 @@ function registerLeadRuntime(pi, options) {
32167
32583
  return policy === "all" || policy.size > 0;
32168
32584
  })
32169
32585
  );
32170
- const tools = profile.tools.filter(
32586
+ const required = [
32587
+ ...role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools,
32588
+ ...supervisoryAgentTools(ctx, profile.definition)
32589
+ ];
32590
+ const projected = leadToolState.projectRoleTools(
32591
+ profile.baseline,
32592
+ profile.definition,
32593
+ required
32594
+ );
32595
+ const tools = projected.filter(
32171
32596
  (name) => !AGENT_COORDINATION_TOOLS.includes(name) || permitted.has(name)
32172
32597
  );
32173
32598
  for (const name of permitted) if (!tools.includes(name)) tools.push(name);
@@ -33236,6 +33661,7 @@ function registerLeadRuntime(pi, options) {
33236
33661
  sessionKind = identity;
33237
33662
  managedLifecycle = "unavailable";
33238
33663
  options.sessionStartOptions.appendRoleError(ctx, error2);
33664
+ options.sessionStartOptions.afterManagedSessionIdentityInitialized?.();
33239
33665
  return;
33240
33666
  }
33241
33667
  assignment = scope ? roleTransitions.projectAssignmentForScope(scope, sessionId) : void 0;
@@ -33263,6 +33689,8 @@ function registerLeadRuntime(pi, options) {
33263
33689
  persistLeadExecution(mode, []);
33264
33690
  }
33265
33691
  managedLifecycle = assignment ? "assigned" : "unavailable";
33692
+ if (resolved.kind === "managed")
33693
+ options.sessionStartOptions.afterManagedSessionIdentityInitialized?.();
33266
33694
  };
33267
33695
  const currentProjectAssignment = async (ctx) => {
33268
33696
  if (!sessionKind || sessionKind.sessionId !== ctx.sessionManager.getSessionId())
@@ -33413,6 +33841,45 @@ function registerLeadRuntime(pi, options) {
33413
33841
  )
33414
33842
  };
33415
33843
  };
33844
+ const managedLeadDefinition = (ctx) => options.commandHost.discoverRoleDefinition(
33845
+ MANAGED_LEAD_DEFINITION_NAME,
33846
+ ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33847
+ );
33848
+ const verifyManagedLeadModelRestoration = async (ctx, signal) => {
33849
+ if (sessionKind?.kind !== "managed") return;
33850
+ coordinationRuntime.invalidateStartupCoordinationState(
33851
+ ctx.sessionManager.getSessionId()
33852
+ );
33853
+ const definition = managedLeadDefinition(ctx);
33854
+ if (signal.aborted) return;
33855
+ const saved = resolveSavedSessionModelSelection(
33856
+ ctx.sessionManager,
33857
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
33858
+ );
33859
+ const explicitModelOverride = configuredModel(definition.frontmatter) !== void 0;
33860
+ if (saved.kind === "unresolved" && !explicitModelOverride)
33861
+ throw new Error(
33862
+ `Managed Lead model restoration failed: saved selection is ambiguous (${saved.candidates.map(({ provider, modelId }) => `${provider}/${modelId}`).join(" vs ")}).`
33863
+ );
33864
+ if (saved.kind === "resolved") {
33865
+ const actual = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
33866
+ assertManagedLeadModelRestored(
33867
+ saved.model,
33868
+ actual,
33869
+ explicitModelOverride
33870
+ );
33871
+ }
33872
+ const startupAttestation = {
33873
+ kind: "model_restore",
33874
+ assignmentId: ctx.sessionManager.getSessionId(),
33875
+ generation: leadRuntime.instanceId,
33876
+ result: explicitModelOverride ? "definition_override" : saved.kind === "none" ? "no_saved_model" : "verified"
33877
+ };
33878
+ if (!coordinationRuntime.persistCoordinatorState(startupAttestation))
33879
+ throw new Error(
33880
+ "Managed Lead model restoration was verified, but its fresh startup attestation could not be published"
33881
+ );
33882
+ };
33416
33883
  const prepareLeadExecution = async (ctx, signal, skipProfileResolution = false, skipAssignmentLookup = false, roleDefinitions) => {
33417
33884
  if (signal.aborted) return;
33418
33885
  const currentBaseline = () => leadToolState.getLeadTools() ?? leadToolState.normalizeBaseTools(pi.getActiveTools());
@@ -33467,10 +33934,7 @@ function registerLeadRuntime(pi, options) {
33467
33934
  persistLeadExecution(mode, baseline);
33468
33935
  if (sessionKind?.kind === "managed") {
33469
33936
  try {
33470
- const definition = options.commandHost.discoverRoleDefinition(
33471
- MANAGED_LEAD_DEFINITION_NAME,
33472
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33473
- );
33937
+ const definition = managedLeadDefinition(ctx);
33474
33938
  if (signal.aborted) return;
33475
33939
  leadExecution = { mode, definition, valid: true, managed: true };
33476
33940
  } catch (error2) {
@@ -33668,6 +34132,7 @@ function registerLeadRuntime(pi, options) {
33668
34132
  };
33669
34133
  },
33670
34134
  initializeSessionKind,
34135
+ verifyManagedLeadModelRestoration,
33671
34136
  quarantineNativeAgentRestore: (ctx) => {
33672
34137
  quarantinedSessionId = ctx.sessionManager.getSessionId();
33673
34138
  roleTransitions.suspendMalformedRole(ctx);
@@ -33769,10 +34234,12 @@ This session belongs to a managed Agent restored without its authorized launch c
33769
34234
  if (!options.hasPane()) return;
33770
34235
  options.queueLeadPresentation(ctx, event?.name ?? options.sessionName());
33771
34236
  });
33772
- pi.on("turn_end", (event, ctx) => {
34237
+ pi.on("turn_end", async (event, ctx) => {
33773
34238
  if (isQuarantinedSession(ctx)) return;
33774
34239
  if (activeLeadRole(leadRuntime) === "lead" || herdRunRuntime.hasActiveTurn())
33775
34240
  herdRunRuntime.turnEnd(event);
34241
+ if (activeLeadRole(leadRuntime) === "manager" && !leadRuntime.roleSuspended)
34242
+ agentEvents.turnEnd();
33776
34243
  options.queueLeadPresentation(ctx);
33777
34244
  });
33778
34245
  pi.on(
@@ -33818,7 +34285,10 @@ This session belongs to a managed Agent restored without its authorized launch c
33818
34285
  lifecycle: managedLifecycle
33819
34286
  } : { managed: false, mode: leadExecution?.mode ?? "flexible" },
33820
34287
  supervisoryProfileBody: (ctx, role2) => currentSupervisoryProfile(ctx, role2)?.valid ? currentSupervisoryProfile(ctx, role2).definition.body : "",
33821
- currentChiefAllowedTools: (ctx) => supervisoryTools(ctx, "chief")
34288
+ currentChiefAllowedTools: (ctx) => supervisoryTools(ctx, "chief"),
34289
+ currentManagerAllowedTools: (ctx) => supervisoryTools(ctx, "manager"),
34290
+ reconcileRoleTools: () => roleTransitions.reconcileRoleTools(),
34291
+ managerTools: [...options.roleTransitionHost.managerTools]
33822
34292
  };
33823
34293
  }
33824
34294
  function createLeadIdentityRuntime(host) {
@@ -39744,6 +40214,9 @@ No active Herdsman role is verified for this Pi session.`;
39744
40214
  },
39745
40215
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
39746
40216
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
40217
+ currentManagerAllowedTools: (ctx) => leadRuntimes.currentManagerAllowedTools(ctx),
40218
+ reconcileRoleTools: () => leadRuntimes.roleTransitions.reconcileRoleTools(),
40219
+ managerTools: MANAGER_TOOLS,
39747
40220
  isActiveManager: () => activeRole() === "manager" && !leadRuntime.roleSuspended,
39748
40221
  isActiveLead: () => activeRole() === "lead",
39749
40222
  prepareLeadSupervisorStateMessage: (ctx) => leadRuntimes.coordinationRuntime.prepareLeadSupervisorStateMessage(
@@ -39932,6 +40405,7 @@ ${summary}`,
39932
40405
  formatMessageLimit,
39933
40406
  validByteLimit,
39934
40407
  validStatusWidgetMaxRows,
40408
+ validMaxAgentDepth,
39935
40409
  input: (ctx, label) => ctx.ui.input(label),
39936
40410
  updateSpawnPlacement: (placement) => updateConfig("spawnPlacement", placement),
39937
40411
  updateMessageLimit: (key, value2) => updateConfig(key, value2),
@@ -40373,6 +40847,7 @@ ${summary}`,
40373
40847
  appendRoleError: (ctx, error2) => appendDurableError(pi, ctx, "pi_herdsman_role_error", error2)
40374
40848
  };
40375
40849
  const sessionStartOptions = {
40850
+ afterManagedSessionIdentityInitialized: lockHooks?.afterManagedSessionIdentityInitialized,
40376
40851
  rejectNativeAgentRestore: (ctx) => {
40377
40852
  const sessionId = ctx.sessionManager.getSessionId();
40378
40853
  try {