granttap-mcp 0.8.171 → 0.8.173
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 +7 -0
- package/apps/bridge/src/bin/runtime/monitor.ts +9 -3
- package/apps/bridge/src/monitor/handlers/user-message.ts +2 -3
- package/apps/bridge/src/monitor/message-delivery/README.md +3 -0
- package/apps/bridge/src/monitor/message-delivery/acceptance.ts +11 -1
- package/apps/bridge/src/monitor/support/runtime.ts +6 -1
- package/apps/bridge/src/provider-account-status/native-usage/memory.ts +25 -7
- package/apps/bridge/src/provider-account-status/native-usage/projection.ts +19 -0
- package/apps/bridge/src/provider-account-status/native-usage/reader.ts +9 -5
- package/apps/bridge/src/reply/in-flight.ts +13 -1
- package/apps/bridge/src/reply/index.ts +1 -1
- package/apps/bridge/src/runtime-updates/README.md +39 -4
- package/apps/bridge/src/runtime-updates/drain/index.ts +140 -0
- package/apps/bridge/src/runtime-updates/index.ts +35 -20
- package/apps/bridge/src/runtime-updates/readiness.ts +11 -5
- package/apps/bridge/src/sessions/catalog.ts +11 -1
- package/apps/bridge/src/sessions/index.ts +1 -1
- package/apps/bridge/src/sessions/scan/claude/turn-state/waits.ts +5 -1
- package/apps/bridge/src/task-dispatch/README.md +7 -0
- package/apps/bridge/src/task-dispatch/worker/index.ts +33 -10
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +8 -3
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/docs/device-management.md +3 -1
- package/package.json +1 -1
- package/packages/protocol/messages/mesh/catalog/provider.ts +2 -0
package/README.md
CHANGED
|
@@ -940,6 +940,13 @@ Verified updates are staged separately and applied after active requests and pen
|
|
|
940
940
|
decisions finish. Startup failures restore the previous version. Pairing and task
|
|
941
941
|
policies are retained; source checkouts and running provider processes stay in place.
|
|
942
942
|
|
|
943
|
+
A computer that always has a chat running is never idle on its own. When an update is
|
|
944
|
+
ready, the background monitor therefore stops starting newly arrived phone messages for
|
|
945
|
+
up to ten minutes, lets the runs already going finish, and then switches. Messages that
|
|
946
|
+
arrive meanwhile are kept and delivered by the new version; none is refused or run
|
|
947
|
+
twice. If a run outlasts the ten minutes, messages run again and the update follows
|
|
948
|
+
when that run has ended.
|
|
949
|
+
|
|
943
950
|
In the plugin's GrantTap connection card, use **Automatic updates: On / Off**.
|
|
944
951
|
The choice is saved for this computer and takes effect without restarting the
|
|
945
952
|
service. Off prevents further update checks and activation; an already running
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { startRuntimeUpdates } from "../../runtime-updates";
|
|
2
2
|
import { runtimeUpdateReadiness } from "../../runtime-updates/readiness";
|
|
3
|
+
import { UpdateDrain } from "../../runtime-updates/drain";
|
|
4
|
+
import { oldestDeliveryStartedAt } from "../../reply";
|
|
3
5
|
/** Persistent, terminal-free task sync for the GrantTap phone app on macOS. */
|
|
4
6
|
import { join } from "node:path";
|
|
5
7
|
import { RelayClient } from "../../../../../packages/core/relay-client";
|
|
@@ -33,6 +35,9 @@ let stopEngineRecovery = () => {};
|
|
|
33
35
|
let stopRuntimeUpdates = () => {};
|
|
34
36
|
let stopUpdateReadiness = () => {};
|
|
35
37
|
const stopWatchdog = startRuntimeWatchdog();
|
|
38
|
+
// Messages keep arriving, so a newer runtime cannot wait for an idle moment: queued work is held for it instead.
|
|
39
|
+
const updateDrain = new UpdateDrain({ oldestRun: oldestDeliveryStartedAt,
|
|
40
|
+
log: line => process.stderr.write(`[monitor] ${line}\n`) });
|
|
36
41
|
|
|
37
42
|
publishStableNode();
|
|
38
43
|
|
|
@@ -46,12 +51,13 @@ try {
|
|
|
46
51
|
});
|
|
47
52
|
monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1", config: cfg });
|
|
48
53
|
stopTaskDispatch = startTaskDispatchMonitor({ config: cfg, client,
|
|
49
|
-
isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish
|
|
54
|
+
isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish,
|
|
55
|
+
held: () => updateDrain.holding(), track: monitor.track });
|
|
50
56
|
stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
|
|
51
57
|
isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
|
|
52
58
|
stopEndpointPublisher = startEndpointPublisher(cfg);
|
|
53
|
-
stopRuntimeUpdates = startRuntimeUpdates(monitor.canUpdate);
|
|
54
|
-
stopUpdateReadiness = runtimeUpdateReadiness(monitor.canUpdate);
|
|
59
|
+
stopRuntimeUpdates = startRuntimeUpdates(monitor.canUpdate, updateDrain);
|
|
60
|
+
stopUpdateReadiness = runtimeUpdateReadiness(monitor.canUpdate, updateDrain);
|
|
55
61
|
} catch (error) {
|
|
56
62
|
process.stderr.write(
|
|
57
63
|
`[granttap-mcp] monitor is not paired: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
import { noteDeliveredRun } from "../../mesh/delivery/run-digest";
|
|
18
18
|
import { evaluateCreateTask } from "../../mesh/tasks/create-task";
|
|
19
19
|
import { sendSessionPayload } from "../../host/session-keys";
|
|
20
|
-
import {
|
|
20
|
+
import { deliveryTarget } from "../../sessions";
|
|
21
21
|
import { publishedSession } from "../../session-catalog";
|
|
22
22
|
import { localTaskOrigins, type TaskOriginRegistry, type TaskOriginScope } from '../../task-origins';
|
|
23
23
|
import { agentEventForUserMessage, sendDeliveryReceipt } from "./receipts";
|
|
@@ -157,8 +157,7 @@ export async function handleUserMessage(
|
|
|
157
157
|
// The catalog this monitor last published already names the chat. A full
|
|
158
158
|
// provider scan blocks the event loop for seconds on a large transcript set,
|
|
159
159
|
// so it runs only for a chat newer than that catalog.
|
|
160
|
-
const target = publishedSession(client, message.sessionId)
|
|
161
|
-
?? await findSessionCooperatively(message.sessionId, false);
|
|
160
|
+
const target = await deliveryTarget(publishedSession(client, message.sessionId), message.sessionId);
|
|
162
161
|
if (!target) return refuse("This task is no longer available on the computer.");
|
|
163
162
|
|
|
164
163
|
const settings = loadRuntimeConfig().providerSettings;
|
|
@@ -7,6 +7,9 @@ Terminal responses remain correlated to the original message id.
|
|
|
7
7
|
|
|
8
8
|
`acceptance.ts` decides when a phone message counts as delivered: when the agent
|
|
9
9
|
has taken it, not when its whole turn ends. Tests live in `tests/acceptance.test.ts`.
|
|
10
|
+
`lateRunsSettling` stays true until the answer of such a run has been sent, so a
|
|
11
|
+
runtime update cannot replace the monitor between the provider exiting and its
|
|
12
|
+
answer reaching the phone.
|
|
10
13
|
|
|
11
14
|
Integration tests: `tests/delivery/processing-receipt.test.ts`; attachment rejection
|
|
12
15
|
coverage: `tests/attachment/attachment-uploads.test.ts`. See the monitor README.
|
|
@@ -20,6 +20,15 @@ export const ACCEPTANCE_WINDOW_MS = 3_000;
|
|
|
20
20
|
/** A safety bound for an unattended turn; the person stops a run with Stop, not with a deadline. */
|
|
21
21
|
export const PHONE_RUN_LIMIT_MS = 6 * 60 * 60_000;
|
|
22
22
|
|
|
23
|
+
let settling = 0;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* True while a run that outlived its acceptance window still owes its chat the answer. The provider
|
|
27
|
+
* process ending is not the end of the turn: the answer is sent after it, and a runtime handoff in
|
|
28
|
+
* between would lose it.
|
|
29
|
+
*/
|
|
30
|
+
export function lateRunsSettling(): boolean { return settling > 0; }
|
|
31
|
+
|
|
23
32
|
export async function acceptWhenStarted<T>(
|
|
24
33
|
run: Promise<T>,
|
|
25
34
|
finish: (result: T) => Promise<unknown>,
|
|
@@ -32,6 +41,7 @@ export async function acceptWhenStarted<T>(
|
|
|
32
41
|
const first = await Promise.race([run, started]);
|
|
33
42
|
clearTimeout(timer);
|
|
34
43
|
if (first !== "started") return first;
|
|
35
|
-
|
|
44
|
+
settling += 1;
|
|
45
|
+
void run.then(finish).catch(() => {}).finally(() => { settling -= 1; });
|
|
36
46
|
return "started";
|
|
37
47
|
}
|
|
@@ -34,6 +34,7 @@ import { scanSessionHistoryCooperatively, scanSessionsCooperatively, TOKEN_WINDO
|
|
|
34
34
|
import { boundedCatalogHistory, INTERVAL_MS, publishSessionEvents } from "../handlers/catalog";
|
|
35
35
|
import { sweepAttachments } from "../handlers/receipts";
|
|
36
36
|
import { handleMonitorMessage } from "../handlers/inbound";
|
|
37
|
+
import { lateRunsSettling } from "../message-delivery/acceptance";
|
|
37
38
|
import { decorateTaskOriginCatalog } from '../../task-origins';
|
|
38
39
|
import { publishCodexQuestions } from '../../codex-questions';
|
|
39
40
|
import { publishClaudeOpenQuestions } from '../../claude-open-questions';
|
|
@@ -50,6 +51,8 @@ export type SessionMonitor = {
|
|
|
50
51
|
publish: () => Promise<void>;
|
|
51
52
|
isLeader: () => boolean;
|
|
52
53
|
canUpdate: () => boolean;
|
|
54
|
+
/** Counts work started outside the relay listener, such as a queued delivery, against `canUpdate`. */
|
|
55
|
+
track: <T>(work: () => Promise<T>) => Promise<T>;
|
|
53
56
|
close: () => void;
|
|
54
57
|
};
|
|
55
58
|
|
|
@@ -189,7 +192,8 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
|
|
|
189
192
|
let historyRead: Promise<SessionsStatus["sessions"]> | undefined;
|
|
190
193
|
let lastHistoryPublishedAt = 0;
|
|
191
194
|
let closed = false;
|
|
192
|
-
const work = runtimeWorkTracker(() => hasPendingDeliveries() ||
|
|
195
|
+
const work = runtimeWorkTracker(() => hasPendingDeliveries() || lateRunsSettling()
|
|
196
|
+
|| approvalsStatus().pending.length > 0 || providerLogins.active() || deviceManagementWorkActive());
|
|
193
197
|
const loadLoop = monitorLoadLoop(client, leadership);
|
|
194
198
|
const stopActivities = options.config ? startTaskActivities({config: options.config,
|
|
195
199
|
catalog: () => publishedCatalog(client), isLeader: () => !closed && client.isConnected && leadership.acquire()}) : () => {};
|
|
@@ -261,6 +265,7 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
|
|
|
261
265
|
publish: () => publish(false),
|
|
262
266
|
isLeader: () => leadership.acquire(),
|
|
263
267
|
canUpdate: work.idle,
|
|
268
|
+
track: work.run,
|
|
264
269
|
close: () => {
|
|
265
270
|
closed = true;
|
|
266
271
|
stopActivities();
|
|
@@ -34,6 +34,8 @@ export function isSignedOutUsage(report: ProviderAccountUsage): boolean {
|
|
|
34
34
|
/** The readings one process holds, kept in step with the other processes on the computer. */
|
|
35
35
|
export function createUsageMemory(saved: SharedUsage | undefined, clock: () => number, known: (provider: string) => boolean) {
|
|
36
36
|
const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
|
|
37
|
+
/** Limits narrower than the account, such as one model's. They are read with the account's reading and follow it. */
|
|
38
|
+
const scoped = new Map<NativeUsageProvider, ProviderAccountUsage[]>();
|
|
37
39
|
const pauses = new Map<NativeUsageProvider, number>(), failures = new Map<NativeUsageProvider, number>();
|
|
38
40
|
const notBefore = (provider: NativeUsageProvider) => {
|
|
39
41
|
let shared = -Infinity;
|
|
@@ -46,19 +48,35 @@ export function createUsageMemory(saved: SharedUsage | undefined, clock: () => n
|
|
|
46
48
|
};
|
|
47
49
|
const restore = () => {
|
|
48
50
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
51
|
+
const stored = saved?.read() ?? [];
|
|
52
|
+
for (const report of stored) {
|
|
53
|
+
const provider = report.provider as NativeUsageProvider, held = reports.get(provider);
|
|
54
|
+
if (!known(provider) || report.limitId !== provider || isSignedOutUsage(report)
|
|
55
|
+
|| (held?.observedAt ?? -Infinity) >= report.observedAt || held && isSignedOutUsage(held)) continue;
|
|
56
|
+
reports.set(provider, report);
|
|
57
|
+
scoped.set(provider, stored.filter(other => other.provider === provider && other.limitId !== provider
|
|
58
|
+
&& !isSignedOutUsage(other)).slice(0, 4));
|
|
53
59
|
}
|
|
54
60
|
} catch { /* A missing or damaged file only means nothing is remembered. */ }
|
|
55
61
|
};
|
|
62
|
+
const persist = () => {
|
|
63
|
+
const kept = [...reports.values()].filter(report => !isSignedOutUsage(report));
|
|
64
|
+
try { saved?.write([...kept, ...kept.flatMap(report => scoped.get(report.provider as NativeUsageProvider) ?? [])]); }
|
|
65
|
+
catch { /* Best effort. */ }
|
|
66
|
+
};
|
|
56
67
|
restore();
|
|
57
68
|
return {
|
|
58
69
|
reports, restore,
|
|
59
|
-
remember(): void {
|
|
60
|
-
|
|
61
|
-
|
|
70
|
+
remember(): void { restore(); persist(); },
|
|
71
|
+
/** A fresh reading names every narrower limit the provider still reports; one it dropped is not kept. */
|
|
72
|
+
setScoped(provider: NativeUsageProvider, limits: ProviderAccountUsage[]): void { scoped.set(provider, limits.slice(0, 4)); },
|
|
73
|
+
scopedFor(provider: NativeUsageProvider): ProviderAccountUsage[] {
|
|
74
|
+
const main = reports.get(provider);
|
|
75
|
+
return main && !isSignedOutUsage(main) ? scoped.get(provider) ?? [] : [];
|
|
76
|
+
},
|
|
77
|
+
/** The login is gone: its readings leave this process and the shared file, instead of coming back from it. */
|
|
78
|
+
forget(provider: NativeUsageProvider): void {
|
|
79
|
+
restore(); reports.delete(provider); scoped.delete(provider); persist();
|
|
62
80
|
},
|
|
63
81
|
/** Not while another process has just read it, or while the provider asked everyone to wait. */
|
|
64
82
|
due(provider: NativeUsageProvider, now: number): boolean {
|
|
@@ -38,6 +38,25 @@ export function projectNativeAccountUsage(provider: NativeUsageProvider, input:
|
|
|
38
38
|
return windows.length ? { provider, limitId: provider, observedAt: now, windows } : undefined;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Limits narrower than the whole account. Claude reports a weekly limit for one model beside the
|
|
43
|
+
* account-wide windows; each becomes its own report, named after the model, so the phone can show
|
|
44
|
+
* it without mistaking it for the account's limit. Only the name and the share cross the wire.
|
|
45
|
+
*/
|
|
46
|
+
export function projectScopedLimits(provider: NativeUsageProvider, input: any, now = Date.now()): ProviderAccountUsage[] {
|
|
47
|
+
if (provider !== "claude" || !Array.isArray(input?.limits)) return [];
|
|
48
|
+
const reports = new Map<string, ProviderAccountUsage>();
|
|
49
|
+
for (const limit of input.limits.slice(0, 16)) {
|
|
50
|
+
const name = typeof limit?.scope?.model?.display_name === "string" ? limit.scope.model.display_name.trim().slice(0, 40) : "";
|
|
51
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9.]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
|
|
52
|
+
const resetsAt = timestamp(limit?.resets_at);
|
|
53
|
+
if (limit?.kind !== "weekly_scoped" || !name || !slug || !percent(limit.percent) || !(resetsAt > now)) continue;
|
|
54
|
+
reports.set(slug, { provider, limitId: `${provider}:model:${slug}`, label: name, observedAt: now,
|
|
55
|
+
windows: [{ id: "secondary", usedPercent: limit.percent, windowMinutes: 10_080, resetsAt }] });
|
|
56
|
+
}
|
|
57
|
+
return [...reports.values()].slice(0, 4);
|
|
58
|
+
}
|
|
59
|
+
|
|
41
60
|
/** Older Cursor plans report a billing-period pool rather than a weekly pool. */
|
|
42
61
|
export function projectCursorPeriodUsage(input: any, now = Date.now()): ProviderAccountUsage | undefined {
|
|
43
62
|
const start = Number(input?.billingCycleStart), end = Number(input?.billingCycleEnd);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
|
|
2
|
-
import { projectCursorPeriodUsage, projectNativeAccountUsage, type NativeUsageProvider } from "./projection";
|
|
2
|
+
import { projectCursorPeriodUsage, projectNativeAccountUsage, projectScopedLimits, type NativeUsageProvider } from "./projection";
|
|
3
3
|
import { CHECK_EVERY_MS, createUsageMemory, isSignedOutUsage, signedOutUsage, type SharedUsage } from "./memory";
|
|
4
4
|
export { isSignedOutUsage, SIGNED_OUT_SUFFIX, signedOutUsage } from "./memory";
|
|
5
5
|
|
|
@@ -71,7 +71,7 @@ export function createNativeAccountUsageReader(options: Options) {
|
|
|
71
71
|
if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
|
|
72
72
|
restore();
|
|
73
73
|
note(provider, "its saved access token has expired; the provider renews it on its next run");
|
|
74
|
-
} else {
|
|
74
|
+
} else { memory.forget(provider); reasons.delete(provider); }
|
|
75
75
|
return;
|
|
76
76
|
}
|
|
77
77
|
restore();
|
|
@@ -97,8 +97,11 @@ export function createNativeAccountUsageReader(options: Options) {
|
|
|
97
97
|
});
|
|
98
98
|
report = projectCursorPeriodUsage(await boundedResponse(legacy), clock());
|
|
99
99
|
}
|
|
100
|
-
if (report) {
|
|
101
|
-
|
|
100
|
+
if (report) {
|
|
101
|
+
memory.succeeded(provider); reports.set(provider, report);
|
|
102
|
+
memory.setScoped(provider, projectScopedLimits(provider, value, report.observedAt));
|
|
103
|
+
remember();
|
|
104
|
+
} else if (response.ok) memory.forget(provider);
|
|
102
105
|
else memory.refused(provider, response);
|
|
103
106
|
note(provider, report ? undefined : response.ok ? "unrecognized response" : `HTTP ${response.status}`);
|
|
104
107
|
} catch (error) {
|
|
@@ -110,7 +113,8 @@ export function createNativeAccountUsageReader(options: Options) {
|
|
|
110
113
|
return {
|
|
111
114
|
current(): ProviderAccountUsage[] {
|
|
112
115
|
const now = clock();
|
|
113
|
-
|
|
116
|
+
const held = [...reports.values()].flatMap(report => [report, ...memory.scopedFor(report.provider as NativeUsageProvider)]);
|
|
117
|
+
return held.flatMap(report => {
|
|
114
118
|
const windows = report.windows.filter(window => window.resetsAt > now);
|
|
115
119
|
return isSignedOutUsage(report) ? (now - report.observedAt <= MARKER_MS ? [report] : [])
|
|
116
120
|
: windows.length && now - report.observedAt <= HELD_USAGE_MS ? [{ ...report, windows }] : [];
|
|
@@ -6,18 +6,30 @@ import type { ReplyResult } from "./payload/types";
|
|
|
6
6
|
* whether a run is live without loading process control.
|
|
7
7
|
*/
|
|
8
8
|
const inFlight = new Map<string, Promise<ReplyResult | null>>();
|
|
9
|
+
const startedAt = new Map<string, number>();
|
|
9
10
|
|
|
10
11
|
export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
|
|
11
12
|
|
|
12
13
|
/** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
|
|
13
14
|
export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
|
|
14
15
|
|
|
16
|
+
/**
|
|
17
|
+
* When the longest-running of those runs began; undefined when none is running. A runtime update that
|
|
18
|
+
* waited for the runs to end and gave up uses it to tell whether the run it waited for is still going.
|
|
19
|
+
*/
|
|
20
|
+
export function oldestDeliveryStartedAt(): number | undefined {
|
|
21
|
+
return startedAt.size ? Math.min(...startedAt.values()) : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
15
24
|
/** One run per key at a time; the key stays live until the provider process settles. */
|
|
16
25
|
export function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
|
|
17
26
|
const previous = inFlight.get(key) ?? Promise.resolve(null);
|
|
27
|
+
if (!inFlight.has(key)) startedAt.set(key, Date.now());
|
|
18
28
|
const next = previous.then(run);
|
|
19
29
|
const settled = next.finally(() => {
|
|
20
|
-
if (inFlight.get(key)
|
|
30
|
+
if (inFlight.get(key) !== tracked) return;
|
|
31
|
+
inFlight.delete(key);
|
|
32
|
+
startedAt.delete(key);
|
|
21
33
|
});
|
|
22
34
|
const tracked = settled.catch(() => null);
|
|
23
35
|
inFlight.set(key, tracked);
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
} from "./process/provider-headless";
|
|
25
25
|
export type { DeliveryOptions, ReplyResult } from "./payload/types";
|
|
26
26
|
export { prunePreparedAttachments } from './payload/attachments';
|
|
27
|
-
export { hasPendingDeliveries, isDeliveryInFlight } from "./in-flight";
|
|
27
|
+
export { hasPendingDeliveries, isDeliveryInFlight, oldestDeliveryStartedAt } from "./in-flight";
|
|
28
28
|
|
|
29
29
|
export const GENERAL_WORKSPACE = "granttap:general";
|
|
30
30
|
|
|
@@ -15,6 +15,39 @@ approval is pending. Existing provider processes and active stdio MCP calls keep
|
|
|
15
15
|
running. A new service that cannot start restores the previous version; that
|
|
16
16
|
failed version is quarantined until a newer release appears.
|
|
17
17
|
|
|
18
|
+
## Draining a busy monitor
|
|
19
|
+
|
|
20
|
+
Phone messages keep arriving, so a monitor in daily use may not be idle for hours.
|
|
21
|
+
`drain/index.ts` (`UpdateDrain`) gives the update a bounded way in. A busy monitor
|
|
22
|
+
starts the staged release once to verify it. If it works, the monitor stops
|
|
23
|
+
starting queued phone messages: they stay staged on this computer and unclaimed
|
|
24
|
+
on the relay. Provider runs already going are never stopped. Every five seconds
|
|
25
|
+
the monitor asks whether its work has ended; the pass that finds it ended selects
|
|
26
|
+
the release and tells the launcher, without asking the registry first. New work
|
|
27
|
+
stays held until the launcher replaces the monitor, so the new runtime delivers
|
|
28
|
+
what arrived meanwhile and no message is claimed by a process that is about to exit.
|
|
29
|
+
|
|
30
|
+
Work in flight means: a relay command or a queued delivery whose handler has not
|
|
31
|
+
returned, a provider run this monitor started, the answer of such a run that is
|
|
32
|
+
still being sent, a pending approval, a provider sign-in, or a maintenance action.
|
|
33
|
+
|
|
34
|
+
| Bound | Value |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| New messages wait in one hold | 10 minutes at most |
|
|
37
|
+
| Pause after a first hold gave up | 5 minutes, and until the runs that outlasted it have ended |
|
|
38
|
+
| Pause after a second hold in a row, or one no run outlasted | 30 minutes |
|
|
39
|
+
| Launcher replaces the monitor after being told | 2 minutes, then messages run again |
|
|
40
|
+
| A release that failed its start check is started again | after 30 minutes |
|
|
41
|
+
|
|
42
|
+
A run that lasts hours therefore delays other chats once, by ten minutes, and the
|
|
43
|
+
update follows within minutes of that run ending. The launcher's own question
|
|
44
|
+
(`granttap.runtime-update-check`, sent while a newer runtime is selected) starts the
|
|
45
|
+
same hold, so a release selected from the phone no longer waits for an idle moment
|
|
46
|
+
either. Direct relay commands are not held: a reply to a provider's question is
|
|
47
|
+
what lets a running turn end. The monitor log has one `[monitor] Update … is ready`
|
|
48
|
+
line when a hold starts, one `… still waits` line when it gives up, and one
|
|
49
|
+
`… takes over` line when the update activates.
|
|
50
|
+
|
|
18
51
|
Pairing, account credentials, task history, capability policy, and provider
|
|
19
52
|
installations are not modified by runtime updates. Offline checks retry later.
|
|
20
53
|
Source checkouts and test processes do not update themselves. The plugin's
|
|
@@ -27,9 +60,11 @@ minute tick without restarting services. Administrators may
|
|
|
27
60
|
set `GRANTTAP_DISABLE_AUTO_UPDATE=1` on their service to retain their installed
|
|
28
61
|
version. Private staging consumes space; old versions are retained for rollback.
|
|
29
62
|
|
|
30
|
-
Public entry: `startRuntimeUpdates`, `runtimeUpdateReadiness`, and the
|
|
31
|
-
`selection.mjs` / `supervision.mjs` boundary. Tests exercise failed downloads
|
|
32
|
-
verification, deferred activation, concurrent installation, selection, and startup
|
|
33
|
-
rollback using isolated directories and owned child processes.
|
|
63
|
+
Public entry: `startRuntimeUpdates`, `runtimeUpdateReadiness`, `UpdateDrain`, and the
|
|
64
|
+
launcher's `selection.mjs` / `supervision.mjs` boundary. Tests exercise failed downloads
|
|
65
|
+
and verification, deferred activation, concurrent installation, selection, and startup
|
|
66
|
+
rollback using isolated directories and owned child processes. `drain/tests` covers the
|
|
67
|
+
hold's bounds, activation while messages keep arriving, and the launcher handoff;
|
|
68
|
+
`tests/monitor/lifecycle/update-switch.test.ts` runs the whole switch with a real provider run.
|
|
34
69
|
|
|
35
70
|
License: [GrantTap Commercial Source License](../../../../LICENSE).
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** How long new phone messages may wait for the running work to end before the update gives way. */
|
|
2
|
+
export const HOLD_LIMIT_MS = 10 * 60_000;
|
|
3
|
+
/** After a first hold gave up, the messages it kept waiting get this long to start before another hold. */
|
|
4
|
+
export const HOLD_PAUSE_MS = 5 * 60_000;
|
|
5
|
+
/** After a second hold in a row gave up, or one that no provider run outlasted, the next follows after this. */
|
|
6
|
+
export const HOLD_RETRY_MS = 30 * 60_000;
|
|
7
|
+
/** The launcher replaces a monitor within seconds of being told; past this the monitor works on. */
|
|
8
|
+
export const HANDOFF_LIMIT_MS = 2 * 60_000;
|
|
9
|
+
/** How often a holding monitor asks whether its running work has ended. */
|
|
10
|
+
export const HOLD_POLL_MS = 5_000;
|
|
11
|
+
/** A staged release that failed its start check is not started again sooner than this. */
|
|
12
|
+
export const VERIFY_RETRY_MS = 30 * 60_000;
|
|
13
|
+
|
|
14
|
+
type Options = {
|
|
15
|
+
now?: () => number;
|
|
16
|
+
log?: (line: string) => void;
|
|
17
|
+
/** When the longest-running provider run of this monitor began; undefined when none is running. */
|
|
18
|
+
oldestRun?: () => number | undefined;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Lets a newer runtime take over a monitor that is never idle. Messages keep arriving, so waiting for
|
|
23
|
+
* an idle moment can take hours; instead the monitor stops starting queued work, lets what is running
|
|
24
|
+
* end, and hands over. The hold is bounded, so a run that lasts hours delays other chats once, by
|
|
25
|
+
* `HOLD_LIMIT_MS`, and the next hold waits until that run has ended. Holds that keep giving up are
|
|
26
|
+
* spaced `HOLD_RETRY_MS` apart, so messages wait at most a quarter of the time.
|
|
27
|
+
*/
|
|
28
|
+
export class UpdateDrain {
|
|
29
|
+
private since?: number;
|
|
30
|
+
private handoffAt?: number;
|
|
31
|
+
private version?: string;
|
|
32
|
+
private notBefore = 0;
|
|
33
|
+
/** Holds given up in a row for the version that is waiting. */
|
|
34
|
+
private failures = 0;
|
|
35
|
+
/** Runs still going when the last hold gave up; a new hold cannot succeed before they end. */
|
|
36
|
+
private outlastedAt?: number;
|
|
37
|
+
private passed?: string;
|
|
38
|
+
/** The release whose start check last failed, and when. */
|
|
39
|
+
private broken?: { version: string; at: number };
|
|
40
|
+
|
|
41
|
+
constructor(private readonly options: Options = {}) {}
|
|
42
|
+
|
|
43
|
+
/** New queued work waits while this is true. It stays staged on this computer and on the relay. */
|
|
44
|
+
holding(): boolean {
|
|
45
|
+
this.expire();
|
|
46
|
+
return this.since !== undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A verified newer runtime waits for a busy monitor. Returns whether new work is now held for it. */
|
|
50
|
+
request(version?: string): boolean {
|
|
51
|
+
this.expire();
|
|
52
|
+
if (this.since !== undefined) return true;
|
|
53
|
+
const now = this.now();
|
|
54
|
+
if (now < this.notBefore || this.outlasting()) return false;
|
|
55
|
+
if (version !== this.version) this.failures = 0;
|
|
56
|
+
this.since = now;
|
|
57
|
+
this.version = version;
|
|
58
|
+
this.outlastedAt = undefined;
|
|
59
|
+
this.log(`${this.label()} is ready. New phone messages wait for the running work to end, `
|
|
60
|
+
+ `${minutes(HOLD_LIMIT_MS)} min at most.`);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The update is selected and the launcher is told. Nothing new starts in a monitor about to be replaced. */
|
|
65
|
+
handoff(version?: string): void {
|
|
66
|
+
this.expire();
|
|
67
|
+
if (this.handoffAt !== undefined) return;
|
|
68
|
+
const now = this.now(), waited = this.since === undefined ? 0 : now - this.since;
|
|
69
|
+
this.handoffAt = now;
|
|
70
|
+
this.since ??= now;
|
|
71
|
+
this.version = version ?? this.version;
|
|
72
|
+
this.log(`${this.label()} takes over: the monitor restarts with it`
|
|
73
|
+
+ (waited > 0 ? `; new phone messages waited ${Math.round(waited / 1000)} s.` : '.'));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Automatic updates were turned off: nothing is waiting any more. */
|
|
77
|
+
cancel(): void {
|
|
78
|
+
if (this.since === undefined || this.handoffAt !== undefined) return;
|
|
79
|
+
this.log(`${this.label()} no longer waits: automatic updates are off. Phone messages run again.`);
|
|
80
|
+
this.since = undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Selecting the update failed, as on a full disk. The hold ends now instead of at its limit. */
|
|
84
|
+
failed(): void {
|
|
85
|
+
if (this.since === undefined || this.handoffAt !== undefined) return;
|
|
86
|
+
this.log(`${this.label()} could not be selected. Phone messages run again; the update is tried again in `
|
|
87
|
+
+ `${minutes(HOLD_RETRY_MS)} min.`);
|
|
88
|
+
this.notBefore = this.now() + HOLD_RETRY_MS;
|
|
89
|
+
this.since = undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Starts a staged release once per version, so a hold is taken only for one that works. */
|
|
93
|
+
async verified(version: string, verify: () => Promise<void>): Promise<boolean> {
|
|
94
|
+
if (this.passed === version) return true;
|
|
95
|
+
if (this.broken?.version === version && this.now() - this.broken.at < VERIFY_RETRY_MS) return false;
|
|
96
|
+
try { await verify(); }
|
|
97
|
+
catch (error) { this.broken = { version, at: this.now() }; throw error; }
|
|
98
|
+
this.passed = version;
|
|
99
|
+
this.broken = undefined;
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private expire(): void {
|
|
104
|
+
if (this.since === undefined) return;
|
|
105
|
+
const now = this.now();
|
|
106
|
+
// A clock set back would stretch either limit by as much, so time running backwards ends the hold too.
|
|
107
|
+
if (this.handoffAt !== undefined) {
|
|
108
|
+
if (within(now - this.handoffAt, HANDOFF_LIMIT_MS)) return;
|
|
109
|
+
this.log(`${this.label()} was to take over, but the monitor was not restarted in `
|
|
110
|
+
+ `${minutes(HANDOFF_LIMIT_MS)} min. Phone messages run again.`);
|
|
111
|
+
this.notBefore = now + HOLD_RETRY_MS;
|
|
112
|
+
} else {
|
|
113
|
+
if (within(now - this.since, HOLD_LIMIT_MS)) return;
|
|
114
|
+
const running = this.options.oldestRun?.() !== undefined;
|
|
115
|
+
this.failures += 1;
|
|
116
|
+
const soon = running && this.failures === 1;
|
|
117
|
+
this.outlastedAt = running ? now : undefined;
|
|
118
|
+
this.notBefore = now + (soon ? HOLD_PAUSE_MS : HOLD_RETRY_MS);
|
|
119
|
+
this.log(`${this.label()} still waits: the running work did not end in ${minutes(HOLD_LIMIT_MS)} min. `
|
|
120
|
+
+ 'Phone messages run again; the update is tried again '
|
|
121
|
+
+ (soon ? '' : `in ${minutes(HOLD_RETRY_MS)} min${running ? ' at the earliest, ' : '.'}`)
|
|
122
|
+
+ (running ? 'when the runs still going have ended.' : ''));
|
|
123
|
+
}
|
|
124
|
+
this.since = undefined;
|
|
125
|
+
this.handoffAt = undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private outlasting(): boolean {
|
|
129
|
+
if (this.outlastedAt === undefined) return false;
|
|
130
|
+
const oldest = this.options.oldestRun?.();
|
|
131
|
+
return oldest !== undefined && oldest <= this.outlastedAt;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
private label(): string { return this.version ? `Update ${this.version}` : 'The newer runtime'; }
|
|
135
|
+
private now(): number { return (this.options.now ?? Date.now)(); }
|
|
136
|
+
private log(line: string): void { this.options.log?.(line); }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function minutes(ms: number): number { return Math.round(ms / 60_000); }
|
|
140
|
+
function within(elapsed: number, limit: number): boolean { return elapsed >= 0 && elapsed < limit; }
|
|
@@ -5,11 +5,12 @@ import { configDir } from '../config/runtime/paths';
|
|
|
5
5
|
import { latestRelease, trustedRelease, installRelease, verifyRelease, type Release } from './registry';
|
|
6
6
|
import { newerVersion, readState, runtimeVersion, saveState, validRuntime, versionRoot } from './selection.mjs';
|
|
7
7
|
import { automaticUpdatesAllowed } from './preferences/storage.mjs';
|
|
8
|
+
import { HOLD_POLL_MS, type UpdateDrain } from './drain';
|
|
8
9
|
export { runtimeUpdateSettings, setRuntimeAutoUpdate } from './preferences';
|
|
9
10
|
|
|
10
11
|
type Options={root:string;stateDirectory:string;manual?:boolean;now?:()=>number;latest?:()=>Promise<unknown>;
|
|
11
12
|
idle:()=>boolean;install?:(release:Release,directory:string)=>Promise<void>;
|
|
12
|
-
verify?:(root:string)=>Promise<void>;activate?:(root:string)=>void};
|
|
13
|
+
verify?:(root:string)=>Promise<void>;activate?:(root:string)=>void;drain?:UpdateDrain};
|
|
13
14
|
|
|
14
15
|
/** An install killed mid-way (a reboot, a full disk) leaves its lock behind; ten minutes covers a real install. */
|
|
15
16
|
function removeStaleLock(lock:string,now:number):void {
|
|
@@ -17,14 +18,17 @@ function removeStaleLock(lock:string,now:number):void {
|
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
/**
|
|
20
|
-
* Stage releases independently; automatic
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
21
|
+
* Stage releases independently; automatic activation waits until no request or decision is pending. Messages
|
|
22
|
+
* keep arriving, so that moment may not come for hours. A monitor with a drain therefore starts the staged
|
|
23
|
+
* release once to verify it, then holds new work until the running work has ended; see `UpdateDrain`. Without
|
|
24
|
+
* a drain a busy check does nothing, since each one would start two Node processes. A phone's explicit update
|
|
25
|
+
* is one check, and a hung run is exactly what it may be replacing, so it verifies and selects at once; the
|
|
26
|
+
* selected version starts with the next MCP restart.
|
|
24
27
|
*/
|
|
25
28
|
export async function checkForRuntimeUpdate(options:Options):Promise<string|undefined> {
|
|
26
29
|
const allowed=()=>options.manual===true || automaticUpdatesAllowed(options.stateDirectory);
|
|
27
30
|
const ready=()=>(options.manual===true || options.idle()) && allowed();
|
|
31
|
+
const drain=options.manual===true?undefined:options.drain;
|
|
28
32
|
if(!allowed())return;
|
|
29
33
|
mkdirSync(options.stateDirectory,{recursive:true,mode:0o700});
|
|
30
34
|
const lock=join(options.stateDirectory,'install.lock');let fd:number;
|
|
@@ -40,47 +44,58 @@ export async function checkForRuntimeUpdate(options:Options):Promise<string|unde
|
|
|
40
44
|
if(!validRuntime(candidate,options.stateDirectory,release.version)) {
|
|
41
45
|
await (options.install??installRelease)(release,options.stateDirectory);
|
|
42
46
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
const verify=async()=>{
|
|
48
|
+
await (options.verify??verifyRelease)(candidate);
|
|
49
|
+
if(!validRuntime(candidate,options.stateDirectory,release.version))throw Error('Runtime verification failed');
|
|
50
|
+
};
|
|
51
|
+
if(!ready() && !(drain && allowed()))return;
|
|
52
|
+
if(drain) {if(!await drain.verified(release.version,verify))return;}
|
|
53
|
+
else await verify();
|
|
54
|
+
if(!ready()) {if(allowed())drain?.request(release.version);return;}
|
|
47
55
|
saveState(options.stateDirectory,{root:candidate,version:release.version,
|
|
48
56
|
previous:state.root?{root:state.root,version:state.version}:undefined});
|
|
57
|
+
drain?.handoff(release.version);
|
|
49
58
|
options.activate?.(candidate);return candidate;
|
|
50
59
|
} finally {closeSync(fd);unlinkSync(lock);}
|
|
51
60
|
}
|
|
52
61
|
|
|
53
62
|
type LoopOptions={root:string;directory:string;idle:()=>boolean;check?:typeof checkForRuntimeUpdate;
|
|
54
|
-
now?:()=>number;schedule?:typeof setTimeout;report?:()=>void;activate?:()=>void
|
|
63
|
+
now?:()=>number;schedule?:typeof setTimeout;report?:()=>void;activate?:()=>void;
|
|
64
|
+
latest?:()=>Promise<unknown>;drain?:UpdateDrain};
|
|
55
65
|
|
|
56
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* Check failure never stops sync; timers are owned and cancellation prevents another check. While new work is
|
|
68
|
+
* held for a staged release, a five-second pass only asks whether the running work has ended, and the pass
|
|
69
|
+
* that finds it ended selects the release it already knows instead of asking the registry first.
|
|
70
|
+
*/
|
|
57
71
|
export function runtimeUpdateLoop(options:LoopOptions):()=>void {
|
|
58
|
-
let stopped=false,timer:NodeJS.Timeout|undefined,lastCheck=0;
|
|
59
|
-
const now=options.now??Date.now,schedule=options.schedule??setTimeout;
|
|
72
|
+
let stopped=false,timer:NodeJS.Timeout|undefined,lastCheck=0,known:unknown;
|
|
73
|
+
const now=options.now??Date.now,schedule=options.schedule??setTimeout,drain=options.drain;
|
|
74
|
+
const latest=async()=>drain?.holding() && known?known:(known=await (options.latest??latestRelease)());
|
|
60
75
|
const tick=async()=>{
|
|
61
76
|
if(stopped)return;
|
|
62
77
|
try {
|
|
63
|
-
if(!automaticUpdatesAllowed(options.directory)){lastCheck=0;return;}
|
|
78
|
+
if(!automaticUpdatesAllowed(options.directory)){lastCheck=0;drain?.cancel();return;}
|
|
64
79
|
removeStaleLock(join(options.directory,'install.lock'),now());
|
|
65
|
-
if(now()-lastCheck>=4*60*60_000) {
|
|
80
|
+
if(drain?.holding()?options.idle():now()-lastCheck>=4*60*60_000) {
|
|
66
81
|
await (options.check??checkForRuntimeUpdate)({root:options.root,stateDirectory:options.directory,idle:options.idle,
|
|
67
|
-
activate:()=>options.activate?.()});
|
|
82
|
+
latest,drain,activate:()=>options.activate?.()});
|
|
68
83
|
lastCheck=options.idle()?now():0;
|
|
69
84
|
}
|
|
70
|
-
} catch {options.report?.();}
|
|
71
|
-
finally {if(!stopped){timer=schedule(()=>void tick(),60_000);timer.unref();}}
|
|
85
|
+
} catch {drain?.failed();options.report?.();}
|
|
86
|
+
finally {if(!stopped){timer=schedule(()=>void tick(),drain?.holding()?HOLD_POLL_MS:60_000);timer.unref();}}
|
|
72
87
|
};
|
|
73
88
|
timer=schedule(()=>void tick(),60_000);timer.unref();
|
|
74
89
|
return ()=>{stopped=true;if(timer)clearTimeout(timer);};
|
|
75
90
|
}
|
|
76
91
|
|
|
77
92
|
/** Only the owned installed background monitor downloads updates; source checkouts stay fixed. */
|
|
78
|
-
export function startRuntimeUpdates(idle:()=>boolean):()=>void {
|
|
93
|
+
export function startRuntimeUpdates(idle:()=>boolean,drain?:UpdateDrain):()=>void {
|
|
79
94
|
if(process.env.GRANTTAP_DISABLE_AUTO_UPDATE==='1' || process.env.GRANTTAP_LOCAL==='1'
|
|
80
95
|
|| process.env.NODE_TEST_CONTEXT || !process.send)return ()=>{};
|
|
81
96
|
const root=fileURLToPath(new URL('../../../../',import.meta.url));
|
|
82
97
|
if(!root.includes('node_modules'))return ()=>{};
|
|
83
|
-
return runtimeUpdateLoop({root,directory:join(configDir(),'runtime-updates'),idle,
|
|
98
|
+
return runtimeUpdateLoop({root,directory:join(configDir(),'runtime-updates'),idle,drain,
|
|
84
99
|
activate:()=>process.send?.({type:'granttap.runtime-update-ready'},()=>{}),
|
|
85
100
|
report:()=>process.stderr.write('[granttap-mcp] Automatic runtime update deferred; current version retained.\n')});
|
|
86
101
|
}
|
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import type { UpdateDrain } from './drain';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Only the launcher's private IPC channel can ask the owned service to drain for an update. It asks while a
|
|
5
|
+
* newer runtime is selected, so a busy monitor with a drain stops starting new work until it can answer.
|
|
6
|
+
*/
|
|
7
|
+
export function runtimeUpdateReadiness(idle:()=>boolean,drain?:Pick<UpdateDrain,'request'|'handoff'>):()=>void {
|
|
3
8
|
const listener=(message:unknown)=>{
|
|
4
|
-
if((message as {type?:string})?.type
|
|
5
|
-
|
|
6
|
-
|
|
9
|
+
if((message as {type?:string})?.type!=='granttap.runtime-update-check')return;
|
|
10
|
+
if(!idle()) {drain?.request();return;}
|
|
11
|
+
drain?.handoff();
|
|
12
|
+
process.send?.({type:'granttap.runtime-update-ready'},()=>{});
|
|
7
13
|
};
|
|
8
14
|
process.on('message',listener);
|
|
9
15
|
process.send?.({type:'granttap.runtime-healthy'},()=>{});
|
|
@@ -76,7 +76,17 @@ export async function scanSessionHistoryCooperatively(): Promise<SessionInfo[]>
|
|
|
76
76
|
export async function findSessionCooperatively(sessionId: string, includeHistory = true): Promise<SessionInfo | undefined> {
|
|
77
77
|
const catalog = catalogFromScans(await cooperativeProviderScans());
|
|
78
78
|
return liveCatalog(catalog).sessions.find(session => session.sessionId === sessionId)
|
|
79
|
-
?? (includeHistory ? historyCatalog(catalog.all).find(session => session.sessionId === sessionId)
|
|
79
|
+
?? (includeHistory ? historyCatalog(catalog.all).find(session => session.sessionId === sessionId)
|
|
80
|
+
?? catalog.all.find(session => session.sessionId === sessionId) : undefined);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The chat a phone message is for. The catalog this monitor last published is used first: a scan can
|
|
85
|
+
* take seconds. A chat missing from it is looked up among every chat on the computer, not only the
|
|
86
|
+
* ones active in the last hours: a chat left idle for days was refused as "no longer available".
|
|
87
|
+
*/
|
|
88
|
+
export async function deliveryTarget(published: SessionInfo | undefined, sessionId: string): Promise<SessionInfo | undefined> {
|
|
89
|
+
return published ?? await findSessionCooperatively(sessionId);
|
|
80
90
|
}
|
|
81
91
|
|
|
82
92
|
export function scanSessions(): { sessions: SessionInfo[]; tokensRecent: number } {
|
|
@@ -47,7 +47,7 @@ export { MAX_ACTIVITY_ENTRIES, MAX_ACTIVITY_TEXT, TOKEN_WINDOW_HOURS };
|
|
|
47
47
|
export { nativeTranscriptRoots, nativeTranscriptSource, restoreNativeTranscriptSource } from "./native-source";
|
|
48
48
|
|
|
49
49
|
export { scanSessions, scanSessionHistory, scanSessionHistoryForPaging,
|
|
50
|
-
scanSessionsCooperatively, scanSessionHistoryCooperatively, findSessionCooperatively } from "./catalog";
|
|
50
|
+
scanSessionsCooperatively, scanSessionHistoryCooperatively, findSessionCooperatively, deliveryTarget } from "./catalog";
|
|
51
51
|
import { scanSessions, scanSessionHistory } from "./catalog";
|
|
52
52
|
|
|
53
53
|
/**
|
|
@@ -7,6 +7,8 @@ export type ClaudeUsageLimit = {resetsAt: number; window?: string};
|
|
|
7
7
|
export type ClaudeWaits = {background?: Record<string, ClaudeBackgroundWork>; limit?: ClaudeUsageLimit};
|
|
8
8
|
|
|
9
9
|
const BASH_DEFAULT_MS = 600_000, LONGEST_MS = 7_200_000, MAX_TRACKED = 32;
|
|
10
|
+
/** The same hour after which the computer no longer continues a limited chat by itself. */
|
|
11
|
+
const LIMIT_STALE_MS = 3_600_000;
|
|
10
12
|
const BASH_LAUNCH = /^Command running in background with ID: ([\w-]+)/;
|
|
11
13
|
const AGENT_LAUNCH = /^Async agent launched/;
|
|
12
14
|
const AGENT_ID = /agentId: ([\w-]+)/;
|
|
@@ -89,6 +91,8 @@ export function claudeWaits(waits: ClaudeWaits, turnEnded: boolean | undefined,
|
|
|
89
91
|
{backgroundTasks?: number; usageLimit?: ClaudeUsageLimit} {
|
|
90
92
|
if (!turnEnded) return {};
|
|
91
93
|
const pending = Object.values(waits.background ?? {}).filter(work => work.until > now).length;
|
|
94
|
+
// A chat left at a limit that reset long ago is simply idle; the phone said it was "continuing" a week later.
|
|
95
|
+
const limited = waits.limit && waits.limit.resetsAt > now - LIMIT_STALE_MS ? waits.limit : undefined;
|
|
92
96
|
return {...(pending ? {backgroundTasks: Math.min(pending, 32)} : {}),
|
|
93
|
-
...(
|
|
97
|
+
...(limited ? {usageLimit: limited} : {})};
|
|
94
98
|
}
|
|
@@ -33,6 +33,13 @@ pause, an in-flight native submission and provider policy still win. Normal jobs
|
|
|
33
33
|
use a catalog observed within 60 seconds rather than rescanning all native logs
|
|
34
34
|
for every pending message on each receiver tick.
|
|
35
35
|
|
|
36
|
+
While a runtime update drains the monitor (`held`), the worker starts nothing new:
|
|
37
|
+
a job stays `staged` here and unclaimed on the relay, so the runtime that takes
|
|
38
|
+
over delivers it once. Refusals, cancellations and completions still go through. A
|
|
39
|
+
delivery counts as monitor work (`track`) from the moment it may start until its
|
|
40
|
+
handler returns, so the update never exits between a relay claim and the provider
|
|
41
|
+
taking the message. Regression case: `worker/tests/update-hold.test.ts`.
|
|
42
|
+
|
|
36
43
|
## License
|
|
37
44
|
|
|
38
45
|
Licensed under the GrantTap Commercial Source License. See LICENSE and NOTICE.
|
|
@@ -18,23 +18,39 @@ export type WorkerOptions = {
|
|
|
18
18
|
deliver: (job: TaskDispatch, beforeStart: () => Promise<void>, peer: string) => Promise<'accepted' | 'rejected'>;
|
|
19
19
|
};
|
|
20
20
|
class DeferredLaunch extends Error {}
|
|
21
|
+
const REFUSED_LOOKUP_MS = 10 * 60_000;
|
|
21
22
|
|
|
22
23
|
/** Server acceptance follows local fsync. Native submission is never replayed on a lease timer. */
|
|
23
24
|
export class TaskDispatchWorker {
|
|
24
25
|
private readonly active = new Map<string, Promise<void>>();
|
|
25
26
|
private readonly conversations = new Set<string>();
|
|
27
|
+
/** When each refused job was last looked up on the relay; it only waits there to be cancelled or to expire. */
|
|
28
|
+
private readonly refusedLookups = new Map<string, number>();
|
|
26
29
|
constructor(private readonly options: WorkerOptions) {}
|
|
27
30
|
|
|
28
|
-
async tick(): Promise<void> {
|
|
31
|
+
async tick(now = Date.now()): Promise<void> {
|
|
29
32
|
if (!this.options.connected()) return;
|
|
30
33
|
const launched: Promise<void>[] = [];
|
|
31
34
|
const records = this.options.inbox.pendingRecords().sort((a, b) =>
|
|
32
35
|
Number(b.job.deliveryMode === 'immediate') - Number(a.job.deliveryMode === 'immediate')
|
|
33
36
|
|| a.job.createdAt - b.job.createdAt);
|
|
37
|
+
const keyOf = (record: StoredTaskDispatch) => this.options.conversationKey?.(record.job, record.peerPublicKey)
|
|
38
|
+
?? record.job.sessionId ?? `new:${record.job.operation.agent ?? 'codex'}`;
|
|
39
|
+
// A refusal is final for its message. It keeps holding the follow-ups that were already queued behind
|
|
40
|
+
// it until the person cancels it; it used to hold every later message of the chat as well, for days.
|
|
41
|
+
const refusedAt = new Map<string, number>();
|
|
34
42
|
for (const record of records) {
|
|
35
|
-
if (
|
|
36
|
-
const key =
|
|
37
|
-
|
|
43
|
+
if (record.phase !== 'rejected') continue;
|
|
44
|
+
const key = keyOf(record);
|
|
45
|
+
refusedAt.set(key, Math.max(refusedAt.get(key) ?? -Infinity, record.updatedAt));
|
|
46
|
+
if (!this.active.has(record.job.jobId)) launched.push(this.settleRefused(record, now));
|
|
47
|
+
}
|
|
48
|
+
for (const record of records) {
|
|
49
|
+
if (['completed', 'cancelled', 'rejected'].includes(record.phase) || this.active.has(record.job.jobId)) continue;
|
|
50
|
+
const key = keyOf(record);
|
|
51
|
+
// Staged before the refusal: a follow-up written for the message that failed. Staged after it: the
|
|
52
|
+
// person saw the failure and sent this anyway.
|
|
53
|
+
if (record.stagedAt <= (refusedAt.get(key) ?? -Infinity)) continue;
|
|
38
54
|
if (this.conversations.has(key)) continue;
|
|
39
55
|
this.conversations.add(key);
|
|
40
56
|
const work = this.process(record).catch(error => { this.options.onError?.(error); }).finally(() => {
|
|
@@ -62,12 +78,6 @@ export class TaskDispatchWorker {
|
|
|
62
78
|
this.options.onTerminal?.(job); return;
|
|
63
79
|
}
|
|
64
80
|
const state = await remote.get(job);
|
|
65
|
-
if (record.phase === 'rejected') {
|
|
66
|
-
if (['cancelled', 'expired'].includes(state)) {
|
|
67
|
-
inbox.transition(job.jobId, 'cancelled'); inbox.retire(job.jobId);
|
|
68
|
-
}
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
81
|
if (['cancelled', 'expired'].includes(state)) { inbox.transition(job.jobId, 'cancelled'); inbox.retire(job.jobId); return; }
|
|
72
82
|
if (state === 'completed' || state === 'failed') {
|
|
73
83
|
// A server terminal state cannot authorize a new native invocation.
|
|
@@ -105,6 +115,19 @@ export class TaskDispatchWorker {
|
|
|
105
115
|
await this.finish(inbox.get(job.jobId));
|
|
106
116
|
}
|
|
107
117
|
|
|
118
|
+
/** A refused job leaves once the relay cancelled or expired it. Asking every two seconds was only load. */
|
|
119
|
+
private async settleRefused(record: StoredTaskDispatch, now: number): Promise<void> {
|
|
120
|
+
const { inbox, remote } = this.options, id = record.job.jobId;
|
|
121
|
+
if (now - (this.refusedLookups.get(id) ?? -Infinity) < REFUSED_LOOKUP_MS) return;
|
|
122
|
+
this.refusedLookups.set(id, now);
|
|
123
|
+
const work = (async () => {
|
|
124
|
+
if (!['cancelled', 'expired'].includes(await remote.get(record.job))) return;
|
|
125
|
+
inbox.transition(id, 'cancelled'); inbox.retire(id); this.refusedLookups.delete(id);
|
|
126
|
+
})().catch(error => { this.options.onError?.(error); }).finally(() => { this.active.delete(id); });
|
|
127
|
+
this.active.set(id, work);
|
|
128
|
+
await work;
|
|
129
|
+
}
|
|
130
|
+
|
|
108
131
|
private async reject(record: StoredTaskDispatch, code: string): Promise<void> {
|
|
109
132
|
const claimId = this.options.inbox.reserveClaim(record.job.jobId);
|
|
110
133
|
if (!await this.options.remote.claim(record.job, claimId)) return;
|
|
@@ -20,8 +20,13 @@ export function startTaskDispatchMonitor(input: {
|
|
|
20
20
|
config: PeerConfig; client: RelayClient; isLeader: () => boolean;
|
|
21
21
|
peerAllowed: (peer: string) => boolean; publish: () => Promise<void>;
|
|
22
22
|
remote?: TaskJobRemote; deliver?: WorkerOptions['deliver'];
|
|
23
|
+
/** True while a runtime update drains the monitor. A queued job then stays staged here and on the relay. */
|
|
24
|
+
held?: () => boolean;
|
|
25
|
+
/** Counts a delivery as monitor work until its handler returns, so an update cannot cut it off. */
|
|
26
|
+
track?: <T>(work: () => Promise<T>) => Promise<T>;
|
|
23
27
|
}): () => void {
|
|
24
28
|
const inbox = new TaskDispatchInbox(join(configDir(), 'task-dispatch'), input.config.room);
|
|
29
|
+
const track = input.track ?? (work => work());
|
|
25
30
|
const origins = localTaskOrigins();
|
|
26
31
|
const resolve = (job: Parameters<typeof resolveTaskOriginJob>[1], peer: string) =>
|
|
27
32
|
resolveTaskOriginJob(origins, job, input.config.room, peer);
|
|
@@ -45,7 +50,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
45
50
|
: state === 'failed' ? 'delivery_failed' : state === 'conflict' ? 'policy_denied' : undefined;
|
|
46
51
|
},
|
|
47
52
|
ready: (original, peer) => {
|
|
48
|
-
const job = resolve(original, peer).job;
|
|
53
|
+
const job = input.held?.() ? undefined : resolve(original, peer).job;
|
|
49
54
|
if (!job) return false;
|
|
50
55
|
const catalog = publishedCatalog(input.client);
|
|
51
56
|
const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
|
|
@@ -69,7 +74,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
69
74
|
}
|
|
70
75
|
return ready;
|
|
71
76
|
},
|
|
72
|
-
deliver:
|
|
77
|
+
deliver: (original, beforeStart, peer) => track(async () => {
|
|
73
78
|
if (original.operation.type === 'user.message' && limitContinuationUnwanted(original.operation)) return 'rejected';
|
|
74
79
|
if (input.deliver) return input.deliver(original, beforeStart, peer);
|
|
75
80
|
const job = resolve(original, peer).job;
|
|
@@ -79,7 +84,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
79
84
|
: (await handleTaskCreate(input.client, job.operation, beforeStart)).status;
|
|
80
85
|
void input.publish().catch(() => {});
|
|
81
86
|
return outcome;
|
|
82
|
-
},
|
|
87
|
+
}),
|
|
83
88
|
});
|
|
84
89
|
const reportFailure = queueFailureReporter().report;
|
|
85
90
|
const tick = () => {
|
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.173
|
|
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.173\";\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.173";
|
|
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;
|
|
@@ -12,7 +12,9 @@ The phone never marks a restart complete until it observes a new process epoch.
|
|
|
12
12
|
Explicit update uses the existing verified npm installer and rollback selection.
|
|
13
13
|
It can be requested with automatic updates off without changing that preference.
|
|
14
14
|
Activation waits for work to finish; managed macOS launch agents can then be
|
|
15
|
-
restarted from the phone.
|
|
15
|
+
restarted from the phone. With automatic updates on, the monitor holds newly queued
|
|
16
|
+
phone messages for up to ten minutes so that its running work can end and the
|
|
17
|
+
selected version can start. Development checkouts are not replaced remotely.
|
|
16
18
|
|
|
17
19
|
Cache cleanup is restricted to rebuildable repository indexes and obsolete
|
|
18
20
|
immutable MCP downloads. The running package, selected package and rollback
|
package/package.json
CHANGED
|
@@ -21,6 +21,8 @@ export type SharedSkill = z.infer<typeof SharedSkill>;
|
|
|
21
21
|
export const ProviderAccountUsage = z.object({
|
|
22
22
|
provider: MeshProvider,
|
|
23
23
|
limitId: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,159}$/),
|
|
24
|
+
/** What a limit narrower than the whole account covers, such as one model's name. Absent for the account-wide limit. */
|
|
25
|
+
label: z.string().trim().min(1).max(40).optional(),
|
|
24
26
|
observedAt: z.number().nonnegative(),
|
|
25
27
|
windows: z.array(z.object({
|
|
26
28
|
id: z.enum(["primary", "secondary"]),
|