granttap-mcp 0.8.153 → 0.8.155
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 +3 -0
- package/apps/bridge/src/bin/runtime/monitor.ts +1 -1
- package/apps/bridge/src/install/monitor-helper.ts +4 -2
- package/apps/bridge/src/install/monitor-launchd/README.md +5 -0
- package/apps/bridge/src/monitor/handlers/catalog.ts +4 -6
- package/apps/bridge/src/monitor/handlers/user-message.ts +2 -2
- package/apps/bridge/src/monitor/index.ts +2 -1
- package/apps/bridge/src/monitor/support/heartbeat.ts +2 -2
- package/apps/bridge/src/monitor/support/runtime.ts +6 -1
- package/apps/bridge/src/session-catalog/README.md +2 -0
- package/apps/bridge/src/session-images/index.ts +2 -3
- package/apps/bridge/src/sessions/catalog.ts +7 -0
- package/apps/bridge/src/sessions/index.ts +1 -1
- package/apps/bridge/src/sessions/scan/claude/child-reading/README.md +12 -0
- package/apps/bridge/src/sessions/scan/claude/child-reading/index.ts +32 -0
- package/apps/bridge/src/sessions/scan/claude/parse.ts +15 -39
- package/apps/bridge/src/sessions/scan/claude/shared.ts +11 -52
- package/apps/bridge/src/sessions/scan/claude/transcript-reading/README.md +13 -0
- package/apps/bridge/src/sessions/scan/claude/transcript-reading/index.ts +47 -0
- package/apps/bridge/src/sessions/scan/claude/transcript-reading/summary.ts +45 -0
- package/apps/bridge/src/task-activities/README.md +20 -0
- package/apps/bridge/src/task-activities/index.ts +13 -0
- package/apps/bridge/src/task-activities/presentation.ts +34 -0
- package/apps/bridge/src/task-activities/publisher.ts +60 -0
- package/apps/bridge/src/task-activities/subscription.ts +27 -0
- package/apps/bridge/src/task-activities/transport.ts +27 -0
- package/apps/mcp/src/mcp-tools/connect/relay.ts +1 -1
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/package.json +1 -1
- package/packages/protocol/schema.ts +1 -0
package/README.md
CHANGED
|
@@ -22,6 +22,9 @@ walk through every provider log. The local helper retains a private metadata
|
|
|
22
22
|
index so a restart can send current heads of the saved Now chats before a fresh
|
|
23
23
|
discovery scan. The Apple clients keep downloaded conversations, pictures, and
|
|
24
24
|
Mesh data locally for offline use; clearing that cache preserves the account login.
|
|
25
|
+
Large Claude parent and child transcripts are read in cooperative slices so network
|
|
26
|
+
heartbeats and decisions keep running. A live child retains its quiet parent
|
|
27
|
+
checkpoint, and an append during a scan is discovered on the next pass.
|
|
25
28
|
|
|
26
29
|
The chat's **Files** pill opens recorded changes for the current reply and the
|
|
27
30
|
Task's **All files** tree. Directory and text reads are paged, encrypted for the
|
|
@@ -44,7 +44,7 @@ try {
|
|
|
44
44
|
replayPath: join(configDir(), `replay-${cfg.room}.json`),
|
|
45
45
|
peerAllowed: controllerPeerGate(cfg),
|
|
46
46
|
});
|
|
47
|
-
monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1" });
|
|
47
|
+
monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1", config: cfg });
|
|
48
48
|
stopTaskDispatch = startTaskDispatchMonitor({ config: cfg, client,
|
|
49
49
|
isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
|
|
50
50
|
stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
|
|
@@ -113,7 +113,8 @@ export function monitorPlistNeedsRepair(path: string): boolean {
|
|
|
113
113
|
if (!existsSync(path)) return true;
|
|
114
114
|
try {
|
|
115
115
|
const contents = readFileSync(path, "utf8");
|
|
116
|
-
return plistUsesTemporaryIO(contents) || legacyUnconfiguredEngine(contents)
|
|
116
|
+
return plistUsesTemporaryIO(contents) || legacyUnconfiguredEngine(contents)
|
|
117
|
+
|| /<key>ProcessType<\/key>\s*<string>Background<\/string>/.test(contents);
|
|
117
118
|
} catch {
|
|
118
119
|
return true;
|
|
119
120
|
}
|
|
@@ -193,7 +194,8 @@ function buildMonitorPlist(input: {
|
|
|
193
194
|
" <key>KeepAlive</key>",
|
|
194
195
|
" <true/>",
|
|
195
196
|
" <key>ProcessType</key>",
|
|
196
|
-
|
|
197
|
+
// iPhone decisions depend on timely socket and filesystem callbacks, without XPC transactions.
|
|
198
|
+
" <string>Interactive</string>",
|
|
197
199
|
" <key>ThrottleInterval</key>",
|
|
198
200
|
` <integer>${usePin ? 10 : 5}</integer>`,
|
|
199
201
|
" <key>StandardErrorPath</key>",
|
|
@@ -5,4 +5,9 @@ macOS monitor LaunchAgents. Current launchers also load the declaration through
|
|
|
5
5
|
the cross-platform Engine startup module. Explicit disablement remains owned
|
|
6
6
|
by that startup contract.
|
|
7
7
|
|
|
8
|
+
The live monitor uses `ProcessType=Interactive`: the phone depends on timely
|
|
9
|
+
heartbeats and approval replies over WebSocket, without XPC transactions that
|
|
10
|
+
could raise an Adaptive job's priority. The installer marks older Background
|
|
11
|
+
definitions for repair. This follows [Apple's launchd process classification](https://github.com/apple-oss-distributions/launchd/blob/main/man/launchd.plist.5).
|
|
12
|
+
|
|
8
13
|
License: GrantTap Commercial Source License, in the repository-root `LICENSE`.
|
|
@@ -8,8 +8,7 @@ import { publishedSession } from "../../session-catalog";
|
|
|
8
8
|
import { activityWithImages } from '../../session-images';
|
|
9
9
|
import { cursorConversationSession } from "../../sessions/cursor";
|
|
10
10
|
import {
|
|
11
|
-
|
|
12
|
-
scanSessions,
|
|
11
|
+
findSessionCooperatively,
|
|
13
12
|
scanThreadActivity,
|
|
14
13
|
} from "../../sessions";
|
|
15
14
|
|
|
@@ -41,7 +40,7 @@ export function boundedCatalogHistory(
|
|
|
41
40
|
return [...pinned, ...rest].sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
42
41
|
}
|
|
43
42
|
|
|
44
|
-
function resolveSession(client: RelayClient, sessionId: string, status?: SessionsStatus): SessionInfo | undefined {
|
|
43
|
+
async function resolveSession(client: RelayClient, sessionId: string, status?: SessionsStatus): Promise<SessionInfo | undefined> {
|
|
45
44
|
const cursor = cursorConversationSession(sessionId);
|
|
46
45
|
const known = status?.sessions.find((session) => session.sessionId === sessionId)
|
|
47
46
|
?? status?.history?.find((session) => session.sessionId === sessionId)
|
|
@@ -50,8 +49,7 @@ function resolveSession(client: RelayClient, sessionId: string, status?: Session
|
|
|
50
49
|
return { ...known, ...cursor, title: known?.title ?? cursor.title };
|
|
51
50
|
}
|
|
52
51
|
if (known) return known;
|
|
53
|
-
return
|
|
54
|
-
?? scanSessionHistory().find((session) => session.sessionId === sessionId);
|
|
52
|
+
return findSessionCooperatively(sessionId);
|
|
55
53
|
}
|
|
56
54
|
|
|
57
55
|
/** Send one bounded transcript under the task-specific E2EE key. */
|
|
@@ -85,7 +83,7 @@ async function sendTranscript(
|
|
|
85
83
|
threadId?: string,
|
|
86
84
|
history?: { history?: boolean; historyCursor?: string; peerPublicKey?: string },
|
|
87
85
|
): Promise<boolean> {
|
|
88
|
-
const known = resolveSession(client, sessionId, status);
|
|
86
|
+
const known = await resolveSession(client, sessionId, status);
|
|
89
87
|
if (!known) return false;
|
|
90
88
|
const observation = observeSessionExecution(known);
|
|
91
89
|
const session = observation?.session ?? known;
|
|
@@ -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 { findSessionCooperatively } 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";
|
|
@@ -158,7 +158,7 @@ export async function handleUserMessage(
|
|
|
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
160
|
const target = publishedSession(client, message.sessionId)
|
|
161
|
-
??
|
|
161
|
+
?? await findSessionCooperatively(message.sessionId, false);
|
|
162
162
|
if (!target) return refuse("This task is no longer available on the computer.");
|
|
163
163
|
|
|
164
164
|
const settings = loadRuntimeConfig().providerSettings;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { RelayClient } from "../../../../packages/core/relay-client";
|
|
2
|
+
import type { PeerConfig } from "../../../../packages/core/relay-client";
|
|
2
3
|
import { startSessionMonitor as start } from "./support/runtime";
|
|
3
4
|
|
|
4
5
|
export { HISTORY_PUBLISH_LIMIT, boundedCatalogHistory, publishSessionEvents } from "./handlers/catalog";
|
|
@@ -16,6 +17,6 @@ export { sweepAttachments, resolveMessageAttachments } from "./handlers/receipts
|
|
|
16
17
|
export { handleUserMessage } from "./handlers/user-message";
|
|
17
18
|
export type { SessionMonitor } from "./support/runtime";
|
|
18
19
|
|
|
19
|
-
export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}) {
|
|
20
|
+
export function startSessionMonitor(client: RelayClient, options: { primary?: boolean; config?: PeerConfig } = {}) {
|
|
20
21
|
return start(client, options);
|
|
21
22
|
}
|
|
@@ -21,7 +21,7 @@ export const HEARTBEAT_INTERVAL_MS = Number(
|
|
|
21
21
|
export async function publishHeartbeat(client: RelayClient): Promise<void> {
|
|
22
22
|
await client.send(
|
|
23
23
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
24
|
-
taskScheduleControls: true },
|
|
24
|
+
taskScheduleControls: true, taskActivityPreviews: true },
|
|
25
25
|
"phone",
|
|
26
26
|
{ ttlMs: HEARTBEAT_INTERVAL_MS * 3, reliable: false },
|
|
27
27
|
);
|
|
@@ -40,7 +40,7 @@ export const HELD_HEARTBEAT_TTL_MS = 60_000;
|
|
|
40
40
|
export async function publishHeldHeartbeat(client: RelayClient): Promise<void> {
|
|
41
41
|
await client.send(
|
|
42
42
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
43
|
-
taskScheduleControls: true },
|
|
43
|
+
taskScheduleControls: true, taskActivityPreviews: true },
|
|
44
44
|
"phone",
|
|
45
45
|
{ ttlMs: HELD_HEARTBEAT_TTL_MS, reliable: true },
|
|
46
46
|
);
|
|
@@ -37,6 +37,8 @@ import { handleMonitorMessage } from "../handlers/inbound";
|
|
|
37
37
|
import { decorateTaskOriginCatalog } from '../../task-origins';
|
|
38
38
|
import { publishCodexQuestions } from '../../codex-questions';
|
|
39
39
|
import { publishClaudeOpenQuestions } from '../../claude-open-questions';
|
|
40
|
+
import { startTaskActivities } from '../../task-activities';
|
|
41
|
+
import type { PeerConfig } from '../../../../../packages/core/relay-client';
|
|
40
42
|
|
|
41
43
|
const HISTORY_INTERVAL_MS = 60_000;
|
|
42
44
|
const resumedHeads = new WeakSet<RelayClient>();
|
|
@@ -176,7 +178,7 @@ async function publishMonitorTick(input: {
|
|
|
176
178
|
* used by MCP tools. This keeps STDIO stdout clean and removes the old need for
|
|
177
179
|
* a separate `granttap-mcp monitor` terminal process.
|
|
178
180
|
*/
|
|
179
|
-
export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}): SessionMonitor {
|
|
181
|
+
export function startSessionMonitor(client: RelayClient, options: { primary?: boolean; config?: PeerConfig } = {}): SessionMonitor {
|
|
180
182
|
const subscriptions = new Set<string>();
|
|
181
183
|
const leadership = monitorLeadership(Date.now, undefined, () => client.isConnected, options.primary === true);
|
|
182
184
|
restoreMonitorState(client);
|
|
@@ -186,6 +188,8 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
|
|
|
186
188
|
let closed = false;
|
|
187
189
|
const work = runtimeWorkTracker(() => hasPendingDeliveries() || approvalsStatus().pending.length > 0 || providerLogins.active() || deviceManagementWorkActive());
|
|
188
190
|
const loadLoop = monitorLoadLoop(client, leadership);
|
|
191
|
+
const stopActivities = options.config ? startTaskActivities({config: options.config,
|
|
192
|
+
catalog: () => publishedCatalog(client), isLeader: () => !closed && client.isConnected && leadership.acquire()}) : () => {};
|
|
189
193
|
|
|
190
194
|
const history = (force = false): Promise<SessionsStatus["sessions"]> => {
|
|
191
195
|
if (historyRead) return historyRead;
|
|
@@ -256,6 +260,7 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
|
|
|
256
260
|
canUpdate: work.idle,
|
|
257
261
|
close: () => {
|
|
258
262
|
closed = true;
|
|
263
|
+
stopActivities();
|
|
259
264
|
offConnected?.();
|
|
260
265
|
stopCatalog();
|
|
261
266
|
stopCatalogHeads(client);
|
|
@@ -57,3 +57,5 @@ minutes, so the transcript-age rule alone would show Idle. Only Idle is
|
|
|
57
57
|
corrected: Waiting and the provider's own states stay as observed. Open chats
|
|
58
58
|
use the same rule, and their observation revision changes when the run starts
|
|
59
59
|
and ends. Tests: [`tests/freshness/owned-delivery.test.ts`](tests/freshness/owned-delivery.test.ts).
|
|
60
|
+
|
|
61
|
+
Cold transcript, image, and message requests use cooperative discovery when the published catalog does not yet know the native identity. Concurrent requests share the same in-progress provider read; a stale phone target cannot reintroduce a synchronous full scan in the relay callback. Tests exercise real files and pending transport callbacks before both successful and unavailable replies.
|
|
@@ -5,7 +5,7 @@ import { sendSessionPayload } from '../host/session-keys';
|
|
|
5
5
|
import { readTranscriptHistory } from '../transcript-history';
|
|
6
6
|
import { publishedSession } from '../session-catalog';
|
|
7
7
|
import { cachedSessionActivity } from '../monitor/support/session-activity';
|
|
8
|
-
import {
|
|
8
|
+
import { findSessionCooperatively } from '../sessions';
|
|
9
9
|
import { sessionImageChunk, transcriptImages } from '../../../mcp/src/desktop/image';
|
|
10
10
|
|
|
11
11
|
export function activityWithImages(activity: SessionActivity): SessionActivity {
|
|
@@ -25,8 +25,7 @@ export function readSessionImage(query: SessionImageQuery, session: SessionInfo,
|
|
|
25
25
|
export async function publishSessionImage(client: RelayClient, query: SessionImageQuery,
|
|
26
26
|
peerPublicKey?: string): Promise<boolean> {
|
|
27
27
|
const session = publishedSession(client, query.sessionId)
|
|
28
|
-
??
|
|
29
|
-
?? scanSessionHistory().find(s => s.sessionId === query.sessionId);
|
|
28
|
+
?? await findSessionCooperatively(query.sessionId);
|
|
30
29
|
const activity = session ? readTranscriptHistory(session, query.historyCursor)
|
|
31
30
|
?? cachedSessionActivity(session) : undefined;
|
|
32
31
|
const chunk = session && activity ? readSessionImage(query, session, activity) : undefined;
|
|
@@ -72,6 +72,13 @@ export async function scanSessionHistoryCooperatively(): Promise<SessionInfo[]>
|
|
|
72
72
|
return historyCatalog(catalogFromScans(await cooperativeProviderScans()).all);
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
+
/** Network requests share fresh discovery without making their socket wait on synchronous CLI reads. */
|
|
76
|
+
export async function findSessionCooperatively(sessionId: string, includeHistory = true): Promise<SessionInfo | undefined> {
|
|
77
|
+
const catalog = catalogFromScans(await cooperativeProviderScans());
|
|
78
|
+
return liveCatalog(catalog).sessions.find(session => session.sessionId === sessionId)
|
|
79
|
+
?? (includeHistory ? historyCatalog(catalog.all).find(session => session.sessionId === sessionId) : undefined);
|
|
80
|
+
}
|
|
81
|
+
|
|
75
82
|
export function scanSessions(): { sessions: SessionInfo[]; tokensRecent: number } {
|
|
76
83
|
return liveCatalog(scanCatalog());
|
|
77
84
|
}
|
|
@@ -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 } from "./catalog";
|
|
50
|
+
scanSessionsCooperatively, scanSessionHistoryCooperatively, findSessionCooperatively } from "./catalog";
|
|
51
51
|
import { scanSessions, scanSessionHistory } from "./catalog";
|
|
52
52
|
|
|
53
53
|
/**
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Cooperative Claude child reading
|
|
2
|
+
|
|
3
|
+
`readClaudeChild` reads child metadata and capability observations in two
|
|
4
|
+
cooperative passes over the same native file snapshot. The final native child ID
|
|
5
|
+
is known before capability source IDs are built. Rows are discarded as they are
|
|
6
|
+
processed; a large child file is never read into one array of transcript text.
|
|
7
|
+
The caller retains the existing fingerprint cache and merges recorded usage.
|
|
8
|
+
|
|
9
|
+
Parent/child behavior tests live in the Claude reader's `tests/` directory. They
|
|
10
|
+
verify reported token totals and allow transport callbacks during a child scan.
|
|
11
|
+
|
|
12
|
+
License: [GrantTap Commercial Source License](../../../../../../../LICENSE).
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { closeSync, fstatSync, openSync } from 'node:fs';
|
|
2
|
+
import type { ChildThreadInfo, SessionInfo } from '../../../../../../../packages/protocol/schema';
|
|
3
|
+
import { safeParse } from '../../../support/common';
|
|
4
|
+
import { createClaudeCapabilityCollector } from '../activity';
|
|
5
|
+
import { createClaudeChildSummary } from '../shared';
|
|
6
|
+
import { readTranscriptRows } from '../transcript-reading';
|
|
7
|
+
|
|
8
|
+
type ChildRead = { summary: ChildThreadInfo; observations: ReturnType<ReturnType<typeof createClaudeCapabilityCollector>['snapshot']> };
|
|
9
|
+
|
|
10
|
+
/** Two bounded passes preserve the native child identity without retaining its whole transcript. */
|
|
11
|
+
export function* readClaudeChild(path: string, parent: SessionInfo): Generator<void, ChildRead | undefined> {
|
|
12
|
+
let fd: number;
|
|
13
|
+
try { fd = openSync(path, 'r'); } catch { return undefined; }
|
|
14
|
+
try {
|
|
15
|
+
const size = fstatSync(fd).size;
|
|
16
|
+
const summary = createClaudeChildSummary(path, parent.sessionId);
|
|
17
|
+
yield* readTranscriptRows(fd, { offset: 0, tail: Buffer.alloc(0) }, size, line => {
|
|
18
|
+
const row = line ? safeParse(line) : null;
|
|
19
|
+
if (!row) return false;
|
|
20
|
+
summary.add(row); return true;
|
|
21
|
+
});
|
|
22
|
+
const child = summary.finish();
|
|
23
|
+
const collector = createClaudeCapabilityCollector(() => parent, child.threadId);
|
|
24
|
+
yield* readTranscriptRows(fd, { offset: 0, tail: Buffer.alloc(0) }, size, line => {
|
|
25
|
+
const row = line ? safeParse(line) : null;
|
|
26
|
+
if (!row) return false;
|
|
27
|
+
collector.add(row); return true;
|
|
28
|
+
});
|
|
29
|
+
return { summary: child, observations: collector.snapshot() };
|
|
30
|
+
} catch { return undefined; }
|
|
31
|
+
finally { closeSync(fd); }
|
|
32
|
+
}
|
|
@@ -14,13 +14,14 @@ import { claudeChangedPaths, claudeCheckout, claudeRepositoryPaths } from "./rep
|
|
|
14
14
|
import {
|
|
15
15
|
childLogsFingerprint,
|
|
16
16
|
claudeChildLogPaths,
|
|
17
|
-
claudeChildSummary,
|
|
18
17
|
claudeContextUsage,
|
|
19
18
|
claudeSummaryCache,
|
|
20
|
-
readLines,
|
|
21
19
|
sumClaudeUsage,
|
|
22
20
|
} from "./shared";
|
|
23
21
|
|
|
22
|
+
import { readTranscriptRows } from "./transcript-reading";
|
|
23
|
+
import { readClaudeChild } from "./child-reading";
|
|
24
|
+
|
|
24
25
|
type ClaudeParseState = {
|
|
25
26
|
sessionId: string;
|
|
26
27
|
cwd?: string;
|
|
@@ -128,9 +129,6 @@ export type ClaudeParseProgress = {
|
|
|
128
129
|
children: Map<string, { fingerprint: string; summary: ChildThreadInfo; observations: ReturnType<typeof claudeCapabilityUsage> }>;
|
|
129
130
|
};
|
|
130
131
|
|
|
131
|
-
const READ_CHUNK_BYTES = 1024 * 1024;
|
|
132
|
-
const TAIL_BYTES = 256;
|
|
133
|
-
|
|
134
132
|
function newProgress(device: number, inode: number, fallbackSessionId: string): ClaudeParseProgress {
|
|
135
133
|
const state: ClaudeParseState = {
|
|
136
134
|
sessionId: "", startedAt: 0, lastActivityAt: 0, lastMessageAt: 0,
|
|
@@ -156,42 +154,17 @@ function applyRow(line: string, progress: ClaudeParseProgress): boolean {
|
|
|
156
154
|
return true;
|
|
157
155
|
}
|
|
158
156
|
|
|
159
|
-
/** Reads only what was appended, in slices, so one long chat cannot hold the event loop. */
|
|
160
|
-
function* readAppended(fd: number, progress: ClaudeParseProgress, size: number): Generator<void> {
|
|
161
|
-
let carry = Buffer.alloc(0);
|
|
162
|
-
while (progress.offset + carry.length < size) {
|
|
163
|
-
const wanted = Math.min(READ_CHUNK_BYTES, size - progress.offset - carry.length);
|
|
164
|
-
const chunk = Buffer.allocUnsafe(wanted);
|
|
165
|
-
const count = readSync(fd, chunk, 0, wanted, progress.offset + carry.length);
|
|
166
|
-
if (count === 0) break;
|
|
167
|
-
const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, count)]) : chunk.subarray(0, count);
|
|
168
|
-
const end = data.lastIndexOf(0x0a);
|
|
169
|
-
if (end < 0) { carry = data; continue; }
|
|
170
|
-
for (const line of data.toString("utf8", 0, end).split("\n")) applyRow(line, progress);
|
|
171
|
-
progress.offset += end + 1;
|
|
172
|
-
progress.tail = Buffer.from(data.subarray(Math.max(0, end + 1 - TAIL_BYTES), end + 1));
|
|
173
|
-
carry = data.subarray(end + 1);
|
|
174
|
-
yield;
|
|
175
|
-
}
|
|
176
|
-
// A complete last row without its newline counts; a row still being written waits.
|
|
177
|
-
if (carry.length && applyRow(carry.toString("utf8"), progress)) {
|
|
178
|
-
progress.offset += carry.length;
|
|
179
|
-
progress.tail = Buffer.from(carry.subarray(Math.max(0, carry.length - TAIL_BYTES)));
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
157
|
/** A subagent log is read again only when it changed, not whenever its parent chat did. */
|
|
184
|
-
function readChildren(paths: string[], ownSession: SessionInfo, progress: ClaudeParseProgress,
|
|
185
|
-
observations: ReturnType<typeof claudeCapabilityUsage>): ChildThreadInfo[] {
|
|
158
|
+
function* readChildren(paths: string[], ownSession: SessionInfo, progress: ClaudeParseProgress,
|
|
159
|
+
observations: ReturnType<typeof claudeCapabilityUsage>): Generator<void, ChildThreadInfo[]> {
|
|
186
160
|
const childThreads: ChildThreadInfo[] = [];
|
|
187
161
|
for (const childPath of paths) {
|
|
188
162
|
const fingerprint = childLogsFingerprint([childPath]);
|
|
189
163
|
let known = progress.children.get(childPath);
|
|
190
164
|
if (known?.fingerprint !== fingerprint || !recordedClaudeUsageIsCurrent(known.observations)) {
|
|
191
|
-
const
|
|
192
|
-
if (!
|
|
193
|
-
|
|
194
|
-
known = { fingerprint, summary: child, observations: claudeCapabilityUsage(ownSession, childLines, child.threadId) };
|
|
165
|
+
const child = yield* readClaudeChild(childPath, ownSession);
|
|
166
|
+
if (!child) continue;
|
|
167
|
+
known = { fingerprint, ...child };
|
|
195
168
|
progress.children.set(childPath, known);
|
|
196
169
|
}
|
|
197
170
|
childThreads.push(known.summary);
|
|
@@ -199,6 +172,7 @@ function readChildren(paths: string[], ownSession: SessionInfo, progress: Claude
|
|
|
199
172
|
rememberCapabilityObservation(observations, observation);
|
|
200
173
|
}
|
|
201
174
|
mergeRecordedClaudeUsage(observations, known.observations);
|
|
175
|
+
yield;
|
|
202
176
|
}
|
|
203
177
|
return childThreads;
|
|
204
178
|
}
|
|
@@ -252,7 +226,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
252
226
|
try {
|
|
253
227
|
progress = continues(resumable, fd, fileStat) ? resumable
|
|
254
228
|
: newProgress(fileStat.dev, fileStat.ino, basename(file, ".jsonl"));
|
|
255
|
-
yield*
|
|
229
|
+
yield* readTranscriptRows(fd, progress, fileStat.size, line => applyRow(line, progress));
|
|
256
230
|
} catch {
|
|
257
231
|
return undefined;
|
|
258
232
|
} finally {
|
|
@@ -280,19 +254,21 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
280
254
|
};
|
|
281
255
|
const actualChildPaths =
|
|
282
256
|
state.sessionId === cachedSessionId ? childPaths : claudeChildLogPaths(file, state.sessionId);
|
|
257
|
+
const scannedChildFingerprint = childLogsFingerprint(actualChildPaths);
|
|
283
258
|
const observations = progress.capabilities.snapshot();
|
|
284
|
-
const childThreads = readChildren(actualChildPaths, ownSession, progress, observations);
|
|
259
|
+
const childThreads = yield* readChildren(actualChildPaths, ownSession, progress, observations);
|
|
285
260
|
const session = aggregateChildThreads(ownSession, childThreads);
|
|
286
261
|
claudeSummaryCache.set(file, {
|
|
287
262
|
mtimeMs: fileStat.mtimeMs,
|
|
288
263
|
size: fileStat.size,
|
|
289
|
-
|
|
264
|
+
// A child can grow between cooperative slices. Only cache the snapshot we started reading.
|
|
265
|
+
childFingerprint: scannedChildFingerprint,
|
|
290
266
|
session,
|
|
291
267
|
tokensSession: session.tokensSession,
|
|
292
268
|
observations,
|
|
293
269
|
turnEnded: state.turnEnded,
|
|
294
270
|
// A chat that has gone quiet gives its memory back and is read again if it returns.
|
|
295
|
-
progress: Date.now() -
|
|
271
|
+
progress: Date.now() - session.lastActivityAt <= LIVE_MS ? progress : undefined,
|
|
296
272
|
});
|
|
297
273
|
return { session, tokensSession: session.tokensSession, childPaths: actualChildPaths };
|
|
298
274
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { diffPreviewFromInput, patchStatsByToolUse, sensitivePath, statsFromInput } from "../../support/edit-stats";
|
|
2
2
|
import { redactSecrets } from "../../telemetry/command-preview";
|
|
3
|
+
import { createChildSummary } from "./transcript-reading";
|
|
3
4
|
import { recordObservedWrite, writtenPaths } from "../../../mesh/observed/writes";
|
|
4
5
|
/**
|
|
5
6
|
* Claude Code session logs:
|
|
@@ -98,58 +99,16 @@ export function claudeChildSummary(
|
|
|
98
99
|
parentSessionId: string,
|
|
99
100
|
lines: string[],
|
|
100
101
|
): ChildThreadInfo {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const at = ts(row.timestamp);
|
|
112
|
-
if (at) {
|
|
113
|
-
if (!startedAt || at < startedAt) startedAt = at;
|
|
114
|
-
if (at > lastActivityAt) lastActivityAt = at;
|
|
115
|
-
}
|
|
116
|
-
if (!title && (row.type === "user" || row.message?.role === "user")) {
|
|
117
|
-
const content = row.message?.content;
|
|
118
|
-
if (typeof content === "string") title = childTitle(content);
|
|
119
|
-
else if (Array.isArray(content)) {
|
|
120
|
-
title = childTitle(
|
|
121
|
-
content
|
|
122
|
-
.filter((block: any) => block?.type === "text" && !pastedImageLabel(block, content))
|
|
123
|
-
.map((block: any) => block.text)
|
|
124
|
-
.join("\n"),
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
const spent = sumClaudeUsage(row.message?.usage);
|
|
129
|
-
if (spent != null) {
|
|
130
|
-
tokensSession += spent;
|
|
131
|
-
tokensLastTurn = spent;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
try {
|
|
135
|
-
const stat = statSync(path);
|
|
136
|
-
startedAt ||= stat.birthtimeMs || stat.mtimeMs;
|
|
137
|
-
lastActivityAt = Math.max(lastActivityAt, stat.mtimeMs);
|
|
138
|
-
} catch {
|
|
139
|
-
// Parsed timestamps still make this child usable.
|
|
140
|
-
}
|
|
141
|
-
claudeChildPathByThread.set(`${parentSessionId}\0${threadId}`, path);
|
|
142
|
-
return {
|
|
143
|
-
threadId,
|
|
144
|
-
parentThreadId: parentSessionId,
|
|
145
|
-
title,
|
|
146
|
-
depth: 1,
|
|
147
|
-
state: stateFor(lastActivityAt),
|
|
148
|
-
startedAt: startedAt || lastActivityAt,
|
|
149
|
-
lastActivityAt,
|
|
150
|
-
tokensSession,
|
|
151
|
-
tokensLastTurn,
|
|
152
|
-
};
|
|
102
|
+
const summary = createClaudeChildSummary(path, parentSessionId);
|
|
103
|
+
for (const line of lines) summary.add(safeParse(line));
|
|
104
|
+
return summary.finish();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createClaudeChildSummary(path: string, parentSessionId: string) {
|
|
108
|
+
return createChildSummary(path, parentSessionId, {
|
|
109
|
+
sumUsage: sumClaudeUsage,
|
|
110
|
+
remember: threadId => claudeChildPathByThread.set(`${parentSessionId}\0${threadId}`, path),
|
|
111
|
+
});
|
|
153
112
|
}
|
|
154
113
|
|
|
155
114
|
/**
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Cooperative native transcript reading
|
|
2
|
+
|
|
3
|
+
`readTranscriptRows` preserves complete UTF-8 JSONL rows, partial final appends,
|
|
4
|
+
and exact byte/tail checkpoints. It yields between bounded read/parse batches
|
|
5
|
+
and while assembling a long row. Long rows are assembled once rather than
|
|
6
|
+
recopied after every chunk. `createChildSummary` retains only native identity,
|
|
7
|
+
timestamps and reported token metadata; it preserves the array reader's result.
|
|
8
|
+
|
|
9
|
+
Behavior is exercised by the Claude reader's `tests/transport-continuity.test.ts`
|
|
10
|
+
and `tests/incremental-parse.test.ts`, including real file reads, growing children,
|
|
11
|
+
replacement/rewrites, missing newlines and callbacks during a long row.
|
|
12
|
+
|
|
13
|
+
License: [GrantTap Commercial Source License](../../../../../../../LICENSE).
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { readSync } from 'node:fs';
|
|
2
|
+
export { createChildSummary } from './summary';
|
|
3
|
+
|
|
4
|
+
export type TranscriptCheckpoint = { offset: number; tail: Buffer };
|
|
5
|
+
const CHUNK_BYTES = 1024 * 1024;
|
|
6
|
+
const TAIL_BYTES = 256;
|
|
7
|
+
|
|
8
|
+
/** Exact JSONL rows, with cooperative checkpoints even inside a long native row. */
|
|
9
|
+
export function* readTranscriptRows(fd: number, progress: TranscriptCheckpoint, size: number,
|
|
10
|
+
consume: (line: string) => boolean): Generator<void> {
|
|
11
|
+
let pieces: Buffer[] = [];
|
|
12
|
+
let carryBytes = 0;
|
|
13
|
+
while (progress.offset + carryBytes < size) {
|
|
14
|
+
const wanted = Math.min(CHUNK_BYTES, size - progress.offset - carryBytes);
|
|
15
|
+
const buffer = Buffer.allocUnsafe(wanted);
|
|
16
|
+
const count = readSync(fd, buffer, 0, wanted, progress.offset + carryBytes);
|
|
17
|
+
if (count === 0) break;
|
|
18
|
+
const chunk = buffer.subarray(0, count);
|
|
19
|
+
const end = chunk.lastIndexOf(0x0a);
|
|
20
|
+
if (end < 0) {
|
|
21
|
+
pieces.push(chunk); carryBytes += count;
|
|
22
|
+
yield;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const completed = carryBytes ? Buffer.concat([...pieces, chunk.subarray(0, end + 1)], carryBytes + end + 1)
|
|
26
|
+
: chunk.subarray(0, end + 1);
|
|
27
|
+
let rows = 0;
|
|
28
|
+
for (const line of completed.toString('utf8').split('\n')) {
|
|
29
|
+
consume(line);
|
|
30
|
+
if (++rows % 64 === 0) yield;
|
|
31
|
+
}
|
|
32
|
+
progress.offset += completed.length;
|
|
33
|
+
progress.tail = Buffer.from(completed.subarray(Math.max(0, completed.length - TAIL_BYTES)));
|
|
34
|
+
const remaining = chunk.subarray(end + 1);
|
|
35
|
+
pieces = remaining.length ? [remaining] : [];
|
|
36
|
+
carryBytes = remaining.length;
|
|
37
|
+
yield;
|
|
38
|
+
}
|
|
39
|
+
if (carryBytes) {
|
|
40
|
+
const last = Buffer.concat(pieces, carryBytes);
|
|
41
|
+
// Complete final JSON counts once; an incomplete append is retried from its last checkpoint.
|
|
42
|
+
if (consume(last.toString('utf8'))) {
|
|
43
|
+
progress.offset += carryBytes;
|
|
44
|
+
progress.tail = Buffer.from(last.subarray(Math.max(0, last.length - TAIL_BYTES)));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { statSync } from 'node:fs';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
import type { ChildThreadInfo } from '../../../../../../../packages/protocol/schema';
|
|
4
|
+
import { claudeTranscriptRecord, pastedImageLabel } from '../../../support/activity-helpers';
|
|
5
|
+
import { childTitle } from '../../../support/child-threads';
|
|
6
|
+
import { stateFor, ts } from '../../../support/common';
|
|
7
|
+
|
|
8
|
+
type Options = { sumUsage: (usage: any) => number | null | undefined; remember: (threadId: string) => void };
|
|
9
|
+
|
|
10
|
+
/** Summary state contains metadata only; transcript rows can be discarded immediately. */
|
|
11
|
+
export function createChildSummary(path: string, parentSessionId: string, options: Options) {
|
|
12
|
+
let threadId = basename(path, '.jsonl').replace(/^agent-/, '');
|
|
13
|
+
let title: string | undefined;
|
|
14
|
+
let startedAt = 0, lastActivityAt = 0, tokensSession = 0, tokensLastTurn = 0;
|
|
15
|
+
return {
|
|
16
|
+
add(row: any): void {
|
|
17
|
+
if (!row || !claudeTranscriptRecord(row)) return;
|
|
18
|
+
if (typeof row.agentId === 'string' && row.agentId) threadId = row.agentId;
|
|
19
|
+
const at = ts(row.timestamp);
|
|
20
|
+
if (at) {
|
|
21
|
+
if (!startedAt || at < startedAt) startedAt = at;
|
|
22
|
+
if (at > lastActivityAt) lastActivityAt = at;
|
|
23
|
+
}
|
|
24
|
+
if (!title && (row.type === 'user' || row.message?.role === 'user')) {
|
|
25
|
+
const content = row.message?.content;
|
|
26
|
+
if (typeof content === 'string') title = childTitle(content);
|
|
27
|
+
else if (Array.isArray(content)) title = childTitle(content
|
|
28
|
+
.filter((block: any) => block?.type === 'text' && !pastedImageLabel(block, content))
|
|
29
|
+
.map((block: any) => block.text).join('\n'));
|
|
30
|
+
}
|
|
31
|
+
const spent = options.sumUsage(row.message?.usage);
|
|
32
|
+
if (spent != null) { tokensSession += spent; tokensLastTurn = spent; }
|
|
33
|
+
},
|
|
34
|
+
finish(): ChildThreadInfo {
|
|
35
|
+
try {
|
|
36
|
+
const stat = statSync(path);
|
|
37
|
+
startedAt ||= stat.birthtimeMs || stat.mtimeMs;
|
|
38
|
+
lastActivityAt = Math.max(lastActivityAt, stat.mtimeMs);
|
|
39
|
+
} catch { /* Parsed timestamps still make a removed child usable. */ }
|
|
40
|
+
options.remember(threadId);
|
|
41
|
+
return { threadId, parentThreadId: parentSessionId, title, depth: 1, state: stateFor(lastActivityAt),
|
|
42
|
+
startedAt: startedAt || lastActivityAt, lastActivityAt, tokensSession, tokensLastTurn };
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Task activities
|
|
2
|
+
|
|
3
|
+
The public entry point is `index.ts`. A leader publishes an encrypted preview of
|
|
4
|
+
its existing root catalog to a phone-created Live Activity. It never scans a
|
|
5
|
+
provider or treats an idle execution as a completed Task. Project/Task identities
|
|
6
|
+
deduplicate executions; provider children remain inside their root conversation.
|
|
7
|
+
|
|
8
|
+
The phone enrolls an independent, expiring preview key encrypted to this computer.
|
|
9
|
+
Every publish revalidates its controller and activity scope. The relay receives
|
|
10
|
+
only ciphertext, opaque identities and delivery metadata. Privacy mode excludes
|
|
11
|
+
computer names and task text before encryption. Catalog freshness, not delivery
|
|
12
|
+
time, determines when the card becomes stale.
|
|
13
|
+
|
|
14
|
+
HTTP delivery has its own bounded, single-flight lane. An unavailable APNs route
|
|
15
|
+
does not block relay heartbeats or ordinary task delivery. Updates are coalesced
|
|
16
|
+
and the system may further limit Live Activity refreshes. Existing clients keep
|
|
17
|
+
their ordinary notifications.
|
|
18
|
+
|
|
19
|
+
This source is covered by the GrantTap Commercial Source License in `LICENSE.md`.
|
|
20
|
+
Third-party dependencies retain their own licenses and notices.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { controllerPeerGate } from '../pairing/controllers';
|
|
2
|
+
import { TaskActivityPublisher, type ActivityPublisherOptions } from './publisher';
|
|
3
|
+
export { TaskActivityPublisher } from './publisher';
|
|
4
|
+
export { taskActivitySnapshot } from './presentation';
|
|
5
|
+
export { activitySubscription } from './subscription';
|
|
6
|
+
|
|
7
|
+
export function startTaskActivities(options: Omit<ActivityPublisherOptions, 'peerAllowed'>): () => void {
|
|
8
|
+
const publisher = new TaskActivityPublisher({...options, peerAllowed: controllerPeerGate(options.config)});
|
|
9
|
+
const timer = setInterval(() => void publisher.tick(), 15_000);
|
|
10
|
+
timer.unref();
|
|
11
|
+
void publisher.tick();
|
|
12
|
+
return () => { clearInterval(timer); publisher.close(); };
|
|
13
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { SessionsStatus } from '../../../../packages/protocol/schema';
|
|
3
|
+
|
|
4
|
+
export type TaskActivitySnapshot = {version: 1; keyId: string; machine: string; taskCount: number;
|
|
5
|
+
generatedAt: number; rows: {id: string; title: string; preview: string; state: string; lastActivityAt: number}[]};
|
|
6
|
+
|
|
7
|
+
function text(value: string | undefined, bytes: number): string {
|
|
8
|
+
let result = '';
|
|
9
|
+
for (const point of (value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim()) {
|
|
10
|
+
if (Buffer.byteLength(result + point) > bytes) break;
|
|
11
|
+
result += point;
|
|
12
|
+
}
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The root catalog already owns child exclusion. Executions of one Task share one row. */
|
|
17
|
+
export function taskActivitySnapshot(catalog: SessionsStatus,
|
|
18
|
+
options: {keyId: string; previews: boolean}): TaskActivitySnapshot {
|
|
19
|
+
const tasks = new Map<string, SessionsStatus['sessions'][number]>();
|
|
20
|
+
for (const session of catalog.sessions) {
|
|
21
|
+
const key = session.projectId && session.taskId
|
|
22
|
+
? `${session.projectId}\0${session.taskId}` : session.sessionId;
|
|
23
|
+
if ((tasks.get(key)?.lastActivityAt ?? -Infinity) < session.lastActivityAt) tasks.set(key, session);
|
|
24
|
+
}
|
|
25
|
+
const sorted = [...tasks].sort(([a, left], [b, right]) =>
|
|
26
|
+
right.lastActivityAt - left.lastActivityAt || a.localeCompare(b));
|
|
27
|
+
return {version: 1, keyId: options.keyId, machine: options.previews ? text(catalog.machine, 128) : 'GrantTap',
|
|
28
|
+
taskCount: tasks.size, generatedAt: catalog.generatedAt,
|
|
29
|
+
rows: options.previews ? sorted.slice(0, 2).map(([id, item]) => ({
|
|
30
|
+
id: createHash('sha256').update(id).digest('hex').slice(0, 24),
|
|
31
|
+
title: text(item.title, 128) || 'GrantTap', preview: text(item.summary, 256),
|
|
32
|
+
state: item.state, lastActivityAt: item.lastActivityAt,
|
|
33
|
+
})) : []};
|
|
34
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import type { PeerConfig } from '../../../../packages/core/relay-client';
|
|
3
|
+
import type { SessionsStatus } from '../../../../packages/protocol/schema';
|
|
4
|
+
import { sealWithTransferKey } from '../../../../packages/core/crypto';
|
|
5
|
+
import { taskActivitySnapshot } from './presentation';
|
|
6
|
+
import { activitySubscription } from './subscription';
|
|
7
|
+
import { activityHTTP, type ActivityHTTP } from './transport';
|
|
8
|
+
|
|
9
|
+
export type ActivityPublisherOptions = {config: PeerConfig; catalog: () => SessionsStatus | null | undefined;
|
|
10
|
+
isLeader: () => boolean; peerAllowed: (key: string) => boolean; http?: ActivityHTTP; now?: () => number};
|
|
11
|
+
|
|
12
|
+
/** A separate single-flight lane consumes the published catalog; it never discovers providers. */
|
|
13
|
+
export class TaskActivityPublisher {
|
|
14
|
+
private pending?: Promise<void>;
|
|
15
|
+
private closed = false;
|
|
16
|
+
private readonly receipts = new Map<string, {fingerprint: string; sentAt: number}>();
|
|
17
|
+
private readonly http: ActivityHTTP;
|
|
18
|
+
constructor(private readonly options: ActivityPublisherOptions) { this.http = options.http ?? activityHTTP(options.config); }
|
|
19
|
+
|
|
20
|
+
tick(): Promise<void> {
|
|
21
|
+
if (this.pending) return this.pending;
|
|
22
|
+
this.pending = this.publish().catch(() => {}).finally(() => { this.pending = undefined; });
|
|
23
|
+
return this.pending;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
close(): void { this.closed = true; this.receipts.clear(); }
|
|
27
|
+
|
|
28
|
+
private active(): boolean { return !this.closed && this.options.isLeader(); }
|
|
29
|
+
|
|
30
|
+
private async publish(): Promise<void> {
|
|
31
|
+
if (!this.active() || !this.options.config.pushAuth) return;
|
|
32
|
+
const now = (this.options.now ?? Date.now)();
|
|
33
|
+
const catalog = this.options.catalog();
|
|
34
|
+
if (!catalog || !Number.isFinite(catalog.generatedAt) || catalog.generatedAt > now + 30_000
|
|
35
|
+
|| now - catalog.generatedAt > 90_000) return;
|
|
36
|
+
const result = await this.http('subscriptions') as {subscriptions?: unknown[]} | null;
|
|
37
|
+
if (!Array.isArray(result?.subscriptions) || result.subscriptions.length > 8) return;
|
|
38
|
+
const active = new Set<string>();
|
|
39
|
+
for (const record of result.subscriptions) {
|
|
40
|
+
if (!this.active()) return;
|
|
41
|
+
const subscription = activitySubscription(this.options.config, record, this.options.peerAllowed, now);
|
|
42
|
+
if (!subscription) continue;
|
|
43
|
+
active.add(subscription.activityId);
|
|
44
|
+
const snapshot = taskActivitySnapshot(catalog, subscription);
|
|
45
|
+
const fingerprint = createHash('sha256').update(JSON.stringify({...snapshot, generatedAt: 0})).digest('hex');
|
|
46
|
+
const prior = this.receipts.get(subscription.activityId);
|
|
47
|
+
if (prior && (now - prior.sentAt < 15_000
|
|
48
|
+
|| prior.fingerprint === fingerprint && now - prior.sentAt < 60_000)) continue;
|
|
49
|
+
const event = snapshot.taskCount === 0 ? 'end' : 'update';
|
|
50
|
+
const contentState = sealWithTransferKey(snapshot, subscription.key);
|
|
51
|
+
if (!this.active() || !this.options.peerAllowed(subscription.peerPublicKey)) continue;
|
|
52
|
+
const delivered = await this.http('update', {activityId: subscription.activityId, deliveryId: randomUUID(),
|
|
53
|
+
event, staleDate: Math.floor((catalog.generatedAt + 90_000) / 1_000), contentState}) as
|
|
54
|
+
{accepted?: boolean; closed?: boolean} | null;
|
|
55
|
+
if (delivered?.accepted) this.receipts.set(subscription.activityId, {fingerprint, sentAt: now});
|
|
56
|
+
if (delivered?.closed) this.receipts.delete(subscription.activityId);
|
|
57
|
+
}
|
|
58
|
+
for (const id of this.receipts.keys()) if (!active.has(id)) this.receipts.delete(id);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { PeerConfig } from '../../../../packages/core/relay-client';
|
|
3
|
+
import { openFromPeersWithIdentity } from '../../../../packages/core/crypto';
|
|
4
|
+
|
|
5
|
+
const subscription = z.object({version: z.literal(1), kind: z.literal('task.activity.subscription'),
|
|
6
|
+
room: z.string().min(1).max(180), activityId: z.string().regex(/^[A-Za-z0-9_-]{1,180}$/),
|
|
7
|
+
keyId: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/), key: z.string().min(43).max(44),
|
|
8
|
+
expiresAt: z.number().int().positive(), previews: z.boolean()}).strict();
|
|
9
|
+
const route = z.object({activityId: z.string(), expiresAt: z.number(),
|
|
10
|
+
nonce: z.string().length(32), box: z.string().min(24).max(2048)}).strict();
|
|
11
|
+
export type ActivitySubscription = z.infer<typeof subscription> & {peerPublicKey: string};
|
|
12
|
+
|
|
13
|
+
export function activitySubscription(config: PeerConfig, input: unknown,
|
|
14
|
+
peerAllowed: (key: string) => boolean, now: number): ActivitySubscription | null {
|
|
15
|
+
const record = route.safeParse(input);
|
|
16
|
+
if (!record.success) return null;
|
|
17
|
+
const opened = openFromPeersWithIdentity(record.data.nonce, record.data.box, config.mySecretKey,
|
|
18
|
+
config.peerPublicKey, config.extraPeerPublicKeys);
|
|
19
|
+
if (!opened || !peerAllowed(opened.peerPublicKey)) return null;
|
|
20
|
+
const parsed = subscription.safeParse(opened.body);
|
|
21
|
+
if (!parsed.success) return null;
|
|
22
|
+
const value = parsed.data;
|
|
23
|
+
if (value.room !== config.room || value.activityId !== record.data.activityId
|
|
24
|
+
|| value.expiresAt !== record.data.expiresAt || value.expiresAt <= now
|
|
25
|
+
|| value.expiresAt > now + 8 * 60 * 60_000 || Buffer.from(value.key, 'base64url').length !== 32) return null;
|
|
26
|
+
return {...value, peerPublicKey: opened.peerPublicKey};
|
|
27
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PeerConfig } from '../../../../packages/core/relay-client';
|
|
2
|
+
|
|
3
|
+
export type ActivityHTTP = (path: 'subscriptions' | 'update', body?: unknown) => Promise<unknown>;
|
|
4
|
+
|
|
5
|
+
/** Never follow an HTTP redirect with the room credential. Responses and time are bounded. */
|
|
6
|
+
export function activityHTTP(config: PeerConfig, request: typeof fetch = fetch): ActivityHTTP {
|
|
7
|
+
return async (path, body) => {
|
|
8
|
+
if (!config.pushAuth) return null;
|
|
9
|
+
const url = new URL(config.relayUrl);
|
|
10
|
+
url.protocol = url.protocol === 'wss:' ? 'https:' : url.protocol === 'ws:' ? 'http:' : url.protocol;
|
|
11
|
+
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return null;
|
|
12
|
+
url.pathname = `/push/activity/${path}`;
|
|
13
|
+
url.search = new URLSearchParams({room: config.room}).toString(); url.hash = '';
|
|
14
|
+
const response = await request(url, {method: body === undefined ? 'GET' : 'POST', redirect: 'error',
|
|
15
|
+
headers: {Authorization: `Bearer ${config.pushAuth}`, 'Content-Type': 'application/json'},
|
|
16
|
+
signal: AbortSignal.timeout(8_000), body: body === undefined ? undefined : JSON.stringify(body)});
|
|
17
|
+
if (!response.ok || !response.body) return null;
|
|
18
|
+
const reader = response.body.getReader(); let bytes = 0; const chunks: Uint8Array[] = [];
|
|
19
|
+
while (true) {
|
|
20
|
+
const part = await reader.read(); if (part.done) break;
|
|
21
|
+
bytes += part.value.byteLength;
|
|
22
|
+
if (bytes > 24_000) { await reader.cancel(); return null; }
|
|
23
|
+
chunks.push(part.value);
|
|
24
|
+
}
|
|
25
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -64,7 +64,7 @@ export async function relay(): Promise<RelayClient | null> {
|
|
|
64
64
|
recordPhoneSeen(phoneLastSeenAt, peerPublicKey);
|
|
65
65
|
return false;
|
|
66
66
|
});
|
|
67
|
-
monitor = startSessionMonitor(client);
|
|
67
|
+
monitor = startSessionMonitor(client, {config});
|
|
68
68
|
stopEndpointPublisher = startEndpointPublisher(config);
|
|
69
69
|
}
|
|
70
70
|
await client.connect();
|
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.155
|
|
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.155\";\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.155";
|
|
11
11
|
const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
|
|
12
12
|
const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
|
|
13
13
|
? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
|
package/package.json
CHANGED
|
@@ -121,6 +121,7 @@ export const MachineHeartbeat = z.object({
|
|
|
121
121
|
createdAt: z.number().catch(() => Date.now()),
|
|
122
122
|
taskQueueImmediate: z.boolean().optional(),
|
|
123
123
|
taskScheduleControls: z.boolean().optional(),
|
|
124
|
+
taskActivityPreviews: z.boolean().optional(),
|
|
124
125
|
});
|
|
125
126
|
export type MachineHeartbeat = z.infer<typeof MachineHeartbeat>;
|
|
126
127
|
|