@narumitw/pi-herdr 0.5.0 → 0.6.0

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.
@@ -0,0 +1,22 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ const CHANNEL = "pi-herdr:runtime-claim:v1";
4
+
5
+ /** Avoid duplicate reporters when Pi discovers both source and generated copies of this package. */
6
+ export function claimHerdrRuntime(pi: ExtensionAPI): (() => void) | undefined {
7
+ const request = { version: 1, claimed: false };
8
+ // Pi's public event bus dispatches synchronous handlers before emit returns.
9
+ pi.events.emit(CHANNEL, request);
10
+ if (request.claimed) return undefined;
11
+ return pi.events.on(CHANNEL, (value: unknown) => {
12
+ if (
13
+ typeof value === "object" &&
14
+ value !== null &&
15
+ "version" in value &&
16
+ value.version === 1 &&
17
+ "claimed" in value &&
18
+ typeof value.claimed === "boolean"
19
+ )
20
+ value.claimed = true;
21
+ });
22
+ }
@@ -4,6 +4,8 @@ import { awaitHerdrSettingsWrites, herdrSettingsPath, readHerdrSettings, updateH
4
4
 
5
5
  export interface HerdrSettingsOptions {
6
6
  settingsPath?: string;
7
+ /** Selected transport, not a saved preference. */
8
+ backend?: "herdr" | "hc";
7
9
  }
8
10
 
9
11
  export function createHerdrSettingsController(
@@ -12,6 +14,7 @@ export function createHerdrSettingsController(
12
14
  options: HerdrSettingsOptions = {},
13
15
  ) {
14
16
  const settingsPath = options.settingsPath ?? herdrSettingsPath();
17
+ const label = options.backend === "hc" ? "hc" : "Herdr";
15
18
  let generation = 0;
16
19
  let owner: ExtensionContext | undefined;
17
20
  let controller = new AbortController();
@@ -21,7 +24,7 @@ export function createHerdrSettingsController(
21
24
  const current = (expected: number) => expected === generation && !controller.signal.aborted;
22
25
 
23
26
  pi.registerCommand("herdr", {
24
- description: "Configure the Herdr agent widget",
27
+ description: `Configure the ${label} agent widget`,
25
28
  handler: async (args, ctx) => {
26
29
  if (args.trim()) throw new Error("/herdr does not accept arguments.");
27
30
  if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
@@ -42,6 +45,7 @@ export function createHerdrSettingsController(
42
45
  ctx,
43
46
  createHerdrMenu({
44
47
  settingsPath,
48
+ backend: options.backend,
45
49
  isEnabled: () => enabled,
46
50
  toggle: (actionSignal) => {
47
51
  const result = changes.then(async () => {
@@ -66,7 +70,7 @@ export function createHerdrSettingsController(
66
70
  } finally {
67
71
  if (current(expected))
68
72
  ctx.ui.notify(
69
- "Herdr settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.",
73
+ `${label} settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.`,
70
74
  "warning",
71
75
  );
72
76
  }
@@ -85,7 +89,7 @@ export function createHerdrSettingsController(
85
89
  signal,
86
90
  isCurrent: () => current(expected),
87
91
  onError: () => {
88
- if (current(expected)) ctx.ui.notify("The Herdr menu could not be displayed.", "error");
92
+ if (current(expected)) ctx.ui.notify(`The ${label} menu could not be displayed.`, "error");
89
93
  },
90
94
  },
91
95
  );
@@ -112,7 +116,7 @@ export function createHerdrSettingsController(
112
116
  enabled = loaded.settings.widget;
113
117
  if (loaded.kind === "invalid" && ctx.hasUI)
114
118
  ctx.ui.notify(
115
- "Herdr ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.",
119
+ `${label} ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.`,
116
120
  "warning",
117
121
  );
118
122
  if (enabled && ctx.mode === "tui") observer.start(ctx);
@@ -0,0 +1,61 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export interface HerdrSpawnProvenance {
4
+ originTerminalId: string;
5
+ originSession: string;
6
+ targetSession: string;
7
+ originLabel: string;
8
+ }
9
+
10
+ function record(value: unknown): value is Record<string, unknown> {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+
14
+ function terminalIdentity(value: unknown): value is string {
15
+ return typeof value === "string" && value.length > 0 && [...value].length <= 256 && !/[\p{Cc}\p{Cf}]/u.test(value);
16
+ }
17
+
18
+ /** Correlates public native Pi identity; neither the source name nor this digest authenticates a caller. */
19
+ export function herdrSessionFingerprint(terminalId: unknown, session: unknown): string | undefined {
20
+ if (
21
+ !terminalIdentity(terminalId) ||
22
+ !record(session) ||
23
+ session.source !== "herdr:pi" ||
24
+ session.agent !== "pi" ||
25
+ (session.kind !== "id" && session.kind !== "path") ||
26
+ typeof session.value !== "string" ||
27
+ session.value.length === 0 ||
28
+ Buffer.byteLength(session.value, "utf8") > 4096
29
+ ) {
30
+ return undefined;
31
+ }
32
+ // Wire format shared with the standalone skill producer; round-trip tests prevent drift.
33
+ return createHash("sha256")
34
+ .update(JSON.stringify([terminalId, session.source, session.agent, session.kind, session.value]))
35
+ .digest("hex");
36
+ }
37
+
38
+ export function parseHerdrSpawnProvenance(
39
+ tokens: unknown,
40
+ targetTerminalId: string,
41
+ targetSession: string | undefined,
42
+ ): HerdrSpawnProvenance | undefined {
43
+ if (!record(tokens) || tokens.pi_spawn_v !== "1" || !targetSession) return undefined;
44
+ const originTerminalId = tokens.pi_spawn_origin;
45
+ const originSession = tokens.pi_spawn_from;
46
+ const originLabel = tokens.pi_spawn_label;
47
+ if (
48
+ !terminalIdentity(originTerminalId) ||
49
+ [...originTerminalId].length > 80 ||
50
+ originTerminalId === targetTerminalId ||
51
+ typeof originSession !== "string" ||
52
+ !/^[a-f0-9]{64}$/u.test(originSession) ||
53
+ tokens.pi_spawn_to !== targetSession ||
54
+ typeof originLabel !== "string" ||
55
+ originLabel.length === 0 ||
56
+ [...originLabel].length > 80
57
+ ) {
58
+ return undefined;
59
+ }
60
+ return { originTerminalId, originSession, targetSession, originLabel };
61
+ }
@@ -2,6 +2,7 @@ import type { Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
3
3
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
4
4
  import type { HerdrAgentStatus, HerdrPane, HerdrWorkspace } from "./herdr-protocol.js";
5
+ import type { HerdrSpawnProvenance } from "./herdr-spawn-provenance.js";
5
6
 
6
7
  export const HERDR_WIDGET_KEY = "herdr:agents";
7
8
  export const MAX_HERDR_WIDGET_AGENTS = 5;
@@ -9,6 +10,9 @@ export const MAX_HERDR_WIDGET_AGENTS = 5;
9
10
  interface ObservedPane {
10
11
  paneId: string;
11
12
  workspaceId: string;
13
+ terminalId: string;
14
+ sessionFingerprint?: string;
15
+ spawn?: HerdrSpawnProvenance;
12
16
  agent?: string;
13
17
  agentName?: string;
14
18
  agentStatus: HerdrAgentStatus;
@@ -18,13 +22,16 @@ interface ObservedPane {
18
22
  title?: string;
19
23
  }
20
24
 
25
+ export type HerdrWidgetState = HerdrAgentStatus | "error";
26
+
21
27
  export interface HerdrWidgetRow {
22
28
  agent: string;
23
29
  pane: string;
24
30
  paneId: string;
25
31
  space: string;
26
- state: HerdrAgentStatus;
32
+ state: HerdrWidgetState;
27
33
  stateLabel: string;
34
+ relation?: string;
28
35
  }
29
36
 
30
37
  export interface HerdrWidgetSnapshot {
@@ -33,7 +40,8 @@ export interface HerdrWidgetSnapshot {
33
40
  rows: readonly HerdrWidgetRow[];
34
41
  }
35
42
 
36
- const STATE_ORDER: Record<HerdrAgentStatus, number> = {
43
+ const STATE_ORDER: Record<HerdrWidgetState, number> = {
44
+ error: -1,
37
45
  blocked: 0,
38
46
  done: 1,
39
47
  working: 2,
@@ -45,6 +53,9 @@ function observedPane(pane: HerdrPane): ObservedPane {
45
53
  return {
46
54
  paneId: pane.paneId,
47
55
  workspaceId: pane.workspaceId,
56
+ terminalId: pane.terminalId,
57
+ sessionFingerprint: pane.sessionFingerprint,
58
+ spawn: pane.spawn ? { ...pane.spawn } : undefined,
48
59
  agent: pane.agent,
49
60
  agentName: pane.agentName,
50
61
  agentStatus: pane.agentStatus,
@@ -94,6 +105,61 @@ function rowForPane(pane: ObservedPane, workspace: HerdrWorkspace): HerdrWidgetR
94
105
  };
95
106
  }
96
107
 
108
+ function spawnRelations(panes: readonly ObservedPane[], currentPaneId: string): Map<string, string> {
109
+ const identities = new Map<string, ObservedPane | undefined>();
110
+ const key = (terminal: string, session: string) => JSON.stringify([terminal, session]);
111
+ for (const pane of panes) {
112
+ if (pane.agent !== "pi" || !pane.sessionFingerprint) continue;
113
+ const identity = key(pane.terminalId, pane.sessionFingerprint);
114
+ // Ambiguous identities must not resolve to an arbitrary live origin.
115
+ identities.set(identity, identities.has(identity) ? undefined : pane);
116
+ }
117
+ const origins = new Map<string, ObservedPane>();
118
+ const records = new Map<string, HerdrSpawnProvenance>();
119
+ for (const pane of panes) {
120
+ const spawn = pane.spawn;
121
+ if (
122
+ pane.agent !== "pi" ||
123
+ !pane.sessionFingerprint ||
124
+ !spawn ||
125
+ spawn.targetSession !== pane.sessionFingerprint ||
126
+ spawn.originTerminalId === pane.terminalId
127
+ )
128
+ continue;
129
+ records.set(pane.paneId, spawn);
130
+ const origin = identities.get(key(spawn.originTerminalId, spawn.originSession));
131
+ if (origin) origins.set(pane.paneId, origin);
132
+ }
133
+ const cyclic = (id: string): boolean => {
134
+ const visited = new Set<string>();
135
+ let next: string | undefined = id;
136
+ while (next !== undefined) {
137
+ if (visited.has(next)) return true;
138
+ visited.add(next);
139
+ next = origins.get(next)?.paneId;
140
+ }
141
+ return false;
142
+ };
143
+ const currentOrigin = cyclic(currentPaneId) ? undefined : origins.get(currentPaneId);
144
+ const relations = new Map<string, string>();
145
+ for (const pane of panes) {
146
+ const labels: string[] = [];
147
+ const spawn = records.get(pane.paneId);
148
+ if (spawn && !cyclic(pane.paneId)) {
149
+ const origin = origins.get(pane.paneId);
150
+ const label = origin
151
+ ? origin.paneId === currentPaneId
152
+ ? "you"
153
+ : `${agentDisplay(origin)}/${paneDisplay(origin)}`
154
+ : `${safeDisplay(spawn.originLabel) ?? "previous agent"} (unavailable)`;
155
+ labels.push(`spawned by ${label}`);
156
+ }
157
+ if (currentOrigin?.paneId === pane.paneId) labels.push("spawned you");
158
+ if (labels.length > 0) relations.set(pane.paneId, labels.join("; "));
159
+ }
160
+ return relations;
161
+ }
162
+
97
163
  function immutableSnapshot(rows: HerdrWidgetRow[]): HerdrWidgetSnapshot | undefined {
98
164
  if (rows.length === 0) return undefined;
99
165
  const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze({ ...row }));
@@ -113,6 +179,7 @@ export class HerdrWidgetModel {
113
179
  this.currentPaneId = currentPane.paneId;
114
180
  this.workspaces = new Map(workspaces.map((workspace) => [workspace.workspaceId, { ...workspace }]));
115
181
  this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
182
+ this.panes.set(currentPane.paneId, observedPane(currentPane));
116
183
  }
117
184
 
118
185
  clear(): void {
@@ -123,9 +190,15 @@ export class HerdrWidgetModel {
123
190
 
124
191
  snapshot(): HerdrWidgetSnapshot | undefined {
125
192
  if (!this.currentPaneId) return undefined;
126
- const rows = [...this.panes.values()]
193
+ const panes = [...this.panes.values()];
194
+ const relations = spawnRelations(panes, this.currentPaneId);
195
+ const rows = panes
127
196
  .filter((pane) => pane.paneId !== this.currentPaneId && pane.agent !== undefined)
128
- .map((pane) => rowForPane(pane, this.workspaces.get(pane.workspaceId) ?? { workspaceId: pane.workspaceId }));
197
+ .map((pane) => {
198
+ const row = rowForPane(pane, this.workspaces.get(pane.workspaceId) ?? { workspaceId: pane.workspaceId });
199
+ const relation = relations.get(pane.paneId);
200
+ return relation ? { ...row, relation } : row;
201
+ });
129
202
  rows.sort(
130
203
  (left, right) =>
131
204
  STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
@@ -137,8 +210,9 @@ export class HerdrWidgetModel {
137
210
  }
138
211
  }
139
212
 
140
- function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string {
213
+ function stateStyle(theme: Theme, state: HerdrWidgetState, text: string): string {
141
214
  switch (state) {
215
+ case "error":
142
216
  case "blocked":
143
217
  return theme.fg("error", text);
144
218
  case "done":
@@ -152,8 +226,10 @@ function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string
152
226
  }
153
227
  }
154
228
 
155
- function stateSymbol(state: HerdrAgentStatus): string {
229
+ function stateSymbol(state: HerdrWidgetState): string {
156
230
  switch (state) {
231
+ case "error":
232
+ return "!";
157
233
  case "blocked":
158
234
  return "×";
159
235
  case "done":
@@ -186,7 +262,8 @@ export function createHerdrWidget(
186
262
  const agent = theme.bold(theme.fg("text", row.agent));
187
263
  const pane = theme.fg("muted", row.pane);
188
264
  const space = theme.fg("dim", row.space);
189
- lines.push(`${state} ${agent}${separator}${pane}${separator}${space}`);
265
+ const relation = row.relation ? `${separator}${theme.fg("muted", row.relation)}` : "";
266
+ lines.push(`${state} ${agent}${separator}${pane}${separator}${space}${relation}`);
190
267
  }
191
268
  if (snapshot.hiddenAgents > 0) {
192
269
  lines.push(theme.fg("dim", `+${snapshot.hiddenAgents} more`));
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export { default } from "./herdr-agent-state.js";
1
+ export { default } from "./herdr-integration.js";
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/herdr-menu.ts"],
4
- "sourcesContent": ["import type { MenuDefinition } from \"@narumitw/pi-tui-kit\";\n\nexport function createHerdrMenu(options: {\n settingsPath: string;\n isEnabled(): boolean;\n toggle(signal: AbortSignal): Promise<boolean>;\n}): MenuDefinition<undefined, \"main\" | \"status\" | \"help\", \"toggle\"> {\n return {\n start: \"main\",\n screens: {\n // One setting stays on the main menu, matching /tool rather than adding a submenu.\n main: () => ({\n kind: \"actions\",\n title: \"Herdr\",\n items: [\n {\n id: \"widget\",\n label: `Agent widget: ${options.isEnabled() ? \"On\" : \"Off\"}`,\n description: \"Show or hide agents across all workspaces above the editor\",\n action: \"toggle\",\n },\n { id: \"status\", label: \"Status\", to: \"status\" },\n { id: \"help\", label: \"Help\", to: \"help\" },\n { id: \"close\", label: \"Close\", close: true },\n ],\n hint: \"close\",\n }),\n status: () => ({\n kind: \"detail\",\n title: \"Herdr Status\",\n lines: [\n `Agent widget setting: ${options.isEnabled() ? \"on\" : \"off\"}`,\n \"The widget appears only in TUI mode with recognized sibling agents.\",\n \"Scope: all workspaces in the connected Herdr session.\",\n \"Lifecycle and metadata reporting are independent of this setting.\",\n `User settings file: ${options.settingsPath}`,\n ],\n hint: \"back\",\n }),\n help: () => ({\n kind: \"detail\",\n title: \"Herdr Help\",\n lines: [\n \"Toggle Agent widget from /herdr. Changes are saved immediately; closing does not undo them.\",\n \"Manual pi-herdr.json changes apply after /reload or the next session start.\",\n \"The widget defaults to on. Project overrides are not read.\",\n ],\n hint: \"back\",\n }),\n },\n actions: {\n toggle: async ({ signal }) => ((await options.toggle(signal)) ? { kind: \"stay\" } : { kind: \"rejected\" }),\n },\n };\n}\n"],
5
- "mappings": ";;;;AAEO,SAAS,gBAAgB,SAIoC;AAClE,SAAO;AAAA,IACL,OAAO;AAAA,IACP,SAAS;AAAA;AAAA,MAEP,MAAM,OAAO;AAAA,QACX,MAAM;AAAA,QACN,OAAO;AAAA,QACP,OAAO;AAAA,UACL;AAAA,YACE,IAAI;AAAA,YACJ,OAAO,iBAAiB,QAAQ,UAAU,IAAI,OAAO,KAAK;AAAA,YAC1D,aAAa;AAAA,YACb,QAAQ;AAAA,UACV;AAAA,UACA,EAAE,IAAI,UAAU,OAAO,UAAU,IAAI,SAAS;AAAA,UAC9C,EAAE,IAAI,QAAQ,OAAO,QAAQ,IAAI,OAAO;AAAA,UACxC,EAAE,IAAI,SAAS,OAAO,SAAS,OAAO,KAAK;AAAA,QAC7C;AAAA,QACA,MAAM;AAAA,MACR;AAAA,MACA,QAAQ,OAAO;AAAA,QACb,MAAM;AAAA,QACN,OAAO;AAAA,QACP,OAAO;AAAA,UACL,yBAAyB,QAAQ,UAAU,IAAI,OAAO,KAAK;AAAA,UAC3D;AAAA,UACA;AAAA,UACA;AAAA,UACA,uBAAuB,QAAQ,YAAY;AAAA,QAC7C;AAAA,QACA,MAAM;AAAA,MACR;AAAA,MACA,MAAM,OAAO;AAAA,QACX,MAAM;AAAA,QACN,OAAO;AAAA,QACP,OAAO;AAAA,UACL;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,QACA,MAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP,QAAQ,OAAO,EAAE,OAAO,MAAQ,MAAM,QAAQ,OAAO,MAAM,IAAK,EAAE,MAAM,OAAO,IAAI,EAAE,MAAM,WAAW;AAAA,IACxG;AAAA,EACF;AACF;",
6
- "names": []
7
- }