@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
@@ -1,7 +1,9 @@
1
1
  import type {
2
2
  AgentToolUpdateCallback,
3
+ ExtensionAPI,
3
4
  ExtensionContext,
4
5
  } from "@earendil-works/pi-coding-agent";
6
+ import { nativeAgentName } from "./agent-identity.js";
5
7
  import {
6
8
  type AgentsParams,
7
9
  requiredAgentField as required,
@@ -15,6 +17,7 @@ import {
15
17
  toolResult,
16
18
  } from "./agents-work.js";
17
19
  import type { AgentBoard } from "./board/host.js";
20
+ import { CoreConnection } from "./core/backend.js";
18
21
  import type { AgentFleet, ConnectedMachine } from "./fleet/index.js";
19
22
  import { isDispatchRejected } from "./herdr-client.js";
20
23
  import {
@@ -29,8 +32,10 @@ import {
29
32
  profileAgentArgs,
30
33
  } from "./profiles.js";
31
34
  import type { SharedAgentContext } from "./shared-context.js";
35
+ import { prepareSpawnOwnership } from "./spawn-ownership.js";
32
36
 
33
37
  export async function spawnAgent(
38
+ pi: ExtensionAPI,
34
39
  fleet: AgentFleet,
35
40
  runtime: ConnectedMachine,
36
41
  params: AgentsParams,
@@ -40,6 +45,7 @@ export async function spawnAgent(
40
45
  ctx: ExtensionContext,
41
46
  board: AgentBoard,
42
47
  ) {
48
+ const recordSpawn = prepareSpawnOwnership(pi, ctx, runtime);
43
49
  const boardThreadId =
44
50
  params.board_thread_id === undefined
45
51
  ? undefined
@@ -70,9 +76,11 @@ export async function spawnAgent(
70
76
  try {
71
77
  const placement =
72
78
  params.placement ??
73
- (runtime.local && process.env["HERDR_WORKSPACE_ID"]
74
- ? "new_tab"
75
- : "new_workspace");
79
+ (runtime.client instanceof CoreConnection
80
+ ? "terminal"
81
+ : runtime.local && process.env["HERDR_WORKSPACE_ID"]
82
+ ? "new_tab"
83
+ : "new_workspace");
76
84
  const workspace =
77
85
  params.workspace ??
78
86
  (placement === "new_tab" && runtime.local
@@ -133,7 +141,7 @@ export async function spawnAgent(
133
141
  const sharing =
134
142
  profile.shareContext === false
135
143
  ? undefined
136
- : await sharedContext.spawns.prepare(ctx, runtime, name, agentArgs);
144
+ : await sharedContext.spawns.prepare(ctx, runtime, agentArgs);
137
145
  const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
138
146
  const started = await startAgent(
139
147
  runtime.client,
@@ -147,9 +155,12 @@ export async function spawnAgent(
147
155
  let dispatch;
148
156
  let shared: { agentName?: string; warning?: string } | undefined;
149
157
  let boardAgent: string | undefined;
158
+ let agentName: string | undefined;
150
159
  let relationshipWarning: string | undefined;
151
160
  const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
152
161
  try {
162
+ agentName = await nativeAgentName(runtime.client, started.agent, signal);
163
+ await recordSpawn(started.agent, agentArgs);
153
164
  relationshipWarning = (await relationship?.accept(started.agent))
154
165
  ?.warning;
155
166
  boardAgent = await boardBinding?.accept(started.agent);
@@ -183,8 +194,6 @@ export async function spawnAgent(
183
194
  }
184
195
  return toolResult(
185
196
  {
186
- ...(boardAgent ? { boardAgent } : {}),
187
- ...(shared?.agentName ? { contextAgent: shared.agentName } : {}),
188
197
  ...(dispatch.command
189
198
  ? {
190
199
  spawned: true,
@@ -204,8 +213,17 @@ export async function spawnAgent(
204
213
  target: started.id,
205
214
  name,
206
215
  status: "working",
207
- next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
216
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
208
217
  }),
218
+ agent: agentName,
219
+ ...(boardAgent || shared?.agentName
220
+ ? {
221
+ sharing: {
222
+ board: !!boardAgent,
223
+ context: !!shared?.agentName,
224
+ },
225
+ }
226
+ : {}),
209
227
  },
210
228
  [dispatch.warning, shared?.warning, relationshipWarning]
211
229
  .filter(Boolean)
@@ -4,6 +4,7 @@ import {
4
4
  getMarkdownTheme,
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
7
+ import { resolveNativeAgent } from "./agent-identity.js";
7
8
  import {
8
9
  AgentsParameters,
9
10
  type AgentsParams,
@@ -26,6 +27,7 @@ import {
26
27
  toolResult,
27
28
  } from "./agents-work.js";
28
29
  import type { AgentBoard } from "./board/host.js";
30
+ import { CoreConnection } from "./core/backend.js";
29
31
  import type { AgentFleet } from "./fleet/index.js";
30
32
  import { resolvePiAgent } from "./herdr.js";
31
33
  import { attributeAgentPrompt } from "./messages/attribution.js";
@@ -43,8 +45,9 @@ export function createAgentsTool(
43
45
  return defineTool({
44
46
  name: "agents",
45
47
  label: "Shepherdr",
46
- description: "Delegate to persistent agents",
47
- promptGuidelines: ["Make the first agents discovery call alone"],
48
+ description:
49
+ "Delegate to persistent agents; {} lists additional action fields",
50
+ promptGuidelines: ["agents: Read help alone first"],
48
51
  parameters: AgentsParameters,
49
52
  executionMode: "parallel",
50
53
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
@@ -52,7 +55,16 @@ export function createAgentsTool(
52
55
  const executionSignal = signal ?? new AbortController().signal;
53
56
  const update = onUpdate ?? (() => undefined);
54
57
  if (params.action === "help" && !params.commands) {
55
- return toolResult(await agentsHelp(board.enabled(ctx), gpt()));
58
+ return toolResult(
59
+ await agentsHelp(
60
+ board.enabled(ctx),
61
+ gpt(),
62
+ Boolean(
63
+ process.env["HC_TERMINAL_ID"] &&
64
+ process.env["HC_TERMINAL_SOCKET"],
65
+ ),
66
+ ),
67
+ );
56
68
  }
57
69
  if (params.commands && params.target === undefined)
58
70
  return toolResult({ commands: commands.available() });
@@ -66,6 +78,7 @@ export function createAgentsTool(
66
78
  let runtime = fleet.connected(params.machine);
67
79
  if (params.action === "spawn") {
68
80
  return spawnAgent(
81
+ pi,
69
82
  fleet,
70
83
  runtime,
71
84
  params,
@@ -86,6 +99,15 @@ export function createAgentsTool(
86
99
  );
87
100
  runtime = root.runtime;
88
101
  target = root.target;
102
+ } else if (target.startsWith("/") && !target.slice(1).includes("/")) {
103
+ const native = await resolveNativeAgent(
104
+ fleet,
105
+ target,
106
+ params.machine,
107
+ executionSignal,
108
+ );
109
+ runtime = native.runtime;
110
+ target = native.panel.pane_id;
89
111
  }
90
112
  if (params.action === "focus") {
91
113
  executionSignal.throwIfAborted();
@@ -123,7 +145,13 @@ export function createAgentsTool(
123
145
  const panel = await resolvePiAgent(
124
146
  runtime.client,
125
147
  target,
126
- runtime.local ? process.env["HERDR_PANE_ID"] : "",
148
+ runtime.local
149
+ ? process.env[
150
+ runtime.client instanceof CoreConnection
151
+ ? "HC_TERMINAL_ID"
152
+ : "HERDR_PANE_ID"
153
+ ]
154
+ : "",
127
155
  );
128
156
  if (params.commands) {
129
157
  return toolResult({
@@ -149,7 +177,7 @@ export function createAgentsTool(
149
177
  watched: true,
150
178
  machine: runtime.machine,
151
179
  target: panel.pane_id,
152
- next: "Completion or blockage will be delivered automatically; do not poll",
180
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
153
181
  });
154
182
  }
155
183
  if (params.action === "read") {
@@ -198,7 +226,7 @@ export function createAgentsTool(
198
226
  runtime,
199
227
  panel,
200
228
  message,
201
- params.blocking !== false,
229
+ params.blocking === true,
202
230
  executionSignal,
203
231
  update,
204
232
  () => runtime.client.sendMessage(panel, attributedMessage),
@@ -221,7 +249,7 @@ export function createAgentsTool(
221
249
  machine: runtime.machine,
222
250
  target: panel.pane_id,
223
251
  status: "working",
224
- next: "Converse, do other work or reply now; completion/blockage arrives even after you reply. No polling or sleep waits",
252
+ next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
225
253
  },
226
254
  dispatch.warning,
227
255
  );
@@ -93,13 +93,13 @@ export function settlementResult(
93
93
  `${settlement.agent.pane_id} assistant stopped with an error`
94
94
  : undefined;
95
95
  if (workerError && !options.reportWorkerError) throw new Error(workerError);
96
- const { pane, name, ...source } = agentSource(
96
+ const { pane, terminal, name, ...source } = agentSource(
97
97
  settlement.agent,
98
98
  settlement.labels,
99
99
  );
100
100
  return {
101
101
  machine,
102
- target: pane,
102
+ target: pane ?? terminal,
103
103
  ...(name ? { name } : {}),
104
104
  source,
105
105
  status: settlement.status,
@@ -98,14 +98,6 @@ export class AttachmentNotes {
98
98
  )
99
99
  );
100
100
  }
101
- unavailable(error: unknown) {
102
- return (
103
- error instanceof Error &&
104
- /^(Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
105
- error.message,
106
- )
107
- );
108
- }
109
101
  async read(
110
102
  request: SharedContextRequest,
111
103
  identity: ContextAgentIdentity,
@@ -148,7 +140,6 @@ export class AttachmentNotes {
148
140
  unavailable = String(error);
149
141
  }
150
142
  }
151
- const result = this.service().read(snapshot, request.params);
152
143
  if (
153
144
  !snapshot ||
154
145
  typeof snapshot !== "object" ||
@@ -157,7 +148,6 @@ export class AttachmentNotes {
157
148
  )
158
149
  throw new Error("Invalid retained checkpoint timestamp");
159
150
  const details = {
160
- ...result.details.codexHistoryNotes,
161
151
  source,
162
152
  read_only: true,
163
153
  captured_at: new Date(snapshot.timestamp).toISOString(),
@@ -173,21 +163,32 @@ export class AttachmentNotes {
173
163
  : {}),
174
164
  }),
175
165
  };
166
+ const warning = `Read-only checkpoints captured ${details.captured_at}.${
167
+ detached
168
+ ? " Counterpart detached."
169
+ : unavailable
170
+ ? " Live owner and saved updates unavailable; these checkpoints may be stale. Resume the counterpart for current notes."
171
+ : " Live owner unavailable; reading saved checkpoints."
172
+ }`;
173
+ const result = this.service().read(snapshot, request.params, {
174
+ read_only: true,
175
+ captured_at: details.captured_at,
176
+ ...(savedAt === undefined ? {} : { saved_at: details.saved_at }),
177
+ warning,
178
+ });
179
+ if (
180
+ !result.structuredContent ||
181
+ typeof result.structuredContent !== "object" ||
182
+ !("warning" in result.structuredContent) ||
183
+ result.structuredContent["warning"] !== warning
184
+ )
185
+ throw new Error("Update Notes to read retained attached checkpoints");
176
186
  return {
177
- content: [
178
- ...result.content,
179
- {
180
- type: "text",
181
- text: `Read-only checkpoints captured ${details.captured_at}.${
182
- detached
183
- ? " Counterpart detached."
184
- : unavailable
185
- ? " Live owner and saved updates unavailable; these checkpoints may be stale. Resume the counterpart for current notes."
186
- : " Live owner unavailable; reading saved checkpoints."
187
- }`,
188
- },
189
- ],
190
- details: { codexHistoryNotes: details },
187
+ ...result,
188
+ details: {
189
+ ...result.details,
190
+ codexHistoryNotes: { ...result.details.codexHistoryNotes, ...details },
191
+ },
191
192
  };
192
193
  }
193
194
  }
@@ -1,22 +1,37 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
- import { Type } from "@earendil-works/pi-ai";
3
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
3
  import { BindingSchema } from "@howaboua/pi-agent-board/integration";
5
4
  import type { SharedContextResult } from "@howaboua/pi-notes-compaction/context-sharing";
6
- import type { Static, TSchema } from "typebox";
5
+ import { type Static, type TSchema, Type } from "typebox";
7
6
  import { Check } from "typebox/value";
8
7
 
9
- const AgentPath = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
8
+ const AgentPath = Type.String({
9
+ pattern: "^/(?:[a-zA-Z0-9_.-]+|root(?:/[a-zA-Z0-9_-]+)*)$",
10
+ });
10
11
  export const Identity = Type.Object({
11
12
  protocol: Type.Literal(1),
12
13
  sessionId: Type.String({ minLength: 1 }),
13
14
  threadId: Type.String({ minLength: 1 }),
14
15
  agentName: AgentPath,
16
+ storageAgentName: Type.Optional(AgentPath),
15
17
  storage: Type.Union([Type.Literal("session"), Type.Literal("remote")]),
16
18
  accountScope: Type.Optional(Type.String({ pattern: "^[a-f0-9]{64}$" })),
17
19
  backendUrl: Type.Optional(Type.String({ minLength: 1 })),
18
20
  routing: Type.Optional(Type.Unknown()),
19
21
  });
22
+ // Persisted attachment records predate native agent references. Keep their storage address.
23
+ export function canonicalContextIdentity(
24
+ identity: Static<typeof Identity>,
25
+ ): Static<typeof Identity> {
26
+ const agentName = `/${identity.threadId}`;
27
+ return identity.agentName === agentName
28
+ ? identity
29
+ : {
30
+ ...identity,
31
+ agentName,
32
+ storageAgentName: identity.storageAgentName ?? identity.agentName,
33
+ };
34
+ }
20
35
  const ContextLink = Type.Object({
21
36
  controller: Identity,
22
37
  target: Identity,
@@ -111,6 +126,19 @@ export function remapResult(
111
126
  from: string,
112
127
  to: string,
113
128
  ): SharedContextResult {
129
+ const remapField = (key: string, value: unknown) =>
130
+ (key === "path" || key === "agent_name") && typeof value === "string"
131
+ ? remap(value, from, to)
132
+ : value;
133
+ const structured =
134
+ result.structuredContent === undefined
135
+ ? {}
136
+ : {
137
+ structuredContent: JSON.parse(
138
+ JSON.stringify(result.structuredContent),
139
+ remapField,
140
+ ),
141
+ };
114
142
  if (
115
143
  typeof result.details.codexHistoryNotes["encrypted_output"] === "string" ||
116
144
  ("externalNotesResponses" in result.details &&
@@ -122,32 +150,24 @@ export function remapResult(
122
150
  result.details.codexHistoryNotes["attachment_hint"] = hint;
123
151
  return {
124
152
  ...result,
153
+ ...structured,
125
154
  content: [{ type: "text", text: hint }, ...result.content],
126
155
  };
127
156
  }
128
157
  const details = JSON.parse(
129
158
  JSON.stringify(result.details.codexHistoryNotes),
130
- (key, value: unknown) =>
131
- (key === "path" || key === "agent_name") && typeof value === "string"
132
- ? remap(value, from, to)
133
- : value,
159
+ remapField,
134
160
  ) as Record<string, unknown>;
135
161
  return {
136
162
  ...result,
163
+ ...structured,
137
164
  // Remap the public payload, never regenerate it from private receipts.
138
165
  content: result.content.map((item) => {
139
166
  if (item.type !== "text") return item;
140
167
  try {
141
168
  return {
142
169
  ...item,
143
- text: JSON.stringify(
144
- JSON.parse(item.text, (key, value: unknown) =>
145
- (key === "path" || key === "agent_name") &&
146
- typeof value === "string"
147
- ? remap(value, from, to)
148
- : value,
149
- ),
150
- ),
170
+ text: JSON.stringify(JSON.parse(item.text, remapField)),
151
171
  };
152
172
  } catch {
153
173
  return item;
@@ -10,6 +10,7 @@ import {
10
10
  type AttachmentRoute,
11
11
  attachmentOwner,
12
12
  attachmentRoutes,
13
+ canonicalContextIdentity,
13
14
  detachment,
14
15
  inside,
15
16
  remap,
@@ -17,6 +18,7 @@ import {
17
18
  remapResult,
18
19
  } from "./attachment-protocol.js";
19
20
  import {
21
+ isContextUnavailable,
20
22
  requestContext,
21
23
  sessionContextPath,
22
24
  } from "./remote/shepherdr-context.mjs";
@@ -45,19 +47,24 @@ export class AttachmentRouting {
45
47
  (route) =>
46
48
  route.phase === "ready" &&
47
49
  route.plan.context &&
48
- inside(request.agentName, route.plan.context.alias),
50
+ (inside(request.agentName, route.plan.context.alias) ||
51
+ request.agentName === `/${route.plan.targetSessionId}`),
49
52
  );
50
53
  if (child?.plan.context) {
51
54
  const link = child.plan.context;
52
- if (!isDeepStrictEqual(native, link.controller))
55
+ const alias =
56
+ request.agentName === `/${child.plan.targetSessionId}`
57
+ ? request.agentName
58
+ : link.alias;
59
+ if (!isDeepStrictEqual(native, canonicalContextIdentity(link.controller)))
53
60
  throw new Error(
54
61
  "Shared notes are unavailable. Use messages to exchange the context you need.",
55
62
  );
56
63
  const next = {
57
64
  ...request,
58
65
  sessionId: link.target.sessionId,
59
- agentName: remap(request.agentName, link.alias, link.target.agentName),
60
- params: remapParams(request.params, link.alias, link.target.agentName),
66
+ agentName: remap(request.agentName, alias, link.target.agentName),
67
+ params: remapParams(request.params, alias, link.target.agentName),
61
68
  };
62
69
  let result: SharedContextResult;
63
70
  if (link.target.storage === "remote") {
@@ -80,7 +87,7 @@ export class AttachmentRouting {
80
87
  })) as SharedContextResult;
81
88
  } catch (error) {
82
89
  signal?.throwIfAborted();
83
- if (!this.notes.canRead(next) || !this.notes.unavailable(error))
90
+ if (!this.notes.canRead(next) || !isContextUnavailable(error))
84
91
  throw error;
85
92
  result = await this.notes.read(
86
93
  next,
@@ -103,28 +110,29 @@ export class AttachmentRouting {
103
110
  true,
104
111
  async () => undefined,
105
112
  );
106
- return remapResult(result, link.target.agentName, link.alias);
113
+ return remapResult(result, link.target.agentName, alias);
107
114
  }
108
115
  const owner = attachmentOwner(ctx);
109
116
  const link = owner?.context;
110
- if (owner && link && inside(request.agentName, link.controllerAlias)) {
111
- if (!isDeepStrictEqual(native, link.target))
117
+ if (
118
+ owner &&
119
+ link &&
120
+ (inside(request.agentName, link.controllerAlias) ||
121
+ request.agentName === `/${owner.controllerSessionId}`)
122
+ ) {
123
+ const alias =
124
+ request.agentName === `/${owner.controllerSessionId}`
125
+ ? request.agentName
126
+ : link.controllerAlias;
127
+ if (!isDeepStrictEqual(native, canonicalContextIdentity(link.target)))
112
128
  throw new Error(
113
129
  "Shared notes are unavailable. Use messages to exchange the context you need.",
114
130
  );
115
131
  const next = {
116
132
  ...request,
117
133
  sessionId: link.controller.sessionId,
118
- agentName: remap(
119
- request.agentName,
120
- link.controllerAlias,
121
- link.controller.agentName,
122
- ),
123
- params: remapParams(
124
- request.params,
125
- link.controllerAlias,
126
- link.controller.agentName,
127
- ),
134
+ agentName: remap(request.agentName, alias, link.controller.agentName),
135
+ params: remapParams(request.params, alias, link.controller.agentName),
128
136
  };
129
137
  const detached = detachment(ctx, owner)?.context;
130
138
  let result: SharedContextResult;
@@ -148,7 +156,7 @@ export class AttachmentRouting {
148
156
  )) as SharedContextResult;
149
157
  } catch (error) {
150
158
  signal?.throwIfAborted();
151
- if (!this.notes.canRead(next) || !this.notes.unavailable(error))
159
+ if (!this.notes.canRead(next) || !isContextUnavailable(error))
152
160
  throw error;
153
161
  result = await this.notes.read(
154
162
  next,
@@ -177,11 +185,7 @@ export class AttachmentRouting {
177
185
  true,
178
186
  async () => undefined,
179
187
  );
180
- return remapResult(
181
- result,
182
- link.controller.agentName,
183
- link.controllerAlias,
184
- );
188
+ return remapResult(result, link.controller.agentName, alias);
185
189
  }
186
190
  return undefined;
187
191
  }
@@ -3,7 +3,11 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
- import { binding } from "@howaboua/pi-agent-board/integration";
6
+ import {
7
+ type BoardBinding,
8
+ binding,
9
+ canonicalBoardBinding,
10
+ } from "@howaboua/pi-agent-board/integration";
7
11
  import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
8
12
  import type { Static } from "typebox";
9
13
  import { Check } from "typebox/value";
@@ -12,6 +16,7 @@ import {
12
16
  type AttachmentPlan,
13
17
  attachmentOwner,
14
18
  attachmentRoutes,
19
+ canonicalContextIdentity,
15
20
  DETACHED,
16
21
  Detachment,
17
22
  detachment,
@@ -26,6 +31,12 @@ import {
26
31
  detachmentMessage,
27
32
  } from "./messages/attachments.js";
28
33
 
34
+ function sameBoard(left: BoardBinding, right: BoardBinding) {
35
+ const { legacyAgentName: _left, ...a } = canonicalBoardBinding(left);
36
+ const { legacyAgentName: _right, ...b } = canonicalBoardBinding(right);
37
+ return isDeepStrictEqual(a, b);
38
+ }
39
+
29
40
  /** Validates and commits attachment membership in the settled target session. */
30
41
  export class AttachmentTarget {
31
42
  private readonly pi: ExtensionAPI;
@@ -135,22 +146,37 @@ export class AttachmentTarget {
135
146
  (plan.context &&
136
147
  (plan.context.controller.threadId !== plan.controllerSessionId ||
137
148
  plan.context.target.threadId !== plan.targetSessionId ||
138
- !plan.context.alias.startsWith(
139
- `${plan.context.controller.agentName}/`,
149
+ !(
150
+ plan.context.alias === `/${plan.targetSessionId}` ||
151
+ plan.context.alias.startsWith(
152
+ `${plan.context.controller.agentName}/`,
153
+ )
140
154
  ) ||
141
- !plan.context.controllerAlias.startsWith(
142
- `${plan.context.target.agentName}/`,
155
+ !(
156
+ plan.context.controllerAlias === `/${plan.controllerSessionId}` ||
157
+ plan.context.controllerAlias.startsWith(
158
+ `${plan.context.target.agentName}/`,
159
+ )
143
160
  ))) ||
144
161
  (plan.board &&
145
162
  (plan.board.controller.sessionId !== plan.controllerSessionId ||
146
163
  plan.board.previous.sessionId !== plan.targetSessionId ||
147
- !isDeepStrictEqual(plan.board.desired, {
148
- ...plan.board.controller,
149
- agentName: plan.board.desired.agentName,
150
- upstream: plan.upstream,
151
- }) ||
152
- !plan.board.desired.agentName.startsWith(
153
- `${plan.board.controller.agentName}/`,
164
+ !(
165
+ sameBoard(plan.board.desired, {
166
+ ...plan.board.controller,
167
+ sessionId: plan.targetSessionId,
168
+ agentName: `/${plan.targetSessionId}`,
169
+ parentSessionId: plan.controllerSessionId,
170
+ upstream: plan.upstream,
171
+ }) ||
172
+ (isDeepStrictEqual(plan.board.desired, {
173
+ ...plan.board.controller,
174
+ agentName: plan.board.desired.agentName,
175
+ upstream: plan.upstream,
176
+ }) &&
177
+ plan.board.desired.agentName.startsWith(
178
+ `${plan.board.controller.agentName}/`,
179
+ ))
154
180
  )))
155
181
  )
156
182
  throw new Error("Invalid attachment identities or routes");
@@ -173,13 +199,16 @@ export class AttachmentTarget {
173
199
  if (
174
200
  plan.context &&
175
201
  (!current.context ||
176
- !isDeepStrictEqual(current.context, plan.context.target))
202
+ !isDeepStrictEqual(
203
+ current.context,
204
+ canonicalContextIdentity(plan.context.target),
205
+ ))
177
206
  )
178
207
  throw new Error(
179
208
  current.contextError ?? "Target context changed during attachment",
180
209
  );
181
210
  if (plan.board && current.boardError) throw new Error(current.boardError);
182
- if (plan.board && !isDeepStrictEqual(current.board, plan.board.previous))
211
+ if (plan.board && !sameBoard(current.board, plan.board.previous))
183
212
  throw new Error("Target board changed during attachment");
184
213
  // Authentication completes before either membership mutation.
185
214
  if (plan.context) {
@@ -196,8 +225,11 @@ export class AttachmentTarget {
196
225
  if (
197
226
  !ctx.isIdle() ||
198
227
  ctx.sessionManager.getSessionId() !== plan.targetSessionId ||
199
- !isDeepStrictEqual(identity, plan.context.target) ||
200
- (plan.board && !isDeepStrictEqual(binding(ctx), plan.board.previous))
228
+ !isDeepStrictEqual(
229
+ identity,
230
+ canonicalContextIdentity(plan.context.target),
231
+ ) ||
232
+ (plan.board && !sameBoard(binding(ctx), plan.board.previous))
201
233
  )
202
234
  throw new Error(
203
235
  "Target changed during attachment authentication; retry after it settles",
@@ -230,16 +262,20 @@ export class AttachmentTarget {
230
262
  } else {
231
263
  if (
232
264
  plan.context &&
233
- !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
265
+ !isDeepStrictEqual(
266
+ await this.context(ctx, false),
267
+ canonicalContextIdentity(plan.context.target),
268
+ )
234
269
  )
235
270
  throw new Error(
236
271
  "Shared notes are unavailable. Use messages to exchange the context you need.",
237
272
  );
238
273
  if (
239
274
  plan.board &&
240
- !isDeepStrictEqual(binding(ctx), {
275
+ !sameBoard(binding(ctx), {
241
276
  ...plan.board.desired,
242
277
  sessionId: plan.targetSessionId,
278
+ parentSessionId: plan.controllerSessionId,
243
279
  })
244
280
  )
245
281
  throw new Error("Attached board changed; resolve the target again");
@@ -275,7 +311,10 @@ export class AttachmentTarget {
275
311
  const previous = detachment(ctx, plan);
276
312
  if (requested.context && plan.context) {
277
313
  if (
278
- !isDeepStrictEqual(await this.context(ctx, false), plan.context.target)
314
+ !isDeepStrictEqual(
315
+ await this.context(ctx, false),
316
+ canonicalContextIdentity(plan.context.target),
317
+ )
279
318
  )
280
319
  throw new Error("Target context changed before detach");
281
320
  this.notes.validate(requested.context, plan.context.controller);