herdr-gentle-shell 1.2.0 → 1.4.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.
@@ -90,6 +90,17 @@
90
90
  // (single effective label, priority error > ask >
91
91
  // review, edge-triggered so the native counter in
92
92
  // herdr-agent-state.ts stays balanced)
93
+ // gentle_error_v1 = <hash>:<code>:<expiry>
94
+ // (durable run-error signal, session-bound + TTL-fresh
95
+ // like gentle_ask_v1: emitted on every beat while the
96
+ // run-error leg stands, null / clear the beat it
97
+ // releases. It is the sidebar's ONLY error carrier —
98
+ // the native pane report never claims `blocked`, so an
99
+ // error raises no host NeedsAttention toast or sound
100
+ // and sends no phone envelope. The consumer reduces a
101
+ // fresh token to `error` (row word `blocked`) with the
102
+ // same error > ask > review priority the label leg
103
+ // uses, independently of work token presence.)
93
104
  //
94
105
  // Event seams (all in-process; this extension imports nothing from
95
106
  // gentle-shell — DESIGN §10 U6 source pin is unresolved, so the producer is
@@ -178,9 +189,17 @@
178
189
  // as user-facing `rdd` (machine key stays `review`).
179
190
  // Fail-safe: no provider verdicts are
180
191
  // invented; the id is a sanitized correlation id only.
181
- // error : subagent task failed status / subagent tool error /
182
- // repeated own-transport failure. Latched until the next
183
- // agent_start (fresh snapshot), TTL-bounded display.
192
+ // error : the agent run itself stopped on an error (an assistant
193
+ // message whose `stopReason` is `error` — the same
194
+ // signal Pi derives `turn_end.outcome === "error"`
195
+ // from). Never a tool-level failure, never a failed
196
+ // delegate record, never our own transport: those are
197
+ // detected and logged, and change no state. Sidebar-only:
198
+ // the pane keeps reporting native `working` while the
199
+ // label stands, so an error never fires the host's
200
+ // NeedsAttention toast or sound. Released by the next
201
+ // non-error beat (agent_start, any tool activity, or a
202
+ // non-error assistant message), never latched.
184
203
  // changes : SESSION_CHANGE_ENTRY facts mirroring the Gentle Shell
185
204
  // SessionChanges model semantics from the session
186
205
  // transcript (write|edit tool outcomes only, never git
@@ -698,11 +717,13 @@ const BEAT_MS = 15000;
698
717
  // `<hash>:<expiry>` token per finish at the settled-and-empty edge, carrying
699
718
  // the hold as its absolute expiry. The sidebar reads it as `done` while it is
700
719
  // fresh and recedes to `idle` once it expires — the delay IS that expiry, so
701
- // no timer and no extra idle hold exists. The hold defaults to 60 s and is
702
- // overridden through GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min]; the
703
- // consumer rejects any expiry beyond the same ceiling.
720
+ // no timer and no extra idle hold exists. The hold is short on purpose (5 s):
721
+ // it exists to make a finish visible, never to pin a settled row, so `idle`
722
+ // follows the finish within seconds. Overridden through
723
+ // GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min]; the consumer rejects any
724
+ // expiry beyond the same ceiling.
704
725
  const DONE_TOKEN = "gentle_done_v1";
705
- const DONE_HOLD_MS = 60000;
726
+ const DONE_HOLD_MS = 5000;
706
727
  const DONE_HOLD_MIN_MS = 1000;
707
728
  export const DONE_HOLD_MAX_MS = 300000;
708
729
  const DONE_HOLD_ENV = "GENTLE_HERDR_DONE_HOLD_MS";
@@ -717,6 +738,21 @@ const DONE_HOLD_ENV = "GENTLE_HERDR_DONE_HOLD_MS";
717
738
  // minutes is the generous end of the [30 s, 5 min] band: a job longer than this
718
739
  // fails open early, and a missed exit event delays `done` by at most this long.
719
740
  export const JOBS_SNAPSHOT_TTL_MS = 300000;
741
+ const JOBS_TTL_ENV = "GENTLE_HERDR_JOBS_TTL_MS";
742
+ const JOBS_TTL_MIN_MS = 100;
743
+ const JOBS_TTL_MAX_MS = 3600000;
744
+
745
+ // Same discipline as doneHoldMs: an absent or unparseable value keeps the
746
+ // default and anything outside the band is clamped, so a debugging session (or
747
+ // a test that cannot wait five minutes) can shorten the bound without ever
748
+ // making every snapshot instantly stale.
749
+ export function jobsSnapshotTtlMs(raw = process.env[JOBS_TTL_ENV]) {
750
+ const text = typeof raw === "string" ? raw.trim() : "";
751
+ if (text.length === 0) return JOBS_SNAPSHOT_TTL_MS;
752
+ const parsed = Number(text);
753
+ if (!Number.isFinite(parsed)) return JOBS_SNAPSHOT_TTL_MS;
754
+ return Math.min(JOBS_TTL_MAX_MS, Math.max(JOBS_TTL_MIN_MS, Math.round(parsed)));
755
+ }
720
756
  const MAX_TOKENS_PER_REPORT = 16;
721
757
  const MAX_LABEL_CHARS = 64;
722
758
  // Herdr's wire ceiling for a single pane-metadata token value, measured in
@@ -732,7 +768,6 @@ const MAX_LABEL_CHARS = 64;
732
768
  const MAX_TOKEN_BYTES = 512;
733
769
  const MAX_TRACKED_TASKS = 128;
734
770
  const MAX_CHANGE_PATHS = 256;
735
- const TRANSPORT_FAIL_LATCH = 3;
736
771
  const CLI_FALLBACK_TIMEOUT_MS = 2500;
737
772
 
738
773
  const ASK_EVENT = "gentle-pi:ask-user-choice:blocked";
@@ -791,6 +826,13 @@ const ASK_TOKEN = "gentle_ask_v1";
791
826
  // review is active (acknowledged capture/group execution only). Null /
792
827
  // clear the beat the last execution resolves — NO GRACE, no timers.
793
828
  const REVIEW_TOKEN = "gentle_review_v1";
829
+ // Durable run-error token name (DESIGN §4.3): session-bound + TTL-fresh
830
+ // `<hash>:<code>:<expiry>`, emitted on every beat while the run-error leg
831
+ // stands and cleared to null the beat it releases. This is the sidebar's only
832
+ // error carrier: the native report stays `working` while the leg stands, so an
833
+ // error never raises the host's NeedsAttention toast, its sound, or a phone
834
+ // envelope (DESIGN §7).
835
+ const ERROR_TOKEN = "gentle_error_v1";
794
836
  // Principal-only activity marker (DESIGN §4.3): session-bound + TTL-fresh
795
837
  // `<hash>:<expiry>`, emitted while this session's own agent is active and
796
838
  // cleared when it settles. It carries the principal input of
@@ -852,7 +894,7 @@ function utf8Bytes(value) {
852
894
  return Buffer.byteLength(value, "utf8");
853
895
  }
854
896
 
855
- // Finish-hold override: an absent or unparseable value keeps the 60 s
897
+ // Finish-hold override: an absent or unparseable value keeps the 5 s
856
898
  // default, and anything outside the ceiling is clamped, so the producer can
857
899
  // never publish an expiry the consumer reads as foreign.
858
900
  export function doneHoldMs(raw = process.env[DONE_HOLD_ENV]) {
@@ -1077,14 +1119,17 @@ function cliFallback(patch) {
1077
1119
  export const NATIVE_STATES = ["working", "blocked", "idle"];
1078
1120
  const NATIVE_MAX_ATTEMPTS = 2;
1079
1121
 
1080
- // Principal-gated native state (pure, testable): blocked on a real
1081
- // principal-stopped error OR an actual human-wait intervention leg
1122
+ // Principal-gated native state (pure, testable): blocked on the `hasError`
1123
+ // input OR an actual human-wait intervention leg
1082
1124
  // (ask/choice/question/questionnaire/permission — never
1083
1125
  // review/RDD execution, which stays working and silent); working while the
1084
1126
  // principal is active OR running/queued delegates exist OR pending launches
1085
1127
  // exist OR review execution holds; idle ONLY on authoritative principal
1086
1128
  // settled plus zero running+queued plus zero pending plus no human-wait
1087
- // prompt and no review execution. Never infer terminal from child
1129
+ // prompt and no review execution. The producer never sets `hasError`: native
1130
+ // `blocked` is what fires the host's NeedsAttention toast and sound, so an
1131
+ // `error:` label stays sidebar-only and the pane reports `working` while it
1132
+ // stands. Never infer terminal from child
1088
1133
  // completion, timeout, or count0 alone (settled required). Never
1089
1134
  // done/finished (only working|blocked|idle) and never a notification
1090
1135
  // method — the host owns finished text plus toast/sound, and desktop ask
@@ -1565,6 +1610,30 @@ function sidebarEffectiveDir() {
1565
1610
  return injected;
1566
1611
  }
1567
1612
 
1613
+ // Status-refresh request file, owned by the consumer daemon: a single
1614
+ // timestamp that `bin/gentle-status.js --refresh` also writes. Reading it (not
1615
+ // spawning) is the whole point — the daemon loop deletes it and draws one
1616
+ // frame, so N beats in one window collapse into one wake and this extension
1617
+ // never renders a frame, never writes a pidfile, and never starts a second
1618
+ // writer loop (DESIGN §8, §10 U2).
1619
+ const STATUS_REFRESH_FILE = "gentle-status.refresh";
1620
+
1621
+ // Event-synchronized drawing: the daemon CANNOT see a report as it lands — it
1622
+ // polls the Herdr snapshot — so without this request a state change stays
1623
+ // invisible for up to one whole baseline poll, which is the sidebar lag. Every
1624
+ // landed beat therefore requests the daemon's coalesced refresh: the drawing
1625
+ // follows the report, and polling stays pure fallback. Best effort by design:
1626
+ // a missing state dir or a read-only filesystem degrades to polling only.
1627
+ function requestStatusRefresh() {
1628
+ if (!enabled()) return false;
1629
+ try {
1630
+ fs.writeFileSync(join(sidebarEffectiveDir(), STATUS_REFRESH_FILE), String(Date.now()), "utf8");
1631
+ return true;
1632
+ } catch {
1633
+ return false;
1634
+ }
1635
+ }
1636
+
1568
1637
  // Optional Moshi notification mirror (DESIGN §7): one flag file, read per
1569
1638
  // event. The producer extension owns it; the consumer daemon never publishes
1570
1639
  // to Moshi (single emitter). Enabling is the flag plus, while
@@ -1788,16 +1857,20 @@ function moshiSessionIsChild(file) {
1788
1857
  return child;
1789
1858
  }
1790
1859
 
1791
- let moshiFlagCache = { mtimeMs: -1, enabled: false };
1860
+ let moshiFlagCache = { key: "", enabled: false };
1792
1861
 
1793
1862
  function moshiEnabled() {
1794
1863
  const path = moshiFlagPath();
1795
1864
  try {
1796
1865
  const stat = fs.statSync(path);
1797
- if (stat.mtimeMs === moshiFlagCache.mtimeMs) return moshiFlagCache.enabled;
1798
- moshiFlagCache = { mtimeMs: stat.mtimeMs, enabled: moshiFlagEnabled(path) };
1866
+ // Identity, not just mtime: a rewrite that lands inside the same timestamp
1867
+ // tick (or on a coarse or network filesystem) must still flip the gate. A
1868
+ // stale "enabled" is exactly the notification the user asked not to get.
1869
+ const key = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
1870
+ if (key === moshiFlagCache.key) return moshiFlagCache.enabled;
1871
+ moshiFlagCache = { key, enabled: moshiFlagEnabled(path) };
1799
1872
  } catch {
1800
- moshiFlagCache = { mtimeMs: -1, enabled: false };
1873
+ moshiFlagCache = { key: "", enabled: false };
1801
1874
  }
1802
1875
  return moshiFlagCache.enabled;
1803
1876
  }
@@ -1906,6 +1979,11 @@ const CUSTOMIZE_OVERLAY_OPTIONS = {
1906
1979
  overlay: true,
1907
1980
  overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" },
1908
1981
  };
1982
+ // The overlay caps its own box at `maxHeight` of the terminal, so the panel's
1983
+ // row budget is that box and never the whole terminal: a card taller than the
1984
+ // box is clipped by the host, and the pointer would then hit-test rows the user
1985
+ // cannot see (the reported "the switch never changes" bug).
1986
+ const CUSTOMIZE_OVERLAY_MAX_HEIGHT = 0.85;
1909
1987
  let customizeTuiLoader = () => import("@earendil-works/pi-tui");
1910
1988
 
1911
1989
  export function setCustomizeTuiLoader(loader) {
@@ -2423,7 +2501,10 @@ async function executeCustomize(rawArgs, ctx) {
2423
2501
  theme,
2424
2502
  rowsAvailable: () => {
2425
2503
  try {
2426
- return hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2504
+ const rows = hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2505
+ return Number.isFinite(rows)
2506
+ ? Math.floor(rows * CUSTOMIZE_OVERLAY_MAX_HEIGHT)
2507
+ : undefined;
2427
2508
  } catch {
2428
2509
  return undefined;
2429
2510
  }
@@ -2534,10 +2615,37 @@ export default function (pi) {
2534
2615
  // it is never a display state of its own: no job count is published and no
2535
2616
  // `job` token exists to render (odd/tasks/restore-done-idle.md).
2536
2617
  let jobsSnapshot;
2618
+ // One timer per live snapshot, armed for the instant that snapshot goes
2619
+ // stale. The bus is edge-emitted, so a job whose exit snapshot never arrives
2620
+ // would otherwise leave `freshRunningJobCount()` frozen at its last value
2621
+ // with nothing left to publish the settle that follows: no beat, no `done`,
2622
+ // and the row stays on the pink generic `gentle` for good. One beat at the
2623
+ // expiry is enough — from that instant the hint is zero jobs, so the beat
2624
+ // either mints `done` or reports the real activity that still holds it.
2625
+ // Never a poll: a new snapshot replaces the timer, the session reset and
2626
+ // shutdown drop it, and an empty snapshot drops it immediately.
2627
+ let jobsExpiryTimer;
2628
+
2629
+ function clearJobsExpiry() {
2630
+ if (jobsExpiryTimer === undefined) return;
2631
+ clearTimeout(jobsExpiryTimer);
2632
+ jobsExpiryTimer = undefined;
2633
+ }
2634
+
2635
+ function armJobsExpiry(at) {
2636
+ clearJobsExpiry();
2637
+ const delay = Math.max(0, at + jobsSnapshotTtlMs() - Date.now());
2638
+ jobsExpiryTimer = setTimeout(() => {
2639
+ jobsExpiryTimer = undefined;
2640
+ if (!rootSession) return;
2641
+ schedulePublish();
2642
+ }, delay);
2643
+ if (jobsExpiryTimer.unref) jobsExpiryTimer.unref();
2644
+ }
2537
2645
 
2538
2646
  function freshRunningJobCount() {
2539
2647
  if (!jobsSnapshot) return 0;
2540
- if (Date.now() - jobsSnapshot.at > JOBS_SNAPSHOT_TTL_MS) return 0;
2648
+ if (Date.now() - jobsSnapshot.at > jobsSnapshotTtlMs()) return 0;
2541
2649
  const owner = jobsSnapshot.sessionId;
2542
2650
  const mine = sessionId;
2543
2651
  if (
@@ -2560,11 +2668,23 @@ export default function (pi) {
2560
2668
  const jobs = value.snapshot.jobs.filter(
2561
2669
  (entry) => isRecord(entry) && typeof entry.id === "string" && entry.id.length > 0,
2562
2670
  );
2671
+ // Gentle Shell publishes a FINISHED TAIL: a job that already ended stays in
2672
+ // the array carrying `status: "exited" | "stopped" | "failed"` (its
2673
+ // `RunningJobDisplay`, optional so older publishers that list running jobs
2674
+ // only keep validating). Only an entry with NO status is still running.
2675
+ // Counting a tail entry made `activity` true forever: the row stayed on the
2676
+ // pink generic `gentle` and the `done` mint — hence the finish token, the
2677
+ // host `idle` edge and the Finished toast — never happened, on a panel that
2678
+ // read `none running`. Any status, known or not, therefore stops counting.
2679
+ // `jobs` is only read by freshRunningJobCount, so the filter lives here.
2680
+ const live = jobs.filter((entry) => entry.status === undefined);
2563
2681
  jobsSnapshot = {
2564
2682
  sessionId: typeof value.sessionId === "string" ? value.sessionId : undefined,
2565
- jobs,
2683
+ jobs: live,
2566
2684
  at: Date.now(),
2567
2685
  };
2686
+ if (live.length > 0) armJobsExpiry(jobsSnapshot.at);
2687
+ else clearJobsExpiry();
2568
2688
  schedulePublish();
2569
2689
  }
2570
2690
 
@@ -2593,6 +2713,10 @@ export default function (pi) {
2593
2713
 
2594
2714
  function moshiEmit(eventName, extra = {}) {
2595
2715
  if (!rootSession) return;
2716
+ // THE gate for every envelope path: the opt-in flag is required here, on
2717
+ // every path, with no per-event exception. A context captured while the
2718
+ // channel was on is Chat View prefill only — it never authorizes a send.
2719
+ if (!moshiEnabled()) return;
2596
2720
  if (!moshiContext && !moshiEnsureContext()) return;
2597
2721
  const context = moshiContext;
2598
2722
  if (!context) return;
@@ -2615,6 +2739,15 @@ export default function (pi) {
2615
2739
  moshiSendEnvelope(envelope);
2616
2740
  }
2617
2741
 
2742
+ // The notifications name the project, so they must resolve it the way a send
2743
+ // resolves its context — capturing on demand, which also keeps a channel
2744
+ // enabled mid-session from announcing itself as a bare "Gentle".
2745
+ function moshiNotifyProject() {
2746
+ if (!moshiEnabled()) return "Gentle";
2747
+ moshiEnsureContext();
2748
+ return moshiContext?.project ?? "Gentle";
2749
+ }
2750
+
2618
2751
  // Captures on demand and sends the silent carrier once per session, so
2619
2752
  // enabling Moshi mid-session still opens the Chat View row instead of
2620
2753
  // waiting for the next Pi session.
@@ -2645,8 +2778,14 @@ export default function (pi) {
2645
2778
  function syncReviewActive() {
2646
2779
  reviewActive = reviewCalls.size > 0;
2647
2780
  }
2648
- // Error latch: cleared on the next agent_start (fresh snapshot).
2781
+ // Run-error leg: set ONLY when the agent run itself stops on an error, and
2782
+ // released by the next non-error beat (see setRunError/clearRunError). Tool
2783
+ // failures never touch it, so a failed tool can no longer repaint the row.
2649
2784
  let errorCode;
2785
+ const RUN_ERROR = "run-failed";
2786
+ // Tool-level failures are still detected (the reported defect asked for
2787
+ // detection) but are telemetry: a counter plus a debug line, never state.
2788
+ let toolErrors = 0;
2650
2789
  let emittedLabel;
2651
2790
 
2652
2791
  let changes = { files: 0, added: 0, deleted: 0 };
@@ -2748,6 +2887,26 @@ export default function (pi) {
2748
2887
  return undefined;
2749
2888
  }
2750
2889
 
2890
+ // Detection surface for tool-level failures: recorded, never published. The
2891
+ // state they reach (label, native state, finish hold) is untouched by design
2892
+ // — only a run that stops on an error may show `error:`.
2893
+ function recordToolFailure(site) {
2894
+ toolErrors += 1;
2895
+ debug("tool-error", `${site} count=${toolErrors}`);
2896
+ }
2897
+
2898
+ function setRunError() {
2899
+ if (errorCode) return;
2900
+ errorCode = RUN_ERROR;
2901
+ updateBlocker();
2902
+ }
2903
+
2904
+ function clearRunError() {
2905
+ if (!errorCode) return;
2906
+ errorCode = undefined;
2907
+ updateBlocker();
2908
+ }
2909
+
2751
2910
  function ensureAskIntent() {
2752
2911
  if (askActiveNow() && !askIntentId) {
2753
2912
  askCounter += 1;
@@ -2755,14 +2914,16 @@ export default function (pi) {
2755
2914
  // Moshi replacement (DESIGN §7): a real ask episode is the only
2756
2915
  // intervention that reaches the phone — one approval_required per
2757
2916
  // intentId, exactly like the Herdr toast, and never a speculative ask.
2758
- if (moshiContext || moshiEnabled()) {
2917
+ // `moshiContext` alone never authorizes it: the flag gates every send.
2918
+ if (moshiEnabled()) {
2919
+ const project = moshiNotifyProject();
2759
2920
  moshiEmit("PermissionRequest", {
2760
2921
  category: "approval_required",
2761
2922
  phase: "waitingForApproval",
2762
2923
  actionId: askIntentId,
2763
- title: `Gentle ask: ${moshiContext?.project ?? "Gentle"}`,
2924
+ title: `Gentle ask: ${project}`,
2764
2925
  subtitle: "Answer in terminal",
2765
- message: `${moshiContext?.project ?? "Gentle"} has a question and is waiting for your answer. Return to Pi to respond.`,
2926
+ message: `${project} has a question and is waiting for your answer. Return to Pi to respond.`,
2766
2927
  ...(lastAskToolName ? { toolName: lastAskToolName } : {}),
2767
2928
  });
2768
2929
  }
@@ -3015,6 +3176,16 @@ export default function (pi) {
3015
3176
  if (!reviewActive) reviewId = undefined;
3016
3177
  if (reviewActive && reviewId) tokens[REVIEW_TOKEN] = `${sessionHash}:${reviewId}:${expiry}`;
3017
3178
  else tokens[REVIEW_TOKEN] = null;
3179
+ // Durable run-error signal: session-bound + TTL-fresh
3180
+ // `<hash>:<code>:<expiry>`, republished on every beat while the run-error
3181
+ // leg stands (durable, never edge-only, so a missed beat cannot strand the
3182
+ // row) and cleared to null on the beat the leg releases. It is the only
3183
+ // carrier of the error to the sidebar: the native report stays `working`
3184
+ // while it stands, which is what keeps the host from firing a
3185
+ // NeedsAttention toast or sound for it (DESIGN §7). Tool-level failures
3186
+ // never reach this leg (recordToolFailure is telemetry only).
3187
+ if (errorCode) tokens[ERROR_TOKEN] = `${sessionHash}:${errorCode}:${expiry}`;
3188
+ else tokens[ERROR_TOKEN] = null;
3018
3189
  // Root-only orchestrating marker (DESIGN §4.3): session-bound freshness
3019
3190
  // (<hash>:<expiry>, same binding/TTL style as gentle_work_v1, no count)
3020
3191
  // emitted by the root Pi session while the main session is actively
@@ -3122,6 +3293,10 @@ export default function (pi) {
3122
3293
  askToolCalls.size > 0 ||
3123
3294
  uiPromptActive ||
3124
3295
  reviewActive ||
3296
+ // The standing run error keeps a beat alive so its durable token stays
3297
+ // republished (and TTL-fresh) until the leg releases, even after the
3298
+ // session settles.
3299
+ errorCode !== undefined ||
3125
3300
  emittedLabel !== undefined ||
3126
3301
  doneExpiry !== undefined
3127
3302
  );
@@ -3155,15 +3330,22 @@ export default function (pi) {
3155
3330
  // stays consumer-side per DESIGN §7).
3156
3331
  function desiredNativeReport() {
3157
3332
  if (!rootSession) return undefined;
3158
- const state = computeNativeState({
3159
- agentActive,
3160
- settled,
3161
- activeCount: activeSubs().length,
3162
- pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3163
- askActive: askActiveNow(),
3164
- reviewActive,
3165
- hasError: !!errorCode,
3166
- });
3333
+ // `error:` is sidebar-only: native `blocked` is exactly what fires the
3334
+ // host's NeedsAttention toast and sound (DESIGN §7), so an error label
3335
+ // never claims it. While the label stands the pane reports `working` —
3336
+ // the only native state that raises no attention — and returns to the
3337
+ // lifecycle state on the next non-error beat. `hasError` stays out of
3338
+ // computeNativeState for this reason.
3339
+ const state = errorCode
3340
+ ? "working"
3341
+ : computeNativeState({
3342
+ agentActive,
3343
+ settled,
3344
+ activeCount: activeSubs().length,
3345
+ pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3346
+ askActive: askActiveNow(),
3347
+ reviewActive,
3348
+ });
3167
3349
  if (!state) return undefined;
3168
3350
  if (state === "blocked") {
3169
3351
  ensureAskIntent();
@@ -3280,7 +3462,7 @@ export default function (pi) {
3280
3462
  // live jobs — never off a raw native working->idle transition, which fires
3281
3463
  // with work still left and used to skip `done` entirely.
3282
3464
  function emitFinish() {
3283
- const project = moshiContext?.project ?? "Gentle";
3465
+ const project = moshiNotifyProject();
3284
3466
  const lastLabel = lastFinishedLabel(tasks);
3285
3467
  moshiEmit("AgentEnd", {
3286
3468
  category: "task_complete",
@@ -3382,25 +3564,31 @@ export default function (pi) {
3382
3564
  maybeStopBeat();
3383
3565
  return;
3384
3566
  }
3567
+ // The finish notification is a Moshi envelope, not a Herdr token: it hangs
3568
+ // off the minted done edge above, and announcing it here — before, and
3569
+ // regardless of, the token publish — keeps a transport failure from
3570
+ // swallowing it. Cleared with the announcement, so a retried beat can
3571
+ // never duplicate it.
3572
+ if (donePending) {
3573
+ donePending = false;
3574
+ emitFinish();
3575
+ }
3385
3576
  publishInFlight = true;
3386
3577
  try {
3387
3578
  const ok = await sendTokens(tokens);
3388
3579
  if (ok) {
3389
- if (donePending) {
3390
- donePending = false;
3391
- emitFinish();
3392
- }
3393
- if (transportFails >= TRANSPORT_FAIL_LATCH && errorCode === "transport") {
3394
- errorCode = undefined;
3395
- updateBlocker();
3396
- }
3580
+ // One coalesced wake per landed beat, after the tokens are in Herdr
3581
+ // (a request written first could render a frame over stale tokens).
3582
+ requestStatusRefresh();
3583
+ if (transportFails > 0) debug("transport-ok", `after ${transportFails} failed beat(s)`);
3397
3584
  transportFails = 0;
3398
3585
  } else {
3586
+ // Our own report transport failing is not the agent failing: it is a
3587
+ // telemetry line, never an `error:` label and never native `blocked`
3588
+ // (that latched a stuck red row on a socket hiccup and fired the
3589
+ // host's toast for it). The next landed beat resets the counter.
3399
3590
  transportFails += 1;
3400
- if (transportFails >= TRANSPORT_FAIL_LATCH && !errorCode) {
3401
- errorCode = "transport";
3402
- updateBlocker();
3403
- }
3591
+ debug("transport-failed", `${transportFails} beat(s) in a row`);
3404
3592
  }
3405
3593
  } finally {
3406
3594
  publishInFlight = false;
@@ -3437,12 +3625,10 @@ export default function (pi) {
3437
3625
  return;
3438
3626
  }
3439
3627
  if (!Array.isArray(applied) || applied.length === 0) return;
3440
- // An explicitly failed delegate latches the error leg exactly like a
3441
- // failed tool_result/message_end; absence-driven completion carries no
3442
- // known terminal state and never latches.
3443
- if (!errorCode && applied.some((entry) => entry && entry.status === "failed")) {
3444
- errorCode = "task-failed";
3445
- updateBlocker();
3628
+ // A delegate that ended failed is a tool-level outcome, not the run
3629
+ // stopping: detected and counted, and no state changes.
3630
+ if (applied.some((entry) => entry && entry.status === "failed")) {
3631
+ recordToolFailure("presence:failed");
3446
3632
  }
3447
3633
  }
3448
3634
 
@@ -3527,7 +3713,9 @@ export default function (pi) {
3527
3713
  donePending = false;
3528
3714
  sawActivity = false;
3529
3715
  jobsSnapshot = undefined;
3716
+ clearJobsExpiry();
3530
3717
  errorCode = undefined;
3718
+ toolErrors = 0;
3531
3719
  liveGen += 1;
3532
3720
  liveInFlight = false;
3533
3721
  liveQueued = false;
@@ -3701,6 +3889,9 @@ export default function (pi) {
3701
3889
 
3702
3890
  pi.on("tool_call", (event) => {
3703
3891
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3892
+ // A tool starting proves a run is alive: an error left over from a run that
3893
+ // already died is released here rather than sticking until the next turn.
3894
+ clearRunError();
3704
3895
  // Structured ask proposals never open ask (execution does); subagent
3705
3896
  // launch correlation below is unchanged.
3706
3897
  if (event.toolName === "subagent_run" || event.toolName === "subagent_continue") {
@@ -3729,6 +3920,7 @@ export default function (pi) {
3729
3920
 
3730
3921
  pi.on("tool_result", (event) => {
3731
3922
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3923
+ clearRunError();
3732
3924
  if (typeof event.toolCallId === "string" && askToolCalls.delete(event.toolCallId)) {
3733
3925
  updateBlocker();
3734
3926
  }
@@ -3759,10 +3951,9 @@ export default function (pi) {
3759
3951
  }
3760
3952
  const details = isRecord(event.details) ? event.details.gentleAgents : undefined;
3761
3953
  if (!isRecord(details) || typeof details.taskId !== "string") {
3762
- if (event.toolName === "subagent_run" && event.isError === true && !errorCode) {
3763
- errorCode = "task-failed";
3764
- updateBlocker();
3765
- }
3954
+ // A tool that failed is detected and counted, and that is all: no label,
3955
+ // no native state, no finish hold, no notification.
3956
+ if (event.isError === true) recordToolFailure(`tool:${event.toolName}`);
3766
3957
  return;
3767
3958
  }
3768
3959
  const previous = tasks.get(details.taskId);
@@ -3829,10 +4020,7 @@ export default function (pi) {
3829
4020
  const oldest = tasks.keys().next().value;
3830
4021
  tasks.delete(oldest);
3831
4022
  }
3832
- if (status === "failed" && !errorCode) {
3833
- errorCode = "task-failed";
3834
- updateBlocker();
3835
- }
4023
+ if (status === "failed") recordToolFailure(`task:${details.taskId}`);
3836
4024
  schedulePublish();
3837
4025
  });
3838
4026
 
@@ -3851,7 +4039,18 @@ export default function (pi) {
3851
4039
  pi.on("message_end", (event) => {
3852
4040
  if (!rootSession || !isRecord(event)) return;
3853
4041
  const message = event.message;
3854
- if (!isRecord(message) || message.role !== "custom") return;
4042
+ if (!isRecord(message)) return;
4043
+ if (message.role === "assistant") {
4044
+ // The one real error state. Pi derives `turn_end.outcome === "error"`
4045
+ // from exactly this stopReason, so a run that stopped on an error is
4046
+ // visible here without a second handler; any other assistant message
4047
+ // proves the run is alive again (a retry that succeeded) and releases
4048
+ // the label.
4049
+ if (message.stopReason === "error") setRunError();
4050
+ else clearRunError();
4051
+ return;
4052
+ }
4053
+ if (message.role !== "custom") return;
3855
4054
  if (message.customType !== AGENTS_RESULT_TYPE) return;
3856
4055
  const details = isRecord(message.details) ? message.details.gentleAgents : undefined;
3857
4056
  if (!isRecord(details) || typeof details.taskId !== "string") return;
@@ -3879,10 +4078,7 @@ export default function (pi) {
3879
4078
  const oldest = tasks.keys().next().value;
3880
4079
  tasks.delete(oldest);
3881
4080
  }
3882
- if (details.status === "failed" && !errorCode) {
3883
- errorCode = "task-failed";
3884
- updateBlocker();
3885
- }
4081
+ if (details.status === "failed") recordToolFailure(`background:${details.taskId}`);
3886
4082
  schedulePublish();
3887
4083
  });
3888
4084
 
@@ -3927,10 +4123,7 @@ export default function (pi) {
3927
4123
  agentActive = true;
3928
4124
  settled = false;
3929
4125
  nativeSettledPending = false;
3930
- if (errorCode) {
3931
- errorCode = undefined;
3932
- updateBlocker();
3933
- }
4126
+ clearRunError();
3934
4127
  refreshChanges();
3935
4128
  schedulePublish();
3936
4129
  });
@@ -3947,7 +4140,7 @@ export default function (pi) {
3947
4140
  // S62 turn-end: the working tree may have changed without transcript
3948
4141
  // evidence (external/untracked edits), so re-scan before publishing.
3949
4142
  refreshChanges();
3950
- if (activeSubs().length === 0 && !askActiveNow() && !reviewActive) {
4143
+ if (activeSubs().length === 0 && !askActiveNow() && !reviewActive && !errorCode) {
3951
4144
  clearEmittedLabel();
3952
4145
  void publishNow();
3953
4146
  } else {