granttap-mcp 0.8.153 → 0.8.154

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 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
@@ -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
- " <string>Background</string>",
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
- scanSessionHistory,
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 scanSessions().sessions.find((session) => session.sessionId === sessionId)
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 { scanSessions } from "../../sessions";
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
- ?? scanSessions().sessions.find((session) => session.sessionId === message.sessionId);
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;
@@ -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 { scanSessions, scanSessionHistory } from '../sessions';
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
- ?? scanSessions().sessions.find(s => s.sessionId === query.sessionId)
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 childLines = readLines(childPath);
192
- if (!childLines) continue;
193
- const child = claudeChildSummary(childPath, ownSession.sessionId, childLines);
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* readAppended(fd, progress, fileStat.size);
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
- childFingerprint: childLogsFingerprint(actualChildPaths),
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() - state.lastActivityAt <= LIVE_MS ? progress : undefined,
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
- let threadId = basename(path, ".jsonl").replace(/^agent-/, "");
102
- let title: string | undefined;
103
- let startedAt = 0;
104
- let lastActivityAt = 0;
105
- let tokensSession = 0;
106
- let tokensLastTurn = 0;
107
- for (const line of lines) {
108
- const row = safeParse(line);
109
- if (!row || !claudeTranscriptRecord(row)) continue;
110
- if (typeof row.agentId === "string" && row.agentId) threadId = row.agentId;
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
+ }
@@ -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.153
13
+ npm install -g granttap-mcp@0.8.154
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -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.153\";\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"
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.154\";\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.153";
10
+ const PACKAGE = "granttap-mcp@0.8.154";
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.153",
3
+ "version": "0.8.154",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {