neurastream 0.1.24 → 0.1.26
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 +4 -1
- package/package.json +2 -3
- package/src/adapters/omp/doctor.ts +6 -2
- package/src/adapters/omp/index.ts +3 -3
- package/src/cli/commands.ts +4 -8
- package/src/cli/dispatch.ts +50 -3
- package/src/cli/init.ts +34 -10
- package/src/core/brief-lint.ts +3 -16
- package/src/core/config.ts +24 -2
- package/src/core/file-lock.ts +89 -0
- package/src/core/guards.ts +22 -6
- package/src/core/heavy-run.ts +37 -29
- package/src/core/host.ts +19 -0
- package/src/core/incidents.ts +14 -1
- package/src/core/machine-guard.ts +5 -2
- package/src/core/main-start.ts +4 -1
- package/src/core/queue/lib.ts +21 -1
- package/src/core/queue-close.ts +5 -3
- package/src/core/quota-reset.ts +127 -0
- package/src/core/subagents.ts +83 -0
- package/src/core/tmp-snapshot.ts +26 -14
- package/templates/config.yml +6 -11
- package/templates/help/agent-score.txt +1 -1
- package/templates/help/brief-lint.txt +1 -1
- package/templates/help/wip-check.txt +1 -1
- package/templates/help/wip-snapshot.txt +1 -1
- package/templates/machine-guard.sh +57 -16
- package/templates/tmp-snapshot.sh +13 -7
- package/bin/pm-fail-facts +0 -6
- package/src/adapters/omp/herdr-agent-state.ts +0 -440
- package/src/core/glm-reset.ts +0 -32
- package/src/core/pm-fail-facts.ts +0 -116
- package/templates/help/pm-fail-facts.txt +0 -6
- /package/bin/{glm-reset → quota-reset} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
set -u
|
|
3
|
-
NPROC=$(nproc)
|
|
3
|
+
NPROC=${CORES:-$(nproc)}
|
|
4
4
|
LOAD_MAX=${LOAD_MAX:-$((NPROC + 4))}
|
|
5
5
|
AVAIL_MIN_MB=${AVAIL_MIN_MB:-3072}
|
|
6
6
|
DISK_MIN_GB=${DISK_MIN_GB:-15}
|
|
@@ -9,22 +9,60 @@ IDLE_MAX_MIN=${IDLE_MAX_MIN:-20}
|
|
|
9
9
|
IDLE_STATE=${HEAVY_IDLE_STATE:?}
|
|
10
10
|
LOCK=${HEAVY_LOCK:?}
|
|
11
11
|
DISK_PATH=${DISK_PATH:-$HOME}
|
|
12
|
-
|
|
12
|
+
HEAVY_STATUS=${HEAVY_STATUS:?}
|
|
13
|
+
HEAVY_MAIN=${HEAVY_MAIN:?}
|
|
14
|
+
UNAME=$(uname -s)
|
|
15
|
+
|
|
16
|
+
# Probes. Only these small functions branch on the OS: Linux keeps /proc, GNU df and procps ps;
|
|
17
|
+
# Darwin uses sysctl, vm_stat, df -P, BSD ps and pgrep.
|
|
18
|
+
is_darwin() { [ "$UNAME" = Darwin ]; }
|
|
19
|
+
|
|
20
|
+
load_1() { if is_darwin; then sysctl -n vm.loadavg | tr -d '{}' | awk '{print $1}'; else cut -d' ' -f1 /proc/loadavg; fi; }
|
|
21
|
+
load_3() { if is_darwin; then sysctl -n vm.loadavg | tr -d '{}' | awk '{print $1, $2, $3}'; else cut -d' ' -f1-3 /proc/loadavg; fi; }
|
|
22
|
+
mem_avail() {
|
|
23
|
+
if is_darwin; then
|
|
24
|
+
vm_stat | awk -v s="$(sysctl -n hw.pagesize)" '/Pages (free|inactive|speculative|purgeable):/{gsub(/\./,"",$NF); p+=$NF} END{print int(p*s/1048576)}'
|
|
25
|
+
else
|
|
26
|
+
awk '/MemAvailable/{print int($2/1024)}' /proc/meminfo
|
|
27
|
+
fi
|
|
28
|
+
}
|
|
29
|
+
swap_free() {
|
|
30
|
+
if is_darwin; then
|
|
31
|
+
sysctl -n vm.swapusage | awk '{for (i = 1; i < NF; i++) if ($i == "free" && $(i + 1) == "=") { v = $(i + 2); u = substr(v, length(v)); sub(/[MG]$/, "", v); print int(u == "G" ? v * 1024 : v); exit }}'
|
|
32
|
+
else
|
|
33
|
+
awk '/SwapFree/{print int($2/1024)}' /proc/meminfo
|
|
34
|
+
fi
|
|
35
|
+
}
|
|
36
|
+
home_free() {
|
|
37
|
+
if is_darwin; then df -Pk "$DISK_PATH" | awk 'NR==2{print int($4/1048576)}'
|
|
38
|
+
else df -BG --output=avail "$DISK_PATH" | tail -1 | tr -dc 0-9; fi
|
|
39
|
+
}
|
|
40
|
+
top_rss() { if is_darwin; then ps -Ao rss,etime,args -m; else ps -eo rss,etime,args --sort=-rss; fi; }
|
|
41
|
+
top_cpu() { if is_darwin; then ps -Ao pcpu,etime,args -r; else ps -eo pcpu,etime,args --sort=-pcpu; fi; }
|
|
42
|
+
child_pids() { if is_darwin; then pgrep -P "$1" 2>/dev/null; else ps -o pid= --ppid "$1" 2>/dev/null; fi; }
|
|
43
|
+
# CPU ticks (1/100 s) of one pid; 0 when the process is gone.
|
|
44
|
+
proc_ticks() {
|
|
45
|
+
if is_darwin; then
|
|
46
|
+
ps -o time= -p "$1" 2>/dev/null | awk '{d = 0; t = $1; if (index(t, "-")) { split(t, x, "-"); d = x[1]; t = x[2] } n = split(t, a, ":"); s = 0; for (i = 1; i <= n; i++) s = s * 60 + a[i]; print int((d * 86400 + s) * 100 + 0.5)} END{if (NR == 0) print 0}'
|
|
47
|
+
else
|
|
48
|
+
awk '{sub(/^.*\) /,""); print $12+$13}' "/proc/$1/stat" 2>/dev/null || echo 0
|
|
49
|
+
fi
|
|
50
|
+
}
|
|
13
51
|
|
|
14
52
|
tree_ticks() {
|
|
15
53
|
local pids=("$1") i=0 kids t=0 p
|
|
16
54
|
while [ $i -lt ${#pids[@]} ]; do
|
|
17
|
-
kids=$(
|
|
55
|
+
kids=$(child_pids "${pids[$i]}"); for p in $kids; do pids+=("$p"); done; i=$((i + 1))
|
|
18
56
|
done
|
|
19
57
|
for p in "${pids[@]}"; do
|
|
20
|
-
t=$((t + $(
|
|
58
|
+
t=$((t + $(proc_ticks "$p")))
|
|
21
59
|
done
|
|
22
60
|
echo "$t"
|
|
23
61
|
}
|
|
24
62
|
|
|
25
63
|
lock_check() {
|
|
26
64
|
local owner pid now ticks spid sts sticks
|
|
27
|
-
if
|
|
65
|
+
if [ "$("$HEAVY_STATUS" "$HEAVY_MAIN" heavy-run --status 2>/dev/null)" = "free" ]; then rm -f "$IDLE_STATE"; return; fi
|
|
28
66
|
owner=$(cat "${HEAVY_OWNER:?}" 2>/dev/null)
|
|
29
67
|
pid=$(sed -nE 's/.*\| pid ([0-9]+).*/\1/p' <<<"$owner")
|
|
30
68
|
[ -n "$pid" ] || { ALERTS+=("heavy-lock busy but owner file empty: find holder with fuser $LOCK"); return; }
|
|
@@ -37,29 +75,32 @@ lock_check() {
|
|
|
37
75
|
|
|
38
76
|
snapshot() {
|
|
39
77
|
local load avail swapfree disk
|
|
40
|
-
load=$(
|
|
41
|
-
avail=$(
|
|
42
|
-
swapfree=$(
|
|
43
|
-
disk=$(
|
|
78
|
+
load=$(load_1)
|
|
79
|
+
avail=$(mem_avail)
|
|
80
|
+
swapfree=$(swap_free)
|
|
81
|
+
disk=$(home_free)
|
|
44
82
|
ALERTS=()
|
|
45
83
|
awk -v l="$load" -v m="$LOAD_MAX" 'BEGIN{exit !(l>m)}' && ALERTS+=("load $load > $LOAD_MAX")
|
|
46
84
|
[ "$avail" -lt "$AVAIL_MIN_MB" ] && ALERTS+=("MemAvailable ${avail}MB < ${AVAIL_MIN_MB}MB")
|
|
47
85
|
[ "$disk" -lt "$DISK_MIN_GB" ] && ALERTS+=("/home free ${disk}G < ${DISK_MIN_GB}G")
|
|
48
|
-
|
|
49
|
-
|
|
86
|
+
# macOS: /tmp is on the disk the check above covers, so there is no separate tmpfs to check.
|
|
87
|
+
if ! is_darwin; then
|
|
88
|
+
tmpmb=$(df -BM --output=used /tmp | tail -1 | tr -dc 0-9)
|
|
89
|
+
[ "$tmpmb" -gt "$TMP_MAX_MB" ] && ALERTS+=("/tmp (RAM tmpfs) ${tmpmb}MB > ${TMP_MAX_MB}MB: move scratch to ${WORK_ROOT}, see du -xsh /tmp/*")
|
|
90
|
+
fi
|
|
50
91
|
lock_check
|
|
51
|
-
echo "$(date +%H:%M:%S) load=$(
|
|
52
|
-
echo "heavy-lock: $("$
|
|
92
|
+
echo "$(date +%H:%M:%S) load=$(load_3) cores=$NPROC avail=${avail}MB swapfree=${swapfree}MB home_free=${disk}G"
|
|
93
|
+
echo "heavy-lock: $("$HEAVY_STATUS" "$HEAVY_MAIN" heavy-run --status 2>&1 | head -1)"
|
|
53
94
|
echo "containers: $(docker ps -q 2>/dev/null | wc -l) running; CI job: $(docker ps --format '{{.Names}}' 2>/dev/null | grep -c '^runner-')"
|
|
54
95
|
echo "top RSS:"
|
|
55
|
-
|
|
96
|
+
top_rss | awk 'NR>1 && NR<=6{printf " %5dMB %11s %s\n",$1/1024,$2,substr($0,index($0,$3),90)}'
|
|
56
97
|
echo "top CPU:"
|
|
57
|
-
|
|
98
|
+
top_cpu | awk 'NR>1 && NR<=6{printf " %5s%% %11s %s\n",$1,$2,substr($0,index($0,$3),90)}'
|
|
58
99
|
if [ ${#ALERTS[@]} -gt 0 ]; then printf 'ALERT: %s\n' "${ALERTS[@]}"; return 1; fi
|
|
59
100
|
echo "OK"
|
|
60
101
|
}
|
|
61
102
|
|
|
62
|
-
oom_count() { journalctl -k --since "$1" 2>/dev/null | grep -ci 'out of memory: killed'; }
|
|
103
|
+
oom_count() { command -v journalctl >/dev/null 2>&1 || { echo 0; return; }; journalctl -k --since "$1" 2>/dev/null | grep -ci 'out of memory: killed'; }
|
|
63
104
|
|
|
64
105
|
if [ "${1:-}" != "--watch" ]; then snapshot; exit $?; fi
|
|
65
106
|
|
|
@@ -4,18 +4,18 @@ set -uo pipefail
|
|
|
4
4
|
SNAP=${SNAP_DEST:?}
|
|
5
5
|
GF=${SNAP_GIT_REPO:-}
|
|
6
6
|
GFB=${SNAP_GIT_BACKUP:-}
|
|
7
|
-
|
|
8
|
-
mkdir -p "$SNAP/tmp" "$(dirname "$LOCK")"
|
|
7
|
+
mkdir -p "$SNAP/tmp"
|
|
9
8
|
chmod 700 "$SNAP"
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
flock -n 9 || { echo "snapshot already running"; exit 0; }
|
|
10
|
+
# The snapshot lock is held by tmp-snapshot.ts (file-lock) for the whole run.
|
|
13
11
|
|
|
14
12
|
EXCLUDES=(${SNAP_EXCLUDES:-})
|
|
15
13
|
rsync_args=(-a --ignore-errors --delete-after)
|
|
16
|
-
for x in "${EXCLUDES[@]}"; do rsync_args+=(--exclude "$x"); done
|
|
14
|
+
for x in ${EXCLUDES[@]+"${EXCLUDES[@]}"}; do rsync_args+=(--exclude "$x"); done
|
|
17
15
|
|
|
18
|
-
|
|
16
|
+
ionice_cmd=""
|
|
17
|
+
if command -v ionice >/dev/null 2>&1; then ionice_cmd="ionice -c3"; fi
|
|
18
|
+
nice -n 10 $ionice_cmd rsync "${rsync_args[@]}" /tmp/ "$SNAP/tmp/"
|
|
19
19
|
rc=$?
|
|
20
20
|
if [[ $rc -ne 0 && $rc -ne 23 && $rc -ne 24 ]]; then
|
|
21
21
|
echo "rsync /tmp failed with $rc" >&2
|
|
@@ -45,5 +45,11 @@ if [[ -n $GF && -n $GFB ]] && git -C "$GF" rev-parse --git-dir >/dev/null 2>&1;
|
|
|
45
45
|
if (( fail == 0 )); then rm -rf "$GFB" && mv "$tmpb" "$GFB"; else rm -rf "$tmpb"; fi
|
|
46
46
|
fi
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
if [[ $(uname -s) == Darwin ]]; then
|
|
49
|
+
stamp=$(date +%Y-%m-%dT%H:%M:%S%z)
|
|
50
|
+
stamp="${stamp%??}:${stamp: -2}"
|
|
51
|
+
else
|
|
52
|
+
stamp=$(date -Is)
|
|
53
|
+
fi
|
|
54
|
+
echo "$stamp" >"$SNAP/LAST_SNAPSHOT"
|
|
49
55
|
echo "snapshot done $(cat "$SNAP/LAST_SNAPSHOT")"
|
package/bin/pm-fail-facts
DELETED
|
@@ -1,440 +0,0 @@
|
|
|
1
|
-
// herdr pane reporter for the omp harness, ported from the original herdr-omp-agent-state.ts
|
|
2
|
-
// (integration id omp, version 10). Reports pane agent state over the herdr socket when
|
|
3
|
-
// HERDR_ENV=1; a nested session (OMPCODE=1) must not report. Not a core rule: core never
|
|
4
|
-
// imports this file, and reinstalling herdr overwrites its installed copy.
|
|
5
|
-
//
|
|
6
|
-
// Identical to the original: env names and values, socket methods and params, the state machine
|
|
7
|
-
// (working / blocked / idle), idle debounce 250 ms and retry grace 2500 ms (both overridable for
|
|
8
|
-
// tests), the retryable provider error pattern, and every subscribed event. Harness payloads are
|
|
9
|
-
// untyped at the boundary: every field read goes through a runtime check.
|
|
10
|
-
|
|
11
|
-
import net from "node:net";
|
|
12
|
-
import path from "node:path";
|
|
13
|
-
|
|
14
|
-
// installed by herdr; reinstalling or updating the integration overwrites this file.
|
|
15
|
-
// HERDR_INTEGRATION_ID=omp
|
|
16
|
-
// HERDR_INTEGRATION_VERSION=10
|
|
17
|
-
|
|
18
|
-
type Timer = NodeJS.Timeout;
|
|
19
|
-
|
|
20
|
-
const HERDR_ENV = process.env.HERDR_ENV;
|
|
21
|
-
const socketPath = process.env.HERDR_SOCKET_PATH;
|
|
22
|
-
const socketEndpoint =
|
|
23
|
-
process.platform === "win32" && socketPath ? `\\\\.\\pipe\\${socketPath}` : socketPath;
|
|
24
|
-
const paneId = process.env.HERDR_PANE_ID;
|
|
25
|
-
const source = "herdr:omp";
|
|
26
|
-
// OMP marks every shell it spawns with OMPCODE=1. A nested `omp` launched from a parent
|
|
27
|
-
// session's shell inherits it, so that process is not the pane's root agent and must not report
|
|
28
|
-
// its short-lived session over the parent's.
|
|
29
|
-
const nestedOmpSession = process.env.OMPCODE === "1";
|
|
30
|
-
|
|
31
|
-
function enabled(): boolean {
|
|
32
|
-
return HERDR_ENV === "1" && !!socketPath && !!paneId && !nestedOmpSession;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
let requestQueue: Promise<void> = Promise.resolve();
|
|
36
|
-
|
|
37
|
-
function sendRequestAttempt(request: unknown, timeoutMs: number): Promise<boolean> {
|
|
38
|
-
if (!enabled() || !socketEndpoint) return Promise.resolve(true);
|
|
39
|
-
const { promise, resolve } = Promise.withResolvers<boolean>();
|
|
40
|
-
let done = false;
|
|
41
|
-
let timeout: Timer | undefined;
|
|
42
|
-
const finish = (delivered: boolean) => {
|
|
43
|
-
if (done) return;
|
|
44
|
-
done = true;
|
|
45
|
-
clearTimeout(timeout);
|
|
46
|
-
socket.destroy();
|
|
47
|
-
resolve(delivered);
|
|
48
|
-
};
|
|
49
|
-
const socket = net.createConnection(socketEndpoint);
|
|
50
|
-
socket.on("error", () => finish(false));
|
|
51
|
-
socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`));
|
|
52
|
-
socket.on("data", () => finish(true));
|
|
53
|
-
socket.on("end", () => finish(false));
|
|
54
|
-
timeout = setTimeout(() => finish(false), timeoutMs);
|
|
55
|
-
timeout.unref?.();
|
|
56
|
-
return promise;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
async function sendRequestNow(request: unknown): Promise<void> {
|
|
60
|
-
if (await sendRequestAttempt(request, 500)) return;
|
|
61
|
-
await sendRequestAttempt(request, 1500);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function sendRequest(request: unknown): Promise<void> {
|
|
65
|
-
requestQueue = requestQueue.then(
|
|
66
|
-
() => sendRequestNow(request),
|
|
67
|
-
() => sendRequestNow(request),
|
|
68
|
-
);
|
|
69
|
-
return requestQueue;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
type AgentState = "working" | "blocked" | "idle";
|
|
73
|
-
|
|
74
|
-
type QueuedState = {
|
|
75
|
-
state: AgentState;
|
|
76
|
-
message?: string;
|
|
77
|
-
seq: number;
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
const idleDebounceMs = parseDurationEnv("HERDR_OMP_IDLE_DEBOUNCE_MS", 250);
|
|
81
|
-
const retryGraceMs = parseDurationEnv("HERDR_OMP_RETRY_GRACE_MS", 2500);
|
|
82
|
-
const retryableErrorPattern =
|
|
83
|
-
/overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i;
|
|
84
|
-
let reportSeq = Date.now() * 1000;
|
|
85
|
-
let currentAgentSessionId: string | undefined;
|
|
86
|
-
let currentAgentSessionPath: string | undefined;
|
|
87
|
-
|
|
88
|
-
function nextReportSeq(): number {
|
|
89
|
-
reportSeq += 1;
|
|
90
|
-
return reportSeq;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function isAbsoluteSessionPath(file: unknown): file is string {
|
|
94
|
-
return typeof file === "string" && (path.posix.isAbsolute(file) || path.win32.isAbsolute(file));
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// Dynamic field read off a harness payload: the envelope cast only enables the dynamic index,
|
|
98
|
-
// every caller checks the returned value before use.
|
|
99
|
-
function field(obj: unknown, key: string): unknown {
|
|
100
|
-
if (!obj || typeof obj !== "object" || !(key in obj)) return undefined;
|
|
101
|
-
return (obj as Record<string, unknown>)[key];
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function stringField(obj: unknown, key: string): string | undefined {
|
|
105
|
-
const value = field(obj, key);
|
|
106
|
-
return typeof value === "string" ? value : undefined;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
function boolField(obj: unknown, key: string): boolean | undefined {
|
|
110
|
-
const value = field(obj, key);
|
|
111
|
-
return typeof value === "boolean" ? value : undefined;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
function arrayField(obj: unknown, key: string): unknown[] {
|
|
115
|
-
const value = field(obj, key);
|
|
116
|
-
return Array.isArray(value) ? value : [];
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// ctx.sessionManager exposes zero-arg getters (original: ctx?.sessionManager?.getFile?.()).
|
|
120
|
-
function managerCall(ctx: unknown, method: "getSessionFile" | "getSessionId"): unknown {
|
|
121
|
-
const manager = field(ctx, "sessionManager");
|
|
122
|
-
if (!manager || typeof manager !== "object") return undefined;
|
|
123
|
-
const get = field(manager, method);
|
|
124
|
-
if (typeof get !== "function") return undefined;
|
|
125
|
-
const call = get as () => unknown;
|
|
126
|
-
return call();
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function updateSessionRef(ctx: unknown): void {
|
|
130
|
-
try {
|
|
131
|
-
const file = managerCall(ctx, "getSessionFile");
|
|
132
|
-
currentAgentSessionPath = isAbsoluteSessionPath(file) ? file : undefined;
|
|
133
|
-
} catch {
|
|
134
|
-
currentAgentSessionPath = undefined;
|
|
135
|
-
}
|
|
136
|
-
try {
|
|
137
|
-
const id = managerCall(ctx, "getSessionId");
|
|
138
|
-
currentAgentSessionId = typeof id === "string" && id.length > 0 ? id : undefined;
|
|
139
|
-
} catch {
|
|
140
|
-
currentAgentSessionId = undefined;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function withSessionRef(params: Record<string, unknown>): Record<string, unknown> {
|
|
145
|
-
if (currentAgentSessionPath) return { ...params, agent_session_path: currentAgentSessionPath };
|
|
146
|
-
if (currentAgentSessionId) return { ...params, agent_session_id: currentAgentSessionId };
|
|
147
|
-
return params;
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function parseDurationEnv(name: string, fallback: number): number {
|
|
151
|
-
const raw = process.env[name];
|
|
152
|
-
if (!raw) return fallback;
|
|
153
|
-
const parsed = Number.parseInt(raw, 10);
|
|
154
|
-
if (!Number.isFinite(parsed) || parsed < 0) return fallback;
|
|
155
|
-
return parsed;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
function currentSessionRef(): Record<string, unknown> | undefined {
|
|
159
|
-
if (currentAgentSessionPath) return { agent_session_path: currentAgentSessionPath };
|
|
160
|
-
if (currentAgentSessionId) return { agent_session_id: currentAgentSessionId };
|
|
161
|
-
return undefined;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function reportSession(sessionStartSource = "startup"): Promise<void> {
|
|
165
|
-
const sessionRef = currentSessionRef();
|
|
166
|
-
if (!sessionRef) return Promise.resolve();
|
|
167
|
-
return sendRequest({
|
|
168
|
-
id: `${source}:session:${Date.now()}:${Math.random().toString(36).slice(2)}`,
|
|
169
|
-
method: "pane.report_agent_session",
|
|
170
|
-
params: {
|
|
171
|
-
pane_id: paneId,
|
|
172
|
-
source,
|
|
173
|
-
agent: "omp",
|
|
174
|
-
seq: nextReportSeq(),
|
|
175
|
-
session_start_source: sessionStartSource,
|
|
176
|
-
...sessionRef,
|
|
177
|
-
},
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function sendState(state: AgentState, message?: string, seq = nextReportSeq()): Promise<void> {
|
|
182
|
-
return sendRequest({
|
|
183
|
-
id: `${source}:${Date.now()}:${Math.random().toString(36).slice(2)}`,
|
|
184
|
-
method: "pane.report_agent",
|
|
185
|
-
params: withSessionRef({
|
|
186
|
-
pane_id: paneId,
|
|
187
|
-
source,
|
|
188
|
-
agent: "omp",
|
|
189
|
-
state,
|
|
190
|
-
message,
|
|
191
|
-
seq,
|
|
192
|
-
}),
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
let sendInFlight = false;
|
|
197
|
-
let queuedState: QueuedState | undefined;
|
|
198
|
-
|
|
199
|
-
function queueState(state: AgentState, message?: string): void {
|
|
200
|
-
queuedState = { state, message, seq: nextReportSeq() };
|
|
201
|
-
if (!sendInFlight) void drainStateQueue();
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
async function drainStateQueue(): Promise<void> {
|
|
205
|
-
if (sendInFlight) return;
|
|
206
|
-
sendInFlight = true;
|
|
207
|
-
try {
|
|
208
|
-
while (queuedState) {
|
|
209
|
-
const next = queuedState;
|
|
210
|
-
queuedState = undefined;
|
|
211
|
-
await sendState(next.state, next.message, next.seq);
|
|
212
|
-
}
|
|
213
|
-
} finally {
|
|
214
|
-
sendInFlight = false;
|
|
215
|
-
if (queuedState) void drainStateQueue();
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function lastAssistantMessage(messages: unknown[]): unknown {
|
|
220
|
-
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
221
|
-
const message = messages[i];
|
|
222
|
-
if (message && typeof message === "object" && stringField(message, "role") === "assistant") return message;
|
|
223
|
-
}
|
|
224
|
-
return undefined;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
function retryableErrorMessage(event: unknown): string | undefined {
|
|
228
|
-
const assistant = lastAssistantMessage(arrayField(event, "messages"));
|
|
229
|
-
if (!assistant || stringField(assistant, "stopReason") !== "error") return undefined;
|
|
230
|
-
const errorMessage = stringField(assistant, "errorMessage") ?? "";
|
|
231
|
-
if (!retryableErrorPattern.test(errorMessage)) return undefined;
|
|
232
|
-
return errorMessage || "retryable provider error";
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
function askBlockedMessage(args: unknown): string {
|
|
236
|
-
for (const question of arrayField(args, "questions")) {
|
|
237
|
-
const text = stringField(question, "question");
|
|
238
|
-
if (text) return text;
|
|
239
|
-
}
|
|
240
|
-
return "waiting for user input";
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
function ctxHasUI(ctx: unknown): boolean {
|
|
244
|
-
return boolField(ctx, "hasUI") === true;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
function ctxNotIdle(ctx: unknown): boolean {
|
|
248
|
-
const isIdle = field(ctx, "isIdle");
|
|
249
|
-
if (typeof isIdle !== "function") return false;
|
|
250
|
-
const call = isIdle as () => unknown;
|
|
251
|
-
return call() === false;
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** What the adapter needs from the harness extension host (the original's `pi`). */
|
|
255
|
-
export interface HerdrHost {
|
|
256
|
-
on(event: string, cb: (event: unknown, ctx: unknown) => unknown): void;
|
|
257
|
-
events?: { on(event: string, cb: (data: unknown) => void): void };
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
export default function herdrAgentState(pi: HerdrHost): void {
|
|
261
|
-
if (!enabled()) return;
|
|
262
|
-
|
|
263
|
-
let agentActive = false;
|
|
264
|
-
let retryHoldActive = false;
|
|
265
|
-
let failureBlocked = false;
|
|
266
|
-
let failureMessage: string | undefined;
|
|
267
|
-
let blockedCount = 0;
|
|
268
|
-
let blockedMessage: string | undefined;
|
|
269
|
-
let lastState: AgentState | undefined;
|
|
270
|
-
let lastMessage: string | undefined;
|
|
271
|
-
let idleTimer: Timer | undefined;
|
|
272
|
-
let retryTimer: Timer | undefined;
|
|
273
|
-
let rootSession = false;
|
|
274
|
-
|
|
275
|
-
function clearPendingTimers(): void {
|
|
276
|
-
clearTimeout(idleTimer);
|
|
277
|
-
clearTimeout(retryTimer);
|
|
278
|
-
idleTimer = undefined;
|
|
279
|
-
retryTimer = undefined;
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function clearFailureState(): void {
|
|
283
|
-
retryHoldActive = false;
|
|
284
|
-
failureBlocked = false;
|
|
285
|
-
failureMessage = undefined;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function desiredState(): { state: AgentState; message: string | undefined } {
|
|
289
|
-
if (blockedCount > 0) return { state: "blocked", message: blockedMessage };
|
|
290
|
-
if (failureBlocked) return { state: "blocked", message: failureMessage };
|
|
291
|
-
if (agentActive || retryHoldActive) return { state: "working", message: undefined };
|
|
292
|
-
return { state: "idle", message: undefined };
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
function publishState(force = false): void {
|
|
296
|
-
const next = desiredState();
|
|
297
|
-
if (!force && next.state === lastState && next.message === lastMessage) return;
|
|
298
|
-
lastState = next.state;
|
|
299
|
-
lastMessage = next.message;
|
|
300
|
-
queueState(next.state, next.message);
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function scheduleIdle(): void {
|
|
304
|
-
clearPendingTimers();
|
|
305
|
-
clearFailureState();
|
|
306
|
-
idleTimer = setTimeout(() => {
|
|
307
|
-
idleTimer = undefined;
|
|
308
|
-
publishState();
|
|
309
|
-
}, idleDebounceMs);
|
|
310
|
-
idleTimer.unref?.();
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
function holdForRetry(message: string): void {
|
|
314
|
-
clearPendingTimers();
|
|
315
|
-
retryHoldActive = true;
|
|
316
|
-
failureBlocked = false;
|
|
317
|
-
failureMessage = message;
|
|
318
|
-
publishState();
|
|
319
|
-
retryTimer = setTimeout(() => {
|
|
320
|
-
retryTimer = undefined;
|
|
321
|
-
retryHoldActive = false;
|
|
322
|
-
failureBlocked = true;
|
|
323
|
-
publishState();
|
|
324
|
-
}, retryGraceMs);
|
|
325
|
-
retryTimer.unref?.();
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function activateRootSession(ctx: unknown, sessionStartSource = "startup"): boolean {
|
|
329
|
-
if (!ctxHasUI(ctx)) return false;
|
|
330
|
-
rootSession = true;
|
|
331
|
-
updateSessionRef(ctx);
|
|
332
|
-
void reportSession(sessionStartSource);
|
|
333
|
-
return true;
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
function resetSessionState(): void {
|
|
337
|
-
clearPendingTimers();
|
|
338
|
-
clearFailureState();
|
|
339
|
-
agentActive = false;
|
|
340
|
-
blockedCount = 0;
|
|
341
|
-
blockedMessage = undefined;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
function activateBlocked(message: string | undefined): void {
|
|
345
|
-
clearPendingTimers();
|
|
346
|
-
blockedCount += 1;
|
|
347
|
-
blockedMessage = message;
|
|
348
|
-
publishState();
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
function deactivateBlocked(): void {
|
|
352
|
-
blockedCount = Math.max(0, blockedCount - 1);
|
|
353
|
-
if (blockedCount === 0) blockedMessage = undefined;
|
|
354
|
-
publishState();
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
pi.events?.on("herdr:blocked", (data: unknown) => {
|
|
358
|
-
if (!rootSession) return;
|
|
359
|
-
if (boolField(data, "active") === false) {
|
|
360
|
-
deactivateBlocked();
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
activateBlocked(stringField(data, "label"));
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
pi.on("session_start", (_event: unknown, ctx: unknown) => {
|
|
367
|
-
if (!activateRootSession(ctx)) return;
|
|
368
|
-
// A reload can replace this extension mid-run without emitting another agent_start.
|
|
369
|
-
agentActive = ctxNotIdle(ctx);
|
|
370
|
-
publishState(true);
|
|
371
|
-
});
|
|
372
|
-
|
|
373
|
-
pi.on("session_switch", (event: unknown, ctx: unknown) => {
|
|
374
|
-
if (!activateRootSession(ctx, stringField(event, "reason") || "resume")) return;
|
|
375
|
-
resetSessionState();
|
|
376
|
-
publishState(true);
|
|
377
|
-
});
|
|
378
|
-
|
|
379
|
-
pi.on("agent_start", (_event: unknown, ctx: unknown) => {
|
|
380
|
-
if (!rootSession && !activateRootSession(ctx)) return;
|
|
381
|
-
updateSessionRef(ctx);
|
|
382
|
-
void reportSession();
|
|
383
|
-
clearPendingTimers();
|
|
384
|
-
clearFailureState();
|
|
385
|
-
agentActive = true;
|
|
386
|
-
publishState();
|
|
387
|
-
});
|
|
388
|
-
|
|
389
|
-
pi.on("tool_approval_requested", (event: unknown, ctx: unknown) => {
|
|
390
|
-
if (!rootSession && !activateRootSession(ctx)) return;
|
|
391
|
-
const label = stringField(event, "reason") || `${stringField(event, "toolName") || "Tool"} approval`;
|
|
392
|
-
activateBlocked(label);
|
|
393
|
-
});
|
|
394
|
-
|
|
395
|
-
pi.on("tool_approval_resolved", (_event: unknown, ctx: unknown) => {
|
|
396
|
-
if (!rootSession && !activateRootSession(ctx)) return;
|
|
397
|
-
deactivateBlocked();
|
|
398
|
-
});
|
|
399
|
-
|
|
400
|
-
pi.on("tool_execution_start", (event: unknown, ctx: unknown) => {
|
|
401
|
-
if (stringField(event, "toolName") !== "ask") return;
|
|
402
|
-
if (!rootSession && !activateRootSession(ctx)) return;
|
|
403
|
-
activateBlocked(askBlockedMessage(field(event, "args")));
|
|
404
|
-
});
|
|
405
|
-
|
|
406
|
-
pi.on("tool_execution_end", (event: unknown, ctx: unknown) => {
|
|
407
|
-
if (stringField(event, "toolName") !== "ask") return;
|
|
408
|
-
if (!rootSession && !activateRootSession(ctx)) return;
|
|
409
|
-
deactivateBlocked();
|
|
410
|
-
});
|
|
411
|
-
|
|
412
|
-
pi.on("agent_end", (event: unknown) => {
|
|
413
|
-
if (!rootSession) return;
|
|
414
|
-
if (!agentActive) {
|
|
415
|
-
// OMP can emit duplicate/late end events while auto-retry is already holding the pane
|
|
416
|
-
// in Working. Do not let an unqualified duplicate end cancel the retry hold and
|
|
417
|
-
// publish a false Idle.
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
if (boolField(event, "willContinue") === true) {
|
|
421
|
-
// A continuation is already scheduled, so this end is not a settle. Older builds omit
|
|
422
|
-
// the field and fall through as before.
|
|
423
|
-
return;
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
agentActive = false;
|
|
427
|
-
|
|
428
|
-
const retryableMessage = retryableErrorMessage(event);
|
|
429
|
-
if (retryableMessage) {
|
|
430
|
-
holdForRetry(retryableMessage);
|
|
431
|
-
return;
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
scheduleIdle();
|
|
435
|
-
});
|
|
436
|
-
|
|
437
|
-
pi.on("session_shutdown", () => {
|
|
438
|
-
if (rootSession) clearPendingTimers();
|
|
439
|
-
});
|
|
440
|
-
}
|
package/src/core/glm-reset.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import { spawnSync } from "node:child_process";
|
|
2
|
-
import type { Config } from "./config.ts";
|
|
3
|
-
|
|
4
|
-
function shDate(tz: string, spec: string, fmt?: string): { ok: boolean; status: number; out: string } {
|
|
5
|
-
const args = fmt ? ["-d", spec, `+${fmt}`] : ["-d", spec, "+%s"];
|
|
6
|
-
// stderr inherited: the original's set -e lets date's own message reach the terminal.
|
|
7
|
-
const r = spawnSync("date", args, { encoding: "utf8", env: { ...process.env, TZ: tz }, stdio: ["ignore", "pipe", "inherit"] });
|
|
8
|
-
return { ok: r.status === 0, status: r.status ?? 1, out: (r.stdout ?? "").trim() };
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function glmReset(args: string[], cfg: Config): number {
|
|
12
|
-
if (args.length < 1) {
|
|
13
|
-
process.stderr.write('usage: glm-reset "YYYY-MM-DD HH:MM[:SS]" (time from the GLM 429 message)\n');
|
|
14
|
-
return 2;
|
|
15
|
-
}
|
|
16
|
-
const when = args.join(" ");
|
|
17
|
-
const epochR = shDate(cfg.glm.reset_tz, when);
|
|
18
|
-
if (!epochR.ok) return epochR.status;
|
|
19
|
-
const epoch = Number(epochR.out);
|
|
20
|
-
const nowR = spawnSync("date", ["+%s"], { encoding: "utf8" });
|
|
21
|
-
const now = Number((nowR.stdout ?? "").trim());
|
|
22
|
-
const localR = spawnSync("date", ["-d", `@${epoch}`, "+%Y-%m-%d %H:%M:%S %Z"], { encoding: "utf8" });
|
|
23
|
-
const local_t = (localR.stdout ?? "").trim();
|
|
24
|
-
const label = cfg.glm.label;
|
|
25
|
-
if (epoch <= now) {
|
|
26
|
-
console.log(`${label} reset (local): ${local_t} — ALREADY BACK (${Math.floor((now - epoch) / 60)} min ago). Use GLM now.`);
|
|
27
|
-
} else {
|
|
28
|
-
const d = epoch - now;
|
|
29
|
-
console.log(`${label} reset (local): ${local_t} — in ${Math.floor(d / 3600)}h ${Math.floor((d % 3600) / 60)}m`);
|
|
30
|
-
}
|
|
31
|
-
return 0;
|
|
32
|
-
}
|