granttap-mcp 0.8.197 → 0.8.199
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/README.md +1 -1
- package/apps/bridge/src/limit-continuation/README.md +42 -12
- package/apps/bridge/src/limit-continuation/holding.ts +134 -0
- package/apps/bridge/src/limit-continuation/index.ts +161 -117
- package/apps/bridge/src/limit-continuation/log.ts +28 -0
- package/apps/bridge/src/limit-continuation/relay-copies.ts +75 -0
- package/apps/bridge/src/limit-continuation/store.ts +52 -12
- package/apps/bridge/src/provider-model-catalog/README.md +36 -18
- package/apps/bridge/src/provider-model-catalog/claude/claude-model-cache.ts +133 -0
- package/apps/bridge/src/provider-model-catalog/claude/claude-model-memory.ts +74 -0
- package/apps/bridge/src/provider-model-catalog/{claude-models.ts → claude/claude-models.ts} +7 -64
- package/apps/bridge/src/provider-model-catalog/index.ts +1 -1
- package/apps/bridge/src/task-dispatch/sender/index.ts +8 -2
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +12 -6
- 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/apps/bridge/src/provider-model-catalog/{claude-account-scope.ts → claude/claude-account-scope.ts} +0 -0
package/README.md
CHANGED
|
@@ -73,7 +73,7 @@ service need a durable path, not npm's temporary `npx` cache.
|
|
|
73
73
|
|
|
74
74
|
## What's new
|
|
75
75
|
|
|
76
|
-
Available now, with GrantTap MCP 0.8.
|
|
76
|
+
Available now, with GrantTap MCP 0.8.199 on npm and GrantTap 1.0.2 on the App Store:
|
|
77
77
|
|
|
78
78
|
- **Phones on the connection card.** In Claude (including the Claude desktop app),
|
|
79
79
|
Codex, Cursor and Grok Build, the GrantTap card lists every phone paired with
|
|
@@ -2,9 +2,34 @@
|
|
|
2
2
|
|
|
3
3
|
Public entry: `index.ts`. When a Claude chat's last request was refused by its subscription
|
|
4
4
|
window, the published session carries `usageLimit { resetsAt, window, autoContinue }`. The
|
|
5
|
-
persistent monitor then
|
|
6
|
-
|
|
7
|
-
and offers it back like any queued phone message: the chat receives it when it is idle.
|
|
5
|
+
persistent monitor then keeps one "continue" waiting for that chat, due a minute after the reset,
|
|
6
|
+
and puts it on the relay's durable task queue. The relay holds it while this computer sleeps or the
|
|
7
|
+
phone is away, and offers it back like any queued phone message: the chat receives it when it is idle.
|
|
8
|
+
|
|
9
|
+
## Waiting
|
|
10
|
+
|
|
11
|
+
The job is written to `limit-continuation.json` first, with the exact message, and put on the relay
|
|
12
|
+
after. A relay that does not answer, a monitor restarted halfway or an update that takes over leaves
|
|
13
|
+
the next pass the same copy, sent again unchanged until the relay confirms it (`holding.ts`,
|
|
14
|
+
`relay-copies.ts`). Every copy has an id of its own. The relay keeps an id it has seen, cancelled or
|
|
15
|
+
delivered, for a week after its expiry and refuses it for another message, so a continuation queued
|
|
16
|
+
again (the chat was refused again for the same reset after it went on, or turned off and on again) is
|
|
17
|
+
a new copy. Up to 0.8.198 the id was the chat and reset alone: a chat continued early from a weekly
|
|
18
|
+
limit and refused again by the same reset days later could not be queued again, and nothing said so.
|
|
19
|
+
|
|
20
|
+
Each monitor process asks the relay about the copy due at the reset when it first sees it, hourly while
|
|
21
|
+
it waits, and every five minutes once it is due. A copy the relay no longer holds, and has not been
|
|
22
|
+
delivered, is queued again under a new id. The relay keeps a job for 30 days and the copy until a week
|
|
23
|
+
after it is due, well past Claude's longest window of 7 days.
|
|
24
|
+
|
|
25
|
+
A continuation is taken back from the relay when the person turned it off, when another limit stops
|
|
26
|
+
the chat, or when the chat went on: it works, or shows activity newer than its refusal. A chat that has
|
|
27
|
+
not moved since it was refused keeps its continuation after Claude's catalog stops showing the limit,
|
|
28
|
+
an hour after the reset, so a Mac that slept through the reset continues the chat soon after it wakes.
|
|
29
|
+
One still waiting a week after its reset expires. A limit found more than an hour after its reset with
|
|
30
|
+
no continuation waiting for it was abandoned, not waited for, and is never woken by an update.
|
|
31
|
+
|
|
32
|
+
## Going early
|
|
8
33
|
|
|
9
34
|
The window often has room before the time the refusal stated. While a continuation waits, the
|
|
10
35
|
monitor looks at Claude's account readings (`lift.ts`). It queues one more continuation, due at once,
|
|
@@ -14,19 +39,24 @@ minutes old, shows it below 98 % used, or ending more than five minutes before t
|
|
|
14
39
|
one, and a weekly limit named after one model (`seven_day_<model>`) from that model's weekly limit
|
|
15
40
|
when exactly one reading names it. `seven_day_overage_included`, other kinds, a signed-out account
|
|
16
41
|
and missing readings never go early. The early continuation is tried once per chat and reset time.
|
|
17
|
-
|
|
18
|
-
|
|
42
|
+
|
|
43
|
+
## Delivery
|
|
44
|
+
|
|
45
|
+
Only the copy the chat's job holds now is delivered, while the phone has not turned it off and the
|
|
46
|
+
newest catalog does not show the chat gone on since its refusal; anything else the relay offers is
|
|
47
|
+
refused. A delivered copy is recorded before the chat gets it. A chat its reset refuses once more after
|
|
48
|
+
it was continued waits a quarter of an hour for the next continuation.
|
|
19
49
|
|
|
20
50
|
Only Claude chats are continued. A Codex chat stopped by its usage limit carries `usageLimit
|
|
21
51
|
{ resetsAt, autoContinue: false }` (`resetsAt` from Codex's "try again at …"), so the phone says
|
|
22
|
-
"Limit reached" and when it resets; nothing is queued for it.
|
|
52
|
+
"Limit reached" and when it resets; nothing is queued for it. The phone turns it off or on per chat
|
|
53
|
+
with `session.autocontinue.set`. It is on by default.
|
|
23
54
|
|
|
24
|
-
The
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
more than an hour ago is treated as abandoned and is never woken by an update.
|
|
55
|
+
The monitor log has one line each time a continuation is queued, queued again, delivered, skipped or
|
|
56
|
+
taken back (with why), or expires, naming the chat by the start of its id and never its words
|
|
57
|
+
(`log.ts`). A state the disk cannot read stops the pass with one line and is never replaced unseen.
|
|
28
58
|
|
|
29
|
-
|
|
30
|
-
|
|
59
|
+
`limitContinuationFor` reads one chat's setting and waiting continuation for that chat's own MCP
|
|
60
|
+
status. Tests live in `tests/`; `relay-fixture.ts` keeps the relay's rules for job ids.
|
|
31
61
|
|
|
32
62
|
License: GrantTap Commercial Source License; see the repository LICENSE.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import type { ProviderAccountUsage, SessionInfo } from '../../../../packages/protocol/schema';
|
|
2
|
+
import { limitLifted } from './lift';
|
|
3
|
+
import { continuationCopy, continuationScope, type ContinuedChat } from './relay-copies';
|
|
4
|
+
import { LIMIT_CONTINUE_GRACE_MS, type LimitContinuationState, type ScheduledContinuation } from './store';
|
|
5
|
+
|
|
6
|
+
/** A chat found at a limit that reset longer ago than this was abandoned, not waiting; an update must not wake it. */
|
|
7
|
+
export const STALE_AFTER_RESET_MS = 3_600_000;
|
|
8
|
+
/** The relay keeps a copy for a week after it is due; a chat still not free to take it by then is not continued. */
|
|
9
|
+
export const KEEP_AFTER_RESET_MS = 7 * 86_400_000;
|
|
10
|
+
/** Refused again for a reset whose continuation it was already given, the chat waits this long for the next. */
|
|
11
|
+
export const REFUSED_AGAIN_MS = 15 * 60_000;
|
|
12
|
+
|
|
13
|
+
/** The account's limit readings; asked only while a queued continuation could still go early. */
|
|
14
|
+
export type UsageReadings = () => ProviderAccountUsage[];
|
|
15
|
+
/** Why a waiting continuation ends; `done` ends it without a word, as it was delivered. */
|
|
16
|
+
export type Release = 'off' | 'expired' | 'another-limit' | 'went-on' | 'done';
|
|
17
|
+
export type NamedLimit = { sessionId: string; window?: string; resetsAt: number };
|
|
18
|
+
export type TakeBack = { scope: ScheduledContinuation['scope']; ids: string[] };
|
|
19
|
+
|
|
20
|
+
export const named = (sessionId: string, job: ScheduledContinuation): NamedLimit =>
|
|
21
|
+
({ sessionId, window: job.window, resetsAt: job.resetsAt });
|
|
22
|
+
|
|
23
|
+
/** The chat a job continues, in the folder the newest catalog shows for it. */
|
|
24
|
+
export function continuedChat(sessionId: string, job: ScheduledContinuation, session?: SessionInfo): ContinuedChat {
|
|
25
|
+
return { sessionId, agent: job.scope.provider, projectId: job.scope.projectId, taskId: job.scope.taskId,
|
|
26
|
+
cwd: session?.worktree ?? session?.cwd ?? job.regular.message?.cwd };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Why a waiting continuation is no longer wanted, or `undefined` while its limit still holds the chat. A chat
|
|
31
|
+
* that has not moved since it was refused is still held after its limit left the catalog, an hour after the
|
|
32
|
+
* reset: the Mac may have slept through the reset. A chat missing from this catalog keeps its continuation.
|
|
33
|
+
*/
|
|
34
|
+
export function released(job: ScheduledContinuation, session: SessionInfo | undefined, off: boolean, now: number)
|
|
35
|
+
: Release | undefined {
|
|
36
|
+
if (off) return 'off';
|
|
37
|
+
const delivered = job.regular.deliveredAt;
|
|
38
|
+
const moved = !!session && (job.activityAt === undefined || session.lastActivityAt > job.activityAt);
|
|
39
|
+
// Delivered, it is done once the chat moved; refused again for the same reset, the chat gets a job of its own.
|
|
40
|
+
if (delivered !== undefined) return moved || now - delivered > STALE_AFTER_RESET_MS ? 'done' : undefined;
|
|
41
|
+
if (now > job.resetsAt + LIMIT_CONTINUE_GRACE_MS + KEEP_AFTER_RESET_MS) return 'expired';
|
|
42
|
+
if (!session) return undefined;
|
|
43
|
+
const limit = session.usageLimit;
|
|
44
|
+
if (limit?.resetsAt === job.resetsAt) return undefined;
|
|
45
|
+
if (!limit && session.state === 'idle' && !moved) return undefined;
|
|
46
|
+
return limit ? 'another-limit' : 'went-on';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What a look at a chat its limit still holds adds: when it was queued, for older jobs, and its latest refusal. */
|
|
50
|
+
function note(job: ScheduledContinuation, session: SessionInfo, now: number): boolean {
|
|
51
|
+
let changed = false;
|
|
52
|
+
// A job queued before its time was recorded counts from now, so no older reading speaks for it.
|
|
53
|
+
if (job.scheduledAt === undefined) { job.scheduledAt = now; changed = true; }
|
|
54
|
+
if (session.lastActivityAt > (job.activityAt ?? -Infinity)) { job.activityAt = session.lastActivityAt; changed = true; }
|
|
55
|
+
if (!job.window && session.usageLimit?.window) { job.window = session.usageLimit.window; changed = true; }
|
|
56
|
+
return changed;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Ends the continuations no longer wanted; their copies still undelivered are to be taken back from the relay. */
|
|
60
|
+
export function settle(state: LimitContinuationState, byId: Map<string, SessionInfo>, now: number,
|
|
61
|
+
report: (limit: NamedLimit, release: Release) => void): { changed: boolean; takeBack: TakeBack[] } {
|
|
62
|
+
let changed = false;
|
|
63
|
+
const takeBack: TakeBack[] = [];
|
|
64
|
+
for (const [sessionId, job] of Object.entries(state.scheduled)) {
|
|
65
|
+
const session = byId.get(sessionId);
|
|
66
|
+
const release = released(job, session, state.off.includes(sessionId), now);
|
|
67
|
+
if (release === undefined) {
|
|
68
|
+
if (session?.usageLimit?.resetsAt === job.resetsAt && note(job, session, now)) changed = true;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
takeBack.push({ scope: job.scope, ids: [job.regular, job.early]
|
|
72
|
+
.flatMap(copy => copy && copy.deliveredAt === undefined ? [copy.messageId] : []) });
|
|
73
|
+
delete state.scheduled[sessionId]; changed = true;
|
|
74
|
+
report(named(sessionId, job), release);
|
|
75
|
+
}
|
|
76
|
+
for (const record of [state.tried ?? {}, state.continued ?? {}] as Record<string, number | { resetsAt: number }>[]) {
|
|
77
|
+
for (const [sessionId, value] of Object.entries(record)) {
|
|
78
|
+
if ((typeof value === 'number' ? value : value.resetsAt) > now - STALE_AFTER_RESET_MS) continue;
|
|
79
|
+
delete record[sessionId]; changed = true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return { changed, takeBack };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Records a job for every Claude chat a limit stopped that has none, due a minute after the reset. A chat
|
|
87
|
+
* refused again for a reset whose continuation it was given waits a little more, so a provider whose
|
|
88
|
+
* window opens late is not asked again every half minute.
|
|
89
|
+
*/
|
|
90
|
+
export function addJobs(state: LimitContinuationState, sessions: SessionInfo[], now: number,
|
|
91
|
+
skipped: (limit: NamedLimit) => void): boolean {
|
|
92
|
+
let changed = false;
|
|
93
|
+
for (const session of sessions) {
|
|
94
|
+
const limit = session.usageLimit, sessionId = session.sessionId;
|
|
95
|
+
if (!limit || session.agent !== 'claude' || session.state !== 'idle' || state.scheduled[sessionId]) continue;
|
|
96
|
+
if (limit.resetsAt <= now - STALE_AFTER_RESET_MS) continue;
|
|
97
|
+
if (state.off.includes(sessionId)) { skipped({ sessionId, window: limit.window, resetsAt: limit.resetsAt }); continue; }
|
|
98
|
+
const given = state.continued?.[sessionId];
|
|
99
|
+
const notBefore = Math.max(now, limit.resetsAt + LIMIT_CONTINUE_GRACE_MS,
|
|
100
|
+
given?.resetsAt === limit.resetsAt ? given.at + REFUSED_AGAIN_MS : 0);
|
|
101
|
+
const chat: ContinuedChat = { sessionId, agent: session.agent, projectId: session.projectId, taskId: session.taskId,
|
|
102
|
+
cwd: session.worktree ?? session.cwd };
|
|
103
|
+
state.scheduled[sessionId] = { resetsAt: limit.resetsAt, ...(limit.window ? { window: limit.window } : {}),
|
|
104
|
+
scope: continuationScope(chat), scheduledAt: now, activityAt: session.lastActivityAt,
|
|
105
|
+
regular: continuationCopy(chat, limit.resetsAt, now, notBefore, false) };
|
|
106
|
+
changed = true;
|
|
107
|
+
}
|
|
108
|
+
return changed;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Records a second continuation, due at once, for a limited chat whose window the account's readings show has
|
|
113
|
+
* room again before its reset. It is tried once per limit; the one due at the reset stays.
|
|
114
|
+
*/
|
|
115
|
+
export function continueEarly(state: LimitContinuationState, byId: Map<string, SessionInfo>, now: number,
|
|
116
|
+
readings: UsageReadings): boolean {
|
|
117
|
+
const waiting = Object.entries(state.scheduled).flatMap(([sessionId, job]) => {
|
|
118
|
+
const session = byId.get(sessionId);
|
|
119
|
+
// A job queued this moment has no reading taken after it yet.
|
|
120
|
+
return session?.usageLimit?.resetsAt === job.resetsAt && job.scheduledAt !== undefined && job.scheduledAt < now
|
|
121
|
+
&& !job.early && state.tried?.[sessionId] !== job.resetsAt && now < job.resetsAt ? [{ sessionId, session, job }] : [];
|
|
122
|
+
});
|
|
123
|
+
if (!waiting.length) return false;
|
|
124
|
+
let usage: ProviderAccountUsage[] = [], changed = false;
|
|
125
|
+
// Unreadable limits only mean nothing goes early.
|
|
126
|
+
try { usage = readings(); } catch { /* No readings. */ }
|
|
127
|
+
for (const { sessionId, session, job } of waiting) {
|
|
128
|
+
if (!limitLifted(session.usageLimit!, job.scheduledAt!, usage, now)) continue;
|
|
129
|
+
job.early = continuationCopy(continuedChat(sessionId, job, session), job.resetsAt, now, now, true);
|
|
130
|
+
(state.tried ??= {})[sessionId] = job.resetsAt;
|
|
131
|
+
changed = true;
|
|
132
|
+
}
|
|
133
|
+
return changed;
|
|
134
|
+
}
|
|
@@ -1,161 +1,205 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import type { SessionInfo, UserMessage } from '../../../../packages/protocol/schema';
|
|
2
|
+
import { addJobs, continueEarly, continuedChat, named, released, settle, type NamedLimit, type Release,
|
|
3
|
+
type TakeBack, type UsageReadings } from './holding';
|
|
4
|
+
import { logContinuation, logContinuationsFailure, logTime } from './log';
|
|
5
|
+
import { continuationCopy, failureReason, isLimitContinuation, putOnRelay, relayHolds,
|
|
6
|
+
type ContinuationQueue } from './relay-copies';
|
|
7
|
+
import { readLimitContinuationState, writeLimitContinuationState, type ContinuationCopy, type LimitContinuationState,
|
|
6
8
|
type ScheduledContinuation } from './store';
|
|
7
9
|
|
|
8
10
|
export { LIFT_BELOW_PERCENT, LIFT_READING_MAX_AGE_MS } from './lift';
|
|
11
|
+
export { LIMIT_CONTINUE_PROMPT, LIMIT_ROOM_PROMPT, type ContinuationQueue } from './relay-copies';
|
|
12
|
+
export { LIMIT_CONTINUE_GRACE_MS } from './store';
|
|
13
|
+
export type { UsageReadings } from './holding';
|
|
9
14
|
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
'GrantTap: the subscription limit that stopped this chat has room again. Continue the work from where you stopped.';
|
|
16
|
-
/** The provider's clock and ours differ a little; arriving just before the reset would hit the limit again. */
|
|
17
|
-
export const LIMIT_CONTINUE_GRACE_MS = 60_000;
|
|
18
|
-
/** A chat left at a limit that reset longer ago than this was abandoned, not waiting; an update must not wake it. */
|
|
19
|
-
const STALE_AFTER_RESET_MS = 3_600_000;
|
|
20
|
-
const PREFIX = 'limit-continue-';
|
|
21
|
-
const EARLY_PREFIX = `${PREFIX}early-`;
|
|
22
|
-
|
|
23
|
-
export type ContinuationQueue = {
|
|
24
|
-
submit: (scope: NativeQueueScope, message: UserMessage, notBefore: number, createdAt: number) => Promise<unknown>;
|
|
25
|
-
cancel: (scope: NativeQueueScope, id: string) => Promise<unknown>;
|
|
26
|
-
};
|
|
27
|
-
/** The account's limit readings; asked only while a queued continuation could still go early. */
|
|
28
|
-
export type UsageReadings = () => ProviderAccountUsage[];
|
|
15
|
+
/** How often a copy on the relay is looked up: hourly while it waits, every five minutes once it is due. */
|
|
16
|
+
const LOOKUP_WAITING_MS = 3_600_000, LOOKUP_DUE_MS = 300_000;
|
|
17
|
+
const RELEASED: Record<Release, string> = { off: 'turned off on the phone', 'went-on': 'the chat went on',
|
|
18
|
+
'another-limit': 'another limit stops the chat now', expired: 'the chat was not free to take it in the 7 days after the reset',
|
|
19
|
+
done: 'it was delivered' };
|
|
29
20
|
|
|
21
|
+
/** What one monitor process remembers between catalogs: lookups, lines already logged, the pass running. */
|
|
22
|
+
type Memory = { lookedUp: Map<string, number>; logged: Set<string>; running?: Promise<void> };
|
|
23
|
+
/** One pass over a catalog: the relay queue it uses, its monitor's memory and the time it runs at. */
|
|
24
|
+
type Pass = { queue: ContinuationQueue; memory: Memory; now: number };
|
|
25
|
+
const memories = new WeakMap<ContinuationQueue, Memory>();
|
|
30
26
|
let registered: ContinuationQueue | undefined;
|
|
27
|
+
|
|
31
28
|
/** Only the persistent monitor owns the durable relay queue; session MCPs never schedule. */
|
|
32
29
|
export function registerLimitContinuationQueue(queue: ContinuationQueue | undefined): void { registered = queue; }
|
|
33
30
|
|
|
34
31
|
export function setAutoContinue(sessionId: string, enabled: boolean): void {
|
|
32
|
+
update(state => {
|
|
33
|
+
state.off = enabled ? state.off.filter(id => id !== sessionId) : [...state.off, sessionId];
|
|
34
|
+
return true;
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Changes the saved state in one step: nothing else in this process runs between its read and its write. */
|
|
39
|
+
function update(change: (state: LimitContinuationState) => boolean): void {
|
|
35
40
|
const state = readLimitContinuationState();
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
if (change(state)) writeLimitContinuationState(state);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function savedState(): LimitContinuationState {
|
|
45
|
+
try { return readLimitContinuationState(); } catch { return { off: [], scheduled: {} }; }
|
|
38
46
|
}
|
|
39
47
|
|
|
40
48
|
/**
|
|
41
49
|
* The phone shows whether a limited chat will go on by itself; that is the default for Claude. Only
|
|
42
|
-
* Claude chats are continued
|
|
50
|
+
* Claude chats are continued, so another agent's limited chat says it will not be.
|
|
43
51
|
*/
|
|
44
52
|
export function annotateLimitContinuations(sessions: SessionInfo[]): SessionInfo[] {
|
|
45
53
|
if (!sessions.some(session => session.usageLimit)) return sessions;
|
|
46
|
-
const off = new Set(
|
|
54
|
+
const off = new Set(savedState().off);
|
|
47
55
|
return sessions.map(session => session.usageLimit ? { ...session, usageLimit: { ...session.usageLimit,
|
|
48
56
|
autoContinue: session.agent === 'claude' && !off.has(session.sessionId) } } : session);
|
|
49
57
|
}
|
|
50
58
|
|
|
51
59
|
/**
|
|
52
60
|
* For the chat itself: whether it goes on by itself after a subscription limit stopped it, and the
|
|
53
|
-
* continuation
|
|
54
|
-
*
|
|
61
|
+
* continuation waiting for it at one. `early` says a second one was queued to go at once because the
|
|
62
|
+
* account's readings showed room before the reset. Read only.
|
|
55
63
|
*/
|
|
56
64
|
export function limitContinuationFor(sessionId: string): { autoContinue: boolean; continuation?: { dueAt: number; early: boolean } } {
|
|
57
|
-
const state =
|
|
65
|
+
const state = savedState(), job = state.scheduled[sessionId];
|
|
58
66
|
return { autoContinue: !state.off.includes(sessionId),
|
|
59
|
-
...(job ? { continuation: { dueAt: Math.max(job.scheduledAt ?? 0, job.
|
|
67
|
+
...(job ? { continuation: { dueAt: Math.max(job.scheduledAt ?? 0, job.regular.notBefore), early: !!job.early } } : {}) };
|
|
60
68
|
}
|
|
61
69
|
|
|
62
|
-
function
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
70
|
+
function memoryOf(queue: ContinuationQueue): Memory {
|
|
71
|
+
let memory = memories.get(queue);
|
|
72
|
+
if (!memory) memories.set(queue, memory = { lookedUp: new Map(), logged: new Set() });
|
|
73
|
+
return memory;
|
|
66
74
|
}
|
|
67
75
|
|
|
68
|
-
function
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const scope: NativeQueueScope = { sessionId: session.sessionId, provider: CodingAgent.parse(session.agent),
|
|
73
|
-
...(session.projectId ? { projectId: session.projectId } : {}), ...(session.taskId ? { taskId: session.taskId } : {}) };
|
|
74
|
-
const cwd = session.worktree ?? session.cwd;
|
|
75
|
-
const message = UserMessage.parse({ type: 'user.message', messageId, sessionId: session.sessionId, agent: session.agent,
|
|
76
|
-
text: early ? LIMIT_ROOM_PROMPT : LIMIT_CONTINUE_PROMPT, createdAt: now, ...(cwd ? { cwd } : {}),
|
|
77
|
-
...(session.projectId ? { projectId: session.projectId } : {}) });
|
|
78
|
-
return { job: { resetsAt, messageId, scope, scheduledAt: now }, message };
|
|
76
|
+
function logOnce(memory: Memory, key: string, limit: NamedLimit, event: string): void {
|
|
77
|
+
if (memory.logged.has(key)) return;
|
|
78
|
+
memory.logged.add(key);
|
|
79
|
+
logContinuation(limit, event);
|
|
79
80
|
}
|
|
80
81
|
|
|
81
|
-
/**
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
82
|
+
/**
|
|
83
|
+
* Keeps one "continue" waiting for every Claude chat its subscription stopped, due a minute after the reset,
|
|
84
|
+
* and takes it back when the chat went on by itself or the person turned it off. The job is written down
|
|
85
|
+
* here first and put on the relay after, so a failed upload, a restart or an update takeover leaves the
|
|
86
|
+
* next pass the same copy to send. The relay holds it while this computer sleeps; a copy the relay no longer
|
|
87
|
+
* holds is queued again under a new id. When the account's readings show room sooner, one more goes at once.
|
|
88
|
+
*/
|
|
89
|
+
export function scheduleLimitContinuations(sessions: SessionInfo[], queue = registered, now = Date.now(),
|
|
90
|
+
readings: UsageReadings = () => []): Promise<void> {
|
|
91
|
+
if (!queue) return Promise.resolve();
|
|
92
|
+
const memory = memoryOf(queue);
|
|
93
|
+
// A catalog comes every 30 s and a pass may wait on the relay; one pass at a time keeps one copy per limit.
|
|
94
|
+
if (memory.running) return memory.running;
|
|
95
|
+
const running = continuationPass(sessions, queue, memory, now, readings).catch(error => {
|
|
96
|
+
const reason = failureReason(error);
|
|
97
|
+
if (!memory.logged.has(`state:${reason}`)) { memory.logged.add(`state:${reason}`); logContinuationsFailure(reason); }
|
|
98
|
+
}).finally(() => { memory.running = undefined; });
|
|
99
|
+
memory.running = running;
|
|
100
|
+
return running;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function continuationPass(sessions: SessionInfo[], queue: ContinuationQueue, memory: Memory, now: number,
|
|
104
|
+
readings: UsageReadings): Promise<void> {
|
|
105
|
+
const byId = new Map(sessions.map(session => [session.sessionId, session]));
|
|
106
|
+
let takeBack: TakeBack[] = [];
|
|
107
|
+
update(state => {
|
|
108
|
+
const settled = settle(state, byId, now, (limit, release) => {
|
|
109
|
+
if (release !== 'done') logContinuation(limit, release === 'expired' ? `expired: ${RELEASED.expired}` : `taken back: ${RELEASED[release]}`);
|
|
110
|
+
});
|
|
111
|
+
takeBack = settled.takeBack;
|
|
112
|
+
const added = addJobs(state, sessions, now, limit =>
|
|
113
|
+
logOnce(memory, `off:${limit.sessionId}:${limit.resetsAt}`, limit, `skipped: ${RELEASED.off}`));
|
|
114
|
+
return settled.changed || added;
|
|
115
|
+
});
|
|
116
|
+
for (const { scope, ids } of takeBack) for (const id of ids) await queue.cancel(scope, id).catch(() => {});
|
|
117
|
+
update(state => continueEarly(state, byId, now, readings));
|
|
118
|
+
const pass: Pass = { queue, memory, now };
|
|
119
|
+
for (const [sessionId, job] of Object.entries(readLimitContinuationState().scheduled)) {
|
|
120
|
+
for (const copy of [job.early, job.regular]) {
|
|
121
|
+
if (!copy || copy.deliveredAt !== undefined) continue;
|
|
122
|
+
if (!copy.onRelay) await send(pass, sessionId, job, copy);
|
|
123
|
+
else if (copy === job.regular) await lookUp(pass, sessionId, job, byId.get(sessionId));
|
|
124
|
+
}
|
|
97
125
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function copyIn(state: LimitContinuationState, sessionId: string, messageId: string | undefined): ContinuationCopy | undefined {
|
|
129
|
+
const job = state.scheduled[sessionId];
|
|
130
|
+
return job && [job.regular, job.early].find(copy => copy?.messageId === messageId);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function send({ queue, memory, now }: Pass, sessionId: string, job: ScheduledContinuation,
|
|
134
|
+
copy: ContinuationCopy): Promise<void> {
|
|
135
|
+
const failure = await putOnRelay(queue, job.scope, copy);
|
|
136
|
+
if (failure) {
|
|
137
|
+
return logOnce(memory, `unsent:${copy.messageId}`, named(sessionId, job),
|
|
138
|
+
`not on the relay yet (${failure}); it is tried again with the next catalog`);
|
|
101
139
|
}
|
|
102
|
-
|
|
140
|
+
memory.lookedUp.set(copy.messageId, now);
|
|
141
|
+
let confirmed = false;
|
|
142
|
+
update(state => {
|
|
143
|
+
const saved = copyIn(state, sessionId, copy.messageId);
|
|
144
|
+
if (saved && !saved.onRelay) saved.onRelay = confirmed = true;
|
|
145
|
+
return confirmed;
|
|
146
|
+
});
|
|
147
|
+
if (confirmed) logContinuation(named(sessionId, job), copy === job.early
|
|
148
|
+
? "queued to go at once: the account's readings show room" : `queued, due ${logTime(copy.notBefore)}`);
|
|
103
149
|
}
|
|
104
150
|
|
|
105
|
-
/**
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
151
|
+
/** Asks the relay, now and then, whether it still holds the copy due at the reset; queues a new one if not. */
|
|
152
|
+
async function lookUp(pass: Pass, sessionId: string, job: ScheduledContinuation, session: SessionInfo | undefined)
|
|
153
|
+
: Promise<void> {
|
|
154
|
+
const { queue, memory, now } = pass, copy = job.regular, last = memory.lookedUp.get(copy.messageId);
|
|
155
|
+
if (last !== undefined && now >= last && now - last < (now >= copy.notBefore ? LOOKUP_DUE_MS : LOOKUP_WAITING_MS)) return;
|
|
156
|
+
const held = await relayHolds(queue, job.scope, copy);
|
|
157
|
+
if (!held) return;
|
|
158
|
+
memory.lookedUp.set(copy.messageId, now);
|
|
159
|
+
if (held.holds) return;
|
|
160
|
+
let replacement: ContinuationCopy | undefined;
|
|
161
|
+
update(state => {
|
|
162
|
+
const current = state.scheduled[sessionId];
|
|
163
|
+
if (current?.regular.messageId !== copy.messageId || current.regular.deliveredAt !== undefined) return false;
|
|
164
|
+
replacement = current.regular = continuationCopy(continuedChat(sessionId, current, session), current.resetsAt, now,
|
|
165
|
+
Math.max(now, copy.notBefore), false);
|
|
166
|
+
return true;
|
|
117
167
|
});
|
|
118
|
-
if (!
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
try { usage = readings(); } catch { /* No readings. */ }
|
|
122
|
-
for (const { session, job, at } of waiting) {
|
|
123
|
-
if (!limitLifted(session.usageLimit!, at, usage, now)) continue;
|
|
124
|
-
const { message } = continuation(session, now, true), tried = state.tried ??= {};
|
|
125
|
-
// It is due at once, so delivery must already find it wanted.
|
|
126
|
-
job.early = message.messageId; tried[session.sessionId] = job.resetsAt; changed = true;
|
|
127
|
-
writeLimitContinuationState(state);
|
|
128
|
-
try { await queue.submit(job.scope, message, now, now); }
|
|
129
|
-
catch (error) { delete job.early; delete tried[session.sessionId]; writeLimitContinuationState(state); throw error; }
|
|
130
|
-
}
|
|
131
|
-
return changed;
|
|
168
|
+
if (!replacement) return;
|
|
169
|
+
logContinuation(named(sessionId, job), `re-queued: the relay no longer held it (${held.state})`);
|
|
170
|
+
await send(pass, sessionId, { ...job, regular: replacement }, replacement);
|
|
132
171
|
}
|
|
133
172
|
|
|
134
173
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
137
|
-
*
|
|
138
|
-
* room again sooner, one more goes at once.
|
|
174
|
+
* Decides at delivery whether a continuation the relay hands back goes to the chat: only the copy its job
|
|
175
|
+
* holds now, while the phone has not turned it off and, by `current` (the chat in the newest catalog), the
|
|
176
|
+
* chat has not gone on since it was refused. One that goes is recorded and logged as delivered first.
|
|
139
177
|
*/
|
|
140
|
-
export
|
|
141
|
-
|
|
142
|
-
if (!
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
178
|
+
export function limitContinuationUnwanted(message: UserMessage, current?: () => SessionInfo | undefined,
|
|
179
|
+
now = Date.now()): boolean {
|
|
180
|
+
if (!isLimitContinuation(message)) return false;
|
|
181
|
+
const sessionId = message.sessionId!, session = current?.();
|
|
182
|
+
let refusal: string | undefined, delivered: { job: ScheduledContinuation; early: boolean } | undefined;
|
|
183
|
+
try {
|
|
184
|
+
update(state => {
|
|
185
|
+
const job = state.scheduled[sessionId], copy = copyIn(state, sessionId, message.messageId);
|
|
186
|
+
const release = job && session ? released(job, session, false, now) : undefined;
|
|
187
|
+
refusal = state.off.includes(sessionId) ? RELEASED.off : !job || !copy ? 'a newer copy replaced it, or the chat went on'
|
|
188
|
+
: release !== undefined && copy.deliveredAt === undefined ? RELEASED[release] : undefined;
|
|
189
|
+
if (refusal || copy!.deliveredAt !== undefined) return false;
|
|
190
|
+
copy!.deliveredAt = now;
|
|
191
|
+
if (copy === job!.regular) (state.continued ??= {})[sessionId] = { resetsAt: job!.resetsAt, at: now };
|
|
192
|
+
delivered = { job: job!, early: copy !== job!.regular };
|
|
193
|
+
return true;
|
|
194
|
+
});
|
|
195
|
+
} catch (error) { refusal = `its state could not be read or saved (${failureReason(error)})`; }
|
|
196
|
+
const job = delivered?.job ?? savedState().scheduled[sessionId];
|
|
197
|
+
const limit = job ? named(sessionId, job) : { sessionId };
|
|
198
|
+
if (refusal) logContinuation(limit, `skipped at delivery: ${refusal}`);
|
|
199
|
+
else if (delivered) {
|
|
200
|
+
const after = Math.round((now - delivered.job.resetsAt) / 60_000);
|
|
201
|
+
logContinuation(limit, delivered.early ? "delivered early: the account's readings showed room"
|
|
202
|
+
: `delivered${after > 0 ? `, ${after} min after the reset` : ''}`);
|
|
151
203
|
}
|
|
152
|
-
|
|
153
|
-
if (changed) writeLimitContinuationState(state);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** A continuation the relay hands back after the person turned it off, or for a limit since lifted, is not delivered. */
|
|
157
|
-
export function limitContinuationUnwanted(message: UserMessage): boolean {
|
|
158
|
-
if (!message.messageId?.startsWith(PREFIX) || !message.sessionId) return false;
|
|
159
|
-
const state = readLimitContinuationState(), job = state.scheduled[message.sessionId];
|
|
160
|
-
return state.off.includes(message.sessionId) || (job?.messageId !== message.messageId && job?.early !== message.messageId);
|
|
204
|
+
return refusal !== undefined;
|
|
161
205
|
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Which limit stopped the chat, as a person reads it. */
|
|
2
|
+
function windowName(window: string | undefined): string {
|
|
3
|
+
if (window === 'five_hour') return '5-hour limit';
|
|
4
|
+
if (window === 'seven_day') return 'weekly limit';
|
|
5
|
+
const model = /^seven_day_([a-z0-9]+)$/.exec(window ?? '')?.[1];
|
|
6
|
+
return model ? `weekly ${model} limit` : window ? `${window} limit` : 'subscription limit';
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A time in the monitor log: UTC to the minute, the way the relay schedules it. */
|
|
10
|
+
export function logTime(at: number): string {
|
|
11
|
+
return `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* One line in the monitor log for a continuation that was queued, queued again, delivered, skipped or
|
|
16
|
+
* expired. It names the chat by the start of its id and the limit by its kind, never the chat's words.
|
|
17
|
+
*/
|
|
18
|
+
export function logContinuation(limit: { sessionId: string; window?: string; resetsAt?: number }, event: string): void {
|
|
19
|
+
const which = limit.resetsAt === undefined ? ''
|
|
20
|
+
: ` after its ${windowName(limit.window)} (reset ${logTime(limit.resetsAt)})`;
|
|
21
|
+
process.stderr.write(`[monitor] Continuation of chat ${limit.sessionId.slice(0, 8)}${which}: ${event}.\n`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The saved continuations could not be read or written; nothing was queued or taken back this time. */
|
|
25
|
+
export function logContinuationsFailure(reason: string): void {
|
|
26
|
+
process.stderr.write(`[monitor] Continuations after subscription limits wait: their state could not be read or saved`
|
|
27
|
+
+ ` (${reason}); tried again with the next catalog.\n`);
|
|
28
|
+
}
|