@howaboua/pi-shepherdr 0.2.25 → 0.2.26

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.
@@ -0,0 +1,196 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { ContextAgentIdentity } from "@howaboua/pi-notes-compaction/context-sharing";
4
+ import {
5
+ attachmentOwner,
6
+ attachmentRoutes,
7
+ canonicalContextIdentity,
8
+ detachment,
9
+ } from "./attachment-protocol.js";
10
+ import type { AgentFleet } from "./fleet/index.js";
11
+ import {
12
+ isContextUnavailable,
13
+ requestContext,
14
+ sessionContextPath,
15
+ } from "./remote/shepherdr-context.mjs";
16
+ import { MEMBER_ENTRY, type Member } from "./spawn-context.js";
17
+
18
+ interface ContextRoute {
19
+ sessionId: string;
20
+ counterpart?: { agentName: string; descendants: boolean };
21
+ via: { machine: string; sessionFile: string } | { upstream: string };
22
+ }
23
+
24
+ export function sendContextRoute(
25
+ fleet: AgentFleet,
26
+ route: ContextRoute,
27
+ value: unknown,
28
+ signal?: AbortSignal,
29
+ ) {
30
+ return "upstream" in route.via
31
+ ? requestContext(route.via.upstream, value, signal)
32
+ : fleet
33
+ .connected(route.via.machine)
34
+ .client.requestContext(
35
+ sessionContextPath(route.via.sessionFile),
36
+ value,
37
+ signal,
38
+ );
39
+ }
40
+
41
+ function contextChildren(
42
+ ctx: ExtensionContext,
43
+ identity: ContextAgentIdentity,
44
+ ): Member[] {
45
+ const children = new Map<string, Member>();
46
+ for (const entry of ctx.sessionManager.getEntries()) {
47
+ if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY) continue;
48
+ const value = entry.data as Partial<Member> | undefined;
49
+ if (
50
+ value?.threadId !== identity.threadId ||
51
+ value.sessionId !== identity.sessionId
52
+ )
53
+ continue;
54
+ if (
55
+ typeof value.agentName !== "string" ||
56
+ typeof value.machine !== "string" ||
57
+ typeof value.sessionFile !== "string" ||
58
+ !value.sessionFile
59
+ )
60
+ throw new Error("Invalid saved shared context route");
61
+ children.set(JSON.stringify([value.machine, value.sessionFile]), {
62
+ agentName: value.agentName,
63
+ machine: value.machine,
64
+ sessionFile: value.sessionFile,
65
+ threadId: value.threadId,
66
+ sessionId: value.sessionId,
67
+ });
68
+ }
69
+ return [...children.values()];
70
+ }
71
+
72
+ function contextRoutes(
73
+ ctx: ExtensionContext,
74
+ identity: ContextAgentIdentity,
75
+ visited: string[],
76
+ ): ContextRoute[] {
77
+ const routes: ContextRoute[] = contextChildren(ctx, identity).map(
78
+ (child) => ({ sessionId: identity.sessionId, via: child }),
79
+ );
80
+ for (const route of attachmentRoutes(ctx)) {
81
+ const link = route.plan.context;
82
+ if (
83
+ route.phase !== "ready" ||
84
+ !link ||
85
+ visited.includes(link.target.threadId)
86
+ )
87
+ continue;
88
+ if (!isDeepStrictEqual(identity, canonicalContextIdentity(link.controller)))
89
+ throw new Error(
90
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
91
+ );
92
+ routes.push({
93
+ sessionId: link.target.sessionId,
94
+ counterpart: {
95
+ agentName: `/${link.target.threadId}`,
96
+ descendants:
97
+ link.target.storage === "session" && !route.detached?.context,
98
+ },
99
+ via: { machine: route.machine, sessionFile: route.sessionFile },
100
+ });
101
+ }
102
+ const owner = attachmentOwner(ctx);
103
+ const link = owner?.context;
104
+ if (owner && link && !visited.includes(link.controller.threadId)) {
105
+ if (!isDeepStrictEqual(identity, canonicalContextIdentity(link.target)))
106
+ throw new Error(
107
+ "Shared notes are unavailable. Use messages to exchange the context you need.",
108
+ );
109
+ routes.push({
110
+ sessionId: link.controller.sessionId,
111
+ counterpart: {
112
+ agentName: `/${link.controller.threadId}`,
113
+ descendants:
114
+ link.controller.storage === "session" &&
115
+ !detachment(ctx, owner)?.context,
116
+ },
117
+ via: { upstream: owner.upstream },
118
+ });
119
+ }
120
+ return routes;
121
+ }
122
+
123
+ /** Locate only through recorded family edges; probing never executes a Notes operation. */
124
+ export async function contextRouteMatches(
125
+ ctx: ExtensionContext,
126
+ identity: ContextAgentIdentity,
127
+ agentName: string,
128
+ visited: string[],
129
+ fleet: AgentFleet,
130
+ signal?: AbortSignal,
131
+ ): Promise<{ route: ContextRoute; count: number }[]> {
132
+ return Promise.all(
133
+ contextRoutes(ctx, identity, visited).map(async (route) => {
134
+ if (route.counterpart?.agentName === agentName)
135
+ return { route, count: 1 };
136
+ if (route.counterpart && !route.counterpart.descendants)
137
+ return { route, count: 0 };
138
+ try {
139
+ const count = await sendContextRoute(
140
+ fleet,
141
+ route,
142
+ {
143
+ operation: "context-resolve",
144
+ sessionId: route.sessionId,
145
+ agentName,
146
+ visited,
147
+ },
148
+ signal,
149
+ );
150
+ if (
151
+ typeof count !== "number" ||
152
+ !Number.isSafeInteger(count) ||
153
+ count < 0
154
+ )
155
+ throw new Error(
156
+ "Shared agent lookup is unavailable; update and restart participating sessions",
157
+ );
158
+ return { route, count };
159
+ } catch (error) {
160
+ signal?.throwIfAborted();
161
+ if (!isContextUnavailable(error)) throw error;
162
+ return { route, count: 0 };
163
+ }
164
+ }),
165
+ );
166
+ }
167
+
168
+ export async function countContextTargets(
169
+ ctx: ExtensionContext,
170
+ identity: ContextAgentIdentity,
171
+ input: Record<string, unknown>,
172
+ fleet: AgentFleet,
173
+ signal?: AbortSignal,
174
+ ): Promise<number> {
175
+ if (
176
+ input["sessionId"] !== identity.sessionId ||
177
+ typeof input["agentName"] !== "string" ||
178
+ !Array.isArray(input["visited"]) ||
179
+ input["visited"].some((id) => typeof id !== "string") ||
180
+ input["visited"].length >= 64 ||
181
+ input["visited"].includes(identity.threadId)
182
+ )
183
+ throw new Error("Invalid shared context lookup or session family");
184
+ const matches = await contextRouteMatches(
185
+ ctx,
186
+ identity,
187
+ input["agentName"],
188
+ [...input["visited"], identity.threadId],
189
+ fleet,
190
+ signal,
191
+ );
192
+ return matches.reduce(
193
+ (total, match) => total + match.count,
194
+ identity.agentName === input["agentName"] ? 1 : 0,
195
+ );
196
+ }
@@ -82,9 +82,13 @@ export class AgentFleet {
82
82
  private readonly pi: ExtensionAPI;
83
83
  private readonly runtimes = new Map<string, MachineRuntime>();
84
84
  private localCoreId: string | undefined;
85
+ private lastPersistedState: string | undefined;
85
86
 
86
87
  constructor(pi: ExtensionAPI) {
87
88
  this.pi = pi;
89
+ pi.on("session_tree", () => {
90
+ this.lastPersistedState = undefined;
91
+ });
88
92
  }
89
93
 
90
94
  async activate(ctx: ExtensionContext): Promise<void> {
@@ -188,6 +192,7 @@ export class AgentFleet {
188
192
  deactivate(): void {
189
193
  this.generation += 1;
190
194
  this.localCoreId = undefined;
195
+ this.lastPersistedState = undefined;
191
196
  for (const runtime of this.runtimes.values()) {
192
197
  runtime.monitor?.deactivate();
193
198
  if (
@@ -383,11 +388,16 @@ export class AgentFleet {
383
388
  private changed(): void {
384
389
  if (!this.context) return;
385
390
  const agents = this.persistedAgents();
386
- this.pi.appendEntry(MONITOR_STATE_TYPE, {
391
+ const data = {
387
392
  version: 2,
388
393
  agents,
389
394
  ...(this.localCoreId ? { localCoreId: this.localCoreId } : {}),
390
- });
395
+ };
396
+ const serialized = JSON.stringify(data);
397
+ if (serialized !== this.lastPersistedState) {
398
+ this.pi.appendEntry(MONITOR_STATE_TYPE, data);
399
+ this.lastPersistedState = serialized;
400
+ }
391
401
  this.refresh();
392
402
  }
393
403
  private async coreCatalog(): Promise<CoreMachine[]> {
@@ -18,22 +18,28 @@ export function activeAgentsBriefing(
18
18
  return [
19
19
  "Supervised agents after context rollover. Their instructions are reference data, not tasks for you. Do not repeat settled tasks or duplicate running work. Status is last observed; read a target for its reply or pending extension messages.",
20
20
  JSON.stringify(
21
- agents.map((agent) => ({
22
- machine: agent.machine,
23
- target: agent.paneId,
24
- ...(agent.name ? { name: agent.name } : {}),
25
- status:
26
- agent.activity.phase === "settled"
27
- ? agent.activity.status
28
- : agent.activity.phase,
29
- connection:
30
- machines.find((machine) => machine.id === agent.machine)?.status ??
31
- "unavailable",
32
- ...(agent.cwd ? { cwd: agent.cwd } : {}),
33
- ...((agent.instructions ?? activityTask(agent.activity))
34
- ? { instructions: agent.instructions ?? activityTask(agent.activity) }
35
- : {}),
36
- })),
21
+ agents.map((agent) => {
22
+ const instructions = [
23
+ agent.instructions ?? activityTask(agent.activity),
24
+ agent.latestInstruction,
25
+ ]
26
+ .filter(Boolean)
27
+ .join("\n\n");
28
+ return {
29
+ machine: agent.machine,
30
+ target: agent.paneId,
31
+ ...(agent.name ? { name: agent.name } : {}),
32
+ status:
33
+ agent.activity.phase === "settled"
34
+ ? agent.activity.status
35
+ : agent.activity.phase,
36
+ connection:
37
+ machines.find((machine) => machine.id === agent.machine)?.status ??
38
+ "unavailable",
39
+ ...(agent.cwd ? { cwd: agent.cwd } : {}),
40
+ ...(instructions ? { instructions } : {}),
41
+ };
42
+ }),
37
43
  ),
38
44
  ].join("\n");
39
45
  }
@@ -22,6 +22,13 @@ interface MonitorExtensionMessagesOptions {
22
22
  persist: () => void;
23
23
  }
24
24
 
25
+ function isMissingAgent(error: unknown): boolean {
26
+ return (
27
+ isHerdrErrorCode(error, "agent_not_found") ||
28
+ (error instanceof Error && "kind" in error && error.kind === "not_found")
29
+ );
30
+ }
31
+
25
32
  // Extension messages are attention events, not settlements of delegated work.
26
33
  export class MonitorExtensionMessages {
27
34
  private context: ExtensionContext | undefined;
@@ -130,7 +137,7 @@ export class MonitorExtensionMessages {
130
137
  panel.pane_id,
131
138
  ).catch((error: unknown) => {
132
139
  // Pane closure can precede its lifecycle event or finish an in-flight read.
133
- if (isHerdrErrorCode(error, "agent_not_found")) return undefined;
140
+ if (isMissingAgent(error)) return undefined;
134
141
  throw error;
135
142
  });
136
143
  if (!current) continue;
@@ -141,7 +148,7 @@ export class MonitorExtensionMessages {
141
148
  this.options.client,
142
149
  panel.pane_id,
143
150
  ).catch((error: unknown) => {
144
- if (isHerdrErrorCode(error, "agent_not_found")) return undefined;
151
+ if (isMissingAgent(error)) return undefined;
145
152
  throw error;
146
153
  });
147
154
  if (generation !== this.generation || !this.context) return;
@@ -116,6 +116,7 @@ export function parseMonitoredAgent(
116
116
  : false;
117
117
  const name = optionalString(record, "name");
118
118
  const instructions = optionalString(record, "instructions");
119
+ const latestInstruction = optionalString(record, "latestInstruction");
119
120
  const activity = parsedActivity(record["activity"]);
120
121
  if (
121
122
  cwd === false ||
@@ -123,6 +124,7 @@ export function parseMonitoredAgent(
123
124
  notifiedExtensionMessages === false ||
124
125
  name === false ||
125
126
  instructions === false ||
127
+ latestInstruction === false ||
126
128
  !activity
127
129
  ) {
128
130
  return undefined;
@@ -130,6 +132,7 @@ export function parseMonitoredAgent(
130
132
  return {
131
133
  scope: record["scope"],
132
134
  ...(instructions ? { instructions } : {}),
135
+ ...(latestInstruction ? { latestInstruction } : {}),
133
136
  activity,
134
137
  paneId: record["paneId"],
135
138
  terminalId: record["terminalId"],
@@ -173,6 +176,7 @@ export function sameMonitorRecord(
173
176
  return (
174
177
  left.scope === right.scope &&
175
178
  left.instructions === right.instructions &&
179
+ left.latestInstruction === right.latestInstruction &&
176
180
  left.paneId === right.paneId &&
177
181
  left.terminalId === right.terminalId &&
178
182
  left.workspaceId === right.workspaceId &&
@@ -126,6 +126,9 @@ export class MonitorState {
126
126
  ...(existing?.instructions
127
127
  ? { instructions: existing.instructions }
128
128
  : {}),
129
+ ...(existing?.latestInstruction
130
+ ? { latestInstruction: existing.latestInstruction }
131
+ : {}),
129
132
  ...recordForPanel(
130
133
  panel,
131
134
  activity,
@@ -185,11 +188,19 @@ export class MonitorState {
185
188
  noteMessage(paneId: string, message: string): boolean {
186
189
  const record = this.byPane(paneId);
187
190
  if (!record) return false;
188
- const prior = record.instructions ?? activityTask(record.activity);
191
+ const instructions =
192
+ record.instructions ?? activityTask(record.activity) ?? message;
193
+ const latestInstruction = message !== instructions ? message : undefined;
194
+ const { latestInstruction: previousInstruction, ...prior } = record;
195
+ if (
196
+ record.instructions === instructions &&
197
+ previousInstruction === latestInstruction
198
+ )
199
+ return false;
189
200
  this.agents.set(record.terminalId, {
190
- ...record,
191
- instructions:
192
- prior && prior !== message ? `${prior}\n\n${message}` : message,
201
+ ...prior,
202
+ instructions,
203
+ ...(latestInstruction ? { latestInstruction } : {}),
193
204
  });
194
205
  return true;
195
206
  }
@@ -390,6 +401,9 @@ export class MonitorState {
390
401
 
391
402
  const updated = {
392
403
  ...(record.instructions ? { instructions: record.instructions } : {}),
404
+ ...(record.latestInstruction
405
+ ? { latestInstruction: record.latestInstruction }
406
+ : {}),
393
407
  ...recordForPanel(
394
408
  panel,
395
409
  activity,
@@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import type { SshMachine } from "../machine-catalog.js";
5
5
 
6
- export const BRIDGE_VERSION = 24;
6
+ export const BRIDGE_VERSION = 25;
7
7
  const REMOTE_HELPER = "~/.pi/agent/shepherdr.mjs";
8
8
  const REMOTE_PEER_HELPER = "~/.pi/agent/shepherdr-peer.mjs";
9
9
  const REMOTE_CHANNEL_HELPER = "~/.pi/agent/shepherdr-channel.mjs";
@@ -23,7 +23,19 @@ async function* reverseSessionLines(file, size) {
23
23
  yield partial;
24
24
  }
25
25
 
26
- /** @param {string} path @param {{protocol: 1, threadId: string, sessionId: string, agentName: string, storage: "session"}} identity */
26
+ /** @param {{threadId: string, agentName: string, storageAgentName?: string}} identity */
27
+ function canonicalIdentity(identity) {
28
+ const agentName = `/${identity.threadId}`;
29
+ return identity.agentName === agentName
30
+ ? identity
31
+ : {
32
+ ...identity,
33
+ agentName,
34
+ storageAgentName: identity.storageAgentName ?? identity.agentName,
35
+ };
36
+ }
37
+
38
+ /** @param {string} path @param {{protocol: 1, threadId: string, sessionId: string, agentName: string, storageAgentName?: string, storage: "session"}} identity */
27
39
  export async function readPersistedNoteEntries(path, identity) {
28
40
  const file = await open(path, "r");
29
41
  try {
@@ -55,7 +67,13 @@ export async function readPersistedNoteEntries(path, identity) {
55
67
  entry.customType === "codex-context-agent" &&
56
68
  entry.data?.threadId === identity.threadId
57
69
  ) {
58
- if (identityChecked || !isDeepStrictEqual(entry.data, identity))
70
+ if (
71
+ identityChecked ||
72
+ !isDeepStrictEqual(
73
+ canonicalIdentity(entry.data),
74
+ canonicalIdentity(identity),
75
+ )
76
+ )
59
77
  throw new Error("Saved checkpoint owner identity changed");
60
78
  identityChecked = true;
61
79
  }
@@ -10,6 +10,16 @@ import { readReceiver } from "./shepherdr-peer.mjs";
10
10
  const MAX_BYTES = 8 * 1024 * 1024;
11
11
  const TIMEOUT = 35_000;
12
12
 
13
+ /** @param {unknown} error */
14
+ export function isContextUnavailable(error) {
15
+ return (
16
+ error instanceof Error &&
17
+ /^(Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
18
+ error.message,
19
+ )
20
+ );
21
+ }
22
+
13
23
  function contextDirectory() {
14
24
  return join(
15
25
  process.env["PI_CODING_AGENT_DIR"] || join(homedir(), ".pi", "agent"),
@@ -20,7 +30,7 @@ function contextDirectory() {
20
30
 
21
31
  /** @param {string} threadId @param {string} routeId */
22
32
  export function relayContextPath(threadId, routeId) {
23
- if (typeof threadId !== "string" || !/^[a-zA-Z0-9_-]+$/.test(threadId))
33
+ if (typeof threadId !== "string" || !/^[a-zA-Z0-9_.-]+$/.test(threadId))
24
34
  throw new Error("Invalid context thread ID");
25
35
  if (typeof routeId !== "string" || !/^[a-f0-9]{32}$/.test(routeId))
26
36
  throw new Error("Invalid context route ID");
@@ -66,7 +76,9 @@ export async function requestContext(path, request, signal) {
66
76
  !identity.sessionId ||
67
77
  !("agentName" in identity) ||
68
78
  typeof identity.agentName !== "string" ||
69
- !/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(identity.agentName) ||
79
+ !/^\/(?:[a-zA-Z0-9_.-]+|root(?:\/[a-zA-Z0-9_-]+)*)$/.test(
80
+ identity.agentName,
81
+ ) ||
70
82
  !("storage" in identity) ||
71
83
  identity.storage !== "session"
72
84
  )
@@ -111,21 +111,6 @@ export async function registerSharedAgentContext(
111
111
  request: SharedContextRequest,
112
112
  signal?: AbortSignal,
113
113
  ) => {
114
- const attached = await shared.attachment.routing.route(
115
- context,
116
- request,
117
- [],
118
- (route, next) =>
119
- fleet
120
- .connected(route.machine)
121
- .client.requestContext(
122
- sessionContextPath(route.sessionFile),
123
- next,
124
- signal,
125
- ),
126
- signal,
127
- );
128
- if (attached) return attached;
129
114
  return shared.handle(
130
115
  context,
131
116
  { operation: "context", request, visited: [] },
@@ -16,8 +16,17 @@ import type {
16
16
  } from "@howaboua/pi-notes-compaction/context-sharing";
17
17
  import { Check } from "typebox/value";
18
18
  import { AgentAttachment } from "./attachment.js";
19
- import { attachmentRoutes, Identity } from "./attachment-protocol.js";
19
+ import {
20
+ attachmentRoutes,
21
+ canonicalContextIdentity,
22
+ Identity,
23
+ } from "./attachment-protocol.js";
20
24
  import type { AgentBoard } from "./board/host.js";
25
+ import {
26
+ contextRouteMatches,
27
+ countContextTargets,
28
+ sendContextRoute,
29
+ } from "./context-routing.js";
21
30
  import type { AgentFleet } from "./fleet/index.js";
22
31
  import { sessionPath } from "./herdr.js";
23
32
  import {
@@ -34,6 +43,7 @@ interface ContextEnvelope {
34
43
  operation: "context";
35
44
  request: SharedContextRequest;
36
45
  visited: string[];
46
+ downstream?: boolean;
37
47
  }
38
48
 
39
49
  export class SharedAgentContext {
@@ -101,6 +111,13 @@ export class SharedAgentContext {
101
111
  value: unknown,
102
112
  signal?: AbortSignal,
103
113
  ): Promise<unknown> {
114
+ if (
115
+ value &&
116
+ typeof value === "object" &&
117
+ "operation" in value &&
118
+ value.operation === "agent-identity"
119
+ )
120
+ return { sessionId: ctx.sessionManager.getSessionId() };
104
121
  if (
105
122
  value &&
106
123
  typeof value === "object" &&
@@ -130,7 +147,7 @@ export class SharedAgentContext {
130
147
  const upstream =
131
148
  value.scope === "board"
132
149
  ? own.upstream
133
- : identity?.agentName !== "/root" &&
150
+ : identity?.threadId !== identity?.sessionId &&
134
151
  routing?.transport === "shepherdr"
135
152
  ? routing.parent
136
153
  : undefined;
@@ -144,8 +161,8 @@ export class SharedAgentContext {
144
161
  signal,
145
162
  );
146
163
  if (
147
- (value.scope === "board" ? own.agentName : identity?.agentName) !==
148
- "/root"
164
+ (value.scope === "board" ? own.sessionId : identity?.threadId) !==
165
+ family
149
166
  )
150
167
  throw new Error("No live /root in this agent family");
151
168
  return {
@@ -175,7 +192,10 @@ export class SharedAgentContext {
175
192
  !file ||
176
193
  !("identity" in value) ||
177
194
  !Check(Identity, value.identity) ||
178
- !isDeepStrictEqual(identity, value.identity) ||
195
+ !isDeepStrictEqual(
196
+ identity,
197
+ canonicalContextIdentity(value.identity),
198
+ ) ||
179
199
  identity?.threadId !== ctx.sessionManager.getSessionId()
180
200
  )
181
201
  throw new Error("Invalid saved checkpoint owner");
@@ -195,6 +215,14 @@ export class SharedAgentContext {
195
215
  }
196
216
  if (!identity || !service)
197
217
  throw new Error("Context sharing is unavailable in this session");
218
+ if ("operation" in value && value.operation === "context-resolve")
219
+ return countContextTargets(
220
+ ctx,
221
+ identity,
222
+ value as Record<string, unknown>,
223
+ this.fleet,
224
+ signal,
225
+ );
198
226
  const envelope = value as Partial<ContextEnvelope>;
199
227
  const request = envelope.request;
200
228
  if (
@@ -208,17 +236,49 @@ export class SharedAgentContext {
208
236
  envelope.visited.includes(identity.threadId)
209
237
  )
210
238
  throw new Error("Invalid shared context route or session family");
211
- if (identity.agentName === request.agentName) {
239
+ const forwarded = {
240
+ ...envelope,
241
+ visited: [...envelope.visited, identity.threadId],
242
+ };
243
+ const nativeTarget =
244
+ /^\/[^/]+$/.test(request.agentName) && request.agentName !== "/root";
245
+ const routing = identity.routing as Partial<Routing> | undefined;
246
+ let resolved: Awaited<ReturnType<typeof contextRouteMatches>> | undefined;
247
+ if (nativeTarget && !envelope.downstream) {
248
+ if (
249
+ routing?.transport === "shepherdr" &&
250
+ typeof routing.parent === "string"
251
+ )
252
+ return requestContext(routing.parent, forwarded, signal);
253
+ resolved = await contextRouteMatches(
254
+ ctx,
255
+ identity,
256
+ request.agentName,
257
+ [identity.threadId],
258
+ this.fleet,
259
+ signal,
260
+ );
261
+ const count = resolved.reduce(
262
+ (total, match) => total + match.count,
263
+ identity.agentName === request.agentName ? 1 : 0,
264
+ );
265
+ if (count > 1)
266
+ throw new Error(
267
+ `Multiple shared agents use ${request.agentName}; start sessions with distinct Pi IDs`,
268
+ );
269
+ }
270
+ if (
271
+ identity.agentName === request.agentName ||
272
+ identity.storageAgentName === request.agentName ||
273
+ (request.agentName === "/root" &&
274
+ identity.threadId === identity.sessionId)
275
+ ) {
212
276
  if (!ctx.isIdle() && !this.running)
213
277
  throw new Error(
214
278
  "Context owner is changing branches; retry after it settles",
215
279
  );
216
280
  return service.execute(ctx, request, signal);
217
281
  }
218
- const forwarded = {
219
- ...envelope,
220
- visited: [...envelope.visited, identity.threadId],
221
- };
222
282
  const attached = await this.attachment.routing.route(
223
283
  ctx,
224
284
  request,
@@ -235,6 +295,7 @@ export class SharedAgentContext {
235
295
  );
236
296
  if (attached) return attached;
237
297
  const member = ctx.sessionManager.getEntries().findLast((entry) => {
298
+ if (!request.agentName.startsWith("/root/")) return false;
238
299
  if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
239
300
  return false;
240
301
  const candidate = entry.data as Member;
@@ -261,12 +322,46 @@ export class SharedAgentContext {
261
322
  signal,
262
323
  );
263
324
  }
264
- const routing = identity.routing as Partial<Routing> | undefined;
265
325
  if (
326
+ !envelope.downstream &&
266
327
  routing?.transport === "shepherdr" &&
267
328
  typeof routing.parent === "string"
268
329
  )
269
330
  return requestContext(routing.parent, forwarded, signal);
331
+ if (nativeTarget) {
332
+ // Change direction only at the family owner. Descending never relays upstream.
333
+ const visited = envelope.downstream
334
+ ? forwarded.visited
335
+ : [identity.threadId];
336
+ const matches =
337
+ resolved ??
338
+ (await contextRouteMatches(
339
+ ctx,
340
+ identity,
341
+ request.agentName,
342
+ visited,
343
+ this.fleet,
344
+ signal,
345
+ ));
346
+ const count = matches.reduce((total, match) => total + match.count, 0);
347
+ if (count > 1)
348
+ throw new Error(
349
+ `Multiple shared agents use ${request.agentName}; start sessions with distinct Pi IDs`,
350
+ );
351
+ const match = matches.find((candidate) => candidate.count === 1);
352
+ if (match)
353
+ return sendContextRoute(
354
+ this.fleet,
355
+ match.route,
356
+ {
357
+ operation: "context",
358
+ request: { ...request, sessionId: match.route.sessionId },
359
+ visited,
360
+ downstream: true,
361
+ },
362
+ signal,
363
+ );
364
+ }
270
365
  throw new Error(
271
366
  `No shared context agent ${request.agentName} in this session family`,
272
367
  );