granttap-mcp 0.8.200 → 0.8.201

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.
Files changed (59) hide show
  1. package/README.md +13 -1
  2. package/apps/bridge/src/bin/runtime/monitor.ts +5 -0
  3. package/apps/bridge/src/context-compaction/README.md +56 -0
  4. package/apps/bridge/src/context-compaction/claude.ts +69 -0
  5. package/apps/bridge/src/context-compaction/index.ts +164 -0
  6. package/apps/bridge/src/context-compaction/store.ts +71 -0
  7. package/apps/bridge/src/context-compaction/trigger.ts +92 -0
  8. package/apps/bridge/src/limit-continuation/README.md +5 -0
  9. package/apps/bridge/src/limit-continuation/index.ts +18 -2
  10. package/apps/bridge/src/limit-continuation/log.ts +2 -2
  11. package/apps/bridge/src/limit-queue-hold/README.md +59 -0
  12. package/apps/bridge/src/limit-queue-hold/decision.ts +83 -0
  13. package/apps/bridge/src/limit-queue-hold/index.ts +108 -0
  14. package/apps/bridge/src/limit-queue-hold/log.ts +44 -0
  15. package/apps/bridge/src/limit-queue-hold/readings.ts +19 -0
  16. package/apps/bridge/src/limit-queue-hold/store.ts +44 -0
  17. package/apps/bridge/src/monitor/catalog-follow-ups.ts +20 -0
  18. package/apps/bridge/src/monitor/handlers/inbound.ts +3 -1
  19. package/apps/bridge/src/monitor/handlers/session-commands.ts +10 -4
  20. package/apps/bridge/src/monitor/support/heartbeat.ts +2 -2
  21. package/apps/bridge/src/monitor/support/runtime.ts +7 -12
  22. package/apps/bridge/src/sessions/context-usage/compactions.ts +76 -0
  23. package/apps/bridge/src/sessions/scan/claude/activity.ts +8 -0
  24. package/apps/bridge/src/sessions/scan/claude/parse.ts +10 -0
  25. package/apps/bridge/src/sessions/scan/claude/turn-state/index.ts +29 -1
  26. package/apps/bridge/src/sessions/scan/codex/parse.ts +6 -0
  27. package/apps/bridge/src/task-automations/README.md +56 -0
  28. package/apps/bridge/src/task-automations/cadence/README.md +18 -0
  29. package/apps/bridge/src/task-automations/cadence/cron.ts +85 -0
  30. package/apps/bridge/src/task-automations/cadence/index.ts +63 -0
  31. package/apps/bridge/src/task-automations/controls/changes.ts +110 -0
  32. package/apps/bridge/src/task-automations/controls/index.ts +80 -0
  33. package/apps/bridge/src/task-automations/controls/relay.ts +46 -0
  34. package/apps/bridge/src/task-automations/index.ts +4 -0
  35. package/apps/bridge/src/task-automations/log.ts +14 -0
  36. package/apps/bridge/src/task-automations/runner/index.ts +103 -0
  37. package/apps/bridge/src/task-automations/runner/monitor.ts +77 -0
  38. package/apps/bridge/src/task-automations/runner/plan.ts +102 -0
  39. package/apps/bridge/src/task-automations/runner/readiness.ts +65 -0
  40. package/apps/bridge/src/task-automations/store.ts +87 -0
  41. package/apps/bridge/src/task-control/README.md +3 -1
  42. package/apps/bridge/src/task-control/index.ts +10 -15
  43. package/apps/bridge/src/task-dispatch/README.md +7 -0
  44. package/apps/bridge/src/task-dispatch/worker/index.ts +19 -4
  45. package/apps/bridge/src/task-dispatch/worker/monitor.ts +18 -7
  46. package/apps/bridge/src/task-schedules/README.md +3 -1
  47. package/apps/bridge/src/task-schedules/controls.ts +7 -5
  48. package/apps/bridge/src/task-schedules/relay.ts +3 -1
  49. package/cursor-plugin/README.md +1 -1
  50. package/cursor-plugin/mcp.json +1 -1
  51. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  52. package/package.json +1 -1
  53. package/packages/core/outbound-scheduler/index.ts +1 -1
  54. package/packages/protocol/messages/README.md +5 -0
  55. package/packages/protocol/messages/sessions/compaction.ts +50 -0
  56. package/packages/protocol/messages/sessions/index.ts +15 -0
  57. package/packages/protocol/schema.ts +8 -0
  58. package/packages/protocol/task-automations/README.md +17 -0
  59. package/packages/protocol/task-automations/index.ts +98 -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.200 on npm and GrantTap 1.0.2 on the App Store:
76
+ Available now, with GrantTap MCP 0.8.201 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
@@ -905,6 +905,18 @@ appears, and Tasks an earlier runtime made for such chats (`codex task`, "Contin
905
905
  are left out of what the phone is sent. See [Codex outcomes](apps/bridge/src/sessions/scan/codex/README.md)
906
906
  and [chat pictures](apps/bridge/src/helper-runs/README.md#pictures-a-chat-saved).
907
907
 
908
+ ### Automations for any agent's chat
909
+
910
+ The phone's Automations sheet adds GrantTap's own automations to a chat: a name, a message, and a
911
+ schedule — once at a time, every N hours, daily at a time on chosen weekdays, or a five-field cron.
912
+ When one is due, the persistent monitor sends the message into the chat as a phone turn, only once
913
+ the chat is free (idle, nothing queued ahead of it) and not held by a usage limit; it waits for the
914
+ reset instead of running into it. After sleep it runs the latest missed run at most once, and skips
915
+ one more than 12 hours late. Pause, resume, edit, delete and Run now come from the phone, which shows
916
+ the next run, a run waiting and why, and the last run or skip. They work in Claude Code, Cursor, Grok
917
+ Build and Codex chats; Codex's own automations are listed beside them, unchanged. The monitor log has
918
+ one line per run or skip. See [GrantTap automations](apps/bridge/src/task-automations/README.md).
919
+
908
920
  ### One computer, whatever the network calls it
909
921
 
910
922
  The Mesh keys a computer by an identity written down once, on first use, in
@@ -25,6 +25,7 @@ import { startRuntimeWatchdog } from "../../runtime-watchdog";
25
25
 
26
26
  import { startTaskDispatchMonitor } from "../../task-dispatch/worker/monitor";
27
27
  import { startTaskNetworkMonitor } from '../../task-network/runtime';
28
+ import { startTaskAutomations } from '../../task-automations';
28
29
  import { claimLinkRestart } from '../../monitor/relay-link';
29
30
 
30
31
  let client: RelayClient;
@@ -34,6 +35,7 @@ let stopping = false;
34
35
  let stopEndpointPublisher = () => {};
35
36
  let stopTaskDispatch = () => {};
36
37
  let stopTaskNetwork = () => {};
38
+ let stopTaskAutomations = () => {};
37
39
  let stopEngineRecovery = () => {};
38
40
  let stopRuntimeUpdates = () => {};
39
41
  let stopUpdateReadiness = () => {};
@@ -70,6 +72,8 @@ try {
70
72
  held: () => updateDrain.holding(), track: monitor.track });
71
73
  stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
72
74
  isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
75
+ stopTaskAutomations = startTaskAutomations({ client, isLeader: monitor.isLeader, publish: monitor.publish,
76
+ held: () => updateDrain.holding(), track: monitor.track });
73
77
  stopEndpointPublisher = startEndpointPublisher(cfg);
74
78
  stopRuntimeUpdates = startRuntimeUpdates(monitor.canUpdate, updateDrain);
75
79
  stopUpdateReadiness = runtimeUpdateReadiness(monitor.canUpdate, updateDrain);
@@ -92,6 +96,7 @@ const stop = (exitCode = 0): void => {
92
96
  stopEngineRecovery();
93
97
  stopTaskDispatch();
94
98
  stopTaskNetwork();
99
+ stopTaskAutomations();
95
100
  monitor.close();
96
101
  stopEndpointPublisher();
97
102
  client.close();
@@ -0,0 +1,56 @@
1
+ # Context compaction
2
+
3
+ Public entry: `index.ts`. GrantTap compacts a Claude Code or Codex chat's context with the provider's
4
+ own command, never by asking the model to summarise in a normal prompt.
5
+
6
+ ## Claude Code
7
+
8
+ Claude Code compacts a resumed chat headless: `claude -p --resume <chat> --output-format stream-json
9
+ --verbose /compact`, run in the chat's folder under the chat's delivery key (`claude.ts`). It prints
10
+ `compact_boundary` with `pre_tokens` and `post_tokens`; the transcript gets the same boundary, Claude's
11
+ summary and `/compact`'s own lines, and the chat goes on from the summary under the same id. A refusal
12
+ (a failed compaction status, the command's own output, an error result) comes back in Claude's words.
13
+ Checked against Claude Code 2.1.330 on a throwaway chat; `tests/fake-claude.ts` replays those rows.
14
+
15
+ Codex keeps its app-server compaction (`../providers/codex-control.ts`).
16
+
17
+ ## When
18
+
19
+ Only between turns (`compactChat`). A chat is refused while its turn runs, while a GrantTap run or a
20
+ queued phone message waits for it, while it is already being compacted, and for Claude while a running
21
+ Claude Code lists the chat in `~/.claude/sessions/<pid>.json` (the same process, by its start time): a
22
+ chat open there keeps its conversation in memory, and a compaction written beside it would not reach it.
23
+
24
+ The phone's Compact now (`session.compact`) is taken at once and answered with `session.compact.result`
25
+ when the compaction ends, which for a context near a million tokens takes minutes.
26
+
27
+ ## Threshold
28
+
29
+ Each catalog the leader publishes is looked at for a chat that reached its threshold since its last
30
+ turn (`trigger.ts`): idle for 20 s, not paused, waiting on no background work or account limit, with a
31
+ reading of its own from the last two hours, newer than its last compaction and not tried before. One
32
+ chat at a time across the computer; a reading is tried once, so a refusal waits for the next turn.
33
+
34
+ The default is 400k tokens for Claude and off for Codex (`DEFAULT_AUTO_COMPACT_TOKENS`). Claude Code's
35
+ own default for its million-token models compacts at about 967k: the window less 20k for the summary
36
+ and a 13k buffer. Every request of a turn sends the whole context again, so 400k spends less than half
37
+ as much of the subscription per request as a chat near that end, and still leaves a long turn more
38
+ than half the window before Claude's compaction would run in the middle of it. Codex compacts itself
39
+ near the end of a far smaller window. The phone sets a chat's threshold, turns it off or back to the
40
+ default with `session.autocompact.set`.
41
+
42
+ ## What the phone sees
43
+
44
+ `SessionInfo.compaction`: how many compactions the transcript records, the newest with the context
45
+ before and after where the provider said, who made it (`auto` and `manual` are Claude's own; `provider`
46
+ is a Codex one; `phone` and `threshold` are this computer's runs, matched to the transcript by time),
47
+ the threshold in force and whether it is the default, and `running` while this computer compacts it.
48
+ The chat shows a compaction as one status line instead of Claude's summary.
49
+
50
+ State: `context-compaction.json` in the GrantTap folder (`store.ts`): the thresholds set per chat, the
51
+ last eight runs per chat and the reading each automatic compaction was tried for. The monitor log has
52
+ one line when a threshold is reached and one with the outcome, naming the chat by the start of its id.
53
+
54
+ Tests: `tests/`.
55
+
56
+ License: GrantTap Commercial Source License; see the repository LICENSE.
@@ -0,0 +1,69 @@
1
+ import type { SessionInfo } from '../../../../packages/protocol/schema';
2
+ import { explainClaudeFailure, resolveClaudeBinary } from '../providers/claude-bin';
3
+ import { runProcess } from '../reply/process';
4
+
5
+ /** `refused`: it did not run, because the chat was not between turns; the words say why. */
6
+ export type CompactOutcome = { ok: true; preTokens?: number; postTokens?: number } | { ok: false; error: string; refused?: boolean };
7
+
8
+ /** Summarising a context near a million tokens streams a long summary; a turn's own deadline is too short. */
9
+ export const CLAUDE_COMPACT_TIMEOUT_MS = 15 * 60_000;
10
+
11
+ const tokens = (value: unknown): number | undefined =>
12
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
13
+
14
+ function rowText(content: unknown): string {
15
+ if (typeof content === 'string') return content;
16
+ return Array.isArray(content) ? content.map((block: any) => typeof block?.text === 'string' ? block.text : '').join('') : '';
17
+ }
18
+
19
+ function short(text: unknown): string | undefined {
20
+ const value = typeof text === 'string' ? text.replace(/\s+/g, ' ').trim() : '';
21
+ return value ? value.slice(0, 300) : undefined;
22
+ }
23
+
24
+ /**
25
+ * What `claude -p --resume <id> --output-format stream-json --verbose /compact` printed. Claude
26
+ * Code reports the compaction itself (`compact_boundary`, with the context before and after); a
27
+ * refusal comes as a failed compaction status, the command's own output or an error result.
28
+ */
29
+ export function readClaudeCompaction(stdout: string): CompactOutcome {
30
+ let boundary: any, failed: string | undefined, said: string | undefined, result: any;
31
+ for (const line of stdout.split('\n')) {
32
+ let row: any;
33
+ try { row = JSON.parse(line); } catch { continue; }
34
+ if (row?.type === 'system' && row.subtype === 'compact_boundary') boundary = row.compact_metadata ?? {};
35
+ else if (row?.type === 'system' && row.subtype === 'status' && row.compact_result === 'failed') {
36
+ failed = short(row.compact_error) ?? 'Claude Code could not compact the conversation.';
37
+ } else if (row?.type === 'user') {
38
+ said = short(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/.exec(rowText(row.message?.content))?.[1]) ?? said;
39
+ } else if (row?.type === 'result') result = row;
40
+ }
41
+ if (boundary) {
42
+ const preTokens = tokens(boundary.pre_tokens), postTokens = tokens(boundary.post_tokens);
43
+ return { ok: true, ...(preTokens != null ? { preTokens } : {}), ...(postTokens != null ? { postTokens } : {}) };
44
+ }
45
+ if (failed) return { ok: false, error: failed };
46
+ if (result?.is_error) {
47
+ return { ok: false, error: short(Array.isArray(result.errors) ? result.errors.join(' ') : result.result)
48
+ ?? 'Claude Code stopped with an error.' };
49
+ }
50
+ return { ok: false, error: said ?? 'Claude Code finished without compacting the conversation.' };
51
+ }
52
+
53
+ /**
54
+ * Claude Code's own `/compact`, run headless on the chat it belongs to, in the chat's folder and
55
+ * under the chat's key: a pause from the phone stops it like any run GrantTap started there.
56
+ */
57
+ export function compactClaudeSession(session: SessionInfo, timeoutMs = CLAUDE_COMPACT_TIMEOUT_MS): Promise<CompactOutcome> {
58
+ const claude = resolveClaudeBinary();
59
+ let outcome: CompactOutcome | undefined;
60
+ const args = ['-p', '--resume', session.sessionId, '--output-format', 'stream-json', '--verbose', '/compact'];
61
+ return runProcess(claude.path, args, session.cwd, timeoutMs, (stdout) => {
62
+ outcome = readClaudeCompaction(stdout);
63
+ return outcome.ok ? { ok: true, text: '' } : { ok: false, error: outcome.error };
64
+ }, undefined, session.sessionId).then((result) => {
65
+ if (outcome) return outcome.ok ? outcome : { ok: false, error: explainClaudeFailure(outcome.error, claude) };
66
+ return result.ok ? { ok: false, error: 'Claude Code finished without compacting the conversation.' }
67
+ : { ok: false, error: explainClaudeFailure(result.error, claude) };
68
+ });
69
+ }
@@ -0,0 +1,164 @@
1
+ import type { SessionCompaction, SessionInfo, SessionsStatus } from '../../../../packages/protocol/schema';
2
+ import { compactCodexSession } from '../providers/codex-control';
3
+ import { isDeliveryInFlight, phoneMessagesWaiting, queued } from '../reply/in-flight';
4
+ import { runningProcessCount } from '../reply/process';
5
+ import { tokenScale } from '../sessions/context-usage/compactions';
6
+ import { compactClaudeSession, type CompactOutcome } from './claude';
7
+ import { savedCompactionState, updateCompactionState, type CompactionRun, type CompactionState } from './store';
8
+ import { autoCompactDue, claudeSessionHeld, DEFAULT_AUTO_COMPACT_TOKENS } from './trigger';
9
+
10
+ export { readClaudeCompaction, type CompactOutcome } from './claude';
11
+ export { AUTO_COMPACT_QUIET_MS, AUTO_COMPACT_RECENT_MS, autoCompactDue, DEFAULT_AUTO_COMPACT_TOKENS } from './trigger';
12
+
13
+ /** A Codex or Claude record of a run lands this long after the run itself ends, at most. */
14
+ const RECORD_LAG_MS = 10_000;
15
+ /** Chats this monitor is compacting now. */
16
+ const running = new Set<string>();
17
+ let automatic: Promise<void> | undefined;
18
+
19
+ const providerName = (agent: string) => agent === 'claude' ? 'Claude Code' : 'Codex';
20
+ const compactable = (session: SessionInfo) => session.agent === 'claude' || session.agent === 'codex';
21
+
22
+ /** The threshold in force for a chat: the one set for it, `0` for off, or the provider's default. */
23
+ export function autoCompactThreshold(session: Pick<SessionInfo, 'sessionId' | 'agent'>,
24
+ state: CompactionState = savedCompactionState()): { atTokens?: number; isDefault: boolean } {
25
+ const set = state.thresholds[session.sessionId];
26
+ if (set === 0) return { isDefault: false };
27
+ if (set) return { atTokens: set, isDefault: false };
28
+ const fallback = DEFAULT_AUTO_COMPACT_TOKENS[session.agent];
29
+ return fallback ? { atTokens: fallback, isDefault: true } : { isDefault: true };
30
+ }
31
+
32
+ /** From the phone: off, a threshold, or back to the provider's default. */
33
+ export function setAutoCompact(sessionId: string, enabled: boolean, atTokens?: number): void {
34
+ updateCompactionState((state) => {
35
+ if (!enabled) state.thresholds[sessionId] = 0;
36
+ else if (atTokens) state.thresholds[sessionId] = atTokens;
37
+ else delete state.thresholds[sessionId];
38
+ });
39
+ }
40
+
41
+ /** Why the chat cannot be compacted now, in words for the phone; undefined when it can. */
42
+ function busyReason(session: SessionInfo): string | undefined {
43
+ const name = providerName(session.agent);
44
+ if (running.has(session.sessionId)) return 'This chat is already being compacted.';
45
+ if (session.state === 'working') return `Wait for the active ${name} turn to finish before compacting it.`;
46
+ if (isDeliveryInFlight(session.sessionId) || runningProcessCount(session.sessionId) > 0
47
+ || phoneMessagesWaiting(session.sessionId) > 0) {
48
+ return `A turn GrantTap started in this chat is still running; compact it after the turn ends.`;
49
+ }
50
+ if (session.agent === 'claude' && claudeSessionHeld(session.sessionId)) {
51
+ return 'This chat is open in Claude Code on the computer. Type /compact there, or close it there and compact it from here.';
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ function record(sessionId: string, run: CompactionRun): void {
57
+ try {
58
+ updateCompactionState((state) => { state.runs[sessionId] = [...(state.runs[sessionId] ?? []), run]; });
59
+ } catch { /* An unreadable state keeps what it holds; the transcript still records the compaction. */ }
60
+ }
61
+
62
+ /**
63
+ * Compacts one chat with its provider's own command: Claude Code's `/compact`, Codex's app-server
64
+ * compaction. Only between turns: never while a turn runs, a GrantTap run or queued message waits for
65
+ * the chat, or a Claude Code open on the computer holds it. Runs under the chat's delivery key, so a
66
+ * message that arrives meanwhile waits for it. The run is recorded so the phone can say who did it.
67
+ */
68
+ export async function compactChat(session: SessionInfo, by: CompactionRun['by']): Promise<CompactOutcome> {
69
+ if (!compactable(session)) return { ok: false, error: `${session.agent} has no compaction GrantTap can run.`, refused: true };
70
+ const busy = busyReason(session);
71
+ if (busy) return { ok: false, error: busy, refused: true };
72
+ running.add(session.sessionId);
73
+ const startedAt = Date.now(), before = session.contextUsage?.usedTokens;
74
+ try {
75
+ let outcome = { ok: false, error: 'The compaction did not run.' } as CompactOutcome;
76
+ await queued(session.sessionId, async () => {
77
+ outcome = session.agent === 'claude' ? await compactClaudeSession(session)
78
+ : await compactCodexSession(session.sessionId).then((result): CompactOutcome => result.ok
79
+ ? { ok: true, ...(before != null ? { preTokens: before } : {}) } : result);
80
+ return outcome.ok ? { ok: true, text: '' } : { ok: false, error: outcome.error };
81
+ });
82
+ record(session.sessionId, { by, startedAt, endedAt: Date.now(), ok: outcome.ok,
83
+ ...(outcome.ok ? { ...(outcome.preTokens != null ? { preTokens: outcome.preTokens } : {}),
84
+ ...(outcome.postTokens != null ? { postTokens: outcome.postTokens } : {}) } : { error: outcome.error.slice(0, 300) }) });
85
+ return outcome;
86
+ } finally {
87
+ running.delete(session.sessionId);
88
+ }
89
+ }
90
+
91
+ /** The words the phone shows for a finished compaction. */
92
+ export function compactedText(session: SessionInfo, outcome: CompactOutcome): string {
93
+ if (!outcome.ok) return outcome.refused ? outcome.error : `Context compaction failed: ${outcome.error}`;
94
+ if (session.agent === 'codex') return 'Codex context compaction completed.';
95
+ const size = outcome.preTokens != null && outcome.postTokens != null
96
+ ? `: ${tokenScale(outcome.preTokens)} → ${tokenScale(outcome.postTokens)} tokens` : '';
97
+ return `Claude Code compacted the context${size}. The chat continues from its summary.`;
98
+ }
99
+
100
+ /**
101
+ * The provider's newest compaction, said to be GrantTap's when one of this computer's runs made it;
102
+ * a run the transcript does not show yet stands in for it and is counted.
103
+ */
104
+ function attributed(seen: Pick<SessionCompaction, 'count' | 'last'>, runs: CompactionRun[]): Pick<SessionCompaction, 'count' | 'last'> {
105
+ const ours = runs.filter((run) => run.ok);
106
+ const last = seen.last;
107
+ const made = last && ours.find((run) => last.at >= run.startedAt && last.at <= run.endedAt + RECORD_LAG_MS);
108
+ if (last && made) {
109
+ return { count: seen.count, last: { preTokens: made.preTokens, postTokens: made.postTokens, ...last, trigger: made.by } };
110
+ }
111
+ const newer = ours.at(-1);
112
+ if (!newer || newer.endedAt <= (last?.at ?? 0)) return seen;
113
+ return { count: seen.count + 1, last: { at: newer.endedAt, trigger: newer.by,
114
+ ...(newer.preTokens != null ? { preTokens: newer.preTokens } : {}),
115
+ ...(newer.postTokens != null ? { postTokens: newer.postTokens } : {}) } };
116
+ }
117
+
118
+ function annotated(session: SessionInfo, state: CompactionState): SessionInfo {
119
+ if (!compactable(session)) return session;
120
+ const seen = attributed(session.compaction ?? { count: 0 }, state.runs[session.sessionId] ?? []);
121
+ const { atTokens, isDefault } = autoCompactThreshold(session, state);
122
+ const last = seen.last && Object.fromEntries(Object.entries(seen.last).filter(([, value]) => value !== undefined));
123
+ return { ...session, compaction: { count: seen.count, ...(last ? { last: last as SessionCompaction['last'] } : {}),
124
+ ...(atTokens ? { autoAtTokens: atTokens } : {}), autoAtDefault: isDefault,
125
+ ...(running.has(session.sessionId) ? { running: true } : {}) } };
126
+ }
127
+
128
+ /** Every Claude and Codex chat in a catalog says how often it was compacted and when GrantTap compacts it. */
129
+ export function annotateCompactionCatalog<T extends Pick<SessionsStatus, 'sessions' | 'history'>>(status: T): T {
130
+ const state = savedCompactionState();
131
+ return { ...status, sessions: status.sessions.map((session) => annotated(session, state)),
132
+ ...(status.history ? { history: status.history.map((session) => annotated(session, state)) } : {}) };
133
+ }
134
+
135
+ function log(session: SessionInfo, text: string): void {
136
+ process.stderr.write(`[monitor] context compaction of ${session.agent} chat ${session.sessionId.slice(0, 8)}: ${text}\n`);
137
+ }
138
+
139
+ async function compactWhenDue(sessions: SessionInfo[], now: number): Promise<void> {
140
+ const state = savedCompactionState();
141
+ // Whether something holds the chat is asked last: it reads Claude's list of running sessions.
142
+ const due = sessions.filter((session) => compactable(session) && !/^transfer-/.test(session.sessionId)
143
+ && autoCompactDue(session, { now, atTokens: autoCompactThreshold(session, state).atTokens,
144
+ triedReading: state.triedReading?.[session.sessionId], busy: false }))
145
+ .find((session) => busyReason(session) === undefined);
146
+ if (!due?.contextUsage) return;
147
+ const reading = due.contextUsage.observedAt, at = autoCompactThreshold(due, state).atTokens!;
148
+ updateCompactionState((saved) => { saved.triedReading = { ...saved.triedReading, [due.sessionId]: reading }; });
149
+ log(due, `${tokenScale(due.contextUsage.usedTokens)} tokens reached its ${tokenScale(at)} threshold between turns`);
150
+ const outcome = await compactChat(due, 'threshold');
151
+ log(due, outcome.ok ? compactedText(due, outcome) : `not compacted: ${outcome.error}`);
152
+ }
153
+
154
+ /**
155
+ * Looks at each catalog for a chat that reached its threshold since its last turn and compacts it, one
156
+ * chat at a time across this computer. A reading is tried once: a refusal waits for the next turn.
157
+ */
158
+ export function scheduleAutoCompactions(sessions: SessionInfo[], now = Date.now()): Promise<void> {
159
+ if (automatic) return automatic;
160
+ automatic = compactWhenDue(sessions, now)
161
+ .catch((error) => { process.stderr.write(`[monitor] context compaction pass failed: ${String(error).slice(0, 200)}\n`); })
162
+ .finally(() => { automatic = undefined; });
163
+ return automatic;
164
+ }
@@ -0,0 +1,71 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { AUTO_COMPACT_MAX_TOKENS, AUTO_COMPACT_MIN_TOKENS } from '../../../../packages/protocol/schema';
5
+ import { configDir, writePrivateFile } from '../config';
6
+
7
+ const Time = z.number().int().nonnegative();
8
+ const Tokens = z.number().int().nonnegative();
9
+ const ChatId = z.string().min(1).max(180);
10
+
11
+ /** One compaction this computer ran: why, its span, and what the provider said it did. */
12
+ const Run = z.object({
13
+ by: z.enum(['phone', 'threshold']),
14
+ startedAt: Time,
15
+ endedAt: Time,
16
+ ok: z.boolean(),
17
+ preTokens: Tokens.optional(),
18
+ postTokens: Tokens.optional(),
19
+ /** The provider's words when it did not compact, kept short; never message text. */
20
+ error: z.string().max(300).optional(),
21
+ }).strict();
22
+ export type CompactionRun = z.infer<typeof Run>;
23
+
24
+ const State = z.object({
25
+ /** The threshold set for a chat from the phone; `0` is off. A chat not listed takes the default. */
26
+ thresholds: z.record(ChatId, z.union([z.literal(0),
27
+ z.number().int().min(AUTO_COMPACT_MIN_TOKENS).max(AUTO_COMPACT_MAX_TOKENS)])),
28
+ /** The newest runs per chat, oldest first. */
29
+ runs: z.record(ChatId, z.array(Run).max(8)),
30
+ /** The context reading, by its time, an automatic compaction was last tried for; it is tried once. */
31
+ triedReading: z.record(ChatId, Time).optional(),
32
+ }).strict();
33
+ export type CompactionState = z.infer<typeof State>;
34
+
35
+ const MAX_CHATS = 2_048;
36
+ const path = () => join(configDir(), 'context-compaction.json');
37
+ const empty = (): CompactionState => ({ thresholds: {}, runs: {} });
38
+
39
+ /**
40
+ * The saved state; a missing file, or one that is not this state, is empty. A disk that cannot be
41
+ * read throws, so a writer never replaces the thresholds the person set with an empty file.
42
+ */
43
+ export function readCompactionState(): CompactionState {
44
+ let raw: string;
45
+ try { raw = readFileSync(path(), 'utf8'); }
46
+ catch (error) {
47
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return empty();
48
+ throw error;
49
+ }
50
+ try { return State.parse(JSON.parse(raw)); } catch { return empty(); }
51
+ }
52
+
53
+ /** The state as it was, or empty when the disk cannot be read: for reading, never for writing back. */
54
+ export function savedCompactionState(): CompactionState {
55
+ try { return readCompactionState(); } catch { return empty(); }
56
+ }
57
+
58
+ function newest<T>(record: Record<string, T>): Record<string, T> {
59
+ return Object.fromEntries(Object.entries(record).slice(-MAX_CHATS));
60
+ }
61
+
62
+ /** Changes the saved state in one step: nothing else in this process runs between its read and write. */
63
+ export function updateCompactionState(change: (state: CompactionState) => void): void {
64
+ const state = readCompactionState();
65
+ change(state);
66
+ writePrivateFile(path(), JSON.stringify(State.parse({
67
+ thresholds: newest(state.thresholds),
68
+ runs: newest(Object.fromEntries(Object.entries(state.runs).map(([id, runs]) => [id, runs.slice(-8)]))),
69
+ ...(state.triedReading ? { triedReading: newest(state.triedReading) } : {}),
70
+ })));
71
+ }
@@ -0,0 +1,92 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readdirSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import type { SessionInfo } from '../../../../packages/protocol/schema';
6
+
7
+ /**
8
+ * GrantTap's own threshold, by provider, for a chat nobody set one for. Claude Code's models have a
9
+ * million-token window and compact themselves at about 967k (the window, less 20k for the summary and
10
+ * a 13k buffer). Every request of a turn sends the whole context again, so a chat held under 400k
11
+ * spends less than half as much of the subscription per request as one near the end, keeps its early
12
+ * messages clearer to the model, and still leaves a long turn more than half the window before
13
+ * Claude's own compaction would have to run in the middle of it. Codex compacts itself near the end
14
+ * of a much smaller window, so it has no default; the person can still set one.
15
+ */
16
+ export const DEFAULT_AUTO_COMPACT_TOKENS: Readonly<Partial<Record<string, number>>> = { claude: 400_000 };
17
+
18
+ /** A turn that ended moments ago may be followed at once by the next queued message; that goes first. */
19
+ export const AUTO_COMPACT_QUIET_MS = 20_000;
20
+ /** Only a turn that ended lately is compacted after; a chat left long ago is not woken up to be. */
21
+ export const AUTO_COMPACT_RECENT_MS = 2 * 60 * 60_000;
22
+
23
+ const STOPPED_BY_ACCOUNT = new Set(['usage_limit', 'rate_limit', 'sign_in']);
24
+
25
+ /** What the monitor knows about a chat besides its catalog row, at the moment it looks. */
26
+ export type AutoCompactFacts = {
27
+ now: number;
28
+ /** The threshold in force for the chat; undefined when it is off. */
29
+ atTokens?: number;
30
+ /** The context reading an automatic compaction was already tried for. */
31
+ triedReading?: number;
32
+ /** Something runs in the chat or holds it: a GrantTap run, a queued message, an open Claude Code. */
33
+ busy: boolean;
34
+ };
35
+
36
+ /**
37
+ * Whether the chat is due for GrantTap's compaction now: between turns, with a fresh reading of its
38
+ * own at or over the threshold, newer than its last compaction and not tried before. Never while a
39
+ * turn runs, the chat is held or waits on background work, or the account stopped it.
40
+ */
41
+ export function autoCompactDue(session: SessionInfo, facts: AutoCompactFacts): boolean {
42
+ const usage = session.contextUsage;
43
+ if (!facts.atTokens || !usage || usage.usedTokens < facts.atTokens || facts.busy) return false;
44
+ if (session.agent !== 'claude' && session.agent !== 'codex') return false;
45
+ if (session.state !== 'idle' || session.paused || session.backgroundTasks || session.usageLimit) return false;
46
+ if (session.stopped && STOPPED_BY_ACCOUNT.has(session.stopped.reason)) return false;
47
+ if (facts.now - session.lastActivityAt < AUTO_COMPACT_QUIET_MS) return false;
48
+ if (facts.now - usage.observedAt > AUTO_COMPACT_RECENT_MS) return false;
49
+ if ((session.compaction?.last?.at ?? 0) >= usage.observedAt) return false;
50
+ return facts.triedReading !== usage.observedAt;
51
+ }
52
+
53
+ function claudeSessionsDir(): string {
54
+ return process.env.GRANTTAP_CLAUDE_SESSIONS_DIR
55
+ ?? join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'sessions');
56
+ }
57
+
58
+ function alive(pid: number): boolean {
59
+ try { process.kill(pid, 0); return true; }
60
+ catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; }
61
+ }
62
+
63
+ const spaced = (text: string) => text.replace(/\s+/g, ' ').trim();
64
+
65
+ /**
66
+ * The process with this id is the one that wrote the entry, not a later one given the same id. Claude
67
+ * writes the start time in UTC on this Mac; it is compared in UTC and in local time.
68
+ */
69
+ function sameProcess(pid: number, started: unknown): boolean {
70
+ if (typeof started !== 'string' || !started.trim()) return true;
71
+ const startedAt = (zone: string | undefined) => spaced(execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)],
72
+ { encoding: 'utf8', timeout: 2_000, env: zone ? { ...process.env, TZ: zone } : process.env }));
73
+ try { return [startedAt('UTC'), startedAt(undefined)].includes(spaced(started)); } catch { return true; }
74
+ }
75
+
76
+ /**
77
+ * Whether a running Claude Code holds the chat: Claude lists each of its sessions in
78
+ * `~/.claude/sessions/<pid>.json`. A chat open there keeps its whole conversation in memory, so a
79
+ * compaction written beside it would not reach it; GrantTap leaves such a chat alone.
80
+ */
81
+ export function claudeSessionHeld(sessionId: string, dir = claudeSessionsDir()): boolean {
82
+ let names: string[];
83
+ try { names = readdirSync(dir).filter((name) => name.endsWith('.json')).slice(0, 512); } catch { return false; }
84
+ return names.some((name) => {
85
+ try {
86
+ const entry = JSON.parse(readFileSync(join(dir, name), 'utf8'));
87
+ const pid = Number(entry?.pid);
88
+ return entry?.sessionId === sessionId && Number.isSafeInteger(pid) && pid > 0 && alive(pid)
89
+ && sameProcess(pid, entry.procStart);
90
+ } catch { return false; }
91
+ });
92
+ }
@@ -56,6 +56,11 @@ The monitor log has one line each time a continuation is queued, queued again, d
56
56
  taken back (with why), or expires, naming the chat by the start of its id and never its words
57
57
  (`log.ts`). A state the disk cannot read stops the pass with one line and is never replaced unseen.
58
58
 
59
+ Phone messages queued for a limited chat wait for its reset and then behind its continuation
60
+ ([`limit-queue-hold`](../limit-queue-hold/README.md)); `continuationAhead` tells that queue, read only, when
61
+ the chat's next undelivered copy is due and when one was last delivered. Up to 0.8.200 the queue went first
62
+ and spent itself on refusals.
63
+
59
64
  `limitContinuationFor` reads one chat's setting and waiting continuation for that chat's own MCP
60
65
  status. Tests live in `tests/`; `relay-fixture.ts` keeps the relay's rules for job ids.
61
66
 
@@ -7,8 +7,10 @@ import { continuationCopy, failureReason, isLimitContinuation, putOnRelay, relay
7
7
  import { readLimitContinuationState, writeLimitContinuationState, type ContinuationCopy, type LimitContinuationState,
8
8
  type ScheduledContinuation } from './store';
9
9
 
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';
10
+ export { LIFT_BELOW_PERCENT, LIFT_READING_MAX_AGE_MS, limitLifted } from './lift';
11
+ export { limitName, logTime } from './log';
12
+ export { REFUSED_AGAIN_MS } from './holding';
13
+ export { isLimitContinuation, LIMIT_CONTINUE_PROMPT, LIMIT_ROOM_PROMPT, type ContinuationQueue } from './relay-copies';
12
14
  export { LIMIT_CONTINUE_GRACE_MS } from './store';
13
15
  export type { UsageReadings } from './holding';
14
16
 
@@ -67,6 +69,20 @@ export function limitContinuationFor(sessionId: string): { autoContinue: boolean
67
69
  ...(job ? { continuation: { dueAt: Math.max(job.scheduledAt ?? 0, job.regular.notBefore), early: !!job.early } } : {}) };
68
70
  }
69
71
 
72
+ /**
73
+ * For the chat's queued phone messages, which wait behind its continuation: the limit the continuation
74
+ * waiting for the chat is for, when the next of its copies not yet delivered is due, and when one was last
75
+ * delivered. Read only; nothing for a chat with no continuation.
76
+ */
77
+ export function continuationAhead(sessionId: string): { resetsAt?: number; dueAt?: number; deliveredAt?: number } {
78
+ const state = savedState(), job = state.scheduled[sessionId], given = state.continued?.[sessionId];
79
+ const copies = job ? [job.early, job.regular].filter(copy => copy !== undefined) : [];
80
+ const due = copies.filter(copy => copy.deliveredAt === undefined).map(copy => copy.notBefore);
81
+ const delivered = [...copies.map(copy => copy.deliveredAt), given?.at].filter(at => at !== undefined);
82
+ return { ...(job ? { resetsAt: job.resetsAt } : {}), ...(due.length ? { dueAt: Math.min(...due) } : {}),
83
+ ...(delivered.length ? { deliveredAt: Math.max(...delivered) } : {}) };
84
+ }
85
+
70
86
  function memoryOf(queue: ContinuationQueue): Memory {
71
87
  let memory = memories.get(queue);
72
88
  if (!memory) memories.set(queue, memory = { lookedUp: new Map(), logged: new Set() });
@@ -1,5 +1,5 @@
1
1
  /** Which limit stopped the chat, as a person reads it. */
2
- function windowName(window: string | undefined): string {
2
+ export function limitName(window: string | undefined): string {
3
3
  if (window === 'five_hour') return '5-hour limit';
4
4
  if (window === 'seven_day') return 'weekly limit';
5
5
  const model = /^seven_day_([a-z0-9]+)$/.exec(window ?? '')?.[1];
@@ -17,7 +17,7 @@ export function logTime(at: number): string {
17
17
  */
18
18
  export function logContinuation(limit: { sessionId: string; window?: string; resetsAt?: number }, event: string): void {
19
19
  const which = limit.resetsAt === undefined ? ''
20
- : ` after its ${windowName(limit.window)} (reset ${logTime(limit.resetsAt)})`;
20
+ : ` after its ${limitName(limit.window)} (reset ${logTime(limit.resetsAt)})`;
21
21
  process.stderr.write(`[monitor] Continuation of chat ${limit.sessionId.slice(0, 8)}${which}: ${event}.\n`);
22
22
  }
23
23
 
@@ -0,0 +1,59 @@
1
+ # Queued messages behind a usage limit
2
+
3
+ Public entry: `index.ts`. Phone messages queued for a chat wait on this computer (`task-dispatch`) and go one
4
+ at a time when the chat is free. A chat refused by its subscription limit is free in that sense: its turn
5
+ ended. Up to 0.8.200 each queued message then started a run the same limit refused at once, the next one
6
+ followed, and the whole queue was spent on refusals within minutes, each shown on the phone as delivered or
7
+ failed. Now the limit holds the chat's queue (`decision.ts`):
8
+
9
+ - **Before the reset** the messages stay queued: not started, not refused, not dropped. A chat has a limit
10
+ while its catalog row carries `usageLimit`, or a stop whose reason is `usage_limit` without a stated reset
11
+ (Codex without "try again at").
12
+ - **After the reset**, and a minute of grace, the chat's own "continue" goes first when it continues by itself
13
+ ([`limit-continuation`](../limit-continuation/README.md)); the messages wait behind it for at most ten
14
+ minutes past its time, then follow it one at a time as usual. With continuing turned off, or for another
15
+ agent, the oldest message goes first after the reset, then the rest in order.
16
+ - **Refused again** after the continuation or a message went, the chat waits a quarter of an hour from that
17
+ refusal, or until a later reset it states, before the next try. One try at a time; nothing follows a
18
+ refusal into the same limit. A reading does not shorten this wait: readings lag, and trusting one the
19
+ provider contradicts would try again with every reading.
20
+ - **No stated reset**: the queue waits until an account reading taken after the refusal shows room
21
+ (`readings.ts`: the refusing Claude window below 98 %, as for an early continuation; otherwise every window
22
+ of the agent's account reading), or a quarter of an hour, then tries one. The Codex account reading is not
23
+ read here, so a Codex chat tries again every quarter of an hour.
24
+ - **Before the reset with room**: a chat with no continuation waiting goes when a reading shows room; one
25
+ with a continuation lets that continuation's own early copy go first.
26
+
27
+ Send now (`deliveryMode: immediate`), a new task and the chat's own continuation are never held. A message
28
+ cancelled from the phone while held leaves this computer at its next relay lookup, every ten minutes, and in
29
+ any case before it would start.
30
+
31
+ The worker skips a held job before it takes the chat's turn (`limitHeld` in `task-dispatch/worker`), so the
32
+ continuation is not stuck behind an older message, and asks the relay about it only every ten minutes instead of
33
+ every two seconds. The job stays staged in the inbox and queued on the relay, so a monitor restart or a runtime
34
+ update keeps it and the order. What was decided is kept in `limit-queue-hold.json`: when a message last went to
35
+ a chat whose limit still showed (so a refusal after it is a refusal again, across restarts too) and whether the
36
+ hold was announced. A chat whose turn ended without a limit is forgotten. A file the disk cannot read is logged
37
+ once and the decision is made without it; the queue still waits for the reset.
38
+
39
+ ## Phone
40
+
41
+ Each listed chat whose queue a limit holds carries `queueHold { reason: "usage_limit", until }` in the catalog:
42
+ the reset, or the next try after a refusal (`annotateQueueHolds`, read only). The phone shows its queued
43
+ messages as waiting for the limit to reset, with that time, and queues what the person sends meanwhile; Send now
44
+ and cancelling still work. Older phones ignore the field and older computers never send it.
45
+
46
+ ## Log
47
+
48
+ One line when a limit starts holding a chat's queue and one when it lets it go, naming the chat by the start of
49
+ its id and the limit by its kind and reset, never its words (`log.ts`):
50
+
51
+ [monitor] Queued messages for chat 1a2b3c4d wait for its 5-hour limit (reset 2026-11-23 13:00 UTC): they go one at a time after the reset.
52
+ [monitor] Queued messages for chat 1a2b3c4d go on after its 5-hour limit (reset 2026-11-23 13:00 UTC): its continuation went first.
53
+
54
+ Tests live in `tests/`: the rules (`decision.test.ts`), the catalog field and stored state (`catalog.test.ts`),
55
+ and the persistent monitor's queue over a fake relay with a mocked clock (`queue.test.ts`): three messages kept
56
+ through a limit and run in order after the continuation, no continuation when it is off, a second refusal
57
+ holding again, restarts, Send now and cancellation.
58
+
59
+ License: GrantTap Commercial Source License; see the repository LICENSE.