@howaboua/pi-shepherdr 0.2.25 → 0.2.27

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.
@@ -16,8 +16,17 @@ import type {
16
16
  } from "@howaboua/pi-notes-compaction/context-sharing";
17
17
  import { Check } from "typebox/value";
18
18
  import { AgentAttachment } from "./attachment.js";
19
- import { attachmentRoutes, Identity } from "./attachment-protocol.js";
19
+ import {
20
+ attachmentRoutes,
21
+ canonicalContextIdentity,
22
+ Identity,
23
+ } from "./attachment-protocol.js";
20
24
  import type { AgentBoard } from "./board/host.js";
25
+ import {
26
+ contextRouteMatches,
27
+ countContextTargets,
28
+ sendContextRoute,
29
+ } from "./context-routing.js";
21
30
  import type { AgentFleet } from "./fleet/index.js";
22
31
  import { sessionPath } from "./herdr.js";
23
32
  import {
@@ -34,6 +43,7 @@ interface ContextEnvelope {
34
43
  operation: "context";
35
44
  request: SharedContextRequest;
36
45
  visited: string[];
46
+ downstream?: boolean;
37
47
  }
38
48
 
39
49
  export class SharedAgentContext {
@@ -101,6 +111,13 @@ export class SharedAgentContext {
101
111
  value: unknown,
102
112
  signal?: AbortSignal,
103
113
  ): Promise<unknown> {
114
+ if (
115
+ value &&
116
+ typeof value === "object" &&
117
+ "operation" in value &&
118
+ value.operation === "agent-identity"
119
+ )
120
+ return { sessionId: ctx.sessionManager.getSessionId() };
104
121
  if (
105
122
  value &&
106
123
  typeof value === "object" &&
@@ -130,7 +147,7 @@ export class SharedAgentContext {
130
147
  const upstream =
131
148
  value.scope === "board"
132
149
  ? own.upstream
133
- : identity?.agentName !== "/root" &&
150
+ : identity?.threadId !== identity?.sessionId &&
134
151
  routing?.transport === "shepherdr"
135
152
  ? routing.parent
136
153
  : undefined;
@@ -144,8 +161,8 @@ export class SharedAgentContext {
144
161
  signal,
145
162
  );
146
163
  if (
147
- (value.scope === "board" ? own.agentName : identity?.agentName) !==
148
- "/root"
164
+ (value.scope === "board" ? own.sessionId : identity?.threadId) !==
165
+ family
149
166
  )
150
167
  throw new Error("No live /root in this agent family");
151
168
  return {
@@ -175,7 +192,10 @@ export class SharedAgentContext {
175
192
  !file ||
176
193
  !("identity" in value) ||
177
194
  !Check(Identity, value.identity) ||
178
- !isDeepStrictEqual(identity, value.identity) ||
195
+ !isDeepStrictEqual(
196
+ identity,
197
+ canonicalContextIdentity(value.identity),
198
+ ) ||
179
199
  identity?.threadId !== ctx.sessionManager.getSessionId()
180
200
  )
181
201
  throw new Error("Invalid saved checkpoint owner");
@@ -195,6 +215,14 @@ export class SharedAgentContext {
195
215
  }
196
216
  if (!identity || !service)
197
217
  throw new Error("Context sharing is unavailable in this session");
218
+ if ("operation" in value && value.operation === "context-resolve")
219
+ return countContextTargets(
220
+ ctx,
221
+ identity,
222
+ value as Record<string, unknown>,
223
+ this.fleet,
224
+ signal,
225
+ );
198
226
  const envelope = value as Partial<ContextEnvelope>;
199
227
  const request = envelope.request;
200
228
  if (
@@ -208,17 +236,49 @@ export class SharedAgentContext {
208
236
  envelope.visited.includes(identity.threadId)
209
237
  )
210
238
  throw new Error("Invalid shared context route or session family");
211
- if (identity.agentName === request.agentName) {
239
+ const forwarded = {
240
+ ...envelope,
241
+ visited: [...envelope.visited, identity.threadId],
242
+ };
243
+ const nativeTarget =
244
+ /^\/[^/]+$/.test(request.agentName) && request.agentName !== "/root";
245
+ const routing = identity.routing as Partial<Routing> | undefined;
246
+ let resolved: Awaited<ReturnType<typeof contextRouteMatches>> | undefined;
247
+ if (nativeTarget && !envelope.downstream) {
248
+ if (
249
+ routing?.transport === "shepherdr" &&
250
+ typeof routing.parent === "string"
251
+ )
252
+ return requestContext(routing.parent, forwarded, signal);
253
+ resolved = await contextRouteMatches(
254
+ ctx,
255
+ identity,
256
+ request.agentName,
257
+ [identity.threadId],
258
+ this.fleet,
259
+ signal,
260
+ );
261
+ const count = resolved.reduce(
262
+ (total, match) => total + match.count,
263
+ identity.agentName === request.agentName ? 1 : 0,
264
+ );
265
+ if (count > 1)
266
+ throw new Error(
267
+ `Multiple shared agents use ${request.agentName}; start sessions with distinct Pi IDs`,
268
+ );
269
+ }
270
+ if (
271
+ identity.agentName === request.agentName ||
272
+ identity.storageAgentName === request.agentName ||
273
+ (request.agentName === "/root" &&
274
+ identity.threadId === identity.sessionId)
275
+ ) {
212
276
  if (!ctx.isIdle() && !this.running)
213
277
  throw new Error(
214
278
  "Context owner is changing branches; retry after it settles",
215
279
  );
216
280
  return service.execute(ctx, request, signal);
217
281
  }
218
- const forwarded = {
219
- ...envelope,
220
- visited: [...envelope.visited, identity.threadId],
221
- };
222
282
  const attached = await this.attachment.routing.route(
223
283
  ctx,
224
284
  request,
@@ -235,6 +295,7 @@ export class SharedAgentContext {
235
295
  );
236
296
  if (attached) return attached;
237
297
  const member = ctx.sessionManager.getEntries().findLast((entry) => {
298
+ if (!request.agentName.startsWith("/root/")) return false;
238
299
  if (entry.type !== "custom" || entry.customType !== MEMBER_ENTRY)
239
300
  return false;
240
301
  const candidate = entry.data as Member;
@@ -261,12 +322,46 @@ export class SharedAgentContext {
261
322
  signal,
262
323
  );
263
324
  }
264
- const routing = identity.routing as Partial<Routing> | undefined;
265
325
  if (
326
+ !envelope.downstream &&
266
327
  routing?.transport === "shepherdr" &&
267
328
  typeof routing.parent === "string"
268
329
  )
269
330
  return requestContext(routing.parent, forwarded, signal);
331
+ if (nativeTarget) {
332
+ // Change direction only at the family owner. Descending never relays upstream.
333
+ const visited = envelope.downstream
334
+ ? forwarded.visited
335
+ : [identity.threadId];
336
+ const matches =
337
+ resolved ??
338
+ (await contextRouteMatches(
339
+ ctx,
340
+ identity,
341
+ request.agentName,
342
+ visited,
343
+ this.fleet,
344
+ signal,
345
+ ));
346
+ const count = matches.reduce((total, match) => total + match.count, 0);
347
+ if (count > 1)
348
+ throw new Error(
349
+ `Multiple shared agents use ${request.agentName}; start sessions with distinct Pi IDs`,
350
+ );
351
+ const match = matches.find((candidate) => candidate.count === 1);
352
+ if (match)
353
+ return sendContextRoute(
354
+ this.fleet,
355
+ match.route,
356
+ {
357
+ operation: "context",
358
+ request: { ...request, sessionId: match.route.sessionId },
359
+ visited,
360
+ downstream: true,
361
+ },
362
+ signal,
363
+ );
364
+ }
270
365
  throw new Error(
271
366
  `No shared context agent ${request.agentName} in this session family`,
272
367
  );
@@ -5,6 +5,7 @@ import type {
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import type { CodexAgentRelationshipService } from "@howaboua/pi-codex-conversion/agent-relationship";
7
7
  import type { ContextSharingService } from "@howaboua/pi-notes-compaction/context-sharing";
8
+ import { nativeAgentName } from "./agent-identity.js";
8
9
  import type { ConnectedMachine } from "./fleet/index.js";
9
10
  import { sessionPath } from "./herdr.js";
10
11
  import { sessionContextPath } from "./remote/shepherdr-context.mjs";
@@ -100,7 +101,6 @@ export class SpawnContext {
100
101
  async prepare(
101
102
  ctx: ExtensionContext,
102
103
  runtime: ConnectedMachine,
103
- name: string,
104
104
  args: readonly string[] = [],
105
105
  ) {
106
106
  const service = this.getService();
@@ -129,15 +129,16 @@ export class SpawnContext {
129
129
  ? sessionContextPath(parentFile)
130
130
  : runtime.client.contextRelayPath(),
131
131
  };
132
- const { binding, adopt } = await service.createChild(ctx, {
133
- name,
134
- routing,
135
- });
136
132
  return {
137
133
  accept: async (agent: PaneInfo) => {
138
134
  const sessionFile = sessionPath(agent);
139
135
  if (!sessionFile)
140
136
  throw new Error("Spawned agent has no native Pi session path");
137
+ const agentName = await nativeAgentName(runtime.client, agent);
138
+ const { binding, adopt } = await service.createChild(ctx, {
139
+ threadId: agentName.slice(1),
140
+ routing,
141
+ });
141
142
  const value = await runtime.client.requestContext(
142
143
  sessionContextPath(sessionFile),
143
144
  { operation: "bind", binding },
package/src/types.ts CHANGED
@@ -108,6 +108,7 @@ export interface SessionSnapshot {
108
108
 
109
109
  export interface MonitoredAgent {
110
110
  readonly instructions?: string;
111
+ readonly latestInstruction?: string;
111
112
  readonly scope: "task" | "persistent";
112
113
  readonly activity: AgentActivity;
113
114
  readonly cwd?: string;
@@ -192,7 +192,7 @@ export function registerWorkerService(
192
192
  const sharing =
193
193
  worker || profile.shareContext === false
194
194
  ? undefined
195
- : await shared.spawns.prepare(ctx, runtime, name, args);
195
+ : await shared.spawns.prepare(ctx, runtime, args);
196
196
  const boardBinding = worker
197
197
  ? undefined
198
198
  : await board.prepare(ctx, runtime, name, args);
package/changelog.ts DELETED
@@ -1,337 +0,0 @@
1
- // Generated extension packages copy this file during changelog:extensions.
2
-
3
- import { randomUUID } from "node:crypto";
4
- import { readFileSync } from "node:fs";
5
- import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
6
- import { dirname, join } from "node:path";
7
- import { fileURLToPath } from "node:url";
8
- import {
9
- DynamicBorder,
10
- type ExtensionAPI,
11
- getAgentDir,
12
- getMarkdownTheme,
13
- } from "@earendil-works/pi-coding-agent";
14
- import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
15
-
16
- const ENTRY_TYPE = "@howaboua/pi-stuff/changelog";
17
- const REGISTRATION_CHANNEL = "@howaboua/pi-stuff/changelog/register/v1";
18
- const STATE_FILENAME = "howaboua-pi-stuff-changelog.json";
19
- const SUPPRESS_KEY = "suppress";
20
- const LOCK_STALE_MS = 30_000;
21
- const LOCK_TIMEOUT_MS = 2_000;
22
-
23
- interface PackageMetadata {
24
- name: string;
25
- version: string;
26
- }
27
-
28
- interface PackageRegistration extends PackageMetadata {
29
- changelogPath: string;
30
- }
31
-
32
- interface RegistrationEvent {
33
- accept: () => void;
34
- registration: PackageRegistration;
35
- }
36
-
37
- interface ChangelogEntry {
38
- content: string;
39
- version: string;
40
- }
41
-
42
- interface ChangelogEntryData {
43
- markdown: string;
44
- }
45
-
46
- type ChangelogState = Record<string, boolean | string>;
47
-
48
- function packageRegistration(): PackageRegistration {
49
- const packageDirectory = fileURLToPath(new URL(".", import.meta.url));
50
- const metadata = JSON.parse(
51
- readFileSync(join(packageDirectory, "package.json"), "utf8"),
52
- ) as Partial<PackageMetadata>;
53
- if (typeof metadata.name !== "string" || typeof metadata.version !== "string")
54
- throw new Error(`Invalid package metadata in ${packageDirectory}`);
55
- return {
56
- name: metadata.name,
57
- version: metadata.version,
58
- changelogPath: join(packageDirectory, "CHANGELOG.md"),
59
- };
60
- }
61
-
62
- function isRegistrationEvent(value: unknown): value is RegistrationEvent {
63
- if (!value || typeof value !== "object") return false;
64
- const event = value as Partial<RegistrationEvent>;
65
- return (
66
- typeof event.accept === "function" &&
67
- typeof event.registration?.name === "string" &&
68
- typeof event.registration.version === "string" &&
69
- typeof event.registration.changelogPath === "string"
70
- );
71
- }
72
-
73
- function parseChangelog(markdown: string): ChangelogEntry[] {
74
- const entries: ChangelogEntry[] = [];
75
- let currentLines: string[] = [];
76
- let currentVersion: string | undefined;
77
-
78
- for (const line of markdown.split("\n")) {
79
- const version = line.match(/^##\s+\[?(\d+\.\d+\.\d+)\]?(?:\s.*)?$/)?.[1];
80
- if (version) {
81
- if (currentVersion)
82
- entries.push({
83
- content: currentLines.join("\n").trim(),
84
- version: currentVersion,
85
- });
86
- currentVersion = version;
87
- currentLines = [line];
88
- } else if (currentVersion) {
89
- currentLines.push(line);
90
- }
91
- }
92
-
93
- if (currentVersion)
94
- entries.push({
95
- content: currentLines.join("\n").trim(),
96
- version: currentVersion,
97
- });
98
- return entries;
99
- }
100
-
101
- function compareVersions(left: string, right: string): number {
102
- const leftParts = left.split(".").map(Number);
103
- const rightParts = right.split(".").map(Number);
104
- for (let index = 0; index < 3; index++) {
105
- const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
106
- if (difference !== 0) return difference;
107
- }
108
- return 0;
109
- }
110
-
111
- function isStableVersion(version: string): boolean {
112
- return /^\d+\.\d+\.\d+$/.test(version);
113
- }
114
-
115
- function statePath(): string {
116
- return join(getAgentDir(), STATE_FILENAME);
117
- }
118
-
119
- async function readState(path: string): Promise<ChangelogState> {
120
- let text: string;
121
- try {
122
- text = await readFile(path, "utf8");
123
- } catch (error) {
124
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
125
- throw error;
126
- }
127
- const parsed = JSON.parse(text) as unknown;
128
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
129
- throw new Error(`${path} must contain a JSON object`);
130
- for (const [name, value] of Object.entries(parsed)) {
131
- if (name === SUPPRESS_KEY) {
132
- if (typeof value !== "boolean")
133
- throw new Error(`${path} ${SUPPRESS_KEY} must be a boolean`);
134
- } else if (typeof value !== "string") {
135
- throw new Error(`${path} version for ${name} must be a string`);
136
- }
137
- }
138
- return parsed as ChangelogState;
139
- }
140
-
141
- async function acquireLock(path: string): Promise<() => Promise<void>> {
142
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
143
- while (true) {
144
- try {
145
- await mkdir(path);
146
- return () => rm(path, { force: true, recursive: true });
147
- } catch (error) {
148
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
149
- const info = await stat(path).catch(() => undefined);
150
- if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
151
- await rm(path, { force: true, recursive: true });
152
- continue;
153
- }
154
- if (Date.now() >= deadline)
155
- throw new Error(`Timed out waiting for ${path}`);
156
- await new Promise((resolve) => setTimeout(resolve, 20));
157
- }
158
- }
159
- }
160
-
161
- async function writeState(path: string, state: ChangelogState): Promise<void> {
162
- await mkdir(dirname(path), { mode: 0o700, recursive: true });
163
- const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
164
- try {
165
- const ordered = Object.fromEntries(
166
- Object.entries(state).sort(([left], [right]) =>
167
- left.localeCompare(right),
168
- ),
169
- );
170
- await writeFile(temporaryPath, `${JSON.stringify(ordered, null, 2)}\n`, {
171
- encoding: "utf8",
172
- mode: 0o600,
173
- });
174
- await rename(temporaryPath, path);
175
- } catch (error) {
176
- await rm(temporaryPath, { force: true });
177
- throw error;
178
- }
179
- }
180
-
181
- function packageMarkdown(
182
- registration: PackageRegistration,
183
- entries: ChangelogEntry[],
184
- ): string {
185
- const body = (entry: ChangelogEntry) =>
186
- entry.content
187
- .replace(/^##[^\n]*\n*/, "")
188
- .replace(/^###\s+(?:Changes|Minor Changes|Patch Changes)\s*\n*/gim, "")
189
- .replace(/^###\s+(.+)$/gm, "**$1**");
190
- if (entries.length === 1) {
191
- const [entry] = entries;
192
- if (!entry) return "";
193
- return `## ${registration.name} ${entry.version}\n\n${body(entry)}`;
194
- }
195
- return [
196
- `## ${registration.name}`,
197
- ...entries.map((entry) => `**${entry.version}**\n\n${body(entry)}`),
198
- ].join("\n\n");
199
- }
200
-
201
- async function claimUpdates(
202
- registrations: Iterable<PackageRegistration>,
203
- ): Promise<{ errors: string[]; markdown?: string }> {
204
- const stableRegistrations = [...registrations]
205
- .filter((registration) => isStableVersion(registration.version))
206
- .sort((left, right) => left.name.localeCompare(right.name));
207
- if (stableRegistrations.length === 0) return { errors: [] };
208
- const path = statePath();
209
- await mkdir(dirname(path), { mode: 0o700, recursive: true });
210
- const release = await acquireLock(`${path}.lock`);
211
- try {
212
- const state = await readState(path);
213
- const errors: string[] = [];
214
- const sections: string[] = [];
215
- let changed = false;
216
- if (state[SUPPRESS_KEY] === true) {
217
- for (const registration of stableRegistrations) {
218
- const seenVersion = state[registration.name];
219
- if (
220
- typeof seenVersion !== "string" ||
221
- compareVersions(registration.version, seenVersion) > 0
222
- ) {
223
- state[registration.name] = registration.version;
224
- changed = true;
225
- }
226
- }
227
- if (changed) await writeState(path, state);
228
- return { errors };
229
- }
230
- for (const registration of stableRegistrations) {
231
- const seenVersion = state[registration.name];
232
- if (
233
- typeof seenVersion === "string" &&
234
- compareVersions(registration.version, seenVersion) <= 0
235
- )
236
- continue;
237
- try {
238
- const entries = parseChangelog(
239
- await readFile(registration.changelogPath, "utf8"),
240
- ).filter(
241
- (entry) =>
242
- compareVersions(entry.version, registration.version) <= 0 &&
243
- (typeof seenVersion === "string"
244
- ? compareVersions(entry.version, seenVersion) > 0
245
- : entry.version === registration.version),
246
- );
247
- if (entries.length === 0) {
248
- errors.push(
249
- `No ${registration.version} changelog entry found for ${registration.name}`,
250
- );
251
- continue;
252
- }
253
- sections.push(packageMarkdown(registration, entries));
254
- state[registration.name] = registration.version;
255
- changed = true;
256
- } catch (error) {
257
- errors.push(
258
- `Could not read the ${registration.name} changelog: ${error instanceof Error ? error.message : String(error)}`,
259
- );
260
- }
261
- }
262
- if (changed) await writeState(path, state);
263
- return {
264
- errors,
265
- ...(sections.length > 0 ? { markdown: sections.join("\n\n") } : {}),
266
- };
267
- } finally {
268
- await release();
269
- }
270
- }
271
-
272
- function registerCoordinator(
273
- pi: ExtensionAPI,
274
- registration: PackageRegistration,
275
- ): void {
276
- let accepted = false;
277
- pi.events.emit(REGISTRATION_CHANNEL, {
278
- registration,
279
- accept: () => {
280
- accepted = true;
281
- },
282
- } satisfies RegistrationEvent);
283
- if (accepted) return;
284
-
285
- const registrations = new Map([[registration.name, registration]]);
286
- pi.events.on(REGISTRATION_CHANNEL, (value) => {
287
- if (!isRegistrationEvent(value)) return;
288
- registrations.set(value.registration.name, value.registration);
289
- value.accept();
290
- });
291
- pi.registerEntryRenderer<ChangelogEntryData>(
292
- ENTRY_TYPE,
293
- (entry, _options, theme) => {
294
- if (!entry.data) return undefined;
295
- const container = new Container();
296
- container.addChild(new DynamicBorder());
297
- container.addChild(
298
- new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0),
299
- );
300
- container.addChild(new Spacer(1));
301
- container.addChild(
302
- new Markdown(entry.data.markdown.trim(), 1, 0, getMarkdownTheme()),
303
- );
304
- container.addChild(new Spacer(1));
305
- container.addChild(new DynamicBorder());
306
- return container;
307
- },
308
- );
309
- pi.on("session_start", async (event, ctx) => {
310
- if (event.reason === "reload" || ctx.mode !== "tui") return;
311
- if (
312
- ctx.sessionManager
313
- .getEntries()
314
- .some((entry) =>
315
- ["branch_summary", "compaction", "message"].includes(entry.type),
316
- )
317
- )
318
- return;
319
- try {
320
- const update = await claimUpdates(registrations.values());
321
- if (update.markdown)
322
- pi.appendEntry<ChangelogEntryData>(ENTRY_TYPE, {
323
- markdown: update.markdown,
324
- });
325
- for (const error of update.errors) ctx.ui.notify(error, "warning");
326
- } catch (error) {
327
- ctx.ui.notify(
328
- `Could not update Howaboua changelog state: ${error instanceof Error ? error.message : String(error)}`,
329
- "warning",
330
- );
331
- }
332
- });
333
- }
334
-
335
- export default function howabouaPackageChangelog(pi: ExtensionAPI): void {
336
- registerCoordinator(pi, packageRegistration());
337
- }