pi-retry-sentinel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
5
+ and the project uses [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-11-25
10
+
11
+ ### Added
12
+
13
+ - Early stop. After two consecutive timeout-like failures that share a signature, remaining retries are cancelled. The same payload is not going to teach anyone anything new. Disable with `PI_RETRY_SENTINEL_NO_STOP=1`.
14
+ - Same-cause report on the way out: attempt count, total time, per-attempt duration and error, and whether the failures share a signature.
15
+ - Signature normalization. Durations are blanked so `aborted (20)` groups with `aborted (35)`.
16
+ - `/retry-sentinel` command: status, session-scoped threshold, early-stop on/off.
17
+ - TUI output via `ui.notify`. `--print` and JSON output via stderr. Never both.
18
+ - `PI_RETRY_SENTINEL_MIN_FAILURES` (default 2, minimum 2), `PI_RETRY_SENTINEL_NO_STOP=1`, `PI_RETRY_SENTINEL_OFF=1`.
19
+ - Hang-like counting only. Rate limits, quota, billing and context overflow are ignored; pi already routes those through its own retry and compaction.
20
+
21
+ ### Not included
22
+
23
+ - Liveness probe (an extra billed request)
24
+ - Payload rewriting (drop images, shrink context)
25
+
26
+ Those change the cost and safety story and are not in this release.
27
+
28
+ [Unreleased]: https://github.com/liyihang866/pi-retry-sentinel/compare/v0.1.0...HEAD
29
+ [0.1.0]: https://github.com/liyihang866/pi-retry-sentinel/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 liyihang866
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # pi-retry-sentinel
4
+
5
+ **Stop burning retries on the same dead request.**
6
+
7
+ [![License: MIT](https://img.shields.io/github/license/liyihang866/pi-retry-sentinel)](LICENSE)
8
+ [![Release](https://img.shields.io/github/v/tag/liyihang866/pi-retry-sentinel?label=version)](https://github.com/liyihang866/pi-retry-sentinel/releases)
9
+ [![pi](https://img.shields.io/badge/works%20with-pi%201.6%2B-blue)](https://pi.dev)
10
+ [![Node](https://img.shields.io/badge/node-%E2%89%A520-brightgreen)](package.json)
11
+
12
+ A [pi](https://github.com/earendil-works/pi) extension.
13
+
14
+ When two consecutive failures look like the same hang, cancel the rest of the retry budget and show what actually happened — instead of waiting out four 300-second timeouts for one line of `Request timed out`.
15
+
16
+ [Install](#install) · [What you see](#what-you-see) · [How it decides](#how-it-decides) · [Configuration](#configuration)
17
+
18
+ </div>
19
+
20
+ ## Why
21
+
22
+ pi already retries timeouts. Two things it does not do:
23
+
24
+ 1. **Stop when retrying is pointless.** The same payload, sent again into the same gateway, does not succeed because you waited another 300 seconds. That is wasted minutes and wasted tokens.
25
+ 2. **Show the attempt history.** You get the last error and nothing else. Whether it failed four times the same way, recovered on attempt two, or was actually three different errors — that lives in the session file, which you then go read by hand.
26
+
27
+ This extension does both, and nothing else.
28
+
29
+ ## What you see
30
+
31
+ While things work: nothing.
32
+
33
+ When the last two timeout-like failures share a signature, remaining retries are cancelled and you get:
34
+
35
+ ```
36
+ [retry-sentinel] Stopped after 2 same-cause timeouts. Remaining retries cancelled.
37
+ [retry-sentinel] 2 timeout-like failures in 14.1s
38
+ 2 × Request timed out.: This operation was aborted
39
+ 6.0s — Request timed out.: This operation was aborted (20)
40
+ 6.0s — Request timed out.: This operation was aborted (20)
41
+ Stopped early: 2 failures share one signature. Remaining retries were cancelled.
42
+ ```
43
+
44
+ In the TUI this is a notification. In `--print` and JSON mode it goes to stderr.
45
+
46
+ If the failures do not match, pi keeps its normal retry. If you pressed Escape, or the run recovered — silence.
47
+
48
+ ## How it decides
49
+
50
+ **What counts as a hang.** Assistant errors that look like timeouts or dead connections: `timeout`, `aborted`, `ECONN*`, socket, network, fetch failed.
51
+
52
+ **What does not.** Rate limits, quota, billing, context overflow. pi already has a retry path and a compaction path for those. Mixing a normal 429 backoff into this count would invent a hang that is not there.
53
+
54
+ **Same cause.** Durations are blanked into a signature, so `aborted (20)` and `aborted (35)` group together. `ECONNRESET` and `timeout` do not.
55
+
56
+ **Then it stops.** Confirmed same-cause → the run is aborted. The point is to not pay for attempts four, five, and six of a request that already died the same way twice.
57
+
58
+ **Counter reset.** A successful reply, or a new user prompt. Not on `agent_start` — in pi, every retry is a new low-level run, and resetting there would forget the previous attempts.
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pi install git:github.com/liyihang866/pi-retry-sentinel
64
+ ```
65
+
66
+ Try it once without saving it to settings:
67
+
68
+ ```bash
69
+ pi -e git:github.com/liyihang866/pi-retry-sentinel
70
+ ```
71
+
72
+ Requires pi 1.6 or later. No runtime dependencies.
73
+
74
+ ## Configuration
75
+
76
+ Defaults come from environment variables, read when pi starts — your shell, `~/.zshrc`, or whatever launcher starts pi.
77
+
78
+ ```bash
79
+ # stop after 3 same-cause failures instead of 2
80
+ export PI_RETRY_SENTINEL_MIN_FAILURES=3
81
+
82
+ # do not cancel retries; only print the report
83
+ export PI_RETRY_SENTINEL_NO_STOP=1
84
+
85
+ # turn the extension off
86
+ export PI_RETRY_SENTINEL_OFF=1
87
+ ```
88
+
89
+ | Variable | Default | Meaning |
90
+ | --- | --- | --- |
91
+ | `PI_RETRY_SENTINEL_MIN_FAILURES` | `2` | Same-signature failures before it stops. Minimum 2. |
92
+ | `PI_RETRY_SENTINEL_NO_STOP` | unset | `1` = keep pi's retries, only print the report. |
93
+ | `PI_RETRY_SENTINEL_OFF` | unset | `1` = extension off. |
94
+
95
+ ### Slash command
96
+
97
+ In the TUI, `/retry-sentinel` changes the current session without touching env vars:
98
+
99
+ ```
100
+ /retry-sentinel status
101
+ /retry-sentinel min 3 same-cause threshold for this session
102
+ /retry-sentinel stop early stop on (default)
103
+ /retry-sentinel resume early stop off, report only
104
+ ```
105
+
106
+ The command is a no-op in `--print` / JSON mode.
107
+
108
+ ## What it will not do
109
+
110
+ - Send a probe request
111
+ - Rewrite the payload (drop images, shrink context, anything)
112
+ - Change `retry.maxRetries` in your settings — that stays yours
113
+
114
+ ## Compatibility
115
+
116
+ Wherever pi loads extensions: TUI, `--print`, JSON, Orca.
117
+
118
+ Does not touch provider selection, tools, skills, or session format.
119
+
120
+ ## Development
121
+
122
+ ```bash
123
+ npm install
124
+ npm run check
125
+ ```
126
+
127
+ `check` type-checks against the published pi 1.6 declaration files. There is no build; pi loads the TypeScript source.
128
+
129
+ ## Origin
130
+
131
+ Out of a real incident: an image request into a gateway that hung, pi retried the identical 288 KB payload twelve times at 300 seconds each, and the only record was the session JSONL. This extension is the part of that problem a user-space extension can fix without sending extra requests or mutating payloads.
132
+
133
+ ## License
134
+
135
+ [MIT](LICENSE)
@@ -0,0 +1,237 @@
1
+ /**
2
+ * pi-retry-sentinel
3
+ *
4
+ * Watches consecutive hang-like failures in a pi session.
5
+ *
6
+ * When the last N failures share one signature, it cancels the remaining
7
+ * retries — sending the same payload into the same wall again will not
8
+ * produce a different result — and, when the run ends, prints a short
9
+ * attempt history instead of one line of "Request timed out".
10
+ *
11
+ * This extension never sends an extra request and never rewrites a payload.
12
+ *
13
+ * Counting survives pi's retry because every retry is a new low-level run
14
+ * (`agent_start` fires again). The counter resets only on a successful
15
+ * reply or a new user prompt (`before_agent_start`).
16
+ */
17
+
18
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
19
+ import type {
20
+ ExtensionAPI,
21
+ ExtensionContext,
22
+ } from "@earendil-works/pi-coding-agent";
23
+
24
+ interface FailureRecord {
25
+ /** Error text with durations blanked, so "aborted (20)" equals "aborted (35)". */
26
+ signature: string;
27
+ errorMessage: string;
28
+ durationMs: number;
29
+ }
30
+
31
+ function envCount(name: string, fallback: number, min: number): number {
32
+ const raw = Number(process.env[name]);
33
+ if (!Number.isFinite(raw) || raw < min) return fallback;
34
+ return Math.floor(raw);
35
+ }
36
+
37
+ const DEFAULT_MIN_FAILURES = envCount("PI_RETRY_SENTINEL_MIN_FAILURES", 2, 2);
38
+ const DEFAULT_NO_STOP = process.env.PI_RETRY_SENTINEL_NO_STOP === "1";
39
+ const DISABLED = process.env.PI_RETRY_SENTINEL_OFF === "1";
40
+
41
+ function signatureOf(errorMessage: string): string {
42
+ return errorMessage
43
+ .replace(/\d+(\.\d+)?\s*(ms|s|sec|seconds|min)\b/gi, "<duration>")
44
+ .replace(/\(\d+\)/g, "")
45
+ .replace(/\s+/g, " ")
46
+ .trim();
47
+ }
48
+
49
+ /**
50
+ * Only hang-like failures join the count.
51
+ *
52
+ * Rate limits, quota and context overflow already have a path in pi
53
+ * (native retry and compaction). Counting them here would turn a normal
54
+ * 429 backoff into a fake "same-cause hang".
55
+ */
56
+ const EXCLUDED =
57
+ /\b(?:429|too many requests|rate.?limit|insufficient_quota|quota exceeded|out of budget|billing|GoUsageLimitError|FreeUsageLimitError)\b/i;
58
+ const OVERFLOW =
59
+ /prompt (?:is )?too long|context window exceeded|exceeds the context window|request_too_large|maximum context length|too many tokens|token limit exceeded/i;
60
+ const HANG_LIKE =
61
+ /timed?\s*out|operation was aborted|timeout|\beconn|\bsocket\b|\bnetwork\b|fetch failed|ECONNRESET|ETIMEDOUT|EPIPE/i;
62
+
63
+ function isHangLike(errorMessage: string): boolean {
64
+ if (EXCLUDED.test(errorMessage)) return false;
65
+ if (OVERFLOW.test(errorMessage)) return false;
66
+ return HANG_LIKE.test(errorMessage);
67
+ }
68
+
69
+ function isSameCause(failures: FailureRecord[], n: number): boolean {
70
+ const recent = failures.slice(-n);
71
+ return (
72
+ recent.length === n &&
73
+ recent.every((f) => f.signature === recent[0].signature)
74
+ );
75
+ }
76
+
77
+ export default function retrySentinel(pi: ExtensionAPI): void {
78
+ if (DISABLED) return;
79
+
80
+ // Environment variables are the defaults. `/retry-sentinel` overrides
81
+ // them for the current session.
82
+ let minFailures = DEFAULT_MIN_FAILURES;
83
+ let noStop = DEFAULT_NO_STOP;
84
+
85
+ let failures: FailureRecord[] = [];
86
+ let runStartAt = 0;
87
+ let stoppedByUs = false;
88
+ let currentCtx: ExtensionContext | undefined;
89
+
90
+ /** TUI gets a notify; print and JSON get stderr. Never both. */
91
+ function report(text: string): void {
92
+ if (currentCtx?.hasUI) currentCtx.ui?.notify(text, "error");
93
+ else console.error(`[retry-sentinel] ${text}`);
94
+ }
95
+
96
+ pi.registerCommand("retry-sentinel", {
97
+ description: "Show or change retry-sentinel (threshold, early stop)",
98
+ getArgumentCompletions: (prefix) => {
99
+ const options = ["status", "min", "stop", "resume"];
100
+ const matches = options.filter((option) => option.startsWith(prefix));
101
+ return matches.length > 0
102
+ ? matches.map((option) => ({ value: option, label: option }))
103
+ : null;
104
+ },
105
+ handler: async (args, ctx) => {
106
+ const [sub, value] = args.trim().split(/\s+/);
107
+ switch (sub) {
108
+ case "min": {
109
+ const next = Number(value);
110
+ if (!Number.isFinite(next) || next < 2) {
111
+ ctx.ui.notify(
112
+ "Usage: /retry-sentinel min <n> (n >= 2)",
113
+ "warning",
114
+ );
115
+ return;
116
+ }
117
+ minFailures = Math.floor(next);
118
+ ctx.ui.notify(`Same-cause threshold: ${minFailures}`, "info");
119
+ return;
120
+ }
121
+ case "stop":
122
+ noStop = false;
123
+ ctx.ui.notify("Early stop: on", "info");
124
+ return;
125
+ case "resume":
126
+ noStop = true;
127
+ ctx.ui.notify("Early stop: off (report only)", "info");
128
+ return;
129
+ default: {
130
+ const last = failures.at(-1);
131
+ const lines = [
132
+ `Early stop: ${noStop ? "off" : "on"}`,
133
+ `Same-cause threshold: ${minFailures}`,
134
+ `Failures this prompt: ${failures.length}`,
135
+ ];
136
+ if (last) {
137
+ lines.push(
138
+ `Last failure: ${(last.durationMs / 1000).toFixed(1)}s — ${last.errorMessage.slice(0, 80)}`,
139
+ );
140
+ }
141
+ lines.push("Commands: /retry-sentinel min <n> · stop · resume");
142
+ ctx.ui.notify(lines.join("\n"), "info");
143
+ }
144
+ }
145
+ },
146
+ });
147
+
148
+ pi.on("session_start", (_event, ctx) => {
149
+ currentCtx = ctx;
150
+ });
151
+
152
+ pi.on("agent_start", (_event, ctx) => {
153
+ currentCtx = ctx;
154
+ runStartAt = runStartAt || Date.now();
155
+ });
156
+
157
+ pi.on("before_agent_start", () => {
158
+ failures = [];
159
+ runStartAt = 0;
160
+ stoppedByUs = false;
161
+ });
162
+
163
+ pi.on("message_end", (event, ctx) => {
164
+ currentCtx = ctx;
165
+ const message = event.message as Partial<AssistantMessage> | undefined;
166
+ if (message?.role !== "assistant") return;
167
+ if (message.stopReason !== "error") {
168
+ failures = [];
169
+ return;
170
+ }
171
+ const errorMessage = message.errorMessage;
172
+ if (!errorMessage || !isHangLike(errorMessage)) return;
173
+
174
+ failures.push({
175
+ signature: signatureOf(errorMessage),
176
+ errorMessage,
177
+ durationMs: message.durationMs ?? 0,
178
+ });
179
+
180
+ if (noStop || stoppedByUs) return;
181
+ if (!isSameCause(failures, minFailures)) return;
182
+
183
+ stoppedByUs = true;
184
+ ctx.abort();
185
+ report(
186
+ `Stopped after ${failures.length} same-cause timeouts. Remaining retries cancelled.`,
187
+ );
188
+ });
189
+
190
+ pi.on("agent_settled", (event, ctx) => {
191
+ currentCtx = ctx;
192
+ if (failures.length === 0) return;
193
+ // A user Escape is not our report's business. Our own abort is.
194
+ if (event.aborted && !stoppedByUs) return;
195
+
196
+ const branch = ctx.sessionManager?.getBranch() ?? [];
197
+ const last = branch.at(-1) as
198
+ | { message?: { stopReason?: string } }
199
+ | undefined;
200
+ const endedInError = last?.message?.stopReason === "error";
201
+ if (!endedInError && !stoppedByUs) return;
202
+
203
+ const seconds = runStartAt > 0 ? (Date.now() - runStartAt) / 1000 : 0;
204
+ const lines = [
205
+ `${failures.length} timeout-like failure${failures.length === 1 ? "" : "s"} in ${seconds.toFixed(1)}s`,
206
+ ];
207
+
208
+ const bySignature = new Map<string, number>();
209
+ for (const f of failures) {
210
+ bySignature.set(f.signature, (bySignature.get(f.signature) ?? 0) + 1);
211
+ }
212
+ for (const [signature, count] of bySignature) {
213
+ lines.push(`${count} × ${signature}`);
214
+ }
215
+ for (const f of failures) {
216
+ lines.push(
217
+ `${(f.durationMs / 1000).toFixed(1)}s — ${f.errorMessage.slice(0, 140)}`,
218
+ );
219
+ }
220
+
221
+ if (stoppedByUs) {
222
+ lines.push(
223
+ `Stopped early: ${failures.length} failures share one signature. Remaining retries were cancelled.`,
224
+ );
225
+ } else if (isSameCause(failures, minFailures)) {
226
+ lines.push(
227
+ `Same cause: the last ${minFailures} failures share one signature. This is not jitter — look at the gateway or the request payload.`,
228
+ );
229
+ } else {
230
+ lines.push(
231
+ "Mixed causes: the failures do not share one signature. Read the per-attempt lines above.",
232
+ );
233
+ }
234
+
235
+ report(lines.join("\n"));
236
+ });
237
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
- "name": "pi-retry-sentinel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "pi-retry-sentinel",
3
+ "version": "0.1.0",
4
+ "description": "A sentinel for pi's retry loop: stop when the same cause repeats, and report the attempt history.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi",
9
+ "pi-extension",
10
+ "retry",
11
+ "timeout",
12
+ "sentinel",
13
+ "same-cause",
14
+ "ai-agent"
15
+ ],
16
+ "author": {
17
+ "name": "liyihang866",
18
+ "url": "https://github.com/liyihang866"
19
+ },
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/liyihang866/pi-retry-sentinel.git"
24
+ },
25
+ "homepage": "https://github.com/liyihang866/pi-retry-sentinel",
26
+ "bugs": {
27
+ "url": "https://github.com/liyihang866/pi-retry-sentinel/issues"
28
+ },
29
+ "files": [
30
+ "extensions/",
31
+ "README.md",
32
+ "LICENSE",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "pi": {
36
+ "extensions": [
37
+ "./extensions/retry-sentinel.ts"
38
+ ]
39
+ },
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-ai": "*",
42
+ "@earendil-works/pi-coding-agent": "*"
43
+ },
44
+ "scripts": {
45
+ "check": "tsc -p ."
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^22.0.0",
49
+ "typescript": "^5.7.0"
50
+ },
51
+ "engines": {
52
+ "node": ">=20"
53
+ }
54
+ }