granttap-mcp 0.8.168 → 0.8.169

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.
@@ -0,0 +1,84 @@
1
+ import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
2
+ import type { NativeUsageProvider } from "./projection";
3
+
4
+ /**
5
+ * What every GrantTap process on this computer shares: the last good readings, kept across restarts,
6
+ * and the time before which a provider must not be asked again. Numbers only, never a credential.
7
+ */
8
+ export type SharedUsage = { read: () => ProviderAccountUsage[]; write: (reports: ProviderAccountUsage[]) => void;
9
+ notBefore?: () => Record<string, number>; defer?: (provider: string, until: number) => void };
10
+
11
+ /**
12
+ * A provider limits how often its account may be read: Claude answers the fifth quick request with
13
+ * 429 and five minutes of refusals. Dozens of GrantTap processes run on one computer, so they share
14
+ * one read per provider every three minutes, wait as long as a refusal names, and otherwise back off.
15
+ */
16
+ const READ_EVERY_MS = 180_000;
17
+ /** How often one process looks at the shared state; the network is asked far less often. */
18
+ export const CHECK_EVERY_MS = 60_000;
19
+ const BACKOFF_MS = 60_000, BACKOFF_MAX_MS = 600_000, RETRY_AFTER_MAX_MS = 900_000;
20
+
21
+ /**
22
+ * A limit report with no windows whose id ends in ":signed-out": the provider is
23
+ * installed but its own login has lapsed. The wire format is unchanged, so older
24
+ * phones show no numbers and newer ones say why.
25
+ */
26
+ export const SIGNED_OUT_SUFFIX = ":signed-out";
27
+ export function signedOutUsage(provider: NativeUsageProvider, now: number): ProviderAccountUsage {
28
+ return { provider, limitId: `${provider}${SIGNED_OUT_SUFFIX}`, observedAt: now, windows: [] };
29
+ }
30
+ export function isSignedOutUsage(report: ProviderAccountUsage): boolean {
31
+ return report.windows.length === 0 && report.limitId.endsWith(SIGNED_OUT_SUFFIX);
32
+ }
33
+
34
+ /** The readings one process holds, kept in step with the other processes on the computer. */
35
+ export function createUsageMemory(saved: SharedUsage | undefined, clock: () => number, known: (provider: string) => boolean) {
36
+ const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
37
+ const pauses = new Map<NativeUsageProvider, number>(), failures = new Map<NativeUsageProvider, number>();
38
+ const notBefore = (provider: NativeUsageProvider) => {
39
+ let shared = -Infinity;
40
+ try { shared = Number(saved?.notBefore?.()[provider] ?? -Infinity); } catch { /* Only this process's pause is known. */ }
41
+ return Math.max(pauses.get(provider) ?? -Infinity, Number.isFinite(shared) ? shared : -Infinity);
42
+ };
43
+ const defer = (provider: NativeUsageProvider, until: number) => {
44
+ pauses.set(provider, until);
45
+ try { saved?.defer?.(provider, until); } catch { /* Best effort. */ }
46
+ };
47
+ const restore = () => {
48
+ try {
49
+ for (const report of saved?.read() ?? []) {
50
+ const held = reports.get(report.provider as NativeUsageProvider);
51
+ if (known(report.provider) && !isSignedOutUsage(report) && (held?.observedAt ?? -Infinity) < report.observedAt
52
+ && (!held || !isSignedOutUsage(held))) reports.set(report.provider as NativeUsageProvider, report);
53
+ }
54
+ } catch { /* A missing or damaged file only means nothing is remembered. */ }
55
+ };
56
+ restore();
57
+ return {
58
+ reports, restore,
59
+ remember(): void {
60
+ restore();
61
+ try { saved?.write([...reports.values()].filter(report => !isSignedOutUsage(report))); } catch { /* Best effort. */ }
62
+ },
63
+ /** Not while another process has just read it, or while the provider asked everyone to wait. */
64
+ due(provider: NativeUsageProvider, now: number): boolean {
65
+ const held = reports.get(provider);
66
+ return now >= notBefore(provider) && !(held && !isSignedOutUsage(held) && now - held.observedAt < READ_EVERY_MS);
67
+ },
68
+ claim(provider: NativeUsageProvider, now: number): void { defer(provider, now + READ_EVERY_MS); },
69
+ succeeded(provider: NativeUsageProvider): void { failures.delete(provider); },
70
+ /**
71
+ * A refused or failed request says nothing about the account: the last good reading stays. Every
72
+ * process waits as long as the provider asked, or twice as long after each failure in a row.
73
+ */
74
+ refused(provider: NativeUsageProvider, response?: Response): void {
75
+ const count = (failures.get(provider) ?? 0) + 1;
76
+ failures.set(provider, count);
77
+ const asked = Number(response?.headers.get("retry-after"));
78
+ defer(provider, clock() + (Number.isFinite(asked) && asked > 0 ? Math.min(asked * 1_000, RETRY_AFTER_MAX_MS)
79
+ : Math.min(BACKOFF_MS * 2 ** (count - 1), BACKOFF_MAX_MS)));
80
+ if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
81
+ restore();
82
+ },
83
+ };
84
+ }
@@ -1,5 +1,7 @@
1
1
  import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
2
2
  import { projectCursorPeriodUsage, projectNativeAccountUsage, type NativeUsageProvider } from "./projection";
3
+ import { CHECK_EVERY_MS, createUsageMemory, isSignedOutUsage, signedOutUsage, type SharedUsage } from "./memory";
4
+ export { isSignedOutUsage, SIGNED_OUT_SUFFIX, signedOutUsage } from "./memory";
3
5
 
4
6
  type Options = {
5
7
  credential: (provider: NativeUsageProvider) => Promise<string | undefined>;
@@ -7,16 +9,13 @@ type Options = {
7
9
  expired?: (provider: NativeUsageProvider) => Promise<boolean>;
8
10
  /** The login is live, but its access token waits for the provider's own CLI to renew it. */
9
11
  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 };
12
+ saved?: SharedUsage;
12
13
  fetcher?: (url: string, init: RequestInit) => Promise<Response>;
13
14
  clock?: () => number;
14
15
  /** Told when a signed-in account's limits become unreadable or readable again; never given a credential. */
15
16
  report?: (provider: NativeUsageProvider, reason: string | undefined) => void;
16
17
  };
17
18
 
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
19
  /** How long the last good reading is still offered, with the time it was really read, while reads fail. */
21
20
  export const HELD_USAGE_MS = 24 * 3_600_000;
22
21
  const MARKER_MS = 300_000;
@@ -27,19 +26,6 @@ const requests = {
27
26
  grok: { url: "https://cli-chat-proxy.grok.com/v1/billing?format=credits", method: "GET" },
28
27
  } as const;
29
28
 
30
- /**
31
- * A limit report with no windows whose id ends in ":signed-out": the provider is
32
- * installed but its own login has lapsed. The wire format is unchanged, so older
33
- * phones show no numbers and newer ones say why.
34
- */
35
- export const SIGNED_OUT_SUFFIX = ":signed-out";
36
- export function signedOutUsage(provider: NativeUsageProvider, now: number): ProviderAccountUsage {
37
- return { provider, limitId: `${provider}${SIGNED_OUT_SUFFIX}`, observedAt: now, windows: [] };
38
- }
39
- export function isSignedOutUsage(report: ProviderAccountUsage): boolean {
40
- return report.windows.length === 0 && report.limitId.endsWith(SIGNED_OUT_SUFFIX);
41
- }
42
-
43
29
  async function boundedResponse(response: Response): Promise<unknown> {
44
30
  if (!response.ok || !response.body) return undefined;
45
31
  const reader = response.body.getReader();
@@ -61,22 +47,10 @@ async function boundedResponse(response: Response): Promise<unknown> {
61
47
  export function createNativeAccountUsageReader(options: Options) {
62
48
  const clock = options.clock ?? Date.now;
63
49
  const fetcher = options.fetcher ?? fetch;
64
- const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
50
+ const memory = createUsageMemory(options.saved, clock, provider => provider in requests);
51
+ const { reports, restore, remember } = memory;
65
52
  let pending: Promise<void> | undefined;
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();
53
+ let attemptedAt = -Infinity;
80
54
  // Missing limits used to leave no trace; one line per change of reason keeps the log readable.
81
55
  const reasons = new Map<NativeUsageProvider, string | undefined>();
82
56
  const note = (provider: NativeUsageProvider, reason: string | undefined) => {
@@ -85,13 +59,6 @@ export function createNativeAccountUsageReader(options: Options) {
85
59
  options.report?.(provider, reason);
86
60
  };
87
61
 
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
-
95
62
  async function update(provider: NativeUsageProvider): Promise<void> {
96
63
  try {
97
64
  const token = await options.credential(provider);
@@ -107,6 +74,11 @@ export function createNativeAccountUsageReader(options: Options) {
107
74
  } else { reports.delete(provider); reasons.delete(provider); remember(); }
108
75
  return;
109
76
  }
77
+ restore();
78
+ const now = clock();
79
+ // Another process on this computer has just read it, or the provider asked everyone to wait.
80
+ if (!memory.due(provider, now)) return;
81
+ memory.claim(provider, now);
110
82
  const request = requests[provider];
111
83
  const response = await fetcher(request.url, {
112
84
  method: request.method, redirect: "error", signal: AbortSignal.timeout(8_000),
@@ -125,12 +97,12 @@ export function createNativeAccountUsageReader(options: Options) {
125
97
  });
126
98
  report = projectCursorPeriodUsage(await boundedResponse(legacy), clock());
127
99
  }
128
- if (report) { reports.set(provider, report); remember(); }
100
+ if (report) { memory.succeeded(provider); reports.set(provider, report); remember(); }
129
101
  else if (response.ok) reports.delete(provider);
130
- else unreadable(provider);
102
+ else memory.refused(provider, response);
131
103
  note(provider, report ? undefined : response.ok ? "unrecognized response" : `HTTP ${response.status}`);
132
104
  } catch (error) {
133
- unreadable(provider);
105
+ memory.refused(provider);
134
106
  note(provider, error instanceof Error ? error.name : "request failed");
135
107
  }
136
108
  }
@@ -146,8 +118,8 @@ export function createNativeAccountUsageReader(options: Options) {
146
118
  },
147
119
  refresh(): Promise<void> {
148
120
  if (pending) return pending;
149
- if (clock() - attemptedAt < (failed ? RETRY_MS : FRESH_MS)) return Promise.resolve();
150
- attemptedAt = clock(); failed = false;
121
+ if (clock() - attemptedAt < CHECK_EVERY_MS) return Promise.resolve();
122
+ attemptedAt = clock();
151
123
  pending = Promise.allSettled((Object.keys(requests) as NativeUsageProvider[]).map(update))
152
124
  .then(() => undefined).finally(() => { pending = undefined; });
153
125
  return pending;
@@ -5,6 +5,7 @@ import { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
5
5
  import { configDir, writePrivateFile } from "../../config";
6
6
 
7
7
  const Saved = z.array(ProviderAccountUsage).max(8);
8
+ const Pauses = z.record(z.string().max(40), z.number().finite());
8
9
 
9
10
  /**
10
11
  * The last good account readings, shared by every GrantTap process on this computer and kept across
@@ -12,7 +13,16 @@ const Saved = z.array(ProviderAccountUsage).max(8);
12
13
  * The file holds percentages and reset times only.
13
14
  */
14
15
  export function savedNativeUsage(path = () => join(configDir(), "native-usage.json")) {
16
+ // Beside the readings: the time before which no process here may ask a provider again.
17
+ const schedule = () => path().replace(/\.json$/, "") + "-schedule.json";
18
+ const pauses = (): Record<string, number> => {
19
+ try { return Pauses.parse(JSON.parse(readFileSync(schedule(), "utf8"))); } catch { return {}; }
20
+ };
15
21
  return {
22
+ notBefore: pauses,
23
+ defer(provider: string, until: number): void {
24
+ try { writePrivateFile(schedule(), JSON.stringify(Pauses.parse({ ...pauses(), [provider]: until }))); } catch { /* Best effort. */ }
25
+ },
16
26
  read(): ProviderAccountUsage[] {
17
27
  try { return Saved.parse(JSON.parse(readFileSync(path(), "utf8"))); } catch { return []; }
18
28
  },
@@ -12,6 +12,10 @@ type TransferProvider = {
12
12
  };
13
13
  const interrupted = (): ReplyResult => ({ ok: false,
14
14
  error: 'The first transfer turn was interrupted. Inspect the destination provider before starting another execution.' });
15
+ /** A transport retry arrives within minutes; a message sent after this long is the person deliberately trying again. */
16
+ const RESTART_AFTER_MS = 10 * 60_000;
17
+ const interruptedUnopened = (): ReplyResult => ({ ok: false,
18
+ error: 'The first transfer turn was interrupted before the agent opened a chat. Send the message again after ten minutes to start it again.' });
15
19
 
16
20
  /** Prepared executions are visible immediately and start only with a person's first message. */
17
21
  export class PreparedTaskTransfers extends TransferPersistence {
@@ -49,7 +53,7 @@ export class PreparedTaskTransfers extends TransferPersistence {
49
53
  }
50
54
 
51
55
  async deliver(id: string, text: string, attachments: UserAttachment[], options: DeliveryOptions,
52
- provider: TransferProvider): Promise<ReplyResult | undefined> {
56
+ provider: TransferProvider, now = Date.now()): Promise<ReplyResult | undefined> {
53
57
  if (!/^transfer-[a-f0-9]{48}$/.test(id)) return undefined;
54
58
  let row = this.load(id);
55
59
  if (!row) return { ok: false, error: 'The prepared transfer is unavailable.' };
@@ -57,6 +61,19 @@ export class PreparedTaskTransfers extends TransferPersistence {
57
61
  const result = await provider.resume({ ...this.session(row), sessionId: row.nativeSessionId }, text, attachments, options);
58
62
  return result.ok ? { ...result, sessionId: id } : result;
59
63
  }
64
+ if (row.phase === 'uncertain') {
65
+ // The launch that owned this transfer is over, whoever ran it. It used to refuse every later message for good.
66
+ if (row.nativeSessionId) {
67
+ // The agent did open its chat: the person's next message continues it, and nothing is started twice.
68
+ const result = await provider.resume({ ...this.session(row), sessionId: row.nativeSessionId }, text, attachments, options);
69
+ if (!result.ok) return result;
70
+ this.update(id, current => current.phase === 'uncertain' ? { ...current, phase: 'active', updatedAt: Date.now() } : current);
71
+ return { ...result, sessionId: id };
72
+ }
73
+ if (now - row.updatedAt < RESTART_AFTER_MS) return interruptedUnopened();
74
+ row = this.update(id, current => current.phase === 'uncertain' && !current.nativeSessionId
75
+ ? { ...current, phase: 'prepared', ownerPid: undefined, updatedAt: Date.now() } : current);
76
+ }
60
77
  if (row.phase !== 'prepared') return interrupted();
61
78
  let ownsLaunch = false;
62
79
  try {
@@ -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.168
13
+ npm install -g granttap-mcp@0.8.169
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.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"
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.169\";\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.168";
10
+ const PACKAGE = "granttap-mcp@0.8.169";
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.168",
3
+ "version": "0.8.169",
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": {