granttap-mcp 0.8.167 → 0.8.168

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.
@@ -67,6 +67,12 @@ export async function claudeCredentialState(options: Options = {}): Promise<"val
67
67
  return claudeToken(record, options.now ?? Date.now()) ? "valid" : "expired";
68
68
  }
69
69
 
70
+ /** A live login whose access token has run out: only Claude Code's next run renews it, and nothing is read until then. */
71
+ export async function claudeAccessRenewable(options: Options = {}): Promise<boolean> {
72
+ const record = await claudeCredentialRecord(options);
73
+ return !!token(record?.claudeAiOauth?.refreshToken) && !claudeToken(record, options.now ?? Date.now());
74
+ }
75
+
70
76
  function claudeToken(value: any, now: number): string | undefined {
71
77
  const row = value?.claudeAiOauth;
72
78
  return typeof row?.expiresAt === "number" && row.expiresAt <= now ? undefined : token(row?.accessToken);
@@ -1,8 +1,9 @@
1
1
  import { homedir } from "node:os";
2
2
  import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
3
3
  import { readClaudeUsage } from "../claude-statusline";
4
- import { claudeCredentialState, readNativeCredential } from "./credentials";
5
- import { createNativeAccountUsageReader, isSignedOutUsage } from "./reader";
4
+ import { claudeAccessRenewable, claudeCredentialState, readNativeCredential } from "./credentials";
5
+ import { createNativeAccountUsageReader, HELD_USAGE_MS, isSignedOutUsage } from "./reader";
6
+ import { savedNativeUsage } from "./saved";
6
7
  import { providerAuthentication } from "../../device-management/provider-command";
7
8
 
8
9
  /**
@@ -17,6 +18,8 @@ export async function claudeLoginLapsed(read = () => claudeCredentialState(),
17
18
  let scope = "";
18
19
  const create = () => createNativeAccountUsageReader({ credential: readNativeCredential,
19
20
  expired: async provider => provider === "claude" && await claudeLoginLapsed(),
21
+ renewable: async provider => provider === "claude" && await claudeAccessRenewable(),
22
+ saved: savedNativeUsage(),
20
23
  report: (provider, reason) => process.stderr.write(reason
21
24
  ? `[granttap-mcp] ${provider} account limits unavailable: ${reason}\n`
22
25
  : `[granttap-mcp] ${provider} account limits readable again\n`) });
@@ -28,7 +31,8 @@ export function mergeNativeUsage(direct: ProviderAccountUsage[], statusLine: Pro
28
31
  for (const report of [...direct, ...statusLine]) {
29
32
  const key = `${report.provider}\u001f${report.limitId}`;
30
33
  const windows = report.windows.filter(window => window.resetsAt > now);
31
- if ((!windows.length && !isSignedOutUsage(report)) || now - report.observedAt > 300_000
34
+ const held = isSignedOutUsage(report) ? 300_000 : HELD_USAGE_MS;
35
+ if ((!windows.length && !isSignedOutUsage(report)) || now - report.observedAt > held
32
36
  || report.observedAt > now + 60_000) continue;
33
37
  if ((newest.get(key)?.observedAt ?? -Infinity) <= report.observedAt) newest.set(key, { ...report, windows });
34
38
  }
@@ -5,12 +5,22 @@ type Options = {
5
5
  credential: (provider: NativeUsageProvider) => Promise<string | undefined>;
6
6
  /** Tells an expired login from none, so a lapsed login is reported rather than silent. */
7
7
  expired?: (provider: NativeUsageProvider) => Promise<boolean>;
8
+ /** The login is live, but its access token waits for the provider's own CLI to renew it. */
9
+ renewable?: (provider: NativeUsageProvider) => Promise<boolean>;
10
+ /** The last good readings, kept across restarts. Numbers only, never a credential. */
11
+ saved?: { read: () => ProviderAccountUsage[]; write: (reports: ProviderAccountUsage[]) => void };
8
12
  fetcher?: (url: string, init: RequestInit) => Promise<Response>;
9
13
  clock?: () => number;
10
14
  /** Told when a signed-in account's limits become unreadable or readable again; never given a credential. */
11
15
  report?: (provider: NativeUsageProvider, reason: string | undefined) => void;
12
16
  };
13
17
 
18
+ /** A good reading is read again after two minutes; a failed read is tried again much sooner. */
19
+ const FRESH_MS = 120_000, RETRY_MS = 20_000;
20
+ /** How long the last good reading is still offered, with the time it was really read, while reads fail. */
21
+ export const HELD_USAGE_MS = 24 * 3_600_000;
22
+ const MARKER_MS = 300_000;
23
+
14
24
  const requests = {
15
25
  claude: { url: "https://api.anthropic.com/api/oauth/usage", method: "GET" },
16
26
  cursor: { url: "https://api2.cursor.sh/aiserver.v1.DashboardService/GetSandUsageStatus", method: "POST" },
@@ -53,7 +63,20 @@ export function createNativeAccountUsageReader(options: Options) {
53
63
  const fetcher = options.fetcher ?? fetch;
54
64
  const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
55
65
  let pending: Promise<void> | undefined;
56
- let attemptedAt = -Infinity;
66
+ let attemptedAt = -Infinity, failed = false;
67
+ const restore = () => {
68
+ try {
69
+ for (const report of options.saved?.read() ?? []) {
70
+ const held = reports.get(report.provider as NativeUsageProvider);
71
+ if (report.provider in requests && !isSignedOutUsage(report) && (held?.observedAt ?? -Infinity) < report.observedAt
72
+ && (!held || !isSignedOutUsage(held))) reports.set(report.provider as NativeUsageProvider, report);
73
+ }
74
+ } catch { /* A missing or damaged file only means nothing is remembered. */ }
75
+ };
76
+ const remember = () => {
77
+ try { options.saved?.write([...reports.values()].filter(report => !isSignedOutUsage(report))); } catch { /* Best effort. */ }
78
+ };
79
+ restore();
57
80
  // Missing limits used to leave no trace; one line per change of reason keeps the log readable.
58
81
  const reasons = new Map<NativeUsageProvider, string | undefined>();
59
82
  const note = (provider: NativeUsageProvider, reason: string | undefined) => {
@@ -62,6 +85,13 @@ export function createNativeAccountUsageReader(options: Options) {
62
85
  options.report?.(provider, reason);
63
86
  };
64
87
 
88
+ /** A refused or failed request says nothing about the account: the last good reading stays, and the read is retried soon. */
89
+ const unreadable = (provider: NativeUsageProvider) => {
90
+ failed = true;
91
+ if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
92
+ restore();
93
+ };
94
+
65
95
  async function update(provider: NativeUsageProvider): Promise<void> {
66
96
  try {
67
97
  const token = await options.credential(provider);
@@ -69,7 +99,12 @@ export function createNativeAccountUsageReader(options: Options) {
69
99
  if (await options.expired?.(provider)) {
70
100
  reports.set(provider, signedOutUsage(provider, clock()));
71
101
  note(provider, "the provider's console login has expired");
72
- } else { reports.delete(provider); reasons.delete(provider); }
102
+ } else if (await options.renewable?.(provider)) {
103
+ // Nothing can be read until the provider's CLI runs again; what was read last still stands.
104
+ if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
105
+ restore();
106
+ note(provider, "its saved access token has expired; the provider renews it on its next run");
107
+ } else { reports.delete(provider); reasons.delete(provider); remember(); }
73
108
  return;
74
109
  }
75
110
  const request = requests[provider];
@@ -90,11 +125,12 @@ export function createNativeAccountUsageReader(options: Options) {
90
125
  });
91
126
  report = projectCursorPeriodUsage(await boundedResponse(legacy), clock());
92
127
  }
93
- if (report) reports.set(provider, report);
94
- else reports.delete(provider);
128
+ if (report) { reports.set(provider, report); remember(); }
129
+ else if (response.ok) reports.delete(provider);
130
+ else unreadable(provider);
95
131
  note(provider, report ? undefined : response.ok ? "unrecognized response" : `HTTP ${response.status}`);
96
132
  } catch (error) {
97
- reports.delete(provider);
133
+ unreadable(provider);
98
134
  note(provider, error instanceof Error ? error.name : "request failed");
99
135
  }
100
136
  }
@@ -104,14 +140,14 @@ export function createNativeAccountUsageReader(options: Options) {
104
140
  const now = clock();
105
141
  return [...reports.values()].flatMap(report => {
106
142
  const windows = report.windows.filter(window => window.resetsAt > now);
107
- return now - report.observedAt <= 300_000 && (windows.length || isSignedOutUsage(report))
108
- ? [{ ...report, windows }] : [];
143
+ return isSignedOutUsage(report) ? (now - report.observedAt <= MARKER_MS ? [report] : [])
144
+ : windows.length && now - report.observedAt <= HELD_USAGE_MS ? [{ ...report, windows }] : [];
109
145
  });
110
146
  },
111
147
  refresh(): Promise<void> {
112
148
  if (pending) return pending;
113
- if (clock() - attemptedAt < 120_000) return Promise.resolve();
114
- attemptedAt = clock();
149
+ if (clock() - attemptedAt < (failed ? RETRY_MS : FRESH_MS)) return Promise.resolve();
150
+ attemptedAt = clock(); failed = false;
115
151
  pending = Promise.allSettled((Object.keys(requests) as NativeUsageProvider[]).map(update))
116
152
  .then(() => undefined).finally(() => { pending = undefined; });
117
153
  return pending;
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
5
+ import { configDir, writePrivateFile } from "../../config";
6
+
7
+ const Saved = z.array(ProviderAccountUsage).max(8);
8
+
9
+ /**
10
+ * The last good account readings, shared by every GrantTap process on this computer and kept across
11
+ * restarts. A monitor that has just started, or whose next read fails, still knows what was read last.
12
+ * The file holds percentages and reset times only.
13
+ */
14
+ export function savedNativeUsage(path = () => join(configDir(), "native-usage.json")) {
15
+ return {
16
+ read(): ProviderAccountUsage[] {
17
+ try { return Saved.parse(JSON.parse(readFileSync(path(), "utf8"))); } catch { return []; }
18
+ },
19
+ write(reports: ProviderAccountUsage[]): void {
20
+ try { writePrivateFile(path(), JSON.stringify(Saved.parse(reports))); } catch { /* Best effort. */ }
21
+ },
22
+ };
23
+ }
@@ -14,6 +14,22 @@ const SIGN_IN_REQUIRED = new RegExp([
14
14
  String.raw`"type"\s*:\s*"authentication_error"`,
15
15
  ].join('|'), 'i');
16
16
 
17
+ /**
18
+ * A block page from the network protection in front of the provider, not an answer from the
19
+ * provider about the login. Claude Code words it "Failed to authenticate. API Error: 403
20
+ * Attention Required! | Cloudflare", which sent people to sign in again when the VPN was the cause.
21
+ */
22
+ const NETWORK_BLOCK = /\b403\b[\s\S]{0,400}(?:attention required!?|just a moment\.\.\.|sorry, you have been blocked|\bcf-ray\b|\bcloudflare\b)/i;
23
+
24
+ /** The request never reached the provider's own service, so signing in again changes nothing. */
25
+ export function providerNetworkBlock(command: string, ...outputs: string[]): string | undefined {
26
+ const text = outputs.join('\n').replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '');
27
+ if (!NETWORK_BLOCK.test(text)) return;
28
+ const agent = providerAgent(command);
29
+ const provider = agent ? PROVIDER_NAMES[agent] : 'The coding agent';
30
+ return `${provider} could not reach its service: the request was blocked on the network (HTTP 403). This is not a sign-in problem. Check the VPN, proxy or network on the computer, then send the message again. This message has not been submitted to the agent.`;
31
+ }
32
+
17
33
  export function providerAgent(command: string): CodingAgent | undefined {
18
34
  const executable = basename(command).toLowerCase();
19
35
  return executable.includes('grok') ? 'grok' : executable.includes('claude') ? 'claude'
@@ -25,10 +41,10 @@ const PROVIDER_NAMES: Record<CodingAgent, string> = { claude: 'Claude Code', cod
25
41
  /** A native sign-in prompt before admission is actionable, not a minute-long delivery timeout. */
26
42
  export function providerSignInFailure(command: string, ...outputs: string[]): string | undefined {
27
43
  const text = outputs.join('\n').replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '');
28
- if (!SIGN_IN_REQUIRED.test(text)) return;
44
+ if (!SIGN_IN_REQUIRED.test(text) || NETWORK_BLOCK.test(text)) return;
29
45
  const agent = providerAgent(command);
30
46
  const provider = agent ? PROVIDER_NAMES[agent] : 'the coding agent';
31
- return `Sign-in required for ${provider}. Open Devices, choose this computer, then Sign in for ${provider}. This message has not been submitted to the agent.`;
47
+ return `Sign-in required for ${provider}. Tap Sign in in this chat, or open Devices, choose this computer, then Sign in for ${provider}. This message has not been submitted to the agent.`;
32
48
  }
33
49
 
34
50
  export function isSignInFailure(error: string): boolean { return error.startsWith('Sign-in required for '); }
@@ -74,7 +90,10 @@ export function providerResultFailure(stdout: string): string | undefined {
74
90
  }
75
91
 
76
92
  export function providerExitFailure(command: string, stderr: string, stdout: string, code: number | null): string {
77
- const signIn = providerSignInFailure(command, stderr, providerResultFailure(stdout) ?? '');
93
+ const said = providerResultFailure(stdout) ?? '';
94
+ const blocked = providerNetworkBlock(command, stderr, said);
95
+ if (blocked) return blocked;
96
+ const signIn = providerSignInFailure(command, stderr, said);
78
97
  if (signIn) return signIn;
79
98
  const reported = stderr.trim() ? undefined : providerResultFailure(stdout);
80
99
  return providerUsageFailure(stderr)
@@ -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.167
13
+ npm install -g granttap-mcp@0.8.168
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.167\";\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.168\";\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.167";
10
+ const PACKAGE = "granttap-mcp@0.8.168";
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.167",
3
+ "version": "0.8.168",
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": {