granttap-mcp 0.8.126 → 0.8.128

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 (27) hide show
  1. package/apps/bridge/src/monitor/README.md +5 -0
  2. package/apps/bridge/src/monitor/handlers/catalog.ts +6 -3
  3. package/apps/bridge/src/monitor/support/leadership.ts +9 -5
  4. package/apps/bridge/src/monitor/support/runtime.ts +12 -1
  5. package/apps/bridge/src/monitor/support/session-activity.ts +3 -3
  6. package/apps/bridge/src/providers/grok-conversation/README.md +9 -0
  7. package/apps/bridge/src/providers/grok-conversation/capture.ts +46 -0
  8. package/apps/bridge/src/providers/grok-conversation/images.ts +20 -0
  9. package/apps/bridge/src/providers/grok-conversation/index.ts +3 -23
  10. package/apps/bridge/src/providers/grok-conversation/projection.ts +29 -11
  11. package/apps/bridge/src/providers/grok-conversation/reader.ts +26 -0
  12. package/apps/bridge/src/session-catalog/README.md +7 -0
  13. package/apps/bridge/src/session-catalog/observed-state.ts +59 -0
  14. package/apps/bridge/src/session-catalog/open-chat-updates.ts +52 -0
  15. package/apps/bridge/src/sessions/scan/claude/parse.ts +2 -11
  16. package/apps/bridge/src/sessions/scan/claude/turn-state/README.md +9 -0
  17. package/apps/bridge/src/sessions/scan/claude/turn-state/index.ts +17 -0
  18. package/apps/bridge/src/sessions/scan/grok.ts +7 -1
  19. package/apps/bridge/src/task-dispatch/worker/monitor.ts +2 -7
  20. package/apps/bridge/src/task-dispatch/worker/readiness.ts +8 -0
  21. package/apps/bridge/src/task-transfer/context/readers.ts +47 -0
  22. package/apps/bridge/src/task-transfer/context.ts +9 -29
  23. package/apps/bridge/src/transcript-history/index.ts +2 -2
  24. package/cursor-plugin/README.md +1 -1
  25. package/cursor-plugin/mcp.json +1 -1
  26. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  27. package/package.json +1 -1
@@ -4,6 +4,11 @@
4
4
  Chat catalogs publish independently of background Mesh enrichment. The Mesh
5
5
  publisher reuses known native identities and yields between Projects.
6
6
 
7
+ Routing leadership requires a connected relay socket. An offline primary
8
+ releases its lease when polled, allowing an online peer to handle phone commands
9
+ immediately. Reconnecting restores the primary's priority without restarting
10
+ the coding providers or changing pending message identities.
11
+
7
12
  Architecture responses acknowledge their explicit request. Coalesced builds
8
13
  retain every controller's receipt; periodic cached reports remain ordinary Mesh
9
14
  snapshots. Repository analysis uses its own Engine socket to keep policy and
@@ -1,6 +1,7 @@
1
1
  import type { SessionInfo, SessionsStatus } from "../../../../../packages/protocol/schema";
2
2
  import type { RelayClient } from "../../../../../packages/core/relay-client";
3
3
  import { sendSessionPayload } from "../../host/session-keys";
4
+ import { observeSessionExecution } from "../../session-catalog/observed-state";
4
5
  import { cachedSessionActivity } from "../support/session-activity";
5
6
  import { readTranscriptHistory } from "../../transcript-history";
6
7
  import { publishedSession } from "../../session-catalog";
@@ -84,11 +85,13 @@ async function sendTranscript(
84
85
  threadId?: string,
85
86
  history?: { history?: boolean; historyCursor?: string; peerPublicKey?: string },
86
87
  ): Promise<boolean> {
87
- const session = resolveSession(client, sessionId, status);
88
- if (!session) return false;
88
+ const known = resolveSession(client, sessionId, status);
89
+ if (!known) return false;
90
+ const observation = observeSessionExecution(known);
91
+ const session = observation?.session ?? known;
89
92
  const activity = threadId ? scanThreadActivity(session, threadId)
90
93
  : (history?.history ? readTranscriptHistory(session, history.historyCursor) : undefined)
91
- ?? cachedSessionActivity(session);
94
+ ?? cachedSessionActivity(session, false, observation?.revision);
92
95
  await sendSessionPayload(client, activityWithImages(activity), sessionId, "phone", {
93
96
  ttlMs: INTERVAL_MS * 24,
94
97
  reliable: false,
@@ -90,6 +90,7 @@ function tryAcquireLock(input: {
90
90
  export function monitorLeadership(
91
91
  now: () => number = Date.now,
92
92
  report: (message: string) => void = (message) => process.stderr.write(message),
93
+ connected: () => boolean = () => true,
93
94
  ): MonitorLeadership {
94
95
  const path = join(configDir(), "monitor.lock");
95
96
  const primary = process.env.GRANTTAP_MONITOR_PRIMARY === "1";
@@ -130,11 +131,14 @@ export function monitorLeadership(
130
131
  );
131
132
  };
132
133
 
133
- const acquire = (): boolean => tryAcquireLock({
134
- path, token, primary, read, write, expired, ownerIsPrimary, reportRefusal,
135
- getLeader: () => leader,
136
- setLeader: (value) => { leader = value; },
137
- });
134
+ const acquire = (): boolean => {
135
+ if (!connected()) { release(); return false; }
136
+ return tryAcquireLock({
137
+ path, token, primary, read, write, expired, ownerIsPrimary, reportRefusal,
138
+ getLeader: () => leader,
139
+ setLeader: (value) => { leader = value; },
140
+ });
141
+ };
138
142
 
139
143
  const release = (): void => {
140
144
  if (!leader || read() !== token) return;
@@ -22,6 +22,7 @@ import { HEARTBEAT_INTERVAL_MS, publishHeartbeat } from "./heartbeat";
22
22
  import { confirmPendingController } from "../../pairing/controllers";
23
23
  import { recordControllerName } from "../../pairing/presence";
24
24
  import { startPublishLoop } from "./publish-loop";
25
+ import { openChatUpdates, OPEN_CHAT_INTERVAL_MS } from "../../session-catalog/open-chat-updates";
25
26
  import { singleFlightPublisher } from "./single-flight";
26
27
  import { publishedCatalog, rememberPublishedCatalog, resumePublishedChats,
27
28
  publishCatalogHeads, stopCatalogHeads } from "../../session-catalog";
@@ -172,7 +173,7 @@ async function publishMonitorTick(input: {
172
173
  */
173
174
  export function startSessionMonitor(client: RelayClient): SessionMonitor {
174
175
  const subscriptions = new Set<string>();
175
- const leadership = monitorLeadership();
176
+ const leadership = monitorLeadership(Date.now, undefined, () => client.isConnected);
176
177
  restoreMonitorState(client);
177
178
  let historyCache: { generatedAt: number; sessions: SessionsStatus["sessions"] } | undefined;
178
179
  let historyRead: Promise<SessionsStatus["sessions"]> | undefined;
@@ -234,6 +235,15 @@ export function startSessionMonitor(client: RelayClient): SessionMonitor {
234
235
  publish: () => publishHeartbeat(client).catch(() => {}),
235
236
  });
236
237
  const stopQuestions = startQuestionLoop(client, leadership, subscriptions);
238
+ const stopChats = startPublishLoop({
239
+ connected: () => client.isConnected,
240
+ intervalMs: OPEN_CHAT_INTERVAL_MS,
241
+ publish: openChatUpdates({
242
+ catalog: () => publishedCatalog(client), subscriptions,
243
+ active: () => !closed && client.isConnected && leadership.acquire(),
244
+ publish: (id, status) => publishSessionEvents(client, id, status),
245
+ }),
246
+ });
237
247
 
238
248
  return {
239
249
  publish: () => publish(false),
@@ -248,6 +258,7 @@ export function startSessionMonitor(client: RelayClient): SessionMonitor {
248
258
  stopMonitorMeshes(client);
249
259
  stopHeartbeat();
250
260
  stopQuestions();
261
+ stopChats();
251
262
  loadLoop.stop();
252
263
  off();
253
264
  subscriptions.clear();
@@ -28,10 +28,10 @@ function cacheKey(session: SessionInfo): string {
28
28
  export function sessionActivityCache(
29
29
  read: ActivityReader,
30
30
  capacity = 64,
31
- ): (session: SessionInfo, forceScan?: boolean) => SessionActivity {
31
+ ): (session: SessionInfo, forceScan?: boolean, sourceRevision?: string) => SessionActivity {
32
32
  const cache = new Map<string, SessionActivity>();
33
- return (session, forceScan = false) => {
34
- const key = cacheKey(session);
33
+ return (session, forceScan = false, sourceRevision = "") => {
34
+ const key = `${cacheKey(session)}\0${sourceRevision}`;
35
35
  if (!forceScan) {
36
36
  const hit = cache.get(key);
37
37
  // Refresh recency so a chat the user keeps open is never the eviction
@@ -18,4 +18,13 @@ instead of calling a partial archive complete. Older CLIs without `updates.jsonl
18
18
  retain their previous reader. Tests live in
19
19
  `../../sessions/scan/tests/grok-persisted-updates.test.ts`.
20
20
 
21
+ Transfers use `captureGrokConversation` in `capture.ts`, independently of the
22
+ bounded display cache. It streams a stable snapshot from byte zero and yields
23
+ between 64 KiB chunks. A native log may contain up to 512 MiB of restore events;
24
+ only visible messages, tool summaries and recoverable images enter the existing
25
+ 16 MB transfer context. The projection permits up to 50,000 visible entries;
26
+ each image remains limited to 8 MiB. Hidden reasoning and hook output stay out.
27
+ Incomplete records, changed source files, invalid images and exceeded budgets
28
+ refuse the transfer. No truncated display projection is called complete.
29
+
21
30
  Licensed under the repository-root GrantTap Commercial Source License.
@@ -0,0 +1,46 @@
1
+ import { createReadStream, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { setImmediate } from 'node:timers/promises';
4
+ import { newProjection } from './projection';
5
+ import { consumeConversationChunk, type ConversationReader } from './reader';
6
+
7
+ const maximumCaptureBytes = 512 * 1024 * 1024;
8
+
9
+ /** Read from the start, yielding between chunks; UI tail caches are never a transfer source. */
10
+ export async function captureGrokConversation(directory: string, sessionId: string) {
11
+ const path = join(directory, 'updates.jsonl');
12
+ let before;
13
+ try { before = statSync(path); }
14
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error; }
15
+ if (before.size > maximumCaptureBytes) throw new Error('The native Grok log exceeds the complete capture budget.');
16
+ const reader: ConversationReader = { device: before.dev, inode: before.ino, offset: 0,
17
+ modified: before.mtimeMs, pending: Buffer.alloc(0), discard: false, incomplete: false,
18
+ projection: newProjection(sessionId, true) };
19
+ if (before.size) {
20
+ const stream = createReadStream(path, { end: before.size - 1, highWaterMark: 64 * 1024 });
21
+ for await (const chunk of stream) {
22
+ consumeConversationChunk(reader, chunk as Buffer);
23
+ if (reader.incomplete || reader.projection.bounded) {
24
+ throw new Error('The complete native Grok conversation exceeds its transfer budget or contains unrecoverable data.');
25
+ }
26
+ await setImmediate();
27
+ }
28
+ }
29
+ const unchanged = () => {
30
+ try {
31
+ const current = statSync(path);
32
+ return current.dev === before.dev && current.ino === before.ino
33
+ && current.size === before.size && current.mtimeMs === before.mtimeMs;
34
+ } catch { return false; }
35
+ };
36
+ if (reader.pending.length || reader.offset !== before.size || !unchanged()) {
37
+ throw new Error('The Grok conversation changed or is still being written. No partial transfer was sent.');
38
+ }
39
+ const image = (_session: unknown, id: string, offset: number) => {
40
+ const value = reader.projection.images?.get(id);
41
+ if (!value || !Number.isSafeInteger(offset) || offset < 0 || offset >= value.bytes.length) return undefined;
42
+ return { mime_type: value.mime, total_bytes: value.bytes.length, offset,
43
+ data_base64: value.bytes.subarray(offset, offset + 64 * 1024).toString('base64') };
44
+ };
45
+ return { entries: reader.projection.entries, image, unchanged };
46
+ }
@@ -0,0 +1,20 @@
1
+ import type { ActivityEntry } from '../../../../../packages/protocol/schema';
2
+
3
+ export type ConversationImage = { bytes: Buffer; mime: string };
4
+
5
+ /** Native image bytes remain private to the capture and are never put in a catalog. */
6
+ export function conversationImage(content: Record<string, unknown>, sessionId: string, offset: number, at: number) {
7
+ const mime = content.mimeType ?? content.mime_type;
8
+ if (typeof content.data !== 'string' || content.data.length > 11_200_000
9
+ || !['image/png', 'image/jpeg', 'image/webp'].includes(String(mime))) return undefined;
10
+ const bytes = Buffer.from(content.data, 'base64');
11
+ if (!bytes.length || bytes.length > 8 * 1024 * 1024 || bytes.toString('base64') !== content.data) return undefined;
12
+ const valid = mime === 'image/png' ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
13
+ : mime === 'image/jpeg' ? bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255]))
14
+ : bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP';
15
+ if (!valid) return undefined;
16
+ const id = `${sessionId}:native-image:${offset}`;
17
+ const entry: ActivityEntry = { id, kind: 'user', text: '[Image]', createdAt: at,
18
+ attachments: ['Image'], images: [{ id, name: 'Image', markdown: `![Image](granttap-image:${id})` }] };
19
+ return { entry, image: { bytes, mime: String(mime) }, encodedBytes: content.data.length };
20
+ }
@@ -1,13 +1,12 @@
1
1
  import { closeSync, openSync, readSync, statSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import type { ActivityEntry } from '../../../../../packages/protocol/schema';
4
- import { newProjection, projectConversationUpdate, type ConversationProjection } from './projection';
4
+ import { newProjection } from './projection';
5
+ import { consumeConversationChunk as consume, type ConversationReader as Reader } from './reader';
6
+ export { captureGrokConversation } from './capture';
5
7
 
6
- type Reader = { device: number; inode: number; offset: number; modified: number;
7
- pending: Buffer; discard: boolean; incomplete: boolean; projection: ConversationProjection };
8
8
  const readers = new Map<string, Reader>();
9
9
  const maximumBytes = 64 * 1024 * 1024;
10
- const maximumRecord = 8 * 1024 * 1024;
11
10
 
12
11
  /** Read the native restore transcript, independently of compacted model context. */
13
12
  export function readGrokConversation(directory: string, sessionId: string, requireComplete = false): ActivityEntry[] | undefined {
@@ -45,22 +44,3 @@ export function readGrokConversation(directory: string, sessionId: string, requi
45
44
  return undefined;
46
45
  } finally { if (fd !== undefined) closeSync(fd); }
47
46
  }
48
-
49
- function consume(reader: Reader, chunk: Buffer): void {
50
- const startOffset = reader.offset - reader.pending.length;
51
- const bytes = reader.pending.length ? Buffer.concat([reader.pending, chunk]) : chunk;
52
- let from = 0;
53
- for (let end = bytes.indexOf(10); end >= 0; end = bytes.indexOf(10, from)) {
54
- if (!reader.discard && end - from <= maximumRecord) {
55
- try {
56
- const value: unknown = JSON.parse(bytes.subarray(from, end).toString('utf8'));
57
- projectConversationUpdate(reader.projection, value, startOffset + from);
58
- } catch { reader.incomplete = true; }
59
- } else reader.incomplete = true;
60
- reader.discard = false; from = end + 1;
61
- }
62
- const remaining = bytes.subarray(from);
63
- reader.pending = remaining.length <= maximumRecord ? Buffer.from(remaining) : Buffer.alloc(0);
64
- if (remaining.length > maximumRecord) { reader.discard = true; reader.incomplete = true; }
65
- reader.offset += chunk.length;
66
- }
@@ -2,6 +2,7 @@ import type { ActivityEntry } from '../../../../../packages/protocol/schema';
2
2
  import { classifyTool, pushEntry, stripTranscriptMarkup, visibleUserText } from '../../sessions/support/activity-helpers';
3
3
  import { grokRecordedChanges, grokToolCalls, grokToolSummary } from '../grok-tools';
4
4
  import { confirmedUpdateChanges } from '../acp-file-changes';
5
+ import { conversationImage, type ConversationImage } from './images';
5
6
 
6
7
  export type ConversationProjection = {
7
8
  sessionId: string;
@@ -13,10 +14,18 @@ export type ConversationProjection = {
13
14
  text?: { entry: ActivityEntry; raw: string };
14
15
  sizes: Map<ActivityEntry, number>;
15
16
  bytes: number;
17
+ textLimit: number;
18
+ entryLimit: number;
19
+ byteLimit: number;
20
+ toolIds: Set<string>;
21
+ images?: Map<string, ConversationImage>;
16
22
  };
17
23
 
18
- export function newProjection(sessionId: string): ConversationProjection {
19
- return { sessionId, entries: [], calls: new Map(), bounded: false, sizes: new Map(), bytes: 0 };
24
+ export function newProjection(sessionId: string, complete = false): ConversationProjection {
25
+ return { sessionId, entries: [], calls: new Map(), bounded: false, sizes: new Map(), bytes: 0,
26
+ textLimit: complete ? 16_000_000 : 65_536, entryLimit: complete ? 50_000 : 4096,
27
+ byteLimit: complete ? 16_000_000 : 8 * 1024 * 1024, toolIds: new Set(),
28
+ ...(complete ? { images: new Map() } : {}) };
20
29
  }
21
30
 
22
31
  const object = (value: unknown): Record<string, unknown> | undefined =>
@@ -34,11 +43,18 @@ export function projectConversationUpdate(state: ConversationProjection, value:
34
43
  let changed: ActivityEntry | undefined;
35
44
  if (kind === 'user_message_chunk' || kind === 'agent_message_chunk') {
36
45
  const content = object(update.content), meta = object(update._meta);
46
+ if (meta?.syntheticReason != null || meta?.synthetic_reason != null) return;
47
+ if (kind === 'user_message_chunk' && content?.type === 'image' && state.images) {
48
+ const captured = conversationImage(content, state.sessionId, offset, at);
49
+ if (!captured) { state.bounded = true; return; }
50
+ state.entries.push(captured.entry); state.images.set(captured.entry.id, captured.image);
51
+ state.bytes += captured.encodedBytes; state.speaking = undefined; state.userKey = undefined; state.text = undefined;
52
+ boundProjection(state, captured.entry); return;
53
+ }
37
54
  if (content?.type !== 'text' || typeof content.text !== 'string' || !content.text) {
38
55
  if (kind === 'user_message_chunk' && content?.type === 'image') state.bounded = true;
39
56
  return;
40
57
  }
41
- if (meta?.syntheticReason != null || meta?.synthetic_reason != null) return;
42
58
  const user = kind === 'user_message_chunk';
43
59
  const promptIndex = meta?.promptIndex;
44
60
  const key = user && Number.isSafeInteger(promptIndex) && Number(promptIndex) >= 0
@@ -46,22 +62,22 @@ export function projectConversationUpdate(state: ConversationProjection, value:
46
62
  const previous = state.entries.at(-1);
47
63
  if (previous && (user && previous.kind === 'user' && state.userKey === key || !user && state.speaking === previous)) {
48
64
  const raw = (state.text?.entry === previous ? state.text.raw : previous.text) + content.text;
49
- state.text = { entry: previous, raw: raw.slice(0, 65_536) };
65
+ state.text = { entry: previous, raw: raw.slice(0, state.textLimit) };
50
66
  previous.text = user ? visibleUserText(state.text.raw) : stripTranscriptMarkup(state.text.raw);
51
- if (raw.length > 65_536) state.bounded = true;
67
+ if (raw.length > state.textLimit) state.bounded = true;
52
68
  boundProjection(state, previous);
53
69
  return;
54
70
  }
55
71
  const count = state.entries.length;
56
72
  pushEntry({ out: state.entries, seen: new Set(), sessionId: state.sessionId, kind: user ? 'user' : 'message',
57
- text: content.text.slice(0, 65_536), createdAt: at, ordinal: offset, idOverride: key, fullText: true });
73
+ text: content.text.slice(0, state.textLimit), createdAt: at, ordinal: offset, idOverride: key, fullText: true });
58
74
  if (state.entries.length > count) {
59
75
  changed = state.entries.at(-1);
60
- state.text = { entry: changed!, raw: content.text.slice(0, 65_536) };
76
+ state.text = { entry: changed!, raw: content.text.slice(0, state.textLimit) };
61
77
  if (user) { state.userKey = key; state.speaking = undefined; }
62
78
  else state.speaking = state.entries.at(-1);
63
79
  }
64
- if (content.text.length > 65_536) state.bounded = true;
80
+ if (content.text.length > state.textLimit) state.bounded = true;
65
81
  } else if (kind === 'tool_call') {
66
82
  changed = projectTool(state, update, at, offset);
67
83
  } else if (kind === 'tool_call_update') {
@@ -90,7 +106,8 @@ export function projectConversationUpdate(state: ConversationProjection, value:
90
106
  function projectTool(state: ConversationProjection, update: Record<string, unknown>, at: number, offset: number): ActivityEntry | undefined {
91
107
  const native = object(object(update._meta)?.['x.ai/tool']);
92
108
  const call = grokToolCalls({ tool_calls: [{ id: update.toolCallId, name: native?.name, arguments: update.rawInput }] })[0];
93
- if (!call?.id || state.entries.some(entry => entry.id === `${state.sessionId}:tool:${call.id}`)) return;
109
+ if (!call?.id || state.toolIds.has(call.id)) return;
110
+ state.toolIds.add(call.id);
94
111
  state.speaking = undefined;
95
112
  const identity = classifyTool(call.name, call.input);
96
113
  pushEntry({ out: state.entries, seen: new Set(), sessionId: state.sessionId, kind: 'tool',
@@ -107,14 +124,15 @@ function boundProjection(state: ConversationProjection, changed?: ActivityEntry)
107
124
  const bytes = Buffer.byteLength(JSON.stringify(changed));
108
125
  state.bytes += bytes - (state.sizes.get(changed) ?? 0); state.sizes.set(changed, bytes);
109
126
  }
110
- while (state.entries.length > 4096 || state.bytes > 8 * 1024 * 1024) {
127
+ while (state.entries.length > state.entryLimit || state.bytes > state.byteLimit) {
111
128
  const removed = state.entries.shift();
112
129
  if (!removed) break;
113
130
  state.bytes -= state.sizes.get(removed) ?? 0; state.sizes.delete(removed);
131
+ if (removed.kind === 'tool') state.toolIds.delete(removed.id.slice(`${state.sessionId}:tool:`.length));
114
132
  for (const [id, call] of state.calls) if (call.entry === removed) state.calls.delete(id);
115
133
  state.bounded = true;
116
134
  }
117
- if (state.calls.size > 256) {
135
+ if (state.calls.size > (state.images ? 50_000 : 256)) {
118
136
  state.calls.delete(state.calls.keys().next().value!); state.bounded = true;
119
137
  }
120
138
  }
@@ -0,0 +1,26 @@
1
+ import { projectConversationUpdate, type ConversationProjection } from './projection';
2
+
3
+ export type ConversationReader = { device: number; inode: number; offset: number; modified: number;
4
+ pending: Buffer; discard: boolean; incomplete: boolean; projection: ConversationProjection };
5
+
6
+ const maximumRecord = 8 * 1024 * 1024;
7
+
8
+ /** Preserve native byte offsets across UTF-8 and incomplete JSON records. */
9
+ export function consumeConversationChunk(reader: ConversationReader, chunk: Buffer): void {
10
+ const startOffset = reader.offset - reader.pending.length;
11
+ const bytes = reader.pending.length ? Buffer.concat([reader.pending, chunk]) : chunk;
12
+ let from = 0;
13
+ for (let end = bytes.indexOf(10); end >= 0; end = bytes.indexOf(10, from)) {
14
+ if (!reader.discard && end - from <= maximumRecord) {
15
+ try {
16
+ const value: unknown = JSON.parse(bytes.subarray(from, end).toString('utf8'));
17
+ projectConversationUpdate(reader.projection, value, startOffset + from);
18
+ } catch { reader.incomplete = true; }
19
+ } else reader.incomplete = true;
20
+ reader.discard = false; from = end + 1;
21
+ }
22
+ const remaining = bytes.subarray(from);
23
+ reader.pending = remaining.length <= maximumRecord ? Buffer.from(remaining) : Buffer.alloc(0);
24
+ if (remaining.length > maximumRecord) { reader.discard = true; reader.incomplete = true; }
25
+ reader.offset += chunk.length;
26
+ }
@@ -32,3 +32,10 @@ and metadata caches serve synchronous CLI readers and cooperative live-monitor
32
32
  readers. Checkout observations are scoped to one asynchronous scan, so unrelated
33
33
  requests cannot inherit an old directory result. Socket recovery immediately
34
34
  republishes the current catalog instead of waiting for the next periodic tick.
35
+
36
+ Open and working chats follow a separate two-second loop of known native sources.
37
+ Only changed source revisions send encrypted transcript heads; reads and sends
38
+ remain single-flight and bounded to eight chats per pass. Claude end-turn and
39
+ Codex turn events update execution state immediately after observation. The same
40
+ native observation releases queued messages without waiting for full discovery.
41
+ A fresh chat does not advance the observation clock of unrelated catalog rows.
@@ -0,0 +1,59 @@
1
+ import {statSync} from 'node:fs';
2
+ import {join} from 'node:path';
3
+ import {homedir} from 'node:os';
4
+ import type {SessionInfo} from '../../../../packages/protocol/schema';
5
+ import {localTaskTransfers} from '../task-transfer';
6
+ import {nativeTranscriptSource} from '../sessions/native-source';
7
+ import {claudeLogPath} from '../sessions/scan/claude/shared';
8
+ import {previousNativeLines} from '../transcript-history/native-lines';
9
+ import {observeClaudeTurn,claudeTurnState,type ClaudeTurnClock} from '../sessions/scan/claude/turn-state';
10
+ import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/scan/codex/turn-state';
11
+ import {ts} from '../sessions/support/common';
12
+ import {grokResumeActivity} from '../providers/grok-activity';
13
+ import {cursorConversationSession} from '../sessions/cursor';
14
+
15
+ type NativeClock={revision:string;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock};
16
+ const clocks=new Map<string,NativeClock>();
17
+ export type SessionObservation={session:SessionInfo;revision:string};
18
+
19
+ /** A known chat uses one bounded native tail, never discovery across unrelated projects. */
20
+ export function observeSessionExecution(input:SessionInfo):SessionObservation|undefined {
21
+ const native=localTaskTransfers().nativeSession(input);
22
+ if(native.agent==='cursor'){
23
+ const current=cursorConversationSession(native.sessionId);
24
+ return current?{session:{...input,state:current.state,lastActivityAt:current.lastActivityAt},revision:`${current.lastActivityAt}:${current.state}`}:undefined;
25
+ }
26
+ if(native.agent==='grok'){
27
+ const live=grokResumeActivity(native);
28
+ if(!native.cwd||!live)return;
29
+ const root=process.env.GRANTTAP_GROK_SESSIONS_DIR??join(process.env.GROK_HOME??join(homedir(),'.grok'),'sessions');
30
+ try{
31
+ const stat=statSync(join(root,encodeURIComponent(native.cwd),native.sessionId,'updates.jsonl'));
32
+ return {session:{...input,state:live.state,lastActivityAt:Math.max(input.lastActivityAt,live.updatedAt)},revision:`${stat.ino}:${stat.size}:${stat.mtimeMs}:${live.state}`};
33
+ }catch{return;}
34
+ }
35
+ if(native.agent!=='claude'&&native.agent!=='codex')return;
36
+ const path=nativeTranscriptSource(native)??(native.agent==='claude'?claudeLogPath(native.sessionId):undefined);
37
+ if(!path)return;
38
+ try{
39
+ const stat=statSync(path),revision=`${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
40
+ const key=`${native.agent}:${native.sessionId}:${path}`;
41
+ let clock=clocks.get(key);
42
+ if(clock?.revision!==revision){
43
+ const window=previousNativeLines(path,native.sessionId);if(!window)return;
44
+ clock={revision,lastActivityAt:0,claude:{},codex:{}};
45
+ for(const line of window.lines){
46
+ let row;try{row=JSON.parse(line.text)}catch{continue}
47
+ if(row.isSidechain===true||row.sessionId&&row.sessionId!==native.sessionId)continue;
48
+ clock.lastActivityAt=Math.max(clock.lastActivityAt,ts(row.timestamp));
49
+ if(native.agent==='claude')observeClaudeTurn(row,clock.claude);else observeCodexTurn(row,clock.codex);
50
+ }
51
+ clocks.delete(key);clocks.set(key,clock);
52
+ while(clocks.size>256)clocks.delete(clocks.keys().next().value!);
53
+ }
54
+ const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
55
+ const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
56
+ :clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
57
+ return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
58
+ }catch{return;}
59
+ }
@@ -0,0 +1,52 @@
1
+ import type {SessionInfo, SessionsStatus} from '../../../../packages/protocol/schema';
2
+ import {observeSessionExecution, type SessionObservation} from './observed-state';
3
+
4
+ export const OPEN_CHAT_INTERVAL_MS = 2_000;
5
+
6
+ /** Follow known native files independently of discovery, without rereading unchanged heads. */
7
+ export function openChatUpdates(options: {
8
+ catalog: () => SessionsStatus | undefined;
9
+ subscriptions: ReadonlySet<string>;
10
+ active: () => boolean;
11
+ publish: (sessionId: string, status: SessionsStatus) => Promise<boolean>;
12
+ observe?: (session: SessionInfo) => SessionObservation | undefined;
13
+ }): () => Promise<void> {
14
+ const revisions = new Map<string, string>();
15
+ const observe = options.observe ?? observeSessionExecution;
16
+ let cursor = 0, openCursor = 0, running = false;
17
+ return async () => {
18
+ if (running || !options.active()) return;
19
+ const status = options.catalog();
20
+ if (!status) return;
21
+ const known = new Map([...status.sessions, ...(status.history ?? [])]
22
+ .map(session => [session.sessionId, session]));
23
+ const ids = [...new Set([...options.subscriptions,
24
+ ...status.sessions.filter(session => session.state === 'working').map(session => session.sessionId)])]
25
+ .filter(id => known.has(id));
26
+ const activeIds = new Set(ids);
27
+ for (const id of revisions.keys()) if (!activeIds.has(id)) revisions.delete(id);
28
+ if (!ids.length) return;
29
+ const opened = ids.filter(id => options.subscriptions.has(id));
30
+ const background = ids.filter(id => !options.subscriptions.has(id));
31
+ const selected = Array.from({length: Math.min(8, opened.length)}, (_, offset) => opened[(openCursor + offset) % opened.length]!);
32
+ openCursor = opened.length ? (openCursor + selected.length) % opened.length : 0;
33
+ const remaining = Math.min(8 - selected.length, background.length);
34
+ selected.push(...Array.from({length: remaining}, (_, offset) => background[(cursor + offset) % background.length]!));
35
+ cursor = background.length ? (cursor + remaining) % background.length : 0;
36
+ running = true;
37
+ try {
38
+ for (const id of selected) {
39
+ await new Promise<void>(resolve => setImmediate(resolve));
40
+ if (!options.active()) break;
41
+ let observed: SessionObservation | undefined;
42
+ try { observed = observe(known.get(id)!); } catch { continue; }
43
+ if (!observed || revisions.get(id) === observed.revision) continue;
44
+ // Keep the full catalog's clock: one fresh chat cannot refresh unrelated chats.
45
+ const fresh = {...status, sessions: [observed.session], history: undefined};
46
+ try {
47
+ if (await options.publish(id, fresh)) revisions.set(id, observed.revision);
48
+ } catch { /* Retry the same revision after a failed encrypted send. */ }
49
+ }
50
+ } finally { running = false; }
51
+ };
52
+ }
@@ -4,6 +4,7 @@ import { basename } from "node:path";
4
4
  import type { ChildThreadInfo, SessionInfo } from "../../../../../../packages/protocol/schema";
5
5
  import { aggregateChildThreads, childTitle } from "../../support/child-threads";
6
6
  import { rememberCapabilityObservation } from "../../telemetry";
7
+ import { observeClaudeTurn } from "./turn-state";
7
8
  import { safeParse, stateFor, ts } from "../../support/common";
8
9
  import { claudeCapabilityUsage } from "./activity";
9
10
  import { claudeRepositoryPaths } from "./repository-observation";
@@ -35,18 +36,8 @@ type ClaudeParseState = {
35
36
  turnEnded: boolean;
36
37
  };
37
38
 
38
- /** Stop reasons after which Claude Code waits for the person's next prompt. */
39
- const FINISHED_TURN = new Set(["end_turn", "stop_sequence", "max_tokens"]);
40
-
41
- /** Metadata, progress and subagent lines do not start or end the chat's own turn. */
42
- function noteTurnBoundary(d: any, state: ClaudeParseState): void {
43
- if (d.isSidechain === true) return;
44
- if (d.type === "user" || d.type === "queue-operation") state.turnEnded = false;
45
- else if (d.type === "assistant") state.turnEnded = FINISHED_TURN.has(d.message?.stop_reason);
46
- }
47
-
48
39
  function applyClaudeLine(d: any, state: ClaudeParseState): void {
49
- noteTurnBoundary(d, state);
40
+ observeClaudeTurn(d, state);
50
41
  if (d.isSidechain !== true) state.repositoryPaths.push(...claudeRepositoryPaths(d));
51
42
  state.repositoryPaths = state.repositoryPaths.slice(-64);
52
43
  if (d.sessionId && !state.sessionId) state.sessionId = String(d.sessionId);
@@ -0,0 +1,9 @@
1
+ # Claude turn state
2
+
3
+ Root turn boundaries are shared by full discovery and bounded live observations.
4
+ An assistant end-turn record ends Working immediately; sidechain and progress
5
+ records do not reopen that root turn. A later user or queued turn reopens it.
6
+
7
+ Covered by sessions/tests/claude-turn-state.test.ts and session-catalog freshness tests.
8
+
9
+ This module uses the GrantTap Commercial Source License.
@@ -0,0 +1,17 @@
1
+ import {stateFor} from '../../../support/common';
2
+ import type {SessionInfo} from '../../../../../../../packages/protocol/schema';
3
+
4
+ export type ClaudeTurnClock = {turnEnded?: boolean};
5
+ const finished = new Set(['end_turn','stop_sequence','max_tokens']);
6
+
7
+ /** Root turn boundaries only; progress and sidechain records cannot resume a finished turn. */
8
+ export function observeClaudeTurn(row: any, clock: ClaudeTurnClock): void {
9
+ if (row.isSidechain === true) return;
10
+ if (row.type === 'user' || row.type === 'queue-operation') clock.turnEnded = false;
11
+ else if (row.type === 'assistant') clock.turnEnded = finished.has(row.message?.stop_reason);
12
+ }
13
+
14
+ export function claudeTurnState(clock: ClaudeTurnClock, lastActivityAt: number,
15
+ fallback: SessionInfo['state']): SessionInfo['state'] {
16
+ return clock.turnEnded === undefined ? fallback : clock.turnEnded ? 'idle' : stateFor(lastActivityAt);
17
+ }
@@ -20,7 +20,7 @@ import type { CapabilityObservation } from "../telemetry";
20
20
  import { grokNativeActivity } from '../../providers/grok-activity';
21
21
  import { grokTimeline } from '../../providers/grok-timeline';
22
22
  import { grokToolCalls, grokToolCompletions, grokToolSummary, grokRecordedChanges } from '../../providers/grok-tools';
23
- import { readGrokConversation } from '../../providers/grok-conversation';
23
+ import { captureGrokConversation, readGrokConversation } from '../../providers/grok-conversation';
24
24
  import { GrokCatalogCache, type GrokParsedContext } from '../../providers/grok-catalog-cache';
25
25
 
26
26
  type Summary = {
@@ -232,6 +232,12 @@ export function grokActivity(session: SessionInfo, fullText = false): ActivityEn
232
232
  return activityBySession.get(session.sessionId) ?? [];
233
233
  }
234
234
 
235
+ export async function grokConversationForTransfer(session: SessionInfo) {
236
+ if (!logPaths.has(session.sessionId)) scanGrok();
237
+ const path = logPaths.get(session.sessionId);
238
+ return path ? captureGrokConversation(dirname(path), session.sessionId) : undefined;
239
+ }
240
+
235
241
  export function grokCapabilityUsage(session: SessionInfo): CapabilityObservation[] {
236
242
  if (!usageBySession.has(session.sessionId)) scanGrok();
237
243
  return usageBySession.get(session.sessionId) ?? [];
@@ -9,10 +9,8 @@ import { TaskDispatchInbox } from '../index';
9
9
  import { TaskDispatchWorker } from './index';
10
10
  import { relayTaskJobRemote } from './remote';
11
11
  import { NativeTaskQueueSender } from '../sender';
12
- import { queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
12
+ import { dispatchSessionObservation, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
13
13
  import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
14
- import { grokResumeActivity } from '../../providers/grok-activity';
15
- import { localTaskTransfers } from '../../task-transfer';
16
14
 
17
15
  /** Only the persistent monitor advertises durable submission capability. */
18
16
  export function startTaskDispatchMonitor(input: {
@@ -45,10 +43,7 @@ export function startTaskDispatchMonitor(input: {
45
43
  const catalog = publishedCatalog(input.client);
46
44
  const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
47
45
  .find(item => item.sessionId === job.sessionId);
48
- const nativeState = session?.agent === 'grok'
49
- ? grokResumeActivity(localTaskTransfers().nativeSession(session))?.state : undefined;
50
- const observation = { session, generatedAt: catalog?.generatedAt,
51
- nativeState,
46
+ const observation = { ...dispatchSessionObservation(session, catalog?.generatedAt),
52
47
  inFlight: isDeliveryInFlight(job.sessionId ?? `__new_${job.operation.agent ?? 'codex'}_task__`),
53
48
  paused: !!job.sessionId && isSessionPaused(job.sessionId) };
54
49
  const ready = taskDispatchReady(job, observation);
@@ -1,4 +1,12 @@
1
1
  import type { SessionInfo, TaskDispatch } from '../../../../../packages/protocol/schema';
2
+ import { observeSessionExecution } from '../../session-catalog/observed-state';
3
+
4
+ /** A known native tail can release a queued turn before the next full discovery. */
5
+ export function dispatchSessionObservation(session: SessionInfo | undefined, generatedAt?: number) {
6
+ const fresh = session && observeSessionExecution(session);
7
+ return { session: fresh?.session ?? session, generatedAt: fresh ? Date.now() : generatedAt,
8
+ nativeState: fresh?.session.state };
9
+ }
2
10
 
3
11
  /** Manual release bypasses busy state only. Pause, native admission and policy still win. */
4
12
  export function taskDispatchReady(job: TaskDispatch, observation: {
@@ -0,0 +1,47 @@
1
+ import type { SessionInfo, SessionActivity } from '../../../../../packages/protocol/schema';
2
+ import { readTranscriptHistory, nativeTranscriptImage } from '../../transcript-history';
3
+ import { cursorActivity } from '../../sessions/cursor';
4
+ import { grokActivity, grokConversationForTransfer } from '../../sessions/scan/grok';
5
+ import { localTaskTransfers } from '../runtime/local';
6
+ import { transferHistory } from '../projection';
7
+
8
+ export type ContextReaders = {
9
+ page: (session: SessionInfo, cursor?: string) => SessionActivity | undefined;
10
+ image?: typeof nativeTranscriptImage;
11
+ unchanged?: () => boolean;
12
+ };
13
+
14
+ function nativePage(session: SessionInfo, entries: SessionActivity['entries']): SessionActivity {
15
+ const native = localTaskTransfers().nativeSession(session);
16
+ const inherited = native.sessionId !== session.sessionId ? transferHistory(session) : undefined;
17
+ const until = inherited ? inherited.entries.length + Number(inherited.history?.cursor?.split(':')[1] ?? 0) : 0;
18
+ return { type: 'session.activity', sessionId: session.sessionId, agent: session.agent,
19
+ state: session.state, generatedAt: Date.now(), entries,
20
+ ...(until ? { history: { hasMore: true, cursor: `transfer-context:${until}` } } : {}) };
21
+ }
22
+
23
+ function visiblePage(session: SessionInfo, cursor?: string): SessionActivity | undefined {
24
+ if (cursor?.startsWith('transfer-context:')) return transferHistory(session, cursor);
25
+ if (session.agent === 'cursor' || session.agent === 'grok') {
26
+ const native = localTaskTransfers().nativeSession(session);
27
+ const entries = session.agent === 'cursor' ? cursorActivity(native, true) : grokActivity(native, true);
28
+ if (!entries.length && native.sessionId !== session.sessionId) return transferHistory(session);
29
+ return nativePage(session, entries);
30
+ }
31
+ return readTranscriptHistory(session, cursor);
32
+ }
33
+
34
+ /** Complete Grok captures have their own projection and attachment bytes, scoped to this operation. */
35
+ export async function transferContextReaders(session: SessionInfo): Promise<ContextReaders> {
36
+ if (session.agent !== 'grok') return { page: visiblePage };
37
+ const native = localTaskTransfers().nativeSession(session);
38
+ const captured = await grokConversationForTransfer(native);
39
+ if (!captured) return { page: visiblePage };
40
+ return {
41
+ page: (input, cursor) => cursor?.startsWith('transfer-context:')
42
+ ? transferHistory(input, cursor) : nativePage(input, captured.entries),
43
+ image: (input, id, offset, cursor) => cursor?.startsWith('transfer-context:')
44
+ ? nativeTranscriptImage(input, id, offset, cursor) : captured.image(input, id, offset),
45
+ unchanged: captured.unchanged,
46
+ };
47
+ }
@@ -1,48 +1,27 @@
1
1
  import { setImmediate } from 'node:timers/promises';
2
- import type { ActivityEntry, SessionActivity, SessionInfo, TaskCapsule } from '../../../../packages/protocol/schema';
3
- import { readTranscriptHistory, nativeTranscriptImage } from '../transcript-history';
4
- import { cursorActivity } from '../sessions/cursor';
5
- import { grokActivity } from '../sessions/scan/grok';
2
+ import type { SessionInfo, TaskCapsule } from '../../../../packages/protocol/schema';
6
3
  import { captureContextImages } from './context/images';
7
4
  import { TransferArchive } from './context/archive';
8
5
  import { MAX_TRANSFER_CONTEXT_BYTES, transferDigest } from './persistence';
9
- import { localTaskTransfers } from './runtime/local';
10
- import { transferHistory } from './projection';
11
-
12
- type ContextReaders = { page: (session: SessionInfo, cursor?: string) => SessionActivity | undefined;
13
- image?: typeof nativeTranscriptImage };
14
-
15
- function visiblePage(session: SessionInfo, cursor?: string): SessionActivity | undefined {
16
- if (cursor?.startsWith('transfer-context:')) return transferHistory(session, cursor);
17
- if (session.agent === 'cursor' || session.agent === 'grok') {
18
- const native = localTaskTransfers().nativeSession(session);
19
- const entries = session.agent === 'cursor' ? cursorActivity(native, true) : grokActivity(native, true);
20
- const inherited = native.sessionId !== session.sessionId ? transferHistory(session) : undefined;
21
- if (!entries.length) return inherited;
22
- const until = inherited ? inherited.entries.length + Number(inherited.history?.cursor?.split(':')[1] ?? 0) : 0;
23
- return { type: 'session.activity', sessionId: session.sessionId, agent: session.agent,
24
- state: session.state, generatedAt: Date.now(), entries,
25
- ...(until ? { history: { hasMore: true, cursor: `transfer-context:${until}` } } : {}) };
26
- }
27
- return readTranscriptHistory(session, cursor);
28
- }
6
+ import { transferContextReaders, type ContextReaders } from './context/readers';
29
7
 
30
8
  /** Every visible root-chat page is carried; hidden reasoning is never a context source. */
31
9
  export async function captureTransferContext(session: SessionInfo, capsule: TaskCapsule,
32
- readers: ContextReaders = { page: visiblePage }): Promise<{ context: string; hash: string }> {
10
+ readers?: ContextReaders): Promise<{ context: string; hash: string }> {
33
11
  if (session.state === 'working') throw new Error('Pause or finish the current turn before transferring this Task.');
12
+ const source = readers ?? await transferContextReaders(session);
34
13
  let cursor: string | undefined, bytes = 0;
35
14
  let latestFingerprint: string | undefined;
36
15
  const cursors = new Set<string>(), entries = new Map<string, TransferArchive["entries"][number]>();
37
16
  while (true) {
38
- const page = readers.page(session, cursor);
17
+ const page = source.page(session, cursor);
39
18
  if (!page) throw new Error('The full visible conversation could not be read. No partial transfer was sent.');
40
19
  if (page.state === 'working') throw new Error('Pause or finish the current turn before transferring this Task.');
41
20
  if (!cursor) latestFingerprint = transferDigest(JSON.stringify(page.entries));
42
21
  for (const row of page.entries) {
43
22
  if (row.childThreadId || entries.has(row.id)) continue;
44
23
  if (!['user', 'message', 'final', 'tool', 'status'].includes(row.kind)) continue;
45
- const images = captureContextImages(session, row, cursor, readers.image);
24
+ const images = captureContextImages(session, row, cursor, source.image);
46
25
  const entry = { id: row.id, role: row.kind === 'message' || row.kind === 'final' ? 'assistant' as const : row.kind,
47
26
  text: row.text, at: row.createdAt, ...(images.length ? { images } : {}) };
48
27
  entries.set(row.id, entry); bytes += Buffer.byteLength(JSON.stringify(entry));
@@ -53,8 +32,9 @@ export async function captureTransferContext(session: SessionInfo, capsule: Task
53
32
  if (!next || cursors.has(next)) throw new Error('The full conversation cursor could not be confirmed.');
54
33
  cursors.add(next); cursor = next; await setImmediate();
55
34
  }
56
- const latest = readers.page(session);
57
- if (!latest || latest.state === 'working' || transferDigest(JSON.stringify(latest.entries)) !== latestFingerprint) {
35
+ const latest = source.page(session);
36
+ if (!latest || latest.state === 'working' || source.unchanged?.() === false
37
+ || transferDigest(JSON.stringify(latest.entries)) !== latestFingerprint) {
58
38
  throw new Error('The conversation changed during capture. No incomplete transfer was sent; retry after the turn finishes.');
59
39
  }
60
40
  const archive = TransferArchive.parse({ version: 1, facts: capsule,
@@ -1,3 +1,4 @@
1
+ import { observeSessionExecution } from "../session-catalog/observed-state";
1
2
  import { localTaskTransfers, transferHistory } from "../task-transfer";
2
3
  import type { ActivityEntry, SessionActivity, SessionInfo } from "../../../../packages/protocol/schema";
3
4
  import { appendCodexActivity, codexCapabilityUsage } from "../sessions/scan/codex/activity";
@@ -8,7 +9,6 @@ import { recordedFileChanges } from "./changes";
8
9
  import { recordedToolDetails } from "./tool-details";
9
10
  import { completedTurnChanges } from "./turn-changes";
10
11
  import { cursorActivity, cursorConversationHistory } from "../sessions/cursor";
11
- import { parseCodexFile } from '../sessions/scan/codex/parse';
12
12
  export { nativeImageLines } from "./images";
13
13
  export { nativeTranscriptImage } from './images/native';
14
14
  export { nativeTranscriptEntry } from './images/advertised-entry';
@@ -94,7 +94,7 @@ export function readTranscriptHistory(input: SessionInfo, cursor?: string): Sess
94
94
  : window.lines[0]?.offset ?? window.start;
95
95
  const prior = input.sessionId !== session.sessionId && offset === 0 ? transferHistory(input) : undefined;
96
96
  return { type: "session.activity", sessionId: input.sessionId, agent: session.agent,
97
- state: session.agent === 'codex' ? parseCodexFile(path)?.session.state ?? session.state : session.state,
97
+ state: cursor ? session.state : observeSessionExecution(input)?.session.state ?? session.state,
98
98
  entries, generatedAt: Date.now(), history: {
99
99
  hasMore: offset > 0 || Boolean(prior?.entries.length),
100
100
  ...(offset > 0 ? { cursor: window.cursorAt(offset) }
@@ -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.126
13
+ npm install -g granttap-mcp@0.8.128
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.126\";\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.128\";\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.126";
10
+ const PACKAGE = "granttap-mcp@0.8.128";
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.126",
3
+ "version": "0.8.128",
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": {