@howaboua/pi-shepherdr 0.2.23 → 0.2.25

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 (96) hide show
  1. package/CHANGELOG.md +20 -18
  2. package/README.md +80 -69
  3. package/biome.json +1 -1
  4. package/index.ts +4 -2
  5. package/package.json +14 -9
  6. package/src/agents-contract.ts +9 -6
  7. package/src/agents-discovery.ts +78 -37
  8. package/src/agents-focus.ts +17 -11
  9. package/src/agents-reply.ts +1 -1
  10. package/src/agents-spawn.ts +24 -8
  11. package/src/agents-tool.ts +26 -8
  12. package/src/agents-work.ts +5 -5
  13. package/src/attachment-notes.ts +14 -2
  14. package/src/attachment-protocol.ts +21 -4
  15. package/src/attachment-routing.ts +1 -1
  16. package/src/attachment-target.ts +5 -2
  17. package/src/attachment.ts +4 -3
  18. package/src/board/host.ts +5 -3
  19. package/src/board/membership.ts +1 -1
  20. package/src/close-idle.ts +89 -0
  21. package/src/{control-panel-actions.ts → control-panel/actions.ts} +2 -2
  22. package/src/{control-panel.ts → control-panel/index.ts} +7 -5
  23. package/src/{control-panel-items.ts → control-panel/items.ts} +17 -5
  24. package/src/{control-panel-view.ts → control-panel/view.ts} +9 -5
  25. package/src/controller.ts +17 -5
  26. package/src/core/AGENTS.md +5 -0
  27. package/src/core/backend.ts +266 -0
  28. package/src/core/client.ts +249 -0
  29. package/src/core/context-relay.mjs +111 -0
  30. package/src/core/focus-channel-helper.mjs +165 -0
  31. package/src/core/focus-channel-stream.ts +140 -0
  32. package/src/core/focus-channel-wire.mjs +160 -0
  33. package/src/core/focus-channel.ts +213 -0
  34. package/src/core/focus-window.ts +192 -0
  35. package/src/core/pi-executable.mjs +34 -0
  36. package/src/core/protocol.ts +116 -0
  37. package/src/core/registration.ts +51 -0
  38. package/src/core/remote-endpoint.ts +119 -0
  39. package/src/core/remote-exec.ts +122 -0
  40. package/src/core/remote-helper.mjs +244 -0
  41. package/src/core/remote-reader.ts +67 -0
  42. package/src/core/remote-relay.ts +191 -0
  43. package/src/core/request.ts +124 -0
  44. package/src/core/spawn.ts +177 -0
  45. package/src/core/status.ts +68 -0
  46. package/src/core/terminal.ts +103 -0
  47. package/src/fleet/catalog.ts +83 -0
  48. package/src/fleet/connection.ts +111 -0
  49. package/src/fleet/index.ts +413 -0
  50. package/src/fleet/inspection.ts +159 -0
  51. package/src/fleet/machine.ts +55 -0
  52. package/src/fleet/monitor.ts +85 -0
  53. package/src/fleet/persistence.ts +65 -0
  54. package/src/fleet/reconnect.ts +75 -0
  55. package/src/fleet/setup.ts +133 -0
  56. package/src/herdr.ts +25 -5
  57. package/src/launch-contract.ts +48 -0
  58. package/src/launch-location.ts +151 -0
  59. package/src/launch.ts +30 -183
  60. package/src/messages/attachments.ts +39 -0
  61. package/src/messages/attribution.ts +84 -0
  62. package/src/messages/event-details.ts +69 -0
  63. package/src/messages/events.ts +195 -0
  64. package/src/messages/focus.ts +47 -0
  65. package/src/messages/guidance.ts +83 -0
  66. package/src/messages/render.ts +89 -0
  67. package/src/messages/voice-announcements.ts +79 -0
  68. package/src/monitor-record.ts +9 -6
  69. package/src/monitor.ts +33 -2
  70. package/src/peer-commands.ts +11 -0
  71. package/src/peer-inbox-delivery.ts +171 -0
  72. package/src/peer-inbox-focus.ts +113 -0
  73. package/src/peer-inbox.ts +127 -209
  74. package/src/remote/client.ts +127 -0
  75. package/src/remote/context-relay.ts +84 -0
  76. package/src/remote/deployment.ts +179 -0
  77. package/src/remote/focus-channels.ts +89 -0
  78. package/src/remote/shepherdr-context.mjs +1 -1
  79. package/src/remote/shepherdr-peer.mjs +18 -5
  80. package/src/remote/shepherdr-session.mjs +9 -2
  81. package/src/remote/shepherdr.mjs +1 -1
  82. package/src/remote/transport.ts +369 -0
  83. package/src/settlement/collector.ts +122 -0
  84. package/src/settlement/delivery.ts +144 -0
  85. package/src/{settlement.ts → settlement/index.ts} +35 -233
  86. package/src/shared-context-host.ts +40 -14
  87. package/src/shared-context.ts +44 -6
  88. package/src/spawn-context.ts +24 -17
  89. package/src/spawn-ownership.ts +91 -0
  90. package/src/types.ts +9 -5
  91. package/src/voice-handoff.ts +1 -1
  92. package/src/worker-ownership.ts +92 -0
  93. package/src/worker-service.ts +14 -83
  94. package/src/fleet.ts +0 -702
  95. package/src/messages.ts +0 -637
  96. package/src/remote-client.ts +0 -761
@@ -6,51 +6,23 @@ import {
6
6
  activityAttemptId,
7
7
  activityExpectedUser,
8
8
  activityTask,
9
- isSettledStatus,
10
- } from "./activity.js";
11
- import { getAgent, getSnapshot, sessionPath } from "./herdr.js";
12
- import type { HerdrConnection } from "./herdr-client.js";
13
- import { injectAgentEvent } from "./messages.js";
14
- import type { MonitorState, WorkAttempt } from "./monitor-state.js";
15
- import { type AssistantReader, SessionReader } from "./session-reader.js";
9
+ } from "../activity.js";
10
+ import type { HerdrConnection } from "../herdr-client.js";
11
+ import type { MonitorState, WorkAttempt } from "../monitor-state.js";
12
+ import type { AssistantReader } from "../session-reader.js";
16
13
  import type {
17
- ExtensionMessage,
18
14
  ExtensionReply,
19
15
  LatestAssistant,
20
16
  MonitoredAgent,
21
17
  PaneInfo,
22
18
  SessionView,
23
19
  SettledAgentStatus,
24
- } from "./types.js";
20
+ } from "../types.js";
21
+ import { blockedSettlement, SettlementCollector } from "./collector.js";
22
+ import { SettlementDelivery } from "./delivery.js";
25
23
 
26
- interface SettlementLabels {
27
- tab?: string;
28
- workspace?: string;
29
- }
30
-
31
- interface CollectedSettlement {
32
- agent: PaneInfo;
33
- extensionMessages?: ExtensionMessage[];
34
- labels: SettlementLabels;
35
- reply?: LatestAssistant;
36
- status: SettledAgentStatus;
37
- }
38
-
39
- interface CollectedSettlementWithSession extends CollectedSettlement {
40
- session: SessionView;
41
- }
42
-
43
- export interface ClaimedSettlement extends CollectedSettlement {
44
- blockedMessage?: string;
45
- record: MonitoredAgent;
46
- }
47
-
48
- interface SettlementClaim {
49
- replyingTo?: ExtensionReply;
50
- cleanup(): void;
51
- reject(error: Error): void;
52
- resolve(settlement: ClaimedSettlement): void;
53
- }
24
+ export type { ClaimedSettlement } from "./delivery.js";
25
+ export { SettlementCollector };
54
26
 
55
27
  interface SettlementRetry {
56
28
  attemptId: string | undefined;
@@ -66,26 +38,6 @@ function attemptKey(terminalId: string, attemptId: string | undefined): string {
66
38
  return JSON.stringify([terminalId, attemptId ?? null]);
67
39
  }
68
40
 
69
- function blockedSettlement(
70
- record: MonitoredAgent,
71
- ): CollectedSettlementWithSession {
72
- return {
73
- agent: {
74
- agent: "pi",
75
- agent_status: "blocked",
76
- ...(record.cwd ? { cwd: record.cwd } : {}),
77
- ...(record.name ? { name: record.name } : {}),
78
- pane_id: record.paneId,
79
- tab_id: record.tabId,
80
- terminal_id: record.terminalId,
81
- workspace_id: record.workspaceId,
82
- },
83
- labels: {},
84
- session: {},
85
- status: "blocked",
86
- };
87
- }
88
-
89
41
  export interface SettlementRequest {
90
42
  blockedMessage?: string;
91
43
  record: MonitoredAgent;
@@ -106,91 +58,12 @@ interface PendingBlockedSettlement {
106
58
  retry?: SettlementRetry;
107
59
  }
108
60
 
109
- export class SettlementCollector {
110
- private readonly client: HerdrConnection;
111
- private readonly reader: AssistantReader;
112
-
113
- constructor(
114
- client: HerdrConnection,
115
- reader: AssistantReader = new SessionReader(),
116
- ) {
117
- this.client = client;
118
- this.reader = reader;
119
- }
120
-
121
- async latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
122
- try {
123
- return await this.reader.latest(sessionPath(panel));
124
- } catch (error) {
125
- if (panel.agent_status !== "blocked") throw error;
126
- return undefined;
127
- }
128
- }
129
-
130
- view(panel: PaneInfo): Promise<SessionView> {
131
- return this.reader.view(sessionPath(panel));
132
- }
133
-
134
- async collect(
135
- record: MonitoredAgent,
136
- reportedStatus?: "blocked",
137
- ): Promise<CollectedSettlementWithSession | undefined> {
138
- const [current, snapshot] = await Promise.all([
139
- getAgent(this.client, record.paneId),
140
- getSnapshot(this.client),
141
- ]);
142
- if (current.terminal_id !== record.terminalId || current.agent !== "pi") {
143
- return reportedStatus === "blocked"
144
- ? blockedSettlement(record)
145
- : undefined;
146
- }
147
- const status =
148
- reportedStatus ??
149
- (isSettledStatus(current.agent_status)
150
- ? current.agent_status
151
- : undefined);
152
- if (!status) return undefined;
153
- let view: SessionView;
154
- try {
155
- view = await this.reader.view(sessionPath(current));
156
- } catch (error) {
157
- if (status !== "blocked") throw error;
158
- view = {};
159
- }
160
- const workspace = snapshot.workspaces.find(
161
- (candidate) => candidate.workspace_id === current.workspace_id,
162
- )?.label;
163
- const tab = snapshot.tabs.find(
164
- (candidate) => candidate.tab_id === current.tab_id,
165
- )?.label;
166
- return {
167
- agent: current,
168
- labels: {
169
- ...(workspace ? { workspace } : {}),
170
- ...(tab ? { tab } : {}),
171
- },
172
- ...(view.assistant ? { reply: view.assistant } : {}),
173
- ...(view.extensionMessages
174
- ? { extensionMessages: view.extensionMessages }
175
- : {}),
176
- session: view,
177
- status,
178
- };
179
- }
180
- }
181
-
182
61
  export class SettlementReporter {
183
62
  private readonly collector: SettlementCollector;
184
63
  private readonly persist: () => void;
185
- private readonly pi: ExtensionAPI;
186
- private readonly origin: {
187
- machine: string;
188
- label: () => string;
189
- operatorPrefix: string;
190
- };
191
64
  private readonly reporting = new Map<string, SettledAgentStatus>();
192
65
  private readonly pendingBlocked = new Map<string, PendingBlockedSettlement>();
193
- private readonly claims = new Map<string, SettlementClaim>();
66
+ private readonly delivery: SettlementDelivery;
194
67
  private readonly retries = new Map<string, NodeJS.Timeout>();
195
68
  private readonly state: MonitorState;
196
69
 
@@ -202,11 +75,10 @@ export class SettlementReporter {
202
75
  reader: AssistantReader | undefined,
203
76
  origin: { machine: string; label: () => string; operatorPrefix: string },
204
77
  ) {
205
- this.pi = pi;
78
+ this.delivery = new SettlementDelivery(pi, origin);
206
79
  this.collector = new SettlementCollector(client, reader);
207
80
  this.state = state;
208
81
  this.persist = persist;
209
- this.origin = origin;
210
82
  }
211
83
 
212
84
  latest(panel: PaneInfo): Promise<LatestAssistant | undefined> {
@@ -220,11 +92,7 @@ export class SettlementReporter {
220
92
  stop(): void {
221
93
  this.reporting.clear();
222
94
  this.pendingBlocked.clear();
223
- for (const claim of this.claims.values()) {
224
- claim.cleanup();
225
- claim.reject(new Error("Shepherdr monitor stopped"));
226
- }
227
- this.claims.clear();
95
+ this.delivery.stop();
228
96
  for (const timer of this.retries.values()) clearTimeout(timer);
229
97
  this.retries.clear();
230
98
  }
@@ -233,51 +101,15 @@ export class SettlementReporter {
233
101
  attempt: WorkAttempt,
234
102
  signal: AbortSignal,
235
103
  replyingTo?: ExtensionReply,
236
- ): Promise<ClaimedSettlement> | undefined {
237
- signal.throwIfAborted();
238
- // Updates share the worker's current settlement, without stealing its waiter.
239
- if (this.claims.has(attempt.attemptId)) return;
240
- return new Promise<ClaimedSettlement>((resolve, reject) => {
241
- const abort = () => {
242
- const claim = this.claims.get(attempt.attemptId);
243
- if (!claim) return;
244
- this.claims.delete(attempt.attemptId);
245
- claim.cleanup();
246
- reject(
247
- signal.reason instanceof Error
248
- ? signal.reason
249
- : new Error("Shepherdr wait aborted"),
250
- );
251
- };
252
- const claim: SettlementClaim = {
253
- ...(replyingTo ? { replyingTo } : {}),
254
- cleanup: () => signal.removeEventListener("abort", abort),
255
- reject,
256
- resolve,
257
- };
258
- this.claims.set(attempt.attemptId, claim);
259
- signal.addEventListener("abort", abort, { once: true });
260
- });
261
- }
262
-
263
- releaseClaim(attempt: WorkAttempt | undefined, error: unknown): void {
264
- if (!attempt) return;
265
- this.releaseAttempt(attempt.attemptId, error);
104
+ ) {
105
+ return this.delivery.claim(attempt, signal, replyingTo);
266
106
  }
267
-
268
- releaseAgentClaim(record: MonitoredAgent, error: unknown): void {
269
- const attemptId = activityAttemptId(record.activity);
270
- if (attemptId) this.releaseAttempt(attemptId, error);
107
+ releaseClaim(attempt: WorkAttempt | undefined, error: unknown) {
108
+ this.delivery.releaseClaim(attempt, error);
271
109
  }
272
-
273
- private releaseAttempt(attemptId: string, error: unknown): void {
274
- const claim = this.claims.get(attemptId);
275
- if (!claim) return;
276
- this.claims.delete(attemptId);
277
- claim.cleanup();
278
- claim.reject(error instanceof Error ? error : new Error(String(error)));
110
+ releaseAgentClaim(record: MonitoredAgent, error: unknown) {
111
+ this.delivery.releaseAgentClaim(record, error);
279
112
  }
280
-
281
113
  async report(
282
114
  lifecycle: SettlementLifecycle,
283
115
  request: SettlementRequest,
@@ -306,7 +138,7 @@ export class SettlementReporter {
306
138
  this.reporting.set(key, request.status);
307
139
  try {
308
140
  const replyingTo = retryState.attemptId
309
- ? this.claims.get(retryState.attemptId)?.replyingTo
141
+ ? this.delivery.replyingTo(retryState.attemptId)
310
142
  : undefined;
311
143
  const settlement = await this.collector.collect(
312
144
  request.record,
@@ -322,7 +154,7 @@ export class SettlementReporter {
322
154
  ) {
323
155
  if (request.status !== "blocked") return;
324
156
  this.clearRetry(request.record.terminalId, retryState.attemptId);
325
- this.deliverSettlement(
157
+ this.delivery.deliverSettlement(
326
158
  lifecycle,
327
159
  request.record,
328
160
  settlement,
@@ -335,6 +167,18 @@ export class SettlementReporter {
335
167
  const retryRequest = task ? { ...request, task } : request;
336
168
  const expectedUser = activityExpectedUser(current.activity);
337
169
  const blocked = settlement.status === "blocked";
170
+ // Status and session writes arrive separately. A tool call is not a reply,
171
+ // even if done arrives before the final message is visible on disk.
172
+ if (!blocked && settlement.session.assistantPending) {
173
+ if (!this.retry(lifecycle, retryRequest, retryState)) {
174
+ this.failReconciliation(
175
+ lifecycle,
176
+ current,
177
+ "the final assistant reply was not persisted",
178
+ );
179
+ }
180
+ return;
181
+ }
338
182
  // Closing a message and publishing resumed status use separate transports.
339
183
  if (blocked && replyingTo) {
340
184
  if (
@@ -405,7 +249,7 @@ export class SettlementReporter {
405
249
  ) {
406
250
  this.clearRetry(current.terminalId, retryState.attemptId);
407
251
  this.persist();
408
- this.deliverSettlement(
252
+ this.delivery.deliverSettlement(
409
253
  lifecycle,
410
254
  current,
411
255
  settlement,
@@ -430,7 +274,7 @@ export class SettlementReporter {
430
274
  ) {
431
275
  this.persist();
432
276
  }
433
- this.deliverSettlement(
277
+ this.delivery.deliverSettlement(
434
278
  lifecycle,
435
279
  currentOwnsAttempt ? current : request.record,
436
280
  blockedSettlement(current),
@@ -473,48 +317,6 @@ export class SettlementReporter {
473
317
  }
474
318
  }
475
319
 
476
- private deliverSettlement(
477
- lifecycle: SettlementLifecycle,
478
- record: MonitoredAgent,
479
- settlement: CollectedSettlementWithSession,
480
- attemptId: string | undefined,
481
- blockedMessage: string | undefined,
482
- reply: LatestAssistant | undefined,
483
- ): void {
484
- const claim = attemptId ? this.claims.get(attemptId) : undefined;
485
- if (claim && attemptId) {
486
- this.claims.delete(attemptId);
487
- claim.cleanup();
488
- const {
489
- reply: _latestReply,
490
- session: _session,
491
- ...claimedSettlement
492
- } = settlement;
493
- claim.resolve({
494
- ...claimedSettlement,
495
- record,
496
- ...(blockedMessage ? { blockedMessage } : {}),
497
- ...(reply ? { reply } : {}),
498
- });
499
- return;
500
- }
501
- injectAgentEvent(this.pi, lifecycle.context, {
502
- agent: settlement.agent,
503
- agentToolName: "agents",
504
- ...(settlement.extensionMessages
505
- ? { extensionMessages: settlement.extensionMessages }
506
- : {}),
507
- machine: this.origin.machine,
508
- machineLabel: this.origin.label(),
509
- operatorPrefix: this.origin.operatorPrefix,
510
- ...(blockedMessage ? { blockedMessage } : {}),
511
- labels: settlement.labels,
512
- record,
513
- ...(reply ? { reply } : {}),
514
- status: settlement.status,
515
- });
516
- }
517
-
518
320
  private clearRetry(terminalId: string, attemptId: string | undefined): void {
519
321
  const key = attemptKey(terminalId, attemptId);
520
322
  const retry = this.retries.get(key);
@@ -580,7 +382,7 @@ export class SettlementReporter {
580
382
  " after " +
581
383
  SETTLEMENT_RETRY_WINDOW_SECONDS +
582
384
  " seconds";
583
- if (attemptId) this.releaseAttempt(attemptId, new Error(message));
385
+ if (attemptId) this.delivery.releaseAttempt(attemptId, new Error(message));
584
386
  lifecycle.context.ui.notify(message, "warning");
585
387
  }
586
388
  }
@@ -5,10 +5,10 @@ import type {
5
5
  import type {
6
6
  SharedContextRequest,
7
7
  SharedContextResult,
8
- } from "@howaboua/pi-codex-conversion/context-sharing";
8
+ } from "@howaboua/pi-notes-compaction/context-sharing";
9
9
  import { attachmentOwner, attachmentRoutes } from "./attachment-protocol.js";
10
10
  import type { AgentBoard } from "./board/host.js";
11
- import type { AgentFleet } from "./fleet.js";
11
+ import type { AgentFleet } from "./fleet/index.js";
12
12
  import {
13
13
  listenContext,
14
14
  sessionContextPath,
@@ -21,37 +21,60 @@ export async function registerSharedAgentContext(
21
21
  board: AgentBoard,
22
22
  ): Promise<SharedAgentContext> {
23
23
  let api:
24
- | typeof import("@howaboua/pi-codex-conversion/context-sharing")
24
+ | typeof import("@howaboua/pi-notes-compaction/context-sharing")
25
25
  | undefined;
26
26
  try {
27
- api = await import("@howaboua/pi-codex-conversion/context-sharing");
27
+ api = await import("@howaboua/pi-notes-compaction/context-sharing");
28
28
  } catch (error) {
29
29
  const failure = error as { code?: string; message?: string };
30
30
  const missing = failure.message?.match(
31
31
  /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
32
32
  )?.[1];
33
- const module = "@howaboua/pi-codex-conversion/context-sharing";
33
+ const module = "@howaboua/pi-notes-compaction/context-sharing";
34
34
  const unavailable =
35
35
  ((failure.code === "ERR_MODULE_NOT_FOUND" ||
36
36
  failure.code === "MODULE_NOT_FOUND") &&
37
- (missing === "@howaboua/pi-codex-conversion" ||
37
+ (missing === "@howaboua/pi-notes-compaction" ||
38
38
  missing === module ||
39
39
  missing?.endsWith(`/${module}`))) ||
40
40
  (failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" &&
41
- failure.message?.includes("@howaboua/pi-codex-conversion") &&
41
+ failure.message?.includes("@howaboua/pi-notes-compaction") &&
42
42
  failure.message.includes("./context-sharing"));
43
43
  if (!unavailable)
44
44
  throw new Error(
45
- "Update pi-codex-conversion to use shared agent context",
45
+ "Update pi-notes-compaction to use shared agent context",
46
46
  { cause: error },
47
47
  );
48
48
  }
49
- const connection = api?.connectCodexContextSharing(pi);
49
+ const connection = api?.connectNotesContextSharing(pi);
50
+ let relationships:
51
+ | ReturnType<
52
+ typeof import("@howaboua/pi-codex-conversion/agent-relationship")["connectCodexAgentRelationships"]
53
+ >
54
+ | undefined;
55
+ try {
56
+ const relationshipApi = await import(
57
+ "@howaboua/pi-codex-conversion/agent-relationship"
58
+ );
59
+ relationships = relationshipApi.connectCodexAgentRelationships(pi);
60
+ } catch (error) {
61
+ const failure = error as { code?: string; message?: string };
62
+ if (
63
+ !(
64
+ (failure.code === "ERR_MODULE_NOT_FOUND" ||
65
+ failure.code === "MODULE_NOT_FOUND" ||
66
+ failure.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") &&
67
+ failure.message?.includes("pi-codex-conversion")
68
+ )
69
+ )
70
+ throw error;
71
+ }
50
72
  const shared = new SharedAgentContext(
51
73
  pi,
52
74
  fleet,
53
75
  () => connection?.service,
54
76
  board,
77
+ () => relationships?.service,
55
78
  );
56
79
  let close: (() => Promise<void>) | undefined;
57
80
  let unregister: (() => void) | undefined;
@@ -103,8 +126,6 @@ export async function registerSharedAgentContext(
103
126
  signal,
104
127
  );
105
128
  if (attached) return attached;
106
- if (connection?.service?.describe(context)?.storage === "remote")
107
- return undefined;
108
129
  return shared.handle(
109
130
  context,
110
131
  { operation: "context", request, visited: [] },
@@ -124,14 +145,19 @@ export async function registerSharedAgentContext(
124
145
  ),
125
146
  );
126
147
  });
127
- pi.on("resources_discover", async (_event, ctx) => publish(ctx));
148
+ pi.on("resources_discover", async (_event, ctx) => {
149
+ await publish(ctx);
150
+ await fleet.restoreSharing(ctx);
151
+ });
128
152
  pi.on("session_shutdown", async () => {
129
153
  unregister?.();
130
154
  await close?.();
131
155
  connection?.dispose();
156
+ relationships?.dispose();
132
157
  });
133
- fleet.setContextRelay((ctx, request, signal) =>
134
- shared.handle(ctx, request, signal),
158
+ fleet.setContextRelay(
159
+ (ctx, request, signal) => shared.handle(ctx, request, signal),
160
+ (ctx, machine) => shared.needsRelay(ctx, machine),
135
161
  );
136
162
  return shared;
137
163
  }
@@ -3,17 +3,22 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import { binding, isBoardEnvelope } from "@howaboua/pi-agent-board/integration";
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";
7
12
  import type {
8
13
  ContextSharingService,
9
14
  SharedContextRequest,
10
15
  SharedContextResult,
11
- } from "@howaboua/pi-codex-conversion/context-sharing";
16
+ } from "@howaboua/pi-notes-compaction/context-sharing";
12
17
  import { Check } from "typebox/value";
13
18
  import { AgentAttachment } from "./attachment.js";
14
- import { Identity } from "./attachment-protocol.js";
19
+ import { attachmentRoutes, Identity } from "./attachment-protocol.js";
15
20
  import type { AgentBoard } from "./board/host.js";
16
- import type { AgentFleet } from "./fleet.js";
21
+ import type { AgentFleet } from "./fleet/index.js";
17
22
  import { sessionPath } from "./herdr.js";
18
23
  import {
19
24
  requestContext,
@@ -35,6 +40,9 @@ export class SharedAgentContext {
35
40
  private readonly fleet: AgentFleet;
36
41
  private readonly getService: () => ContextSharingService | undefined;
37
42
  private readonly board: AgentBoard;
43
+ private readonly getRelationships: () =>
44
+ | CodexAgentRelationshipService
45
+ | undefined;
38
46
  private running = false;
39
47
  readonly attachment: AgentAttachment;
40
48
  readonly spawns: SpawnContext;
@@ -44,12 +52,14 @@ export class SharedAgentContext {
44
52
  fleet: AgentFleet,
45
53
  getService: () => ContextSharingService | undefined,
46
54
  board: AgentBoard,
55
+ getRelationships: () => CodexAgentRelationshipService | undefined,
47
56
  ) {
48
57
  this.fleet = fleet;
49
58
  this.getService = getService;
50
59
  this.board = board;
60
+ this.getRelationships = getRelationships;
51
61
  this.attachment = new AgentAttachment(pi, board, getService);
52
- this.spawns = new SpawnContext(pi, getService);
62
+ this.spawns = new SpawnContext(pi, getService, getRelationships);
53
63
  pi.on("before_agent_start", () => {
54
64
  this.running = true;
55
65
  });
@@ -58,6 +68,34 @@ export class SharedAgentContext {
58
68
  });
59
69
  }
60
70
 
71
+ needsRelay(ctx: ExtensionContext, machine: string): boolean {
72
+ if (children(ctx).some((child) => child.machine === machine)) return true;
73
+ if (
74
+ attachmentRoutes(ctx).some(
75
+ (route) =>
76
+ route.machine === machine &&
77
+ ((route.plan.context && !route.detached?.context) ||
78
+ (route.plan.board && !route.detached?.board)),
79
+ )
80
+ )
81
+ return true;
82
+ const identity = this.getService()?.describe(ctx);
83
+ if (!identity) return false;
84
+ return ctx.sessionManager.getEntries().some((entry) => {
85
+ if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
86
+ return false;
87
+ const child = entry.data as Partial<Member> | undefined;
88
+ return (
89
+ child?.machine === machine &&
90
+ child.threadId === identity.threadId &&
91
+ child.sessionId === identity.sessionId &&
92
+ typeof child.sessionFile === "string" &&
93
+ !!child.sessionFile &&
94
+ typeof child.agentName === "string"
95
+ );
96
+ });
97
+ }
98
+
61
99
  async handle(
62
100
  ctx: ExtensionContext,
63
101
  value: unknown,
@@ -149,7 +187,7 @@ export class SharedAgentContext {
149
187
  }
150
188
  if ("operation" in value && value.operation === "bind-relationship") {
151
189
  return (
152
- service?.bindRelationship?.(
190
+ this.getRelationships()?.bind(
153
191
  ctx,
154
192
  "relationship" in value ? value.relationship : undefined,
155
193
  ) ?? null
@@ -3,8 +3,9 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import type { ContextSharingService } from "@howaboua/pi-codex-conversion/context-sharing";
7
- import type { ConnectedMachine } from "./fleet.js";
6
+ import type { CodexAgentRelationshipService } from "@howaboua/pi-codex-conversion/agent-relationship";
7
+ import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
8
+ import type { ConnectedMachine } from "./fleet/index.js";
8
9
  import { sessionPath } from "./herdr.js";
9
10
  import { sessionContextPath } from "./remote/shepherdr-context.mjs";
10
11
  import type { PaneInfo } from "./types.js";
@@ -21,23 +22,32 @@ interface Routing {
21
22
  transport: "shepherdr";
22
23
  parent: string;
23
24
  }
25
+
24
26
  export class SpawnContext {
25
27
  private readonly pi: ExtensionAPI;
28
+ private readonly getRelationships: () =>
29
+ | CodexAgentRelationshipService
30
+ | undefined;
26
31
  private readonly getService: () => ContextSharingService | undefined;
27
32
  constructor(
28
33
  pi: ExtensionAPI,
29
34
  getService: () => ContextSharingService | undefined,
35
+ getRelationships: () => CodexAgentRelationshipService | undefined,
30
36
  ) {
31
37
  this.pi = pi;
38
+ this.getRelationships = getRelationships;
32
39
  this.getService = getService;
33
40
  }
41
+ canShare(ctx: ExtensionContext): boolean {
42
+ return this.getService()?.canCreateChild(ctx) === true;
43
+ }
34
44
  prepareRelationship(
35
45
  ctx: ExtensionContext,
36
46
  runtime: ConnectedMachine,
37
47
  args: readonly string[],
38
48
  ) {
39
- const service = this.getService();
40
- if (!service?.bindRelationship) return undefined;
49
+ const service = this.getRelationships();
50
+ if (!service) return undefined;
41
51
  // Session-selection profiles resume existing identities rather than creating workers.
42
52
  if (
43
53
  args.some((arg) =>
@@ -48,7 +58,7 @@ export class SpawnContext {
48
58
  )
49
59
  return undefined;
50
60
  const parentThreadId = ctx.sessionManager.getSessionId();
51
- const cacheAffinityId = service.cacheAffinityId?.(ctx);
61
+ const cacheAffinityId = service.cacheAffinityId(ctx);
52
62
  const linkage = { parentThreadId, subagentKind: "collab_spawn" };
53
63
  const relationship = {
54
64
  ...linkage,
@@ -112,18 +122,16 @@ export class SpawnContext {
112
122
  throw new Error(
113
123
  "Shared context spawn requires a saved controller session",
114
124
  );
115
- const routing: Routing | undefined =
116
- parent.storage === "session"
117
- ? {
118
- transport: "shepherdr",
119
- parent: runtime.local
120
- ? sessionContextPath(parentFile)
121
- : runtime.client.contextRelayPath(),
122
- }
123
- : undefined;
125
+ await runtime.prepareSharing();
126
+ const routing: Routing = {
127
+ transport: "shepherdr",
128
+ parent: runtime.local
129
+ ? sessionContextPath(parentFile)
130
+ : runtime.client.contextRelayPath(),
131
+ };
124
132
  const { binding, adopt } = await service.createChild(ctx, {
125
133
  name,
126
- ...(routing ? { routing } : {}),
134
+ routing,
127
135
  });
128
136
  return {
129
137
  accept: async (agent: PaneInfo) => {
@@ -136,8 +144,7 @@ export class SpawnContext {
136
144
  );
137
145
  if (!value)
138
146
  return {
139
- warning:
140
- "Spawned without shared context: the target needs Codex conversion with notes-based continuity",
147
+ warning: "Spawned without shared context: the target needs Notes",
141
148
  };
142
149
  if (
143
150
  typeof value !== "object" ||