@narumitw/pi-herdr 0.4.1 → 0.5.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
  {
@@ -150,7 +137,7 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
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,28 @@ 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]));
175
162
  const namesByPane = new Map(
176
163
  parseAgentListResult(agentResult)
177
- .filter((pane) => pane.workspaceId === currentPane.workspaceId && paneIds.has(pane.paneId))
164
+ .filter((pane) => panesById.get(pane.paneId)?.workspaceId === pane.workspaceId)
178
165
  .map((pane) => [pane.paneId, pane.agentName]),
179
166
  );
180
167
  const withAgentName = (pane: HerdrPane): HerdrPane => ({
181
168
  ...pane,
182
169
  agentName: namesByPane.get(pane.paneId) ?? pane.agentName,
183
170
  });
184
- const workspace = parseWorkspaceGetResult(workspaceResult);
185
- if (workspace.workspaceId !== currentPane.workspaceId) {
186
- throw new Error("Herdr returned a mismatched workspace");
187
- }
188
171
  return {
189
172
  currentPane: withAgentName(currentPane),
190
173
  panes: panes.map(withAgentName),
191
- workspace,
174
+ workspaces: parseWorkspaceListResult(workspaceResult),
192
175
  };
193
176
  };
194
177
 
@@ -232,8 +215,8 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
232
215
  if (!discovered) return;
233
216
  const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
234
217
  const model = new HerdrWidgetModel();
235
- model.reset(discovered.currentPane, discovered.panes, discovered.workspace);
236
218
  let dirty = true;
219
+ let consecutiveDiscards = 0;
237
220
 
238
221
  subscription = await subscribe(
239
222
  options.environment.socketEndpoint,
@@ -246,7 +229,7 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
246
229
  (frame) => {
247
230
  if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
248
231
  const event = parseHerdrPaneEvent(frame);
249
- if (!event || !isRelevantEvent(model, event)) return;
232
+ if (!event) return;
250
233
  dirty = true;
251
234
  wakeRefresh();
252
235
  },
@@ -269,13 +252,19 @@ export function createHerdrWidgetObserver(options: HerdrObserverOptions): HerdrW
269
252
  dirty = false;
270
253
  const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
271
254
  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
255
  if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
276
256
  throw new HerdrTopologyChangedError();
277
257
  }
278
- model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
258
+ // Events and reads have no common sequence boundary. Discard short
259
+ // bursts, but bound discards so continuous events cannot starve rows.
260
+ // Publish only complete reads, never event payloads; dirty below makes
261
+ // the next refresh immediate after a bounded best-effort publication.
262
+ if (dirty && consecutiveDiscards < MAX_CONSECUTIVE_DISCARDS) {
263
+ consecutiveDiscards += 1;
264
+ continue;
265
+ }
266
+ consecutiveDiscards = 0;
267
+ model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspaces);
279
268
  publish(ctx, model, expectedGeneration);
280
269
  await new Promise<void>((resolve) => {
281
270
  wake = resolve;
@@ -31,7 +31,7 @@ export type HerdrPaneEvent =
31
31
  paneId: string;
32
32
  workspaceId: string;
33
33
  }
34
- | { type: "workspace_renamed"; workspaceId: string }
34
+ | { type: "workspace_created" | "workspace_closed" | "workspace_renamed"; workspaceId: string }
35
35
  | {
36
36
  type: "moved";
37
37
  pane: HerdrPane;
@@ -40,6 +40,8 @@ export type HerdrPaneEvent =
40
40
  };
41
41
 
42
42
  const HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
43
+ { type: "workspace.created" },
44
+ { type: "workspace.closed" },
43
45
  { type: "pane.created" },
44
46
  { type: "pane.updated" },
45
47
  { type: "workspace.renamed" },
@@ -152,13 +154,16 @@ export function parseAgentListResult(value: unknown): HerdrPane[] {
152
154
  });
153
155
  }
154
156
 
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");
157
+ export function parseWorkspaceListResult(value: unknown): HerdrWorkspace[] {
158
+ if (!isRecord(value) || value.type !== "workspace_list" || !Array.isArray(value.workspaces)) {
159
+ throw new Error("Herdr returned an invalid workspace-list response");
158
160
  }
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) };
161
+ return value.workspaces.map((workspace: unknown) => {
162
+ if (!isRecord(workspace)) throw new Error("Herdr returned an invalid workspace");
163
+ const workspaceId = requiredString(workspace.workspace_id);
164
+ if (!workspaceId) throw new Error("Herdr returned an invalid workspace identity");
165
+ return { workspaceId, label: optionalString(workspace.label) };
166
+ });
162
167
  }
163
168
 
164
169
  export function parseHerdrPaneEvent(value: unknown): HerdrPaneEvent | undefined {
@@ -167,6 +172,14 @@ export function parseHerdrPaneEvent(value: unknown): HerdrPaneEvent | undefined
167
172
  }
168
173
  const data = value.data;
169
174
 
175
+ if (value.event === "workspace_created") {
176
+ const workspaceId = isRecord(data.workspace) ? requiredString(data.workspace.workspace_id) : undefined;
177
+ return workspaceId ? { type: "workspace_created", workspaceId } : undefined;
178
+ }
179
+ if (value.event === "workspace_closed") {
180
+ const workspaceId = requiredString(data.workspace_id);
181
+ return workspaceId ? { type: "workspace_closed", workspaceId } : undefined;
182
+ }
170
183
  if (value.event === "workspace_renamed") {
171
184
  const workspaceId = requiredString(data.workspace_id);
172
185
  if (!workspaceId || typeof data.label !== "string") return undefined;
@@ -106,46 +106,26 @@ function immutableSnapshot(rows: HerdrWidgetRow[]): HerdrWidgetSnapshot | undefi
106
106
 
107
107
  export class HerdrWidgetModel {
108
108
  private currentPaneId: string | undefined;
109
- private currentWorkspaceId: string | undefined;
110
- private workspace: HerdrWorkspace | undefined;
109
+ private workspaces = new Map<string, HerdrWorkspace>();
111
110
  private panes = new Map<string, ObservedPane>();
112
111
 
113
- reset(
114
- currentPane: HerdrPane,
115
- panes: readonly HerdrPane[],
116
- workspace: HerdrWorkspace = { workspaceId: currentPane.workspaceId },
117
- ): void {
112
+ reset(currentPane: HerdrPane, panes: readonly HerdrPane[], workspaces: readonly HerdrWorkspace[] = []): void {
118
113
  this.currentPaneId = currentPane.paneId;
119
- this.currentWorkspaceId = currentPane.workspaceId;
120
- this.workspace = { ...workspace };
114
+ this.workspaces = new Map(workspaces.map((workspace) => [workspace.workspaceId, { ...workspace }]));
121
115
  this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
122
116
  }
123
117
 
124
118
  clear(): void {
125
119
  this.currentPaneId = undefined;
126
- this.currentWorkspaceId = undefined;
127
- this.workspace = undefined;
120
+ this.workspaces.clear();
128
121
  this.panes.clear();
129
122
  }
130
123
 
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
124
  snapshot(): HerdrWidgetSnapshot | undefined {
140
- if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return undefined;
125
+ if (!this.currentPaneId) return undefined;
141
126
  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));
127
+ .filter((pane) => pane.paneId !== this.currentPaneId && pane.agent !== undefined)
128
+ .map((pane) => rowForPane(pane, this.workspaces.get(pane.workspaceId) ?? { workspaceId: pane.workspaceId }));
149
129
  rows.sort(
150
130
  (left, right) =>
151
131
  STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
@@ -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.
@@ -1,34 +0,0 @@
1
- ---
2
- name: herdr
3
- description: "Control Herdr, a terminal multiplexer for coding agents. Use only when the user explicitly mentions Herdr or asks to use Herdr to inspect or control panes, tabs, workspaces, commands, or another agent. Do not use merely because a task could benefit from a background terminal, delegation, or parallel work. Requires HERDR_ENV=1."
4
- ---
5
-
6
- # Herdr
7
-
8
- Before the first Herdr control command in a session, check whether the complete output of `herdr --skill` is already present in the current context.
9
- If it is present, reuse it and do not load it again.
10
- Otherwise run this single shell call:
11
-
12
- ```bash
13
- test "${HERDR_ENV:-}" = 1 || {
14
- printf '%s\n' "Not running inside Herdr." >&2
15
- exit 1
16
- }
17
- herdr --skill
18
- ```
19
-
20
- If the environment check or command fails, report the error and stop.
21
- Read the returned skill completely and follow it as the authoritative operating instructions for the installed Herdr version.
22
- Run it again only after compaction removes those instructions or when the user explicitly asks to refresh them.
23
-
24
- Apply this cleanup policy in addition to those version-specific instructions:
25
-
26
- - Maintain an in-context cleanup ledger with each pane ID you create, its intended lifetime, and every stable pane-generation, terminal, and shell identity that Herdr exposes; for an agent pane, also record the assigned agent and stable agent-session or occupant-process identity.
27
- - Mark a pane as retained only when the user explicitly asks it to remain open after the task for later inspection or use, or when its continued existence is itself part of the requested result, and never close a retained pane automatically.
28
- - For a temporary pane, collect the required output, decide that no follow-up is needed, and attempt cleanup as soon as its work is no longer needed.
29
- - Automatically close a pane only through an operation documented by the loaded instructions that atomically checks the recorded pane and occupant identity together with an acceptable live state at mutation time.
30
- - For an agent pane, the atomic guard must match the assigned agent and every recorded stable identity and require `idle` or `done`; for a returned shell, it must match the recorded pane-generation, terminal, and shell identities and require no replacement occupant or foreground process.
31
- - A separate state read followed by an unconditional close is unsafe; if the installed Herdr version provides no suitable guarded close, leave the pane open and report that limitation.
32
- - Keep unresolved temporary entries after cancellation or interruption while the current model context survives, retry guarded cleanup at the next recovery boundary before further Herdr work, and sweep them again before the final response.
33
- - Never close the calling pane, a pre-existing pane, or a pane created by the user or another agent.
34
- - If guarded closure fails, keep the ledger entry and report the pane ID and reason.