granttap-mcp 0.8.166 → 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.
- package/apps/bridge/src/limit-continuation/README.md +16 -0
- package/apps/bridge/src/limit-continuation/index.ts +88 -0
- package/apps/bridge/src/limit-continuation/store.ts +27 -0
- package/apps/bridge/src/monitor/handlers/inbound.ts +2 -18
- package/apps/bridge/src/monitor/handlers/session-commands.ts +13 -0
- package/apps/bridge/src/monitor/support/heartbeat.ts +2 -2
- package/apps/bridge/src/monitor/support/runtime.ts +4 -1
- package/apps/bridge/src/provider-account-status/native-usage/credentials.ts +15 -1
- package/apps/bridge/src/provider-account-status/native-usage/index.ts +18 -4
- package/apps/bridge/src/provider-account-status/native-usage/reader.ts +45 -9
- package/apps/bridge/src/provider-account-status/native-usage/saved.ts +23 -0
- package/apps/bridge/src/reply/process/auth-failure.ts +22 -3
- package/apps/bridge/src/session-catalog/observed-state.ts +5 -2
- package/apps/bridge/src/sessions/scan/claude/parse.ts +5 -3
- package/apps/bridge/src/sessions/scan/claude/shared.ts +3 -0
- package/apps/bridge/src/sessions/scan/claude/turn-state/index.ts +10 -1
- package/apps/bridge/src/sessions/scan/claude/turn-state/waits.ts +94 -0
- package/apps/bridge/src/task-dispatch/sender/store.ts +2 -2
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +5 -1
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/package.json +1 -1
- package/packages/protocol/messages/sessions/index.ts +21 -0
- package/packages/protocol/schema.ts +4 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Limit continuation
|
|
2
|
+
|
|
3
|
+
Public entry: `index.ts`. When a Claude chat's last request was refused by its subscription
|
|
4
|
+
window, the published session carries `usageLimit { resetsAt, window, autoContinue }`. The
|
|
5
|
+
persistent monitor then queues one "continue" for that chat on the relay's durable task queue,
|
|
6
|
+
due a minute after the reset. The relay holds it while this computer sleeps or the phone is away,
|
|
7
|
+
and offers it back like any queued phone message: the chat receives it when it is idle.
|
|
8
|
+
|
|
9
|
+
The phone turns it off or on per chat with `session.autocontinue.set`. It is on by default.
|
|
10
|
+
Turning it off takes the queued copy back from the relay. A copy the relay still offers afterwards
|
|
11
|
+
is refused at delivery. The same happens when the chat went on by itself first. A limit that reset
|
|
12
|
+
more than an hour ago is treated as abandoned and is never woken by an update.
|
|
13
|
+
|
|
14
|
+
State lives in `limit-continuation.json` in the private config directory. Tests live in `tests/`.
|
|
15
|
+
|
|
16
|
+
License: GrantTap Commercial Source License; see the repository LICENSE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CodingAgent, UserMessage, type SessionInfo } from '../../../../packages/protocol/schema';
|
|
3
|
+
import type { NativeQueueScope } from '../task-dispatch/sender/store';
|
|
4
|
+
import { readLimitContinuationState, writeLimitContinuationState, type ScheduledContinuation } from './store';
|
|
5
|
+
|
|
6
|
+
/** What the agent reads when the computer continues a chat its subscription had stopped. */
|
|
7
|
+
export const LIMIT_CONTINUE_PROMPT =
|
|
8
|
+
'GrantTap: the subscription limit that stopped this chat has reset. Continue the work from where you stopped.';
|
|
9
|
+
/** The provider's clock and ours differ a little; arriving just before the reset would hit the limit again. */
|
|
10
|
+
export const LIMIT_CONTINUE_GRACE_MS = 60_000;
|
|
11
|
+
/** A chat left at a limit that reset longer ago than this was abandoned, not waiting; an update must not wake it. */
|
|
12
|
+
const STALE_AFTER_RESET_MS = 3_600_000;
|
|
13
|
+
const PREFIX = 'limit-continue-';
|
|
14
|
+
|
|
15
|
+
export type ContinuationQueue = {
|
|
16
|
+
submit: (scope: NativeQueueScope, message: UserMessage, notBefore: number, createdAt: number) => Promise<unknown>;
|
|
17
|
+
cancel: (scope: NativeQueueScope, id: string) => Promise<unknown>;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
let registered: ContinuationQueue | undefined;
|
|
21
|
+
/** Only the persistent monitor owns the durable relay queue; session MCPs never schedule. */
|
|
22
|
+
export function registerLimitContinuationQueue(queue: ContinuationQueue | undefined): void { registered = queue; }
|
|
23
|
+
|
|
24
|
+
export function setAutoContinue(sessionId: string, enabled: boolean): void {
|
|
25
|
+
const state = readLimitContinuationState();
|
|
26
|
+
state.off = enabled ? state.off.filter(id => id !== sessionId) : [...state.off, sessionId];
|
|
27
|
+
writeLimitContinuationState(state);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The phone shows whether a limited chat will go on by itself; that is the default. */
|
|
31
|
+
export function annotateLimitContinuations(sessions: SessionInfo[]): SessionInfo[] {
|
|
32
|
+
if (!sessions.some(session => session.usageLimit)) return sessions;
|
|
33
|
+
const off = new Set(readLimitContinuationState().off);
|
|
34
|
+
return sessions.map(session => session.usageLimit
|
|
35
|
+
? { ...session, usageLimit: { ...session.usageLimit, autoContinue: !off.has(session.sessionId) } } : session);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function wanted(session: SessionInfo, off: Set<string>, now: number): boolean {
|
|
39
|
+
const limit = session.usageLimit;
|
|
40
|
+
return !!limit && session.agent === 'claude' && session.state === 'idle' && !off.has(session.sessionId)
|
|
41
|
+
&& limit.resetsAt > now - STALE_AFTER_RESET_MS;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function continuation(session: SessionInfo, now: number): { job: ScheduledContinuation; message: UserMessage } {
|
|
45
|
+
const resetsAt = session.usageLimit!.resetsAt;
|
|
46
|
+
const messageId = PREFIX + createHash('sha256').update(`${session.sessionId}:${resetsAt}`).digest('hex').slice(0, 40);
|
|
47
|
+
const scope: NativeQueueScope = { sessionId: session.sessionId, provider: CodingAgent.parse(session.agent),
|
|
48
|
+
...(session.projectId ? { projectId: session.projectId } : {}), ...(session.taskId ? { taskId: session.taskId } : {}) };
|
|
49
|
+
const cwd = session.worktree ?? session.cwd;
|
|
50
|
+
const message = UserMessage.parse({ type: 'user.message', messageId, sessionId: session.sessionId, agent: session.agent,
|
|
51
|
+
text: LIMIT_CONTINUE_PROMPT, createdAt: now, ...(cwd ? { cwd } : {}),
|
|
52
|
+
...(session.projectId ? { projectId: session.projectId } : {}) });
|
|
53
|
+
return { job: { resetsAt, messageId, scope }, message };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Puts one "continue" on the relay for every chat its subscription stopped, due when the limit resets,
|
|
58
|
+
* and takes it back when the chat went on by itself or the person turned it off. The relay holds it
|
|
59
|
+
* while this computer sleeps or the phone is away.
|
|
60
|
+
*/
|
|
61
|
+
export async function scheduleLimitContinuations(sessions: SessionInfo[], queue = registered, now = Date.now()): Promise<void> {
|
|
62
|
+
if (!queue) return;
|
|
63
|
+
const state = readLimitContinuationState(), off = new Set(state.off);
|
|
64
|
+
const byId = new Map(sessions.map(session => [session.sessionId, session]));
|
|
65
|
+
let changed = false;
|
|
66
|
+
for (const [sessionId, job] of Object.entries(state.scheduled)) {
|
|
67
|
+
const session = byId.get(sessionId);
|
|
68
|
+
const current = session?.usageLimit?.resetsAt === job.resetsAt && wanted(session, off, now);
|
|
69
|
+
const missing = !session && job.resetsAt > now - 7 * 86_400_000 && !off.has(sessionId);
|
|
70
|
+
if (current || missing) continue;
|
|
71
|
+
await queue.cancel(job.scope, job.messageId).catch(() => {});
|
|
72
|
+
delete state.scheduled[sessionId]; changed = true;
|
|
73
|
+
}
|
|
74
|
+
for (const session of sessions) {
|
|
75
|
+
if (!wanted(session, off, now) || state.scheduled[session.sessionId]) continue;
|
|
76
|
+
const { job, message } = continuation(session, now);
|
|
77
|
+
await queue.submit(job.scope, message, Math.max(now, job.resetsAt + LIMIT_CONTINUE_GRACE_MS), now);
|
|
78
|
+
state.scheduled[session.sessionId] = job; changed = true;
|
|
79
|
+
}
|
|
80
|
+
if (changed) writeLimitContinuationState(state);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A continuation the relay hands back after the person turned it off, or for a limit since lifted, is not delivered. */
|
|
84
|
+
export function limitContinuationUnwanted(message: UserMessage): boolean {
|
|
85
|
+
if (!message.messageId?.startsWith(PREFIX) || !message.sessionId) return false;
|
|
86
|
+
const state = readLimitContinuationState();
|
|
87
|
+
return state.off.includes(message.sessionId) || state.scheduled[message.sessionId]?.messageId !== message.messageId;
|
|
88
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { configDir, writePrivateFile } from '../config';
|
|
5
|
+
import { NativeQueueScope } from '../task-dispatch/sender/store';
|
|
6
|
+
|
|
7
|
+
const Scheduled = z.object({ resetsAt: z.number().int(), messageId: z.string().min(1).max(180), scope: NativeQueueScope }).strict();
|
|
8
|
+
export type ScheduledContinuation = z.infer<typeof Scheduled>;
|
|
9
|
+
const State = z.object({
|
|
10
|
+
/** Chats the person told not to continue by themselves. */
|
|
11
|
+
off: z.array(z.string().min(1).max(180)).max(4_096),
|
|
12
|
+
/** Continuations this computer put on the relay, by chat. */
|
|
13
|
+
scheduled: z.record(z.string(), Scheduled),
|
|
14
|
+
}).strict();
|
|
15
|
+
export type LimitContinuationState = z.infer<typeof State>;
|
|
16
|
+
|
|
17
|
+
const path = () => join(configDir(), 'limit-continuation.json');
|
|
18
|
+
|
|
19
|
+
export function readLimitContinuationState(): LimitContinuationState {
|
|
20
|
+
try { return State.parse(JSON.parse(readFileSync(path(), 'utf8'))); }
|
|
21
|
+
catch { return { off: [], scheduled: {} }; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function writeLimitContinuationState(state: LimitContinuationState): void {
|
|
25
|
+
writePrivateFile(path(), JSON.stringify(State.parse({ off: [...new Set(state.off)].sort().slice(-4_096),
|
|
26
|
+
scheduled: state.scheduled })));
|
|
27
|
+
}
|
|
@@ -26,14 +26,11 @@ import { recordPhoneSeen } from "../../pairing/presence";
|
|
|
26
26
|
import { handleProjectPolicySet } from "../../project-policy/runtime";
|
|
27
27
|
import { sendDeliveryReceipt } from "./receipts";
|
|
28
28
|
import {
|
|
29
|
-
|
|
29
|
+
applySessionSetting,
|
|
30
30
|
handleCompact,
|
|
31
31
|
handleConfigSet,
|
|
32
32
|
handleHostGrant,
|
|
33
|
-
handleMcpSet,
|
|
34
33
|
handleSessionControl,
|
|
35
|
-
handleShellSet,
|
|
36
|
-
handleSkillSet,
|
|
37
34
|
handleSubscription,
|
|
38
35
|
} from "./session-commands";
|
|
39
36
|
import { handleTaskCreate } from "./task-create";
|
|
@@ -102,20 +99,7 @@ export async function handleMonitorMessage(
|
|
|
102
99
|
} else if (payload.type === "sessions.history.query") {
|
|
103
100
|
await publishHistoryPage(client, payload);
|
|
104
101
|
return true;
|
|
105
|
-
} else if (payload
|
|
106
|
-
handleAccessSet(payload);
|
|
107
|
-
void publish(true).catch(() => {});
|
|
108
|
-
return true;
|
|
109
|
-
} else if (payload.type === "session.mcp.set") {
|
|
110
|
-
handleMcpSet(payload);
|
|
111
|
-
void publish(true).catch(() => {});
|
|
112
|
-
return true;
|
|
113
|
-
} else if (payload.type === "session.skill.set") {
|
|
114
|
-
handleSkillSet(payload);
|
|
115
|
-
void publish(true).catch(() => {});
|
|
116
|
-
return true;
|
|
117
|
-
} else if (payload.type === "session.shell.set") {
|
|
118
|
-
handleShellSet(payload);
|
|
102
|
+
} else if (applySessionSetting(payload)) {
|
|
119
103
|
void publish(true).catch(() => {});
|
|
120
104
|
return true;
|
|
121
105
|
} else if (payload.type === "session.compact") {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ConfigSet,
|
|
3
3
|
HostGrant,
|
|
4
|
+
Payload,
|
|
4
5
|
SessionAccessSet,
|
|
5
6
|
SessionCompact,
|
|
6
7
|
SessionControl,
|
|
@@ -10,6 +11,7 @@ import type {
|
|
|
10
11
|
SessionSubscription,
|
|
11
12
|
} from "../../../../../packages/protocol/schema";
|
|
12
13
|
import type { RelayClient } from "../../../../../packages/core/relay-client";
|
|
14
|
+
import { setAutoContinue } from "../../limit-continuation";
|
|
13
15
|
import {
|
|
14
16
|
applyConfigSet,
|
|
15
17
|
loadConfigCommandState,
|
|
@@ -45,6 +47,17 @@ export function handleShellSet(message: SessionShellSet): void {
|
|
|
45
47
|
setSessionShellAllowed(message.sessionId, message.allowed);
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
/** One chat's own settings from the phone; each is answered by republishing the catalog. */
|
|
51
|
+
export function applySessionSetting(payload: Payload): boolean {
|
|
52
|
+
if (payload.type === "session.access.set") handleAccessSet(payload);
|
|
53
|
+
else if (payload.type === "session.mcp.set") handleMcpSet(payload);
|
|
54
|
+
else if (payload.type === "session.skill.set") handleSkillSet(payload);
|
|
55
|
+
else if (payload.type === "session.shell.set") handleShellSet(payload);
|
|
56
|
+
else if (payload.type === "session.autocontinue.set") setAutoContinue(payload.sessionId, payload.enabled);
|
|
57
|
+
else return false;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
48
61
|
export { RESUME_PROMPT } from "../../task-control";
|
|
49
62
|
|
|
50
63
|
/** Phone and local desktop actions share the same computer-enforced implementation. */
|
|
@@ -21,7 +21,7 @@ export const HEARTBEAT_INTERVAL_MS = Number(
|
|
|
21
21
|
export async function publishHeartbeat(client: RelayClient): Promise<void> {
|
|
22
22
|
await client.send(
|
|
23
23
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
24
|
-
taskScheduleControls: true, taskActivityPreviews: true },
|
|
24
|
+
taskScheduleControls: true, taskActivityPreviews: true, limitAutoContinue: true },
|
|
25
25
|
"phone",
|
|
26
26
|
{ ttlMs: HEARTBEAT_INTERVAL_MS * 3, reliable: false },
|
|
27
27
|
);
|
|
@@ -40,7 +40,7 @@ export const HELD_HEARTBEAT_TTL_MS = 60_000;
|
|
|
40
40
|
export async function publishHeldHeartbeat(client: RelayClient): Promise<void> {
|
|
41
41
|
await client.send(
|
|
42
42
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
43
|
-
taskScheduleControls: true, taskActivityPreviews: true },
|
|
43
|
+
taskScheduleControls: true, taskActivityPreviews: true, limitAutoContinue: true },
|
|
44
44
|
"phone",
|
|
45
45
|
{ ttlMs: HELD_HEARTBEAT_TTL_MS, reliable: true },
|
|
46
46
|
);
|
|
@@ -44,6 +44,7 @@ const HISTORY_INTERVAL_MS = 60_000;
|
|
|
44
44
|
const resumedHeads = new WeakSet<RelayClient>();
|
|
45
45
|
import { publishMonitorMeshes, stopMonitorMeshes } from "../mesh-publication";
|
|
46
46
|
import { publishMonitorCapabilities, stopMonitorCapabilities } from "../capability-publication";
|
|
47
|
+
import { annotateLimitContinuations, scheduleLimitContinuations } from "../../limit-continuation";
|
|
47
48
|
|
|
48
49
|
export type SessionMonitor = {
|
|
49
50
|
publish: () => Promise<void>;
|
|
@@ -158,7 +159,8 @@ async function publishMonitorTick(input: {
|
|
|
158
159
|
const includeHistory = forceHistory || (!initial && Date.now() - lastHistoryPublishedAt >= HISTORY_INTERVAL_MS);
|
|
159
160
|
const snapshot = await monitorSnapshot({ includeHistory, forceHistory, subscriptions, history });
|
|
160
161
|
if (!input.active()) return { lastHistoryPublishedAt };
|
|
161
|
-
const
|
|
162
|
+
const observed = decorateTaskOriginCatalog(refreshObservedCatalog(snapshot), client.room);
|
|
163
|
+
const status = { ...observed, sessions: annotateLimitContinuations(observed.sessions) };
|
|
162
164
|
rememberPublishedCatalog(client, status);
|
|
163
165
|
await client.send(status, "phone", { ttlMs: INTERVAL_MS * 24, reliable: false });
|
|
164
166
|
// Provider review is independent of task visibility; a hung hook RPC must
|
|
@@ -167,6 +169,7 @@ async function publishMonitorTick(input: {
|
|
|
167
169
|
if (includeHistory || initial) lastHistoryPublishedAt = Date.now();
|
|
168
170
|
loadLoop.updateStatus(status);
|
|
169
171
|
void refreshMcpLoad(status.sessions).catch(() => {});
|
|
172
|
+
void scheduleLimitContinuations(status.sessions).catch(() => {});
|
|
170
173
|
publishCatalogHeads(client, status, subscriptions, publishSessionEvents);
|
|
171
174
|
if (loadRuntimeConfig().meshEnabled) publishMonitorMeshes(client, status);
|
|
172
175
|
publishMonitorCapabilities(client, status, () => history(false));
|
|
@@ -20,6 +20,10 @@ export function readNativeKeychain(service: string, account?: string, run = exec
|
|
|
20
20
|
(error, stdout) => resolve(error ? undefined : stdout.trim() || undefined)));
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
async function exists(path: string): Promise<boolean> {
|
|
24
|
+
try { await stat(path); return true; } catch { return false; }
|
|
25
|
+
}
|
|
26
|
+
|
|
23
27
|
async function jsonFile(path: string): Promise<any> {
|
|
24
28
|
try {
|
|
25
29
|
if ((await stat(path)).size > 65_536) return undefined;
|
|
@@ -42,7 +46,9 @@ async function claudeCredentialRecord(options: Options = {}): Promise<any> {
|
|
|
42
46
|
const override = env.GRANTTAP_CLAUDE_DIR ?? env.NODVOX_CLAUDE_DIR ?? env.CLAUDE_CONFIG_DIR;
|
|
43
47
|
const saved = await jsonFile(join(override ?? join(home, ".claude"), ".credentials.json"));
|
|
44
48
|
if (claudeToken(saved, options.now ?? Date.now()) || platform !== "darwin" || override || !keychainAllowed) return saved;
|
|
45
|
-
|
|
49
|
+
// Only whether Claude Code is set up here matters; its settings outgrow any parse limit with saved
|
|
50
|
+
// permissions, and reading them used to skip the Keychain for a stale credentials file.
|
|
51
|
+
if (!await exists(join(home, ".claude", "settings.json"))) return saved;
|
|
46
52
|
try {
|
|
47
53
|
const raw = await keychain("Claude Code-credentials");
|
|
48
54
|
return raw ? JSON.parse(raw) : saved;
|
|
@@ -56,9 +62,17 @@ async function claudeCredentialRecord(options: Options = {}): Promise<any> {
|
|
|
56
62
|
export async function claudeCredentialState(options: Options = {}): Promise<"valid" | "expired" | "absent"> {
|
|
57
63
|
const record = await claudeCredentialRecord(options);
|
|
58
64
|
if (!record?.claudeAiOauth) return "absent";
|
|
65
|
+
// An access token lasts hours; Claude Code renews it with its refresh token on the next run.
|
|
66
|
+
if (token(record.claudeAiOauth.refreshToken)) return "valid";
|
|
59
67
|
return claudeToken(record, options.now ?? Date.now()) ? "valid" : "expired";
|
|
60
68
|
}
|
|
61
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
|
+
|
|
62
76
|
function claudeToken(value: any, now: number): string | undefined {
|
|
63
77
|
const row = value?.claudeAiOauth;
|
|
64
78
|
return typeof row?.expiresAt === "number" && row.expiresAt <= now ? undefined : token(row?.accessToken);
|
|
@@ -1,12 +1,25 @@
|
|
|
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";
|
|
7
|
+
import { providerAuthentication } from "../../device-management/provider-command";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Claude Code's own CLI decides whether its login lapsed, whether or not the desktop app runs. A saved
|
|
11
|
+
* record alone said "expired" while phone messages kept running through the CLI.
|
|
12
|
+
*/
|
|
13
|
+
export async function claudeLoginLapsed(read = () => claudeCredentialState(),
|
|
14
|
+
cli = () => providerAuthentication("claude")): Promise<boolean> {
|
|
15
|
+
return await read() === "expired" && await cli() === "signed-out";
|
|
16
|
+
}
|
|
6
17
|
|
|
7
18
|
let scope = "";
|
|
8
19
|
const create = () => createNativeAccountUsageReader({ credential: readNativeCredential,
|
|
9
|
-
expired: async provider => provider === "claude" && await
|
|
20
|
+
expired: async provider => provider === "claude" && await claudeLoginLapsed(),
|
|
21
|
+
renewable: async provider => provider === "claude" && await claudeAccessRenewable(),
|
|
22
|
+
saved: savedNativeUsage(),
|
|
10
23
|
report: (provider, reason) => process.stderr.write(reason
|
|
11
24
|
? `[granttap-mcp] ${provider} account limits unavailable: ${reason}\n`
|
|
12
25
|
: `[granttap-mcp] ${provider} account limits readable again\n`) });
|
|
@@ -18,7 +31,8 @@ export function mergeNativeUsage(direct: ProviderAccountUsage[], statusLine: Pro
|
|
|
18
31
|
for (const report of [...direct, ...statusLine]) {
|
|
19
32
|
const key = `${report.provider}\u001f${report.limitId}`;
|
|
20
33
|
const windows = report.windows.filter(window => window.resetsAt > now);
|
|
21
|
-
|
|
34
|
+
const held = isSignedOutUsage(report) ? 300_000 : HELD_USAGE_MS;
|
|
35
|
+
if ((!windows.length && !isSignedOutUsage(report)) || now - report.observedAt > held
|
|
22
36
|
|| report.observedAt > now + 60_000) continue;
|
|
23
37
|
if ((newest.get(key)?.observedAt ?? -Infinity) <= report.observedAt) newest.set(key, { ...report, windows });
|
|
24
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
|
|
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
|
-
|
|
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 <=
|
|
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 <
|
|
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}.
|
|
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
|
|
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)
|
|
@@ -6,7 +6,7 @@ import {localTaskTransfers} from '../task-transfer';
|
|
|
6
6
|
import {nativeTranscriptSource} from '../sessions/native-source';
|
|
7
7
|
import {claudeLogPath} from '../sessions/scan/claude/shared';
|
|
8
8
|
import {previousNativeLines} from '../transcript-history/native-lines';
|
|
9
|
-
import {observeClaudeTurn,claudeTurnState,type ClaudeTurnClock} from '../sessions/scan/claude/turn-state';
|
|
9
|
+
import {observeClaudeTurn,claudeTurnState,claudeWaits,withClaudeWaits,type ClaudeTurnClock} from '../sessions/scan/claude/turn-state';
|
|
10
10
|
import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/scan/codex/turn-state';
|
|
11
11
|
import {ts} from '../sessions/support/common';
|
|
12
12
|
import {grokResumeActivity} from '../providers/grok-activity';
|
|
@@ -80,6 +80,9 @@ function observeNativeTail(input:SessionInfo,native:SessionInfo):SessionObservat
|
|
|
80
80
|
const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
|
|
81
81
|
const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
|
|
82
82
|
:clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
|
|
83
|
-
return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
|
|
83
|
+
if(native.agent!=='claude')return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
|
|
84
|
+
const waits=claudeWaits(clock!.claude,clock!.claude.turnEnded);
|
|
85
|
+
return {session:withClaudeWaits({...input,state,lastActivityAt:at},waits),
|
|
86
|
+
revision:`${revision}:${state}:${waits.backgroundTasks??0}:${waits.usageLimit?.resetsAt??0}`};
|
|
84
87
|
}catch{return;}
|
|
85
88
|
}
|
|
@@ -5,7 +5,7 @@ import type { ChildThreadInfo, SessionInfo } from "../../../../../../packages/pr
|
|
|
5
5
|
import { aggregateChildThreads, childTitle } from "../../support/child-threads";
|
|
6
6
|
import { plainPreview } from '../../plain-preview';
|
|
7
7
|
import { rememberCapabilityObservation } from "../../telemetry";
|
|
8
|
-
import { observeClaudeTurn } from "./turn-state";
|
|
8
|
+
import { claudeWaits, observeClaudeTurn, withClaudeWaits, type ClaudeTurnClock } from "./turn-state";
|
|
9
9
|
import { claudeContextReport } from "../../context-usage";
|
|
10
10
|
import { LIVE_MS, safeParse, stateFor, ts } from "../../support/common";
|
|
11
11
|
import { finishScan } from "../../cooperative-scan";
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
import { readTranscriptRows } from "./transcript-reading";
|
|
24
24
|
import { readClaudeChild } from "./child-reading";
|
|
25
25
|
|
|
26
|
-
type ClaudeParseState = {
|
|
26
|
+
type ClaudeParseState = ClaudeTurnClock & {
|
|
27
27
|
sessionId: string;
|
|
28
28
|
cwd?: string;
|
|
29
29
|
launchCwd?: string;
|
|
@@ -201,7 +201,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
201
201
|
recordedClaudeUsageIsCurrent(cached.observations)
|
|
202
202
|
) {
|
|
203
203
|
const session = {
|
|
204
|
-
...cached.session,
|
|
204
|
+
...withClaudeWaits(cached.session, claudeWaits(cached.waits ?? {}, cached.turnEnded)),
|
|
205
205
|
state:
|
|
206
206
|
cached.session.childThreads?.some((child) => stateFor(child.lastActivityAt) === "working")
|
|
207
207
|
? "working" as const
|
|
@@ -252,6 +252,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
252
252
|
tokensLastTurn: state.tokensLastTurn,
|
|
253
253
|
contextTokensUsed: state.contextTokensUsed,
|
|
254
254
|
...(state.contextUsage ? { contextUsage: state.contextUsage } : {}),
|
|
255
|
+
...claudeWaits(state, state.turnEnded),
|
|
255
256
|
};
|
|
256
257
|
const actualChildPaths =
|
|
257
258
|
state.sessionId === cachedSessionId ? childPaths : claudeChildLogPaths(file, state.sessionId);
|
|
@@ -268,6 +269,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
268
269
|
tokensSession: session.tokensSession,
|
|
269
270
|
observations,
|
|
270
271
|
turnEnded: state.turnEnded,
|
|
272
|
+
waits: { background: state.background, limit: state.limit },
|
|
271
273
|
// A chat that has gone quiet gives its memory back and is read again if it returns.
|
|
272
274
|
progress: Date.now() - session.lastActivityAt <= LIVE_MS ? progress : undefined,
|
|
273
275
|
});
|
|
@@ -2,6 +2,7 @@ import { diffPreviewFromInput, patchStatsByToolUse, sensitivePath, statsFromInpu
|
|
|
2
2
|
import { redactSecrets } from "../../telemetry/command-preview";
|
|
3
3
|
import { createChildSummary } from "./transcript-reading";
|
|
4
4
|
import { recordObservedWrite, writtenPaths } from "../../../mesh/observed/writes";
|
|
5
|
+
import type { ClaudeWaits } from "./turn-state/waits";
|
|
5
6
|
/**
|
|
6
7
|
* Claude Code session logs:
|
|
7
8
|
* ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl
|
|
@@ -56,6 +57,8 @@ export type CachedClaudeSummary = {
|
|
|
56
57
|
observations: CapabilityObservation[];
|
|
57
58
|
/** The chat's own last turn ended; recent writes no longer mean it is working. */
|
|
58
59
|
turnEnded?: boolean;
|
|
60
|
+
/** What the ended turn waits on besides the person; deadlines are read against the clock at use. */
|
|
61
|
+
waits?: ClaudeWaits;
|
|
59
62
|
/** Where a growing transcript was last read to; see `ClaudeParseProgress`. */
|
|
60
63
|
progress?: unknown;
|
|
61
64
|
};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {stateFor} from '../../../support/common';
|
|
2
2
|
import type {SessionInfo} from '../../../../../../../packages/protocol/schema';
|
|
3
|
+
import {observeClaudeWaits, type ClaudeWaits} from './waits';
|
|
4
|
+
export {claudeWaits, type ClaudeWaits} from './waits';
|
|
3
5
|
|
|
4
|
-
export type ClaudeTurnClock = {turnEnded?: boolean};
|
|
6
|
+
export type ClaudeTurnClock = {turnEnded?: boolean} & ClaudeWaits;
|
|
5
7
|
const finished = new Set(['end_turn','stop_sequence','max_tokens']);
|
|
6
8
|
|
|
7
9
|
/** Root turn boundaries only; progress and sidechain records cannot resume a finished turn. */
|
|
@@ -9,9 +11,16 @@ export function observeClaudeTurn(row: any, clock: ClaudeTurnClock): void {
|
|
|
9
11
|
if (row.isSidechain === true) return;
|
|
10
12
|
if (row.type === 'user' || row.type === 'queue-operation') clock.turnEnded = false;
|
|
11
13
|
else if (row.type === 'assistant') clock.turnEnded = finished.has(row.message?.stop_reason);
|
|
14
|
+
observeClaudeWaits(row, clock);
|
|
12
15
|
}
|
|
13
16
|
|
|
14
17
|
export function claudeTurnState(clock: ClaudeTurnClock, lastActivityAt: number,
|
|
15
18
|
fallback: SessionInfo['state']): SessionInfo['state'] {
|
|
16
19
|
return clock.turnEnded === undefined ? fallback : clock.turnEnded ? 'idle' : stateFor(lastActivityAt);
|
|
17
20
|
}
|
|
21
|
+
|
|
22
|
+
/** Replaces what an older reading said the chat was waiting on with what this one says. */
|
|
23
|
+
export function withClaudeWaits(session: SessionInfo, waits: Pick<SessionInfo, 'backgroundTasks' | 'usageLimit'>): SessionInfo {
|
|
24
|
+
const {backgroundTasks: _background, usageLimit: _limit, ...rest} = session;
|
|
25
|
+
return {...rest, ...waits};
|
|
26
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {ts} from '../../../support/common';
|
|
2
|
+
|
|
3
|
+
/** Background work the chat started and has not heard back from, keyed by the launching tool call. */
|
|
4
|
+
export type ClaudeBackgroundWork = {taskId?: string; until: number};
|
|
5
|
+
/** The subscription window that refused the chat's last request. */
|
|
6
|
+
export type ClaudeUsageLimit = {resetsAt: number; window?: string};
|
|
7
|
+
export type ClaudeWaits = {background?: Record<string, ClaudeBackgroundWork>; limit?: ClaudeUsageLimit};
|
|
8
|
+
|
|
9
|
+
const BASH_DEFAULT_MS = 600_000, LONGEST_MS = 7_200_000, MAX_TRACKED = 32;
|
|
10
|
+
const BASH_LAUNCH = /^Command running in background with ID: ([\w-]+)/;
|
|
11
|
+
const AGENT_LAUNCH = /^Async agent launched/;
|
|
12
|
+
const AGENT_ID = /agentId: ([\w-]+)/;
|
|
13
|
+
const launched = new Map<string, {name: string; timeout?: number}>();
|
|
14
|
+
|
|
15
|
+
function text(content: unknown): string {
|
|
16
|
+
if (typeof content === 'string') return content;
|
|
17
|
+
if (!Array.isArray(content)) return '';
|
|
18
|
+
return content.map((block: any) => typeof block?.text === 'string' ? block.text
|
|
19
|
+
: typeof block?.content === 'string' ? block.content : '').join('\n');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Bash reports its own bound; an agent is given the longest a background command may run. */
|
|
23
|
+
function bound(name: string | undefined, timeout: unknown): number {
|
|
24
|
+
if (name !== 'Bash') return LONGEST_MS;
|
|
25
|
+
return typeof timeout === 'number' && timeout > 0 ? Math.min(timeout, LONGEST_MS) : BASH_DEFAULT_MS;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function noteLaunch(block: any, at: number, waits: ClaudeWaits): void {
|
|
29
|
+
const id = String(block.tool_use_id ?? ''), body = text(block.content);
|
|
30
|
+
if (!id || block.is_error === true) { if (id && waits.background) delete waits.background[id]; return; }
|
|
31
|
+
const bash = BASH_LAUNCH.exec(body), agent = AGENT_LAUNCH.test(body) ? AGENT_ID.exec(body) : null;
|
|
32
|
+
if (!bash && !AGENT_LAUNCH.test(body)) return;
|
|
33
|
+
const call = launched.get(id);
|
|
34
|
+
const background = waits.background ??= {};
|
|
35
|
+
background[id] = {taskId: bash?.[1] ?? agent?.[1], until: at + bound(call?.name ?? (bash ? 'Bash' : 'Agent'), call?.timeout)};
|
|
36
|
+
const ids = Object.keys(background);
|
|
37
|
+
for (const old of ids.slice(0, Math.max(0, ids.length - MAX_TRACKED))) delete background[old];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function noteNotifications(body: string, waits: ClaudeWaits): void {
|
|
41
|
+
if (!waits.background || !body.includes('<task-notification>')) return;
|
|
42
|
+
for (const note of body.split('<task-notification>').slice(1)) {
|
|
43
|
+
const status = /<status>([^<]+)<\/status>/.exec(note)?.[1];
|
|
44
|
+
if (status === 'running') continue;
|
|
45
|
+
const toolUse = /<tool-use-id>([^<]+)<\/tool-use-id>/.exec(note)?.[1];
|
|
46
|
+
const taskId = /<task-id>([^<]+)<\/task-id>/.exec(note)?.[1];
|
|
47
|
+
for (const [id, work] of Object.entries(waits.background)) {
|
|
48
|
+
if (id === toolUse || (taskId && work.taskId === taskId)) delete waits.background[id];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function usageLimit(row: any): ClaudeUsageLimit | undefined {
|
|
54
|
+
if (row.isApiErrorMessage !== true) return;
|
|
55
|
+
const quota = row.quotaLimits ?? row.apiErrorParams?.rate_limit_info;
|
|
56
|
+
const resetsAt = Number(quota?.resetsAt);
|
|
57
|
+
if (quota?.status !== 'rejected' || !Number.isFinite(resetsAt) || resetsAt <= 0) return;
|
|
58
|
+
const window = typeof quota.rateLimitType === 'string' ? quota.rateLimitType.slice(0, 40) : undefined;
|
|
59
|
+
return {resetsAt: resetsAt * 1_000, ...(window ? {window} : {})};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What a root Claude row says about the chat waiting on something other than the person:
|
|
64
|
+
* background work that will resume it, or a subscription window that refused it.
|
|
65
|
+
*/
|
|
66
|
+
export function observeClaudeWaits(row: any, waits: ClaudeWaits): void {
|
|
67
|
+
const at = ts(row.timestamp) || Date.now(), content = row.message?.content;
|
|
68
|
+
if (row.type === 'assistant') {
|
|
69
|
+
waits.limit = usageLimit(row);
|
|
70
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
71
|
+
if (block?.type === 'tool_use' && typeof block.id === 'string') {
|
|
72
|
+
launched.set(block.id, {name: String(block.name ?? ''), timeout: block.input?.timeout});
|
|
73
|
+
while (launched.size > 512) launched.delete(launched.keys().next().value!);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (row.type !== 'user' && row.type !== 'queue-operation') return;
|
|
79
|
+
const body = typeof row.content === 'string' ? row.content : text(content);
|
|
80
|
+
noteNotifications(body, waits);
|
|
81
|
+
if (row.type === 'user' && !body.includes('<task-notification>')) waits.limit = undefined;
|
|
82
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
83
|
+
if (block?.type === 'tool_result') noteLaunch(block, at, waits);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Published only once the turn has ended: before that the chat is simply working. */
|
|
88
|
+
export function claudeWaits(waits: ClaudeWaits, turnEnded: boolean | undefined, now = Date.now()):
|
|
89
|
+
{backgroundTasks?: number; usageLimit?: ClaudeUsageLimit} {
|
|
90
|
+
if (!turnEnded) return {};
|
|
91
|
+
const pending = Object.values(waits.background ?? {}).filter(work => work.until > now).length;
|
|
92
|
+
return {...(pending ? {backgroundTasks: Math.min(pending, 32)} : {}),
|
|
93
|
+
...(waits.limit ? {usageLimit: waits.limit} : {})};
|
|
94
|
+
}
|
|
@@ -6,8 +6,8 @@ import { withStoreLock } from '../../../../../packages/core/store-file-lock';
|
|
|
6
6
|
import { Envelope, CodingAgent } from '../../../../../packages/protocol/schema';
|
|
7
7
|
import { digest, readRequest, syncDirectory, writeRequest } from '../journal';
|
|
8
8
|
|
|
9
|
-
export const NativeQueueScope = z.object({ projectId: z.string().min(1).max(180),
|
|
10
|
-
taskId: z.string().min(1).max(180), sessionId: z.string().min(1).max(180), provider: CodingAgent }).strict();
|
|
9
|
+
export const NativeQueueScope = z.object({ projectId: z.string().min(1).max(180).optional(),
|
|
10
|
+
taskId: z.string().min(1).max(180).optional(), sessionId: z.string().min(1).max(180), provider: CodingAgent }).strict();
|
|
11
11
|
export type NativeQueueScope = z.infer<typeof NativeQueueScope>;
|
|
12
12
|
const Header = z.object({ id: z.string(), scope: NativeQueueScope, intent: z.string(),
|
|
13
13
|
createdAt: z.number().int(), notBefore: z.number().int(), expiresAt: z.number().int() }).strict();
|
|
@@ -13,6 +13,7 @@ import { NativeTaskQueueSender } from '../sender';
|
|
|
13
13
|
import { dispatchSessionObservation, newTaskOperationKey, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
|
|
14
14
|
import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
|
|
15
15
|
import { queueFailureReporter } from './failure-report';
|
|
16
|
+
import { limitContinuationUnwanted, registerLimitContinuationQueue } from '../../limit-continuation';
|
|
16
17
|
|
|
17
18
|
/** Only the persistent monitor advertises durable submission capability. */
|
|
18
19
|
export function startTaskDispatchMonitor(input: {
|
|
@@ -28,6 +29,8 @@ export function startTaskDispatchMonitor(input: {
|
|
|
28
29
|
const waitingSince = new Map<string, number>();
|
|
29
30
|
const sender = new NativeTaskQueueSender({ root: join(configDir(), 'native-task-queue'), config: input.config });
|
|
30
31
|
const peerAllowed = (peer: string) => peer === input.config.myPublicKey || input.peerAllowed(peer);
|
|
32
|
+
registerLimitContinuationQueue({ submit: (scope, message, notBefore, createdAt) => sender.submit(scope, message, notBefore, createdAt),
|
|
33
|
+
cancel: (scope, id) => sender.cancel(scope, id) });
|
|
31
34
|
const worker = new TaskDispatchWorker({ inbox, remote: input.remote ?? relayTaskJobRemote(input.config),
|
|
32
35
|
connected: () => !stopped && input.client.isConnected && input.isLeader(),
|
|
33
36
|
authorized: peerAllowed,
|
|
@@ -67,6 +70,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
67
70
|
return ready;
|
|
68
71
|
},
|
|
69
72
|
deliver: async (original, beforeStart, peer) => {
|
|
73
|
+
if (original.operation.type === 'user.message' && limitContinuationUnwanted(original.operation)) return 'rejected';
|
|
70
74
|
if (input.deliver) return input.deliver(original, beforeStart, peer);
|
|
71
75
|
const job = resolve(original, peer).job;
|
|
72
76
|
if (!job || job.operation.type === 'user.message.continue') return 'rejected';
|
|
@@ -101,5 +105,5 @@ export function startTaskDispatchMonitor(input: {
|
|
|
101
105
|
});
|
|
102
106
|
const interval = setInterval(tick, 2_000); interval.unref();
|
|
103
107
|
tick();
|
|
104
|
-
return () => { stopped = true; clearInterval(interval); off(); };
|
|
108
|
+
return () => { stopped = true; clearInterval(interval); off(); registerLimitContinuationQueue(undefined); };
|
|
105
109
|
}
|
package/cursor-plugin/README.md
CHANGED
|
@@ -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.
|
|
13
|
+
npm install -g granttap-mcp@0.8.168
|
|
14
14
|
granttap setup
|
|
15
15
|
granttap status
|
|
16
16
|
```
|
package/cursor-plugin/mcp.json
CHANGED
|
@@ -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.
|
|
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.
|
|
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
|
@@ -66,6 +66,14 @@ export const SessionSealed = z.object({
|
|
|
66
66
|
});
|
|
67
67
|
export type SessionSealed = z.infer<typeof SessionSealed>;
|
|
68
68
|
|
|
69
|
+
export const SessionUsageLimit = z.object({
|
|
70
|
+
resetsAt: z.number().int().positive(),
|
|
71
|
+
window: z.string().max(40).optional(),
|
|
72
|
+
/** Whether this computer will continue the chat itself once the limit resets; on unless turned off. */
|
|
73
|
+
autoContinue: z.boolean().optional(),
|
|
74
|
+
});
|
|
75
|
+
export type SessionUsageLimit = z.infer<typeof SessionUsageLimit>;
|
|
76
|
+
|
|
69
77
|
export const SessionInfo = z.object({
|
|
70
78
|
creationOrigins: z.array(z.object({ originId: z.string().min(1).max(180),
|
|
71
79
|
controllerPublicKey: z.string().min(1).max(180) }).strict()).max(32).optional(),
|
|
@@ -100,6 +108,10 @@ export const SessionInfo = z.object({
|
|
|
100
108
|
shellAllowed: z.boolean().optional(),
|
|
101
109
|
/** Held from the phone: its tool calls are refused until it is resumed. */
|
|
102
110
|
paused: z.boolean().optional(),
|
|
111
|
+
/** The turn ended while background work it started still runs; the chat resumes itself when it finishes. */
|
|
112
|
+
backgroundTasks: z.number().int().min(1).max(32).optional(),
|
|
113
|
+
/** The subscription refused the chat's last request until `resetsAt`. */
|
|
114
|
+
usageLimit: SessionUsageLimit.optional(),
|
|
103
115
|
});
|
|
104
116
|
export type SessionInfo = z.infer<typeof SessionInfo>;
|
|
105
117
|
|
|
@@ -224,6 +236,15 @@ export const SessionShellSet = z.object({
|
|
|
224
236
|
});
|
|
225
237
|
export type SessionShellSet = z.infer<typeof SessionShellSet>;
|
|
226
238
|
|
|
239
|
+
/** Whether a chat stopped by its subscription limit is continued automatically when the limit resets. */
|
|
240
|
+
export const SessionAutoContinueSet = z.object({
|
|
241
|
+
type: z.literal("session.autocontinue.set"),
|
|
242
|
+
sessionId: CapabilitySessionId,
|
|
243
|
+
enabled: z.boolean(),
|
|
244
|
+
createdAt: z.number(),
|
|
245
|
+
}).strict();
|
|
246
|
+
export type SessionAutoContinueSet = z.infer<typeof SessionAutoContinueSet>;
|
|
247
|
+
|
|
227
248
|
export const SessionCompact = z.object({
|
|
228
249
|
type: z.literal("session.compact"),
|
|
229
250
|
sessionId: z.string(),
|
|
@@ -74,6 +74,7 @@ import {
|
|
|
74
74
|
SessionMcpSet,
|
|
75
75
|
SessionSealed,
|
|
76
76
|
SessionShellSet,
|
|
77
|
+
SessionAutoContinueSet,
|
|
77
78
|
SessionSkillSet,
|
|
78
79
|
SessionsStatus,
|
|
79
80
|
SessionsHistoryQuery,
|
|
@@ -121,6 +122,8 @@ export const MachineHeartbeat = z.object({
|
|
|
121
122
|
createdAt: z.number().catch(() => Date.now()),
|
|
122
123
|
taskQueueImmediate: z.boolean().optional(),
|
|
123
124
|
taskScheduleControls: z.boolean().optional(),
|
|
125
|
+
/** Continues a chat stopped by its subscription limit when the limit resets, and takes `session.autocontinue.set`. */
|
|
126
|
+
limitAutoContinue: z.boolean().optional(),
|
|
124
127
|
taskActivityPreviews: z.boolean().optional(),
|
|
125
128
|
});
|
|
126
129
|
export type MachineHeartbeat = z.infer<typeof MachineHeartbeat>;
|
|
@@ -165,6 +168,7 @@ export const Payload = z.union([
|
|
|
165
168
|
SessionMcpSet,
|
|
166
169
|
SessionSkillSet,
|
|
167
170
|
SessionShellSet,
|
|
171
|
+
SessionAutoContinueSet,
|
|
168
172
|
SessionCompact,
|
|
169
173
|
SessionCompactResult,
|
|
170
174
|
SessionControl,
|