pi-herdsman 0.41.0 → 0.42.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
@@ -1176,6 +1176,7 @@ function validate(value2, kind) {
1176
1176
  "bootstrap",
1177
1177
  "mailbox_state",
1178
1178
  "controller_recovery",
1179
+ "model_restore",
1179
1180
  "request_observer",
1180
1181
  "metadata"
1181
1182
  ].includes(v.stage))
@@ -2742,6 +2743,9 @@ function withoutDelegationCapability(definition) {
2742
2743
  frontmatter
2743
2744
  };
2744
2745
  }
2746
+ function agentScopeAtDepth(depth, maxAgentDepth) {
2747
+ return depth >= maxAgentDepth ? "leaf" : "delegating";
2748
+ }
2745
2749
  function projectAgentDefinition(agent, scope) {
2746
2750
  return scope === "leaf" ? withoutDelegationCapability(agent) : agent;
2747
2751
  }
@@ -2932,7 +2936,13 @@ function configuredModel(frontmatter) {
2932
2936
  function resolveChildModel(input) {
2933
2937
  if (input.configured !== void 0 && input.configured.trim() !== "")
2934
2938
  return { kind: "use", model: input.configured, extensionDiscovery: false };
2935
- if (input.inherited === void 0) return { kind: "none" };
2939
+ if (input.inherited === void 0) {
2940
+ const saved = input.saved;
2941
+ return {
2942
+ kind: "none",
2943
+ extensionDiscovery: input.savedUnresolved === true || !!saved && (input.isForeignProvider(saved.provider) || input.isKnownModel !== void 0 && !input.isKnownModel(saved.provider, saved.modelId))
2944
+ };
2945
+ }
2936
2946
  return {
2937
2947
  kind: "use",
2938
2948
  model: input.inherited.token,
@@ -3034,7 +3044,7 @@ function agentLaunchArgs(agent, options) {
3034
3044
  if (approveProject === true) args.push("--approve");
3035
3045
  else if (approveProject === false) args.push("--no-approve");
3036
3046
  const requestedModel = configuredModel(frontmatter) ?? inheritedModel;
3037
- const decision = options.modelDecision ?? (requestedModel === void 0 ? { kind: "none" } : {
3047
+ const decision = options.modelDecision ?? (requestedModel === void 0 ? { kind: "none", extensionDiscovery: false } : {
3038
3048
  kind: "use",
3039
3049
  model: requestedModel,
3040
3050
  extensionDiscovery: false
@@ -3099,8 +3109,7 @@ function agentLaunchArgs(agent, options) {
3099
3109
  const noSkills = frontmatter.noSkills ?? frontmatter.inheritSkills !== true;
3100
3110
  if (noSkills) args.push("--no-skills");
3101
3111
  for (const skill of frontmatter.skills ?? []) args.push("--skill", skill);
3102
- const extensionDiscovery = decision.kind === "use" && decision.extensionDiscovery;
3103
- if (frontmatter.noExtensions && !extensionDiscovery)
3112
+ if (frontmatter.noExtensions && !decision.extensionDiscovery)
3104
3113
  args.push("--no-extensions");
3105
3114
  for (const extension of frontmatter.extensions ?? [])
3106
3115
  args.push("--extension", extension);
@@ -7730,10 +7739,14 @@ function validLeadState(value2) {
7730
7739
  const r = value2;
7731
7740
  const keys = ["version", "instanceId", "piSessionId", "updatedAt"];
7732
7741
  if (Object.keys(r).some(
7733
- (k) => !keys.includes(k) && k !== "role" && k !== "build"
7742
+ (k) => !keys.includes(k) && k !== "role" && k !== "build" && k !== "startupAttestation"
7734
7743
  ) || keys.some((k) => !Object.hasOwn(r, k)))
7735
7744
  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;
7745
+ const attestation = r.startupAttestation;
7746
+ 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(
7747
+ attestation.result
7748
+ );
7749
+ 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
7750
  }
7738
7751
  function readLeadCoordinationState(runtime, piSessionId) {
7739
7752
  const path = leadCoordinationStatePath(runtime, piSessionId);
@@ -9695,17 +9708,19 @@ function formatToolModelResult(action, v) {
9695
9708
  ];
9696
9709
  };
9697
9710
  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));
9711
+ const renderTree = (agent, depth) => {
9712
+ rendered.add(agent);
9713
+ const nested = children(agent).filter((child) => !rendered.has(child));
9702
9714
  return [
9703
- ...agentLines(root2),
9704
- ...directChildren.length ? [" agents:"] : [],
9705
- ...directChildren.flatMap((child) => agentLines(child, " ")),
9706
- ""
9715
+ ...agentLines(agent, " ".repeat(depth)),
9716
+ ...nested.length ? [`${" ".repeat(depth)} agents:`] : [],
9717
+ ...nested.flatMap((child) => renderTree(child, depth + 1))
9707
9718
  ];
9708
- });
9719
+ };
9720
+ const renderedAgents = roots.flatMap((root2) => [
9721
+ ...renderTree(root2, 0),
9722
+ ""
9723
+ ]);
9709
9724
  const fallbackAgents = agents.filter((agent) => !rendered.has(agent));
9710
9725
  return [
9711
9726
  `Agents: ${agents.length}`,
@@ -12742,6 +12757,14 @@ function validByteLimit(value2) {
12742
12757
  function validStatusWidgetMaxRows(value2) {
12743
12758
  return typeof value2 === "number" && Number.isInteger(value2) && value2 >= 1 && value2 <= 100;
12744
12759
  }
12760
+ function validMaxAgentDepth(value2) {
12761
+ return typeof value2 === "number" && Number.isSafeInteger(value2) && value2 >= 1;
12762
+ }
12763
+ function invalidMaxAgentDepth(value2) {
12764
+ return new Error(
12765
+ `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}.`
12766
+ );
12767
+ }
12745
12768
  function validRepoIdentity(value2) {
12746
12769
  return typeof value2 === "string" && !!value2.trim() && value2 === value2.trim() && value2.length <= 4096 && value2 !== "__proto__" && value2 !== "constructor" && value2 !== "prototype" && !containsControlCharacter(value2);
12747
12770
  }
@@ -12778,6 +12801,11 @@ function parseRawConfig(content) {
12778
12801
  throw new Error("Invalid Pi Herdsman config field statusWidgetMaxRows");
12779
12802
  result.statusWidgetMaxRows = record.statusWidgetMaxRows;
12780
12803
  }
12804
+ if ("maxAgentDepth" in record) {
12805
+ if (!validMaxAgentDepth(record.maxAgentDepth))
12806
+ throw invalidMaxAgentDepth(record.maxAgentDepth);
12807
+ result.maxAgentDepth = record.maxAgentDepth;
12808
+ }
12781
12809
  if ("spawnPlacement" in record) {
12782
12810
  if (!isSpawnPlacement(record.spawnPlacement))
12783
12811
  throw new Error("Invalid Pi Herdsman config field spawnPlacement");
@@ -13083,6 +13111,8 @@ function updateConfig(key, value2) {
13083
13111
  if (value2 !== void 0) {
13084
13112
  if (key === "statusWidgetMaxRows" && !validStatusWidgetMaxRows(value2))
13085
13113
  throw new Error("Invalid Pi Herdsman config field statusWidgetMaxRows");
13114
+ if (key === "maxAgentDepth" && !validMaxAgentDepth(value2))
13115
+ throw invalidMaxAgentDepth(value2);
13086
13116
  if (key === "spawnPlacement" && !isSpawnPlacement(value2))
13087
13117
  throw new Error("Invalid Pi Herdsman config field spawnPlacement");
13088
13118
  if (key === "defaultLeadExecution" && !isLeadExecutionMode(value2))
@@ -13107,7 +13137,7 @@ function updateConfig(key, value2) {
13107
13137
  throw new Error(
13108
13138
  "Invalid Pi Herdsman config field worktreeRemovalPreapprovedRepos"
13109
13139
  );
13110
- if (key !== "spawnPlacement" && key !== "statusWidgetMaxRows" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerGitBootstrapWithoutConfirmation" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
13140
+ if (key !== "spawnPlacement" && key !== "statusWidgetMaxRows" && key !== "maxAgentDepth" && key !== "defaultLeadExecution" && key !== "contextRetirement" && key !== "autoActivateManager" && key !== "managerGitBootstrapWithoutConfirmation" && key !== "managerMergeEnabled" && key !== "managerMergeOverrides" && key !== "worktreeRemovalPreapprovedRepos" && !validByteLimit(value2))
13111
13141
  throw new Error(`Invalid Pi Herdsman config field ${key}`);
13112
13142
  current[key] = value2;
13113
13143
  } else delete current[key];
@@ -13125,7 +13155,7 @@ function updateConfig(key, value2) {
13125
13155
  release();
13126
13156
  }
13127
13157
  }
13128
- var import_proper_lockfile, DEFAULT_BYTE_LIMIT, MIN_BYTE_LIMIT, MAX_BYTE_LIMIT, DEFAULT_STATUS_WIDGET_MAX_ROWS, DEFAULT_CONFIG, CONFIG_KEYS;
13158
+ 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
13159
  var init_config = __esm({
13130
13160
  "extension/config.ts"() {
13131
13161
  "use strict";
@@ -13137,8 +13167,10 @@ var init_config = __esm({
13137
13167
  MIN_BYTE_LIMIT = 1024;
13138
13168
  MAX_BYTE_LIMIT = 1024 * 1024;
13139
13169
  DEFAULT_STATUS_WIDGET_MAX_ROWS = 8;
13170
+ DEFAULT_MAX_AGENT_DEPTH = 2;
13140
13171
  DEFAULT_CONFIG = {
13141
13172
  statusWidgetMaxRows: DEFAULT_STATUS_WIDGET_MAX_ROWS,
13173
+ maxAgentDepth: DEFAULT_MAX_AGENT_DEPTH,
13142
13174
  spawnPlacement: "subtree",
13143
13175
  defaultLeadExecution: "flexible",
13144
13176
  contextRetirement: true,
@@ -13152,6 +13184,7 @@ var init_config = __esm({
13152
13184
  };
13153
13185
  CONFIG_KEYS = /* @__PURE__ */ new Set([
13154
13186
  "statusWidgetMaxRows",
13187
+ "maxAgentDepth",
13155
13188
  "spawnPlacement",
13156
13189
  "defaultLeadExecution",
13157
13190
  "contextRetirement",
@@ -13704,6 +13737,53 @@ function agentToolName(action) {
13704
13737
  return action;
13705
13738
  }
13706
13739
  }
13740
+ function resolveSavedSessionModelSelection(manager, catalogModel) {
13741
+ const contextModel = manager.buildSessionContext?.().model ?? void 0;
13742
+ if (typeof manager.getBranch !== "function")
13743
+ return contextModel ? { kind: "resolved", model: contextModel } : { kind: "none" };
13744
+ const branch = manager.getBranch();
13745
+ let change;
13746
+ let changeIndex = -1;
13747
+ let response;
13748
+ let responseIndex = -1;
13749
+ for (let index = 0; index < branch.length; index++) {
13750
+ const entry = branch[index];
13751
+ if (entry.type === "model_change") {
13752
+ change = entry;
13753
+ changeIndex = index;
13754
+ } else if (entry.type === "message" && entry.message?.role === "assistant" && entry.message?.stopReason !== "error" && typeof entry.message?.provider === "string" && typeof entry.message?.model === "string") {
13755
+ response = {
13756
+ provider: entry.message.provider,
13757
+ modelId: entry.message.model
13758
+ };
13759
+ responseIndex = index;
13760
+ }
13761
+ }
13762
+ if (!change && !response)
13763
+ return contextModel ? { kind: "resolved", model: contextModel } : { kind: "none" };
13764
+ if (change && changeIndex > responseIndex)
13765
+ return {
13766
+ kind: "resolved",
13767
+ model: { provider: change.provider, modelId: change.modelId }
13768
+ };
13769
+ if (change && response && (change.provider !== response.provider || change.modelId !== response.modelId)) {
13770
+ const catalog = catalogModel(change.provider, change.modelId);
13771
+ if (catalog?.api === "pi-virtual")
13772
+ return {
13773
+ kind: "resolved",
13774
+ model: { provider: change.provider, modelId: change.modelId }
13775
+ };
13776
+ if (!catalog)
13777
+ return {
13778
+ kind: "unresolved",
13779
+ candidates: [
13780
+ { provider: change.provider, modelId: change.modelId },
13781
+ response
13782
+ ]
13783
+ };
13784
+ }
13785
+ return response ? { kind: "resolved", model: response } : change ? { kind: "resolved", model: change } : { kind: "none" };
13786
+ }
13707
13787
  function requiredEvidenceEntriesForRequest(entries, requestId) {
13708
13788
  return entries.filter(
13709
13789
  (entry) => entry?.type === "custom" && entry.customType === "pi-herdsman-agent-required-evidence" && entry.data?.requestId === requestId
@@ -14930,6 +15010,13 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
14930
15010
  definition: child.definition,
14931
15011
  label: child.label,
14932
15012
  cwd: manager.getCwd(),
15013
+ ...(() => {
15014
+ const selection = resolveSavedSessionModelSelection(
15015
+ manager,
15016
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
15017
+ );
15018
+ return selection.kind === "resolved" ? { savedModel: selection.model } : selection.kind === "unresolved" ? { savedModelUnresolved: true } : {};
15019
+ })(),
14933
15020
  ...evidence ? { evidence } : {}
14934
15021
  };
14935
15022
  }
@@ -14957,13 +15044,49 @@ function resolveAssignmentSession(ctx, raw, options = {}) {
14957
15044
  );
14958
15045
  return resolved;
14959
15046
  }
15047
+ function childAgentDepth(scope) {
15048
+ return scope.kind === "managed-agent" ? scope.depth + 1 : 1;
15049
+ }
15050
+ function durableAgentDepth(states, agent) {
15051
+ const seen = /* @__PURE__ */ new Set([agent.piSessionId]);
15052
+ let depth = 1;
15053
+ let current = agent;
15054
+ for (; ; ) {
15055
+ const owners = states.filter(
15056
+ (candidate) => candidate.workspaceId === agent.workspaceId && candidate.piSessionId === current.ownerSessionId
15057
+ );
15058
+ if (owners.length > 1)
15059
+ throw new Error(
15060
+ `owner session ${current.ownerSessionId} has ${owners.length} ownership records, so the chain is ambiguous`
15061
+ );
15062
+ const owner = owners[0];
15063
+ if (!owner) {
15064
+ if (!agent.rootSessionId?.trim())
15065
+ throw new Error(
15066
+ "its record has no verified root session, so the ownership chain cannot be checked"
15067
+ );
15068
+ if (current.ownerSessionId !== agent.rootSessionId)
15069
+ throw new Error(
15070
+ `the ownership chain does not reach its verified root: owner session ${current.ownerSessionId} has no ownership record and is not root session ${agent.rootSessionId}`
15071
+ );
15072
+ return depth;
15073
+ }
15074
+ if (seen.has(owner.piSessionId))
15075
+ throw new Error("Managed Agent ownership records form a cycle");
15076
+ seen.add(owner.piSessionId);
15077
+ depth++;
15078
+ current = owner;
15079
+ }
15080
+ }
14960
15081
  function sameRootDelegationGeneration(a, b) {
14961
15082
  return !!b && a.sessionId === b.sessionId && a.roleGeneration === b.roleGeneration && a.role === b.role && a.authority === b.authority && a.profile === b.profile;
14962
15083
  }
14963
15084
  function permitsRootDelegation(policy, definition) {
14964
15085
  return policy === "all" || policy.has(definition);
14965
15086
  }
14966
- function visibleAgentCapabilities(definitions, scope, rootPolicy = "all") {
15087
+ function visibleAgentCapabilities(definitions, scope, rootPolicy = "all", maxAgentDepth = readConfig().maxAgentDepth) {
15088
+ if (scope.kind === "managed-agent" && scope.depth >= maxAgentDepth) return [];
15089
+ const childScope = agentScopeAtDepth(childAgentDepth(scope), maxAgentDepth);
14967
15090
  const availableNames = new Set(
14968
15091
  definitions.filter(agentDefinitionEnabled).map(({ name }) => name)
14969
15092
  );
@@ -14980,14 +15103,14 @@ function visibleAgentCapabilities(definitions, scope, rootPolicy = "all") {
14980
15103
  return available.map((definition) => {
14981
15104
  const metadata = agentDefinitionMetadata(
14982
15105
  definition,
14983
- scope.kind === "managed-agent" ? "leaf" : "delegating"
15106
+ childScope
14984
15107
  );
14985
15108
  return {
14986
15109
  name: definition.name,
14987
15110
  ...typeof metadata.description === "string" ? { description: metadata.description } : {},
14988
15111
  tools: formatTools(metadata),
14989
15112
  skills: formatSkills(metadata),
14990
- ...scope.kind === "root" && agentDefinitionDelegationEnabled(definition) && definition.frontmatter.agents?.length ? { agents: [...definition.frontmatter.agents] } : {}
15113
+ ...childScope === "delegating" && agentDefinitionDelegationEnabled(definition) && definition.frontmatter.agents?.length ? { agents: [...definition.frontmatter.agents] } : {}
14991
15114
  };
14992
15115
  });
14993
15116
  }
@@ -15386,14 +15509,9 @@ function listedAgentRecord(view, snapshot, ownerSessionId, scope, unresolvedMail
15386
15509
  let closeAvailable = false;
15387
15510
  if (direct && (presence.kind === "live" || presence.kind === "lost")) {
15388
15511
  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]);
15512
+ if (!unresolvedMailboxState) {
15513
+ const plan = dependencies.cascadePlan(view, state);
15514
+ dependencies.assertCascadeSafe([plan.parent, ...plan.descendants]);
15397
15515
  closeAvailable = true;
15398
15516
  }
15399
15517
  } catch {
@@ -17475,7 +17593,10 @@ function createAgentController(pi, options) {
17475
17593
  ].filter((id) => !!id);
17476
17594
  if (requestIds.some((id) => id !== result.requestId))
17477
17595
  throw new Error("agent has newer mailbox work");
17478
- if (managedAgent)
17596
+ const ownsDescendants = listAgentStates().some(
17597
+ ({ state: candidate }) => candidate.workspaceId === state.workspaceId && candidate.ownerSessionId === state.piSessionId
17598
+ );
17599
+ if (managedAgent && !ownsDescendants && listAgentStateIssues().length === 0)
17479
17600
  await finalizeDeliveredRoot(context, state, result.requestId, signal);
17480
17601
  else await closeCascade(context, state, signal, result.requestId);
17481
17602
  return true;
@@ -17790,6 +17911,36 @@ function createAgentController(pi, options) {
17790
17911
  "Only a Herdr controller may start agent assignments",
17791
17912
  p.action
17792
17913
  );
17914
+ const maxAgentDepth = readConfig().maxAgentDepth;
17915
+ if (scope.kind === "managed-agent") {
17916
+ let durableDepth;
17917
+ try {
17918
+ const own = options.managedAgentState?.(ctx);
17919
+ if (!own) throw new Error("its own ownership record is unavailable");
17920
+ durableDepth = durableAgentDepth(
17921
+ listAgentStates().map(({ state }) => state),
17922
+ own
17923
+ );
17924
+ } catch (error2) {
17925
+ fail(
17926
+ "invalid_request",
17927
+ `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`,
17928
+ p.action
17929
+ );
17930
+ }
17931
+ if (durableDepth !== scope.depth)
17932
+ fail(
17933
+ "invalid_request",
17934
+ `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`,
17935
+ p.action
17936
+ );
17937
+ if (childAgentDepth(scope) > maxAgentDepth)
17938
+ fail(
17939
+ "invalid_request",
17940
+ `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`,
17941
+ p.action
17942
+ );
17943
+ }
17793
17944
  const resumed = p.action === "continue" ? resolveAssignmentSession(ctx, p.session, {
17794
17945
  isContextRetired: options.isContextRetired,
17795
17946
  contextRetirementForSession: (context, manager) => sameCwd(context.cwd, manager.getCwd()) ? readEffectiveConfig(context).contextRetirement : void 0
@@ -18426,9 +18577,10 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18426
18577
  p.action
18427
18578
  );
18428
18579
  const preparedDefinition = preparedBody === definition.body ? definition : { ...definition, body: preparedBody };
18580
+ const childDepth = childAgentDepth(scope);
18429
18581
  const effectiveDefinition = projectAgentDefinition(
18430
18582
  preparedDefinition,
18431
- scope.kind === "managed-agent" ? "leaf" : "delegating"
18583
+ agentScopeAtDepth(childDepth, maxAgentDepth)
18432
18584
  );
18433
18585
  const delegationEnabled = agentDefinitionDelegationEnabled(effectiveDefinition);
18434
18586
  const runId = assignment.runId;
@@ -18642,6 +18794,7 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18642
18794
  `PI_HERDSMAN_LABEL=${label}`,
18643
18795
  `PI_HERDSMAN_WORKSPACE_ID=${workspaceId}`,
18644
18796
  `PI_HERDSMAN_AGENT_DEFINITION=${agentDefinition}`,
18797
+ `PI_HERDSMAN_DEPTH=${childDepth}`,
18645
18798
  `PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS=${JSON.stringify(
18646
18799
  delegationEnabled ? effectiveDefinition.frontmatter.agents : []
18647
18800
  )}`,
@@ -18654,8 +18807,13 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18654
18807
  const childModel = resolveChildModel({
18655
18808
  configured: configuredModel(effectiveDefinition.frontmatter),
18656
18809
  inherited: !resumed && ctx.model ? { provider: ctx.model.provider, token: modelToken(ctx.model) } : void 0,
18657
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId)
18810
+ saved: resumed?.savedModel,
18811
+ savedUnresolved: resumed?.savedModelUnresolved,
18812
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
18813
+ isKnownModel: (provider, id) => ctx.modelRegistry.find(provider, id) !== void 0
18658
18814
  });
18815
+ if ((resumed?.savedModel || resumed?.savedModelUnresolved) && !configuredModel(effectiveDefinition.frontmatter))
18816
+ env.push("PI_HERDSMAN_RESTORE_MODEL=saved-session");
18659
18817
  const launchArgs = agentLaunchArgs(effectiveDefinition, {
18660
18818
  ...effectiveDefinition.body ? { bodyPromptPath: promptPaths[0] } : {},
18661
18819
  sharedPromptPath: promptPaths[effectiveDefinition.body ? 1 : 0],
@@ -18666,6 +18824,12 @@ This batch was not embedded. Use read_evidence to retrieve the items relevant to
18666
18824
  modelDecision: childModel
18667
18825
  });
18668
18826
  assertRootDelegationAllowed();
18827
+ if (readConfig().maxAgentDepth !== maxAgentDepth)
18828
+ fail(
18829
+ "invalid_request",
18830
+ `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`,
18831
+ p.action
18832
+ );
18669
18833
  started = await startHerdrAgent(pi, ctx, {
18670
18834
  label,
18671
18835
  runId,
@@ -20693,7 +20857,8 @@ Your herd is your internal team: you and your recursively owned Agents.
20693
20857
  Any review conducted within the herd is internal feedback, not user or supervisor
20694
20858
  review or approval.`;
20695
20859
  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
20860
+ agents delegate further only within the configured maximum nesting depth and
20861
+ are leaves beyond it. Delegate bounded execution work when an Agent can reasonably
20697
20862
  own it and delegation is useful. Keep work local when it is trivial,
20698
20863
  inseparable, otherwise unsuitable for an Agent, or delegation would add more
20699
20864
  coordination than value. Reuse adequate supplied evidence rather than
@@ -20722,6 +20887,7 @@ __export(managed_agent_runtime_exports, {
20722
20887
  AGENT_REQUIRED_EVIDENCE_ENTRY: () => AGENT_REQUIRED_EVIDENCE_ENTRY,
20723
20888
  READ_EVIDENCE_MAX_BYTES: () => READ_EVIDENCE_MAX_BYTES,
20724
20889
  READ_EVIDENCE_MAX_LINES: () => READ_EVIDENCE_MAX_LINES,
20890
+ agentDepthFromEnv: () => agentDepthFromEnv,
20725
20891
  allowedAgentDefinitionsFromEnv: () => allowedAgentDefinitionsFromEnv,
20726
20892
  authorizedScopedResult: () => authorizedScopedResult,
20727
20893
  createManagedAgentAskOwnerHandler: () => createManagedAgentAskOwnerHandler,
@@ -22478,6 +22644,7 @@ function registerManagedAgentRuntime(pi, options) {
22478
22644
  event.input.timeout = options.shellTimeoutSeconds;
22479
22645
  });
22480
22646
  const allowedAgentDefinitions = allowedAgentDefinitionsFromEnv();
22647
+ const agentDepth = agentDepthFromEnv();
22481
22648
  const delegationEnabled = allowedAgentDefinitions.length > 0;
22482
22649
  let startupDefinitionRoster;
22483
22650
  const controller = delegationEnabled ? createAgentController(pi, {
@@ -22490,16 +22657,19 @@ function registerManagedAgentRuntime(pi, options) {
22490
22657
  );
22491
22658
  return rootSessionId;
22492
22659
  },
22660
+ managedAgentState: (ctx) => managedAgentControllerIdentity(ctx),
22493
22661
  scope: {
22494
22662
  kind: "managed-agent",
22495
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
22663
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
22664
+ depth: agentDepth
22496
22665
  },
22497
22666
  build: options.build
22498
22667
  }) : void 0;
22499
22668
  if (controller) {
22500
22669
  const scope = {
22501
22670
  kind: "managed-agent",
22502
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
22671
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
22672
+ depth: agentDepth
22503
22673
  };
22504
22674
  options.statusRuntime.configure({
22505
22675
  pendingStartEntries: () => controller.pendingStartEntries(),
@@ -22854,7 +23024,8 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
22854
23024
  await options.getAgentDefinitions(ctx),
22855
23025
  {
22856
23026
  kind: "managed-agent",
22857
- allowedAgentDefinitions: new Set(allowedAgentDefinitions)
23027
+ allowedAgentDefinitions: new Set(allowedAgentDefinitions),
23028
+ depth: agentDepth
22858
23029
  }
22859
23030
  )
22860
23031
  };
@@ -23110,6 +23281,17 @@ function parseAllowedAgentDefinitions(raw) {
23110
23281
  );
23111
23282
  return value2;
23112
23283
  }
23284
+ function parseAgentDepth(raw) {
23285
+ if (raw === void 0) return 1;
23286
+ if (!/^[1-9][0-9]{0,8}$/.test(raw))
23287
+ throw new Error(
23288
+ "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"
23289
+ );
23290
+ return Number(raw);
23291
+ }
23292
+ function agentDepthFromEnv() {
23293
+ return parseAgentDepth(process.env.PI_HERDSMAN_DEPTH);
23294
+ }
23113
23295
  function allowedAgentDefinitionsFromEnv() {
23114
23296
  return parseAllowedAgentDefinitions(
23115
23297
  process.env.PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS
@@ -23136,6 +23318,7 @@ function managedAgentEnvironmentError() {
23136
23318
  if (!e.HERDR_PANE_ID?.trim()) return "HERDR_PANE_ID missing";
23137
23319
  try {
23138
23320
  parseAllowedAgentDefinitions(e.PI_HERDSMAN_ALLOWED_AGENT_DEFINITIONS);
23321
+ parseAgentDepth(e.PI_HERDSMAN_DEPTH);
23139
23322
  } catch (error2) {
23140
23323
  return String(error2).replace(/^Error: /, "");
23141
23324
  }
@@ -23297,6 +23480,36 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
23297
23480
  options.captureOwnTools(options.getActiveTools());
23298
23481
  options.ensureAgentIdentity(ctx);
23299
23482
  verified = candidate;
23483
+ const restoreModel = process.env.PI_HERDSMAN_RESTORE_MODEL;
23484
+ if (restoreModel) {
23485
+ startupStage = "model_restore";
23486
+ if (restoreModel !== "saved-session")
23487
+ throw new Error(
23488
+ "Cannot continue Agent: saved model expectation is invalid"
23489
+ );
23490
+ const selection = resolveSavedSessionModelSelection(
23491
+ ctx.sessionManager,
23492
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
23493
+ );
23494
+ const actual = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
23495
+ if (selection.kind === "none")
23496
+ throw new Error(
23497
+ `Cannot continue Agent: saved model selection could not be recovered. Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
23498
+ );
23499
+ if (selection.kind === "unresolved")
23500
+ throw new Error(
23501
+ `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"}.`
23502
+ );
23503
+ const expected = selection.model;
23504
+ const available = ctx.modelRegistry.find(
23505
+ expected.provider,
23506
+ expected.modelId
23507
+ );
23508
+ if (!available || !actual || actual.provider !== expected.provider || actual.modelId !== expected.modelId)
23509
+ throw new Error(
23510
+ `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"}.`
23511
+ );
23512
+ }
23300
23513
  const mailbox = process.env.PI_HERDSMAN_MAILBOX;
23301
23514
  const existing = readAgentState(mailbox);
23302
23515
  if (existing && !options.sameIdentity(existing, candidate))
@@ -23504,7 +23717,7 @@ function registerManagedAgentSessionStartHandler(pi, execution, options) {
23504
23717
  agentLabel: verified.agentLabel,
23505
23718
  paneId: verified.paneId,
23506
23719
  status: "failed",
23507
- error: "Managed Agent initialization failed",
23720
+ error: startupStage === "model_restore" ? String(error2).slice(0, 256) : "Managed Agent initialization failed",
23508
23721
  stage: startupStage
23509
23722
  });
23510
23723
  } finally {
@@ -23574,7 +23787,7 @@ import { fileURLToPath as fileURLToPath3 } from "node:url";
23574
23787
  // package.json
23575
23788
  var package_default = {
23576
23789
  name: "pi-herdsman",
23577
- version: "0.41.0",
23790
+ version: "0.42.0",
23578
23791
  type: "module",
23579
23792
  description: "Asynchronous Pi subagents and agent fleet orchestration for parallel coding agents with nested delegation, background work, and supervision in herdr.",
23580
23793
  license: "Apache-2.0",
@@ -23856,6 +24069,11 @@ init_agent_definitions();
23856
24069
  import { randomUUID as randomUUID12 } from "node:crypto";
23857
24070
  import { realpathSync as realpathSync6, statSync as statSync7, unlinkSync as unlinkSync9 } from "node:fs";
23858
24071
  import { isAbsolute as isAbsolute6, resolve as resolve6 } from "node:path";
24072
+ function isFreshLeadStartupAttestation(state, sessionId, previousInstanceId, startedAt) {
24073
+ 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(
24074
+ state.startupAttestation.result
24075
+ );
24076
+ }
23859
24077
  function hasManagerEvidenceSelectors(refs) {
23860
24078
  return refs.some(
23861
24079
  (ref) => ref.startsWith("result:") || ref.startsWith("evidence:")
@@ -26021,16 +26239,29 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26021
26239
  }
26022
26240
  resumeMessageQueued = true;
26023
26241
  };
26242
+ const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
26243
+ if (live.length === 1 && currentAssignment.piSessionFile)
26244
+ await bindLeadSessionFile(currentAssignment, live[0]);
26024
26245
  let savedSessionCwd;
26246
+ let savedModel;
26025
26247
  if (operation.action === "resume" && currentAssignment.piSessionFile) {
26248
+ let saved;
26026
26249
  try {
26027
- const saved = host.SessionManager.open(
26028
- currentAssignment.piSessionFile
26250
+ saved = host.SessionManager.open(currentAssignment.piSessionFile);
26251
+ } catch (error2) {
26252
+ throw new Error(
26253
+ `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
26254
  );
26030
- if (saved.getSessionId() === currentAssignment.id)
26031
- savedSessionCwd = saved.getCwd();
26032
- } catch {
26033
26255
  }
26256
+ if (saved.getSessionId() !== currentAssignment.id)
26257
+ throw new Error(
26258
+ `Saved Lead session restoration failed for ${currentAssignment.id}: recorded session history has a mismatched session ID; existing work was preserved.`
26259
+ );
26260
+ savedSessionCwd = saved.getCwd();
26261
+ savedModel = resolveSavedSessionModelSelection(
26262
+ saved,
26263
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
26264
+ );
26034
26265
  }
26035
26266
  const placement = operation.action === "resume" ? resolveAssignmentCheckout(
26036
26267
  currentAssignment,
@@ -26073,7 +26304,6 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26073
26304
  };
26074
26305
  if (branchWorktrees.length > 1)
26075
26306
  throw new Error(`Multiple Herdr worktrees match branch ${branch}`);
26076
- const live = operation.action === "resume" ? await liveAgent(ctx, currentAssignment.id) : [];
26077
26307
  if (live.length > 1)
26078
26308
  throw new Error(`Assignment ${id} has ambiguous live Lead identity`);
26079
26309
  if (live.length === 1) {
@@ -26423,6 +26653,9 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26423
26653
  await assertUnoccupied(workspaceId);
26424
26654
  let lead;
26425
26655
  let startedLead = false;
26656
+ let previousLeadInstanceId;
26657
+ let leadStartupStartedAt;
26658
+ let freshRestorationAttestation = false;
26426
26659
  const verifyLeadCandidate = (candidate) => {
26427
26660
  const reported = sessionIdentity2(candidate?.agent_session);
26428
26661
  if (!reported) return false;
@@ -26449,6 +26682,15 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26449
26682
  throw new Error(
26450
26683
  "Existing session in new worktree has a conflicting role or identity"
26451
26684
  );
26685
+ if (startedLead) {
26686
+ freshRestorationAttestation = leadStartupStartedAt !== void 0 && isFreshLeadStartupAttestation(
26687
+ state,
26688
+ assignment.id,
26689
+ previousLeadInstanceId,
26690
+ leadStartupStartedAt
26691
+ );
26692
+ if (!freshRestorationAttestation) return false;
26693
+ }
26452
26694
  return state?.role === "lead" && state.piSessionId === assignment.id;
26453
26695
  };
26454
26696
  const currentInventory = await herdrSessionSnapshot2(pi, ctx, signal);
@@ -26525,7 +26767,10 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26525
26767
  provider: ctx.model.provider,
26526
26768
  token: `${ctx.model.provider}/${ctx.model.id}`
26527
26769
  } : void 0,
26528
- isForeignProvider: (providerId) => registeredProviderIds.has(providerId)
26770
+ saved: operation.action === "resume" && savedModel?.kind === "resolved" ? savedModel.model : void 0,
26771
+ savedUnresolved: operation.action === "resume" && (savedModel === void 0 || savedModel.kind === "unresolved"),
26772
+ isForeignProvider: (providerId) => registeredProviderIds.has(providerId),
26773
+ isKnownModel: (provider, modelId) => ctx.modelRegistry.find(provider, modelId) !== void 0
26529
26774
  });
26530
26775
  const launchArgs = agentLaunchArgs(effectiveDefinition, {
26531
26776
  ...body ? { bodyPromptPath: promptPaths.at(-1) } : {},
@@ -26535,6 +26780,11 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26535
26780
  ...operation.action === "delegate" ? { inheritedThinking: pi.getThinkingLevel() } : {},
26536
26781
  modelDecision
26537
26782
  });
26783
+ previousLeadInstanceId = readLeadCoordinationState2(
26784
+ supervisionRuntime2(),
26785
+ assignment.id
26786
+ )?.instanceId;
26787
+ leadStartupStartedAt = Date.now();
26538
26788
  await startHerdrAgentInPane2(pi, ctx, {
26539
26789
  primaryWorkspaceId,
26540
26790
  workspaceId,
@@ -26555,6 +26805,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26555
26805
  let herdrSessionReported = false;
26556
26806
  let sessionIdResolved = false;
26557
26807
  let leadStateObserved = false;
26808
+ let leadIdentityObserved = false;
26558
26809
  while (!lead && Date.now() < deadline) {
26559
26810
  const inventory = await herdrSessionSnapshot2(pi, ctx, signal);
26560
26811
  const candidates = inventory.agents.filter(
@@ -26572,6 +26823,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26572
26823
  assignment.id
26573
26824
  );
26574
26825
  leadStateObserved = Boolean(candidateState);
26826
+ leadIdentityObserved = candidateState?.role === "lead" && candidateState.piSessionId === assignment.id;
26575
26827
  if (candidateState)
26576
26828
  requireCompatibleBuild2(
26577
26829
  HERDSMAN_BUILD2,
@@ -26602,7 +26854,7 @@ Subsequent explicitly requested removals here can proceed without a per-removal
26602
26854
  }
26603
26855
  const leadSessionId = lead && assignment.id;
26604
26856
  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";
26857
+ 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
26858
  let processInfo = "unavailable";
26607
26859
  try {
26608
26860
  const process2 = await runHerdr3(
@@ -28455,6 +28707,12 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28455
28707
  description: String(config.statusWidgetMaxRows),
28456
28708
  help: "Maximum ambient widget lines, including header and overflow (1\u2013100)."
28457
28709
  },
28710
+ {
28711
+ value: "max-agent-depth",
28712
+ label: "Max Agent depth",
28713
+ description: String(config.maxAgentDepth),
28714
+ 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."
28715
+ },
28458
28716
  {
28459
28717
  value: "message-limits",
28460
28718
  label: "Message limits",
@@ -28515,6 +28773,49 @@ Continuity proof saved for ${persisted} stopped Agent${persisted === 1 ? "" : "s
28515
28773
  );
28516
28774
  }
28517
28775
  }
28776
+ } else if (selected === "max-agent-depth") {
28777
+ while (true) {
28778
+ const choice = await host.selectMenu(ctx, "Max Agent depth", [
28779
+ {
28780
+ value: "default",
28781
+ label: `Default (${DEFAULT_MAX_AGENT_DEPTH})`
28782
+ },
28783
+ ...[1, 2, 3, 4, 5].map((depth) => ({
28784
+ value: String(depth),
28785
+ label: String(depth)
28786
+ })),
28787
+ { value: "custom", label: "Custom\u2026" },
28788
+ { value: "reset", label: "Reset" }
28789
+ ]);
28790
+ if (!choice) break;
28791
+ let value2;
28792
+ if (choice === "reset") value2 = void 0;
28793
+ else if (choice === "custom") {
28794
+ const input = await host.input(
28795
+ ctx,
28796
+ "Custom max Agent depth (positive integer)"
28797
+ );
28798
+ if (input === void 0) continue;
28799
+ value2 = Number(input.trim());
28800
+ if (!/^\d+$/u.test(input.trim()) || !host.validMaxAgentDepth(value2)) {
28801
+ ctx.ui.notify("Enter a positive integer", "error");
28802
+ continue;
28803
+ }
28804
+ } else
28805
+ value2 = choice === "default" ? DEFAULT_MAX_AGENT_DEPTH : Number(choice);
28806
+ try {
28807
+ host.updateConfig("maxAgentDepth", value2);
28808
+ ctx.ui.notify(
28809
+ `Max Agent depth: ${value2 === void 0 ? "reset" : value2}`
28810
+ );
28811
+ break;
28812
+ } catch (error2) {
28813
+ ctx.ui.notify(
28814
+ `Could not update max Agent depth: ${String(error2)}`,
28815
+ "error"
28816
+ );
28817
+ }
28818
+ }
28518
28819
  } else if (selected === "message-limits")
28519
28820
  await this.openMessageLimitsMenu(ctx);
28520
28821
  else if (selected === "default-lead-execution") {
@@ -29629,6 +29930,7 @@ function readRootOwners(inventory, mailboxes, workspaceId, dependencies) {
29629
29930
  }
29630
29931
  function createLeadCoordinationRuntime(host) {
29631
29932
  let leadCoordinationHealthy = true;
29933
+ let startupAttestation;
29632
29934
  let peerPresenceLease;
29633
29935
  let peerPresenceRecord;
29634
29936
  let peerPresenceGeneration = 0;
@@ -29697,12 +29999,13 @@ function createLeadCoordinationRuntime(host) {
29697
29999
  }
29698
30000
  });
29699
30001
  };
29700
- const persistCoordinatorState = () => {
30002
+ const persistCoordinatorState = (attestation) => {
29701
30003
  try {
30004
+ if (attestation) startupAttestation = attestation;
29702
30005
  pi.appendEntry("pi-herdsman-lead-state", {
29703
30006
  instanceId: host.leadInstanceId()
29704
30007
  });
29705
- return persistLeadCoordination();
30008
+ return persistLeadCoordination(startupAttestation);
29706
30009
  } catch (error2) {
29707
30010
  markLeadCoordinationUnhealthy();
29708
30011
  if (leadRuntime.leadContext)
@@ -29715,7 +30018,7 @@ function createLeadCoordinationRuntime(host) {
29715
30018
  return false;
29716
30019
  }
29717
30020
  };
29718
- const persistLeadCoordination = () => {
30021
+ const persistLeadCoordination = (attestation = startupAttestation) => {
29719
30022
  if (controllerScope?.kind !== "root" || leadRuntime.chiefMode !== "inactive" || leadRuntime.roleSuspended)
29720
30023
  return true;
29721
30024
  const wasHealthy = leadCoordinationHealthy;
@@ -29726,7 +30029,8 @@ function createLeadCoordinationRuntime(host) {
29726
30029
  role: activeRole() === "manager" ? "manager" : "lead",
29727
30030
  instanceId: host.leadInstanceId(),
29728
30031
  piSessionId: leadRuntime.leadContext?.sessionManager.getSessionId() ?? "",
29729
- updatedAt: Date.now()
30032
+ updatedAt: Date.now(),
30033
+ ...attestation && attestation.assignmentId === leadRuntime.leadContext?.sessionManager.getSessionId() && attestation.generation === host.leadInstanceId() ? { startupAttestation: attestation } : {}
29730
30034
  });
29731
30035
  leadCoordinationHealthy = true;
29732
30036
  if (!wasHealthy && leadRuntime.leadContext)
@@ -31498,6 +31802,7 @@ ${receivedRefs.join("\n")}` : ""}`,
31498
31802
  return {
31499
31803
  persistCoordinatorState,
31500
31804
  persistLeadCoordination,
31805
+ invalidateStartupCoordinationState: (sessionId) => host.invalidateLeadCoordinationState(supervisionRuntime2(), sessionId),
31501
31806
  removePeerPresence,
31502
31807
  markLeadCoordinationUnhealthy,
31503
31808
  schedulePeerPresence,
@@ -31531,6 +31836,13 @@ ${receivedRefs.join("\n")}` : ""}`,
31531
31836
 
31532
31837
  // extension/lead-runtime.ts
31533
31838
  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}$/;
31839
+ function assertManagedLeadModelRestored(saved, actual, explicitModelOverride = false) {
31840
+ if (explicitModelOverride) return;
31841
+ if (!actual || actual.provider !== saved.provider || actual.modelId !== saved.modelId)
31842
+ throw new Error(
31843
+ `Managed Lead model restoration failed: saved model ${saved.provider}/${saved.modelId} was not restored; Pi selected ${actual ? `${actual.provider}/${actual.modelId}` : "no model"}.`
31844
+ );
31845
+ }
31534
31846
  function createLeadRuntimeState() {
31535
31847
  return {
31536
31848
  instanceId: randomUUID16(),
@@ -31782,6 +32094,14 @@ function createLeadSessionStartRuntime(host) {
31782
32094
  host.roleTransitions.finalizeOptionalManagerStartup(ctx);
31783
32095
  if (!leadStateRestored && !malformedRole && host.roleTransitions.canRestoreChiefState() && !host.roleTransitions.restoreChiefState(ctx))
31784
32096
  malformedRole = true;
32097
+ try {
32098
+ await host.verifyManagedLeadModelRestoration?.(ctx, sessionSignal);
32099
+ } catch (error2) {
32100
+ await host.failClosedRole(ctx, error2);
32101
+ host.setLeadExecutionPending(false);
32102
+ return;
32103
+ }
32104
+ if (sessionSignal.aborted) return;
31785
32105
  if (malformedRole) host.roleTransitions.suspendMalformedRole(ctx);
31786
32106
  if (host.roleTransitions.shouldRestoreChief(persistedRole)) {
31787
32107
  try {
@@ -31935,6 +32255,13 @@ function createLeadAgentEventRuntime(host) {
31935
32255
  const message = await host.prepareSupervisionMessage(ctx);
31936
32256
  if (message) host.sendMessage(message);
31937
32257
  await host.drainRetirementNotices(ctx, true);
32258
+ try {
32259
+ host.reconcileRoleTools?.();
32260
+ } catch (error2) {
32261
+ host.setActiveTools([]);
32262
+ throw error2;
32263
+ }
32264
+ sections.pi_herdsman_role = host.roleCharter(ctx);
31938
32265
  return;
31939
32266
  }
31940
32267
  const activeLead = host.isActiveLead() && !host.isRoleSuspended();
@@ -31966,14 +32293,39 @@ This is the session-start definition snapshot. Use list_agents for live Agent st
31966
32293
  });
31967
32294
  }
31968
32295
  },
32296
+ turnEnd() {
32297
+ if (!host.isActiveManager() || host.isRoleSuspended()) return;
32298
+ try {
32299
+ host.reconcileRoleTools?.();
32300
+ } catch (error2) {
32301
+ host.setActiveTools([]);
32302
+ throw error2;
32303
+ }
32304
+ },
31969
32305
  toolCall(event, ctx) {
31970
- if (!host.isCurrentChief(ctx) || (host.currentChiefAllowedTools(ctx) ?? host.chiefTools).includes(
31971
- event.toolName
31972
- ))
31973
- return void 0;
32306
+ if (host.isCurrentChief(ctx)) {
32307
+ if ((host.currentChiefAllowedTools(ctx) ?? host.chiefTools).includes(
32308
+ event.toolName
32309
+ ))
32310
+ return void 0;
32311
+ return {
32312
+ block: true,
32313
+ reason: "Tool is unavailable in the active Chief profile."
32314
+ };
32315
+ }
32316
+ if (!host.isActiveManager()) return void 0;
32317
+ try {
32318
+ if ((host.currentManagerAllowedTools?.(ctx) ?? host.managerTools ?? []).includes(event.toolName))
32319
+ return void 0;
32320
+ } catch {
32321
+ return {
32322
+ block: true,
32323
+ reason: "Manager tool authorization is unavailable."
32324
+ };
32325
+ }
31974
32326
  return {
31975
32327
  block: true,
31976
- reason: "Tool is unavailable in the active Chief profile."
32328
+ reason: "Tool is unavailable in the active Manager profile."
31977
32329
  };
31978
32330
  }
31979
32331
  };
@@ -32014,10 +32366,7 @@ function registerLeadRuntime(pi, options) {
32014
32366
  return {
32015
32367
  role: role2,
32016
32368
  definition: prepared,
32017
- tools: leadToolState.projectRoleTools(baseline, prepared, [
32018
- ...role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools,
32019
- ...supervisoryAgentTools(ctx, prepared)
32020
- ]),
32369
+ baseline,
32021
32370
  sessionId: ctx.sessionManager.getSessionId(),
32022
32371
  valid: true
32023
32372
  };
@@ -32030,10 +32379,7 @@ function registerLeadRuntime(pi, options) {
32030
32379
  frontmatter: {},
32031
32380
  body: ""
32032
32381
  },
32033
- tools: leadToolState.appendRegisteredTools(
32034
- [],
32035
- role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools
32036
- ),
32382
+ baseline: [],
32037
32383
  sessionId: ctx.sessionManager.getSessionId(),
32038
32384
  valid: false
32039
32385
  });
@@ -32167,7 +32513,16 @@ function registerLeadRuntime(pi, options) {
32167
32513
  return policy === "all" || policy.size > 0;
32168
32514
  })
32169
32515
  );
32170
- const tools = profile.tools.filter(
32516
+ const required = [
32517
+ ...role2 === "manager" ? options.roleTransitionHost.managerTools : options.roleTransitionHost.chiefTools,
32518
+ ...supervisoryAgentTools(ctx, profile.definition)
32519
+ ];
32520
+ const projected = leadToolState.projectRoleTools(
32521
+ profile.baseline,
32522
+ profile.definition,
32523
+ required
32524
+ );
32525
+ const tools = projected.filter(
32171
32526
  (name) => !AGENT_COORDINATION_TOOLS.includes(name) || permitted.has(name)
32172
32527
  );
32173
32528
  for (const name of permitted) if (!tools.includes(name)) tools.push(name);
@@ -33236,6 +33591,7 @@ function registerLeadRuntime(pi, options) {
33236
33591
  sessionKind = identity;
33237
33592
  managedLifecycle = "unavailable";
33238
33593
  options.sessionStartOptions.appendRoleError(ctx, error2);
33594
+ options.sessionStartOptions.afterManagedSessionIdentityInitialized?.();
33239
33595
  return;
33240
33596
  }
33241
33597
  assignment = scope ? roleTransitions.projectAssignmentForScope(scope, sessionId) : void 0;
@@ -33263,6 +33619,8 @@ function registerLeadRuntime(pi, options) {
33263
33619
  persistLeadExecution(mode, []);
33264
33620
  }
33265
33621
  managedLifecycle = assignment ? "assigned" : "unavailable";
33622
+ if (resolved.kind === "managed")
33623
+ options.sessionStartOptions.afterManagedSessionIdentityInitialized?.();
33266
33624
  };
33267
33625
  const currentProjectAssignment = async (ctx) => {
33268
33626
  if (!sessionKind || sessionKind.sessionId !== ctx.sessionManager.getSessionId())
@@ -33413,6 +33771,45 @@ function registerLeadRuntime(pi, options) {
33413
33771
  )
33414
33772
  };
33415
33773
  };
33774
+ const managedLeadDefinition = (ctx) => options.commandHost.discoverRoleDefinition(
33775
+ MANAGED_LEAD_DEFINITION_NAME,
33776
+ ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33777
+ );
33778
+ const verifyManagedLeadModelRestoration = async (ctx, signal) => {
33779
+ if (sessionKind?.kind !== "managed") return;
33780
+ coordinationRuntime.invalidateStartupCoordinationState(
33781
+ ctx.sessionManager.getSessionId()
33782
+ );
33783
+ const definition = managedLeadDefinition(ctx);
33784
+ if (signal.aborted) return;
33785
+ const saved = resolveSavedSessionModelSelection(
33786
+ ctx.sessionManager,
33787
+ (provider, modelId) => ctx.modelRegistry.find(provider, modelId)
33788
+ );
33789
+ const explicitModelOverride = configuredModel(definition.frontmatter) !== void 0;
33790
+ if (saved.kind === "unresolved" && !explicitModelOverride)
33791
+ throw new Error(
33792
+ `Managed Lead model restoration failed: saved selection is ambiguous (${saved.candidates.map(({ provider, modelId }) => `${provider}/${modelId}`).join(" vs ")}).`
33793
+ );
33794
+ if (saved.kind === "resolved") {
33795
+ const actual = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
33796
+ assertManagedLeadModelRestored(
33797
+ saved.model,
33798
+ actual,
33799
+ explicitModelOverride
33800
+ );
33801
+ }
33802
+ const startupAttestation = {
33803
+ kind: "model_restore",
33804
+ assignmentId: ctx.sessionManager.getSessionId(),
33805
+ generation: leadRuntime.instanceId,
33806
+ result: explicitModelOverride ? "definition_override" : saved.kind === "none" ? "no_saved_model" : "verified"
33807
+ };
33808
+ if (!coordinationRuntime.persistCoordinatorState(startupAttestation))
33809
+ throw new Error(
33810
+ "Managed Lead model restoration was verified, but its fresh startup attestation could not be published"
33811
+ );
33812
+ };
33416
33813
  const prepareLeadExecution = async (ctx, signal, skipProfileResolution = false, skipAssignmentLookup = false, roleDefinitions) => {
33417
33814
  if (signal.aborted) return;
33418
33815
  const currentBaseline = () => leadToolState.getLeadTools() ?? leadToolState.normalizeBaseTools(pi.getActiveTools());
@@ -33467,10 +33864,7 @@ function registerLeadRuntime(pi, options) {
33467
33864
  persistLeadExecution(mode, baseline);
33468
33865
  if (sessionKind?.kind === "managed") {
33469
33866
  try {
33470
- const definition = options.commandHost.discoverRoleDefinition(
33471
- MANAGED_LEAD_DEFINITION_NAME,
33472
- ctx.isProjectTrusted() ? { projectRoot: ctx.cwd } : {}
33473
- );
33867
+ const definition = managedLeadDefinition(ctx);
33474
33868
  if (signal.aborted) return;
33475
33869
  leadExecution = { mode, definition, valid: true, managed: true };
33476
33870
  } catch (error2) {
@@ -33668,6 +34062,7 @@ function registerLeadRuntime(pi, options) {
33668
34062
  };
33669
34063
  },
33670
34064
  initializeSessionKind,
34065
+ verifyManagedLeadModelRestoration,
33671
34066
  quarantineNativeAgentRestore: (ctx) => {
33672
34067
  quarantinedSessionId = ctx.sessionManager.getSessionId();
33673
34068
  roleTransitions.suspendMalformedRole(ctx);
@@ -33769,10 +34164,12 @@ This session belongs to a managed Agent restored without its authorized launch c
33769
34164
  if (!options.hasPane()) return;
33770
34165
  options.queueLeadPresentation(ctx, event?.name ?? options.sessionName());
33771
34166
  });
33772
- pi.on("turn_end", (event, ctx) => {
34167
+ pi.on("turn_end", async (event, ctx) => {
33773
34168
  if (isQuarantinedSession(ctx)) return;
33774
34169
  if (activeLeadRole(leadRuntime) === "lead" || herdRunRuntime.hasActiveTurn())
33775
34170
  herdRunRuntime.turnEnd(event);
34171
+ if (activeLeadRole(leadRuntime) === "manager" && !leadRuntime.roleSuspended)
34172
+ agentEvents.turnEnd();
33776
34173
  options.queueLeadPresentation(ctx);
33777
34174
  });
33778
34175
  pi.on(
@@ -33818,7 +34215,10 @@ This session belongs to a managed Agent restored without its authorized launch c
33818
34215
  lifecycle: managedLifecycle
33819
34216
  } : { managed: false, mode: leadExecution?.mode ?? "flexible" },
33820
34217
  supervisoryProfileBody: (ctx, role2) => currentSupervisoryProfile(ctx, role2)?.valid ? currentSupervisoryProfile(ctx, role2).definition.body : "",
33821
- currentChiefAllowedTools: (ctx) => supervisoryTools(ctx, "chief")
34218
+ currentChiefAllowedTools: (ctx) => supervisoryTools(ctx, "chief"),
34219
+ currentManagerAllowedTools: (ctx) => supervisoryTools(ctx, "manager"),
34220
+ reconcileRoleTools: () => roleTransitions.reconcileRoleTools(),
34221
+ managerTools: [...options.roleTransitionHost.managerTools]
33822
34222
  };
33823
34223
  }
33824
34224
  function createLeadIdentityRuntime(host) {
@@ -39744,6 +40144,9 @@ No active Herdsman role is verified for this Pi session.`;
39744
40144
  },
39745
40145
  supervisoryProfileBody: (ctx, role2) => leadRuntimes.supervisoryProfileBody(ctx, role2),
39746
40146
  currentChiefAllowedTools: (ctx) => leadRuntimes.currentChiefAllowedTools(ctx),
40147
+ currentManagerAllowedTools: (ctx) => leadRuntimes.currentManagerAllowedTools(ctx),
40148
+ reconcileRoleTools: () => leadRuntimes.roleTransitions.reconcileRoleTools(),
40149
+ managerTools: MANAGER_TOOLS,
39747
40150
  isActiveManager: () => activeRole() === "manager" && !leadRuntime.roleSuspended,
39748
40151
  isActiveLead: () => activeRole() === "lead",
39749
40152
  prepareLeadSupervisorStateMessage: (ctx) => leadRuntimes.coordinationRuntime.prepareLeadSupervisorStateMessage(
@@ -39932,6 +40335,7 @@ ${summary}`,
39932
40335
  formatMessageLimit,
39933
40336
  validByteLimit,
39934
40337
  validStatusWidgetMaxRows,
40338
+ validMaxAgentDepth,
39935
40339
  input: (ctx, label) => ctx.ui.input(label),
39936
40340
  updateSpawnPlacement: (placement) => updateConfig("spawnPlacement", placement),
39937
40341
  updateMessageLimit: (key, value2) => updateConfig(key, value2),
@@ -40373,6 +40777,7 @@ ${summary}`,
40373
40777
  appendRoleError: (ctx, error2) => appendDurableError(pi, ctx, "pi_herdsman_role_error", error2)
40374
40778
  };
40375
40779
  const sessionStartOptions = {
40780
+ afterManagedSessionIdentityInitialized: lockHooks?.afterManagedSessionIdentityInitialized,
40376
40781
  rejectNativeAgentRestore: (ctx) => {
40377
40782
  const sessionId = ctx.sessionManager.getSessionId();
40378
40783
  try {