@howaboua/pi-shepherdr 0.2.24 → 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.
Files changed (85) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +20 -12
  3. package/index.ts +2 -2
  4. package/package.json +10 -11
  5. package/src/agent-identity.ts +75 -0
  6. package/src/agents-contract.ts +20 -12
  7. package/src/agents-discovery.ts +79 -34
  8. package/src/agents-focus.ts +15 -9
  9. package/src/agents-spawn.ts +25 -7
  10. package/src/agents-tool.ts +35 -7
  11. package/src/agents-work.ts +2 -2
  12. package/src/attachment-notes.ts +25 -24
  13. package/src/attachment-protocol.ts +35 -15
  14. package/src/attachment-routing.ts +28 -24
  15. package/src/attachment-target.ts +58 -19
  16. package/src/attachment.ts +13 -17
  17. package/src/board/host.ts +19 -20
  18. package/src/board/membership.ts +49 -30
  19. package/src/close-idle.ts +89 -0
  20. package/src/context-routing.ts +196 -0
  21. package/src/control-panel/index.ts +3 -1
  22. package/src/control-panel/items.ts +14 -2
  23. package/src/control-panel/view.ts +6 -2
  24. package/src/controller.ts +11 -2
  25. package/src/core/AGENTS.md +5 -0
  26. package/src/core/backend.ts +266 -0
  27. package/src/core/client.ts +249 -0
  28. package/src/core/context-relay.mjs +111 -0
  29. package/src/core/focus-channel-helper.mjs +165 -0
  30. package/src/core/focus-channel-stream.ts +140 -0
  31. package/src/core/focus-channel-wire.mjs +160 -0
  32. package/src/core/focus-channel.ts +213 -0
  33. package/src/core/focus-window.ts +192 -0
  34. package/src/core/pi-executable.mjs +34 -0
  35. package/src/core/protocol.ts +116 -0
  36. package/src/core/registration.ts +51 -0
  37. package/src/core/remote-endpoint.ts +119 -0
  38. package/src/core/remote-exec.ts +122 -0
  39. package/src/core/remote-helper.mjs +244 -0
  40. package/src/core/remote-reader.ts +67 -0
  41. package/src/core/remote-relay.ts +191 -0
  42. package/src/core/request.ts +124 -0
  43. package/src/core/spawn.ts +177 -0
  44. package/src/core/status.ts +68 -0
  45. package/src/core/terminal.ts +103 -0
  46. package/src/fleet/catalog.ts +83 -0
  47. package/src/fleet/connection.ts +111 -0
  48. package/src/fleet/index.ts +161 -122
  49. package/src/fleet/inspection.ts +19 -1
  50. package/src/fleet/machine.ts +3 -0
  51. package/src/fleet/monitor.ts +18 -4
  52. package/src/fleet/persistence.ts +26 -3
  53. package/src/fleet/setup.ts +54 -13
  54. package/src/herdr.ts +25 -5
  55. package/src/launch-contract.ts +48 -0
  56. package/src/launch-location.ts +151 -0
  57. package/src/launch.ts +30 -183
  58. package/src/messages/attribution.ts +15 -6
  59. package/src/messages/events.ts +10 -4
  60. package/src/messages/focus.ts +11 -2
  61. package/src/messages/guidance.ts +22 -16
  62. package/src/monitor-extension-messages.ts +9 -2
  63. package/src/monitor-record.ts +13 -6
  64. package/src/monitor-state.ts +18 -4
  65. package/src/monitor.ts +31 -0
  66. package/src/peer-commands.ts +11 -0
  67. package/src/peer-inbox-delivery.ts +171 -0
  68. package/src/peer-inbox-focus.ts +113 -0
  69. package/src/peer-inbox.ts +126 -208
  70. package/src/remote/deployment.ts +1 -1
  71. package/src/remote/shepherdr-checkpoints.mjs +20 -2
  72. package/src/remote/shepherdr-context.mjs +15 -3
  73. package/src/remote/shepherdr-peer.mjs +18 -5
  74. package/src/remote/shepherdr-session.mjs +9 -2
  75. package/src/remote/shepherdr.mjs +1 -1
  76. package/src/settlement/collector.ts +2 -2
  77. package/src/settlement/index.ts +12 -0
  78. package/src/shared-context-host.ts +7 -18
  79. package/src/shared-context.ts +139 -12
  80. package/src/spawn-context.ts +10 -5
  81. package/src/spawn-ownership.ts +91 -0
  82. package/src/types.ts +10 -5
  83. package/src/worker-ownership.ts +92 -0
  84. package/src/worker-service.ts +13 -82
  85. package/changelog.ts +0 -337
package/src/attachment.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { isDeepStrictEqual } from "node:util";
3
2
  import type {
4
3
  ExtensionAPI,
@@ -14,6 +13,7 @@ import {
14
13
  type AttachmentPlan,
15
14
  attachmentOwner,
16
15
  attachmentRoutes,
16
+ canonicalContextIdentity,
17
17
  ROUTE,
18
18
  Snapshot,
19
19
  } from "./attachment-protocol.js";
@@ -97,6 +97,8 @@ export class AgentAttachment {
97
97
  "Target has different attachment choices; changing an attachment is unsupported",
98
98
  );
99
99
  let route = prior;
100
+ await runtime.prepareSharing();
101
+ await check();
100
102
  if (!route) {
101
103
  const snapshot = await runtime.client.requestContext(
102
104
  sessionContextPath(sessionFile),
@@ -121,7 +123,6 @@ export class AgentAttachment {
121
123
  const upstream = runtime.local
122
124
  ? sessionContextPath(controllerFile)
123
125
  : runtime.client.contextRelayPath();
124
- const segment = `attached-${randomUUID()}`;
125
126
  const plan: AttachmentPlan = {
126
127
  controllerSessionId,
127
128
  targetSessionId: current.sessionId,
@@ -131,8 +132,8 @@ export class AgentAttachment {
131
132
  context: {
132
133
  controller: controllerContext,
133
134
  target: current.context,
134
- alias: `${controllerContext.agentName}/${segment}`,
135
- controllerAlias: `${current.context.agentName}/controller-${randomUUID()}`,
135
+ alias: `/${current.sessionId}`,
136
+ controllerAlias: `/${controllerSessionId}`,
136
137
  ...(runtime.local ? { controllerFile } : {}),
137
138
  controllerNotes: await this.notes.export(ctx),
138
139
  targetNotes: current.notes,
@@ -146,7 +147,7 @@ export class AgentAttachment {
146
147
  desired: this.board.membership.prepareAttachment(
147
148
  ctx,
148
149
  upstream,
149
- segment,
150
+ current.sessionId,
150
151
  ),
151
152
  controller: binding(ctx),
152
153
  },
@@ -191,19 +192,11 @@ export class AgentAttachment {
191
192
  }
192
193
  return {
193
194
  attached: true,
195
+ agent: `/${route.plan.targetSessionId}`,
194
196
  machine: runtime.machine,
195
197
  target: panel.pane_id,
196
- ...(route.plan.context
197
- ? {
198
- contextAgent: route.plan.context.alias,
199
- controllerContextAgent: route.plan.context.controllerAlias,
200
- }
201
- : {}),
202
- ...(route.plan.board
203
- ? {
204
- boardAgent: route.plan.board.desired.agentName,
205
- }
206
- : {}),
198
+ context: !!route.plan.context,
199
+ board: !!route.plan.board,
207
200
  };
208
201
  }
209
202
  async detach(
@@ -246,7 +239,10 @@ export class AgentAttachment {
246
239
  )) ||
247
240
  (params.context &&
248
241
  plan.context &&
249
- !isDeepStrictEqual(currentContext, plan.context.controller)) ||
242
+ !isDeepStrictEqual(
243
+ currentContext,
244
+ canonicalContextIdentity(plan.context.controller),
245
+ )) ||
250
246
  (controllerBoard && !isDeepStrictEqual(binding(ctx), controllerBoard))
251
247
  )
252
248
  throw new Error(
package/src/board/host.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import type {
3
2
  ExtensionAPI,
4
3
  ExtensionContext,
@@ -62,22 +61,23 @@ export class AgentBoard {
62
61
  request: requestContext,
63
62
  commitDirectory: (own, directory, caller, request) =>
64
63
  this.membership.commitDirectory(own, directory, caller, request),
65
- routeNotice: (ctx, request, signal) => {
64
+ routeNotice: async (ctx, request, signal) => {
65
+ const next = request.route?.[0] ?? request.sessionId;
66
66
  const child = children(ctx).find(
67
- (entry) =>
68
- request.target === entry.binding.agentName ||
69
- request.target.startsWith(`${entry.binding.agentName}/`),
67
+ (entry) => entry.binding.sessionId === next,
68
+ );
69
+ if (!child) return false;
70
+ return fleet.connected(child.machine).client.requestContext(
71
+ sessionContextPath(child.sessionFile),
72
+ {
73
+ ...request,
74
+ ...(request.route ? { route: request.route.slice(1) } : {}),
75
+ },
76
+ signal,
70
77
  );
71
- if (!child) return Promise.resolve(false);
72
- return fleet
73
- .connected(child.machine)
74
- .client.requestContext(
75
- sessionContextPath(child.sessionFile),
76
- request,
77
- signal,
78
- );
79
78
  },
80
79
  propagateEnabled: async (ctx, enabled) => {
80
+ let boardId: string | undefined;
81
81
  await Promise.all(
82
82
  children(ctx).map(async (child) => {
83
83
  try {
@@ -85,7 +85,7 @@ export class AgentBoard {
85
85
  sessionContextPath(child.sessionFile),
86
86
  {
87
87
  operation: "board-enabled",
88
- boardId: binding(ctx).boardId,
88
+ boardId: (boardId ??= binding(ctx).boardId),
89
89
  enabled,
90
90
  },
91
91
  AbortSignal.timeout(750),
@@ -133,7 +133,7 @@ export class AgentBoard {
133
133
  async prepare(
134
134
  ctx: ExtensionContext,
135
135
  runtime: ConnectedMachine,
136
- name: string,
136
+ _name: string,
137
137
  args: readonly string[],
138
138
  ) {
139
139
  if (!this.enabled(ctx)) return undefined;
@@ -153,9 +153,7 @@ export class AgentBoard {
153
153
  throw new Error(
154
154
  "Board child binding requires a saved controller session",
155
155
  );
156
- const segment =
157
- name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "agent";
158
- const agentName = `${own.agentName}/${segment}-${randomUUID()}`;
156
+ await runtime.prepareSharing();
159
157
  const upstream = runtime.local
160
158
  ? sessionContextPath(file)
161
159
  : runtime.client.contextRelayPath();
@@ -166,7 +164,7 @@ export class AgentBoard {
166
164
  const sessionFile = sessionPath(agent);
167
165
  if (!sessionFile)
168
166
  throw new Error("Spawned agent has no native Pi session path");
169
- const prepared = { ...own, agentName, upstream };
167
+ const prepared = { ...own, upstream };
170
168
  const result = await runtime.client.requestContext(
171
169
  sessionContextPath(sessionFile),
172
170
  { operation: "board-bind", binding: prepared },
@@ -175,7 +173,8 @@ export class AgentBoard {
175
173
  if (
176
174
  adopted.boardId !== own.boardId ||
177
175
  adopted.databasePath !== own.databasePath ||
178
- adopted.agentName !== agentName ||
176
+ adopted.agentName !== `/${adopted.sessionId}` ||
177
+ adopted.parentSessionId !== own.sessionId ||
179
178
  adopted.rootSessionId !== own.rootSessionId ||
180
179
  adopted.upstream !== upstream ||
181
180
  adopted.sessionId === own.sessionId
@@ -9,6 +9,7 @@ import {
9
9
  binding,
10
10
  children,
11
11
  members,
12
+ parseBinding,
12
13
  removeMember,
13
14
  saveBinding,
14
15
  saveChild,
@@ -17,10 +18,17 @@ import {
17
18
  import type { ConnectedMachine } from "../fleet/index.js";
18
19
 
19
20
  function sameMembership(left: BoardBinding, right: BoardBinding) {
20
- return isDeepStrictEqual(
21
- { ...left, enabled: false },
22
- { ...right, enabled: false },
23
- );
21
+ const { legacyAgentName: _left, ...a } = parseBinding(left);
22
+ const { legacyAgentName: _right, ...b } = parseBinding(right);
23
+ return isDeepStrictEqual({ ...a, enabled: false }, { ...b, enabled: false });
24
+ }
25
+
26
+ function adoptedBinding(desired: BoardBinding, sessionId: string) {
27
+ return parseBinding({
28
+ ...desired,
29
+ sessionId,
30
+ parentSessionId: desired.parentSessionId ?? desired.sessionId,
31
+ });
24
32
  }
25
33
 
26
34
  /** Owns board attachment adoption, registration, restoration and removal. */
@@ -50,7 +58,11 @@ export class BoardMembership {
50
58
  throw new Error("Target already owns or belongs to a board family");
51
59
  return own;
52
60
  }
53
- prepareAttachment(ctx: ExtensionContext, upstream: string, name: string) {
61
+ prepareAttachment(
62
+ ctx: ExtensionContext,
63
+ upstream: string,
64
+ targetSessionId: string,
65
+ ) {
54
66
  this.getActive();
55
67
  const own = binding(ctx);
56
68
  if (!own.enabled)
@@ -59,7 +71,14 @@ export class BoardMembership {
59
71
  );
60
72
  if (!ctx.sessionManager.getSessionFile())
61
73
  throw new Error("Board attachment requires a saved controller session");
62
- return { ...own, agentName: `${own.agentName}/${name}`, upstream };
74
+ const { legacyAgentName: _legacy, ...board } = own;
75
+ return {
76
+ ...board,
77
+ upstream,
78
+ sessionId: targetSessionId,
79
+ agentName: `/${targetSessionId}`,
80
+ parentSessionId: own.sessionId,
81
+ };
63
82
  }
64
83
  commitAttachment(
65
84
  ctx: ExtensionContext,
@@ -70,9 +89,9 @@ export class BoardMembership {
70
89
  if (!ctx.isIdle())
71
90
  throw new Error("Attach a board only after the target settles");
72
91
  const own = binding(ctx);
73
- const adopted = { ...desired, sessionId: own.sessionId };
92
+ const adopted = adoptedBinding(desired, own.sessionId);
74
93
  if (isDeepStrictEqual(own, adopted)) return adopted;
75
- if (!isDeepStrictEqual(this.inspectAttachment(ctx), expected))
94
+ if (!sameMembership(this.inspectAttachment(ctx), expected))
76
95
  throw new Error(
77
96
  "Target board changed during attachment; resolve it again",
78
97
  );
@@ -87,19 +106,22 @@ export class BoardMembership {
87
106
  expected: BoardBinding,
88
107
  ) {
89
108
  this.getActive();
90
- if (!isDeepStrictEqual(binding(ctx), expected))
109
+ if (!sameMembership(binding(ctx), expected))
91
110
  throw new Error("Controller board changed during attachment");
92
- saveBinding(this.pi, expected);
111
+ saveBinding(this.pi, parseBinding(expected));
93
112
  await this.toOwner(ctx, {
94
113
  operation: "board-register",
95
- caller: expected,
96
- member: adopted,
114
+ caller: parseBinding(expected),
115
+ member: parseBinding({ ...adopted, parentSessionId: expected.sessionId }),
97
116
  });
98
- if (!isDeepStrictEqual(binding(ctx), expected))
117
+ if (!sameMembership(binding(ctx), expected))
99
118
  throw new Error("Controller board changed during attachment");
100
119
  saveChild(this.pi, {
101
120
  parentSessionId: expected.sessionId,
102
- binding: adopted,
121
+ binding: parseBinding({
122
+ ...adopted,
123
+ parentSessionId: expected.sessionId,
124
+ }),
103
125
  machine: runtime.machine,
104
126
  sessionFile,
105
127
  });
@@ -115,10 +137,7 @@ export class BoardMembership {
115
137
  "Detach a board member only when it has no board children",
116
138
  );
117
139
  if (
118
- !sameMembership(binding(ctx), {
119
- ...desired,
120
- sessionId: previous.sessionId,
121
- })
140
+ !sameMembership(binding(ctx), adoptedBinding(desired, previous.sessionId))
122
141
  )
123
142
  throw new Error("Target board changed before detach");
124
143
  saveBinding(this.pi, previous);
@@ -130,7 +149,7 @@ export class BoardMembership {
130
149
  await this.toOwner(ctx, {
131
150
  operation: "board-unregister",
132
151
  caller: own,
133
- member,
152
+ member: parseBinding({ ...member, parentSessionId: own.sessionId }),
134
153
  });
135
154
  if (!sameMembership(binding(ctx), own))
136
155
  throw new Error("Controller board changed during detach");
@@ -146,37 +165,37 @@ export class BoardMembership {
146
165
  >,
147
166
  ) {
148
167
  if (request.operation === "board-unregister") {
149
- const member = request.member;
168
+ const member = parseBinding(request.member);
150
169
  if (
151
170
  member.boardId !== own.boardId ||
152
171
  member.databasePath !== own.databasePath ||
153
- !member.agentName.startsWith(`${caller.agentName}/`)
172
+ member.parentSessionId !== caller.sessionId
154
173
  )
155
174
  throw new Error("Invalid board member removal");
156
- if (
157
- directory.some((entry) =>
158
- entry.agentName.startsWith(`${member.agentName}/`),
159
- )
160
- )
175
+ if (directory.some((entry) => entry.parentSessionId === member.sessionId))
161
176
  throw new Error(
162
177
  "Detach a board member only when it has no board children",
163
178
  );
164
179
  const existing = directory.find(
165
180
  (entry) => entry.agentName === member.agentName,
166
181
  );
167
- if (existing && !sameMembership(existing, member))
182
+ if (
183
+ existing &&
184
+ (existing.parentSessionId !== caller.sessionId ||
185
+ !sameMembership(existing, member))
186
+ )
168
187
  throw new Error("Board member changed before detach");
169
188
  removeMember(this.pi, member);
170
189
  this.getActive().delete(member.agentName);
171
190
  return true;
172
191
  }
173
192
  if (request.operation === "board-register") {
174
- const member = request.member;
193
+ const member = parseBinding(request.member);
175
194
  if (
176
195
  member.boardId !== own.boardId ||
177
196
  member.databasePath !== own.databasePath ||
178
197
  member.rootSessionId !== own.rootSessionId ||
179
- !member.agentName.startsWith(`${caller.agentName}/`)
198
+ member.parentSessionId !== caller.sessionId
180
199
  )
181
200
  throw new Error("Invalid board member registration");
182
201
  const existing = directory.find(
@@ -184,7 +203,7 @@ export class BoardMembership {
184
203
  entry.agentName === member.agentName ||
185
204
  entry.sessionId === member.sessionId,
186
205
  );
187
- if (existing && isDeepStrictEqual(existing, member)) return true;
206
+ if (existing && sameMembership(existing, member)) return true;
188
207
  if (existing) throw new Error("Board member already bound");
189
208
  saveMember(this.pi, member);
190
209
  return true;
@@ -0,0 +1,89 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { CoreConnection } from "./core/backend.js";
3
+ import type { AgentFleet } from "./fleet/index.js";
4
+ import { getSnapshot, sessionPath } from "./herdr.js";
5
+ import { spawnedChildren } from "./spawn-ownership.js";
6
+
7
+ export async function closeIdleChildren(
8
+ fleet: AgentFleet,
9
+ ctx: ExtensionContext,
10
+ current: () => boolean,
11
+ ): Promise<string> {
12
+ let closed = 0;
13
+ let skipped = 0;
14
+ const failures: string[] = [];
15
+ for (const child of spawnedChildren(ctx)) {
16
+ if (!current()) break;
17
+ try {
18
+ const status = fleet
19
+ .statuses()
20
+ .find((value) => value.id === child.machine);
21
+ if (!status || status.status !== "connected" || status.monitoringIssue) {
22
+ skipped += 1;
23
+ continue;
24
+ }
25
+ const runtime = fleet.connected(child.machine);
26
+ const identity = await runtime.client.machineIdentity();
27
+ const snapshot = await getSnapshot(runtime.client);
28
+ const panel = snapshot.agents.find(
29
+ (value) => value.pane_id === child.pane,
30
+ );
31
+ const record = runtime.monitor
32
+ .list()
33
+ .find((value) => value.terminalId === child.terminal);
34
+ if (
35
+ !current() ||
36
+ !spawnedChildren(ctx).some(
37
+ (value) =>
38
+ value.machine === child.machine &&
39
+ value.pane === child.pane &&
40
+ value.terminal === child.terminal &&
41
+ value.sessionFile === child.sessionFile,
42
+ ) ||
43
+ identity.host !== child.host ||
44
+ identity.session !== child.session ||
45
+ !panel ||
46
+ panel.agent !== "pi" ||
47
+ panel.terminal_id !== child.terminal ||
48
+ sessionPath(panel) !== child.sessionFile ||
49
+ (runtime.local &&
50
+ panel.pane_id ===
51
+ process.env[
52
+ runtime.client instanceof CoreConnection
53
+ ? "HC_TERMINAL_ID"
54
+ : "HERDR_PANE_ID"
55
+ ]) ||
56
+ snapshot.agents.some(
57
+ (value) =>
58
+ value.pane_id !== child.pane &&
59
+ sessionPath(value) === child.sessionFile,
60
+ ) ||
61
+ panel.interactive_ready !== true ||
62
+ panel.launch_pending === true ||
63
+ (panel.agent_status !== "idle" && panel.agent_status !== "done") ||
64
+ !record ||
65
+ record.paneId !== child.pane ||
66
+ record.activity.phase !== "settled" ||
67
+ (record.activity.status !== "idle" && record.activity.status !== "done")
68
+ ) {
69
+ skipped += 1;
70
+ continue;
71
+ }
72
+ await runtime.client.sendMessage(panel, {
73
+ text: "/quit",
74
+ sender: '<herdr_sender kind="idle-close" />',
75
+ closeIfIdle: true,
76
+ });
77
+ closed += 1;
78
+ } catch (error) {
79
+ skipped += 1;
80
+ failures.push(
81
+ `${child.machine}:${child.pane}: ${error instanceof Error ? error.message : String(error)}`,
82
+ );
83
+ }
84
+ }
85
+ return [
86
+ `Closed ${closed} idle child sessions; skipped ${skipped}.`,
87
+ ...failures,
88
+ ].join("\n");
89
+ }
@@ -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
+ }
@@ -18,7 +18,9 @@ export function controlPanelStatus(options: PanelOptions): string {
18
18
  "Fleet inactive. Run Pi inside Herdr; open /herdr → Status to reconnect.",
19
19
  ]
20
20
  : []),
21
- "Open /herdr in TUI for Settings, Status and SSH Connections.",
21
+ process.env["HC_TERMINAL_SOCKET"]
22
+ ? "Open /herdr in TUI for Settings and Status. Manage machines in Herdr or with hc machine add."
23
+ : "Open /herdr in TUI for Settings, Status and SSH Connections.",
22
24
  ].join("\n");
23
25
  }
24
26
 
@@ -15,7 +15,17 @@ export function buildPanelItems(
15
15
  tab: PanelTab,
16
16
  draft: SshSetupDraft,
17
17
  ): SettingItem[] {
18
- if (tab === "Connections") return sshSetupItems(draft);
18
+ if (tab === "Connections") {
19
+ if (process.env["HC_TERMINAL_SOCKET"])
20
+ return [
21
+ {
22
+ id: "core-machines",
23
+ label: "Manage machines in Herdr or with hc machine add",
24
+ currentValue: "",
25
+ },
26
+ ];
27
+ return sshSetupItems(draft);
28
+ }
19
29
  if (tab === "Status")
20
30
  return [
21
31
  {
@@ -23,7 +33,9 @@ export function buildPanelItems(
23
33
  label: "Refresh and reconnect",
24
34
  currentValue: "Enter",
25
35
  values: ["Enter"],
26
- description: "Reload Herdr profiles and retry connections.",
36
+ description: process.env["HC_TERMINAL_SOCKET"]
37
+ ? "Refresh Core machines and retry connections."
38
+ : "Reload Herdr profiles and retry connections.",
27
39
  },
28
40
  ...options.fleet.statuses().map((machine) => ({
29
41
  id: `machine:${machine.id}`,
@@ -150,8 +150,12 @@ export class PanelView {
150
150
  this.tab === "Settings"
151
151
  ? ""
152
152
  : this.tab === "Connections"
153
- ? "Remote needs Node on SSH PATH and Pi with Herdr integration. Herdr prepares its server before saving."
154
- : `${this.owners.fleet.isActive() ? "" : "Run Pi inside Herdr. "}Add SSH targets in Connections; select a machine here to reconnect.`,
153
+ ? process.env["HC_TERMINAL_SOCKET"]
154
+ ? ""
155
+ : "Remote needs Node on SSH PATH and Pi with Herdr integration. Herdr prepares its server before saving."
156
+ : process.env["HC_TERMINAL_SOCKET"]
157
+ ? "Select a machine to reconnect."
158
+ : `${this.owners.fleet.isActive() ? "" : "Run Pi inside Herdr. "}Add SSH targets in Connections; select a machine here to reconnect.`,
155
159
  ).filter((line) => line.trim()),
156
160
  "",
157
161
  ];