herdr-gentle-shell 1.9.0 → 2.0.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.
package/DESIGN.md CHANGED
@@ -1538,9 +1538,12 @@ painted with the host theme, where a theme option shows that theme's own palette
1538
1538
  through the raw SGR the host hands back. Three footer legends (categories,
1539
1539
  option row, panes) are chosen by what the keys do right now and compact instead
1540
1540
  of wrapping. The theme list comes from `ctx.ui.getAllThemes()` in the host's own
1541
- order with `None` first, the `Gentle Shell theme` setting is painted dim and
1542
- refused with `Turn Theme sync off to pick a specific theme.` while the sync is
1543
- on, and a host that exposes no list shows one note instead of an empty picker.
1541
+ order with `None` first, the `Gentle Shell theme` setting is absent — never
1542
+ dim, never a refusal line — while the sync is on, and it returns on the same
1543
+ mounted card the moment the sync is turned off; a theme attempt that still
1544
+ arrives (the plain fallback menu, the apply path) writes nothing and is refused
1545
+ with `Turn Theme sync off to pick a specific theme.`. A host that exposes no
1546
+ list shows one note instead of an empty picker.
1544
1547
  The panel writes nothing itself: it calls the extension's apply path, swaps in
1545
1548
  the model that path re-read, and keeps the cursor by structural option ids.
1546
1549
 
package/README.md CHANGED
@@ -619,19 +619,22 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
619
619
  Pi session at a path. A linked Git worktree opens as a **worktree panel**
620
620
  (reusing the workspace Herdr already has for that checkout); a repository's
621
621
  primary checkout, a subdirectory or any generic directory opens as a
622
- **normal panel**. Panel kind is decided from git, the pane Herdr names is
622
+ **normal panel**. Panel kind is decided from git, and the pane Herdr names is
623
623
  verified to belong to its workspace and to sit in the requested path before
624
- Pi starts, and (unless `notify: false`) the caller is woken when that session
625
- really finishes. A worktree panel passes the target as both `--path` and
626
- `--cwd`, because Herdr resolves the owning repository from `--cwd` rather
627
- than from the process directory, so a worktree of another repository opens
628
- too; and when Herdr still answers `worktree_not_found` for a path git proves
629
- is a linked worktree, the panel opens as a normal one at the same path and
630
- the result says which kind it opened (`panel: normal` plus a `fallback:`
631
- row), while every other Herdr failure still aborts and opens nothing. The
632
- other worktree tools and the ODD and issues panels live
633
- in `odd-worktree` now; the sidebar and Moshi switches stayed here and are
634
- reached through `/herdr-gentle:customize` and, when gentle-shell-bridge
624
+ Pi starts. Opening is the whole job: the tool starts the session and returns,
625
+ the success text carries `path`, `branch` and `session` only, and the caller
626
+ reads real state itself with `orchestrator_list` or the herdr CLI — no
627
+ subscribe, no watcher, and no finish claim pushed back, because a "never
628
+ started" message about a working delegate is worse than no message. A
629
+ worktree panel passes the target as both `--path` and `--cwd`, because Herdr
630
+ resolves the owning repository from `--cwd` rather than from the process
631
+ directory, so a worktree of another repository opens too; and when Herdr
632
+ still answers `worktree_not_found` for a path git proves is a linked
633
+ worktree, the panel opens as a normal one at the same path and the result
634
+ says so with a `fallback:` row, while every other Herdr failure still aborts
635
+ and opens nothing. The other worktree tools and the ODD and issues panels
636
+ live in `odd-worktree` now; the sidebar and Moshi switches stayed here and
637
+ are reached through `/herdr-gentle:customize` and, when gentle-shell-bridge
635
638
  answers, also through the Gentle Shell customize menu's `Herdr` page. See
636
639
  [docs/herdr-session-open.md](docs/herdr-session-open.md).
637
640
 
@@ -645,9 +648,13 @@ switch and one pinned theme.
645
648
  palette of the theme Pi is showing, and it follows a theme change while Pi keeps
646
649
  running. While it is off, `Gentle Shell theme` pins one Gentle Shell / Pi theme
647
650
  from Pi's own inline list (`None` first, then the host's order) and `None`
648
- clears the pin; the setting is painted dim and refused while the sync is on
649
- (`Turn Theme sync off to pick a specific theme.`). Turning the sync off writes
650
- nothing to Herdr, so **Herdr keeps the last applied palette** — a fresh install
651
+ clears the pin. While the sync is on, `Gentle Shell theme` is not offered at
652
+ all: it is absent from the panel and from the page alike, and it comes back on
653
+ the surface you already have the moment the sync is turned off. A theme attempt
654
+ that still arrives (the plain fallback menu, the apply path) writes nothing and
655
+ is refused with `Turn Theme sync off to pick a specific theme.`. Turning the
656
+ sync off writes nothing to Herdr, so **Herdr keeps the last applied palette** — a
657
+ fresh install
651
658
  whose sync is off and whose theme is unassigned writes nothing at all. State is
652
659
  one file, `gentle-theme.json`, beside `gentle-moshi.json`.
653
660
 
@@ -35,7 +35,7 @@ canonical path.
35
35
 
36
36
  Extension: `extensions/herdr-session-open.ts`
37
37
  Libraries: `lib/herdr-session-open.js` (path classification, herdr argv,
38
- reply parsers), `lib/herdr-session-notifications.js` (finish subscription)
38
+ reply parsers)
39
39
 
40
40
  ## What it does, step by step
41
41
 
@@ -72,16 +72,23 @@ reply parsers), `lib/herdr-session-notifications.js` (finish subscription)
72
72
  --timeout 120000 -- --name <name> --session-id <uuid>` — or `--session <id>`
73
73
  when a session id is passed to resume. No `--session-dir` is needed: the
74
74
  pane's cwd is already the requested path.
75
- 6. **Subscribe to the finish** unless `notify: false` was passed.
76
-
77
- The result is compact, ordered `label: value` rows — `outcome`, `path`,
78
- `panel` (`worktree` or `normal`, naming the kind really opened), `fallback`
79
- (only when a worktree open fell back: `normal panel after herdr reported
80
- worktree_not_found`), `branch` (only for a Git checkout), `session`,
81
- `workspace`, `pane`, `agent` — and the same facts ride in `details` as `path`,
82
- `kind` (`worktree` / `primary` / `generic` / `normal` after a fallback),
83
- `branch`, `fallback` (only when it happened), `paneId`, `workspaceId`,
84
- `sessionId`, `resumed`, `agentName`, `notify`.
75
+ 6. **Return the result.** Opening is the whole job: the tool starts the
76
+ session and returns. It registers no watcher, polls nothing, and sends no
77
+ follow-up message — read the session's state with `orchestrator_list` or the
78
+ herdr CLI itself.
79
+
80
+ The result is compact, ordered `label: value` rows and nothing else: `path`,
81
+ `fallback` (only when a worktree open fell back: `normal panel after herdr
82
+ reported worktree_not_found`), `branch` (only for a Git checkout) and
83
+ `session` — each row only when it has a value. A success needs no `outcome`
84
+ row (it succeeded, so it is open), and a workspace, pane or agent name is
85
+ routing detail the caller never reads, so the success text carries none of
86
+ them. The same facts ride in `details` as `path`, `kind` (`worktree` /
87
+ `primary` / `generic` / `normal` after a fallback), `branch`, `fallback` (only
88
+ when it happened), `paneId`, `workspaceId`, `sessionId`, `resumed` and
89
+ `agentName`: `details` is the machine view, not the text. Refusals are the
90
+ opposite — every error names the pane and/or workspace id that failed,
91
+ because an error without the id that failed is useless.
85
92
 
86
93
  ## Parameters
87
94
 
@@ -90,36 +97,21 @@ worktree_not_found`), `branch` (only for a Git checkout), `session`,
90
97
  | `path` (required) | Directory to open the panel in: a Git worktree, a repository checkout, or any other directory |
91
98
  | `session` | Pi session id to resume; absent mints a new id |
92
99
  | `name` | Agent/pane name; defaults to the branch for a worktree panel and to the directory name otherwise, sanitized into Herdr's shape |
93
- | `notify` | Subscribe the caller to the finish notification (default `true`) |
94
100
 
95
101
  Agent names must match Herdr's documented shape — lowercase letters, digits,
96
102
  dash and underscore, starting with a letter, at most 32 characters
97
103
  (`^[a-z][a-z0-9_-]{0,31}$`). A name Herdr would reject is refused here, because
98
104
  the alternative is a launch that fails after a panel already exists.
99
105
 
100
- ## The finish notification
101
-
102
- With `notify` left on, the opener starts **one** watcher for the pane it just
103
- opened and polls `herdr agent get <paneId>` on a bounded interval:
104
-
105
- - **finished** — `agent_status` reads `idle` *after* that same pane was observed
106
- `working` at least once;
107
- - **never-started** — the pane went idle without ever reporting `working`;
108
- - **vanished** — the agent is gone (`agent_not_found`);
109
- - **timed-out** — nothing conclusive before the maximum wait (four hours by
110
- default).
111
-
112
- Only `finished` claims a finish. `blocked` means the delegate is waiting for
113
- input and never counts as `working`. A pane bound to a *different* Pi session is
114
- never reported as ours, and a launch grace window keeps the delegate's idle
115
- state right after `agent start` from being read as a finish.
106
+ ## No finish subscription
116
107
 
117
- The delivery route is the host's own message channel —
118
- `pi.sendMessage({ customType: "herdr-agent-sessions.finished", display: true,
119
- content, details }, { deliverAs: "followUp", triggerTurn: true })` — so the
120
- orchestrator is woken with the outcome instead of having to poll. A send that
121
- throws or rejects is retried, not swallowed; a send that never settles stops the
122
- watcher at the maximum wait.
108
+ The opener has none. There is no watcher, no polling interval, no environment
109
+ knob and no follow-up message: opening a session opens a session, and the
110
+ caller reads real state with `orchestrator_list` or the herdr CLI itself. A
111
+ subscription the opener published used to report `herdr session never
112
+ started` about a delegate that was working — the published state is another
113
+ process's view, so "never started" and "never reported anything" are
114
+ indistinguishable — and a claim that can be wrong is worse than no claim.
123
115
 
124
116
  ## Safety checks
125
117
 
@@ -127,10 +119,11 @@ watcher at the maximum wait.
127
119
  path or an agent name can never become a command.
128
120
  - **Closed herdr allowlist.** `herdrArgv` accepts only the operations this tool
129
121
  uses (`worktree list`, `worktree open`, `workspace create`, `pane list`,
130
- `agent start`, `agent get`) and, per operation, only the flags it passes.
122
+ `agent start`) and, per operation, only the flags it passes.
131
123
  Unknown operations and flags throw. `--trust-repository` is on no allowlist —
132
124
  trusting a repository is a human decision this tool never takes — and
133
- `--focus` is not either: panels open with `--no-focus`.
125
+ `--focus` is not either: panels open with `--no-focus`. A read operation is
126
+ on no allowlist either: nothing reads a session back.
134
127
  - **No unsafe guesses.** A missing path, a file instead of a directory, an
135
128
  unparseable reply, two workspaces claiming one checkout, a pane that belongs
136
129
  to another workspace, a pane whose cwd left the path, a reply that names no
@@ -146,9 +139,9 @@ watcher at the maximum wait.
146
139
  directory), or when the test opts in with
147
140
  `GENTLE_HERDR_ALLOW_LIVE_HERDR=1`. Any other inherited path is refused
148
141
  instead of spawned.
149
- - **Non-blocking.** Every herdr call and every `agent get` poll runs off the
150
- event loop with a bounded timeout that reaps the child, so a slow or hung
151
- daemon cannot freeze the session that opened the panel.
142
+ - **Non-blocking.** Every herdr call runs off the event loop with a bounded
143
+ timeout that reaps the child, so a slow or hung daemon cannot freeze the
144
+ session that opened the panel.
152
145
 
153
146
  ## Relation to the rest of the package
154
147
 
@@ -162,7 +155,8 @@ code with `odd-worktree` — it needs only a path.
162
155
  `node --test tools/herdr-session-open.test.js` covers the three path classes
163
156
  (linked worktree, primary checkout, generic directory including a subdirectory
164
157
  and a relative path), workspace reuse, the panel verification refusals, the
165
- herdr failures, the finish subscription, the binary-allowlist refusal and the
158
+ herdr failures, the create-only contract (no agent read, no follow-up message,
159
+ no subscription flag in `details`), the binary-allowlist refusal and the
166
160
  agent-name rules. `node --test tools/herdr-session-open-paths.test.js` covers
167
161
  symlinked generic/worktree/primary paths (including worktree reuse through a
168
162
  symlink), `git init --separate-git-dir` checkouts, and the refuse-before-panel
@@ -34,8 +34,11 @@ on both:
34
34
  applied palette survives Pi closing.
35
35
  - `Gentle Shell theme` assigns one Gentle Shell / Pi theme by name from Pi's own
36
36
  list (`None` first, then the host's order). While the stored sync is on the
37
- setting is painted dim, never given the selection band, and pressing Enter on
38
- it writes nothing: the apply path refuses with
37
+ setting is not offered at all: it is absent from the panel and from the
38
+ `Herdr` page alike, never painted dim and never a refusal line, and it comes
39
+ back on the surface you already have the moment the sync is turned off. A
40
+ theme attempt that still arrives — the plain fallback menu or the apply path —
41
+ writes nothing and is refused with
39
42
  `Turn Theme sync off to pick a specific theme.` Choosing `None` clears the pin
40
43
  (`theme: null`); choosing a name stores it. The stored pin is carried across a
41
44
  sync toggle untouched, so turning the sync off restores that choice instead of
@@ -51,7 +54,7 @@ The notices are fixed strings:
51
54
  | Sync turned on | `Theme sync on; Herdr's palette follows the theme active in Pi.` |
52
55
  | Sync turned off | `Theme sync off; Herdr keeps the palette it was last given.` |
53
56
  | Toggle already in that state | `Theme sync already on/off; nothing was changed.` |
54
- | Theme setting while the sync is on | `Turn Theme sync off to pick a specific theme.` |
57
+ | Theme attempt while the sync is on (fallback menu, apply path) | `Turn Theme sync off to pick a specific theme.` |
55
58
  | Theme assigned | `Gentle Shell theme set to <name>.` |
56
59
  | Pin cleared | `Gentle Shell theme set to Off; Herdr keeps the palette it was last given.` (the stored value stays `null` and the inline list marks `None`; only this notice — and the `Off (no theme assigned)` entry of the fallback menu and of the Gentle Shell page — spell it `Off`) |
57
60
  | Host exposes no theme list | `Could not read Pi's theme list (this host exposes no getAllThemes()); nothing was changed.` |
@@ -93,7 +96,9 @@ then rename), preserve an existing file's mode and create a new one as `0600`.
93
96
  setting marks no option and carries `state unknown; Enter turns the sync on`,
94
97
  the theme list marks nothing, and the follower does nothing. It is
95
98
  written over only when you act — toggling the sync writes a fresh document,
96
- and the theme setting is refused only by a *stored* `sync: true`.
99
+ and the theme setting is withheld only by a *stored* `sync: true` (the write
100
+ still refuses such an attempt, with
101
+ `Turn Theme sync off to pick a specific theme.`).
97
102
  - **`sync: false` with `theme: null`** is the default install: the follower
98
103
  asks for no palette at all, so nothing is written, nothing is reloaded and
99
104
  nothing is removed (S7).
@@ -737,15 +742,19 @@ the rest.
737
742
  - The theme list is read automatically from the host (`ctx.ui.getAllThemes()`)
738
743
  in the host's own order, `None` first; a host that exposes no list shows one
739
744
  note (`Themes unavailable; use Pi /settings`) instead of an empty picker, and
740
- an unreadable store adds `state unknown; Enter pins a theme`.
745
+ an unreadable store adds `state unknown; Enter pins a theme`. While the stored
746
+ sync is on the setting is not offered at all: the card reads
747
+ `Herdr Theme · 1/1`, with no dim line and no note, and the picker is back on
748
+ the same mounted card as soon as the sync is turned off.
741
749
 
742
750
  When gentle-shell-bridge answers, this card is still there and the same two
743
751
  settings are ALSO the `Theme sync` and `Select theme` rows of the `Herdr` page in
744
752
  Gentle Shell's own menu, painted by that host. One row per value, walked with
745
753
  the arrows and applied with `Enter` (the bridge never applies on a cursor move),
746
754
  the theme row keeps its own swatch, and the theme rows are simply not shown
747
- while the sync is on instead of being refused in place. The notices are the
748
- same fixed strings, and the sync needs no Pi reload on either surface.
755
+ while the sync is on instead of being refused in place — the panel withholds the
756
+ same setting the same way. The notices are the same fixed strings, and the sync
757
+ needs no Pi reload on either surface.
749
758
 
750
759
  The page's rows are FIXED for as long as the menu is open, which is why its
751
760
  theme rows cost one model read per paint burst instead of one per row. Two
@@ -2225,6 +2225,17 @@ function readHostThemeNames(ctx) {
2225
2225
  // here: the panel is a plain CommonJS module with no host colour API, and
2226
2226
  // falling back to the active theme would show a palette the user did not pick.
2227
2227
  // An unreadable theme throws, and the panel renders `Preview unavailable`.
2228
+ //
2229
+ // The background token is `selectedBg`, NEVER `accent`: Pi's `Theme.getBgAnsi`
2230
+ // throws `Unknown theme color: accent` because `accent` is a FOREGROUND token
2231
+ // (`theme-tokens.d.ts`: `accent` has `slot: "foreground"`; only `selectedBg`,
2232
+ // `searchMatchBg`, `userMessageBg`, `customMessageBg`, `toolPendingBg`,
2233
+ // `toolSuccessBg` and `toolErrorBg` are background tokens). Pi 1.6.0's built-in
2234
+ // catalogue is `system`, `dark` and `light`, and all three answer `selectedBg`,
2235
+ // so their swatches render again; the text side stays on the `text` foreground
2236
+ // token, which the same themes answer. A theme that throws for either, or
2237
+ // answers a non-string, still throws here and both surfaces paint
2238
+ // `Preview unavailable`.
2228
2239
  function themePreviewFactory(ctx) {
2229
2240
  const getTheme = ctx?.ui?.getTheme;
2230
2241
  if (typeof getTheme !== "function") return null;
@@ -2239,13 +2250,19 @@ function themePreviewFactory(ctx) {
2239
2250
  if (typeof theme.name === "string" && theme.name !== name) {
2240
2251
  throw new Error(`Theme ${name} is unavailable.`);
2241
2252
  }
2242
- const accent = typeof theme.getBgAnsi === "function" ? theme.getBgAnsi("accent") : undefined;
2253
+ const background = typeof theme.getBgAnsi === "function" ? theme.getBgAnsi("selectedBg") : undefined;
2243
2254
  const text = typeof theme.getFgAnsi === "function" ? theme.getFgAnsi("text") : undefined;
2244
- if (typeof accent !== "string" || typeof text !== "string") {
2255
+ if (typeof background !== "string" || typeof text !== "string") {
2245
2256
  throw new Error(`Theme ${name} exposes no palette escapes.`);
2246
2257
  }
2247
- // The upstream sample: a background block then the sample text.
2248
- return { title: "source palette", sample: `${accent} \x1b[0m ${text}Aa sample text\x1b[0m` };
2258
+ // The upstream sample: a background block then the sample text. The words are
2259
+ // painted OVER the theme's own background — no reset between the chip and
2260
+ // them — because that is the pairing every theme is designed to keep
2261
+ // readable. A reset there dropped the words onto the user's AMBIENT terminal
2262
+ // background (the verifier measured 1.62:1 for `light` on a #141414 terminal
2263
+ // and 1.22:1 for `dark` on #fafafa). `system` keeps working: its `selectedBg`
2264
+ // is the terminal's default background and its `text` the default foreground.
2265
+ return { title: "source palette", sample: `${background} ${text}Aa sample text\x1b[0m` };
2249
2266
  };
2250
2267
  }
2251
2268
 
@@ -2945,7 +2962,7 @@ async function runCustomizeFallback(ctx) {
2945
2962
  : (moshiFlagEnabled(moshiFlagPath()) ? "on" : "off");
2946
2963
  let choice = null;
2947
2964
  try {
2948
- choice = await select(`${picked} (currently ${current})`, [CUSTOMIZE_ON, CUSTOMIZE_OFF]);
2965
+ choice = await select(`${picked} (currently ${current})`, [CUSTOMIZE_OFF, CUSTOMIZE_ON]);
2949
2966
  } catch {
2950
2967
  choice = undefined;
2951
2968
  }
@@ -55,14 +55,6 @@ function openLib() {
55
55
  return libRequire("herdr-session-open.js");
56
56
  }
57
57
 
58
- function notifyLib() {
59
- try {
60
- return libRequire("herdr-session-notifications.js");
61
- } catch {
62
- return null;
63
- }
64
- }
65
-
66
58
  // The herdr binary. Resolving it can THROW on purpose: under a test harness a
67
59
  // possible live binary is refused instead of being spawned (the guard lives in
68
60
  // lib/herdr-session-open.js, so no fallback here may re-decide it).
@@ -92,7 +84,7 @@ function errorResult(text, details) {
92
84
 
93
85
  // Core of the tool. Exported so a test can drive it with a live-shaped context;
94
86
  // the registered tool calls it with the Pi context it was given.
95
- async function executeSessionOpen(params, ctx, watcherOptions) {
87
+ async function executeSessionOpen(params, ctx) {
96
88
  const lib = openLib();
97
89
  const cwd = toolCwd(ctx);
98
90
 
@@ -107,7 +99,6 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
107
99
  const rawName = nameProvided
108
100
  ? typeof params.name === "string" ? params.name : String(params.name)
109
101
  : undefined;
110
- const notify = !(params && params.notify === false);
111
102
  if (typeof rawPath !== "string" || rawPath.length === 0) {
112
103
  return errorResult(
113
104
  "herdr_session_open requires a path: pass an existing directory (a Git worktree, a repository checkout, or any directory)",
@@ -368,7 +359,7 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
368
359
  const details = {
369
360
  path: target, kind: openedKind, branch,
370
361
  ...(fallbackCode === null ? {} : { fallback: fallbackCode }),
371
- paneId, workspaceId, sessionId, resumed, agentName, notify,
362
+ paneId, workspaceId, sessionId, resumed, agentName,
372
363
  };
373
364
  if (started.status !== 0) {
374
365
  const createdNote = openedHere
@@ -379,35 +370,18 @@ async function executeSessionOpen(params, ctx, watcherOptions) {
379
370
  details,
380
371
  );
381
372
  }
382
- const result = textResult(lib.sessionOpenRows(details).join("\n"), details, false);
383
- // Subscribing IS opening with `notify !== false`: one watcher for the pane
384
- // just opened, `notify: false` starts none. The watcher needs the host message
385
- // route; without it nothing is watched.
386
- const notifications = notifyLib();
387
- if (notify && notifications && typeof notifications.startAgentSessionWatcher === "function") {
388
- try {
389
- notifications.startAgentSessionWatcher(
390
- {
391
- paneId, path: target, kind: openedKind, branch, sessionId,
392
- agentName, workspaceId, repoRoot: target,
393
- },
394
- watcherOptions,
395
- );
396
- } catch {}
397
- }
398
- return result;
373
+ return textResult(lib.sessionOpenRows(details).join("\n"), details, false);
399
374
  }
400
375
 
401
376
  const sessionOpenTool = defineTool({
402
377
  name: TOOL_NAME,
403
378
  label: "Herdr Session Open",
404
379
  exposure: "codemode",
405
- description: "Open a Herdr panel running a Pi session at a path: a linked Git worktree opens as a worktree panel, a repository's primary checkout or any other directory opens as a normal panel. Pass an optional session id to resume; a new session id is minted when resuming is not asked. Unless notify:false is passed, the creator is notified when that session really finishes.",
380
+ description: "Open a Herdr panel running a Pi session at a path: a linked Git worktree opens as a worktree panel, a repository's primary checkout or any other directory opens as a normal panel. Pass an optional session id to resume; a new session id is minted when resuming is not asked. Opening is the whole job: read the session's state with orchestrator_list or the herdr CLI.",
406
381
  parameters: Type.Object({
407
382
  path: Type.String({ description: "Directory to open the panel in (absolute, or relative to the session cwd): a Git worktree, a repository checkout, or any other directory" }),
408
383
  session: opt(Type.String({ description: "Pi session id to resume; absent means a new session" })),
409
384
  name: opt(Type.String({ description: "Agent/pane name; defaults to a name derived from the path (lowercase letters, digits, dash, underscore)" })),
410
- notify: opt(Type.Boolean({ description: "Subscribe the creator to the delegate finish notification (default true)" })),
411
385
  }),
412
386
  async execute(toolCallId, params, signal, onUpdate, ctx) {
413
387
  try {
@@ -424,23 +398,7 @@ const sessionOpenTool = defineTool({
424
398
  });
425
399
 
426
400
  export default function (pi) {
427
- // The delivery route for the finish subscription started by the tool.
428
- const notifications = notifyLib();
429
- if (notifications && typeof notifications.setSessionNotifier === "function") {
430
- try {
431
- notifications.setSessionNotifier(pi);
432
- } catch {}
433
- }
434
401
  pi.registerTool(sessionOpenTool);
435
402
  }
436
403
 
437
- export { executeSessionOpen, sessionOpenTool, clearSessionWatchers };
438
-
439
- // Stop every finish watcher this process started: the test seam for the
440
- // pane-keyed registry, and the shutdown path for a host that wants one.
441
- function clearSessionWatchers() {
442
- const notifications = notifyLib();
443
- if (notifications && typeof notifications.clearSessionWatchers === "function") {
444
- notifications.clearSessionWatchers();
445
- }
446
- }
404
+ export { executeSessionOpen, sessionOpenTool };
@@ -173,9 +173,11 @@ const CUSTOMIZE_OPTION_GAP = " ";
173
173
  // The pointer hint lives in the footer exactly like upstream's `Click · …`.
174
174
  const CUSTOMIZE_CLICK_PREFIX = "Click · ";
175
175
 
176
- // The three settings this package owns, with the upstream order of their two
177
- // options and the static preview each option carries. `id` is the apply target
178
- // the extension knows; it is structural, never the label.
176
+ // The three settings this package owns, with the ONE value order every switch
177
+ // reads — Off on the left, On on the right — and the static preview each option
178
+ // carries (the On sample follows On, whichever side it sits on). `id` is the
179
+ // apply target the extension knows; it is structural, never the label, and no
180
+ // option is ever identified by its position: the ids are always `on` and `off`.
179
181
  const CUSTOMIZE_SIDEBAR_SAMPLE_ON = "● project gentle worker";
180
182
  const CUSTOMIZE_SIDEBAR_SAMPLE_OFF = "native Herdr rows; no managed block";
181
183
  const CUSTOMIZE_MOSHI_SAMPLE_ON = "ask finished";
@@ -188,7 +190,7 @@ const CUSTOMIZE_TOGGLES = Object.freeze({
188
190
  sidebar: {
189
191
  id: "sidebar",
190
192
  setting: "Sidebar agent rows",
191
- order: ["on", "off"],
193
+ order: ["off", "on"],
192
194
  // S5: the sample shows what the managed rows add, from the README's own
193
195
  // description of the heading cell and the role words.
194
196
  preview: (which) => ({
@@ -200,7 +202,7 @@ const CUSTOMIZE_TOGGLES = Object.freeze({
200
202
  moshi: {
201
203
  id: "moshi",
202
204
  setting: "Notifications",
203
- order: ["on", "off"],
205
+ order: ["off", "on"],
204
206
  preview: (which) => ({
205
207
  title: "static notification sample",
206
208
  sample: which === "on" ? CUSTOMIZE_MOSHI_SAMPLE_ON : CUSTOMIZE_MOSHI_SAMPLE_OFF,
@@ -228,7 +230,6 @@ const CUSTOMIZE_THEME_NONE_ID = "none";
228
230
  const CUSTOMIZE_THEME_NONE_LABEL = "None";
229
231
  const CUSTOMIZE_THEME_OPTION_PREFIX = "theme:";
230
232
  const CUSTOMIZE_THEME_UNAVAILABLE_NOTE = "Themes unavailable; use Pi /settings";
231
- const CUSTOMIZE_THEME_DISABLED_NOTE = "Turn Theme sync off to pick a specific theme.";
232
233
  const CUSTOMIZE_THEME_UNKNOWN_NOTE = "state unknown; Enter pins a theme";
233
234
 
234
235
  // The key legend is ONE terminal row: the `key` spelling paints as the key
@@ -449,9 +450,13 @@ function customizeToggleSetting(definition, stored) {
449
450
  }
450
451
 
451
452
  // The one setting that is not a boolean: `None` plus one option per installed
452
- // theme, in Pi's own order. Its options are disabled (still selectable) only
453
- // while the stored sync is on, and an unavailable theme list shows one note
454
- // with no options at all instead of an empty list that looks pickable.
453
+ // theme, in Pi's own order. While the stored sync is on the setting is marked
454
+ // `disabled`, which is how the model says the pinned theme is not available; the
455
+ // PANEL never offers such a setting at all (see `customizeOfferedSettings`), so
456
+ // there is nothing to explain there, while the Gentle Shell page keeps its
457
+ // mounted rows and hides them with `visible()` so the picker returns in place
458
+ // when the sync is turned off. An unavailable theme list shows one note with no
459
+ // options at all instead of an empty list that looks pickable.
455
460
  function customizeThemeSetting(themeState, themeNames, themePreview) {
456
461
  const readable = themeState.ok !== false;
457
462
  const syncOn = readable && themeState.sync === true;
@@ -475,7 +480,6 @@ function customizeThemeSetting(themeState, themeNames, themePreview) {
475
480
  : [];
476
481
  const notes = [];
477
482
  if (!readable) notes.push(CUSTOMIZE_THEME_UNKNOWN_NOTE);
478
- else if (syncOn) notes.push(CUSTOMIZE_THEME_DISABLED_NOTE);
479
483
  if (!listed) notes.push(CUSTOMIZE_THEME_UNAVAILABLE_NOTE);
480
484
  return {
481
485
  id: CUSTOMIZE_THEME_SETTING_ID,
@@ -523,6 +527,19 @@ function customizePanelModel({ sidebar, moshi, theme, themeNames, themePreview }
523
527
  ];
524
528
  }
525
529
 
530
+ // The settings a surface OFFERS: a setting the model marks `disabled` is absent,
531
+ // not dim and not refusing, because the honest answer to "the pinned theme is
532
+ // only available while the sync is off" is to not offer the picker at all — the
533
+ // Gentle Shell page already hides its theme rows that way (`lib/customize-rows.js`
534
+ // `visible()`), and the panel must not offer what the page hides. The model keeps
535
+ // the setting (the page's mounted rows need it to come back in place), so the
536
+ // gate is applied HERE, on every read: the same panel answers a new model after an
537
+ // apply settles, which is how the setting returns without closing and reopening.
538
+ function customizeOfferedSettings(settings) {
539
+ const list = Array.isArray(settings) ? settings : [];
540
+ return list.filter((setting) => !(setting && setting.disabled === true));
541
+ }
542
+
526
543
  /* ---------------------------------------------------------- setting line */
527
544
 
528
545
  // One setting line: the name column, then every option inline. `●` is the
@@ -665,7 +682,7 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model: i
665
682
  };
666
683
  function settings() {
667
684
  const category = state.model[state.cat];
668
- return category && Array.isArray(category.settings) ? category.settings : [];
685
+ return customizeOfferedSettings(category && category.settings);
669
686
  }
670
687
  function settingIndex() {
671
688
  const at = settings().findIndex((entry) => entry.id === state.settingId);
@@ -674,11 +691,17 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model: i
674
691
  function focusedSetting() {
675
692
  return settings()[settingIndex()] || null;
676
693
  }
677
- // A setting is entered on its stored option (upstream `landOn`); an unknown
678
- // state has no stored option, so it enters on the first one.
694
+ // A setting is entered on its stored option (upstream `landOn`). An unknown
695
+ // state has no stored option, and every note that explains an unknown state
696
+ // here promises the same thing — `Enter turns the rows on`, `Enter turns the
697
+ // sync on` — so the fallback is the `on` option BY ID. Position 0 is Off now,
698
+ // and landing there would make the panel's own note a lie.
679
699
  function landOn(setting) {
680
- const at = setting && Array.isArray(setting.options) ? setting.options.findIndex((option) => option.current === true) : -1;
681
- return at < 0 ? 0 : at;
700
+ const options = setting && Array.isArray(setting.options) ? setting.options : [];
701
+ const current = options.findIndex((option) => option.current === true);
702
+ if (current >= 0) return current;
703
+ const on = options.findIndex((option) => option.id === "on");
704
+ return on >= 0 ? on : 0;
682
705
  }
683
706
  function cursorIndex(setting) {
684
707
  if (!setting || !Array.isArray(setting.options)) return 0;
@@ -766,7 +789,7 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model: i
766
789
  const chrome = 1 + (showHeading ? 2 : 0) + (showTopGap ? 1 : 0) + (showBottomGap ? 1 : 0);
767
790
  const contentHeight = Math.max(1, height - 2 - chrome - previewLines);
768
791
  const category = state.model[state.cat] || { id: null, title: "Settings", settings: [] };
769
- const entries = category.settings || [];
792
+ const entries = customizeOfferedSettings(category.settings);
770
793
  const focusedAt = settingIndex();
771
794
  // Right pane rows: one line per setting plus, when the state cannot name a
772
795
  // value, one muted note under it.
@@ -780,9 +803,15 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model: i
780
803
  const listLength = navOnly ? state.model.length : rightLines.length;
781
804
  const start = Math.min(Math.max(0, position - contentHeight + 1), Math.max(0, listLength - contentHeight));
782
805
  const navStart = Math.min(Math.max(0, state.cat - contentHeight + 1), Math.max(0, state.model.length - contentHeight));
806
+ // The label column is sized from the category's FULL setting set, offered or
807
+ // not (D2): a setting the theme gate withholds must not move the values of
808
+ // the settings that remain. The column is a property of the category, not of
809
+ // what happens to be offered in this frame — with the sync off the widest
810
+ // label is `Gentle Shell theme`, and the same width is kept when it is gone.
811
+ const allSettings = Array.isArray(category.settings) ? category.settings : [];
783
812
  const nameWidth = Math.min(
784
813
  20,
785
- entries.reduce((need, setting) => Math.max(need, customizeMeasure(helpers, setting.setting)), 0),
814
+ allSettings.reduce((need, setting) => Math.max(need, customizeMeasure(helpers, setting.setting)), 0),
786
815
  );
787
816
  const paintCell = (text, size, kind) => customizePaint(helpers, theme, kind, text, size);
788
817
  const compose = (segments, size) => customizeCompose(helpers, theme, segments, size);
@@ -234,11 +234,23 @@ function valueText(option, optionId) {
234
234
  return optionId;
235
235
  }
236
236
 
237
- // S6's swatch, resolved from the model's optional preview source: the model may
238
- // carry the read-only `{ title, sample }` pair or the factory that produces it.
239
- // Anything unreadable — a throw, a missing source, a pair of the wrong shape —
240
- // answers `undefined`, which the host paints as `Preview unavailable` instead of
241
- // the row ever breaking.
237
+ // S6's swatch and every static sample: resolved from the model's optional
238
+ // preview source, so the page paints what the panel paints without carrying a
239
+ // copy of one text. The model may carry the read-only `{ title, sample }` pair or
240
+ // the factory that produces it. Anything unreadable — a throw, a missing source,
241
+ // a pair of the wrong shape — answers `undefined`, which the host paints as
242
+ // `Preview unavailable` instead of the row ever breaking.
243
+ //
244
+ // The panel's per-setting `note` (an unreadable state, a theme catalogue Pi
245
+ // cannot list) rides HERE, live, as the tail of the preview title — never as
246
+ // `choice.hint`. The host gives a hint precedence over the preview title
247
+ // (`lib/visual-customize-view.ts:745`), and the bridge types `hint` as a plain
248
+ // string that cannot be re-read, so a hint taken at build time could outlive the
249
+ // state it describes: after the user repaired an unreadable store by turning the
250
+ // sync on, the mounted row still read `Theme sync — state unknown; Enter turns
251
+ // the sync on` and hid the correct sample. A note inside the preview title is
252
+ // re-read with the rest of the snapshot, so the row can never print a fact that
253
+ // is no longer true — and the title keeps naming the sample while it does.
242
254
  function optionPreview(rows, settingId, optionId) {
243
255
  const option = findOption(rows, settingId, optionId);
244
256
  if (!option) return undefined;
@@ -253,7 +265,9 @@ function optionPreview(rows, settingId, optionId) {
253
265
  if (!value || typeof value !== "object") return undefined;
254
266
  const { title, sample } = value;
255
267
  if (typeof title !== "string" || typeof sample !== "string") return undefined;
256
- return { title, sample };
268
+ const setting = findSetting(rows, settingId);
269
+ const note = setting && typeof setting.note === "string" ? setting.note : "";
270
+ return note.length > 0 ? { title: `${title} · ${note}`, sample } : { title, sample };
257
271
  }
258
272
 
259
273
  // The one write a row can cause. `apply` is the extension's injected async
@@ -274,7 +288,8 @@ async function dispatch(cache, apply, settingId, optionId) {
274
288
  }
275
289
 
276
290
  function toggleRow(cache, apply, setting, optionId) {
277
- const option = findOption(cache.read(), setting.id, optionId);
291
+ const snapshot = cache.read();
292
+ const option = findOption(snapshot, setting.id, optionId);
278
293
  const text = valueText(option, optionId);
279
294
  return {
280
295
  category: CUSTOMIZE_ROWS_CATEGORY,
@@ -283,11 +298,19 @@ function toggleRow(cache, apply, setting, optionId) {
283
298
  choice: {
284
299
  // The line's NAME, shared by every value of this setting, so the host
285
300
  // draws one line and ←/→ walks its values (Enter applies: the bridge
286
- // stages `applyOnMove: false` on every row it contributes).
301
+ // stages `applyOnMove: false` on every row it contributes). No `hint`: it
302
+ // would be a build-time string the host prefers over the live preview.
287
303
  setting: setting.line,
288
304
  value: text,
289
305
  current: () => isCurrent(cache.read(), setting.id, optionId),
290
306
  },
307
+ // The SAME title and sample the panel paints for this setting and value: the
308
+ // page reads the model's preview source (`lib/customize-panel.js` owns the
309
+ // texts through `CUSTOMIZE_SIDEBAR_SAMPLE_*`, `CUSTOMIZE_MOSHI_SAMPLE_*`,
310
+ // `CUSTOMIZE_SYNC_SAMPLE_*` and `CUSTOMIZE_THEME_NONE_SAMPLE`) instead of
311
+ // copying a single line of it, and it is re-read, so the sample follows the
312
+ // grown state without a rebuild.
313
+ preview: () => optionPreview(cache.read(), setting.id, optionId),
291
314
  action: () => dispatch(cache, apply, setting.id, optionId),
292
315
  };
293
316
  }
@@ -315,7 +338,8 @@ function unassignText(rows) {
315
338
  }
316
339
 
317
340
  function themeRow(cache, apply, optionId, index, noneText) {
318
- const option = findOption(cache.read(), THEME_SETTING.id, optionId);
341
+ const snapshot = cache.read();
342
+ const option = findOption(snapshot, THEME_SETTING.id, optionId);
319
343
  const isNone = optionId === THEME_NONE_OPTION_ID;
320
344
  const text = isNone ? noneText : valueText(option, optionId);
321
345
  return {
@@ -325,12 +349,15 @@ function themeRow(cache, apply, optionId, index, noneText) {
325
349
  // word at all still gets a legal, distinguishable one — the exact theme is
326
350
  // in the option id either way.
327
351
  label: isNone ? THEME_UNASSIGN_LABEL : (rowName(text) ?? `Theme ${index + 1}`),
352
+ // No `hint`: the picker's unknown-state note rides in the live preview title
353
+ // (see `optionPreview`), so it can never outlive the state it describes.
328
354
  choice: {
329
355
  setting: THEME_SETTING.line,
330
356
  value: text,
331
357
  current: () => isCurrent(cache.read(), THEME_SETTING.id, optionId),
332
358
  },
333
- // The theme's own swatch, read from the model's preview source.
359
+ // The theme's own swatch, read from the model's preview source — the very
360
+ // one the panel draws for the same value.
334
361
  preview: () => optionPreview(cache.read(), THEME_SETTING.id, optionId),
335
362
  // Present while the sync is off, hidden while it is on — and the answer is
336
363
  // re-read on every repaint, so turning the sync on hides the picker on the
@@ -296,12 +296,16 @@ function agentNameForPath(target, options = {}) {
296
296
 
297
297
  // Closed union of herdr operations with a per-operation flag allowlist,
298
298
  // mirroring the installed CLI surface (`herdr worktree list|open`,
299
- // `herdr workspace create`, `herdr pane list`, `herdr agent start|get`). Every
299
+ // `herdr workspace create`, `herdr pane list`, `herdr agent start`). Every
300
300
  // value travels as its own argv element because herdr rejects
301
301
  // `--flag=value`. Unknown operations or flags throw, and `--trust-repository`
302
302
  // is absent everywhere: trusting a repository is a human decision this tool
303
303
  // never takes. `--focus` stays out too — panels open with `--no-focus`.
304
304
  //
305
+ // There is no read operation: the opener starts a session and returns, so a
306
+ // session's state is read by the caller with `orchestrator_list` or the herdr
307
+ // CLI itself, never through an allowlist entry kept for a subscription.
308
+ //
305
309
  // `open` accepts `cwd` beside `path` because herdr resolves a worktree against
306
310
  // the repository of the FOCUSED workspace, not against the process cwd
307
311
  // (herdr 0.9.5: `herdr worktree list` reported the focused workspace's repo
@@ -314,7 +318,6 @@ const HERDR_ALLOWLIST = {
314
318
  'workspace-create': ['cwd', 'noFocus'],
315
319
  'pane-list': ['workspace'],
316
320
  'agent-start': ['name', 'kind', 'pane', 'timeout', 'agentArgs'],
317
- 'agent-get': ['target'],
318
321
  };
319
322
 
320
323
  const HERDR_COMMAND = {
@@ -354,11 +357,6 @@ function herdrArgv(operation, params = {}) {
354
357
  }
355
358
  return ['agent', 'start', name, '--kind', kind, '--pane', pane, '--timeout', timeout, '--', ...agentArgs];
356
359
  }
357
- if (operation === 'agent-get') {
358
- const { target } = params;
359
- if (typeof target !== 'string' || target === '') throw new Error('invalid value for herdr agent-get target');
360
- return ['agent', 'get', target];
361
- }
362
360
  const argv = [...HERDR_COMMAND[operation]];
363
361
  for (const key of Object.keys(params)) {
364
362
  const value = params[key];
@@ -676,14 +674,15 @@ function cleanValue(value) {
676
674
  return value.replace(ANSI_PATTERN, '').replace(CONTROL_PATTERN, '').replace(/\s+/g, ' ').trim();
677
675
  }
678
676
 
679
- // The agent-facing result: short `label: value` rows in a stable order, naming
680
- // the panel that was opened and the routing ids a caller needs to reach the
681
- // session it just started.
677
+ // The agent-facing result: the rows the caller can act on, in a stable order —
678
+ // where the session is, which branch it is on, and the id to reach it by. A
679
+ // success IS opened, so there is no `outcome` row, and the workspace/pane ids
680
+ // are routing details the caller never reads: they stay in `details` and in
681
+ // every refusal, where an id is what makes an error actionable.
682
682
  function sessionOpenRows(details) {
683
- const rows = [`outcome: ${details.resumed === true ? 'resumed' : 'opened'}`];
683
+ const rows = [];
684
684
  const target = cleanValue(details.path);
685
685
  if (target.length > 0) rows.push(`path: ${target}`);
686
- rows.push(`panel: ${details.kind === 'worktree' ? 'worktree' : 'normal'}`);
687
686
  // A fallback is never silent: a normal panel created because herdr refused
688
687
  // the worktree says so, and names the error code that made it happen.
689
688
  const fallback = cleanValue(details.fallback);
@@ -692,12 +691,6 @@ function sessionOpenRows(details) {
692
691
  if (branch.length > 0) rows.push(`branch: ${branch}`);
693
692
  const session = cleanValue(details.sessionId);
694
693
  if (session.length > 0) rows.push(`session: ${session}`);
695
- const workspace = cleanValue(details.workspaceId);
696
- if (workspace.length > 0) rows.push(`workspace: ${workspace}`);
697
- const pane = cleanValue(details.paneId);
698
- if (pane.length > 0) rows.push(`pane: ${pane}`);
699
- const agent = cleanValue(details.agentName);
700
- if (agent.length > 0) rows.push(`agent: ${agent}`);
701
694
  return rows;
702
695
  }
703
696
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-gentle-shell",
3
- "version": "1.9.0",
3
+ "version": "2.0.0",
4
4
  "description": "Pi package for Herdr sidebar states: the Pi extension sidecar that publishes session facts as Herdr pane-metadata tokens, the optional Moshi notification channel, and the Pi-side helpers the Herdr Gentle Shell plugin drives.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -1,320 +0,0 @@
1
- 'use strict';
2
- // Finish subscription for `herdr_session_open` (recovered from the
3
- // pre-split extensions/gentle-worktree-tools.ts, S26/T35).
4
- //
5
- // Whoever opens a session subscribes to its real finish: the tool passes
6
- // `notify !== false` and ONE watcher starts for the pane it just opened.
7
- // Watchers live in `SESSION_WATCHERS`, keyed by pane id, and
8
- // `clearSessionWatchers` stops them all so tests can reset the registry.
9
- //
10
- // WHAT it watches: the pane id the tool returns, read with `herdr agent get
11
- // <paneId>`. A missing agent (`agent_not_found`) is the VANISHED signal.
12
- // WHAT a finish is: `agent_status` reading `idle` AFTER that same pane was
13
- // observed `working`. `blocked` means the delegate waits for input and never
14
- // counts as `working`. A delegate that never reports `working` is reported as
15
- // never-started, a vanished pane as vanished, the maximum wait as timed out —
16
- // none of those three claims a finish.
17
- // HOW it polls: a bounded unref'd interval with a launch grace window (the
18
- // delegate is idle right after `agent start`, so a finish inside it is
19
- // impossible) and a maximum wait, all injectable so tests run in
20
- // milliseconds.
21
- // HOW it delivers: `pi.sendMessage({customType, content, display, details},
22
- // {deliverAs: "followUp", triggerTurn: true})`, the route incoming session
23
- // messages already use, because the orchestrator has to act on it.
24
-
25
- const { spawn } = require('node:child_process');
26
- const path = require('node:path');
27
-
28
- const lib = require('./herdr-session-open.js');
29
-
30
- const SESSION_WATCH_DEFAULTS = { intervalMs: 15000, graceMs: 60000, maxWaitMs: 4 * 60 * 60 * 1000 };
31
- const AGENT_GET_TIMEOUT_MS = 10000;
32
-
33
- const SESSION_WATCHERS = new Map();
34
- let sessionNotifyPi = null;
35
-
36
- // The host handle whose `sendMessage` is the delivery route (set once by the
37
- // extension at load, null until then).
38
- function setSessionNotifier(pi) {
39
- sessionNotifyPi = pi && typeof pi.sendMessage === 'function' ? pi : null;
40
- }
41
-
42
- // Explicit options win, then the environment overrides (tests), then the
43
- // production defaults. Non-positive or unparseable values never apply.
44
- function sessionWatchOptions(overrides) {
45
- const pick = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined);
46
- const envPick = (name) => {
47
- const raw = process.env[name];
48
- if (typeof raw !== 'string' || raw.length === 0) return undefined;
49
- const n = Number(raw);
50
- return Number.isFinite(n) && n > 0 ? n : undefined;
51
- };
52
- const src = overrides && typeof overrides === 'object' ? overrides : {};
53
- return {
54
- intervalMs: pick(src.intervalMs) ?? envPick('GENTLE_HERDR_SESSION_WATCH_INTERVAL_MS')
55
- ?? SESSION_WATCH_DEFAULTS.intervalMs,
56
- graceMs: pick(src.graceMs) ?? envPick('GENTLE_HERDR_SESSION_WATCH_GRACE_MS')
57
- ?? SESSION_WATCH_DEFAULTS.graceMs,
58
- maxWaitMs: pick(src.maxWaitMs) ?? envPick('GENTLE_HERDR_SESSION_WATCH_MAX_MS')
59
- ?? SESSION_WATCH_DEFAULTS.maxWaitMs,
60
- };
61
- }
62
-
63
- // One outcome, one text. Only the finished text claims a finish.
64
- function sessionWatchContent(outcome, { path: targetPath, paneId, sessionId, maxWaitMs }) {
65
- switch (outcome) {
66
- case 'finished':
67
- return `herdr session finished: ${targetPath} ${sessionId} in pane ${paneId} is idle after working`;
68
- case 'never-started':
69
- return `herdr session never started: ${targetPath} ${sessionId} in pane ${paneId} went idle without ever reporting working (the published state is another process's view, so "never started" and "never reported anything" are indistinguishable)`;
70
- case 'vanished':
71
- return `herdr session vanished: ${targetPath} ${sessionId} in pane ${paneId} disappeared (agent not found)`;
72
- default:
73
- return `herdr session timed out: ${targetPath} ${sessionId} in pane ${paneId} did not finish within ${maxWaitMs}ms`;
74
- }
75
- }
76
-
77
- // Is this published binding OUR session? The value is the session file this
78
- // plugin reports, named `<timestamp>_<session-id>.jsonl`, so the id is
79
- // compared against the SEGMENT the file names — never the whole name as a
80
- // substring or suffix: `session: "def"` would otherwise match
81
- // `..._abc_def.jsonl` and `session: "."` would match any path. The timestamp
82
- // prefix is stripped only when it has the shape Pi writes, so an id that
83
- // itself contains `_` still matches its own file.
84
- const SESSION_FILE_STEM = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z_/;
85
-
86
- function bindingNamesSession(value, sessionId) {
87
- if (typeof value !== 'string' || value.length === 0) return false;
88
- if (typeof sessionId !== 'string' || sessionId.length === 0) return false;
89
- if (value === sessionId) return true;
90
- const base = path.basename(value);
91
- if (!base.endsWith('.jsonl')) return false;
92
- return base.slice(0, -6).replace(SESSION_FILE_STEM, '') === sessionId;
93
- }
94
-
95
- // Read one `herdr agent get` reply: `{status, vanished, bound, foreign}`.
96
- // `bound` means the pane reports OUR session and `foreign` that it reports a
97
- // different one; both stay false when no binding is available, where the
98
- // published status is all there is. Anything unparseable is neither, so the
99
- // watcher keeps polling to its maximum.
100
- function sessionWatchReading(stdout, sessionId) {
101
- const unreadable = { status: null, vanished: false, bound: false, foreign: false };
102
- let doc = null;
103
- try {
104
- doc = JSON.parse(stdout);
105
- } catch {
106
- return unreadable;
107
- }
108
- if (!doc || typeof doc !== 'object') return unreadable;
109
- const err = doc.error;
110
- if (err && typeof err === 'object' && err.code === 'agent_not_found') {
111
- return { status: null, vanished: true, bound: false, foreign: false };
112
- }
113
- const agent = doc.result && typeof doc.result === 'object' ? doc.result.agent : null;
114
- const boundValue = agent && agent.agent_session && typeof agent.agent_session.value === 'string'
115
- ? agent.agent_session.value
116
- : null;
117
- const bound = bindingNamesSession(boundValue, sessionId);
118
- const foreign = boundValue !== null && !bound;
119
- const status = agent && typeof agent.agent_status === 'string'
120
- ? agent.agent_status
121
- : doc.result && typeof doc.result === 'object' && typeof doc.result.agent_status === 'string'
122
- ? doc.result.agent_status
123
- : typeof doc.agent_status === 'string' ? doc.agent_status : null;
124
- return { status, vanished: false, bound, foreign };
125
- }
126
-
127
- // One non-blocking `herdr agent get <pane>`: a hung daemon must never freeze
128
- // the session that opened the delegate, so the poll is an async child with
129
- // its own kill timer. `null` means "no reading", never a state.
130
- function pollAgentGet(paneId, repoRoot, onDone) {
131
- let child = null;
132
- let settled = false;
133
- let killer = null;
134
- const done = (value) => {
135
- if (settled) return;
136
- settled = true;
137
- if (killer !== null) {
138
- try {
139
- clearTimeout(killer);
140
- } catch {}
141
- }
142
- onDone(value);
143
- };
144
- try {
145
- child = spawn(lib.resolveHerdrBinary(process.env), lib.herdrArgv('agent-get', { target: paneId }), {
146
- cwd: repoRoot,
147
- stdio: ['ignore', 'pipe', 'ignore'],
148
- });
149
- } catch {
150
- done(null);
151
- return;
152
- }
153
- killer = setTimeout(() => {
154
- try {
155
- child.kill('SIGKILL');
156
- } catch {}
157
- done(null);
158
- }, AGENT_GET_TIMEOUT_MS);
159
- if (killer && typeof killer.unref === 'function') {
160
- try {
161
- killer.unref();
162
- } catch {}
163
- }
164
- let out = '';
165
- try {
166
- child.stdout.on('data', (chunk) => {
167
- out += chunk;
168
- });
169
- child.on('error', () => done(null));
170
- child.on('close', () => done(out));
171
- } catch {
172
- done(null);
173
- }
174
- }
175
-
176
- // Start the watcher for one opened pane, replacing any watcher already keyed
177
- // at that pane id. The timer is unref'd so it never holds the process open,
178
- // and cleared with the registry entry the moment an outcome is delivered.
179
- function startAgentSessionWatcher({ paneId, path: targetPath, kind, branch, sessionId, agentName, workspaceId, repoRoot }, options) {
180
- const { intervalMs, graceMs, maxWaitMs } = sessionWatchOptions(options);
181
- const startedAt = Date.now();
182
- let seenWorking = false;
183
- let sawBound = false;
184
- let pendingOutcome = null;
185
- let pendingAt = 0;
186
- let polling = false;
187
- let delivering = false;
188
- const previous = SESSION_WATCHERS.get(paneId);
189
- if (previous) {
190
- try {
191
- clearInterval(previous.timer);
192
- } catch {}
193
- }
194
- const stop = () => {
195
- const record = SESSION_WATCHERS.get(paneId);
196
- if (record && record.timer === timer) SESSION_WATCHERS.delete(paneId);
197
- try {
198
- clearInterval(timer);
199
- } catch {}
200
- };
201
- // Deliver the one outcome. A host whose `sendMessage` throws or rejects
202
- // does not turn the notification into silence: the outcome stays pending
203
- // and is retried on the next tick, bounded by the same maximum wait
204
- // measured from the outcome itself. One send in flight at a time, so a
205
- // promise that settles after the next tick cannot deliver twice.
206
- const attemptDelivery = () => {
207
- if (delivering) return;
208
- const sender = sessionNotifyPi && typeof sessionNotifyPi.sendMessage === 'function' ? sessionNotifyPi : null;
209
- if (!sender) {
210
- stop();
211
- return;
212
- }
213
- const content = sessionWatchContent(pendingOutcome, { path: targetPath, paneId, sessionId, maxWaitMs });
214
- const details = {
215
- path: targetPath, kind, branch, paneId, workspaceId, sessionId, agentName,
216
- outcome: pendingOutcome, seenWorking,
217
- };
218
- const retry = () => {
219
- delivering = false;
220
- if (Date.now() - pendingAt >= maxWaitMs) stop();
221
- };
222
- let sent;
223
- delivering = true;
224
- try {
225
- sent = sender.sendMessage(
226
- { customType: 'herdr-agent-sessions.finished', content, display: true, details },
227
- { deliverAs: 'followUp', triggerTurn: true },
228
- );
229
- } catch {
230
- retry();
231
- return;
232
- }
233
- if (sent && typeof sent.then === 'function') {
234
- Promise.resolve(sent).then(() => {
235
- delivering = false;
236
- stop();
237
- }, retry);
238
- return;
239
- }
240
- delivering = false;
241
- stop();
242
- };
243
- const finish = (outcome) => {
244
- pendingOutcome = outcome;
245
- pendingAt = Date.now();
246
- attemptDelivery();
247
- };
248
- const timer = setInterval(() => {
249
- if (pendingOutcome !== null) {
250
- // A host whose send never settles must not keep the watcher alive past
251
- // its maximum wait: the outcome is dropped, and the timer with it.
252
- if (delivering && Date.now() - pendingAt >= maxWaitMs) {
253
- stop();
254
- return;
255
- }
256
- attemptDelivery();
257
- return;
258
- }
259
- if (polling) return;
260
- polling = true;
261
- pollAgentGet(paneId, repoRoot, (stdout) => {
262
- polling = false;
263
- if (pendingOutcome !== null) return;
264
- const reading = stdout === null
265
- ? { status: null, vanished: false, bound: false, foreign: false }
266
- : sessionWatchReading(stdout, sessionId);
267
- const elapsed = Date.now() - startedAt;
268
- const ours = reading.bound || !reading.foreign;
269
- if (reading.status === 'working' && ours) seenWorking = true;
270
- if (reading.bound) sawBound = true;
271
- // Launch grace: the delegate is idle right after `agent start`, so no
272
- // outcome is concluded inside it. Observations still count: a `working`
273
- // here arms the finish.
274
- if (elapsed < graceMs) return;
275
- if (reading.vanished) {
276
- finish('vanished');
277
- return;
278
- }
279
- // A pane holding a DIFFERENT session is never ours: a finish is only
280
- // ever concluded for the session this tool opened.
281
- if (reading.foreign) {
282
- finish(sawBound ? 'vanished' : 'never-started');
283
- return;
284
- }
285
- if (reading.status === 'idle') {
286
- finish(seenWorking ? 'finished' : 'never-started');
287
- return;
288
- }
289
- // `blocked` is the delegate waiting for input — never a finish — and
290
- // anything unparseable keeps polling to the maximum.
291
- if (elapsed >= maxWaitMs) finish('timed-out');
292
- });
293
- }, intervalMs);
294
- if (timer && typeof timer.unref === 'function') {
295
- try {
296
- timer.unref();
297
- } catch {}
298
- }
299
- SESSION_WATCHERS.set(paneId, { timer, startedAt, paneId, path: targetPath, sessionId });
300
- return timer;
301
- }
302
-
303
- // Stop every watcher and empty the registry.
304
- function clearSessionWatchers() {
305
- for (const record of SESSION_WATCHERS.values()) {
306
- try {
307
- clearInterval(record.timer);
308
- } catch {}
309
- }
310
- SESSION_WATCHERS.clear();
311
- }
312
-
313
- module.exports = {
314
- setSessionNotifier,
315
- startAgentSessionWatcher,
316
- clearSessionWatchers,
317
- sessionWatchOptions,
318
- sessionWatchContent,
319
- sessionWatchReading,
320
- };