granttap-mcp 0.8.185 → 0.8.187

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 (33) hide show
  1. package/README.md +11 -7
  2. package/apps/bridge/src/engine/README.md +5 -3
  3. package/apps/bridge/src/engine/distribution/artifacts.ts +2 -2
  4. package/apps/bridge/src/engine/runtime/launch/index.ts +4 -1
  5. package/apps/bridge/src/limit-continuation/README.md +2 -1
  6. package/apps/bridge/src/limit-continuation/index.ts +11 -0
  7. package/apps/bridge/src/monitor/handlers/user-message.ts +8 -3
  8. package/apps/bridge/src/reply/index.ts +2 -1
  9. package/apps/bridge/src/reply/payload/types.ts +5 -0
  10. package/apps/bridge/src/runtime-updates/README.md +6 -1
  11. package/apps/bridge/src/runtime-updates/index.ts +27 -2
  12. package/apps/bridge/src/sessions/cursor/transcripts.ts +2 -1
  13. package/apps/bridge/src/sessions/scan/claude/parse.ts +12 -0
  14. package/apps/bridge/src/sessions/support/activity-helpers.ts +3 -1
  15. package/apps/bridge/src/task-dispatch/README.md +22 -0
  16. package/apps/bridge/src/task-dispatch/inbox.ts +19 -0
  17. package/apps/bridge/src/task-dispatch/queue-note.ts +33 -0
  18. package/apps/bridge/src/task-dispatch/worker/index.ts +13 -4
  19. package/apps/bridge/src/task-dispatch/worker/monitor.ts +5 -6
  20. package/apps/bridge/src/task-dispatch/worker/queue-depth.ts +68 -0
  21. package/apps/mcp/src/connection-center/README.md +8 -0
  22. package/apps/mcp/src/connection-center/state.ts +22 -4
  23. package/apps/mcp/src/connection-center/update-controls.ts +3 -1
  24. package/apps/mcp/src/mcp-tools/connect/index.ts +27 -6
  25. package/apps/mcp/src/mcp-tools/interaction/notify.ts +4 -1
  26. package/apps/mcp/src/mcp-tools/interaction/questions.ts +4 -2
  27. package/apps/mcp/src/mcp-tools/mesh/resource.ts +3 -1
  28. package/apps/mcp/src/status/chat-status.ts +36 -0
  29. package/apps/mcp/src/status/pairing-status.ts +16 -0
  30. package/cursor-plugin/README.md +1 -1
  31. package/cursor-plugin/mcp.json +1 -1
  32. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  33. package/package.json +1 -1
package/README.md CHANGED
@@ -606,14 +606,14 @@ trust.
606
606
 
607
607
  | Tool | Contract |
608
608
  | --- | --- |
609
- | `set_runtime_auto_update` | When the user asks, turn automatic GrantTap runtime updates on this computer on or off; saves the preference without restarting services or changing pairing, tasks, or provider policy |
610
- | `connection_status` | Open the connection card and inspect saved pairing, QR expiry, relay observations, and provider readiness without changing pairing |
611
- | `connect_with_passkey` | Open a short-lived GrantTap account passkey request for this computer; the passkey is entered only on granttap.com and existing QR pairings stay unchanged |
612
- | `connect` | Reuse the existing production pairing or return a one-time QR |
609
+ | `set_runtime_auto_update` | When the user asks, turn automatic GrantTap runtime updates on this computer on or off; saves the preference without restarting services or changing pairing, tasks, or provider policy, and returns the connection state |
610
+ | `connection_status` | Read-only: saved pairing and paired phones by when each last reached this computer, QR expiry, relay observations, provider readiness, a newer runtime waiting to take over and why, and for the calling Claude Code chat the phone messages queued behind its turn and its continuation after a subscription limit |
611
+ | `connect_with_passkey` | Link this computer to the user's GrantTap account so a signed-in phone can connect without a QR; returns a 15-minute granttap.com link, the passkey is entered only there, and existing QR pairings stay unchanged |
612
+ | `connect` | Show the existing pairing on the connection card, or on an unpaired computer create a one-time QR shown only on the card |
613
613
  | `reconnect` | After explicit confirmation, show a one-time QR to reconnect or add an independent controller device while retaining the current room |
614
- | `notify` | Send a non-blocking status update of at most 2,000 characters |
615
- | `ask_yes_no` | Ask a yes/no question and wait for the explicit answer |
616
- | `ask` | Ask an open question and wait for typed or spoken text |
614
+ | `notify` | Send a non-blocking status of at most 2,000 characters that nobody answers, and/or one task-scoped Mesh event |
615
+ | `ask_yes_no` | Ask a yes/no question and wait about three minutes for the explicit answer; a timeout is neither yes nor no |
616
+ | `ask` | Ask an open question and wait about three minutes for typed or spoken text |
617
617
  | `request_sign_in` | Send an https sign-in page to the phone, wait for the person, and deliver the browser's loopback redirect once to the port the CLI listens on; returns `completed`, `cancelled` or `timed_out`, never the page or the redirect's contents |
618
618
  | `offload_task` | Request moving the calling Task to a compatible computer in its Mesh, keeping provider, model, effort and visible conversation; requires Automatic computer transfers, and `action=status` or `action=cancel` acts only on the caller's own request |
619
619
 
@@ -623,6 +623,10 @@ existing pairing remains usable during a new enrollment attempt.
623
623
  Setup is CLI-only because it changes provider configuration and must not be
624
624
  available to a model through prompt injection.
625
625
 
626
+ A phone message delivered while more phone messages wait for the same chat carries one GrantTap
627
+ line after the person's words, saying how many follow and that repository-wide checks, full test
628
+ runs and publishing can wait for the last of them. The phone's transcript view does not show it.
629
+
626
630
  `notify` may alternatively carry one bounded task-scoped Mesh event. This does
627
631
  not add another MCP tool or grant any global setup capability, and it publishes
628
632
  only for the execution whose provider hook attributed the call.
@@ -29,9 +29,11 @@ Explicit Graph builds also invoke the Engine's `graph.analyze_project` for two
29
29
  to eight admitted local repositories. The projection labels these shared static
30
30
  contracts and keeps their runtime destination unverified. They do not become
31
31
  verified Backbone dependencies or merge Project grants. The Apple Silicon
32
- artifact pins Engine 0.1.5 with Weavatrix 2.17.5, injective package import identities
33
- and per-file function extent reuse during metrics analysis; unsupported Engine operations
34
- leave this analysis unavailable. See `runtime/project-relationships/README.md`.
32
+ artifact pins Engine 0.1.8 with Weavatrix 2.17.17 and Cortex Loom 0.1.1, injective package
33
+ import identities and per-file function extent reuse during metrics analysis; unsupported Engine
34
+ operations leave this analysis unavailable. The Engine keeps a search index of the repositories it
35
+ searched in `weavatrix-search/` beside its socket, with the socket's owner-only permissions; the
36
+ launch never passes on a person's own `WEAVATRIX_SEARCH_HOME`. See `runtime/project-relationships/README.md`.
35
37
 
36
38
  Claude, Codex, and Cursor hooks can evaluate the engine's local Project
37
39
  Governance policy only when both `GRANTTAP_ENGINE_ENABLED` and
@@ -8,8 +8,8 @@ export type EngineArtifact = {
8
8
 
9
9
  /** Release hashes are part of the reviewed MCP, never supplied by a remote manifest. */
10
10
  export const ENGINE_ARTIFACTS: readonly EngineArtifact[] = [
11
- { version: "0.1.7", platform: "darwin", arch: "arm64",
12
- sha256: "bf7fcf3d08d78a437da21fcb88057d77840be4b22a0f7388f383059e685a76ef", bytes: 12201856 },
11
+ { version: "0.1.8", platform: "darwin", arch: "arm64",
12
+ sha256: "15cc6bd1d35ed19af06199603f4051ef28e8c03ebe40bff1c3febd1bb2a75279", bytes: 13059296 },
13
13
  // The 0.1.2 Intel Mac and Linux x64 builds are no longer published. Without a
14
14
  // pin, setup reports Graph as unavailable and the helper does not retry a 404;
15
15
  // an Engine already installed and verified on such a computer keeps working.
@@ -9,8 +9,11 @@ export function engineLaunchEnvironment(
9
9
  env: NodeJS.ProcessEnv, socketPath: string, platform: NodeJS.Platform = process.platform,
10
10
  ): NodeJS.ProcessEnv {
11
11
  const requestedStack = Number(env.RUST_MIN_STACK);
12
+ // The Engine keeps its search index of repository text in its own state folder beside the socket;
13
+ // a person's own Weavatrix setting must not move it into their Weavatrix data.
14
+ const { WEAVATRIX_SEARCH_HOME: _personalSearchHome, ...inherited } = env;
12
15
  return {
13
- ...env,
16
+ ...inherited,
14
17
  GRANTTAP_ENGINE_SOCKET: engineSocketEndpoint(socketPath),
15
18
  // Rust's default worker stack aborts the daemon on ordinary long ASTs.
16
19
  // Scope this reserve to the verified Engine child; keep larger explicit reserves.
@@ -22,6 +22,7 @@ Turning it off takes the queued copies back from the relay. A copy the relay sti
22
22
  is refused at delivery. The same happens when the chat went on by itself first. A limit that reset
23
23
  more than an hour ago is treated as abandoned and is never woken by an update.
24
24
 
25
- State lives in `limit-continuation.json` in the private config directory. Tests live in `tests/`.
25
+ State lives in `limit-continuation.json` in the private config directory. `limitContinuationFor`
26
+ reads one chat's setting and queued continuation for that chat's own MCP status. Tests live in `tests/`.
26
27
 
27
28
  License: GrantTap Commercial Source License; see the repository LICENSE.
@@ -45,6 +45,17 @@ export function annotateLimitContinuations(sessions: SessionInfo[]): SessionInfo
45
45
  ? { ...session, usageLimit: { ...session.usageLimit, autoContinue: !off.has(session.sessionId) } } : session);
46
46
  }
47
47
 
48
+ /**
49
+ * For the chat itself: whether it goes on by itself after a subscription limit stopped it, and the
50
+ * continuation queued for it while it waits at one. `early` says a second one was queued to go at once
51
+ * because the account's readings showed room before the reset. Read only.
52
+ */
53
+ export function limitContinuationFor(sessionId: string): { autoContinue: boolean; continuation?: { dueAt: number; early: boolean } } {
54
+ const state = readLimitContinuationState(), job = state.scheduled[sessionId];
55
+ return { autoContinue: !state.off.includes(sessionId),
56
+ ...(job ? { continuation: { dueAt: Math.max(job.scheduledAt ?? 0, job.resetsAt + LIMIT_CONTINUE_GRACE_MS), early: !!job.early } } : {}) };
57
+ }
58
+
48
59
  function wanted(session: SessionInfo, off: Set<string>, now: number): boolean {
49
60
  const limit = session.usageLimit;
50
61
  return !!limit && session.agent === 'claude' && session.state === 'idle' && !off.has(session.sessionId)
@@ -1,4 +1,5 @@
1
1
  import { projectGuidancePrompt } from "../../mesh/restrictions/guidance";
2
+ import { withQueueNote } from "../../task-dispatch/queue-note";
2
3
  import type { UserMessage } from "../../../../../packages/protocol/schema";
3
4
  import { ATTACHMENT_MISSING_ERROR } from "../../../../../packages/protocol/schema";
4
5
  import type { RelayClient } from "../../../../../packages/core/relay-client";
@@ -32,6 +33,7 @@ async function startNewAgentTask(input: {
32
33
  onProcessing?: () => Promise<void>;
33
34
  origin?: { registry: TaskOriginRegistry; scope: TaskOriginScope };
34
35
  peerPublicKey?: string;
36
+ queuedBehind?: () => number;
35
37
  }): Promise<"accepted" | "rejected"> {
36
38
  const { client, message, say } = input;
37
39
  const agent = message.agent ?? "codex";
@@ -86,7 +88,8 @@ async function startNewAgentTask(input: {
86
88
  const started = (sessionId: string) => {
87
89
  try { input.origin?.registry.started(input.origin.scope, sessionId); } catch { /* The run's end records it. */ }
88
90
  };
89
- const prompt = projectGuidancePrompt(admittedProjectId, message.text);
91
+ // Follow-ups written before this chat existed reach it after its first turn.
92
+ const prompt = projectGuidancePrompt(admittedProjectId, withQueueNote(message.text, input.queuedBehind?.()));
90
93
  let run: Promise<ReplyResult>;
91
94
  try {
92
95
  run = (agent === 'codex'
@@ -127,6 +130,8 @@ export async function handleUserMessage(
127
130
  peerPublicKey?: string,
128
131
  native?: { messageId: string; questionReply: true },
129
132
  onRefusal?: (error: string) => Promise<void>,
133
+ /** Phone messages queued for the same chat behind this one; the prompt says how many. */
134
+ queuedBehind?: () => number,
130
135
  ): Promise<"accepted" | "rejected"> {
131
136
  const say = (text: string, sessionId?: string, wake = false, kind: "status" | "response" = "response") => {
132
137
  const payload = agentEventForUserMessage(message, text, sessionId, kind);
@@ -145,7 +150,7 @@ export async function handleUserMessage(
145
150
  registry: localTaskOrigins(),
146
151
  scope: { room: client.room, peerPublicKey, originMessageId: message.taskOriginId },
147
152
  } : undefined;
148
- return startNewAgentTask({ client, message, say, onProcessing, origin, peerPublicKey });
153
+ return startNewAgentTask({ client, message, say, onProcessing, origin, peerPublicKey, queuedBehind });
149
154
  }
150
155
  const resolved = resolveMessageAttachments(message, (attachmentId) => takeAttachment(attachmentId, client.room));
151
156
  if (!resolved.ok) {
@@ -183,7 +188,7 @@ export async function handleUserMessage(
183
188
  skill: message.skill,
184
189
  model: message.model,
185
190
  permissionMode: message.permissionMode,
186
- effort: message.effort,
191
+ effort: message.effort, queuedBehind: queuedBehind?.(),
187
192
  });
188
193
  const settle = async (result: ReplyResult, late: boolean) => {
189
194
  if (result.ok && result.delivery === 'native') return;
@@ -17,6 +17,7 @@ import { routingPrompt } from "./payload/routing";
17
17
  import type { DeliveryOptions, ReplyResult } from "./payload/types";
18
18
  import { deliveryIntent } from './payload/identity';
19
19
  import { queued } from "./in-flight";
20
+ import { withQueueNote } from "../task-dispatch/queue-note";
20
21
  import {
21
22
  runCursorNew,
22
23
  runCursorResume,
@@ -88,7 +89,7 @@ export function deliverToSession(
88
89
  },
89
90
  )) ?? { ok: false, error: "The prepared transfer is unavailable." });
90
91
  }
91
- return queued(session.sessionId, () => withAttachments(attachments, text, (prepared) =>
92
+ return queued(session.sessionId, () => withAttachments(attachments, withQueueNote(text, options.queuedBehind), (prepared) =>
92
93
  runDelivery(
93
94
  session,
94
95
  session.agent === "codex" ? prepared.prompt : prepared.claudePrompt,
@@ -20,4 +20,9 @@ export type DeliveryOptions = {
20
20
  effort?: string;
21
21
  /** The resume prompt itself is sent while the hold is being lifted. */
22
22
  ignorePause?: boolean;
23
+ /**
24
+ * Phone messages queued for this chat behind this one. The prompt gets a GrantTap line saying so;
25
+ * the controller's intent, and so the delivery's identity, stays the person's text.
26
+ */
27
+ queuedBehind?: number;
23
28
  };
@@ -60,7 +60,12 @@ minute tick without restarting services. Administrators may
60
60
  set `GRANTTAP_DISABLE_AUTO_UPDATE=1` on their service to retain their installed
61
61
  version. Private staging consumes space; old versions are retained for rollback.
62
62
 
63
- Public entry: `startRuntimeUpdates`, `runtimeUpdateReadiness`, `UpdateDrain`, and the
63
+ `pendingRuntimeUpdate` reads the version cache for status views without writing: a newer release
64
+ that is selected but older processes still run, or one downloaded and not yet selected, with the
65
+ reason that can be told from the cache (running work, or automatic updates off). Why a busy
66
+ monitor's hold gave way lives only in that monitor and its log.
67
+
68
+ Public entry: `startRuntimeUpdates`, `pendingRuntimeUpdate`, `runtimeUpdateReadiness`, `UpdateDrain`, and the
64
69
  launcher's `selection.mjs` / `supervision.mjs` boundary. Tests exercise failed downloads
65
70
  and verification, deferred activation, concurrent installation, selection, and startup
66
71
  rollback using isolated directories and owned child processes. `drain/tests` covers the
@@ -1,11 +1,11 @@
1
- import { closeSync, mkdirSync, openSync, statSync, unlinkSync } from 'node:fs';
1
+ import { closeSync, mkdirSync, openSync, readdirSync, statSync, unlinkSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { configDir } from '../config/runtime/paths';
5
5
  import { latestRelease, trustedRelease, installRelease, verifyRelease, type Release } from './registry';
6
6
  import { newerVersion, readState, runtimeVersion, saveState, validRuntime, versionRoot } from './selection.mjs';
7
7
  import { automaticUpdatesAllowed } from './preferences/storage.mjs';
8
- import { HOLD_POLL_MS, type UpdateDrain } from './drain';
8
+ import { HOLD_LIMIT_MS, HOLD_POLL_MS, type UpdateDrain } from './drain';
9
9
  export { runtimeUpdateSettings, setRuntimeAutoUpdate } from './preferences';
10
10
 
11
11
  type Options={root:string;stateDirectory:string;manual?:boolean;now?:()=>number;latest?:()=>Promise<unknown>;
@@ -89,6 +89,31 @@ export function runtimeUpdateLoop(options:LoopOptions):()=>void {
89
89
  return ()=>{stopped=true;if(timer)clearTimeout(timer);};
90
90
  }
91
91
 
92
+ export type PendingRuntimeUpdate = { version: string; state: 'selected' | 'downloaded'; detail: string };
93
+
94
+ /**
95
+ * A newer runtime this computer holds while `running` is older: selected and started by GrantTap processes
96
+ * from their next start, or downloaded and not yet selected. Read from the version cache alone, without
97
+ * writing. The cache does not say why a busy monitor's hold gave way; its log does.
98
+ */
99
+ export function pendingRuntimeUpdate(running:string,directory=join(configDir(),'runtime-updates')):PendingRuntimeUpdate|undefined {
100
+ const state=readState(directory);
101
+ if(state.version && newerVersion(state.version,running) && validRuntime(state.root,directory,state.version)) {
102
+ return {version:state.version,state:'selected',
103
+ detail:`Selected. GrantTap processes started on ${running}, this MCP server included, run it from their next start.`};
104
+ }
105
+ let versions:string[]=[];
106
+ try {versions=readdirSync(join(directory,'versions'));} catch {return undefined;}
107
+ const staged=versions.filter(version=>newerVersion(version,running) && version!==state.rejectedVersion
108
+ && (!state.version || newerVersion(version,state.version)) && validRuntime(versionRoot(directory,version),directory,version))
109
+ .sort((a,b)=>newerVersion(a,b)?-1:1)[0];
110
+ if(!staged)return undefined;
111
+ return {version:staged,state:'downloaded',detail:automaticUpdatesAllowed(directory)
112
+ ? 'Downloaded. It takes over once the monitor\'s running work has ended; new phone messages wait for that at most '
113
+ +`${HOLD_LIMIT_MS/60_000} min at a time, and the monitor log says when a wait gave up.`
114
+ : 'Downloaded, but automatic updates are off on this computer, so it does not take over.'};
115
+ }
116
+
92
117
  /** Only the owned installed background monitor downloads updates; source checkouts stay fixed. */
93
118
  export function startRuntimeUpdates(idle:()=>boolean,drain?:UpdateDrain):()=>void {
94
119
  if(process.env.GRANTTAP_DISABLE_AUTO_UPDATE==='1' || process.env.GRANTTAP_LOCAL==='1'
@@ -2,6 +2,7 @@ import { recordObservedWrite, writtenPaths } from "../../mesh/observed/writes";
2
2
  import { readFileSync, statSync } from "node:fs";
3
3
  import { basename, dirname } from "node:path";
4
4
  import { normalizeMcpServerName, stripTranscriptMarkup } from "../support/activity-helpers";
5
+ import { stripQueueNote } from "../../task-dispatch/queue-note";
5
6
  import { cursorTranscriptsRoot, recentLogs, safeParse, ts } from "../support/common";
6
7
  import {
7
8
  estimateTokens,
@@ -43,7 +44,7 @@ export function textBlocks(content: unknown): string[] {
43
44
  }
44
45
 
45
46
  function titleFrom(text: string): string | undefined {
46
- const clean = stripTranscriptMarkup(text).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
47
+ const clean = stripQueueNote(stripTranscriptMarkup(text)).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
47
48
  return clean ? clean.slice(0, 120) : undefined;
48
49
  }
49
50
 
@@ -34,6 +34,8 @@ type ClaudeParseState = ClaudeTurnClock & {
34
34
  customTitle?: string;
35
35
  /** The name Claude generated for the chat; the latest one counts. */
36
36
  aiTitle?: string;
37
+ /** The reasoning effort of the chat's latest request. */
38
+ effort?: SessionInfo["effort"];
37
39
  summary?: string;
38
40
  startedAt: number;
39
41
  lastActivityAt: number;
@@ -47,6 +49,12 @@ type ClaudeParseState = ClaudeTurnClock & {
47
49
  turnEnded: boolean;
48
50
  };
49
51
 
52
+ const CLAUDE_EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
53
+
54
+ function claudeEffort(value: unknown): SessionInfo["effort"] | undefined {
55
+ return typeof value === "string" && CLAUDE_EFFORTS.has(value) ? value as SessionInfo["effort"] : undefined;
56
+ }
57
+
50
58
  function claudeName(value: unknown): string | undefined {
51
59
  if (typeof value !== "string") return undefined;
52
60
  const name = value.replace(/\s+/g, " ").trim();
@@ -71,6 +79,9 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
71
79
  if (typeof d.gitBranch === "string" && d.gitBranch.trim()) state.branch = d.gitBranch;
72
80
  }
73
81
  if (d.type === "custom-title") state.customTitle = claudeName(d.customTitle) ?? state.customTitle;
82
+ // Claude records each request it sends with its settings; the latest one says what the chat runs with,
83
+ // whether it was started on the phone or on the computer.
84
+ if (d.type === "api-request" && d.isSidechain !== true) state.effort = claudeEffort(d.params?.output_config?.effort) ?? state.effort;
74
85
  if (d.type === "ai-title") state.aiTitle = claudeName(d.aiTitle ?? d.content) ?? state.aiTitle;
75
86
  if (!state.title && (d.type === "user" || d.message?.role === "user")) {
76
87
  const raw =
@@ -259,6 +270,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
259
270
  worktree: state.cwd ? claudeCheckout({ ...state, cwd: state.cwd }) : undefined,
260
271
  branch: state.branch,
261
272
  model: state.model,
273
+ ...(state.effort ? { effort: state.effort } : {}),
262
274
  summary: state.summary,
263
275
  state: state.turnEnded ? "idle" : stateFor(state.lastActivityAt),
264
276
  startedAt: state.startedAt || state.lastActivityAt,
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { ActivityEntry } from "../../../../../packages/protocol/schema";
7
7
  import { heartbeatDisplayText } from '../host-heartbeat';
8
+ import { stripQueueNote } from '../../task-dispatch/queue-note';
8
9
  import {
9
10
  parseMcpToolName,
10
11
  skillNameFromInput,
@@ -106,7 +107,8 @@ export function visibleUserText(value: unknown): string {
106
107
  /^(?:\s*<external_codex_apps_open_page\b[^>]*>[\s\S]*?(?:<\/external_codex_apps_open_page\s*>|$))+/i,
107
108
  "",
108
109
  );
109
- const text = stripAttachmentNote(stripTranscriptMarkup(contextFree).trim());
110
+ // GrantTap's own lines after the person's words: the queued-messages note, then the attachment note.
111
+ const text = stripAttachmentNote(stripQueueNote(stripTranscriptMarkup(contextFree).trim()));
110
112
  if (!text) return "";
111
113
  // The host's own notes about what it showed the model: nobody typed them.
112
114
  if (text.startsWith("[Image: original ") || text.startsWith("<local-command-caveat>")) return "";
@@ -53,6 +53,28 @@ job, refreshes its catalog while held, and starts automatically once it is idle.
53
53
  This does not turn a temporary native busy state into a failed delivery or ask
54
54
  the person to resend. It does not claim provider-native mid-turn Steer support.
55
55
 
56
+ ## Messages still queued behind a delivery
57
+
58
+ When a message reaches its chat while more phone messages for that chat wait here, its prompt
59
+ carries one GrantTap line after the person's words (`queue-note.ts`), for example:
60
+
61
+ > GrantTap: 3 more messages from the phone are queued for this chat and arrive after this turn.
62
+ > Tests of what you change can run now; repository-wide checks, full test runs and publishing can
63
+ > wait for the last of them unless this message asks for those now.
64
+
65
+ `worker/queue-depth.ts` counts, when the prompt is written, the jobs staged or claimed for the same
66
+ chat; for a new task, the follow-ups written for it before its chat existed. It leaves out the
67
+ delivered job, this computer's own jobs such as a limit continuation, and messages held behind a
68
+ refusal. Every job the relay offers is staged here at once, whether its chat is free or not, so the
69
+ count covers what the relay has offered; a message scheduled more than five minutes ahead is counted
70
+ once it is offered. No line is added when nothing waits or the message is attachments alone. The
71
+ delivery's identity stays the person's text, so a retried Codex delivery is still the same one.
72
+ The transcript views remove the line (`visibleUserText`, Cursor's chat name), so the phone shows
73
+ the person's words. `queuedPhoneMessages` reads the same count from another process without
74
+ writing; the chat's own MCP server reports it in `connection_status`, so an agent can look again
75
+ before a long run. Regression cases: `tests/queue-note.test.ts`, `worker/tests/queue-depth.test.ts`
76
+ and `../monitor/handlers/tests/queue-note.test.ts`.
77
+
56
78
  Relay queue errors are logged by `worker/failure-report.ts`. A dropped connection,
57
79
  a timeout or a relay 5xx is retried on the next two-second pass and is logged only
58
80
  after 30 seconds of continuing failures; storage faults are logged at once. Both
@@ -10,6 +10,25 @@ import { InboxState, RequestRecord, phaseTransitions, type InboxPhase, type Stor
10
10
  type StageResult = 'staged' | 'existing' | 'conflict';
11
11
  const safeId = /^[A-Za-z0-9][A-Za-z0-9_-]{7,119}$/;
12
12
 
13
+ /**
14
+ * The jobs of a room that have not completed or been cancelled, read from another process without
15
+ * creating, repairing or locking anything. A record being written is skipped until it is whole.
16
+ */
17
+ export function waitingDispatchRecords(root: string, room: string): StoredTaskDispatch[] {
18
+ const directory = join(root, digest(room));
19
+ if (!existsSync(directory)) return [];
20
+ return readdirSync(directory, { withFileTypes: true })
21
+ .filter(entry => entry.isDirectory() && safeId.test(entry.name))
22
+ .flatMap(entry => {
23
+ try {
24
+ const request = RequestRecord.parse(readRequest(join(directory, entry.name, 'request.json')));
25
+ if (request.room !== room || request.job.jobId !== entry.name) return [];
26
+ const { state } = readJournal(join(directory, entry.name, 'events.jsonl'), { phase: 'staged', updatedAt: request.stagedAt });
27
+ return ['completed', 'cancelled'].includes(state.phase) ? [] : [{ ...request, ...state }];
28
+ } catch { return []; }
29
+ });
30
+ }
31
+
13
32
  /** A receiver persists the complete operation before claiming it from the relay. */
14
33
  export class TaskDispatchInbox {
15
34
  private readonly directory: string;
@@ -0,0 +1,33 @@
1
+ const ADVICE = 'Tests of what you change can run now; repository-wide checks, full test runs and publishing can wait for';
2
+ const ASKED = 'unless this message asks for those now.';
3
+
4
+ /**
5
+ * The line a phone message carries into its chat when more messages for that chat wait behind it.
6
+ * The agent can then leave repository-wide checks, full test runs and publishing for the last of
7
+ * them instead of running them once per message. It is GrantTap's line, not the person's: the
8
+ * transcript views remove it (`stripQueueNote`), so the phone shows the words the person typed.
9
+ */
10
+ export function queueNote(count: number | undefined): string | undefined {
11
+ if (!count || !Number.isSafeInteger(count) || count < 1) return undefined;
12
+ return count === 1
13
+ ? `GrantTap: 1 more message from the phone is queued for this chat and arrives after this turn. ${ADVICE} it ${ASKED}`
14
+ : `GrantTap: ${count} more messages from the phone are queued for this chat and arrive after this turn. `
15
+ + `${ADVICE} the last of them ${ASKED}`;
16
+ }
17
+
18
+ /**
19
+ * The person's text with the line after it, as its own paragraph. A message of attachments alone
20
+ * gets no line: its prompt is written by the attachment step, which needs the text left empty.
21
+ */
22
+ export function withQueueNote(text: string, count: number | undefined): string {
23
+ const note = queueNote(count);
24
+ return note && text.trim() ? `${text}\n\n${note}` : text;
25
+ }
26
+
27
+ const NOTE = new RegExp('\\n\\nGrantTap: \\d+ more messages? from the phone (?:is|are) queued for this chat and arrives? '
28
+ + `after this turn\\. ${ADVICE} (?:it|the last of them) ${ASKED.replace('.', '\\.')}(?=\\n\\n|$)`);
29
+
30
+ /** The text without that line, wherever the attachment note or a host wrapper left it. */
31
+ export function stripQueueNote(text: string): string {
32
+ return text.replace(NOTE, '');
33
+ }
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import type { TaskDispatch } from '../../../../../packages/protocol/schema';
3
3
  import { TaskDispatchInbox, type StoredTaskDispatch } from '../index';
4
+ import { queuedBehind } from './queue-depth';
4
5
 
5
6
  export interface TaskJobRemote {
6
7
  get(job: TaskDispatch): Promise<string>;
@@ -15,7 +16,12 @@ export type WorkerOptions = {
15
16
  conversationKey?: (job: TaskDispatch, peer: string) => string;
16
17
  validationCode?: (job: TaskDispatch, peer: string) => string | undefined;
17
18
  ready: (job: TaskDispatch, peer: string) => boolean;
18
- deliver: (job: TaskDispatch, beforeStart: () => Promise<void>, peer: string) => Promise<'accepted' | 'rejected'>;
19
+ /**
20
+ * `queued` counts the phone messages that reach the same chat after this one. It reads the queue
21
+ * when called, so the count is the one at the moment the prompt is written.
22
+ */
23
+ deliver: (job: TaskDispatch, beforeStart: () => Promise<void>, peer: string,
24
+ queued: () => number) => Promise<'accepted' | 'rejected'>;
19
25
  };
20
26
  class DeferredLaunch extends Error {}
21
27
  const REFUSED_LOOKUP_MS = 10 * 60_000;
@@ -34,8 +40,7 @@ export class TaskDispatchWorker {
34
40
  const records = this.options.inbox.pendingRecords().sort((a, b) =>
35
41
  Number(b.job.deliveryMode === 'immediate') - Number(a.job.deliveryMode === 'immediate')
36
42
  || a.job.createdAt - b.job.createdAt);
37
- const keyOf = (record: StoredTaskDispatch) => this.options.conversationKey?.(record.job, record.peerPublicKey)
38
- ?? record.job.sessionId ?? `new:${record.job.operation.agent ?? 'codex'}`;
43
+ const keyOf = (record: StoredTaskDispatch) => this.key(record.job, record.peerPublicKey);
39
44
  // A refusal is final for its message. It keeps holding the follow-ups that were already queued behind
40
45
  // it until the person cancels it; it used to hold every later message of the chat as well, for days.
41
46
  const refusedAt = new Map<string, number>();
@@ -61,6 +66,10 @@ export class TaskDispatchWorker {
61
66
  await Promise.all(launched);
62
67
  }
63
68
 
69
+ private key(job: TaskDispatch, peer: string): string {
70
+ return this.options.conversationKey?.(job, peer) ?? job.sessionId ?? `new:${job.operation.agent ?? 'codex'}`;
71
+ }
72
+
64
73
  private async process(record: StoredTaskDispatch): Promise<void> {
65
74
  const { inbox, remote } = this.options, { job } = record;
66
75
  let claimId = record.claimId;
@@ -101,7 +110,7 @@ export class TaskDispatchWorker {
101
110
  throw new DeferredLaunch();
102
111
  }
103
112
  started = true;
104
- }, record.peerPublicKey);
113
+ }, record.peerPublicKey, () => queuedBehind(inbox.pendingRecords(), record, (next, peer) => this.key(next, peer)));
105
114
  if (!started) { if (outcome === 'rejected') await this.reject(record, 'policy_denied'); return; }
106
115
  inbox.transition(job.jobId, outcome === 'accepted' ? 'delivered' : 'failed',
107
116
  outcome === 'rejected' ? { code: 'delivery_failed' } : {});
@@ -9,6 +9,7 @@ import { sendDeliveryArrival } from '../../monitor/handlers/receipts';
9
9
  import { TaskDispatchInbox } from '../index';
10
10
  import { TaskDispatchWorker, type TaskJobRemote, type WorkerOptions } from './index';
11
11
  import { relayTaskJobRemote } from './remote';
12
+ import { conversationKeyOf } from './queue-depth';
12
13
  import { NativeTaskQueueSender } from '../sender';
13
14
  import { dispatchSessionObservation, newTaskOperationKey, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
14
15
  import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
@@ -41,9 +42,7 @@ export function startTaskDispatchMonitor(input: {
41
42
  authorized: peerAllowed,
42
43
  onTerminal: job => sender.confirmReceiverOutcome(job),
43
44
  onError: error => reportFailure(error),
44
- conversationKey: (job, peer) => resolve(job, peer).job?.sessionId
45
- ?? (job.operation.type === 'user.message.continue'
46
- ? JSON.stringify([peer, job.operation.originMessageId]) : `new:${job.operation.agent ?? 'codex'}`),
45
+ conversationKey: conversationKeyOf((job, peer) => resolve(job, peer).job),
47
46
  validationCode: (job, peer) => {
48
47
  const state = resolve(job, peer).state;
49
48
  return state === 'uncertain' ? 'confirmation_required'
@@ -74,13 +73,13 @@ export function startTaskDispatchMonitor(input: {
74
73
  }
75
74
  return ready;
76
75
  },
77
- deliver: (original, beforeStart, peer) => track(async () => {
76
+ deliver: (original, beforeStart, peer, queued) => track(async () => {
78
77
  if (original.operation.type === 'user.message' && limitContinuationUnwanted(original.operation)) return 'rejected';
79
- if (input.deliver) return input.deliver(original, beforeStart, peer);
78
+ if (input.deliver) return input.deliver(original, beforeStart, peer, queued);
80
79
  const job = resolve(original, peer).job;
81
80
  if (!job || job.operation.type === 'user.message.continue') return 'rejected';
82
81
  const outcome = job.operation.type === 'user.message'
83
- ? await handleUserMessage(input.client, job.operation, beforeStart, peer)
82
+ ? await handleUserMessage(input.client, job.operation, beforeStart, peer, undefined, undefined, queued)
84
83
  : (await handleTaskCreate(input.client, job.operation, beforeStart)).status;
85
84
  void input.publish().catch(() => {});
86
85
  return outcome;
@@ -0,0 +1,68 @@
1
+ import { join } from 'node:path';
2
+ import type { TaskDispatch } from '../../../../../packages/protocol/schema';
3
+ import { configDir } from '../../config';
4
+ import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
5
+ import { waitingDispatchRecords } from '../inbox';
6
+ import type { StoredTaskDispatch } from '../records';
7
+
8
+ export type ConversationKey = (job: TaskDispatch, peer: string) => string;
9
+ type Delivered = { job: TaskDispatch; peerPublicKey: string };
10
+
11
+ /** Phases of a job that has not reached its chat yet and will when its turn comes. */
12
+ const WAITING = new Set(['staged', 'claimed']);
13
+
14
+ /**
15
+ * The chat a queued job goes to: its own, or the one its new task became. Jobs of one key run one
16
+ * at a time. New tasks of one provider share a key, so one creation finishes before the next starts.
17
+ */
18
+ export function conversationKeyOf(resolve: (job: TaskDispatch, peer: string) => TaskDispatch | undefined): ConversationKey {
19
+ return (job, peer) => resolve(job, peer)?.sessionId
20
+ ?? (job.operation.type === 'user.message.continue'
21
+ ? JSON.stringify([peer, job.operation.originMessageId]) : `new:${job.operation.agent ?? 'codex'}`);
22
+ }
23
+
24
+ /**
25
+ * The jobs for the chat a delivery goes to. A new task has no chat id yet, so its chat's messages
26
+ * are the follow-ups written for it, which name its origin. Other new tasks share its key but are
27
+ * other chats, and a Project task (`project.task.create`) takes no follow-ups.
28
+ */
29
+ function sameChat(delivered: Delivered, keyOf: ConversationKey): ((record: StoredTaskDispatch) => boolean) | undefined {
30
+ const { job, peerPublicKey } = delivered, operation = job.operation;
31
+ if (operation.type === 'project.task.create') return undefined;
32
+ if (operation.type === 'user.message' && !job.sessionId) {
33
+ const origin = operation.taskOriginId;
34
+ return origin ? record => record.peerPublicKey === peerPublicKey
35
+ && record.job.operation.type === 'user.message.continue' && record.job.operation.originMessageId === origin
36
+ : undefined;
37
+ }
38
+ const key = keyOf(job, peerPublicKey);
39
+ return record => keyOf(record.job, record.peerPublicKey) === key;
40
+ }
41
+
42
+ /**
43
+ * How many messages from the phone wait for one chat. This computer's own queued work, such as a
44
+ * limit continuation, is not from the phone. A message staged before a refused one of the same chat
45
+ * waits for the person to cancel the refusal, not for this turn. Neither is counted.
46
+ */
47
+ function waitingFor(records: StoredTaskDispatch[], ours: (record: StoredTaskDispatch) => boolean, except?: string): number {
48
+ let refusedAt = -Infinity;
49
+ for (const record of records) if (record.phase === 'rejected' && ours(record)) refusedAt = Math.max(refusedAt, record.updatedAt);
50
+ return records.filter(record => record.job.jobId !== except && record.job.origin !== 'computer'
51
+ && WAITING.has(record.phase) && record.stagedAt > refusedAt && ours(record)).length;
52
+ }
53
+
54
+ /** The phone messages that reach the same chat after `delivered`. */
55
+ export function queuedBehind(records: StoredTaskDispatch[], delivered: Delivered, keyOf: ConversationKey): number {
56
+ const ours = sameChat(delivered, keyOf);
57
+ return ours ? waitingFor(records, ours, delivered.job.jobId) : 0;
58
+ }
59
+
60
+ /**
61
+ * For a status view in another process, such as a chat's own MCP server: the phone messages this
62
+ * computer holds for `sessionId`. Reading creates nothing in the queue's directory.
63
+ */
64
+ export function queuedPhoneMessages(sessionId: string, room: string, root = join(configDir(), 'task-dispatch')): number {
65
+ const origins = localTaskOrigins();
66
+ const keyOf = conversationKeyOf((job, peer) => resolveTaskOriginJob(origins, job, room, peer).job);
67
+ return waitingFor(waitingDispatchRecords(root, room), record => keyOf(record.job, record.peerPublicKey) === sessionId);
68
+ }
@@ -11,6 +11,14 @@ phone export is absent. Reconnect requires explicit confirmation. A pending QR
11
11
  is reusable until expiry in this MCP process; restarting the process loses the
12
12
  transfer code but preserves the pairing. It never persists transfer secrets.
13
13
 
14
+ Status also carries, read without writing: a text line sorting the paired phones by when each
15
+ last reached this computer (keys stay paired until the pairing is replaced, so old test installs
16
+ stay listed); `pendingUpdate`, a newer runtime this computer holds and why it is not running yet;
17
+ and `chat`, for the chat named in this server's environment (Claude Code's
18
+ `CLAUDE_CODE_SESSION_ID`), the phone messages queued to reach it after its turn and whether it
19
+ continues by itself after a subscription limit. Hosts that name no chat get `chat: null`; none is
20
+ guessed. `../status/chat-status.ts` assembles the chat part.
21
+
14
22
  Saved keys, this process's relay socket, and recent authenticated phone messages
15
23
  are distinct. Unknown phone availability stays unknown. Provider readiness is
16
24
  configuration information, not evidence that the provider is currently running.
@@ -7,7 +7,8 @@ import { packageVersion } from "../status/package-version";
7
7
  import { connectionRuntimeStatus } from "../mcp-tools/connect/relay";
8
8
  import { beginEnrollment, cancelEnrollment, enrollmentIsOpen } from "./enrollment";
9
9
  import { loadAccountLink } from "../../../bridge/src/account-recovery/link";
10
- import { runtimeUpdateSettings } from "../../../bridge/src/runtime-updates";
10
+ import { pendingRuntimeUpdate, runtimeUpdateSettings } from "../../../bridge/src/runtime-updates";
11
+ import { chatStatus } from "../status/chat-status";
11
12
 
12
13
  export const connectionOutput = {
13
14
  status: z.enum(["disconnected", "paired", "pairing", "expired", "connected"]),
@@ -18,15 +19,30 @@ export const connectionOutput = {
18
19
  phoneLastSeenAt: z.number().nullable(),
19
20
  phones: z.array(z.object({
20
21
  name: z.string(),
21
- status: z.enum(["paired", "seen"]),
22
- lastSeenAt: z.number().nullable(),
23
- })),
22
+ status: z.enum(["paired", "seen"]).describe("seen: an authenticated message from this phone arrived in the last minute"),
23
+ lastSeenAt: z.number().nullable().describe(
24
+ "When this computer last received an authenticated message from this phone key; null: never. A key stays "
25
+ + "paired until the pairing is replaced, so a test install that was deleted keeps its row with an old or null time",
26
+ ),
27
+ })).describe("Every phone or iPad key allowed to control this computer: the first pairing, then added devices"),
24
28
  expiresAt: z.number().nullable(),
25
29
  expiresInMinutes: z.number().int().positive().nullable(),
26
30
  providers: z.array(z.object({ id: z.string(), status: z.string(), detail: z.string() })),
27
31
  roomPrefix: z.string(),
28
32
  accountLinkSaved: z.boolean(),
29
33
  runtimeUpdates: z.object({ enabled: z.boolean(), lockedByEnvironment: z.boolean() }),
34
+ pendingUpdate: z.object({
35
+ version: z.string(),
36
+ state: z.enum(["selected", "downloaded"]),
37
+ detail: z.string(),
38
+ }).nullable().describe("A newer GrantTap runtime on this computer than the one this server runs, and why it is not running yet"),
39
+ chat: z.object({
40
+ queuedPhoneMessages: z.number().int().nonnegative()
41
+ .describe("Phone messages this computer holds for the calling chat; they arrive one by one after the current turn"),
42
+ autoContinue: z.boolean().describe("Whether the chat continues by itself after a subscription limit stopped it"),
43
+ continuation: z.object({ dueAt: z.number(), early: z.boolean() }).nullable()
44
+ .describe("The continuation queued for the chat after a subscription limit; early: another goes at once"),
45
+ }).nullable().describe("The calling chat, when this server knows it (Claude Code); null elsewhere"),
30
46
  passkeyUrl: z.string().url().optional(),
31
47
  };
32
48
 
@@ -83,6 +99,8 @@ export class ConnectionState {
83
99
  roomPrefix: config?.room ? config.room.slice(0, 8) : "",
84
100
  accountLinkSaved: loadAccountLink() !== null,
85
101
  runtimeUpdates: runtimeUpdateSettings(),
102
+ pendingUpdate: pendingRuntimeUpdate(packageVersion()) ?? null,
103
+ chat: chatStatus(config?.room),
86
104
  },
87
105
  _meta: { granttap: code ? { pairingUri: code.pairingUri, qrDataUrl: code.qrDataUrl } : {} },
88
106
  };
@@ -9,7 +9,9 @@ export function registerRuntimeUpdateControl(
9
9
  ): void {
10
10
  server.registerTool('set_runtime_auto_update', {
11
11
  title: 'GrantTap automatic updates',
12
- description: 'Enable or disable automatic GrantTap runtime updates on this computer when the user requests it. Saves the preference without restarting services or changing pairing, tasks, or provider policy.',
12
+ description: 'Turn automatic GrantTap runtime updates on this computer on or off, only when the person asks for it. '
13
+ + 'Saves the computer-wide preference without restarting services or changing pairing, tasks or provider policy; a '
14
+ + 'service-level disable cannot be overridden from here. Returns the same state as connection_status with the saved setting.',
13
15
  inputSchema: { enabled: z.boolean().describe('Whether this computer should automatically check for and apply stable GrantTap runtime updates') },
14
16
  outputSchema: connectionOutput,
15
17
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
@@ -9,6 +9,8 @@ import { CONNECTION_WIDGET_URI } from "./widget";
9
9
  import { resetRelay, relay } from "./relay";
10
10
  import { startPasskeyAccountLink } from "../../connection-center/passkey";
11
11
  import { registerRuntimeUpdateControl } from "../../connection-center/update-controls";
12
+ import { chatStatusLine } from "../../status/chat-status";
13
+ import { phoneSummary } from "../../status/pairing-status";
12
14
 
13
15
  const widgetMeta = {
14
16
  ui: { resourceUri: CONNECTION_WIDGET_URI, visibility: ["model", "app"] },
@@ -36,7 +38,12 @@ export function registerConnectTool(server: McpServer): void {
36
38
  };
37
39
  server.registerTool("connection_status", {
38
40
  title: "GrantTap connection center",
39
- description: "Open connection controls and inspect pairing, QR expiry, this computer, relay observations and provider readiness. Does not create or replace pairing.",
41
+ description: "Read GrantTap's state on this computer without changing it: the pairing and paired phones with when each "
42
+ + "last reached this computer, any open pairing QR, relay reachability, provider readiness, the runtime version and any "
43
+ + "newer one waiting to take over, and, for the calling Claude Code chat, how many phone messages are queued to reach "
44
+ + "it after this turn and whether it continues by itself after a subscription limit. Shows the connection card where "
45
+ + "the host renders one. Use it to diagnose pairing or phone delivery, and before long repository-wide work. Never "
46
+ + "creates, replaces or removes a pairing.",
40
47
  inputSchema: {},
41
48
  outputSchema: connectionOutput,
42
49
  annotations: { ...changes, readOnlyHint: true, idempotentHint: true },
@@ -44,7 +51,9 @@ export function registerConnectTool(server: McpServer): void {
44
51
  }, async () => connectionResult(state));
45
52
  server.registerTool("connect_with_passkey", {
46
53
  title: "Link this Mac to a GrantTap account",
47
- description: "Open a short-lived GrantTap account passkey request for this Mac. The passkey is entered only on granttap.com; existing QR pairings remain unchanged.",
54
+ description: "Link this Mac to the person's GrantTap account, so a phone signed in to that account can connect to it "
55
+ + "without a QR. Returns passkeyUrl, a granttap.com page valid for 15 minutes (also on the connection card), where the "
56
+ + "person confirms with their account passkey; the passkey is entered only there. Existing QR pairings are unchanged.",
48
57
  inputSchema: {},
49
58
  outputSchema: connectionOutput,
50
59
  annotations: changes,
@@ -65,7 +74,10 @@ export function registerConnectTool(server: McpServer): void {
65
74
  server.registerTool(
66
75
  "connect",
67
76
  {
68
- description: "Open the GrantTap connection card: the saved pairing slot and Add a device. QR stays on the card, not in chat.",
77
+ description: "Pair this computer with the GrantTap phone app. On a computer that is not paired yet, creates a one-time "
78
+ + "pairing QR, valid 15 minutes, shown on the connection card and never in chat; on a paired computer, only shows the "
79
+ + "card with the saved pairing and starts the relay link. Returns the same state as connection_status. To pair a "
80
+ + "phone again or add another device, use reconnect.",
69
81
  inputSchema: {},
70
82
  outputSchema: connectionOutput,
71
83
  annotations: changes,
@@ -76,7 +88,11 @@ export function registerConnectTool(server: McpServer): void {
76
88
  server.registerTool(
77
89
  "reconnect",
78
90
  {
79
- description: "Show a one-time QR for reconnect or add an independent controller device to this computer. Requires confirmation and keeps the current room.",
91
+ description: "After the person confirms, show a new one-time pairing QR, valid 15 minutes, on the connection card. "
92
+ + "mode=reconnect offers this computer's existing phone pairing again, for a phone that lost it; mode=add_device "
93
+ + "enrolls one more phone or iPad with its own key (at most 16 added keys; a scanned key stays paired until the "
94
+ + "pairing is replaced, one never scanned is dropped). The current room and paired phones keep working. Pass "
95
+ + "confirmed=true only after the person agreed.",
80
96
  inputSchema: {
81
97
  confirmed: z.boolean().describe("True only after the user confirms showing a new QR"),
82
98
  mode: z.enum(["reconnect", "add_device"]).default("reconnect"),
@@ -128,16 +144,21 @@ async function connect(
128
144
 
129
145
  function connectionResult(state: ConnectionState): CallToolResult {
130
146
  const snapshot = state.snapshot();
131
- const { status, computer, relay, version, relayStatus, runtimeUpdates } = snapshot.structuredContent;
147
+ const { status, computer, relay, version, relayStatus, runtimeUpdates, phones, pendingUpdate, chat } = snapshot.structuredContent;
132
148
  const instructions = status === "pairing"
133
149
  ? "Use the GrantTap card: tap Add a device if needed, then scan the QR on the card."
134
150
  : status === "disconnected" ? "Use the GrantTap card and tap Add a device. The QR stays on the card."
135
151
  : status === "expired" ? "The card QR expired. Tap Add a device again and confirm."
136
152
  : "The GrantTap card shows the saved pairing room on this Mac and last confirmed activity. Add another device to start a new enrollment attempt. A Mesh link shares Mesh only.";
153
+ const details = [
154
+ phoneSummary(phones),
155
+ pendingUpdate ? `Runtime ${pendingUpdate.version} is waiting: ${pendingUpdate.detail}` : undefined,
156
+ chatStatusLine(chat),
157
+ ].filter(Boolean).join("\n");
137
158
  return {
138
159
  ...snapshot,
139
160
  content: [{ type: "text", text:
140
- `GrantTap: ${status}. Computer: ${computer}. MCP ${version}. Relay: ${relay || "not configured"} (${relayStatus}). Automatic runtime updates: ${runtimeUpdates.enabled ? "on" : "off"}.\n${instructions}`,
161
+ `GrantTap: ${status}. Computer: ${computer}. MCP ${version}. Relay: ${relay || "not configured"} (${relayStatus}). Automatic runtime updates: ${runtimeUpdates.enabled ? "on" : "off"}.\n${details ? `${details}\n` : ""}${instructions}`,
141
162
  }],
142
163
  };
143
164
  }
@@ -45,7 +45,10 @@ export function registerNotifyTool(server: McpServer, once: Once): void {
45
45
  "notify",
46
46
  {
47
47
  description:
48
- "Send a non-blocking status to the user, or publish one bounded task-scoped Project Mesh event. "
48
+ "Show a short status on the person's phone without waiting, or publish one bounded task-scoped Project "
49
+ + "Mesh event, or both. Nobody answers a status: use ask or ask_yes_no for an answer. Use it for what the person "
50
+ + "would want to know while away, such as a long run finishing or a blocker; the reply that ends this turn reaches "
51
+ + "the phone without it. "
49
52
  + "The result says whether the text was sent and whether the event was recorded; an error means nothing happened, "
50
53
  + "and a result with an error field says which part is still owed. Give the call an operationId to make retries safe. "
51
54
  + "A handoff is started by the person from the phone, never by an event published here.",
@@ -23,7 +23,8 @@ export function registerQuestionTools(server: McpServer, once: Once): void {
23
23
  "ask_yes_no",
24
24
  {
25
25
  description:
26
- "Ask the user a yes/no question on their phone/watch and wait for the tap. Returns 'yes' or 'no' "
26
+ "Ask the person a yes/no question on their phone or watch and wait for the tap, about three minutes by default. "
27
+ + "Use it when the work needs their decision and they may be away from this computer. Returns 'yes' or 'no' "
27
28
  + "when they answered, or 'no-answer (timeout)' when nobody answered in time. A timeout is not a "
28
29
  + "refusal: do not treat it as 'no', and do not treat it as permission. With an operationId, a retry "
29
30
  + "returns the answer already given instead of asking again.",
@@ -50,7 +51,8 @@ export function registerQuestionTools(server: McpServer, once: Once): void {
50
51
  "ask",
51
52
  {
52
53
  description:
53
- "Ask the user an open question on their phone/watch and wait for their spoken or typed reply. "
54
+ "Ask the person an open question on their phone or watch and wait for their spoken or typed reply, about three "
55
+ + "minutes by default. Use it when the work needs their words, such as a name or a choice among more than two options. "
54
56
  + "Returns their answer text, or 'no-answer (timeout)' when nobody answered in time; a timeout is "
55
57
  + "not an answer. With an operationId, a retry returns the answer already given instead of asking again.",
56
58
  inputSchema: { question, operationId },
@@ -17,7 +17,9 @@ export function registerMeshResource(server: McpServer): void {
17
17
  MESH_URI,
18
18
  {
19
19
  title: "GrantTap Project Mesh",
20
- description: "How to obtain this execution's scoped coordination state.",
20
+ description: "This chat's Project Mesh state (Project, Task, owners, claims, dependencies and recent events) when this "
21
+ + "server knows the calling chat, as in Claude Code; elsewhere, a hint naming the scoped URI to read instead. Never "
22
+ + "another chat's Project; transcripts are never included.",
21
23
  mimeType: "application/json",
22
24
  },
23
25
  async (uri) => readCurrentMesh(uri),
@@ -0,0 +1,36 @@
1
+ import { limitContinuationFor } from "../../../bridge/src/limit-continuation";
2
+ import { queuedPhoneMessages } from "../../../bridge/src/task-dispatch/worker/queue-depth";
3
+ import { sessionFromEnvironment } from "../mcp-tools/mesh/session-env";
4
+
5
+ export type ChatStatus = {
6
+ queuedPhoneMessages: number;
7
+ autoContinue: boolean;
8
+ continuation: { dueAt: number; early: boolean } | null;
9
+ };
10
+
11
+ /**
12
+ * What this computer holds for the chat that started this MCP server: the phone messages queued to
13
+ * reach it after its current turn, and whether it goes on by itself after a subscription limit. The
14
+ * chat is the one Claude Code names in this server's environment; other hosts name none, and no
15
+ * chat is guessed from a working directory. Reading writes nothing.
16
+ */
17
+ export function chatStatus(room: string | undefined, env: NodeJS.ProcessEnv = process.env): ChatStatus | null {
18
+ const sessionId = sessionFromEnvironment(env);
19
+ if (!sessionId || !room) return null;
20
+ let queued = 0;
21
+ try { queued = queuedPhoneMessages(sessionId, room); } catch { /* An unreadable queue shows none. */ }
22
+ const limit = limitContinuationFor(sessionId);
23
+ return { queuedPhoneMessages: queued, autoContinue: limit.autoContinue, continuation: limit.continuation ?? null };
24
+ }
25
+
26
+ export function chatStatusLine(chat: ChatStatus | null): string | undefined {
27
+ if (!chat) return undefined;
28
+ const queued = chat.queuedPhoneMessages === 0 ? "no phone messages are queued for it"
29
+ : `${chat.queuedPhoneMessages} phone message${chat.queuedPhoneMessages === 1 ? " is" : "s are"} queued to reach it after this turn`;
30
+ const limit = chat.continuation
31
+ ? `a continuation after a subscription limit is queued for it, due ${new Date(chat.continuation.dueAt).toISOString()}`
32
+ + (chat.continuation.early ? ", and another to go at once because the account's readings showed room" : "")
33
+ : chat.autoContinue ? "it continues by itself if a subscription limit stops it"
34
+ : "it does not continue by itself after a subscription limit (turned off on the phone)";
35
+ return `This chat: ${queued}; ${limit}.`;
36
+ }
@@ -73,3 +73,19 @@ export function listPairedPhones(phoneLastSeenAt: number | null = null, now = Da
73
73
  });
74
74
  return [primary, ...additional];
75
75
  }
76
+
77
+ const RECENT_MS = 7 * 86_400_000;
78
+
79
+ /**
80
+ * The paired phones by how recently each spoke to this computer. Keys stay paired until the pairing is
81
+ * replaced, so test installs and deleted apps pile up; this tells the ones in use from the rest.
82
+ */
83
+ export function phoneSummary(phones: PairedPhone[], now = Date.now()): string | undefined {
84
+ if (phones.length === 0) return undefined;
85
+ const seen = phones.filter((phone) => phone.status === "seen").length;
86
+ const recent = phones.filter((phone) => phone.status !== "seen" && phone.lastSeenAt != null
87
+ && now - phone.lastSeenAt < RECENT_MS).length;
88
+ const rest = phones.length - seen - recent;
89
+ return `Paired phones: ${phones.length} — ${seen} active in the last minute, ${recent} more seen in the last 7 days, `
90
+ + `${rest} not seen for 7 days or never.`;
91
+ }
@@ -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.185
13
+ npm install -g granttap-mcp@0.8.187
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.185\";\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.187\";\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.185";
10
+ const PACKAGE = "granttap-mcp@0.8.187";
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.185",
3
+ "version": "0.8.187",
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": {