@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
@@ -0,0 +1,133 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { ContextSharingService } from "@howaboua/pi-agent-comms/context-sharing";
4
+ import { type Static, Type } from "typebox";
5
+ import { Check } from "typebox/value";
6
+ import {
7
+ attachmentOwner,
8
+ attachmentRoutes,
9
+ canonicalContextIdentity,
10
+ detachment,
11
+ Identity,
12
+ } from "../attachment-protocol.js";
13
+ import type { AgentBoard } from "../board/host.js";
14
+ import { sessionPath } from "../core/agents.js";
15
+ import type { ConnectedMachine } from "../fleet/index.js";
16
+ import { sessionContextPath } from "../remote/shepherdr-context.mjs";
17
+ import { MEMBER_ENTRY } from "../spawn-context.js";
18
+ import type { PaneInfo } from "../types.js";
19
+
20
+ const Sharing = Type.Object({
21
+ sessionId: Type.String({ minLength: 1 }),
22
+ notes: Type.Union([Identity, Type.Null()]),
23
+ boardId: Type.Union([Type.String({ minLength: 1 }), Type.Null()]),
24
+ });
25
+ type Sharing = Static<typeof Sharing>;
26
+ type Access = "shared" | "not shared" | "retained checkpoints only" | "unknown";
27
+
28
+ /** Read-only facts, never attachment inspection or adoption. */
29
+ export function describePeerSharing(
30
+ ctx: ExtensionContext,
31
+ service: ContextSharingService | undefined,
32
+ board: AgentBoard,
33
+ ): Sharing {
34
+ const notes = service?.describe(ctx);
35
+ if (notes && !Check(Identity, notes))
36
+ throw new Error("Sharing status unavailable");
37
+ return {
38
+ sessionId: ctx.sessionManager.getSessionId(),
39
+ notes: notes ?? null,
40
+ boardId: board.enabled(ctx) ? board.binding(ctx).boardId : null,
41
+ };
42
+ }
43
+
44
+ function notesAccess(
45
+ ctx: ExtensionContext,
46
+ own: Sharing,
47
+ peer: Sharing,
48
+ ): Access {
49
+ const from = own.notes;
50
+ const to = peer.notes;
51
+ if (!from || !to) return "not shared";
52
+ if (
53
+ from.sessionId === to.sessionId &&
54
+ from.accountScope === to.accountScope &&
55
+ from.backendUrl === to.backendUrl
56
+ )
57
+ return "shared";
58
+ const routes = attachmentRoutes(ctx);
59
+ for (const route of routes) {
60
+ const link = route.plan.context;
61
+ if (
62
+ route.phase === "ready" &&
63
+ link &&
64
+ isDeepStrictEqual(from, canonicalContextIdentity(link.controller)) &&
65
+ isDeepStrictEqual(to, canonicalContextIdentity(link.target))
66
+ )
67
+ return route.detached?.context ? "retained checkpoints only" : "shared";
68
+ }
69
+ const owner = attachmentOwner(ctx);
70
+ if (
71
+ owner?.context &&
72
+ isDeepStrictEqual(from, canonicalContextIdentity(owner.context.target)) &&
73
+ isDeepStrictEqual(to, canonicalContextIdentity(owner.context.controller))
74
+ )
75
+ return detachment(ctx, owner)?.context
76
+ ? "retained checkpoints only"
77
+ : "shared";
78
+ // A standalone family with no edges cannot reach another family. For more
79
+ // complex graphs, absence of a direct edge does not establish lack of access.
80
+ if (
81
+ from.threadId === from.sessionId &&
82
+ !from.routing &&
83
+ !owner?.context &&
84
+ !routes.some((route) => route.plan.context) &&
85
+ !ctx.sessionManager
86
+ .getEntries()
87
+ .some(
88
+ (entry) =>
89
+ entry.type === "custom" &&
90
+ entry.customType === MEMBER_ENTRY &&
91
+ (entry.data as { threadId?: unknown } | undefined)?.threadId ===
92
+ from.threadId,
93
+ )
94
+ )
95
+ return "not shared";
96
+ return "unknown";
97
+ }
98
+
99
+ /** Describe the originator's access to the recipient, not the reverse. */
100
+ export async function peerReplyContext(
101
+ ctx: ExtensionContext,
102
+ describe: () => Sharing,
103
+ runtime: ConnectedMachine,
104
+ panel: PaneInfo,
105
+ signal?: AbortSignal,
106
+ ): Promise<string> {
107
+ let notes: Access = "unknown";
108
+ let board: Access = "unknown";
109
+ try {
110
+ const file = sessionPath(panel);
111
+ if (!file) throw new Error("Target has no saved session");
112
+ const deadline = AbortSignal.timeout(2_000);
113
+ const result = await runtime.client.requestContext(
114
+ sessionContextPath(file),
115
+ { operation: "peer-sharing" },
116
+ signal ? AbortSignal.any([signal, deadline]) : deadline,
117
+ );
118
+ if (
119
+ !Check(Sharing, result) ||
120
+ (result.notes && result.notes.threadId !== result.sessionId)
121
+ )
122
+ throw new Error("Sharing status unavailable");
123
+ const own = describe();
124
+ notes = notesAccess(ctx, own, result);
125
+ board =
126
+ own.boardId && own.boardId === result.boardId ? "shared" : "not shared";
127
+ } catch {
128
+ // Older/unavailable peers still receive the message, with uncertainty
129
+ // visible rather than turning a failed lookup into an access claim.
130
+ signal?.throwIfAborted();
131
+ }
132
+ return `Sender access at send time — your current Notes: ${notes}; your current Board: ${board}.`;
133
+ }
@@ -1,5 +1,5 @@
1
- import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
2
- import type { HerdrEvent, MonitoringIssue } from "./types.js";
1
+ import type { CoreConnection } from "./core/backend.js";
2
+ import type { MonitoringIssue } from "./types.js";
3
3
 
4
4
  interface SubscriptionAttempt {
5
5
  key: string;
@@ -12,9 +12,9 @@ interface Subscription {
12
12
  }
13
13
 
14
14
  interface MonitorEventsOptions {
15
- client: HerdrConnection;
15
+ client: CoreConnection;
16
16
  reconnect?: boolean;
17
- onEvent: (event: HerdrEvent) => void;
17
+ onChange: () => void;
18
18
  reconcile: () => Promise<void>;
19
19
  onWarning: (issue: MonitoringIssue) => void;
20
20
  onRecovered: () => void;
@@ -94,11 +94,12 @@ export class MonitorEvents {
94
94
  try {
95
95
  if (this.resync) {
96
96
  this.resync = false;
97
- // Remap panes moved during the outage before requesting new coverage.
97
+ // Reconcile changes missed during the outage before restoring coverage.
98
98
  await this.options.reconcile();
99
99
  if (!this.active || epoch !== this.epoch) return;
100
100
  }
101
- const key = this.targetKey();
101
+ const targets = [...new Set(this.options.targets())].sort();
102
+ const key = JSON.stringify(targets);
102
103
  if (key === "[]") {
103
104
  this.closeSubscription();
104
105
  this.recovered();
@@ -108,18 +109,10 @@ export class MonitorEvents {
108
109
  const candidate = { key, controller: new AbortController() };
109
110
  attempt = candidate;
110
111
  this.pending = candidate;
111
- const subscriptions = [
112
- ...this.options.targets().map((paneId) => ({
113
- type: "pane.agent_status_changed",
114
- pane_id: paneId,
115
- })),
116
- { type: "pane.moved" },
117
- { type: "pane.closed" },
118
- ];
119
112
  const unsubscribe = await this.options.client.subscribe(
120
- subscriptions,
121
- (event) => {
122
- if (this.isLive(candidate)) this.options.onEvent(event);
113
+ targets,
114
+ () => {
115
+ if (this.isLive(candidate)) this.options.onChange();
123
116
  },
124
117
  (error) => this.disconnected(candidate, error),
125
118
  candidate.controller.signal,
@@ -132,7 +125,7 @@ export class MonitorEvents {
132
125
  this.subscription = { attempt: candidate, unsubscribe };
133
126
  this.pending = undefined;
134
127
  }
135
- // Herdr baselines status before ACK; reconcile afterward to cover setup transitions.
128
+ // Reconcile after subscription setup to cover transitions during handover.
136
129
  await this.options.reconcile();
137
130
  if (!this.active || epoch !== this.epoch) return;
138
131
  if (key !== this.targetKey()) {
@@ -147,29 +140,7 @@ export class MonitorEvents {
147
140
  attempt?.controller.signal.aborted
148
141
  )
149
142
  return;
150
- let failure = error instanceof Error ? error : new Error(String(error));
151
- if (attempt && isHerdrErrorCode(error, "pane_not_found")) {
152
- try {
153
- // A closed or moved pane can disappear before its lifecycle event arrives.
154
- await this.options.reconcile();
155
- if (!this.active || epoch !== this.epoch) return;
156
- if (attempt.key !== this.targetKey()) {
157
- this.dirty = true;
158
- return;
159
- }
160
- } catch (reconcileError) {
161
- failure =
162
- reconcileError instanceof Error
163
- ? reconcileError
164
- : new Error(String(reconcileError));
165
- }
166
- if (
167
- !this.active ||
168
- epoch !== this.epoch ||
169
- attempt.controller.signal.aborted
170
- )
171
- return;
172
- }
143
+ const failure = error instanceof Error ? error : new Error(String(error));
173
144
  this.warn(failure.message);
174
145
  if (this.options.reconnect === false) throw failure;
175
146
  this.scheduleReconnect();
@@ -213,8 +184,8 @@ export class MonitorEvents {
213
184
  this.warning = state;
214
185
  const message =
215
186
  state === "degraded"
216
- ? "Herdr monitor update failed. Existing stream retained, coverage may be incomplete"
217
- : "Herdr monitoring unavailable";
187
+ ? "Core monitor update failed. Existing stream retained, coverage may be incomplete"
188
+ : "Core monitoring unavailable";
218
189
  this.options.onWarning({
219
190
  state,
220
191
  message: `${message}: ${detail}${this.options.reconnect === false ? "" : ". Retrying"}`,
@@ -1,14 +1,14 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { sameAgentIdentity } from "./agent-identity.js";
3
- import { getAgent, sessionPath } from "./herdr.js";
4
- import { type HerdrConnection, isHerdrErrorCode } from "./herdr-client.js";
3
+ import { getAgent, sessionPath } from "./core/agents.js";
4
+ import type { CoreConnection } from "./core/backend.js";
5
5
  import type { MonitorState } from "./monitor-state.js";
6
6
  import { extensionMessageKey } from "./remote/shepherdr-session.mjs";
7
7
  import type { AssistantReader } from "./session-reader.js";
8
8
  import type { ExtensionMessage, MonitoredAgent, PaneInfo } from "./types.js";
9
9
 
10
10
  interface MonitorExtensionMessagesOptions {
11
- client: HerdrConnection;
11
+ client: CoreConnection;
12
12
  machine: string;
13
13
  machineLabel: () => string;
14
14
  reader: AssistantReader;
@@ -24,8 +24,7 @@ interface MonitorExtensionMessagesOptions {
24
24
 
25
25
  function isMissingAgent(error: unknown): boolean {
26
26
  return (
27
- isHerdrErrorCode(error, "agent_not_found") ||
28
- (error instanceof Error && "kind" in error && error.kind === "not_found")
27
+ error instanceof Error && "kind" in error && error.kind === "not_found"
29
28
  );
30
29
  }
31
30
 
@@ -136,7 +135,7 @@ export class MonitorExtensionMessages {
136
135
  this.options.client,
137
136
  panel.pane_id,
138
137
  ).catch((error: unknown) => {
139
- // Pane closure can precede its lifecycle event or finish an in-flight read.
138
+ // Terminal closure can precede reconciliation or finish an in-flight read.
140
139
  if (isMissingAgent(error)) return undefined;
141
140
  throw error;
142
141
  });
@@ -95,6 +95,7 @@ export function parseMonitoredAgent(
95
95
  const record = value as Record<string, unknown>;
96
96
  if (
97
97
  (record["scope"] !== "task" && record["scope"] !== "persistent") ||
98
+ (record["worker"] !== undefined && record["worker"] !== true) ||
98
99
  typeof record["paneId"] !== "string" ||
99
100
  typeof record["terminalId"] !== "string" ||
100
101
  (record["workspaceId"] !== undefined &&
@@ -131,6 +132,7 @@ export function parseMonitoredAgent(
131
132
  }
132
133
  return {
133
134
  scope: record["scope"],
135
+ ...(record["worker"] === true ? { worker: true } : {}),
134
136
  ...(instructions ? { instructions } : {}),
135
137
  ...(latestInstruction ? { latestInstruction } : {}),
136
138
  activity,
@@ -157,6 +159,7 @@ export function recordForPanel(
157
159
  const cwd = panel.foreground_cwd ?? panel.cwd;
158
160
  return {
159
161
  scope,
162
+ ...(panel.worker ? { worker: true } : {}),
160
163
  activity,
161
164
  paneId: panel.pane_id,
162
165
  terminalId: panel.terminal_id,
@@ -175,6 +178,7 @@ export function sameMonitorRecord(
175
178
  ): boolean {
176
179
  return (
177
180
  left.scope === right.scope &&
181
+ left.worker === right.worker &&
178
182
  left.instructions === right.instructions &&
179
183
  left.latestInstruction === right.latestInstruction &&
180
184
  left.paneId === right.paneId &&
@@ -1,18 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import {
3
- activityForPanel,
4
- activityTask,
5
- isSettledStatus,
6
- sameAgentActivity,
7
- } from "./activity.js";
2
+ import { activityForPanel, activityTask, isSettledStatus } from "./activity.js";
8
3
  import {
9
4
  parseMonitoredAgent,
10
5
  recordForPanel,
11
6
  sameMonitorRecord,
12
7
  } from "./monitor-record.js";
13
8
  import type {
14
- AgentActivity,
15
- AgentStatus,
16
9
  MonitoredAgent,
17
10
  PaneInfo,
18
11
  SessionSnapshot,
@@ -37,11 +30,6 @@ interface ReconcileResult {
37
30
  removed: MonitoredAgent[];
38
31
  }
39
32
 
40
- interface StatusResult {
41
- changed: boolean;
42
- completion?: CompletionCandidate;
43
- }
44
-
45
33
  export class MonitorState {
46
34
  private readonly agents = new Map<string, MonitoredAgent>();
47
35
  private readonly pendingSubmissions = new Set<string>();
@@ -250,79 +238,6 @@ export class MonitorState {
250
238
  return true;
251
239
  }
252
240
 
253
- applyStatus(paneId: string, status: AgentStatus): StatusResult {
254
- const record = this.byPane(paneId);
255
- if (!record) return { changed: false };
256
- // Submission owns the transaction until its receipt decides whether this
257
- // is delegated work at all. The caller reconciles after accepting it.
258
- if (
259
- record.activity.phase === "submitting" &&
260
- this.pendingSubmissions.has(record.activity.attemptId)
261
- )
262
- return { changed: false };
263
- if (status === "working") {
264
- const task = activityTask(record.activity);
265
- const attemptId =
266
- record.activity.phase === "settled"
267
- ? undefined
268
- : record.activity.attemptId;
269
- const expectedUserAfter =
270
- record.activity.phase === "settled"
271
- ? undefined
272
- : record.activity.expectedUserAfter;
273
- const next: AgentActivity = {
274
- phase: "working",
275
- ...(attemptId ? { attemptId } : {}),
276
- ...(expectedUserAfter !== undefined ? { expectedUserAfter } : {}),
277
- ...(task ? { task } : {}),
278
- };
279
- const changed = !sameAgentActivity(record.activity, next);
280
- this.agents.set(record.terminalId, { ...record, activity: next });
281
- return { changed };
282
- }
283
- if (
284
- status === "blocked" &&
285
- record.activity.phase === "settled" &&
286
- record.activity.status !== "blocked"
287
- ) {
288
- const observed = {
289
- ...record,
290
- activity: {
291
- attemptId: randomUUID(),
292
- phase: "working",
293
- } as const,
294
- };
295
- this.agents.set(record.terminalId, observed);
296
- return {
297
- changed: true,
298
- completion: {
299
- record: observed,
300
- requireNewReply: false,
301
- status,
302
- },
303
- };
304
- }
305
- if (isSettledStatus(status) && record.activity.phase !== "settled") {
306
- const task = activityTask(record.activity);
307
- return {
308
- changed: false,
309
- completion: {
310
- record,
311
- requireNewReply: record.activity.phase === "submitting",
312
- status,
313
- ...(task ? { task } : {}),
314
- },
315
- };
316
- }
317
- if (status === "unknown" && record.activity.phase !== "settled") {
318
- return { changed: false };
319
- }
320
- const next: AgentActivity = { phase: "settled", status };
321
- const changed = !sameAgentActivity(record.activity, next);
322
- this.agents.set(record.terminalId, { ...record, activity: next });
323
- return { changed };
324
- }
325
-
326
241
  reconcile(
327
242
  snapshot: SessionSnapshot,
328
243
  controllingPaneId?: string,
@@ -422,21 +337,6 @@ export class MonitorState {
422
337
  return { changed, completions, removed };
423
338
  }
424
339
 
425
- movePane(
426
- previousPaneId: string,
427
- pane: { pane_id: string; tab_id?: string; workspace_id?: string },
428
- ): boolean {
429
- const record = this.byPane(previousPaneId);
430
- if (!record) return false;
431
- this.agents.set(record.terminalId, {
432
- ...record,
433
- paneId: pane.pane_id,
434
- ...(pane.workspace_id ? { workspaceId: pane.workspace_id } : {}),
435
- ...(pane.tab_id ? { tabId: pane.tab_id } : {}),
436
- });
437
- return true;
438
- }
439
-
440
340
  complete(
441
341
  terminalId: string,
442
342
  status: SettledAgentStatus,
package/src/monitor.ts CHANGED
@@ -3,13 +3,13 @@ import type {
3
3
  ExtensionContext,
4
4
  } from "@earendil-works/pi-coding-agent";
5
5
  import { isSettledStatus } from "./activity.js";
6
- import { getSnapshot } from "./herdr.js";
7
- import { type HerdrConnection, isDispatchRejected } from "./herdr-client.js";
6
+ import { getSnapshot } from "./core/agents.js";
7
+ import type { CoreConnection } from "./core/backend.js";
8
8
  import { injectAgentEvent } from "./messages/events.js";
9
- import { parseMonitorEvent } from "./monitor-event.js";
10
9
  import { MonitorEvents } from "./monitor-events.js";
11
10
  import { MonitorExtensionMessages } from "./monitor-extension-messages.js";
12
11
  import { MonitorState, type WorkAttempt } from "./monitor-state.js";
12
+ import { isDispatchRejected } from "./remote/shepherdr-peer.mjs";
13
13
  import { type AssistantReader, SessionReader } from "./session-reader.js";
14
14
  import {
15
15
  type ClaimedSettlement,
@@ -18,7 +18,6 @@ import {
18
18
  } from "./settlement/index.js";
19
19
  import type {
20
20
  ExtensionReply,
21
- HerdrEvent,
22
21
  MonitoredAgent,
23
22
  MonitoringIssue,
24
23
  PaneInfo,
@@ -26,7 +25,7 @@ import type {
26
25
  } from "./types.js";
27
26
 
28
27
  interface AgentMonitorOptions {
29
- client: HerdrConnection;
28
+ client: CoreConnection;
30
29
  machine: string;
31
30
  machineLabel: () => string;
32
31
  onChange: () => void;
@@ -40,7 +39,7 @@ interface AgentMonitorOptions {
40
39
  }
41
40
 
42
41
  export class AgentMonitor {
43
- readonly client: HerdrConnection;
42
+ readonly client: CoreConnection;
44
43
  readonly machine: string;
45
44
  private readonly onChange: () => void;
46
45
  private readonly onRefresh: () => void;
@@ -96,15 +95,19 @@ export class AgentMonitor {
96
95
  label: options.machineLabel,
97
96
  operatorPrefix: options.operatorPrefix,
98
97
  },
98
+ async (record) => {
99
+ if (this.state.byPane(record.paneId)?.terminalId === record.terminalId)
100
+ await this.unwatch(record.paneId);
101
+ },
99
102
  );
100
103
  this.events = new MonitorEvents({
101
104
  client: this.client,
102
105
  reconnect: options.reconnect,
103
- onEvent: (event) => this.handleEvent(event),
106
+ onChange: () => this.invalidate(),
104
107
  reconcile: () => this.reconcileNow(),
105
108
  onWarning: options.onWarning,
106
109
  onRecovered: options.onRecovered,
107
- targets: () => this.list().map((record) => record.paneId),
110
+ targets: () => this.list().map((record) => record.terminalId),
108
111
  });
109
112
  }
110
113
 
@@ -238,7 +241,7 @@ export class AgentMonitor {
238
241
  await this.reconcileNow();
239
242
  } catch (reconcileError) {
240
243
  this.context?.ui.notify(
241
- `Herdr prompt outcome remains uncertain: ${reconcileError instanceof Error ? reconcileError.message : String(reconcileError)}`,
244
+ `Core prompt outcome remains uncertain: ${reconcileError instanceof Error ? reconcileError.message : String(reconcileError)}`,
242
245
  "warning",
243
246
  );
244
247
  }
@@ -290,69 +293,38 @@ export class AgentMonitor {
290
293
  if (changed || persistRestoration) this.persist();
291
294
  else this.onRefresh();
292
295
  await this.extensionMessages.refresh(snapshot.agents);
296
+ // Snapshot removals must also retire their subscription coverage.
297
+ if (removed.length) void this.events.refresh().catch(() => undefined);
293
298
  for (const completion of completions) {
294
299
  void this.report(completion);
295
300
  }
296
301
  }
297
302
 
298
- private handleEvent(event: HerdrEvent): void {
299
- if (event.event === "core.reconcile") {
300
- const generation = this.activationGeneration;
301
- const context = this.context;
302
- this.coreDirty = true;
303
- if (this.coreReconcile) return;
304
- this.coreReconcile = Promise.resolve()
305
- .then(async () => {
306
- while (this.coreDirty && generation === this.activationGeneration) {
307
- this.coreDirty = false;
308
- await this.reconcile(generation, context);
309
- }
310
- })
311
- .catch((error) => {
312
- if (generation === this.activationGeneration) {
313
- this.context?.ui.notify(
314
- `Core monitoring reconciliation failed: ${String(error)}`,
315
- "warning",
316
- );
317
- void this.events.retry().catch(() => undefined);
318
- }
319
- })
320
- .finally(() => {
321
- if (generation === this.activationGeneration)
322
- this.coreReconcile = undefined;
323
- });
324
- return;
325
- }
326
- const parsed = parseMonitorEvent(event);
327
- if (!parsed) return;
328
- if (parsed.type === "closed") {
329
- const record = this.state.removePane(parsed.paneId);
330
- if (record) {
331
- this.settlements.releaseAgentClaim(
332
- record,
333
- new Error(`${parsed.paneId} closed before its work settled`),
334
- );
335
- this.persist();
336
- this.refreshAfterEvent();
337
- }
338
- return;
339
- }
340
- if (parsed.type === "moved") {
341
- if (!this.state.movePane(parsed.previousPaneId, parsed.pane)) return;
342
- this.persist();
343
- this.refreshAfterEvent();
344
- return;
345
- }
346
- const result = this.state.applyStatus(parsed.paneId, parsed.status);
347
- if (result.changed) this.persist();
348
- if (result.completion) {
349
- void this.report({
350
- ...result.completion,
351
- ...(parsed.blockedMessage
352
- ? { blockedMessage: parsed.blockedMessage }
353
- : {}),
303
+ private invalidate(): void {
304
+ const generation = this.activationGeneration;
305
+ const context = this.context;
306
+ this.coreDirty = true;
307
+ if (this.coreReconcile) return;
308
+ this.coreReconcile = Promise.resolve()
309
+ .then(async () => {
310
+ while (this.coreDirty && generation === this.activationGeneration) {
311
+ this.coreDirty = false;
312
+ await this.reconcile(generation, context);
313
+ }
314
+ })
315
+ .catch((error) => {
316
+ if (generation === this.activationGeneration) {
317
+ this.context?.ui.notify(
318
+ `Core monitoring reconciliation failed: ${String(error)}`,
319
+ "warning",
320
+ );
321
+ void this.events.retry().catch(() => undefined);
322
+ }
323
+ })
324
+ .finally(() => {
325
+ if (generation === this.activationGeneration)
326
+ this.coreReconcile = undefined;
354
327
  });
355
- }
356
328
  }
357
329
 
358
330
  private refreshAfterEvent(): void {
@@ -0,0 +1,67 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { ContextSharingService } from "@howaboua/pi-agent-comms/context-sharing";
6
+
7
+ export const NOTES_UNAVAILABLE =
8
+ "Shared Notes require active, compatible Notes Compaction or Agent Comms in both sessions. Enable or update it, then reload Pi. Other agent operations remain available.";
9
+
10
+ /** Notes' public v1 broker, shared with released Notes Compaction. */
11
+ export function connectNotesContextSharing(
12
+ pi: ExtensionAPI,
13
+ onAvailable: () => void,
14
+ ) {
15
+ let service: ContextSharingService | undefined;
16
+ let context: ExtensionContext | undefined;
17
+ let failure: Error | undefined;
18
+ pi.on("session_start", (_event, ctx) => {
19
+ context = ctx;
20
+ if (failure) ctx.ui.notify(failure.message, "error");
21
+ });
22
+ const off = pi.events.on(
23
+ "pi-notes-compaction:context-sharing:available",
24
+ (value) => {
25
+ if (
26
+ !value ||
27
+ typeof value !== "object" ||
28
+ !("protocol" in value) ||
29
+ value.protocol !== 1 ||
30
+ ![
31
+ "canCreateChild",
32
+ "describe",
33
+ "verify",
34
+ "createChild",
35
+ "bind",
36
+ "execute",
37
+ "registerRouter",
38
+ ].every(
39
+ (key) =>
40
+ key in value && typeof Reflect.get(value, key) === "function",
41
+ )
42
+ ) {
43
+ failure = new Error(
44
+ "Shared Notes could not connect. Update their extension and reload Pi. Other agent operations remain available.",
45
+ );
46
+ context?.ui.notify(failure.message, "error");
47
+ throw failure;
48
+ }
49
+ failure = undefined;
50
+ service = value as ContextSharingService;
51
+ onAvailable();
52
+ },
53
+ );
54
+ pi.events.emit("pi-notes-compaction:context-sharing:request", {
55
+ protocol: 1,
56
+ });
57
+ return {
58
+ get service() {
59
+ return service;
60
+ },
61
+ dispose() {
62
+ off();
63
+ service = undefined;
64
+ context = undefined;
65
+ },
66
+ };
67
+ }