@howaboua/pi-shepherdr 0.2.27 → 0.2.28-core.12.1.gda85fa2e8a0f

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 (112) hide show
  1. package/README.md +48 -48
  2. package/index.ts +7 -1
  3. package/package.json +2 -9
  4. package/src/agent-identity.ts +3 -3
  5. package/src/agents-contract.ts +10 -14
  6. package/src/agents-discovery.ts +34 -54
  7. package/src/agents-focus.ts +23 -35
  8. package/src/agents-spawn.ts +24 -23
  9. package/src/agents-tool.ts +4 -19
  10. package/src/agents-work.ts +4 -3
  11. package/src/attachment-notes.ts +8 -7
  12. package/src/attachment-protocol.ts +3 -2
  13. package/src/attachment-routing.ts +1 -1
  14. package/src/attachment-target.ts +10 -18
  15. package/src/attachment.ts +14 -9
  16. package/src/board/discovery.ts +67 -0
  17. package/src/board/host.ts +93 -63
  18. package/src/board/membership.ts +16 -11
  19. package/src/board/records.ts +185 -0
  20. package/src/close-idle.ts +2 -9
  21. package/src/context-briefing.ts +230 -0
  22. package/src/context-routing.ts +1 -1
  23. package/src/control-panel/index.ts +2 -4
  24. package/src/control-panel/items.ts +1 -11
  25. package/src/control-panel/view.ts +3 -9
  26. package/src/controller.ts +50 -63
  27. package/src/core/AGENTS.md +7 -4
  28. package/src/core/admission-broker.mjs +235 -0
  29. package/src/core/admission-endpoint.ts +180 -0
  30. package/src/core/admission-owner.mjs +52 -0
  31. package/src/core/admission-startup.ts +130 -0
  32. package/src/core/admission.ts +181 -0
  33. package/src/core/agents.ts +102 -0
  34. package/src/core/backend.ts +110 -84
  35. package/src/core/client.ts +16 -0
  36. package/src/core/focus-channel-helper.mjs +6 -27
  37. package/src/core/focus-channel-wire.mjs +9 -6
  38. package/src/core/focus-channel.ts +5 -3
  39. package/src/core/focus-window.ts +15 -4
  40. package/src/core/helper-bootstrap.mjs +70 -0
  41. package/src/core/helper-context.mjs +98 -0
  42. package/src/core/helper-core.mjs +121 -0
  43. package/src/core/machines.ts +30 -0
  44. package/src/core/registration.ts +7 -2
  45. package/src/core/remote-endpoint.ts +80 -74
  46. package/src/core/remote-helper.ts +330 -0
  47. package/src/core/remote-reader.ts +3 -42
  48. package/src/core/remote-service.mjs +239 -0
  49. package/src/core/remote-transport.ts +290 -0
  50. package/src/core/spawn.ts +20 -20
  51. package/src/core/terminal-peer.mjs +57 -0
  52. package/src/core/terminal.ts +4 -2
  53. package/src/delivery.ts +39 -0
  54. package/src/fleet/catalog.ts +16 -58
  55. package/src/fleet/connection.ts +9 -18
  56. package/src/fleet/index.ts +38 -76
  57. package/src/fleet/inspection.ts +9 -22
  58. package/src/fleet/machine.ts +28 -12
  59. package/src/fleet/monitor.ts +8 -29
  60. package/src/fleet/persistence.ts +2 -2
  61. package/src/fleet/reconnect.ts +5 -3
  62. package/src/fleet/setup.ts +6 -16
  63. package/src/launch-contract.ts +0 -3
  64. package/src/launch-location.ts +4 -132
  65. package/src/launch.ts +18 -144
  66. package/src/messages/attachments.ts +1 -1
  67. package/src/messages/attribution.ts +9 -14
  68. package/src/messages/events.ts +5 -9
  69. package/src/messages/focus.ts +2 -7
  70. package/src/messages/guidance.ts +2 -43
  71. package/src/messages/peer-sharing.ts +133 -0
  72. package/src/monitor-events.ts +14 -43
  73. package/src/monitor-extension-messages.ts +5 -6
  74. package/src/monitor-record.ts +4 -0
  75. package/src/monitor-state.ts +1 -101
  76. package/src/monitor.ts +38 -66
  77. package/src/notes-discovery.ts +67 -0
  78. package/src/peer-inbox.ts +21 -27
  79. package/src/remote/context-relay.ts +25 -10
  80. package/src/remote/notes-reader.mjs +67 -0
  81. package/src/remote/shepherdr-channel.mjs +1 -1
  82. package/src/remote/shepherdr-checkpoints.mjs +49 -102
  83. package/src/remote/shepherdr-context.mjs +1 -1
  84. package/src/remote/shepherdr-peer.mjs +19 -24
  85. package/src/remote/shepherdr-session.mjs +18 -7
  86. package/src/saved-context.ts +62 -0
  87. package/src/settlement/collector.ts +29 -9
  88. package/src/settlement/index.ts +35 -6
  89. package/src/shared-context-host.ts +27 -33
  90. package/src/shared-context.ts +44 -15
  91. package/src/spawn-context.ts +11 -3
  92. package/src/spawn-ownership.ts +1 -1
  93. package/src/ssh-setup.ts +40 -73
  94. package/src/types.ts +4 -8
  95. package/src/voice-handoff.ts +1 -1
  96. package/src/widget.ts +7 -2
  97. package/src/worker-ownership.ts +2 -8
  98. package/src/worker-service.ts +6 -14
  99. package/src/core/context-relay.mjs +0 -111
  100. package/src/core/remote-exec.ts +0 -122
  101. package/src/core/remote-helper.mjs +0 -244
  102. package/src/core/remote-relay.ts +0 -191
  103. package/src/core/request.ts +0 -124
  104. package/src/herdr-client.ts +0 -364
  105. package/src/herdr.ts +0 -268
  106. package/src/machine-catalog.ts +0 -83
  107. package/src/monitor-event.ts +0 -84
  108. package/src/remote/client.ts +0 -127
  109. package/src/remote/deployment.ts +0 -179
  110. package/src/remote/focus-channels.ts +0 -89
  111. package/src/remote/shepherdr.mjs +0 -504
  112. package/src/remote/transport.ts +0 -369
@@ -1,6 +1,8 @@
1
1
  import { isSettledStatus } from "../activity.js";
2
- import { getAgent, getSnapshot, sessionPath } from "../herdr.js";
3
- import type { HerdrConnection } from "../herdr-client.js";
2
+ import { getSnapshot, sessionPath } from "../core/agents.js";
3
+ import type { CoreConnection } from "../core/backend.js";
4
+ import { object } from "../core/protocol.js";
5
+ import { terminalPane } from "../core/terminal.js";
4
6
  import { type AssistantReader, SessionReader } from "../session-reader.js";
5
7
  import type {
6
8
  ExtensionMessage,
@@ -49,11 +51,11 @@ export function blockedSettlement(
49
51
  }
50
52
 
51
53
  export class SettlementCollector {
52
- private readonly client: HerdrConnection;
54
+ private readonly client: CoreConnection;
53
55
  private readonly reader: AssistantReader;
54
56
 
55
57
  constructor(
56
- client: HerdrConnection,
58
+ client: CoreConnection,
57
59
  reader: AssistantReader = new SessionReader(),
58
60
  ) {
59
61
  this.client = client;
@@ -76,11 +78,28 @@ export class SettlementCollector {
76
78
  async collect(
77
79
  record: MonitoredAgent,
78
80
  reportedStatus?: "blocked",
79
- ): Promise<CollectedSettlementWithSession | undefined> {
80
- const [current, snapshot] = await Promise.all([
81
- getAgent(this.client, record.paneId),
82
- getSnapshot(this.client),
83
- ]);
81
+ ): Promise<CollectedSettlementWithSession | "closed" | undefined> {
82
+ let terminal: unknown;
83
+ try {
84
+ terminal = await this.client.core.request("terminal.get", {
85
+ terminal: record.terminalId,
86
+ });
87
+ } catch (error) {
88
+ // Only this exact lookup proves closure; snapshot/read/transport failures do not.
89
+ if (
90
+ error instanceof Error &&
91
+ "kind" in error &&
92
+ error.kind === "not_found"
93
+ )
94
+ return "closed";
95
+ throw error;
96
+ }
97
+ const current = terminalPane(terminal);
98
+ if (
99
+ current.terminal_id === record.terminalId &&
100
+ object(terminal)["state"] === "finished"
101
+ )
102
+ return "closed";
84
103
  if (current.terminal_id !== record.terminalId || current.agent !== "pi") {
85
104
  return reportedStatus === "blocked"
86
105
  ? blockedSettlement(record)
@@ -92,6 +111,7 @@ export class SettlementCollector {
92
111
  ? current.agent_status
93
112
  : undefined);
94
113
  if (!status) return undefined;
114
+ const snapshot = await getSnapshot(this.client);
95
115
  let view: SessionView;
96
116
  try {
97
117
  view = await this.reader.view(sessionPath(current));
@@ -7,7 +7,7 @@ import {
7
7
  activityExpectedUser,
8
8
  activityTask,
9
9
  } from "../activity.js";
10
- import type { HerdrConnection } from "../herdr-client.js";
10
+ import type { CoreConnection } from "../core/backend.js";
11
11
  import type { MonitorState, WorkAttempt } from "../monitor-state.js";
12
12
  import type { AssistantReader } from "../session-reader.js";
13
13
  import type {
@@ -62,23 +62,30 @@ export class SettlementReporter {
62
62
  private readonly collector: SettlementCollector;
63
63
  private readonly persist: () => void;
64
64
  private readonly reporting = new Map<string, SettledAgentStatus>();
65
+ private readonly failedAttempts = new Map<string, string | undefined>();
65
66
  private readonly pendingBlocked = new Map<string, PendingBlockedSettlement>();
66
67
  private readonly delivery: SettlementDelivery;
67
- private readonly retries = new Map<string, NodeJS.Timeout>();
68
+ private readonly retries = new Map<
69
+ string,
70
+ { terminalId: string; timer: NodeJS.Timeout }
71
+ >();
68
72
  private readonly state: MonitorState;
73
+ private readonly onClosed: (record: MonitoredAgent) => Promise<void>;
69
74
 
70
75
  constructor(
71
76
  pi: ExtensionAPI,
72
- client: HerdrConnection,
77
+ client: CoreConnection,
73
78
  state: MonitorState,
74
79
  persist: () => void,
75
80
  reader: AssistantReader | undefined,
76
81
  origin: { machine: string; label: () => string; operatorPrefix: string },
82
+ onClosed: (record: MonitoredAgent) => Promise<void>,
77
83
  ) {
78
84
  this.delivery = new SettlementDelivery(pi, origin);
79
85
  this.collector = new SettlementCollector(client, reader);
80
86
  this.state = state;
81
87
  this.persist = persist;
88
+ this.onClosed = onClosed;
82
89
  }
83
90
 
84
91
  latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
@@ -91,9 +98,10 @@ export class SettlementReporter {
91
98
 
92
99
  stop(): void {
93
100
  this.reporting.clear();
101
+ this.failedAttempts.clear();
94
102
  this.pendingBlocked.clear();
95
103
  this.delivery.stop();
96
- for (const timer of this.retries.values()) clearTimeout(timer);
104
+ for (const { timer } of this.retries.values()) clearTimeout(timer);
97
105
  this.retries.clear();
98
106
  }
99
107
 
@@ -108,6 +116,16 @@ export class SettlementReporter {
108
116
  this.delivery.releaseClaim(attempt, error);
109
117
  }
110
118
  releaseAgentClaim(record: MonitoredAgent, error: unknown) {
119
+ this.failedAttempts.delete(record.terminalId);
120
+ for (const [key, retry] of this.retries) {
121
+ if (retry.terminalId !== record.terminalId) continue;
122
+ clearTimeout(retry.timer);
123
+ this.retries.delete(key);
124
+ }
125
+ for (const [key, pending] of this.pendingBlocked) {
126
+ if (pending.request.record.terminalId === record.terminalId)
127
+ this.pendingBlocked.delete(key);
128
+ }
111
129
  this.delivery.releaseAgentClaim(record, error);
112
130
  }
113
131
  async report(
@@ -145,6 +163,10 @@ export class SettlementReporter {
145
163
  request.status === "blocked" && !replyingTo ? "blocked" : undefined,
146
164
  );
147
165
  if (!settlement || !lifecycle.isCurrent()) return;
166
+ if (settlement === "closed") {
167
+ await this.onClosed(request.record);
168
+ return;
169
+ }
148
170
  if (this.pendingBlocked.has(key)) return;
149
171
  const current = this.state.byPane(settlement.agent.pane_id);
150
172
  if (!current || current.terminalId !== request.record.terminalId) return;
@@ -248,6 +270,7 @@ export class SettlementReporter {
248
270
  )
249
271
  ) {
250
272
  this.clearRetry(current.terminalId, retryState.attemptId);
273
+ this.failedAttempts.delete(current.terminalId);
251
274
  this.persist();
252
275
  this.delivery.deliverSettlement(
253
276
  lifecycle,
@@ -320,7 +343,7 @@ export class SettlementReporter {
320
343
  private clearRetry(terminalId: string, attemptId: string | undefined): void {
321
344
  const key = attemptKey(terminalId, attemptId);
322
345
  const retry = this.retries.get(key);
323
- if (retry) clearTimeout(retry);
346
+ if (retry) clearTimeout(retry.timer);
324
347
  this.retries.delete(key);
325
348
  }
326
349
 
@@ -363,7 +386,7 @@ export class SettlementReporter {
363
386
  { ...retry, count: retry.count + 1 },
364
387
  );
365
388
  }, delay);
366
- this.retries.set(key, timer);
389
+ this.retries.set(key, { terminalId: request.record.terminalId, timer });
367
390
  timer.unref();
368
391
  return true;
369
392
  }
@@ -383,6 +406,12 @@ export class SettlementReporter {
383
406
  SETTLEMENT_RETRY_WINDOW_SECONDS +
384
407
  " seconds";
385
408
  if (attemptId) this.delivery.releaseAttempt(attemptId, new Error(message));
409
+ if (
410
+ this.failedAttempts.has(record.terminalId) &&
411
+ this.failedAttempts.get(record.terminalId) === attemptId
412
+ )
413
+ return;
414
+ this.failedAttempts.set(record.terminalId, attemptId);
386
415
  lifecycle.context.ui.notify(message, "warning");
387
416
  }
388
417
  }
@@ -5,14 +5,16 @@ import type {
5
5
  import type {
6
6
  SharedContextRequest,
7
7
  SharedContextResult,
8
- } from "@howaboua/pi-notes-compaction/context-sharing";
8
+ } from "@howaboua/pi-agent-comms/context-sharing";
9
9
  import { attachmentOwner, attachmentRoutes } from "./attachment-protocol.js";
10
10
  import type { AgentBoard } from "./board/host.js";
11
11
  import type { AgentFleet } from "./fleet/index.js";
12
+ import { connectNotesContextSharing } from "./notes-discovery.js";
12
13
  import {
13
14
  listenContext,
14
15
  sessionContextPath,
15
16
  } from "./remote/shepherdr-context.mjs";
17
+ import { savedContextLoader } from "./saved-context.js";
16
18
  import { SharedAgentContext } from "./shared-context.js";
17
19
 
18
20
  export async function registerSharedAgentContext(
@@ -20,33 +22,10 @@ export async function registerSharedAgentContext(
20
22
  fleet: AgentFleet,
21
23
  board: AgentBoard,
22
24
  ): Promise<SharedAgentContext> {
23
- let api:
24
- | typeof import("@howaboua/pi-notes-compaction/context-sharing")
25
- | undefined;
26
- try {
27
- api = await import("@howaboua/pi-notes-compaction/context-sharing");
28
- } catch (error) {
29
- const failure = error as { code?: string; message?: string };
30
- const missing = failure.message?.match(
31
- /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
32
- )?.[1];
33
- const module = "@howaboua/pi-notes-compaction/context-sharing";
34
- const unavailable =
35
- ((failure.code === "ERR_MODULE_NOT_FOUND" ||
36
- failure.code === "MODULE_NOT_FOUND") &&
37
- (missing === "@howaboua/pi-notes-compaction" ||
38
- missing === module ||
39
- missing?.endsWith(`/${module}`))) ||
40
- (failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
41
- failure.message?.includes("@howaboua/pi-notes-compaction") &&
42
- failure.message.includes("./context-sharing"));
43
- if (!unavailable)
44
- throw new Error(
45
- "Update pi-notes-compaction to use shared agent context",
46
- { cause: error },
47
- );
48
- }
49
- const connection = api?.connectNotesContextSharing(pi);
25
+ let started = false;
26
+ const connection = connectNotesContextSharing(pi, () => {
27
+ if (started) connectRoutes();
28
+ });
50
29
  let relationships:
51
30
  | ReturnType<
52
31
  typeof import("@howaboua/pi-codex-conversion/agent-relationship")["connectCodexAgentRelationships"]
@@ -69,15 +48,20 @@ export async function registerSharedAgentContext(
69
48
  )
70
49
  throw error;
71
50
  }
51
+ const notes = () =>
52
+ connection?.service?.registerSavedSessionLoader
53
+ ? connection.service
54
+ : undefined;
72
55
  const shared = new SharedAgentContext(
73
56
  pi,
74
57
  fleet,
75
- () => connection?.service,
58
+ notes,
76
59
  board,
77
60
  () => relationships?.service,
78
61
  );
79
62
  let close: (() => Promise<void>) | undefined;
80
63
  let unregister: (() => void) | undefined;
64
+ let unregisterSaved: (() => void) | undefined;
81
65
  const publish = async (ctx: ExtensionContext) => {
82
66
  const file = ctx.sessionManager.getSessionFile();
83
67
  if (!file) return;
@@ -100,11 +84,13 @@ export async function registerSharedAgentContext(
100
84
  );
101
85
  }
102
86
  };
103
- pi.on("session_start", async () => {
104
- await close?.();
105
- close = undefined;
87
+ const connectRoutes = () => {
106
88
  unregister?.();
107
- unregister = connection?.service?.registerRouter(
89
+ unregisterSaved?.();
90
+ unregisterSaved = notes()?.registerSavedSessionLoader?.(
91
+ savedContextLoader(fleet),
92
+ );
93
+ unregister = notes()?.registerRouter(
108
94
  Object.assign(
109
95
  async (
110
96
  context: ExtensionContext,
@@ -129,13 +115,21 @@ export async function registerSharedAgentContext(
129
115
  },
130
116
  ),
131
117
  );
118
+ };
119
+ pi.on("session_start", async () => {
120
+ await close?.();
121
+ close = undefined;
122
+ started = true;
123
+ connectRoutes();
132
124
  });
133
125
  pi.on("resources_discover", async (_event, ctx) => {
134
126
  await publish(ctx);
135
127
  await fleet.restoreSharing(ctx);
136
128
  });
137
129
  pi.on("session_shutdown", async () => {
130
+ started = false;
138
131
  unregister?.();
132
+ unregisterSaved?.();
139
133
  await close?.();
140
134
  connection?.dispose();
141
135
  relationships?.dispose();
@@ -3,17 +3,12 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import {
7
- binding,
8
- children,
9
- isBoardEnvelope,
10
- } from "@howaboua/pi-agent-board/integration";
11
- import type { CodexAgentRelationshipService } from "@howaboua/pi-codex-conversion/agent-relationship";
12
6
  import type {
13
7
  ContextSharingService,
14
8
  SharedContextRequest,
15
9
  SharedContextResult,
16
- } from "@howaboua/pi-notes-compaction/context-sharing";
10
+ } from "@howaboua/pi-agent-comms/context-sharing";
11
+ import type { CodexAgentRelationshipService } from "@howaboua/pi-codex-conversion/agent-relationship";
17
12
  import { Check } from "typebox/value";
18
13
  import { AgentAttachment } from "./attachment.js";
19
14
  import {
@@ -22,18 +17,25 @@ import {
22
17
  Identity,
23
18
  } from "./attachment-protocol.js";
24
19
  import type { AgentBoard } from "./board/host.js";
20
+ import { children, isBoardEnvelope } from "./board/records.js";
25
21
  import {
26
22
  contextRouteMatches,
27
23
  countContextTargets,
28
24
  sendContextRoute,
29
25
  } from "./context-routing.js";
30
- import type { AgentFleet } from "./fleet/index.js";
31
- import { sessionPath } from "./herdr.js";
26
+ import { sessionPath } from "./core/agents.js";
27
+ import type { AgentFleet, ConnectedMachine } from "./fleet/index.js";
28
+ import {
29
+ describePeerSharing,
30
+ peerReplyContext,
31
+ } from "./messages/peer-sharing.js";
32
+ import { NOTES_UNAVAILABLE } from "./notes-discovery.js";
32
33
  import {
33
34
  requestContext,
34
35
  sessionContextPath,
35
36
  } from "./remote/shepherdr-context.mjs";
36
37
  import { MEMBER_ENTRY, type Member, SpawnContext } from "./spawn-context.js";
38
+ import type { PaneInfo } from "./types.js";
37
39
 
38
40
  interface Routing {
39
41
  transport: "shepherdr";
@@ -68,8 +70,14 @@ export class SharedAgentContext {
68
70
  this.getService = getService;
69
71
  this.board = board;
70
72
  this.getRelationships = getRelationships;
71
- this.attachment = new AgentAttachment(pi, board, getService);
72
- this.spawns = new SpawnContext(pi, getService, getRelationships);
73
+ const localMachine = () => fleet.localMachine();
74
+ this.attachment = new AgentAttachment(pi, board, getService, localMachine);
75
+ this.spawns = new SpawnContext(
76
+ pi,
77
+ getService,
78
+ getRelationships,
79
+ localMachine,
80
+ );
73
81
  pi.on("before_agent_start", () => {
74
82
  this.running = true;
75
83
  });
@@ -106,6 +114,21 @@ export class SharedAgentContext {
106
114
  });
107
115
  }
108
116
 
117
+ peerReplyContext(
118
+ ctx: ExtensionContext,
119
+ runtime: ConnectedMachine,
120
+ panel: PaneInfo,
121
+ signal?: AbortSignal,
122
+ ): Promise<string> {
123
+ return peerReplyContext(
124
+ ctx,
125
+ () => describePeerSharing(ctx, this.getService(), this.board),
126
+ runtime,
127
+ panel,
128
+ signal,
129
+ );
130
+ }
131
+
109
132
  async handle(
110
133
  ctx: ExtensionContext,
111
134
  value: unknown,
@@ -118,13 +141,20 @@ export class SharedAgentContext {
118
141
  value.operation === "agent-identity"
119
142
  )
120
143
  return { sessionId: ctx.sessionManager.getSessionId() };
144
+ if (
145
+ value &&
146
+ typeof value === "object" &&
147
+ "operation" in value &&
148
+ value.operation === "peer-sharing"
149
+ )
150
+ return describePeerSharing(ctx, this.getService(), this.board);
121
151
  if (
122
152
  value &&
123
153
  typeof value === "object" &&
124
154
  "operation" in value &&
125
155
  value.operation === "agent-root"
126
156
  ) {
127
- const own = binding(ctx);
157
+ const own = this.board.binding(ctx);
128
158
  const identity = this.getService()?.describe(ctx);
129
159
  if (
130
160
  !("scope" in value) ||
@@ -213,8 +243,7 @@ export class SharedAgentContext {
213
243
  ) ?? null
214
244
  );
215
245
  }
216
- if (!identity || !service)
217
- throw new Error("Context sharing is unavailable in this session");
246
+ if (!identity || !service) throw new Error(NOTES_UNAVAILABLE);
218
247
  if ("operation" in value && value.operation === "context-resolve")
219
248
  return countContextTargets(
220
249
  ctx,
@@ -372,7 +401,7 @@ export class SharedAgentContext {
372
401
  machine?: string,
373
402
  signal?: AbortSignal,
374
403
  ) {
375
- const own = binding(ctx);
404
+ const own = this.board.binding(ctx);
376
405
  const identity = this.getService()?.describe(ctx);
377
406
  const scope = own.upstream || !identity ? "board" : "context";
378
407
  const family = scope === "board" ? own.rootSessionId : identity?.sessionId;
@@ -3,11 +3,11 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import type { ContextSharingService } from "@howaboua/pi-agent-comms/context-sharing";
6
7
  import type { CodexAgentRelationshipService } from "@howaboua/pi-codex-conversion/agent-relationship";
7
- import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
8
8
  import { nativeAgentName } from "./agent-identity.js";
9
+ import { sessionPath } from "./core/agents.js";
9
10
  import type { ConnectedMachine } from "./fleet/index.js";
10
- import { sessionPath } from "./herdr.js";
11
11
  import { sessionContextPath } from "./remote/shepherdr-context.mjs";
12
12
  import type { PaneInfo } from "./types.js";
13
13
 
@@ -22,6 +22,7 @@ export interface Member {
22
22
  interface Routing {
23
23
  transport: "shepherdr";
24
24
  parent: string;
25
+ savedParent: { machine: string; sessionFile: string };
25
26
  }
26
27
 
27
28
  export class SpawnContext {
@@ -30,14 +31,17 @@ export class SpawnContext {
30
31
  | CodexAgentRelationshipService
31
32
  | undefined;
32
33
  private readonly getService: () => ContextSharingService | undefined;
34
+ private readonly localMachine: () => string;
33
35
  constructor(
34
36
  pi: ExtensionAPI,
35
37
  getService: () => ContextSharingService | undefined,
36
38
  getRelationships: () => CodexAgentRelationshipService | undefined,
39
+ localMachine: () => string,
37
40
  ) {
38
41
  this.pi = pi;
39
42
  this.getRelationships = getRelationships;
40
43
  this.getService = getService;
44
+ this.localMachine = localMachine;
41
45
  }
42
46
  canShare(ctx: ExtensionContext): boolean {
43
47
  return this.getService()?.canCreateChild(ctx) === true;
@@ -125,6 +129,10 @@ export class SpawnContext {
125
129
  await runtime.prepareSharing();
126
130
  const routing: Routing = {
127
131
  transport: "shepherdr",
132
+ savedParent: {
133
+ machine: this.localMachine(),
134
+ sessionFile: parentFile,
135
+ },
128
136
  parent: runtime.local
129
137
  ? sessionContextPath(parentFile)
130
138
  : runtime.client.contextRelayPath(),
@@ -143,7 +151,7 @@ export class SpawnContext {
143
151
  sessionContextPath(sessionFile),
144
152
  { operation: "bind", binding },
145
153
  );
146
- if (!value)
154
+ if (value === null)
147
155
  return {
148
156
  warning: "Spawned without shared context: the target needs Notes",
149
157
  };
@@ -2,8 +2,8 @@ import type {
2
2
  ExtensionAPI,
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
+ import { sessionPath } from "./core/agents.js";
5
6
  import type { ConnectedMachine } from "./fleet/index.js";
6
- import { sessionPath } from "./herdr.js";
7
7
  import type { PaneInfo } from "./types.js";
8
8
 
9
9
  const ENTRY = "herdr-spawn-ownership-v1";
package/src/ssh-setup.ts CHANGED
@@ -1,12 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { SettingItem } from "@earendil-works/pi-tui";
3
- import { readMachineCatalog, withHerdrBinary } from "./machine-catalog.js";
4
3
  import { runSetupProcess } from "./setup-process.js";
5
4
 
6
- // Herdr's default session is named "default". Pin it explicitly so native
7
- // interactive session discovery cannot change the identity of a blank draft.
8
- const DEFAULT_REMOTE_SESSION = "default";
9
-
10
5
  export interface SshSetupDraft {
11
6
  target: string;
12
7
  label: string;
@@ -25,16 +20,16 @@ export function sshSetupItems(draft: SshSetupDraft): SettingItem[] {
25
20
  },
26
21
  {
27
22
  id: "ssh:label",
28
- label: "Label",
23
+ label: "Machine name",
29
24
  currentValue: draft.label || "required",
30
25
  values: ["Enter"],
31
26
  },
32
27
  {
33
28
  id: "ssh:session",
34
29
  label: "Remote session",
35
- currentValue: draft.session || "Herdr default",
30
+ currentValue: draft.session || "Core default",
36
31
  values: ["Enter"],
37
- description: "Optional Herdr session name. Leave empty for the default.",
32
+ description: "Optional Core session name. Leave empty for the default.",
38
33
  },
39
34
  {
40
35
  id: "ssh:add",
@@ -42,7 +37,7 @@ export function sshSetupItems(draft: SshSetupDraft): SettingItem[] {
42
37
  currentValue: "Enter",
43
38
  values: ["Enter"],
44
39
  description:
45
- "Opens Herdr setup in the terminal. Ctrl+C cancels. Installation approvals stay interactive.",
40
+ "Opens hc machine add in the terminal. Ctrl+C cancels. Installation approvals stay interactive.",
46
41
  },
47
42
  ];
48
43
  }
@@ -53,25 +48,21 @@ export function sshSetupArgs(draft: SshSetupDraft): string[] {
53
48
  throw new Error(
54
49
  "Enter an SSH alias or user@host, without spaces or options.",
55
50
  );
56
- if (!label || /[\x00-\x1f\x7f]/.test(label))
57
- throw new Error("Enter a label without control characters.");
58
- if (
59
- session &&
60
- (!/^[a-zA-Z0-9_.-]{1,64}$/.test(session) ||
61
- session === "." ||
62
- session === "..")
63
- )
51
+ if (!/^[a-z0-9][a-z0-9_.-]{0,31}$/.test(label))
52
+ throw new Error(
53
+ "Machine name must use 1–32 lowercase letters, digits, dots, underscores or hyphens, starting with a letter or digit.",
54
+ );
55
+ if (session && !/^[a-z0-9][a-z0-9_.-]{0,31}$/.test(session))
64
56
  throw new Error(
65
- "Session must use 1–64 letters, digits, dots, underscores or hyphens.",
57
+ "Session must use 1–32 lowercase letters, digits, dots, underscores or hyphens, starting with a letter or digit.",
66
58
  );
67
59
  return [
68
60
  "machine",
69
61
  "add",
70
62
  target,
71
- "--label",
63
+ "--name",
72
64
  label,
73
- "--remote-session",
74
- session || DEFAULT_REMOTE_SESSION,
65
+ ...(session ? ["--session", session] : []),
75
66
  ];
76
67
  }
77
68
 
@@ -81,64 +72,40 @@ export async function addSshConnection(
81
72
  signal: AbortSignal,
82
73
  ): Promise<{ message: string; refresh: boolean }> {
83
74
  const args = sshSetupArgs(draft);
84
- const session = draft.session || DEFAULT_REMOTE_SESSION;
85
- const matchesDraft = (machine: { target: string; session: string }) =>
86
- machine.target === draft.target && machine.session === session;
87
- // Inspect on every attempt, including retries after interrupted setup.
88
- const catalog = await readMachineCatalog(signal);
89
- signal.throwIfAborted();
90
- const existing = Object.values(catalog).find(matchesDraft);
91
- if (existing)
92
- return {
93
- message: `Already configured as ${existing.label}. Check Status.`,
94
- refresh: true,
75
+ const result = await ctx.ui.custom<{
76
+ code: number | null;
77
+ signal: NodeJS.Signals | null;
78
+ interrupted: boolean;
79
+ }>(async (tui, _theme, _kb, done) => {
80
+ signal.throwIfAborted();
81
+ tui.stop();
82
+ // The terminal sends Ctrl+C to both processes. Let hc handle it,
83
+ // without allowing Node's default handler to terminate Pi.
84
+ let interrupted = false;
85
+ const interrupt = () => {
86
+ interrupted = true;
95
87
  };
96
- const result = await withHerdrBinary((binary) =>
97
- ctx.ui.custom<{
98
- code: number | null;
99
- signal: NodeJS.Signals | null;
100
- interrupted: boolean;
101
- }>(async (tui, _theme, _kb, done) => {
102
- signal.throwIfAborted();
103
- tui.stop();
104
- // The terminal sends Ctrl+C to both processes. Let Herdr handle it,
105
- // without allowing Node's default handler to terminate Pi.
106
- let interrupted = false;
107
- const interrupt = () => {
108
- interrupted = true;
109
- };
110
- let result: { code: number | null; signal: NodeJS.Signals | null };
111
- try {
112
- process.stdout.write("\x1b[2J\x1b[H");
113
- process.on("SIGINT", interrupt);
114
- result = await runSetupProcess(binary, args, signal);
115
- } finally {
116
- process.removeListener("SIGINT", interrupt);
117
- tui.start();
118
- tui.requestRender(true);
119
- }
120
- done({ ...result, interrupted });
121
- return { render: () => [], invalidate: () => {} };
122
- }),
123
- );
88
+ let result: { code: number | null; signal: NodeJS.Signals | null };
89
+ try {
90
+ process.stdout.write("\x1b[2J\x1b[H");
91
+ process.on("SIGINT", interrupt);
92
+ result = await runSetupProcess("hc", args, signal);
93
+ } finally {
94
+ process.removeListener("SIGINT", interrupt);
95
+ tui.start();
96
+ tui.requestRender(true);
97
+ }
98
+ done({ ...result, interrupted });
99
+ return { render: () => [], invalidate: () => {} };
100
+ });
124
101
  signal.throwIfAborted();
125
102
  if (result.interrupted || result.code !== 0)
126
103
  return {
127
- message: `Herdr setup ${result.interrupted || result.signal ? `cancelled (${result.signal ?? "SIGINT"})` : `exited with code ${result.code ?? "unknown"}`}. Profile not confirmed. Retry checks the catalog first.`,
128
- refresh: false,
129
- };
130
- const saved = Object.values(await readMachineCatalog(signal)).some(
131
- matchesDraft,
132
- );
133
- signal.throwIfAborted();
134
- if (!saved)
135
- return {
136
- message:
137
- "No matching profile saved. Setup may have been cancelled; retry checks the catalog first.",
138
- refresh: false,
104
+ message: `Core setup ${result.interrupted || result.signal ? `cancelled (${result.signal ?? "SIGINT"})` : `exited with code ${result.code ?? "unknown"}`}. Check Status before retrying.`,
105
+ refresh: true,
139
106
  };
140
107
  return {
141
- message: "Herdr setup completed. Check Status for the connection.",
108
+ message: "Core setup completed. Check Status for the connection.",
142
109
  refresh: true,
143
110
  };
144
111
  }