granttap-mcp 0.8.129 → 0.8.130

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.
@@ -243,7 +243,7 @@ export function startSessionMonitor(client: RelayClient): SessionMonitor {
243
243
  publish: openChatUpdates({
244
244
  catalog: () => publishedCatalog(client), subscriptions,
245
245
  active: () => !closed && client.isConnected && leadership.acquire(),
246
- publish: (id, status) => publishSessionEvents(client, id, status),
246
+ publish: (id, status) => publishSessionEvents(client, id, status, undefined, {history: true}),
247
247
  }),
248
248
  });
249
249
 
@@ -15,6 +15,7 @@ import { abortProcesses, runProcess } from "./process";
15
15
  import { routingPrompt } from "./payload/routing";
16
16
  import type { DeliveryOptions, ReplyResult } from "./payload/types";
17
17
  import { deliveryIntent } from './payload/identity';
18
+ import {NativeTurnCompletions, type NativeCompletionProof} from './native-completion';
18
19
  import {
19
20
  runCursorNew,
20
21
  runCursorResume,
@@ -34,11 +35,14 @@ export function resolveAgentWorkspace(cwd: string | undefined, agent: CodingAgen
34
35
  }
35
36
 
36
37
  const inFlight = new Map<string, Promise<ReplyResult | null>>();
38
+ const physicalRuns = new Set<Promise<ReplyResult>>();
39
+ const nativeCompletions = new NativeTurnCompletions();
37
40
 
38
41
  export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
39
42
 
40
43
  /** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
41
- export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
44
+ export function hasPendingDeliveries(): boolean { return inFlight.size > 0 || physicalRuns.size > 0; }
45
+ export const completeObservedNativeTurn = (key: string, proof: NativeCompletionProof) => nativeCompletions.complete(key, proof);
42
46
 
43
47
  /** Request a stop for owned processes; confirmation arrives only on process exit. */
44
48
  export function stopDeliveries(sessionId: string): number {
@@ -164,7 +168,14 @@ export function createGrokSession(
164
168
 
165
169
  function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
166
170
  const previous = inFlight.get(key) ?? Promise.resolve(null);
167
- const next = previous.then(run);
171
+ const next = previous.then(async () => {
172
+ const native = nativeCompletions.begin(key);
173
+ const physical = Promise.resolve().then(run);
174
+ physicalRuns.add(physical);
175
+ void physical.then(() => physicalRuns.delete(physical), () => physicalRuns.delete(physical));
176
+ try { return await Promise.race([physical, native.result]); }
177
+ finally { native.close(); }
178
+ });
168
179
  const settled = next.finally(() => {
169
180
  if (inFlight.get(key) === tracked) inFlight.delete(key);
170
181
  });
@@ -194,6 +205,8 @@ function runClaude(
194
205
  timeoutMs: number,
195
206
  options: DeliveryOptions,
196
207
  ): Promise<ReplyResult> {
208
+ nativeCompletions.bind(session.sessionId, text, key => localTaskTransfers()
209
+ .nativeSession({...session, sessionId: key}).sessionId);
197
210
  const disabled = loadRuntimeConfig().sessionMcpDisabled[session.sessionId] ?? [];
198
211
  const mcpArgs = disabled.length === 0
199
212
  ? []
@@ -0,0 +1,35 @@
1
+ import {createHash} from 'node:crypto';
2
+ import type {ReplyResult} from './payload/types';
3
+
4
+ export const nativePromptDigest = (text: string) => createHash('sha256').update(text).digest('hex');
5
+ export type NativeCompletionProof = {nativeSessionId: string; promptAt: number; completedAt: number;
6
+ promptDigests: string[]; text: string};
7
+ type Run = {key: string; startedAt: number; nativeId?: string; digest?: string;
8
+ resolve: (result: ReplyResult) => void; result: Promise<ReplyResult>; completed: boolean};
9
+
10
+ /** Match this invocation's exact native prompt before releasing its confirmed final answer. */
11
+ export class NativeTurnCompletions {
12
+ private readonly runs = new Map<string, Run>();
13
+ constructor(private readonly now = Date.now) {}
14
+ begin(key: string) {
15
+ let resolve!: Run['resolve'];
16
+ const result = new Promise<ReplyResult>(done => {resolve = done});
17
+ const run: Run = {key, startedAt: this.now(), resolve, result, completed: false};
18
+ this.runs.set(key, run);
19
+ return {result, close: () => {if (this.runs.get(key) === run) this.runs.delete(key)}};
20
+ }
21
+ bind(nativeId: string, prompt: string, nativeForKey: (key: string) => string) {
22
+ const run = [...this.runs.values()].find(item => !item.nativeId && nativeForKey(item.key) === nativeId);
23
+ if (run) {run.nativeId = nativeId; run.digest = nativePromptDigest(prompt)}
24
+ }
25
+ complete(key: string, proof: NativeCompletionProof): boolean {
26
+ const run = this.runs.get(key);
27
+ if (!run || run.completed || run.nativeId !== proof.nativeSessionId || !run.digest
28
+ || !proof.promptDigests.includes(run.digest) || proof.promptAt < run.startedAt
29
+ || proof.completedAt < proof.promptAt || proof.completedAt > this.now() + 5_000
30
+ || !proof.text.trim()) return false;
31
+ run.completed = true;
32
+ run.resolve({ok: true, text: proof.text, delivery: 'native'});
33
+ return true;
34
+ }
35
+ }
@@ -33,7 +33,7 @@ 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
35
 
36
- Open and working chats follow a separate two-second loop of known native sources.
36
+ Open chats follow a separate two-second loop of known native sources.
37
37
  Only changed source revisions send encrypted transcript heads; reads and sends
38
38
  remain single-flight and bounded to eight chats per pass. Claude end-turn and
39
39
  Codex turn events update execution state immediately after observation. The same
@@ -43,3 +43,9 @@ Full discoveries recheck known native execution state immediately before sending
43
43
  their catalog, so a scan started during a turn cannot restore stale Working after
44
44
  an independently delivered completion. Runtime handoff also waits for owned
45
45
  provider turns to settle, including work already acknowledged to the phone.
46
+
47
+ Fast open-chat heads use bounded native root pages. Closed chats and child
48
+ conversations remain on their independent refresh/request paths. A Claude final
49
+ can finish its matched logical turn while its physical CLI drains background
50
+ work: native identity, exact routed prompt hash and prompt/final timestamps must
51
+ all match. Physical processes remain tracked for Stop and runtime handoff.
@@ -11,10 +11,12 @@ import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/s
11
11
  import {ts} from '../sessions/support/common';
12
12
  import {grokResumeActivity} from '../providers/grok-activity';
13
13
  import {cursorConversationSession} from '../sessions/cursor';
14
+ import {nativePromptDigest, type NativeCompletionProof} from '../reply/native-completion';
14
15
 
15
- type NativeClock={revision:string;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock};
16
+ type NativeClock={revision:string;identity:string;bytes:number;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock;
17
+ promptAt:number;promptDigests:string[];completion?:NativeCompletionProof};
16
18
  const clocks=new Map<string,NativeClock>();
17
- export type SessionObservation={session:SessionInfo;revision:string};
19
+ export type SessionObservation={session:SessionInfo;revision:string;completion?:NativeCompletionProof};
18
20
 
19
21
  /** Discovery may have started before an open chat finished its turn. Recheck before publication. */
20
22
  export function refreshObservedCatalog(status: SessionsStatus): SessionsStatus {
@@ -47,12 +49,22 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
47
49
  let clock=clocks.get(key);
48
50
  if(clock?.revision!==revision){
49
51
  const window=previousNativeLines(path,native.sessionId);if(!window)return;
50
- clock={revision,lastActivityAt:0,claude:{},codex:{}};
52
+ const identity = `${stat.dev}:${stat.ino}`;
53
+ const append = clock?.identity === identity && stat.size > clock.bytes;
54
+ clock={revision,identity,bytes:stat.size,lastActivityAt:0,claude:append?{...clock!.claude}:{},codex:{},
55
+ promptAt:append?clock!.promptAt:0,promptDigests:append?clock!.promptDigests:[],completion:append?clock!.completion:undefined};
51
56
  for(const line of window.lines){
52
57
  let row;try{row=JSON.parse(line.text)}catch{continue}
53
58
  if(row.isSidechain===true||row.sessionId&&row.sessionId!==native.sessionId)continue;
54
59
  clock.lastActivityAt=Math.max(clock.lastActivityAt,ts(row.timestamp));
55
- if(native.agent==='claude')observeClaudeTurn(row,clock.claude);else observeCodexTurn(row,clock.codex);
60
+ if(native.agent==='claude'){
61
+ observeClaudeTurn(row,clock.claude);
62
+ const content=row.message?.content;
63
+ const texts=typeof content==='string'?[content]:Array.isArray(content)?content.filter(b=>b?.type==='text'&&typeof b.text==='string').map(b=>b.text):[];
64
+ if(row.type==='user'&&texts.length){clock.promptAt=ts(row.timestamp);clock.promptDigests=[...texts,texts.join('\n')].map(nativePromptDigest)}
65
+ if(row.type==='assistant'&&clock.claude.turnEnded)clock.completion={nativeSessionId:native.sessionId,
66
+ promptAt:clock.promptAt,promptDigests:clock.promptDigests,completedAt:ts(row.timestamp),text:texts.join('\n')};
67
+ }else observeCodexTurn(row,clock.codex);
56
68
  }
57
69
  clocks.delete(key);clocks.set(key,clock);
58
70
  while(clocks.size>256)clocks.delete(clocks.keys().next().value!);
@@ -60,6 +72,7 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
60
72
  const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
61
73
  const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
62
74
  :clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
63
- return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
75
+ return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`,
76
+ ...(native.agent==='claude'&&clock!.claude.turnEnded&&clock!.completion?{completion:clock!.completion}:{})};
64
77
  }catch{return;}
65
78
  }
@@ -13,26 +13,19 @@ export function openChatUpdates(options: {
13
13
  }): () => Promise<void> {
14
14
  const revisions = new Map<string, string>();
15
15
  const observe = options.observe ?? observeSessionExecution;
16
- let cursor = 0, openCursor = 0, running = false;
16
+ let cursor = 0, running = false;
17
17
  return async () => {
18
18
  if (running || !options.active()) return;
19
19
  const status = options.catalog();
20
20
  if (!status) return;
21
21
  const known = new Map([...status.sessions, ...(status.history ?? [])]
22
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));
23
+ const ids = [...options.subscriptions].filter(id => known.has(id));
26
24
  const activeIds = new Set(ids);
27
25
  for (const id of revisions.keys()) if (!activeIds.has(id)) revisions.delete(id);
28
26
  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;
27
+ const selected = Array.from({length: Math.min(8, ids.length)}, (_, offset) => ids[(cursor + offset) % ids.length]!);
28
+ cursor = (cursor + selected.length) % ids.length;
36
29
  running = true;
37
30
  try {
38
31
  for (const id of selected) {
@@ -1,7 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import type { PeerConfig, RelayClient } from '../../../../../packages/core/relay-client';
3
3
  import { configDir, isSessionPaused } from '../../config';
4
- import { isDeliveryInFlight } from '../../reply';
4
+ import { completeObservedNativeTurn, isDeliveryInFlight } from '../../reply';
5
5
  import { publishedCatalog } from '../../session-catalog';
6
6
  import { handleUserMessage } from '../../monitor/handlers/user-message';
7
7
  import { handleTaskCreate } from '../../monitor/handlers/task-create';
@@ -43,7 +43,9 @@ export function startTaskDispatchMonitor(input: {
43
43
  const catalog = publishedCatalog(input.client);
44
44
  const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
45
45
  .find(item => item.sessionId === job.sessionId);
46
- const observation = { ...dispatchSessionObservation(session, catalog?.generatedAt),
46
+ const native = dispatchSessionObservation(session, catalog?.generatedAt);
47
+ if (job.sessionId && native.completion) completeObservedNativeTurn(job.sessionId, native.completion);
48
+ const observation = { ...native,
47
49
  inFlight: isDeliveryInFlight(job.sessionId ?? `__new_${job.operation.agent ?? 'codex'}_task__`),
48
50
  paused: !!job.sessionId && isSessionPaused(job.sessionId) };
49
51
  const ready = taskDispatchReady(job, observation);
@@ -5,7 +5,7 @@ import { observeSessionExecution } from '../../session-catalog/observed-state';
5
5
  export function dispatchSessionObservation(session: SessionInfo | undefined, generatedAt?: number) {
6
6
  const fresh = session && observeSessionExecution(session);
7
7
  return { session: fresh?.session ?? session, generatedAt: fresh ? Date.now() : generatedAt,
8
- nativeState: fresh?.session.state };
8
+ nativeState: fresh?.session.state, completion: fresh?.completion };
9
9
  }
10
10
 
11
11
  /** Manual release bypasses busy state only. Pause, native admission and policy still win. */
@@ -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.129
13
+ npm install -g granttap-mcp@0.8.130
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.129\";\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.130\";\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.129";
10
+ const PACKAGE = "granttap-mcp@0.8.130";
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.129",
3
+ "version": "0.8.130",
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": {