granttap-mcp 0.8.145 → 0.8.147

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.
@@ -20,6 +20,7 @@ import { startRuntimeWatchdog } from "../../runtime-watchdog";
20
20
 
21
21
  import { startTaskDispatchMonitor } from "../../task-dispatch/worker/monitor";
22
22
  import { startTaskNetworkMonitor } from '../../task-network/runtime';
23
+ import { claimLinkRestart } from '../../monitor/relay-link';
23
24
 
24
25
  let client: RelayClient;
25
26
  let monitor: ReturnType<typeof startSessionMonitor>;
@@ -58,7 +59,7 @@ try {
58
59
  process.exit(1);
59
60
  }
60
61
 
61
- const stop = (): void => {
62
+ const stop = (exitCode = 0): void => {
62
63
  if (stopping) return;
63
64
  stopping = true;
64
65
  stopWatchdog();
@@ -70,11 +71,19 @@ const stop = (): void => {
70
71
  monitor.close();
71
72
  stopEndpointPublisher();
72
73
  client.close();
73
- void engine.stop().finally(() => process.exit(0));
74
+ void engine.stop().finally(() => process.exit(exitCode));
74
75
  };
75
76
 
76
- process.on("SIGINT", stop);
77
- process.on("SIGTERM", stop);
77
+ process.on("SIGINT", () => stop());
78
+ process.on("SIGTERM", () => stop());
79
+ // A monitor that cannot stay on the relay looks online on the phone while no message reaches it.
80
+ client.onLinkStuck(report => {
81
+ process.stderr.write(`[monitor] cannot stay on the relay: ${report.failures} failures in five minutes, last ${report.reason}\n`);
82
+ if (claimLinkRestart()) {
83
+ process.stderr.write("[monitor] restarting for a fresh relay link\n");
84
+ stop(75);
85
+ }
86
+ });
78
87
 
79
88
  stopEngineRecovery = startEngineRecovery({
80
89
  prepare: prepareMonitorEngine,
@@ -33,6 +33,8 @@ const pendingBindingSyncs = new Map<string, Promise<boolean>>();
33
33
  // The Apple Mesh envelope is 256KiB; leave room for Tasks, bindings and receipts.
34
34
  const MAX_REPOSITORY_GRAPH_WIRE_BYTES = 192 * 1_024 - 128;
35
35
  const MAX_SINGLE_GRAPH_WIRE_BYTES = 192 * 1_024;
36
+ /** A person asked for this build; a repository the size of pytorch did not finish in two minutes. */
37
+ const EXPLICIT_ANALYSIS_MS = 600_000;
36
38
  const repositoryGraphJobs = new RepositoryGraphJobs<ProjectRepositoryGraph>(Date.now,120_000,300_000,32,
37
39
  new RepositoryGraphCache(()=>join(configDir(),"repository-graph-cache")));
38
40
 
@@ -209,7 +211,7 @@ export async function projectRepositoryGraphs(
209
211
  ))
210
212
  : await Promise.all(repositories.map((binding, index) => repositoryGraphJobs.refresh(
211
213
  JSON.stringify([projectId, binding.repositoryId, binding.revision]),
212
- () => analyzeRepositoryGraph(client, projectId, binding.repositoryId, 120_000, binding.revision),
214
+ () => analyzeRepositoryGraph(client, projectId, binding.repositoryId, EXPLICIT_ANALYSIS_MS, binding.revision),
213
215
  Number.MAX_SAFE_INTEGER, observations[index],
214
216
  )));
215
217
  return boundRepositoryGraphs(graphs.filter((item): item is ProjectRepositoryGraph => item != null));
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { projectRelationshipPeers, mergeRelationshipPeers } from "../../../engine/runtime/project-relationships";
2
3
  import type { RelayClient } from "../../../../../../packages/core/relay-client";
3
4
  import type { MeshSnapshot } from "../../../../../../packages/protocol/schema";
@@ -58,7 +59,12 @@ export async function analyzeProjectGraphNow(
58
59
  const rejected = new Set(failures.map(report => report.repositoryId));
59
60
  const bindings = graphAnalysisBindings((current.bindings ?? [])
60
61
  .filter(binding => !rejected.has(binding.repositoryId)), dependencies.endpoint?.());
61
- if (dependencies.endpoint && !bindings.length && !failures.length && current.bindings?.length) return false;
62
+ // The Engine analyses Git checkouts only; the Project's own folder without one is named, not dropped.
63
+ const endpoint = dependencies.endpoint?.();
64
+ const own = (current.bindings ?? []).find(binding => binding.repositoryId === current.project.canonicalRepositoryId
65
+ && (!endpoint || binding.endpointId === endpoint) && binding.available && binding.localPathHint
66
+ && existsSync(binding.localPathHint) && !bindings.some(selected => selected.repositoryId === binding.repositoryId));
67
+ if (dependencies.endpoint && !bindings.length && !failures.length && !own && current.bindings?.length) return false;
62
68
  const [backbone, repositoryGraphs, details] = await Promise.all([
63
69
  dependencies.backbone(projectId),
64
70
  dependencies.graphs(projectId, bindings, { background: false }),
@@ -73,9 +79,14 @@ export async function analyzeProjectGraphNow(
73
79
  analysisStatus: "UNAVAILABLE" as const, analysisErrorCode,
74
80
  nodes: [], relations: [], totalNodes: 0, totalRelations: 0, truncated: false,
75
81
  });
76
- // "Not bound" is true only without bindings here; checkouts whose analysis did not come back are named.
77
- const reports = observed.length > 0 ? observed : bindings.length > 0
78
- ? [...new Set(bindings.map(binding => binding.repositoryId))].map(id => unavailable(id, "ANALYSIS_NOT_FINISHED"))
82
+ // "Not bound" is true only without bindings here. Every bound repository is named: one whose
83
+ // analysis did not come back used to vanish once another finished, so a Mesh of several
84
+ // repositories showed a single graph as if it were the whole Mesh.
85
+ const reported = new Set(observed.map(report => report.repositoryId));
86
+ const unfinished = [...new Set(bindings.map(binding => binding.repositoryId))]
87
+ .filter(id => !reported.has(id)).map(id => unavailable(id, "ANALYSIS_NOT_FINISHED"));
88
+ const needsGit = own ? [unavailable(own.repositoryId, "GIT_CHECKOUT_REQUIRED")] : [];
89
+ const reports = observed.length + unfinished.length + needsGit.length > 0 ? [...observed, ...unfinished, ...needsGit]
79
90
  : [unavailable(current.project.canonicalRepositoryId, "REPOSITORY_NOT_BOUND")];
80
91
  const receipts = requestIds?.size ? requestIds : new Set<string | undefined>([undefined]);
81
92
  for (const id of receipts) {
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDir } from "../../config/runtime/paths";
4
+ import { writePrivateFile } from "../../config/access/write-private";
5
+
6
+ const recordPath = () => join(configDir(), "relay-link-restart.json");
7
+
8
+ /**
9
+ * A fresh process helps when the monitor's own link state wedged, and cannot help when the relay
10
+ * refuses this computer for good. One restart an hour, remembered across restarts, gives the first
11
+ * case its cure without turning the second into a restart loop. A record that cannot be written
12
+ * (a full disk) claims nothing, for the same reason.
13
+ */
14
+ export function claimLinkRestart(now = Date.now(), spacingMs = 60 * 60_000): boolean {
15
+ let last = -Infinity;
16
+ try {
17
+ const value = JSON.parse(readFileSync(recordPath(), "utf8")) as { at?: unknown };
18
+ if (typeof value.at === "number" && Number.isFinite(value.at)) last = value.at;
19
+ } catch { /* no restart recorded yet */ }
20
+ if (last <= now && now - last < spacingMs) return false;
21
+ try { writePrivateFile(recordPath(), JSON.stringify({ at: now })); } catch { return false; }
22
+ return true;
23
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Every Claude Desktop, Cursor or Codex session runs its own GrantTap MCP, and each kept a relay
3
+ * socket open for good under the computer's identity. The relay allows a computer only so many
4
+ * connections, so a dozen idle sessions left the monitor, which carries the phone's messages, no
5
+ * place. A session's link now closes after it goes unused, unless this process is the one leading
6
+ * the computer's monitoring because no separate monitor runs.
7
+ */
8
+ export function createIdleRelease(options: {
9
+ idleMs: number;
10
+ isLeader: () => boolean;
11
+ release: () => void;
12
+ }): { touch: () => void; cancel: () => void } {
13
+ let timer: NodeJS.Timeout | undefined;
14
+ const cancel = () => { if (timer) clearTimeout(timer); timer = undefined; };
15
+ const touch = () => {
16
+ cancel();
17
+ timer = setTimeout(() => {
18
+ timer = undefined;
19
+ if (options.isLeader()) { touch(); return; }
20
+ options.release();
21
+ }, options.idleMs);
22
+ timer.unref?.();
23
+ };
24
+ return { touch, cancel };
25
+ }
@@ -15,12 +15,16 @@ import { confirmPendingController, controllerPeerGate } from "../../../../bridge
15
15
  import { applyNetworkRoute } from "../../../../bridge/src/device-network/settings";
16
16
  import { startEndpointPublisher } from "../../../../bridge/src/device-network/directory";
17
17
  import { managedAdmissionOptions } from "../../../../bridge/src/managed-admission";
18
+ import { createIdleRelease } from "./idle-release";
18
19
 
19
20
  const ASK_TIMEOUT_MS = Number(
20
21
  process.env.GRANTTAP_ASK_TIMEOUT_MS ?? process.env.NODVOX_ASK_TIMEOUT_MS ?? 180_000,
21
22
  );
22
23
  let client: RelayClient | null = null;
23
24
  let monitor: SessionMonitor | null = null;
25
+ // Longer than any question can wait for its answer, so a pending ask never loses its link.
26
+ const idle = createIdleRelease({ idleMs: Math.max(5 * 60_000, ASK_TIMEOUT_MS + 60_000),
27
+ isLeader: () => monitor?.isLeader() === true, release: () => resetRelay() });
24
28
  let phoneLastSeenAt: number | null = null;
25
29
  let stopEndpointPublisher = () => {};
26
30
 
@@ -64,6 +68,7 @@ export async function relay(): Promise<RelayClient | null> {
64
68
  stopEndpointPublisher = startEndpointPublisher(config);
65
69
  }
66
70
  await client.connect();
71
+ idle.touch();
67
72
  await publishHeldHeartbeat(client).catch(() => {});
68
73
  await monitor?.publish().catch(() => {});
69
74
  return client;
@@ -73,6 +78,7 @@ export async function relay(): Promise<RelayClient | null> {
73
78
  }
74
79
 
75
80
  export function resetRelay(): void {
81
+ idle.cancel();
76
82
  stopEndpointPublisher();
77
83
  monitor?.close();
78
84
  monitor = null;
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.145
13
+ npm install -g granttap-mcp@0.8.147
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.145\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.147\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.145";
10
+ const PACKAGE = "granttap-mcp@0.8.147";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.145",
3
+ "version": "0.8.147",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,6 +2,7 @@ import { retainedPayloadOptions } from "./retained-state";
2
2
  /** Shared authenticated relay transport. See README.md for delivery and encryption boundaries. */
3
3
  import WebSocket from "ws";
4
4
  import { ManagedRelayLease, RelaySocketHealth, RelayReconnectBackoff, RelayConnectionNotifications, relayUpgradeHeaders } from "./socket-lifecycle";
5
+ import { RelayLinkWatch, type LinkStuckReport } from "./socket-lifecycle/link-watch";
5
6
  import { OutboundFrameQueue, sendEncryptedPayload, priorityControlPayload } from "./outbound-scheduler";
6
7
  import { openRelayMessage, parseRelayControl, waitForRelayPayload } from "./relay-inbound";
7
8
  import { consumeTaskJobOffer, type TaskDispatchListener } from "./task-dispatch";
@@ -30,6 +31,11 @@ export class RelayClient {
30
31
  private readonly reconnect: RelayReconnectBackoff;
31
32
  private readonly socketHealth = new RelaySocketHealth();
32
33
  private readonly admissionLease = new ManagedRelayLease();
34
+ private readonly linkStuckListeners = new Set<(report: LinkStuckReport) => void>();
35
+ private readonly linkWatch = new RelayLinkWatch({ onStuck: report => {
36
+ for (const listener of this.linkStuckListeners) { try { listener(report); } catch { /* the watch outlives a listener */ } }
37
+ } });
38
+ private readonly refusalLoggedAt = new Map<string, number>();
33
39
  private readonly sessionKeys = new Map<string, string>();
34
40
  private readonly replay: RelayMessageAcceptance;
35
41
 
@@ -88,6 +94,7 @@ export class RelayClient {
88
94
 
89
95
  ws.on("open", () => {
90
96
  opened = true;
97
+ this.linkWatch.opened();
91
98
  clearTimeout(timer);
92
99
  openedAt = Date.now();
93
100
  this.socketHealth.start(ws, this.opts.pingIntervalMs ?? 20_000);
@@ -107,12 +114,13 @@ export class RelayClient {
107
114
  ws.on("message", (data: WebSocket.RawData) => void this.onRaw(data.toString()).catch(() => {}));
108
115
  ws.on('unexpected-response', (_request, response) => {
109
116
  this.reconnect.defer(response.headers['retry-after']);
117
+ this.noteRefusal(response.statusCode, response.headers['x-hostwatch-client-limit']);
110
118
  response.resume(); ws.terminate();
111
119
  clearTimeout(timer); reject(new Error('Relay upgrade was not accepted.'));
112
120
  });
113
121
  ws.on("error", (err) => {
114
122
  clearTimeout(timer);
115
- if (!opened) reject(err);
123
+ if (!opened) { this.linkWatch.failed((err as NodeJS.ErrnoException).code ?? "connect error"); reject(err); }
116
124
  });
117
125
  ws.on("close", (code, reason) => {
118
126
  frames.cancel();
@@ -120,6 +128,7 @@ export class RelayClient {
120
128
  this.socketHealth.stop(ws);
121
129
  this.admissionLease.stop(ws);
122
130
  if (this.ws === ws) { this.reconnect.closed(openedAt, code, reason.toString()); this.ws = undefined; }
131
+ if (opened) this.linkWatch.closed(code, reason.toString().slice(0, 80));
123
132
  // The relay names why it closed; without this a refusal loop looked like an idle, online computer.
124
133
  if (opened && code !== 1000 && code !== 1001 && code !== 1005) {
125
134
  process.stderr.write(`[relay] connection closed: ${code} ${reason.toString().slice(0, 80)}\n`);
@@ -254,6 +263,22 @@ export class RelayClient {
254
263
  }
255
264
 
256
265
  /** Observe each actual socket recovery so replaceable snapshots are sent immediately. */
266
+ /** Told when this computer cannot stay on the relay; see `RelayLinkWatch`. */
267
+ onLinkStuck(listener: (report: LinkStuckReport) => void): () => void {
268
+ this.linkStuckListeners.add(listener);
269
+ return () => { this.linkStuckListeners.delete(listener); };
270
+ }
271
+
272
+ /** A refused upgrade is a failure for the watch, and its reason is logged once per ten minutes. */
273
+ private noteRefusal(status: number | undefined, limit: string | string[] | undefined): void {
274
+ const reason = `${status ?? "?"} ${typeof limit === "string" && /^[a-z-]{1,40}$/.test(limit) ? limit : ""}`.trim();
275
+ this.linkWatch.failed(reason);
276
+ const now = Date.now();
277
+ if (now - (this.refusalLoggedAt.get(reason) ?? -Infinity) < 10 * 60_000) return;
278
+ this.refusalLoggedAt.set(reason, now);
279
+ process.stderr.write(`[relay] upgrade refused: ${reason}\n`);
280
+ }
281
+
257
282
  onConnected(listener: () => void | Promise<void>): () => void {
258
283
  return this.connections.subscribe(listener);
259
284
  }
@@ -0,0 +1,44 @@
1
+ export type LinkStuckReport = { failures: number; reason: string };
2
+
3
+ /**
4
+ * Notices a computer that cannot stay on the relay. Each refused upgrade, and each socket that
5
+ * closes before it held for a minute, is a failure; six inside five minutes with no link that held
6
+ * is reported once per ten minutes with the relay's last reason. On 2026-11-05 the monitor was
7
+ * refused for hours while the phone showed the computer online, and nothing said why.
8
+ */
9
+ export class RelayLinkWatch {
10
+ private failures: number[] = [];
11
+ private openedAt?: number;
12
+ private reportedAt = -Infinity;
13
+
14
+ constructor(private readonly options: {
15
+ onStuck: (report: LinkStuckReport) => void;
16
+ now?: () => number;
17
+ windowMs?: number;
18
+ holdMs?: number;
19
+ threshold?: number;
20
+ quietMs?: number;
21
+ }) {}
22
+
23
+ private get now(): number { return (this.options.now ?? Date.now)(); }
24
+
25
+ opened(): void { this.openedAt = this.now; }
26
+
27
+ closed(code: number, reason: string): void {
28
+ const opened = this.openedAt;
29
+ this.openedAt = undefined;
30
+ if (opened === undefined) return;
31
+ if (this.now - opened >= (this.options.holdMs ?? 60_000)) { this.failures = []; return; }
32
+ this.failed(`${code} ${reason}`.trim());
33
+ }
34
+
35
+ failed(reason: string): void {
36
+ const now = this.now;
37
+ const window = this.options.windowMs ?? 5 * 60_000;
38
+ this.failures = [...this.failures.filter(at => now - at < window), now];
39
+ if (this.failures.length < (this.options.threshold ?? 6)) return;
40
+ if (now - this.reportedAt < (this.options.quietMs ?? 10 * 60_000)) return;
41
+ this.reportedAt = now;
42
+ this.options.onStuck({ failures: this.failures.length, reason });
43
+ }
44
+ }