@howaboua/pi-shepherdr 0.2.25 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @howaboua/pi-shepherdr
2
2
 
3
+ ## 0.2.26
4
+
5
+ - Requires Pi 1.5 or newer.
6
+
7
+ Update and restart controllers and workers together for shared Notes and boards.
8
+ - `spawn` and `assign` now return after task submission by default. Set `blocking: true` to wait for the result. A profile's `blocking` setting still overrides `spawn`.
9
+ - Agent references now use Pi session IDs across delegation, Notes and boards. Spawn returns one `agent` reference and sharing flags instead of separate context and board references.
10
+ - Attached Notes reads keep alias paths and read-only warnings consistent across native, Code and Notebook results.
11
+ - Rollover briefings now retain initial scope and the latest instruction without accumulating every message. Full messages remain in session history.
12
+ - Fixed repeated writes of unchanged agent snapshots.
13
+ - Closed workers no longer trigger a misleading notices-unavailable reconnect warning.
14
+ - Removed custom changelog suppression. Updates use Pi's native notices and `collapseChangelog`.
15
+
3
16
  ## 0.2.25
4
17
 
5
18
  - When switching from the older Herdr TUI or another Core instance, reselect local watches.
package/README.md CHANGED
@@ -75,7 +75,7 @@ Call `agents` with `{}` before first use, alone, then send flat request objects
75
75
  | `watch` | Push future settlement from an existing Pi agent |
76
76
  | `unwatch` | Stop reporting an agent |
77
77
 
78
- `spawn` and `assign` block by default. Set `blocking: false` when the controller should continue other work immediately. A profile's `blocking` setting overrides the call for `spawn`. Task completion and blockage are then delivered automatically.
78
+ `spawn` and `assign` return once the task is submitted by default, so consecutive calls can dispatch work to several agents without waiting for the first task to finish. Task completion and blockage arrive automatically. Set `blocking: true` when the call must wait for its result. A profile's `blocking` setting still overrides the call for `spawn`.
79
79
 
80
80
  Blocking calls can run in parallel. In Code or Notebook, use `await Promise.allSettled([...])` to start independent calls together and wait for every result, including failures. Keep blocking enabled when the controller must wait, such as for parallel reviews. Consecutive `await` calls still run one after another; `Promise.all` can exit early on failure.
81
81
 
@@ -83,7 +83,7 @@ Nonblocking extension messages notify the controller once; blocking messages arr
83
83
 
84
84
  `reply` returns the extension's receipt after semantic delivery. Blocking messages also wait for resumed work unless another call already owns that wait. Nonblocking replies do not wait for the worker's task to finish. Shepherdr forwards strings unchanged. The producing extension owns their meaning, validation and retries.
85
85
 
86
- Use `send` for messages and work updates without waiting or adding supervision. Use `assign` when you need the result: it also accepts updates to running work, sharing that work's pending result rather than replacing it. If another call is already waiting, the update returns after submission and leaves that waiter intact. Close finished workers silently instead of waking them with completion acknowledgements or shutdown notices.
86
+ Use `send` for messages and work updates without adding supervision. Use `assign` to delegate work and receive its monitored result, automatically or through an explicit blocking call. It also accepts updates to running work, sharing that work's pending result rather than replacing it. If another call is already waiting, the update returns after submission and leaves that waiter intact. Close finished workers silently instead of waking them with completion acknowledgements or shutdown notices.
87
87
 
88
88
  Delegation and explicit `watch` keep reporting subsequent work until `unwatch` or the agent's pane closes. Finishing or failing a task clears that task, not its watch. Follow-up messages through `send` retain completion reporting without replacing the task.
89
89
 
@@ -250,7 +250,7 @@ That directory is authoritative after initialization. Edit a profile to change i
250
250
  `prompt` is read as system-prompt text. An optional `prepare` module may export `prepare({ cwd, message, base, local })` and return the worker message. Preparation runs on the controlling machine before dispatch; `local` says whether that machine also hosts the worker.
251
251
 
252
252
  Optional profile settings:
253
- - `blocking`: `true` forces blocking spawns, `false` forces asynchronous spawns. Omission respects the call's `blocking` value, which defaults to `true`. This does not affect `assign` to existing agents.
253
+ - `blocking`: `true` forces blocking spawns, `false` forces asynchronous spawns. Omission respects the call's `blocking` value, which defaults to `false`. This does not affect `assign` to existing agents.
254
254
  - `share_context`: `false` opts new spawns out of shared notes and history. Omission or `true` follows the controller setting.
255
255
 
256
256
  `help` and `list` expose each profile's description and configured settings. Profile names carry no blocking policy. The bundled reviewer profile sets `"blocking": true`; change it to `false` to force asynchronous review, or remove it to choose per call. Existing installed profiles are never overwritten. An existing reviewer without `blocking` now respects the call like any other profile.
package/index.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import registerPackageChangelog from "./changelog.js";
3
2
  import { isBlockingAgentsCall } from "./src/agents-contract.js";
4
3
  import { acceptFocus, registerFocusArrivals } from "./src/agents-focus.js";
5
4
  import { createAgentsTool } from "./src/agents-tool.js";
@@ -26,7 +25,6 @@ export default async function shepherdrExtension(
26
25
  ): Promise<void> {
27
26
  registerCoreStatus(pi);
28
27
  const workerRole = registerWorkerRole(pi);
29
- registerPackageChangelog(pi);
30
28
 
31
29
  await installAgentProfiles();
32
30
  registerProfilePrompt(pi);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-shepherdr",
3
- "version": "0.2.25",
3
+ "version": "0.2.26",
4
4
  "description": "Persistent blocking and asynchronous Pi agents through Herdr.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,7 +31,6 @@
31
31
  "LICENSE",
32
32
  "tsconfig.json",
33
33
  "biome.json",
34
- "changelog.ts",
35
34
  "CHANGELOG.md"
36
35
  ],
37
36
  "scripts": {
@@ -43,10 +42,10 @@
43
42
  "pack:dry": "npm pack --dry-run"
44
43
  },
45
44
  "peerDependencies": {
46
- "@howaboua/pi-notes-compaction": ">=0.0.12",
47
- "@howaboua/pi-codex-conversion": ">=4.0.6",
45
+ "@howaboua/pi-notes-compaction": ">=0.0.14",
46
+ "@howaboua/pi-codex-conversion": ">=4.0.8",
48
47
  "@earendil-works/pi-ai": ">=1.1.0",
49
- "@earendil-works/pi-coding-agent": ">=1.2.0",
48
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
50
49
  "@earendil-works/pi-tui": ">=1.1.0",
51
50
  "typebox": "*"
52
51
  },
@@ -59,15 +58,15 @@
59
58
  }
60
59
  },
61
60
  "dependencies": {
62
- "@howaboua/pi-agent-board": "0.0.4"
61
+ "@howaboua/pi-agent-board": "0.0.5"
63
62
  },
64
63
  "devDependencies": {
65
- "@howaboua/pi-notes-compaction": "0.0.12",
66
- "@howaboua/pi-codex-conversion": "4.0.6",
64
+ "@howaboua/pi-notes-compaction": "0.0.14",
65
+ "@howaboua/pi-codex-conversion": "4.0.8",
67
66
  "@biomejs/biome": "^2.6.3",
68
- "@earendil-works/pi-ai": "1.4.0",
69
- "@earendil-works/pi-coding-agent": "1.4.0",
70
- "@earendil-works/pi-tui": "1.4.0",
67
+ "@earendil-works/pi-ai": "1.5.0",
68
+ "@earendil-works/pi-coding-agent": "1.5.0",
69
+ "@earendil-works/pi-tui": "1.5.0",
71
70
  "@types/node": "^26.6.5",
72
71
  "typebox": "1.4.3",
73
72
  "typescript": "^7.0.2"
@@ -1,5 +1,80 @@
1
+ import type { AgentFleet } from "./fleet/index.js";
2
+ import { sessionPath } from "./herdr.js";
3
+ import type { HerdrConnection } from "./herdr-client.js";
4
+ import { sessionContextPath } from "./remote/shepherdr-context.mjs";
1
5
  import type { PaneInfo } from "./types.js";
2
6
 
7
+ /** Read the live Pi owner, never infer identity from a filename or terminal ID. */
8
+ export async function nativeAgentName(
9
+ client: HerdrConnection,
10
+ panel: PaneInfo,
11
+ signal?: AbortSignal,
12
+ ): Promise<string> {
13
+ const file = sessionPath(panel);
14
+ if (!file) throw new Error("Agent has no saved Pi session");
15
+ const value = await client.requestContext(
16
+ sessionContextPath(file),
17
+ { operation: "agent-identity" },
18
+ signal,
19
+ );
20
+ if (
21
+ !value ||
22
+ typeof value !== "object" ||
23
+ !("sessionId" in value) ||
24
+ typeof value.sessionId !== "string" ||
25
+ !value.sessionId ||
26
+ /[/\\\u0000]/.test(value.sessionId)
27
+ )
28
+ throw new Error(
29
+ "Agent identity unavailable; update and reload Shepherdr on the target",
30
+ );
31
+ if (value.sessionId === "root")
32
+ throw new Error(
33
+ "Pi session ID root conflicts with the legacy /root reference; start a session with another ID",
34
+ );
35
+ return `/${value.sessionId}`;
36
+ }
37
+
38
+ export async function resolveNativeAgent(
39
+ fleet: AgentFleet,
40
+ name: string,
41
+ machine?: string,
42
+ signal?: AbortSignal,
43
+ ) {
44
+ const snapshots = await fleet.snapshots(machine);
45
+ const candidates = snapshots.flatMap((entry) => {
46
+ if (!entry.snapshot) return [];
47
+ const runtime = fleet.connected(entry.id);
48
+ return entry.snapshot.agents
49
+ .filter((panel) => panel.agent === "pi" && sessionPath(panel))
50
+ .map((panel) => ({ runtime, panel }));
51
+ });
52
+ const found = await Promise.all(
53
+ candidates.map(async (candidate) => {
54
+ try {
55
+ return (await nativeAgentName(
56
+ candidate.runtime.client,
57
+ candidate.panel,
58
+ signal,
59
+ )) === name
60
+ ? candidate
61
+ : undefined;
62
+ } catch {
63
+ signal?.throwIfAborted();
64
+ return undefined;
65
+ }
66
+ }),
67
+ );
68
+ const matches = found.filter((candidate) => candidate !== undefined);
69
+ if (matches.length !== 1)
70
+ throw new Error(
71
+ matches.length
72
+ ? `Multiple live agents use ${name}; select an exact terminal target and machine`
73
+ : `No reachable live agent ${name}; use find for an exact target or reconnect its machine`,
74
+ );
75
+ return matches[0]!;
76
+ }
77
+
3
78
  export function sameAgentIdentity(
4
79
  expected: PaneInfo,
5
80
  current: PaneInfo,
@@ -1,9 +1,12 @@
1
- import { StringEnum, Type } from "@earendil-works/pi-ai";
2
- import type { Static } from "typebox";
1
+ import { type Static, Type } from "typebox";
3
2
  import { Check } from "typebox/value";
4
3
  import { START_PLACEMENTS } from "./launch.js";
5
4
  import { loadAgentProfileBlocking } from "./profiles.js";
6
5
 
6
+ function StringEnum<T extends readonly string[]>(values: T) {
7
+ return Type.Unsafe<T[number]>({ type: "string", enum: values });
8
+ }
9
+
7
10
  const ACTIONS = [
8
11
  "help",
9
12
  "list",
@@ -19,7 +22,6 @@ const ACTIONS = [
19
22
  "read",
20
23
  "reply",
21
24
  ] as const;
22
- const BLOCKING_ACTIONS = new Set<string>(["spawn", "assign", "reply"]);
23
25
  export const READ_SOURCES = ["latest", "visible", "recent"] as const;
24
26
  const STATUSES = ["idle", "working", "blocked", "done", "unknown"] as const;
25
27
 
@@ -81,7 +83,7 @@ const AgentsRequest = Type.Object(
81
83
  blocking: Type.Optional(
82
84
  Type.Boolean({
83
85
  description:
84
- "Delegation only; profile policy overrides spawn; otherwise defaults true",
86
+ "Wait for delegated result; profile policy overrides spawn; default false",
85
87
  }),
86
88
  ),
87
89
  context: Type.Optional(Type.Boolean()),
@@ -210,7 +212,10 @@ export function isBlockingAgentsCall(input: unknown): boolean {
210
212
  ),
211
213
  value.blocking,
212
214
  );
213
- return BLOCKING_ACTIONS.has(value.action) && value.blocking !== false;
215
+ return (
216
+ value.action === "reply" ||
217
+ (value.action === "assign" && value.blocking === true)
218
+ );
214
219
  } catch {
215
220
  return false;
216
221
  }
@@ -220,5 +225,5 @@ export function shouldBlockAgentSpawn(
220
225
  profileBlocking: boolean | undefined,
221
226
  blocking: boolean | undefined,
222
227
  ): boolean {
223
- return profileBlocking ?? blocking ?? true;
228
+ return profileBlocking ?? blocking ?? false;
224
229
  }
@@ -1,3 +1,4 @@
1
+ import { nativeAgentName } from "./agent-identity.js";
1
2
  import type { AgentsParams, READ_SOURCES } from "./agents-contract.js";
2
3
  import type { AgentFleet, ConnectedMachine } from "./fleet/index.js";
3
4
  import { type AgentProfile, loadAgentProfiles } from "./profiles.js";
@@ -58,8 +59,8 @@ export async function agentsHelp(
58
59
  ? "machine omitted=local Pi host; list/find omitted=all machines; remote=list profile ID, NOT label/hostname"
59
60
  : "Omit for local (host running Pi); list/find omit for all machines. Remote: profile ID from list, not label/hostname",
60
61
  target: gpt
61
- ? "spawn/find target EXACT; /root=this family live root"
62
- : "Use spawn/find target exactly; /root selects this family's live root",
62
+ ? "target=agent (same Notes/Board ID) or terminal target; /root=this family live root"
63
+ : "Use agent for the same identity as Notes/Board, or the terminal target; /root selects this family's live root",
63
64
  label: core
64
65
  ? "Short Pi session name; app tabs use default names"
65
66
  : gpt
@@ -95,8 +96,8 @@ export async function agentsHelp(
95
96
  ? "Idle target; stop selected membership; counterpart checkpoints remain readonly"
96
97
  : "Stop selected membership; retain counterpart checkpoints read-only; idle target",
97
98
  blocking: gpt
98
- ? "spawn/assign default true; profile overrides spawn; await blocking calls; JS parallel: await Promise.allSettled; false ONLY if other work continues; background reports automatic→do other work/end turn, NO poll or await timers/extra Promises"
99
- : "spawn/assign default true; profile blocking overrides spawn. Await blocking calls; use await Promise.allSettled for parallel calls, including failures. Use false only to continue other work. Background reports arrive automatically: do other work or end this turn, never poll or await timers or extra Promises for reports",
99
+ ? "spawn/assign default false→dispatch then return; true→wait for result; profile overrides spawn. Parallel blocking calls: await Promise.allSettled. Background reports automatic→do other work/end turn, NO poll or await timers/extra Promises"
100
+ : "spawn/assign return after dispatch by default. Set blocking:true to wait for the result; profile blocking overrides spawn. Use await Promise.allSettled for parallel blocking calls, including failures. Background reports arrive automatically: do other work or end this turn, never poll or await timers or extra Promises for reports",
100
101
  share_context: gpt
101
102
  ? "Profile false→isolated notes/history; otherwise→controller sharing setting"
102
103
  : "Profile false isolates notes/history; otherwise follows controller sharing setting",
@@ -196,28 +197,46 @@ export async function listFleetAgents(
196
197
  loadAgentProfiles(),
197
198
  fleet.snapshots(params.machine),
198
199
  ]);
199
- const agents = machines.flatMap((machine) => {
200
- if (!machine.snapshot) return [];
201
- return machine.snapshot.agents
202
- .filter(
203
- (agent) =>
204
- agent.agent === "pi" &&
205
- (!machine.local ||
206
- agent.pane_id !==
207
- (agent.backend === "core"
208
- ? process.env["HC_TERMINAL_ID"]
209
- : process.env["HERDR_PANE_ID"])),
210
- )
211
- .map((agent) =>
212
- compactAgent(
213
- agent,
214
- machine.snapshot!,
215
- machine.id,
216
- machine.monitoredPaneIds?.has(agent.pane_id) ?? false,
217
- ),
218
- )
219
- .filter((agent) => matchesAgent(agent, params.query, params.status));
220
- });
200
+ const agents = (
201
+ await Promise.all(
202
+ machines.map(async (machine) => {
203
+ if (!machine.snapshot) return [];
204
+ const runtime = fleet.connected(machine.id);
205
+ return (
206
+ await Promise.all(
207
+ machine.snapshot.agents
208
+ .filter(
209
+ (agent) =>
210
+ agent.agent === "pi" &&
211
+ (!machine.local ||
212
+ agent.pane_id !==
213
+ (agent.backend === "core"
214
+ ? process.env["HC_TERMINAL_ID"]
215
+ : process.env["HERDR_PANE_ID"])),
216
+ )
217
+ .map(async (agent) => {
218
+ const result = compactAgent(
219
+ agent,
220
+ machine.snapshot!,
221
+ machine.id,
222
+ machine.monitoredPaneIds?.has(agent.pane_id) ?? false,
223
+ );
224
+ try {
225
+ result["agent"] = await nativeAgentName(
226
+ runtime.client,
227
+ agent,
228
+ );
229
+ } catch {
230
+ // Older or unavailable receivers remain addressable by their terminal.
231
+ result["identityUnavailable"] = true;
232
+ }
233
+ return result;
234
+ }),
235
+ )
236
+ ).filter((agent) => matchesAgent(agent, params.query, params.status));
237
+ }),
238
+ )
239
+ ).flat();
221
240
  const workspaces = machines.flatMap((machine) =>
222
241
  (machine.snapshot?.workspaces ?? []).map((workspace) => ({
223
242
  machine: machine.id,
@@ -3,6 +3,7 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import { nativeAgentName } from "./agent-identity.js";
6
7
  import {
7
8
  type AgentsParams,
8
9
  requiredAgentField as required,
@@ -140,7 +141,7 @@ export async function spawnAgent(
140
141
  const sharing =
141
142
  profile.shareContext === false
142
143
  ? undefined
143
- : await sharedContext.spawns.prepare(ctx, runtime, name, agentArgs);
144
+ : await sharedContext.spawns.prepare(ctx, runtime, agentArgs);
144
145
  const boardBinding = await board.prepare(ctx, runtime, name, agentArgs);
145
146
  const started = await startAgent(
146
147
  runtime.client,
@@ -154,9 +155,11 @@ export async function spawnAgent(
154
155
  let dispatch;
155
156
  let shared: { agentName?: string; warning?: string } | undefined;
156
157
  let boardAgent: string | undefined;
158
+ let agentName: string | undefined;
157
159
  let relationshipWarning: string | undefined;
158
160
  const blocking = shouldBlockAgentSpawn(profile.blocking, params.blocking);
159
161
  try {
162
+ agentName = await nativeAgentName(runtime.client, started.agent, signal);
160
163
  await recordSpawn(started.agent, agentArgs);
161
164
  relationshipWarning = (await relationship?.accept(started.agent))
162
165
  ?.warning;
@@ -212,13 +215,12 @@ export async function spawnAgent(
212
215
  status: "working",
213
216
  next: "Do other work or end this turn; completion/blockage arrives automatically. Do not poll or await timers/extra Promises for reports",
214
217
  }),
218
+ agent: agentName,
215
219
  ...(boardAgent || shared?.agentName
216
220
  ? {
217
221
  sharing: {
218
- ...(boardAgent ? { boardAgent } : {}),
219
- ...(shared?.agentName
220
- ? { contextAgent: shared.agentName }
221
- : {}),
222
+ board: !!boardAgent,
223
+ context: !!shared?.agentName,
222
224
  },
223
225
  }
224
226
  : {}),
@@ -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,
@@ -46,7 +47,7 @@ export function createAgentsTool(
46
47
  label: "Shepherdr",
47
48
  description:
48
49
  "Delegate to persistent agents; {} lists additional action fields",
49
- promptGuidelines: ["Read agents help alone before first use"],
50
+ promptGuidelines: ["agents: Read help alone first"],
50
51
  parameters: AgentsParameters,
51
52
  executionMode: "parallel",
52
53
  async execute(_toolCallId, input: AgentsToolParams, signal, onUpdate, ctx) {
@@ -98,6 +99,15 @@ export function createAgentsTool(
98
99
  );
99
100
  runtime = root.runtime;
100
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;
101
111
  }
102
112
  if (params.action === "focus") {
103
113
  executionSignal.throwIfAborted();
@@ -216,7 +226,7 @@ export function createAgentsTool(
216
226
  runtime,
217
227
  panel,
218
228
  message,
219
- params.blocking !== false,
229
+ params.blocking === true,
220
230
  executionSignal,
221
231
  update,
222
232
  () => runtime.client.sendMessage(panel, attributedMessage),
@@ -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;