herdr-gentle-shell 1.5.2 → 1.6.1
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 +79 -34
- package/README.md +43 -10
- package/docs/diagnostics.md +4 -3
- package/docs/herdr-session-open.md +15 -5
- package/docs/performance-trace.md +2 -1
- package/docs/sidebar-control.md +4 -2
- package/docs/supervision.md +17 -3
- package/extensions/gentle-herdr-state.ts +464 -114
- package/extensions/herdr-session-open.ts +69 -22
- package/lib/gentle-sidebar.js +87 -33
- package/lib/herdr-session-open.js +62 -1
- package/lib/perf-trace.js +83 -13
- package/package.json +1 -1
|
@@ -17,9 +17,19 @@
|
|
|
17
17
|
// Tokens (§4.3):
|
|
18
18
|
// gentle_work_v1 = <hash>:<count>:<expiry>
|
|
19
19
|
// (normative running total — only `running` counts as
|
|
20
|
-
// executing; queued/waiting
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// executing; queued/waiting never count. The total is
|
|
21
|
+
// the UNION of running TaskStore records and the
|
|
22
|
+
// distinct in-flight `subagent_run`/`subagent_continue`
|
|
23
|
+
// launches the store does not list yet, deduplicated so
|
|
24
|
+
// one delegate counts once: a task-mode (synchronous)
|
|
25
|
+
// launch has no record until it returns, so without it
|
|
26
|
+
// two live delegates counted zero. Per agent the union
|
|
27
|
+
// is a MAX (S11b): an announced running record and its
|
|
28
|
+
// own in-flight launch are the same delegate and carry
|
|
29
|
+
// no shared call id, so a record consumes one launch of
|
|
30
|
+
// its own agent. The consumer renders the oldest
|
|
31
|
+
// running role plus this total in parentheses only when
|
|
32
|
+
// above one.)
|
|
23
33
|
// gentle_roles_v1 = CSV of canonical role slugs from TaskRecord.agent
|
|
24
34
|
// (oldest-first by immutable firstSeen, e.g.
|
|
25
35
|
// `worker,explorer` with worker oldest; null /
|
|
@@ -750,15 +760,29 @@ const QUIET_BEAT_LIMIT = 3;
|
|
|
750
760
|
const LOST_SETTLE_BEATS = 2;
|
|
751
761
|
// Synthesized finish signal (DESIGN §4.3, S2/D2). The host never reports
|
|
752
762
|
// `done`, so the producer mints the finish itself: one session-bound
|
|
753
|
-
// `<hash>:<expiry>` token per finish at the settled-and-empty edge
|
|
754
|
-
// the
|
|
755
|
-
//
|
|
756
|
-
//
|
|
757
|
-
//
|
|
758
|
-
//
|
|
759
|
-
//
|
|
760
|
-
// expiry beyond the same ceiling.
|
|
763
|
+
// `<hash>:<expiry>` token per finish at the settled-and-empty edge. Since T3
|
|
764
|
+
// the expiry is the UNSEEN cap, not the visible dwell: the row holds `done`
|
|
765
|
+
// until the human views the pane, then the consumer's own 3 s dwell and
|
|
766
|
+
// `idle`, and a pane nobody looks at recedes at the cap. The producer owns the
|
|
767
|
+
// mint and the cap because it stamps the token; the consumer owns the recede
|
|
768
|
+
// because `focused` rides the snapshot the daemon already reads. The finish
|
|
769
|
+
// signal is never refreshed, so the cap can never be extended.
|
|
761
770
|
const DONE_TOKEN = "gentle_done_v1";
|
|
771
|
+
// Default unseen cap: 15 minutes (S8). It bounds how long a finish can read
|
|
772
|
+
// `done` without the human ever looking at it, so the marker stays an answer
|
|
773
|
+
// to "which finished panes have I not reviewed yet". Overridden through
|
|
774
|
+
// GENTLE_DONE_UNSEEN_CAP_MS, clamped exactly like JOBS_SNAPSHOT_TTL_MS.
|
|
775
|
+
const DONE_UNSEEN_CAP_MS = 900000;
|
|
776
|
+
const DONE_UNSEEN_CAP_MIN_MS = 100;
|
|
777
|
+
export const DONE_UNSEEN_CAP_MAX_MS = 3600000;
|
|
778
|
+
const DONE_UNSEEN_CAP_ENV = "GENTLE_DONE_UNSEEN_CAP_MS";
|
|
779
|
+
// Settle-time pending hold (T9/S12), NOT the finish token's life: one finish
|
|
780
|
+
// spell in which a stranded `subagent_run` keeps the native state non-terminal
|
|
781
|
+
// and the `done` mint withheld, after which the terminal state lands. Its 5 s
|
|
782
|
+
// default is the time the latch waits on a launch result that may never come;
|
|
783
|
+
// the 3 s dwell after the human views a finish lives consumer-side
|
|
784
|
+
// (`DONE_VIEW_DWELL_MS` in herdr-plugin/lib/gentle-tokens.js). Overridden
|
|
785
|
+
// through GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min].
|
|
762
786
|
const DONE_HOLD_MS = 5000;
|
|
763
787
|
const DONE_HOLD_MIN_MS = 1000;
|
|
764
788
|
export const DONE_HOLD_MAX_MS = 300000;
|
|
@@ -948,6 +972,36 @@ export function doneHoldMs(raw = process.env[DONE_HOLD_ENV]) {
|
|
|
948
972
|
return Math.min(DONE_HOLD_MAX_MS, Math.max(DONE_HOLD_MIN_MS, Math.round(parsed)));
|
|
949
973
|
}
|
|
950
974
|
|
|
975
|
+
// S12/T9c: the deadline for one settle-time pending episode. A first raise
|
|
976
|
+
// starts the episode at `now`. A re-settle that adds no launch id to the
|
|
977
|
+
// retained union keeps the deadline exactly, so repeated settles can never
|
|
978
|
+
// extend the latch. One that adds a new in-flight launch may extend it from
|
|
979
|
+
// `now` (new work means the pane is not finished), but the whole episode never
|
|
980
|
+
// runs past the hold ceiling measured from its first raise. `holdMs` is clamped
|
|
981
|
+
// by the same band as doneHoldMs.
|
|
982
|
+
export function settleHoldUntil({ now, held, startedAt, until, added, holdMs }) {
|
|
983
|
+
const raw = Number.isFinite(holdMs) ? holdMs : DONE_HOLD_MS;
|
|
984
|
+
const hold = Math.min(DONE_HOLD_MAX_MS, Math.max(DONE_HOLD_MIN_MS, Math.round(raw)));
|
|
985
|
+
if (!held) return { startedAt: now, until: now + hold };
|
|
986
|
+
if (!added) return { startedAt, until };
|
|
987
|
+
return {
|
|
988
|
+
startedAt,
|
|
989
|
+
until: Math.min(startedAt + DONE_HOLD_MAX_MS, Math.max(until, now + hold)),
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
// Unseen-cap override, the same discipline as jobsSnapshotTtlMs: an absent or
|
|
994
|
+
// unparseable value keeps the 15 min default and anything outside the band is
|
|
995
|
+
// clamped, so a debugging session (or a test that cannot wait 15 minutes) can
|
|
996
|
+
// shorten the cap without ever making the finish token instantly stale.
|
|
997
|
+
export function doneUnseenCapMs(raw = process.env[DONE_UNSEEN_CAP_ENV]) {
|
|
998
|
+
const text = typeof raw === "string" ? raw.trim() : "";
|
|
999
|
+
if (text.length === 0) return DONE_UNSEEN_CAP_MS;
|
|
1000
|
+
const parsed = Number(text);
|
|
1001
|
+
if (!Number.isFinite(parsed)) return DONE_UNSEEN_CAP_MS;
|
|
1002
|
+
return Math.min(DONE_UNSEEN_CAP_MAX_MS, Math.max(DONE_UNSEEN_CAP_MIN_MS, Math.round(parsed)));
|
|
1003
|
+
}
|
|
1004
|
+
|
|
951
1005
|
// Beat cadence override, the same discipline as doneHoldMs: an absent or
|
|
952
1006
|
// unparseable value keeps the 15 s default and anything outside the band is
|
|
953
1007
|
// clamped, so a debugging session (or a test that cannot wait 15 s per beat)
|
|
@@ -1190,9 +1244,10 @@ const NATIVE_MAX_ATTEMPTS = 2;
|
|
|
1190
1244
|
// (ask/choice/question/questionnaire/permission — never
|
|
1191
1245
|
// review/RDD execution, which stays working and silent); working while the
|
|
1192
1246
|
// principal is active OR running/queued delegates exist OR pending launches
|
|
1193
|
-
// exist OR review execution holds
|
|
1247
|
+
// exist OR review execution holds OR a fresh session-owned background job
|
|
1248
|
+
// still runs; idle ONLY on authoritative principal
|
|
1194
1249
|
// settled plus zero running+queued plus zero pending plus no human-wait
|
|
1195
|
-
// prompt and no review execution. The producer never sets `hasError`: native
|
|
1250
|
+
// prompt and no review execution and no live job. The producer never sets `hasError`: native
|
|
1196
1251
|
// `blocked` is what fires the host's NeedsAttention toast and sound, so an
|
|
1197
1252
|
// `error:` label stays sidebar-only and the pane reports `working` while it
|
|
1198
1253
|
// stands. Never infer terminal from child
|
|
@@ -1205,6 +1260,14 @@ const NATIVE_MAX_ATTEMPTS = 2;
|
|
|
1205
1260
|
// host's own live truth (`ctx.isIdle()`), so a missed `agent_settled` cannot
|
|
1206
1261
|
// leave this producer unable to reach `idle` — not when no turn was observed,
|
|
1207
1262
|
// and not when a turn this producer saw start never delivered its settle edge.
|
|
1263
|
+
//
|
|
1264
|
+
// `liveJobCount` closes the disagreement that `restore-done-idle.md` S4 opened
|
|
1265
|
+
// (this document's L3/L4): the display already waited on a live
|
|
1266
|
+
// `bash_background` / `monitor` job while the native state reported `idle`, and
|
|
1267
|
+
// Herdr presents that `idle` as finished (check circle + notification) on a pane
|
|
1268
|
+
// whose row still read pink `gentle`. The input is the freshness-bounded,
|
|
1269
|
+
// session-owned count (`freshRunningJobCount`), so a stale or foreign snapshot
|
|
1270
|
+
// arrives here as 0 and can never block the terminal state (fail OPEN).
|
|
1208
1271
|
export function computeNativeState({
|
|
1209
1272
|
agentActive,
|
|
1210
1273
|
settled,
|
|
@@ -1213,10 +1276,11 @@ export function computeNativeState({
|
|
|
1213
1276
|
askActive,
|
|
1214
1277
|
reviewActive,
|
|
1215
1278
|
hasError,
|
|
1279
|
+
liveJobCount = 0,
|
|
1216
1280
|
}) {
|
|
1217
1281
|
if (hasError) return "blocked";
|
|
1218
1282
|
if (askActive) return "blocked";
|
|
1219
|
-
if (agentActive || activeCount > 0 || pendingCount > 0 || reviewActive) {
|
|
1283
|
+
if (agentActive || activeCount > 0 || pendingCount > 0 || reviewActive || liveJobCount > 0) {
|
|
1220
1284
|
return "working";
|
|
1221
1285
|
}
|
|
1222
1286
|
if (settled && !agentActive && activeCount === 0 && pendingCount === 0 && !askActive && !reviewActive) {
|
|
@@ -1611,9 +1675,23 @@ export async function liveSummarizeRoots(roots) {
|
|
|
1611
1675
|
|
|
1612
1676
|
// Producer state, resolved once for both flag files below. GENTLE_STATUS_STATE_DIR
|
|
1613
1677
|
// (explicit user override) is used as-is; HERDR_PLUGIN_STATE_DIR is
|
|
1614
|
-
// Herdr-injected and changes with the plugin id, so
|
|
1615
|
-
//
|
|
1616
|
-
//
|
|
1678
|
+
// Herdr-injected and changes with the plugin id, so the stored dir wins
|
|
1679
|
+
// whenever it holds any of our files — one stray known file in the injected
|
|
1680
|
+
// dir may never outrank it, because the daemon writes its pidfile into the dir
|
|
1681
|
+
// it resolves and that made the split self-perpetuating.
|
|
1682
|
+
//
|
|
1683
|
+
// S1b: the stored canonical dir is the FINAL fallback. This process never
|
|
1684
|
+
// receives HERDR_PLUGIN_STATE_DIR, so resolving the injected dir on a fresh
|
|
1685
|
+
// install named a directory the daemon never created: the refresh write below
|
|
1686
|
+
// failed and the sidebar fell back to polling. The active-id dir is therefore a
|
|
1687
|
+
// candidate here too, derived from the state home when the variable is absent,
|
|
1688
|
+
// so a legacy install whose live flags sit only there is still found.
|
|
1689
|
+
// Selection order: stored if it holds a known file, else the active-id/injected
|
|
1690
|
+
// dir if it holds one, else stored. An injected path is honoured only when it IS
|
|
1691
|
+
// the directory this package derives for that name under the resolved state home
|
|
1692
|
+
// (S1c): any other basename, and an owned basename under another root, is
|
|
1693
|
+
// ignored, so the daemon and this helper can never be pointed at another
|
|
1694
|
+
// plugin's state or at a second root for the same name.
|
|
1617
1695
|
//
|
|
1618
1696
|
// S15 identity rename: the active plugin lookup id is herdr-gentle-shell, but
|
|
1619
1697
|
// every stored state path keeps the herdr-gentle-agents segment (no migration
|
|
@@ -1624,6 +1702,15 @@ export async function liveSummarizeRoots(roots) {
|
|
|
1624
1702
|
// writes: an upgraded install still carries them, and a family that differs
|
|
1625
1703
|
// between consumers splits the state across both dirs.
|
|
1626
1704
|
const SIDEBAR_STATE_SEGMENT = "herdr-gentle-agents";
|
|
1705
|
+
const SIDEBAR_ACTIVE_PLUGIN_ID = "herdr-gentle-shell";
|
|
1706
|
+
// S1c: an injected path is honoured only when its basename names a directory
|
|
1707
|
+
// this package owns — the active plugin id (what Herdr injects today) or the
|
|
1708
|
+
// stored canonical segment — AND it is the path this package derives for that
|
|
1709
|
+
// name under the resolved state home. Any other path, e.g. a third plugin id or
|
|
1710
|
+
// an owned name under another root, is IGNORED: the daemon receives
|
|
1711
|
+
// HERDR_PLUGIN_STATE_DIR while no producer does, so honouring a directory we do
|
|
1712
|
+
// not own (or the same name under another root) is exactly what splits them.
|
|
1713
|
+
const SIDEBAR_OWNED_DIR_NAMES = [SIDEBAR_ACTIVE_PLUGIN_ID, SIDEBAR_STATE_SEGMENT];
|
|
1627
1714
|
const SIDEBAR_STATE_KNOWN_FILES = [
|
|
1628
1715
|
"gentle-sidebar-mode.json",
|
|
1629
1716
|
"gentle-moshi.json",
|
|
@@ -1635,12 +1722,71 @@ const SIDEBAR_STATE_KNOWN_FILES = [
|
|
|
1635
1722
|
"gentle-plugin-tools.json",
|
|
1636
1723
|
];
|
|
1637
1724
|
|
|
1638
|
-
function
|
|
1725
|
+
function sidebarStatePluginsDir() {
|
|
1639
1726
|
const env = process.env;
|
|
1640
1727
|
const base = env.XDG_STATE_HOME
|
|
1641
1728
|
? join(env.XDG_STATE_HOME, "herdr")
|
|
1642
1729
|
: join(homedir(), ".local", "state", "herdr");
|
|
1643
|
-
return join(base, "plugins"
|
|
1730
|
+
return join(base, "plugins");
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
function sidebarStoredDir() {
|
|
1734
|
+
return join(sidebarStatePluginsDir(), SIDEBAR_STATE_SEGMENT);
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
// Two spellings name the same directory when their canonical forms match.
|
|
1738
|
+
// realpath resolves symlinks but throws for a path that does not exist yet, so
|
|
1739
|
+
// walk up to the deepest existing ancestor and re-append the missing tail: that
|
|
1740
|
+
// keeps a symlinked or relative spelling of the derived dir from being rejected
|
|
1741
|
+
// as a different directory (S1c/T12 compares paths, never raw strings).
|
|
1742
|
+
function sidebarCanonicalDir(dir) {
|
|
1743
|
+
const absolute = resolvePath(dir);
|
|
1744
|
+
const tail = [];
|
|
1745
|
+
let current = absolute;
|
|
1746
|
+
for (;;) {
|
|
1747
|
+
try {
|
|
1748
|
+
const real = fs.realpathSync(current);
|
|
1749
|
+
return tail.length ? join(real, ...tail) : real;
|
|
1750
|
+
} catch {
|
|
1751
|
+
const parent = dirname(current);
|
|
1752
|
+
if (parent === current) return absolute;
|
|
1753
|
+
// Prepended so the missing tail is re-appended in its original order.
|
|
1754
|
+
tail.unshift(pathBasename(current));
|
|
1755
|
+
current = parent;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
// The active plugin id dir: what Herdr injects as HERDR_PLUGIN_STATE_DIR for the
|
|
1761
|
+
// current plugin id, or — because this producer never receives that variable —
|
|
1762
|
+
// the same path derived from the state home. An injected path is only honoured
|
|
1763
|
+
// when it IS the directory this package derives for that name under the resolved
|
|
1764
|
+
// state home; any other basename (S1c) or an owned basename under another root —
|
|
1765
|
+
// the exact split, since the daemon receives the variable and this producer
|
|
1766
|
+
// derives its own — falls back to the derived path.
|
|
1767
|
+
function sidebarActiveDir() {
|
|
1768
|
+
const injected = process.env.HERDR_PLUGIN_STATE_DIR;
|
|
1769
|
+
if (typeof injected === "string" && injected.length > 0) {
|
|
1770
|
+
const name = pathBasename(injected);
|
|
1771
|
+
if (
|
|
1772
|
+
SIDEBAR_OWNED_DIR_NAMES.includes(name) &&
|
|
1773
|
+
sidebarCanonicalDir(injected) === sidebarCanonicalDir(join(sidebarStatePluginsDir(), name))
|
|
1774
|
+
) {
|
|
1775
|
+
return injected;
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
return join(sidebarStatePluginsDir(), SIDEBAR_ACTIVE_PLUGIN_ID);
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
function sidebarDirHasKnownFile(dir) {
|
|
1782
|
+
for (const name of SIDEBAR_STATE_KNOWN_FILES) {
|
|
1783
|
+
try {
|
|
1784
|
+
if (fs.existsSync(join(dir, name))) return true;
|
|
1785
|
+
} catch {
|
|
1786
|
+
// A single unreadable entry never decides; keep scanning.
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
return false;
|
|
1644
1790
|
}
|
|
1645
1791
|
|
|
1646
1792
|
function sidebarEffectiveDir() {
|
|
@@ -1650,35 +1796,17 @@ function sidebarEffectiveDir() {
|
|
|
1650
1796
|
const stored = sidebarStoredDir();
|
|
1651
1797
|
// HEAD parity: an explicit-but-empty (or otherwise invalid non-nullish)
|
|
1652
1798
|
// value ignores every override and uses the stored default. Only an
|
|
1653
|
-
// omitted (null/undefined) explicit falls through to the
|
|
1799
|
+
// omitted (null/undefined) explicit falls through to the active-id dir.
|
|
1654
1800
|
if (explicit !== undefined && explicit !== null) return stored;
|
|
1655
|
-
const
|
|
1656
|
-
if (
|
|
1657
|
-
if (injected === stored) return injected;
|
|
1801
|
+
const active = sidebarActiveDir();
|
|
1802
|
+
if (active === stored) return stored;
|
|
1658
1803
|
try {
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
try {
|
|
1662
|
-
if (fs.existsSync(join(injected, name))) {
|
|
1663
|
-
injectedHas = true;
|
|
1664
|
-
break;
|
|
1665
|
-
}
|
|
1666
|
-
} catch {
|
|
1667
|
-
// A single unreadable entry never decides; keep scanning.
|
|
1668
|
-
}
|
|
1669
|
-
}
|
|
1670
|
-
if (injectedHas) return injected;
|
|
1671
|
-
for (const name of SIDEBAR_STATE_KNOWN_FILES) {
|
|
1672
|
-
try {
|
|
1673
|
-
if (fs.existsSync(join(stored, name))) return stored;
|
|
1674
|
-
} catch {
|
|
1675
|
-
// A single unreadable entry never decides; keep scanning.
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1804
|
+
if (sidebarDirHasKnownFile(stored)) return stored;
|
|
1805
|
+
if (sidebarDirHasKnownFile(active)) return active;
|
|
1678
1806
|
} catch {
|
|
1679
|
-
// Fall through to the
|
|
1807
|
+
// Fall through to the stored canonical dir on unexpected failure.
|
|
1680
1808
|
}
|
|
1681
|
-
return
|
|
1809
|
+
return stored;
|
|
1682
1810
|
}
|
|
1683
1811
|
|
|
1684
1812
|
// Status-refresh request file, owned by the consumer daemon: a single
|
|
@@ -2633,16 +2761,18 @@ export default function (pi) {
|
|
|
2633
2761
|
// exactly the entries whose status is running|queued. Gentle Shell owns
|
|
2634
2762
|
// lifecycle/status truth: no local age/staleness timeout is applied.
|
|
2635
2763
|
// pendingCalls holds label correlation state for a later
|
|
2636
|
-
// gentleAgents.taskId result plus
|
|
2637
|
-
//
|
|
2638
|
-
// flight
|
|
2764
|
+
// gentleAgents.taskId result plus the in-flight launch evidence: its own
|
|
2765
|
+
// contribution to the consolidated `(n)` count (a task-mode `subagent_run`
|
|
2766
|
+
// stays in flight with no TaskStore record until tool_result, so the record
|
|
2767
|
+
// set alone undercounts it) and a role-only display hint (exact pending
|
|
2768
|
+
// subagent agent -> gentle_roles_v1 slug). Task-mode `subagent_run` stays
|
|
2639
2769
|
// in flight with no TaskStore record until tool_result, so without the
|
|
2640
2770
|
// hint the active role would be invisible and the sidebar would show
|
|
2641
2771
|
// generic `working` during execution.
|
|
2642
2772
|
// Finished/failed/cancelled/waiting entries may linger in the map but
|
|
2643
2773
|
// never count; the map is cleared only on session reset (plus the
|
|
2644
2774
|
// bounded-map guard) — never by a local staleness timeout.
|
|
2645
|
-
const pendingCalls = new Map(); // toolCallId -> { agent, label, at }; agent/label are undefined when no agent is resolvable
|
|
2775
|
+
const pendingCalls = new Map(); // toolCallId -> { agent, label, at, taskId?, cancelled? }; agent/label are undefined when no agent is resolvable
|
|
2646
2776
|
const tasks = new Map(); // taskId -> { agent, label, status, at }
|
|
2647
2777
|
|
|
2648
2778
|
// Blocker legs. ask combines choice + native questionnaire + legacy
|
|
@@ -2909,23 +3039,42 @@ export default function (pi) {
|
|
|
2909
3039
|
// beat arriving mid-send is describing.
|
|
2910
3040
|
let nativeSending = null;
|
|
2911
3041
|
let nativeLastOk = undefined;
|
|
2912
|
-
// T2
|
|
2913
|
-
//
|
|
2914
|
-
//
|
|
2915
|
-
//
|
|
2916
|
-
//
|
|
2917
|
-
// never
|
|
2918
|
-
//
|
|
2919
|
-
//
|
|
2920
|
-
//
|
|
3042
|
+
// T2/S12 terminal guard: agent_settled clears the metadata pending-launch
|
|
3043
|
+
// hint below, but a settle that observes in-flight launches retains pending
|
|
3044
|
+
// evidence here so the terminal state stays held until those launches
|
|
3045
|
+
// resolve. It gates BOTH sides — the native report (via `pendingCount`) and
|
|
3046
|
+
// the display (`done` mint and the `orchestrating` marker) — so a stranded
|
|
3047
|
+
// launch can never leave the row reading `done` beside a native `working`.
|
|
3048
|
+
// Metadata/tasks untouched; the guard clears when the union of the episode's
|
|
3049
|
+
// unresolved launches is empty, on agent_start, with the session, and — when
|
|
3050
|
+
// a launch never reports back — at `nativeSettledPendingUntil`, the
|
|
3051
|
+
// finish-hold deadline of the settle that raised it. Past that hold the
|
|
3052
|
+
// evidence stops counting and the expiry beat below lands the terminal state,
|
|
3053
|
+
// so a lost launch result can never pin the report at `working` for good
|
|
3054
|
+
// (seq itself never resets).
|
|
2921
3055
|
let nativeSettledPending = false;
|
|
2922
3056
|
let nativeSettledPendingUntil = 0;
|
|
2923
|
-
//
|
|
3057
|
+
// When the episode's hold was first raised. The episode ceiling is measured
|
|
3058
|
+
// from here, so repeated re-settles can extend up to it but never past it.
|
|
3059
|
+
let nativeSettledPendingStartedAt = 0;
|
|
3060
|
+
// The exact launches the settling turn left in flight. A result retires only
|
|
3061
|
+
// its own id; a later settle ADDS to this union instead of replacing it, and
|
|
3062
|
+
// the hold stands until the union is empty, so one early result can never
|
|
3063
|
+
// release evidence another launch still owes.
|
|
3064
|
+
let nativeSettledPendingCalls = new Set();
|
|
3065
|
+
// One timer at that deadline, the same discipline as `armJobsExpiry`: the
|
|
3066
|
+
// hold has no other edge behind it, so without this beat neither the native
|
|
3067
|
+
// `idle` nor the `done` mint would ever land. One beat is enough — from that
|
|
3068
|
+
// instant the evidence is zero, so the beat either reports the terminal
|
|
3069
|
+
// state or the real activity that still holds it. Never a poll: a launch
|
|
3070
|
+
// resolution, `agent_start`, and the session reset drop it.
|
|
3071
|
+
let settledPendingExpiryTimer;
|
|
3072
|
+
// Finish episode (S2/T3): minted once at the settled-and-empty edge so the
|
|
2924
3073
|
// row reads `done`, then republished unchanged (never refreshed) until the
|
|
2925
|
-
//
|
|
2926
|
-
// that actually delivers the token (S3), and `sawActivity` remembers
|
|
2927
|
-
// the session did work, so a session that never ran a turn stays idle.
|
|
2928
|
-
// three clear with the session and the moment any work reappears.
|
|
3074
|
+
// unseen cap expires. `donePending` carries the unannounced finish to the
|
|
3075
|
+
// beat that actually delivers the token (S3), and `sawActivity` remembers
|
|
3076
|
+
// that the session did work, so a session that never ran a turn stays idle.
|
|
3077
|
+
// All three clear with the session and the moment any work reappears.
|
|
2929
3078
|
let doneExpiry;
|
|
2930
3079
|
let donePending = false;
|
|
2931
3080
|
let sawActivity = false;
|
|
@@ -2956,14 +3105,47 @@ export default function (pi) {
|
|
|
2956
3105
|
function clearSettledPending() {
|
|
2957
3106
|
nativeSettledPending = false;
|
|
2958
3107
|
nativeSettledPendingUntil = 0;
|
|
3108
|
+
nativeSettledPendingStartedAt = 0;
|
|
3109
|
+
nativeSettledPendingCalls.clear();
|
|
3110
|
+
clearSettledPendingExpiry();
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
function clearSettledPendingExpiry() {
|
|
3114
|
+
if (settledPendingExpiryTimer === undefined) return;
|
|
3115
|
+
clearTimeout(settledPendingExpiryTimer);
|
|
3116
|
+
settledPendingExpiryTimer = undefined;
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
function armSettledPendingExpiry(at) {
|
|
3120
|
+
clearSettledPendingExpiry();
|
|
3121
|
+
const delay = Math.max(0, at - Date.now());
|
|
3122
|
+
settledPendingExpiryTimer = setTimeout(() => {
|
|
3123
|
+
settledPendingExpiryTimer = undefined;
|
|
3124
|
+
if (!rootSession) return;
|
|
3125
|
+
schedulePublish();
|
|
3126
|
+
}, delay);
|
|
3127
|
+
if (settledPendingExpiryTimer.unref) settledPendingExpiryTimer.unref();
|
|
2959
3128
|
}
|
|
2960
3129
|
|
|
2961
3130
|
// Past the finish hold of the settle that raised it, the retained pending
|
|
2962
|
-
// evidence stops counting: the hold is the span it exists to cover.
|
|
3131
|
+
// evidence stops counting: the hold is the span it exists to cover. This is
|
|
3132
|
+
// the single condition the native report and the display both gate on.
|
|
2963
3133
|
function settledPendingHeld() {
|
|
2964
3134
|
return nativeSettledPending && Date.now() < nativeSettledPendingUntil;
|
|
2965
3135
|
}
|
|
2966
3136
|
|
|
3137
|
+
// One launch result retires its own evidence. The hold releases — and the
|
|
3138
|
+
// caller must publish on this edge — only when no launch the settle observed
|
|
3139
|
+
// is still unresolved. An id outside the settling set (an earlier launch, or
|
|
3140
|
+
// one started after the settle) never releases the hold.
|
|
3141
|
+
function resolveSettledPending(callId) {
|
|
3142
|
+
if (!settledPendingHeld()) return false;
|
|
3143
|
+
if (typeof callId !== "string" || !nativeSettledPendingCalls.delete(callId)) return false;
|
|
3144
|
+
if (nativeSettledPendingCalls.size > 0) return false;
|
|
3145
|
+
clearSettledPending();
|
|
3146
|
+
return true;
|
|
3147
|
+
}
|
|
3148
|
+
|
|
2967
3149
|
// The settle state `agent_settled` applies, shared with the reconcile below
|
|
2968
3150
|
// so both paths agree on every field except the finish episode.
|
|
2969
3151
|
function applySettled(fromTurn) {
|
|
@@ -3173,13 +3355,11 @@ export default function (pi) {
|
|
|
3173
3355
|
// Authoritative TaskStore projection for liveness/marker coverage:
|
|
3174
3356
|
// every entry whose status is running|queued is active here (T1
|
|
3175
3357
|
// epochs/witness unchanged). Display count/roles use runningSubs()
|
|
3176
|
-
// below (running only).
|
|
3177
|
-
//
|
|
3178
|
-
//
|
|
3179
|
-
//
|
|
3180
|
-
//
|
|
3181
|
-
// The count is normative; role display below is the
|
|
3182
|
-
// only consumer of the pending hint.
|
|
3358
|
+
// below (running only). Finished/failed/cancelled/waiting entries never
|
|
3359
|
+
// count. The consolidated `(n)` count adds the in-flight launch calls the
|
|
3360
|
+
// record set does not list yet (countSubs below, S11): a task-mode
|
|
3361
|
+
// `subagent_run` has no TaskStore record until it returns tool_result, so
|
|
3362
|
+
// the record set alone counted live synchronous delegates as zero.
|
|
3183
3363
|
// Order is oldest-first by immutable firstSeen (fallback at): progress
|
|
3184
3364
|
// reads bump `at` but never move `firstSeen`, so they never reorder.
|
|
3185
3365
|
function activeSubs() {
|
|
@@ -3202,6 +3382,8 @@ export default function (pi) {
|
|
|
3202
3382
|
// T2b display projection: only `running` counts as executing.
|
|
3203
3383
|
// Queued/waiting never count and never supply a role; the total here is
|
|
3204
3384
|
// the consumer's `(n)` suffix source (suffix only when > 1).
|
|
3385
|
+
// This map is the producer's own evidence, so it is authoritative only
|
|
3386
|
+
// when no presence snapshot can be read: displaySubs() below narrows it.
|
|
3205
3387
|
function runningSubs() {
|
|
3206
3388
|
const out = [];
|
|
3207
3389
|
for (const [id, task] of tasks) {
|
|
@@ -3219,18 +3401,108 @@ export default function (pi) {
|
|
|
3219
3401
|
return out;
|
|
3220
3402
|
}
|
|
3221
3403
|
|
|
3404
|
+
// Authoritative display projection for the produced count, role words and
|
|
3405
|
+
// names: the ids a VALID presence snapshot lists running. A local record
|
|
3406
|
+
// the upstream store does not list is not running whatever this map still
|
|
3407
|
+
// says, so a record stranded by an epoch bump after its last witnessed
|
|
3408
|
+
// generation contributes no name, no role and no count, and an idle session
|
|
3409
|
+
// reaches `idle` instead of a stale role word. Fallback (never zero): with
|
|
3410
|
+
// no usable snapshot the local map is the only evidence and stands in full
|
|
3411
|
+
// — zero would flip the consumer's `done` gate and hide real running work.
|
|
3412
|
+
// Pending launch hints are deliberately not narrowed: they exist only while
|
|
3413
|
+
// their own tool call is in flight, and their purpose is a record the store
|
|
3414
|
+
// does not carry yet.
|
|
3415
|
+
function displaySubs(snapshot) {
|
|
3416
|
+
const local = runningSubs();
|
|
3417
|
+
if (!isRecord(snapshot) || !Array.isArray(snapshot.tasks)) return local;
|
|
3418
|
+
const listed = new Set();
|
|
3419
|
+
for (const entry of snapshot.tasks) {
|
|
3420
|
+
if (isRecord(entry) && typeof entry.id === "string" && entry.status === "running") {
|
|
3421
|
+
listed.add(entry.id);
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
return local.filter((sub) => listed.has(sub.id));
|
|
3425
|
+
}
|
|
3426
|
+
|
|
3427
|
+
// Distinct in-flight launch calls the running record set does not already
|
|
3428
|
+
// list (S11): the second half of the `(n)` union. One delegate is one
|
|
3429
|
+
// entry — the map is keyed by call id, so a call counts at most once, and a
|
|
3430
|
+
// call that resumes a task the records already list running (its `taskId`)
|
|
3431
|
+
// is the SAME delegate and adds nothing. A cancelled call is no longer an
|
|
3432
|
+
// executing delegate; it keeps its pending evidence only for the terminal
|
|
3433
|
+
// gate, which is a separate leg.
|
|
3434
|
+
function inFlightLaunchSubs(listed) {
|
|
3435
|
+
const out = [];
|
|
3436
|
+
for (const pending of pendingCalls.values()) {
|
|
3437
|
+
if (pending.cancelled === true) continue;
|
|
3438
|
+
if (pending.taskId !== undefined && listed.has(pending.taskId)) continue;
|
|
3439
|
+
out.push(pending);
|
|
3440
|
+
}
|
|
3441
|
+
out.sort((a, b) => a.at - b.at);
|
|
3442
|
+
return out;
|
|
3443
|
+
}
|
|
3444
|
+
|
|
3445
|
+
// The consolidated `(n)` source (S11/S11b): the UNION of the running
|
|
3446
|
+
// records the presence snapshot confirms and the distinct in-flight launches
|
|
3447
|
+
// the store does not list yet, deduplicated so one delegate is counted once.
|
|
3448
|
+
// In-flight launches are never narrowed by the snapshot: like the role hint,
|
|
3449
|
+
// they exist only while their own call is in flight, which is exactly the
|
|
3450
|
+
// evidence the store cannot carry yet.
|
|
3451
|
+
// S11b: an announced running record and its own in-flight launch are the SAME
|
|
3452
|
+
// delegate and share no call id — a background launch is acked synchronously
|
|
3453
|
+
// while its START may announce the record on the lifecycle channel before
|
|
3454
|
+
// that ack lands, and the announcement carries only the agent. So per agent
|
|
3455
|
+
// the count is max(running records, unbound in-flight launches): a record
|
|
3456
|
+
// consumes one launch of its own agent (oldest first, which max() expresses
|
|
3457
|
+
// without an arbitrary pairing) and never a launch of another agent, while
|
|
3458
|
+
// two launches beside one record stay two delegates (real work is never
|
|
3459
|
+
// hidden). Only KNOWN agents form a group; an entry with no agent is counted
|
|
3460
|
+
// on its own, because identity is the only evidence that two entries are the
|
|
3461
|
+
// same delegate.
|
|
3462
|
+
function countSubs(snapshot) {
|
|
3463
|
+
const running = displaySubs(snapshot);
|
|
3464
|
+
const listed = new Set(running.map((sub) => sub.id));
|
|
3465
|
+
const launches = inFlightLaunchSubs(listed);
|
|
3466
|
+
const groups = new Map(); // known agent -> { records, launches }
|
|
3467
|
+
let unknown = 0;
|
|
3468
|
+
const groupOf = (agent) => {
|
|
3469
|
+
if (typeof agent !== "string" || agent.length === 0) return undefined;
|
|
3470
|
+
let group = groups.get(agent);
|
|
3471
|
+
if (group === undefined) {
|
|
3472
|
+
group = { records: 0, launches: 0 };
|
|
3473
|
+
groups.set(agent, group);
|
|
3474
|
+
}
|
|
3475
|
+
return group;
|
|
3476
|
+
};
|
|
3477
|
+
for (const sub of running) {
|
|
3478
|
+
const group = groupOf(sub.agent);
|
|
3479
|
+
if (group === undefined) unknown += 1;
|
|
3480
|
+
else group.records += 1;
|
|
3481
|
+
}
|
|
3482
|
+
for (const launch of launches) {
|
|
3483
|
+
const group = groupOf(launch.agent);
|
|
3484
|
+
if (group === undefined) unknown += 1;
|
|
3485
|
+
else group.launches += 1;
|
|
3486
|
+
}
|
|
3487
|
+
let total = unknown;
|
|
3488
|
+
for (const group of groups.values()) total += Math.max(group.records, group.launches);
|
|
3489
|
+
return total;
|
|
3490
|
+
}
|
|
3491
|
+
|
|
3222
3492
|
// Role-only hint from in-flight `subagent_run`/`subagent_continue` tool
|
|
3223
3493
|
// calls: task-mode launches stay in flight (no tool_result yet, hence no
|
|
3224
3494
|
// TaskStore record) even though `tool_call` input already carries the
|
|
3225
3495
|
// exact agent name. Publishing that agent's role slug keeps the sidebar
|
|
3226
|
-
// from showing generic `working` during execution.
|
|
3227
|
-
//
|
|
3228
|
-
// is cleared when its tool_result
|
|
3229
|
-
//
|
|
3230
|
-
//
|
|
3496
|
+
// from showing generic `working` during execution. The hint never adds a
|
|
3497
|
+
// name; its count contribution comes from countSubs above, so the hint
|
|
3498
|
+
// itself stays role-only. Each hint is cleared when its tool_result
|
|
3499
|
+
// arrives, the call is cancelled, or the agent settles. The hint carries
|
|
3500
|
+
// the mapped word or the sanitized passthrough slug (unsalvageable names
|
|
3501
|
+
// yield no hint and read gentle).
|
|
3231
3502
|
function pendingRoleSubs() {
|
|
3232
3503
|
const out = [];
|
|
3233
3504
|
for (const pending of pendingCalls.values()) {
|
|
3505
|
+
if (pending.cancelled === true) continue;
|
|
3234
3506
|
if (agentToRole(pending.agent) !== undefined) {
|
|
3235
3507
|
out.push({ agent: pending.agent, label: pending.label, at: pending.at });
|
|
3236
3508
|
}
|
|
@@ -3252,8 +3524,8 @@ export default function (pi) {
|
|
|
3252
3524
|
// Merged role sources, oldest-first by first-seen: authoritative running
|
|
3253
3525
|
// TaskStore subs plus pending role hints. Authoritative entries win on
|
|
3254
3526
|
// duplicates via rolesCsv dedup (first wins = oldest wins).
|
|
3255
|
-
function mergedRoleSubs() {
|
|
3256
|
-
const merged = [...
|
|
3527
|
+
function mergedRoleSubs(subs) {
|
|
3528
|
+
const merged = [...subs, ...pendingRoleSubs()];
|
|
3257
3529
|
merged.sort((a, b) => (a.firstSeen ?? a.at) - (b.firstSeen ?? b.at));
|
|
3258
3530
|
return merged;
|
|
3259
3531
|
}
|
|
@@ -3358,15 +3630,17 @@ export default function (pi) {
|
|
|
3358
3630
|
return parts.join(",");
|
|
3359
3631
|
}
|
|
3360
3632
|
|
|
3361
|
-
function buildTokens() {
|
|
3633
|
+
function buildTokens(snapshot) {
|
|
3362
3634
|
if (!sessionHash) return {};
|
|
3363
3635
|
const expiry = Date.now() + TTL_MS;
|
|
3364
3636
|
// Liveness/marker coverage stays running|queued (T1); the visible
|
|
3365
|
-
// count + roles are running-only (T2b executing set)
|
|
3637
|
+
// count + roles are running-only (T2b executing set) narrowed to the ids
|
|
3638
|
+
// the presence snapshot lists running (displaySubs), plus the distinct
|
|
3639
|
+
// in-flight launches the store does not list yet (countSubs, S11/S11b).
|
|
3366
3640
|
const subs = activeSubs();
|
|
3367
|
-
const running =
|
|
3641
|
+
const running = displaySubs(snapshot);
|
|
3368
3642
|
const tokens = {};
|
|
3369
|
-
const count = String(
|
|
3643
|
+
const count = String(countSubs(snapshot));
|
|
3370
3644
|
if (COUNT_RE.test(count)) tokens.gentle_work_v1 = `${sessionHash}:${count}:${expiry}`;
|
|
3371
3645
|
const csv = namesCsv(running);
|
|
3372
3646
|
// Clear (null) when the authoritative active TaskStore list has no
|
|
@@ -3379,11 +3653,12 @@ export default function (pi) {
|
|
|
3379
3653
|
// §4.3), merged with the in-flight pending role hint: running TaskStore
|
|
3380
3654
|
// roles (oldest-first) plus the exact pending subagent agent while its
|
|
3381
3655
|
// tool call is in flight (task-mode launches have no TaskStore record
|
|
3382
|
-
// yet). The hint is role-only — the count above
|
|
3383
|
-
//
|
|
3384
|
-
//
|
|
3385
|
-
// the consumer's `working`
|
|
3386
|
-
|
|
3656
|
+
// yet). The hint is role-only — the count above adds the in-flight call
|
|
3657
|
+
// itself in countSubs, grouped per agent (S11b) — and is cleared with the
|
|
3658
|
+
// pending call. Null (clear) when no active recognized roles in either
|
|
3659
|
+
// source — unrecognized agents degrade to the consumer's `working`
|
|
3660
|
+
// display.
|
|
3661
|
+
const roles = rolesCsv(mergedRoleSubs(running));
|
|
3387
3662
|
if (roles.length > 0) tokens.gentle_roles_v1 = roles;
|
|
3388
3663
|
else tokens.gentle_roles_v1 = null;
|
|
3389
3664
|
// Clear the retired disclosure token left by older producers.
|
|
@@ -3434,8 +3709,17 @@ export default function (pi) {
|
|
|
3434
3709
|
// fresh marker to the
|
|
3435
3710
|
// `orchestrating` display only when no recognized role is active (below
|
|
3436
3711
|
// attention, terminal `done`, and recognized roles; ahead of main
|
|
3437
|
-
// `working`).
|
|
3438
|
-
|
|
3712
|
+
// `working`). It answers the same held condition as the native report
|
|
3713
|
+
// (S12): while the settle-time pending evidence stands, the row must read
|
|
3714
|
+
// the pink generic wait, never `done` beside a native `working`.
|
|
3715
|
+
if (
|
|
3716
|
+
rootSession &&
|
|
3717
|
+
(agentActive ||
|
|
3718
|
+
subs.length > 0 ||
|
|
3719
|
+
pendingCalls.size > 0 ||
|
|
3720
|
+
freshRunningJobCount() > 0 ||
|
|
3721
|
+
settledPendingHeld())
|
|
3722
|
+
) {
|
|
3439
3723
|
tokens.gentle_orchestrating_v1 = `${sessionHash}:${expiry}`;
|
|
3440
3724
|
} else {
|
|
3441
3725
|
tokens.gentle_orchestrating_v1 = null;
|
|
@@ -3460,19 +3744,26 @@ export default function (pi) {
|
|
|
3460
3744
|
const pending = pendingRole();
|
|
3461
3745
|
if (pending !== undefined) tokens[PENDING_TOKEN] = `${sessionHash}:${pending}:${expiry}`;
|
|
3462
3746
|
else tokens[PENDING_TOKEN] = null;
|
|
3463
|
-
// Synthesized finish signal (S2/D2): minted once at the settled-and-
|
|
3464
|
-
// edge — principal settled with no running/queued delegate, no
|
|
3465
|
-
// launch, no live background job, and no human-wait, review, or
|
|
3466
|
-
// — then republished with the SAME expiry so the
|
|
3467
|
-
// extended.
|
|
3468
|
-
//
|
|
3469
|
-
//
|
|
3470
|
-
//
|
|
3747
|
+
// Synthesized finish signal (S2/D2/T3): minted once at the settled-and-
|
|
3748
|
+
// empty edge — principal settled with no running/queued delegate, no
|
|
3749
|
+
// pending launch, no live background job, and no human-wait, review, or
|
|
3750
|
+
// error leg — then republished with the SAME expiry so the unseen cap can
|
|
3751
|
+
// never be extended. The consumer holds `done` until the pane is viewed
|
|
3752
|
+
// (its own 3 s dwell, then idle) and lets the token expire at the cap when
|
|
3753
|
+
// nobody ever looks. Any work appearing during the episode clears it on
|
|
3754
|
+
// that beat, so the row moves straight back to the role state. A session
|
|
3755
|
+
// that never worked never mints one. A live background job counts as
|
|
3756
|
+
// activity: the finish waits while the session still waits on it.
|
|
3757
|
+
// A stranded settle-time launch is activity too (S12): the same held
|
|
3758
|
+
// condition the native report uses blocks the `done` mint here, so the
|
|
3759
|
+
// display and the native status agree at the settle edge. The settle
|
|
3760
|
+
// hold's expiry releases it through the beat armed at that deadline.
|
|
3471
3761
|
const activity =
|
|
3472
3762
|
agentActive ||
|
|
3473
3763
|
subs.length > 0 ||
|
|
3474
3764
|
pendingCalls.size > 0 ||
|
|
3475
3765
|
freshRunningJobCount() > 0 ||
|
|
3766
|
+
settledPendingHeld() ||
|
|
3476
3767
|
askActiveNow() ||
|
|
3477
3768
|
reviewActive ||
|
|
3478
3769
|
!!errorCode;
|
|
@@ -3482,7 +3773,7 @@ export default function (pi) {
|
|
|
3482
3773
|
donePending = false;
|
|
3483
3774
|
} else if (settled && turnSettled) {
|
|
3484
3775
|
if (doneExpiry === undefined && sawActivity) {
|
|
3485
|
-
doneExpiry = Date.now() +
|
|
3776
|
+
doneExpiry = Date.now() + doneUnseenCapMs();
|
|
3486
3777
|
donePending = true;
|
|
3487
3778
|
sawActivity = false;
|
|
3488
3779
|
}
|
|
@@ -3647,6 +3938,10 @@ export default function (pi) {
|
|
|
3647
3938
|
pendingCount: pendingCalls.size + (settledPendingHeld() ? 1 : 0),
|
|
3648
3939
|
askActive: askActiveNow(),
|
|
3649
3940
|
reviewActive,
|
|
3941
|
+
// S4/S5: the same freshness-bounded job count the display `done` mint
|
|
3942
|
+
// waits on, so a live job can never leave a non-terminal row beside a
|
|
3943
|
+
// terminal native status.
|
|
3944
|
+
liveJobCount: freshRunningJobCount(),
|
|
3650
3945
|
});
|
|
3651
3946
|
if (!state) return undefined;
|
|
3652
3947
|
if (state === "blocked") {
|
|
@@ -3862,9 +4157,10 @@ export default function (pi) {
|
|
|
3862
4157
|
// Host truth first: a settle this producer missed must be visible to both
|
|
3863
4158
|
// the native report and the tokens built below.
|
|
3864
4159
|
reconcileSettled();
|
|
3865
|
-
|
|
4160
|
+
const snapshot = readPresence();
|
|
4161
|
+
reconcilePresence(snapshot);
|
|
3866
4162
|
queueNative();
|
|
3867
|
-
const tokens = buildTokens();
|
|
4163
|
+
const tokens = buildTokens(snapshot);
|
|
3868
4164
|
if (Object.keys(tokens).length === 0) {
|
|
3869
4165
|
maybeStopBeat();
|
|
3870
4166
|
return;
|
|
@@ -3907,6 +4203,17 @@ export default function (pi) {
|
|
|
3907
4203
|
debug("beat", `tokens=${Object.keys(tokens).length} subs=${activeSubs().length}`);
|
|
3908
4204
|
}
|
|
3909
4205
|
|
|
4206
|
+
// One snapshot read per beat, shared by reconciliation and the display
|
|
4207
|
+
// projection, so both legs decide on the same generation.
|
|
4208
|
+
function readPresence() {
|
|
4209
|
+
if (!sessionId) return undefined;
|
|
4210
|
+
try {
|
|
4211
|
+
return readPresenceSnapshot(sessionId, Date.now());
|
|
4212
|
+
} catch {
|
|
4213
|
+
return undefined;
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
|
|
3910
4217
|
// T1 passive presence reconciliation: resolve explicit terminal task
|
|
3911
4218
|
// statuses (and witnessed absence in a newer complete snapshot) from the
|
|
3912
4219
|
// Gentle Shell presence files before building tokens, so delegate
|
|
@@ -3914,14 +4221,7 @@ export default function (pi) {
|
|
|
3914
4221
|
// no timers, no writes, no imported upstream dependencies; any unreadable
|
|
3915
4222
|
// or inapplicable snapshot leaves tasks untouched. Count, TTL, and
|
|
3916
4223
|
// transport semantics below are unchanged.
|
|
3917
|
-
function reconcilePresence() {
|
|
3918
|
-
if (!sessionId) return;
|
|
3919
|
-
let snapshot;
|
|
3920
|
-
try {
|
|
3921
|
-
snapshot = readPresenceSnapshot(sessionId, Date.now());
|
|
3922
|
-
} catch {
|
|
3923
|
-
return;
|
|
3924
|
-
}
|
|
4224
|
+
function reconcilePresence(snapshot) {
|
|
3925
4225
|
if (!snapshot) return;
|
|
3926
4226
|
let applied = [];
|
|
3927
4227
|
try {
|
|
@@ -4197,6 +4497,9 @@ export default function (pi) {
|
|
|
4197
4497
|
// role evidence at all — the pending call still covers the blocking/
|
|
4198
4498
|
// orchestrating marker, but it contributes no role and no name, and it
|
|
4199
4499
|
// must never publish the launch-correlation placeholder as a role word.
|
|
4500
|
+
// The named `task_id` is retained for the count's dedupe (S11): a resume of
|
|
4501
|
+
// a task the records already list running is the same delegate, and a
|
|
4502
|
+
// cancel of that task ends it.
|
|
4200
4503
|
function launchInput(input) {
|
|
4201
4504
|
if (!isRecord(input)) return undefined;
|
|
4202
4505
|
const taskId = typeof input.task_id === "string" ? input.task_id : undefined;
|
|
@@ -4207,7 +4510,11 @@ export default function (pi) {
|
|
|
4207
4510
|
const labelSource =
|
|
4208
4511
|
typeof input.label === "string" && input.label.length > 0 ? input.label : agent;
|
|
4209
4512
|
const label = labelSource === undefined ? undefined : sanitizeLabel(labelSource, labelSource);
|
|
4210
|
-
return {
|
|
4513
|
+
return {
|
|
4514
|
+
agent: agent === undefined ? undefined : truncateChars(agent, MAX_LABEL_CHARS),
|
|
4515
|
+
label,
|
|
4516
|
+
taskId,
|
|
4517
|
+
};
|
|
4211
4518
|
}
|
|
4212
4519
|
|
|
4213
4520
|
pi.on("tool_call", (event) => {
|
|
@@ -4234,11 +4541,23 @@ export default function (pi) {
|
|
|
4234
4541
|
const taskId = isRecord(event.input) ? event.input.task_id : undefined;
|
|
4235
4542
|
if (typeof taskId !== "string") return;
|
|
4236
4543
|
const known = tasks.get(taskId);
|
|
4544
|
+
let changed = false;
|
|
4545
|
+
// A cancelled task's own in-flight launch is no longer an executing
|
|
4546
|
+
// delegate, so it stops counting on this beat (S11: the count
|
|
4547
|
+
// decrements on cancellation). Its pending evidence is NOT dropped: the
|
|
4548
|
+
// pending-call leg still gates the terminal state (S4) and the call's
|
|
4549
|
+
// own result still arrives later.
|
|
4550
|
+
for (const [callId, pending] of pendingCalls) {
|
|
4551
|
+
if (pending.taskId !== taskId || pending.cancelled === true) continue;
|
|
4552
|
+
pendingCalls.set(callId, { ...pending, cancelled: true });
|
|
4553
|
+
changed = true;
|
|
4554
|
+
}
|
|
4237
4555
|
if (known) {
|
|
4238
4556
|
// Progress/cancel bumps recency only; firstSeen never moves (T2b).
|
|
4239
4557
|
tasks.set(taskId, { ...known, status: "cancelled", at: Date.now() });
|
|
4240
|
-
|
|
4558
|
+
changed = true;
|
|
4241
4559
|
}
|
|
4560
|
+
if (changed) schedulePublish();
|
|
4242
4561
|
}
|
|
4243
4562
|
});
|
|
4244
4563
|
|
|
@@ -4261,7 +4580,11 @@ export default function (pi) {
|
|
|
4261
4580
|
// outcome is now covered by the task record (working via activeSubs),
|
|
4262
4581
|
// the error latch (blocked), or genuine emptiness (idle on next beat).
|
|
4263
4582
|
if (event.toolName === "subagent_run" || event.toolName === "subagent_continue") {
|
|
4264
|
-
|
|
4583
|
+
// A launch resolution retires only its own evidence. When it is the LAST
|
|
4584
|
+
// one the settling turn owed, the hold releases and this edge publishes:
|
|
4585
|
+
// a single result while another launch is still unresolved must keep the
|
|
4586
|
+
// native state non-terminal and announce nothing.
|
|
4587
|
+
if (resolveSettledPending(event.toolCallId)) schedulePublish();
|
|
4265
4588
|
}
|
|
4266
4589
|
if (typeof event.toolCallId === "string" ? reviewCalls.delete(event.toolCallId) : false) {
|
|
4267
4590
|
// The ended id was a known acknowledged execution; remaining tracked
|
|
@@ -4473,13 +4796,40 @@ export default function (pi) {
|
|
|
4473
4796
|
retainContext(ctx);
|
|
4474
4797
|
// Retain settle-time pending evidence for native gating before the
|
|
4475
4798
|
// metadata hint clears (see nativeSettledPending above), bounded by the
|
|
4476
|
-
// finish hold this settle opens.
|
|
4477
|
-
|
|
4799
|
+
// finish hold this settle opens. A redundant or later settle of the same
|
|
4800
|
+
// episode must never drop an id an earlier settle still owes: evaluate the
|
|
4801
|
+
// live episode before applySettled clears it, then merge.
|
|
4802
|
+
const pendingAtSettle = [...pendingCalls.keys()];
|
|
4478
4803
|
pendingCalls.clear();
|
|
4804
|
+
const carriedHeld = settledPendingHeld();
|
|
4805
|
+
const carried = carriedHeld ? [...nativeSettledPendingCalls] : [];
|
|
4806
|
+
const carriedUntil = carriedHeld ? nativeSettledPendingUntil : 0;
|
|
4807
|
+
const carriedStart = carriedHeld ? nativeSettledPendingStartedAt : 0;
|
|
4479
4808
|
applySettled(true);
|
|
4480
|
-
|
|
4809
|
+
const union = new Set(carried);
|
|
4810
|
+
let added = false;
|
|
4811
|
+
for (const id of pendingAtSettle) {
|
|
4812
|
+
if (union.has(id)) continue;
|
|
4813
|
+
union.add(id);
|
|
4814
|
+
added = true;
|
|
4815
|
+
}
|
|
4816
|
+
if (union.size > 0) {
|
|
4817
|
+
const next = settleHoldUntil({
|
|
4818
|
+
now: Date.now(),
|
|
4819
|
+
held: carriedHeld,
|
|
4820
|
+
startedAt: carriedStart,
|
|
4821
|
+
until: carriedUntil,
|
|
4822
|
+
added,
|
|
4823
|
+
holdMs: doneHoldMs(),
|
|
4824
|
+
});
|
|
4481
4825
|
nativeSettledPending = true;
|
|
4482
|
-
|
|
4826
|
+
nativeSettledPendingStartedAt = next.startedAt;
|
|
4827
|
+
nativeSettledPendingUntil = next.until;
|
|
4828
|
+
nativeSettledPendingCalls = union;
|
|
4829
|
+
// Nothing else will publish when the last launch resolves or the hold
|
|
4830
|
+
// expires: arm the one beat that lands native `idle` and the single
|
|
4831
|
+
// `done` mint without waiting for an unrelated event.
|
|
4832
|
+
armSettledPendingExpiry(nativeSettledPendingUntil);
|
|
4483
4833
|
}
|
|
4484
4834
|
// S62 turn-end: the working tree may have changed without transcript
|
|
4485
4835
|
// evidence (external/untracked edits), so re-scan before publishing.
|