@narumitw/pi-herdr 0.4.1 → 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.
@@ -3,14 +3,13 @@ import { createEditorStatusPublisher, type EditorStatusPublisher } from "@narumi
3
3
  import { type HerdrRequest, type HerdrSubscription, openHerdrSubscription, requestHerdr } from "./herdr-client.js";
4
4
  import {
5
5
  type HerdrPane,
6
- type HerdrPaneEvent,
7
6
  type HerdrWorkspace,
8
7
  herdrWidgetSubscriptions,
9
8
  parseAgentListResult,
10
9
  parseHerdrPaneEvent,
11
10
  parsePaneCurrentResult,
12
11
  parsePaneListResult,
13
- parseWorkspaceGetResult,
12
+ parseWorkspaceListResult,
14
13
  } from "./herdr-protocol.js";
15
14
  import {
16
15
  createHerdrWidget,
@@ -46,6 +45,8 @@ export interface HerdrWidgetObserver {
46
45
  shutdown(ctx: ExtensionContext): Promise<void>;
47
46
  }
48
47
 
48
+ const MAX_CONSECUTIVE_DISCARDS = 2;
49
+
49
50
  class HerdrTopologyChangedError extends Error {}
50
51
  class HerdrCleanupError extends AggregateError {}
51
52
 
@@ -53,20 +54,6 @@ function renderHerdrWidget(snapshot: HerdrWidgetSnapshot, theme: Theme, width: n
53
54
  return createHerdrWidget(snapshot, theme, false).render(width);
54
55
  }
55
56
 
56
- function isRelevantEvent(model: HerdrWidgetModel, event: HerdrPaneEvent): boolean {
57
- if (event.type === "created" || event.type === "updated") {
58
- return model.isCurrentWorkspace(event.pane.workspaceId);
59
- }
60
- if (event.type === "moved") {
61
- return (
62
- model.isCurrentPane(event.previousPaneId) ||
63
- model.isCurrentWorkspace(event.previousWorkspaceId) ||
64
- model.isCurrentWorkspace(event.pane.workspaceId)
65
- );
66
- }
67
- return "workspaceId" in event && model.isCurrentWorkspace(event.workspaceId);
68
- }
69
-
70
57
  function subscriptionFingerprint(currentPane: HerdrPane, panes: readonly HerdrPane[]): string {
71
58
  const agentPaneIds = panes
72
59
  .filter((pane) => pane.agent !== undefined)
@@ -132,7 +119,7 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
132
119
  ctx: ExtensionContext,
133
120
  expectedGeneration: number,
134
121
  signal: AbortSignal,
135
- ): Promise<{ currentPane: HerdrPane; panes: HerdrPane[]; workspace: HerdrWorkspace } | undefined> => {
122
+ ): Promise<{ currentPane: HerdrPane; panes: HerdrPane[]; workspaces: HerdrWorkspace[] } | undefined> => {
136
123
  const currentResult = await request(
137
124
  options.environment.socketEndpoint,
138
125
  {
@@ -143,14 +130,14 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
143
130
  signal,
144
131
  );
145
132
  if (!owns(ctx, expectedGeneration) || signal.aborted) return undefined;
146
- const currentPane = parsePaneCurrentResult(currentResult);
133
+ const caller = parsePaneCurrentResult(currentResult);
147
134
  const [listResult, agentResult, workspaceResult] = await Promise.all([
148
135
  request(
149
136
  options.environment.socketEndpoint,
150
137
  {
151
138
  id: requestId("list"),
152
139
  method: "pane.list",
153
- params: { workspace_id: currentPane.workspaceId },
140
+ params: {},
154
141
  },
155
142
  signal,
156
143
  ),
@@ -163,32 +150,31 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
163
150
  options.environment.socketEndpoint,
164
151
  {
165
152
  id: requestId("workspace"),
166
- method: "workspace.get",
167
- params: { workspace_id: currentPane.workspaceId },
153
+ method: "workspace.list",
154
+ params: {},
168
155
  },
169
156
  signal,
170
157
  ),
171
158
  ]);
172
159
  if (!owns(ctx, expectedGeneration) || signal.aborted) return undefined;
173
160
  const panes = parsePaneListResult(listResult);
174
- const paneIds = new Set(panes.map((pane) => pane.paneId));
161
+ const panesById = new Map(panes.map((pane) => [pane.paneId, pane]));
162
+ // Pin the terminal, not its session. The later list supplies the session identity.
163
+ const currentPane = panesById.get(caller.paneId);
164
+ if (currentPane?.terminalId !== caller.terminalId) throw new HerdrTopologyChangedError();
175
165
  const namesByPane = new Map(
176
166
  parseAgentListResult(agentResult)
177
- .filter((pane) => pane.workspaceId === currentPane.workspaceId && paneIds.has(pane.paneId))
167
+ .filter((pane) => panesById.get(pane.paneId)?.workspaceId === pane.workspaceId)
178
168
  .map((pane) => [pane.paneId, pane.agentName]),
179
169
  );
180
170
  const withAgentName = (pane: HerdrPane): HerdrPane => ({
181
171
  ...pane,
182
172
  agentName: namesByPane.get(pane.paneId) ?? pane.agentName,
183
173
  });
184
- const workspace = parseWorkspaceGetResult(workspaceResult);
185
- if (workspace.workspaceId !== currentPane.workspaceId) {
186
- throw new Error("Herdr returned a mismatched workspace");
187
- }
188
174
  return {
189
175
  currentPane: withAgentName(currentPane),
190
176
  panes: panes.map(withAgentName),
191
- workspace,
177
+ workspaces: parseWorkspaceListResult(workspaceResult),
192
178
  };
193
179
  };
194
180
 
@@ -232,8 +218,8 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
232
218
  if (!discovered) return;
233
219
  const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
234
220
  const model = new HerdrWidgetModel();
235
- model.reset(discovered.currentPane, discovered.panes, discovered.workspace);
236
221
  let dirty = true;
222
+ let consecutiveDiscards = 0;
237
223
 
238
224
  subscription = await subscribe(
239
225
  options.environment.socketEndpoint,
@@ -246,7 +232,7 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
246
232
  (frame) => {
247
233
  if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
248
234
  const event = parseHerdrPaneEvent(frame);
249
- if (!event || !isRelevantEvent(model, event)) return;
235
+ if (!event) return;
250
236
  dirty = true;
251
237
  wakeRefresh();
252
238
  },
@@ -269,13 +255,19 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
269
255
  dirty = false;
270
256
  const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
271
257
  if (!refreshed || signal.aborted) break;
272
- // Events and reads have no common sequence boundary. Never replay event
273
- // payloads over a read, or publish a read invalidated while in flight.
274
- if (dirty) continue;
275
258
  if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
276
259
  throw new HerdrTopologyChangedError();
277
260
  }
278
- model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
261
+ // Events and reads have no common sequence boundary. Discard short
262
+ // bursts, but bound discards so continuous events cannot starve rows.
263
+ // Publish only complete reads, never event payloads; dirty below makes
264
+ // the next refresh immediate after a bounded best-effort publication.
265
+ if (dirty && consecutiveDiscards < MAX_CONSECUTIVE_DISCARDS) {
266
+ consecutiveDiscards += 1;
267
+ continue;
268
+ }
269
+ consecutiveDiscards = 0;
270
+ model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspaces);
279
271
  publish(ctx, model, expectedGeneration);
280
272
  await new Promise<void>((resolve) => {
281
273
  wake = resolve;
@@ -1,3 +1,9 @@
1
+ import {
2
+ type HerdrSpawnProvenance,
3
+ herdrSessionFingerprint,
4
+ parseHerdrSpawnProvenance,
5
+ } from "./herdr-spawn-provenance.js";
6
+
1
7
  export const HERDR_AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"] as const;
2
8
 
3
9
  export type HerdrAgentStatus = (typeof HERDR_AGENT_STATUSES)[number];
@@ -7,6 +13,8 @@ export interface HerdrPane {
7
13
  workspaceId: string;
8
14
  tabId: string;
9
15
  terminalId: string;
16
+ sessionFingerprint?: string;
17
+ spawn?: HerdrSpawnProvenance;
10
18
  focused: boolean;
11
19
  revision: number;
12
20
  agent?: string;
@@ -31,7 +39,7 @@ export type HerdrPaneEvent =
31
39
  paneId: string;
32
40
  workspaceId: string;
33
41
  }
34
- | { type: "workspace_renamed"; workspaceId: string }
42
+ | { type: "workspace_created" | "workspace_closed" | "workspace_renamed"; workspaceId: string }
35
43
  | {
36
44
  type: "moved";
37
45
  pane: HerdrPane;
@@ -40,6 +48,8 @@ export type HerdrPaneEvent =
40
48
  };
41
49
 
42
50
  const HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
51
+ { type: "workspace.created" },
52
+ { type: "workspace.closed" },
43
53
  { type: "pane.created" },
44
54
  { type: "pane.updated" },
45
55
  { type: "workspace.renamed" },
@@ -104,11 +114,16 @@ export function parseHerdrPane(value: unknown): HerdrPane | undefined {
104
114
  ) {
105
115
  return undefined;
106
116
  }
117
+ const sessionFingerprint =
118
+ value.agent === "pi" ? herdrSessionFingerprint(terminalId, value.agent_session) : undefined;
119
+ const spawn = parseHerdrSpawnProvenance(value.tokens, terminalId, sessionFingerprint);
107
120
  return {
108
121
  paneId,
109
122
  workspaceId,
110
123
  tabId,
111
124
  terminalId,
125
+ ...(sessionFingerprint ? { sessionFingerprint } : {}),
126
+ ...(spawn ? { spawn } : {}),
112
127
  focused: value.focused,
113
128
  revision,
114
129
  agent: optionalString(value.agent),
@@ -152,13 +167,16 @@ export function parseAgentListResult(value: unknown): HerdrPane[] {
152
167
  });
153
168
  }
154
169
 
155
- export function parseWorkspaceGetResult(value: unknown): HerdrWorkspace {
156
- if (!isRecord(value) || value.type !== "workspace_info" || !isRecord(value.workspace)) {
157
- throw new Error("Herdr returned an invalid workspace response");
170
+ export function parseWorkspaceListResult(value: unknown): HerdrWorkspace[] {
171
+ if (!isRecord(value) || value.type !== "workspace_list" || !Array.isArray(value.workspaces)) {
172
+ throw new Error("Herdr returned an invalid workspace-list response");
158
173
  }
159
- const workspaceId = requiredString(value.workspace.workspace_id);
160
- if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
161
- return { workspaceId, label: optionalString(value.workspace.label) };
174
+ return value.workspaces.map((workspace: unknown) => {
175
+ if (!isRecord(workspace)) throw new Error("Herdr returned an invalid workspace");
176
+ const workspaceId = requiredString(workspace.workspace_id);
177
+ if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
178
+ return { workspaceId, label: optionalString(workspace.label) };
179
+ });
162
180
  }
163
181
 
164
182
  export function parseHerdrPaneEvent(value: unknown): HerdrPaneEvent | undefined {
@@ -167,6 +185,14 @@ export function parseHerdrPaneEvent(value: unknown): HerdrPaneEvent | undefined
167
185
  }
168
186
  const data = value.data;
169
187
 
188
+ if (value.event === "workspace_created") {
189
+ const workspaceId = isRecord(data.workspace) ? requiredString(data.workspace.workspace_id) : undefined;
190
+ return workspaceId ? { type: "workspace_created", workspaceId } : undefined;
191
+ }
192
+ if (value.event === "workspace_closed") {
193
+ const workspaceId = requiredString(data.workspace_id);
194
+ return workspaceId ? { type: "workspace_closed", workspaceId } : undefined;
195
+ }
170
196
  if (value.event === "workspace_renamed") {
171
197
  const workspaceId = requiredString(data.workspace_id);
172
198
  if (!workspaceId || typeof data.label !== "string") return undefined;
@@ -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 }));
@@ -106,46 +172,33 @@ function immutableSnapshot(rows: HerdrWidgetRow[]): HerdrWidgetSnapshot | undefi
106
172
 
107
173
  export class HerdrWidgetModel {
108
174
  private currentPaneId: string | undefined;
109
- private currentWorkspaceId: string | undefined;
110
- private workspace: HerdrWorkspace | undefined;
175
+ private workspaces = new Map<string, HerdrWorkspace>();
111
176
  private panes = new Map<string, ObservedPane>();
112
177
 
113
- reset(
114
- currentPane: HerdrPane,
115
- panes: readonly HerdrPane[],
116
- workspace: HerdrWorkspace = { workspaceId: currentPane.workspaceId },
117
- ): void {
178
+ reset(currentPane: HerdrPane, panes: readonly HerdrPane[], workspaces: readonly HerdrWorkspace[] = []): void {
118
179
  this.currentPaneId = currentPane.paneId;
119
- this.currentWorkspaceId = currentPane.workspaceId;
120
- this.workspace = { ...workspace };
180
+ this.workspaces = new Map(workspaces.map((workspace) => [workspace.workspaceId, { ...workspace }]));
121
181
  this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
182
+ this.panes.set(currentPane.paneId, observedPane(currentPane));
122
183
  }
123
184
 
124
185
  clear(): void {
125
186
  this.currentPaneId = undefined;
126
- this.currentWorkspaceId = undefined;
127
- this.workspace = undefined;
187
+ this.workspaces.clear();
128
188
  this.panes.clear();
129
189
  }
130
190
 
131
- isCurrentPane(paneId: string): boolean {
132
- return this.currentPaneId === paneId;
133
- }
134
-
135
- isCurrentWorkspace(workspaceId: string): boolean {
136
- return this.currentWorkspaceId === workspaceId;
137
- }
138
-
139
191
  snapshot(): HerdrWidgetSnapshot | undefined {
140
- if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return undefined;
141
- const rows = [...this.panes.values()]
142
- .filter(
143
- (pane) =>
144
- pane.workspaceId === this.currentWorkspaceId &&
145
- pane.paneId !== this.currentPaneId &&
146
- pane.agent !== undefined,
147
- )
148
- .map((pane) => rowForPane(pane, this.workspace as HerdrWorkspace));
192
+ if (!this.currentPaneId) return undefined;
193
+ const panes = [...this.panes.values()];
194
+ const relations = spawnRelations(panes, this.currentPaneId);
195
+ const rows = panes
196
+ .filter((pane) => pane.paneId !== this.currentPaneId && pane.agent !== undefined)
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
+ });
149
202
  rows.sort(
150
203
  (left, right) =>
151
204
  STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
@@ -157,8 +210,9 @@ export class HerdrWidgetModel {
157
210
  }
158
211
  }
159
212
 
160
- function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string {
213
+ function stateStyle(theme: Theme, state: HerdrWidgetState, text: string): string {
161
214
  switch (state) {
215
+ case "error":
162
216
  case "blocked":
163
217
  return theme.fg("error", text);
164
218
  case "done":
@@ -172,8 +226,10 @@ function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string
172
226
  }
173
227
  }
174
228
 
175
- function stateSymbol(state: HerdrAgentStatus): string {
229
+ function stateSymbol(state: HerdrWidgetState): string {
176
230
  switch (state) {
231
+ case "error":
232
+ return "!";
177
233
  case "blocked":
178
234
  return "×";
179
235
  case "done":
@@ -206,7 +262,8 @@ export function createHerdrWidget(
206
262
  const agent = theme.bold(theme.fg("text", row.agent));
207
263
  const pane = theme.fg("muted", row.pane);
208
264
  const space = theme.fg("dim", row.space);
209
- 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}`);
210
267
  }
211
268
  if (snapshot.hiddenAgents > 0) {
212
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 sibling agents 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 \"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,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
- }
@@ -1,22 +0,0 @@
1
- ---
2
- name: hc
3
- description: "Control persistent terminals and coding agents through the Herdr Core hc CLI. Use only when the user explicitly mentions hc, Herdr Core, or herdr-core, or asks to use them to run programs, delegate tasks, inspect terminals, or send input. Do not use merely because a task could benefit from a background terminal, delegation, or parallel work."
4
- ---
5
-
6
- # Herdr Core
7
-
8
- `hc` controls Herdr Core terminals, not legacy Herdr panes.
9
- It does not require a Herdr-managed pane or `HC_TERMINAL_ID`.
10
-
11
- Before the first hc control command in a session, check whether the complete output of `hc --skill` is already present in the current context.
12
- If it is present, reuse it and do not load it again.
13
- Otherwise run this single shell call:
14
-
15
- ```bash
16
- hc --skill
17
- ```
18
-
19
- If the CLI is unavailable or the command fails, report the error and stop without falling back to `herdr`.
20
- Read the returned skill completely and follow it as the authoritative operating instructions for the installed Herdr Core version.
21
- If the output is truncated, retrieve the complete guidance before running a control command.
22
- Run it again only after compaction removes those instructions or when the user explicitly asks to refresh them.