herdr-gentle-shell 1.9.1 → 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/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
 
@@ -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
@@ -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 };
@@ -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.1",
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
- };