granttap-mcp 0.8.201 → 0.8.202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,7 +73,7 @@ service need a durable path, not npm's temporary `npx` cache.
73
73
 
74
74
  ## What's new
75
75
 
76
- Available now, with GrantTap MCP 0.8.201 on npm and GrantTap 1.0.2 on the App Store:
76
+ Available now, with GrantTap MCP 0.8.202 on npm and GrantTap 1.0.2 on the App Store:
77
77
 
78
78
  - **Phones on the connection card.** In Claude (including the Claude desktop app),
79
79
  Codex, Cursor and Grok Build, the GrantTap card lists every phone paired with
@@ -6,9 +6,13 @@ let running = 0;
6
6
  const waiting: Array<() => void> = [];
7
7
  const pending = new Map<string, Promise<RepositoryFacts>>();
8
8
 
9
- /** Native read-only Git work stays bounded without blocking relay callbacks. */
9
+ /**
10
+ * Native read-only Git work stays bounded without blocking relay callbacks. An `urgent` read, one a
11
+ * person is waiting for on the phone, goes ahead of the background readings and may take a third
12
+ * slot: behind a queue of catalog and working-tree readings it came after the phone stopped waiting.
13
+ */
10
14
  export function readRepositoryGit(cwd: string, args: string[],
11
- options: { timeoutMs?: number; maxBuffer?: number } = {}): Promise<string | undefined> {
15
+ options: { timeoutMs?: number; maxBuffer?: number; urgent?: boolean } = {}): Promise<string | undefined> {
12
16
  return new Promise(resolve => {
13
17
  const run = () => {
14
18
  running++;
@@ -24,7 +28,9 @@ export function readRepositoryGit(cwd: string, args: string[],
24
28
  }, done);
25
29
  } catch { done(new Error("Repository command could not start")); }
26
30
  };
27
- if (running < 2) run(); else waiting.push(run);
31
+ if (running < (options.urgent ? 3 : 2)) run();
32
+ else if (options.urgent) waiting.unshift(run);
33
+ else waiting.push(run);
28
34
  });
29
35
  }
30
36
 
@@ -25,6 +25,8 @@ import { reportMessageAgentActivity } from '../message-delivery/activity';
25
25
  import { ACCEPTANCE_WINDOW_MS, acceptWhenStarted, PHONE_RUN_LIMIT_MS } from "../message-delivery/acceptance";
26
26
  import { chatReplyHandle, newTaskHandle, sentMessage, settleChatReply, settleNewTask } from "../message-delivery/late-results";
27
27
  import { withSurvivor } from "../../reply/survival";
28
+ import { lineageAgent } from "../../started-by/headless";
29
+ import { rememberStartedLinks } from "../../started-by/links";
28
30
 
29
31
  async function startNewAgentTask(input: {
30
32
  client: RelayClient;
@@ -87,6 +89,7 @@ async function startNewAgentTask(input: {
87
89
  // Claude, Grok and Cursor name the chat as it starts; Codex only when its run ends.
88
90
  const started = (sessionId: string) => {
89
91
  try { input.origin?.registry.started(input.origin.scope, sessionId); } catch { /* The run's end records it. */ }
92
+ linkStartedFromPhone(agent, sessionId, message.startedBy);
90
93
  };
91
94
  // Follow-ups written before this chat existed reach it after its first turn.
92
95
  const prompt = projectGuidancePrompt(admittedProjectId, withQueueNote(message.text, input.queuedBehind?.()));
@@ -109,7 +112,11 @@ async function startNewAgentTask(input: {
109
112
  await say(`Could not create a ${displayName} task on this computer.`, undefined, true);
110
113
  return 'rejected';
111
114
  }
112
- const settle = (result: ReplyResult, late: boolean) => settleNewTask(client, outcome, result, late);
115
+ // Codex names its chat only when the run ends.
116
+ const settle = (result: ReplyResult, late: boolean) => {
117
+ if (result.ok && result.sessionId) linkStartedFromPhone(agent, result.sessionId, message.startedBy);
118
+ return settleNewTask(client, outcome, result, late);
119
+ };
113
120
  const early = await acceptWhenStarted(run, (result) => settle(result, true), ACCEPTANCE_WINDOW_MS, handle);
114
121
  if (early === "started") return "accepted";
115
122
  await settle(early, false);
@@ -191,3 +198,16 @@ export async function handleUserMessage(
191
198
  await settle(early, false);
192
199
  return early.ok || early.delivery === 'native' ? "accepted" : "rejected";
193
200
  }
201
+
202
+ /**
203
+ * A chat the phone started for another one ("Run in a sub-chat") is linked beneath it as soon as
204
+ * its provider names it, the way a run a chat started from its shell is: the phone then draws it
205
+ * in that chat's tree. The first link of a chat stands; a link to itself is ignored.
206
+ */
207
+ export function linkStartedFromPhone(agent: string, sessionId: string, parent: UserMessage["startedBy"]): void {
208
+ if (!parent || !lineageAgent(agent) || (parent.agent === agent && parent.sessionId === sessionId)) return;
209
+ try {
210
+ rememberStartedLinks([{ agent, sessionId, parent: { agent: parent.agent, sessionId: parent.sessionId },
211
+ source: "process", at: Date.now() }]);
212
+ } catch { /* The chat still runs; it is only drawn on its own. */ }
213
+ }
@@ -6,7 +6,11 @@ envelope, including period totals and authenticated room routing, while trimming
6
6
  only the recent event feed. `index.ts` is
7
7
  the public entry point. Named secret arguments remain redacted; attached `-p`
8
8
  values are redacted for password-taking commands rather than ordinary build,
9
- port and path options. Behavior tests live in `tests/`, with provider integration
9
+ port and path options. An MCP tool call or a skill carries `inputPreview`, what it was
10
+ asked in one line of at most 120 characters (`query: disk usage, limit: 5`): arguments read
11
+ in order and cut early, a long value at 60 characters, a list as its length, a nested object
12
+ elided, secrets redacted as in a command. The phone keeps it with each call, so Usage can
13
+ say what an agent asked a server for, not only how often. Behavior tests live in `tests/`, with provider integration
10
14
  tests in the root `tests/provider/` directory.
11
15
 
12
16
  License: this module is distributed under the GrantTap Commercial Source License
@@ -115,6 +115,51 @@ export function commandTextFromInput(input: unknown): string | null {
115
115
  return collapsed || null;
116
116
  }
117
117
 
118
+ export const MAX_INPUT_PREVIEW_LENGTH = 120;
119
+ const MAX_INPUT_VALUE_LENGTH = 60;
120
+
121
+ /** One argument's value, short: a long string is cut, a list says how long it is, a nested object is elided. */
122
+ function previewValue(value: unknown): string {
123
+ if (typeof value === "string") {
124
+ const flat = value.replace(/[\s\u0000-\u001f\u007f]+/g, " ").trim();
125
+ return flat.length > MAX_INPUT_VALUE_LENGTH ? `${flat.slice(0, MAX_INPUT_VALUE_LENGTH)}…` : flat;
126
+ }
127
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
128
+ if (value === null) return "null";
129
+ if (Array.isArray(value)) return value.length === 1 ? `[${previewValue(value[0])}]` : `[${value.length} items]`;
130
+ if (typeof value === "object") return "{…}";
131
+ return "";
132
+ }
133
+
134
+ /**
135
+ * What an MCP tool or a skill was asked, in one short line: `query: disk usage, host: web-1`.
136
+ * Arguments are read in order and cut early, so a call carrying a whole file costs nothing more;
137
+ * secrets come out as they do from a command (`redactSecrets`). Nothing for an empty call.
138
+ */
139
+ export function inputPreviewFromInput(input: unknown): string | null {
140
+ let raw: string;
141
+ if (typeof input === "string") {
142
+ raw = previewValue(input);
143
+ } else if (input && typeof input === "object" && !Array.isArray(input)) {
144
+ const parts: string[] = [];
145
+ let length = 0;
146
+ for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
147
+ if (length > MAX_INPUT_PREVIEW_LENGTH) break;
148
+ const shown = previewValue(value);
149
+ if (!shown) continue;
150
+ const part = `${key.slice(0, 40)}: ${shown}`;
151
+ parts.push(part);
152
+ length += part.length + 2;
153
+ }
154
+ raw = parts.join(", ");
155
+ } else {
156
+ raw = input === undefined ? "" : previewValue(input);
157
+ }
158
+ const clean = redactCommandSecrets(raw).replace(/[\s\u0000-\u001f\u007f]+/g, " ").trim();
159
+ if (!clean) return null;
160
+ return clean.length > MAX_INPUT_PREVIEW_LENGTH ? `${clean.slice(0, MAX_INPUT_PREVIEW_LENGTH - 1)}…` : clean;
161
+ }
162
+
118
163
  export function commandPreviewFromInput(input: unknown): string | null {
119
164
  const collapsed = commandTextFromInput(input);
120
165
  return collapsed ? collapsed.slice(0, MAX_COMMAND_PREVIEW_LENGTH) : null;
@@ -6,7 +6,7 @@ import type {
6
6
  ObservedCapability,
7
7
  RemoteCapabilityUsageEvent,
8
8
  } from "../../../../../packages/protocol/schema";
9
- import { commandPreviewFromInput, commandTextFromInput } from "./command-preview";
9
+ import { commandPreviewFromInput, commandTextFromInput, inputPreviewFromInput, MAX_INPUT_PREVIEW_LENGTH } from "./command-preview";
10
10
  import {
11
11
  clampTokens,
12
12
  estimateBaselineTokens,
@@ -43,6 +43,8 @@ export type CapabilityObservation = {
43
43
  skill?: string;
44
44
  cli?: true;
45
45
  commandPreview?: string;
46
+ /** What an MCP tool or a skill was asked, short and without secrets (`inputPreviewFromInput`). */
47
+ inputPreview?: string;
46
48
  estimatedContextTokens?: number;
47
49
  estimatedBaselineTokens?: number;
48
50
  durationMs?: number;
@@ -103,6 +105,7 @@ export function pendingCapabilityObservation(
103
105
  createdAt: pending.createdAt,
104
106
  outcome: "unknown",
105
107
  ...identity,
108
+ ...(identity.cli ? {} : { inputPreview: inputPreviewFromInput(pending.input) ?? undefined }),
106
109
  estimatedContextTokens: clampTokens(estimateTokens(pending.input)) || undefined,
107
110
  };
108
111
  }
@@ -145,6 +148,12 @@ export function observeCapability(
145
148
  };
146
149
  }
147
150
 
151
+ /** An observation's preview as the wire takes it: trimmed, at most its length, or nothing. */
152
+ function boundedInputPreview(value: string | undefined): string | undefined {
153
+ const clean = value?.trim();
154
+ return clean ? clean.slice(0, MAX_INPUT_PREVIEW_LENGTH) : undefined;
155
+ }
156
+
148
157
  function inferredOutcome(value: unknown): CapabilityOutcome {
149
158
  if (value && typeof value === "object" && !Array.isArray(value)) {
150
159
  const row = value as Record<string, unknown>;
@@ -224,6 +233,7 @@ export function toObservedCapability(
224
233
  name: (observation.mcpServer ?? observation.skill ?? commandName(kind === "cli" ? commandTextFromInput(observation.commandPreview) : undefined) ?? toolName).trim().slice(0, 160),
225
234
  toolName,
226
235
  commandPreview,
236
+ inputPreview: kind === "cli" ? undefined : boundedInputPreview(observation.inputPreview),
227
237
  estimatedContextTokens: observation.estimatedContextTokens,
228
238
  estimatedBaselineTokens: observation.estimatedBaselineTokens,
229
239
  durationMs: observation.durationMs,
@@ -272,6 +282,7 @@ export function toRemoteCapabilityUsageEvent(
272
282
  toolName: toolName.slice(0, 240),
273
283
  commandPreview:
274
284
  kind === "cli" ? commandPreviewFromInput(observation.commandPreview) ?? undefined : undefined,
285
+ inputPreview: kind === "cli" ? undefined : boundedInputPreview(observation.inputPreview),
275
286
  createdAt: observation.createdAt,
276
287
  estimatedContextTokens: observation.estimatedContextTokens,
277
288
  estimatedBaselineTokens: observation.estimatedBaselineTokens,
@@ -10,7 +10,7 @@ function richness(event: RemoteCapabilityUsageEvent): number {
10
10
  return (event.durationMs != null ? 4 : 0) + (event.outcome !== "unknown" ? 4 : 0) +
11
11
  (event.resource != null ? 3 : 0) +
12
12
  (event.estimatedBaselineTokens != null ? 2 : 0) +
13
- (event.commandPreview != null ? 1 : 0) +
13
+ (event.commandPreview != null ? 1 : 0) + (event.inputPreview != null ? 1 : 0) +
14
14
  (event.estimatedContextTokens ?? 0) / MAX_TOKEN_ESTIMATE;
15
15
  }
16
16
 
@@ -16,6 +16,13 @@ the phone decides how to show it. A short helper run in a folder made for it
16
16
  (see [helper runs](../helper-runs/README.md)) stays one of its chat's nested
17
17
  conversations in `childThreads`, not a chat with `startedBy`.
18
18
 
19
+ **Started from the phone** (`monitor/handlers/user-message.ts`). The phone can start a
20
+ new chat for another one ("Run in a sub-chat": a queued message handed to one or more other
21
+ agents in the same folder). Its `user.message` then carries `startedBy` naming that chat, and
22
+ the monitor writes the link (`source: "process"`) as soon as the provider names the new
23
+ chat, Codex at the end of its run. The phone draws it in that chat's tree like any run. A
24
+ computer before this ignores the field and the chat stands on its own.
25
+
19
26
  **What is a child** (`headless.ts`). Only a session started headless: `codex
20
27
  exec` (`originator: codex_exec` in its rollout), `claude -p`/`--print` or the
21
28
  SDK's stream-json input (`entrypoint: sdk-*` in its transcript), a headless Grok
@@ -22,7 +22,7 @@ live chats only. A commit from the phone makes the next catalog read the folder
22
22
 
23
23
  | Request | Fields | Answer |
24
24
  | --- | --- | --- |
25
- | `session.changes.query` | `sessionId`, `requestId`, `createdAt` | `session.changes.result`: `branch`, `detached`, `operation`, `files` (at most 200 of `{ path, status, from? }`: paths relative to the checkout root, `status` Git's two letters such as ` M`, `M `, `A `, `D `, `R `, `UU`, `??`; `from` for a rename), `total`, `truncated`, `treeToken` (64 hex), or `unavailable: true` |
25
+ | `session.changes.query` | `sessionId`, `requestId`, `worktree?`, `createdAt` | `session.changes.result`: `branch`, `detached`, `ahead`, `behind`, `operation`, `folder` (the listed checkout's root), `worktrees` (at most 100 of `{ path, branch?, detached?, head?, current?, locked? }`), `files` (at most 200 of `{ path, status, from? }`: paths relative to the checkout root, `status` Git's two letters such as ` M`, `M `, `A `, `D `, `R `, `UU`, `??`; `from` for a rename), `total`, `truncated`, `treeToken` (64 hex), or `unavailable: true` |
26
26
  | `session.commit` | `sessionId`, `requestId`, `message` (1–2000 characters), `paths` (1–200, as listed), `treeToken`, `confirmWhileWorking?`, `createdAt` | `session.commit.result`: `ok`, `commit` (the new HEAD), or `reason`: `changed`, `detached`, `operation`, `working`, `unavailable`, `failed` with Git's first line in `detail` |
27
27
 
28
28
  A commit is refused when the tree no longer gives the listing's `treeToken` (HEAD and status
@@ -33,6 +33,20 @@ not send `confirmWhileWorking: true`. Otherwise the paths not yet staged are add
33
33
  staged work stays staged and out of the commit. The repository's hooks run; a hook's refusal is
34
34
  `failed`. Nothing is pushed, and no option bypasses hooks or signing.
35
35
 
36
+ **Worktrees.** A listing names every checkout of the chat's repository from one `git worktree list
37
+ --porcelain -z`: the main one and each linked one, with its branch (or detached), the commit it has
38
+ out and whether it is locked; the chat's own is `current`. Agents often work in worktrees of their
39
+ own, so the chat's folder can show one change while the work sits beside it. `worktree` in the query,
40
+ an absolute path the listing named, lists that checkout instead: branch, upstream distance and files,
41
+ read-only, with no `treeToken`, so a commit stays with the chat's own folder. A path that is not one of
42
+ the repository's worktrees is answered `unavailable`. The schema is strict, so a computer before this
43
+ refuses the field: a phone sends it only to a computer whose listing had `worktrees`.
44
+
45
+ **The phone waits for these reads.** They go through the shared Git pool as `urgent`: ahead of the
46
+ queued catalog and working-tree readings, and into a third slot when both are busy. Before, a
47
+ listing waited behind every queued reading of every Mesh repository and folder; with slow folders
48
+ in the queue it came after the phone's ten seconds, which said "The computer did not answer."
49
+
36
50
  Both answers travel in the relay queue's control lane, like a picture's chunks, ahead of catalogs,
37
51
  Mesh snapshots and load reports. In 0.8.190 they waited among those replaceable snapshots: on a
38
52
  computer whose upload was backed up they reached the phone after it had stopped waiting, or were
@@ -24,7 +24,7 @@ function firstLine(output: string): string | undefined {
24
24
  export async function commitChosenPaths(session: SessionInfo, folder: string, request: SessionCommit,
25
25
  write: GitWrite = gitWrite): Promise<Outcome> {
26
26
  if (session.state === "working" && request.confirmWhileWorking !== true) return { ok: false, reason: "working" };
27
- const tree = await readTree(folder);
27
+ const tree = await readTree(folder, { urgent: true });
28
28
  if (!tree) return { ok: false, reason: "unavailable" };
29
29
  if (tree.detached) return { ok: false, reason: "detached" };
30
30
  if (tree.operation) return { ok: false, reason: "operation" };
@@ -1,4 +1,5 @@
1
1
  /** The phone's working-tree requests, answered only to the phone that asked, under the chat's key. */
2
+ import { realpathSync } from "node:fs";
2
3
  import type { RelayClient } from "../../../../packages/core/relay-client";
3
4
  import { SessionChangesResult, SessionCommitResult, type SessionChangesQuery, type SessionCommit,
4
5
  type SessionInfo } from "../../../../packages/protocol/schema";
@@ -6,19 +7,44 @@ import { sendSessionPayload } from "../host/session-keys";
6
7
  import { publishedSession } from "../session-catalog";
7
8
  import { commitChosenPaths } from "./commit";
8
9
  import { chatFolder, forgetFolder } from "./index";
9
- import { readTree } from "./status";
10
+ import { readTree, readWorktrees } from "./status";
10
11
 
11
12
  const MAX_LISTED = 200;
13
+ const MAX_WORKTREES = 100;
12
14
 
15
+ /**
16
+ * The chat's checkout, or another checkout of its repository the phone named (`worktree`), read for
17
+ * the phone, which waits: its Git reads go ahead of the background ones. Every checkout of the
18
+ * repository is listed with it, the chat's own marked `current`. Another checkout is listed
19
+ * read-only, without a `treeToken`, and only when it is one of the repository's worktrees.
20
+ */
13
21
  export async function listChanges(session: SessionInfo | undefined, query: SessionChangesQuery): Promise<SessionChangesResult> {
14
22
  const base = { type: "session.changes.result" as const, sessionId: query.sessionId, requestId: query.requestId, createdAt: Date.now() };
23
+ const none = SessionChangesResult.parse({ ...base, files: [], total: 0, truncated: false, unavailable: true });
15
24
  const folder = session && chatFolder(session);
16
- const tree = folder ? await readTree(folder) : undefined;
17
- if (!tree) return SessionChangesResult.parse({ ...base, files: [], total: 0, truncated: false, unavailable: true });
25
+ const own = folder ? await readTree(folder, { urgent: true }) : undefined;
26
+ if (!own) return none;
27
+ const worktrees = await readWorktrees(own.root, { urgent: true }) ?? [];
28
+ const named = query.worktree === undefined ? undefined : worktrees.find((tree) => samePath(tree.path, query.worktree!));
29
+ if (query.worktree !== undefined && !named) return none;
30
+ const tree = named && !samePath(named.path, own.root) ? await readTree(named.path, { urgent: true }) : own;
31
+ if (!tree) return none;
32
+ const listed = worktrees.slice(0, MAX_WORKTREES).map((checkout) => ({ path: checkout.path,
33
+ ...(checkout.branch ? { branch: checkout.branch.slice(0, 256) } : {}), ...(checkout.detached ? { detached: true } : {}),
34
+ ...(checkout.head ? { head: checkout.head } : {}), ...(samePath(checkout.path, own.root) ? { current: true } : {}),
35
+ ...(checkout.locked ? { locked: true } : {}) }));
18
36
  return SessionChangesResult.parse({ ...base, ...(tree.branch ? { branch: tree.branch.slice(0, 256) } : {}),
19
- ...(tree.detached ? { detached: true } : {}), ...(tree.operation ? { operation: tree.operation } : {}),
37
+ ...(tree.detached ? { detached: true } : {}), ...(tree.ahead !== undefined ? { ahead: tree.ahead } : {}),
38
+ ...(tree.behind !== undefined ? { behind: tree.behind } : {}), ...(tree.operation ? { operation: tree.operation } : {}),
39
+ folder: tree.root, ...(listed.length ? { worktrees: listed } : {}),
20
40
  files: tree.files.slice(0, MAX_LISTED), total: tree.files.length, truncated: tree.files.length > MAX_LISTED,
21
- treeToken: tree.token });
41
+ ...(tree === own ? { treeToken: tree.token } : {}) });
42
+ }
43
+
44
+ /** Git prints a worktree's path as it stored it; macOS may reach the same folder through /private or a symlink. */
45
+ function samePath(left: string, right: string): boolean {
46
+ if (left === right) return true;
47
+ try { return realpathSync(left) === realpathSync(right); } catch { return false; }
22
48
  }
23
49
 
24
50
  export async function commitChanges(session: SessionInfo | undefined, request: SessionCommit): Promise<SessionCommitResult> {
@@ -45,16 +45,20 @@ export function parseStatus(output: string): Pick<TreeReading, "branch" | "detac
45
45
  return { branch, detached, ahead, behind, files };
46
46
  }
47
47
 
48
- /** The checkout this folder is in and its status, or nothing when it is no checkout or Git did not answer. */
49
- export async function readTree(folder: string): Promise<TreeReading | undefined> {
48
+ /**
49
+ * The checkout this folder is in and its status, or nothing when it is no checkout or Git did not answer.
50
+ * `urgent` for a reading the phone waits for (`readRepositoryGit`).
51
+ */
52
+ export async function readTree(folder: string, options: { urgent?: boolean } = {}): Promise<TreeReading | undefined> {
50
53
  if (!isAbsolute(folder)) return undefined;
51
- const root = (await readRepositoryGit(folder, ["rev-parse", "--show-toplevel"]))?.trim();
54
+ const urgent = options.urgent === true;
55
+ const root = (await readRepositoryGit(folder, ["rev-parse", "--show-toplevel"], { urgent }))?.trim();
52
56
  if (!root) return undefined;
53
57
  const [status, gitDir, head] = await Promise.all([
54
58
  readRepositoryGit(root, ["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=normal"],
55
- { timeoutMs: 5_000, maxBuffer: 4 * 1024 * 1024 }),
56
- readRepositoryGit(root, ["rev-parse", "--absolute-git-dir"]),
57
- readRepositoryGit(root, ["rev-parse", "--verify", "--quiet", "HEAD"]),
59
+ { timeoutMs: 5_000, maxBuffer: 4 * 1024 * 1024, urgent }),
60
+ readRepositoryGit(root, ["rev-parse", "--absolute-git-dir"], { urgent }),
61
+ readRepositoryGit(root, ["rev-parse", "--verify", "--quiet", "HEAD"], { urgent }),
58
62
  ]);
59
63
  if (status === undefined) return undefined;
60
64
  const directory = gitDir?.trim();
@@ -62,3 +66,39 @@ export async function readTree(folder: string): Promise<TreeReading | undefined>
62
66
  const token = createHash("sha256").update(`${head?.trim() ?? ""}\0${status}`).digest("hex");
63
67
  return { root, ...parseStatus(status), ...(operation ? { operation } : {}), token };
64
68
  }
69
+
70
+ export type Worktree = { path: string; branch?: string; detached: boolean; head?: string; locked: boolean };
71
+
72
+ /** `git worktree list --porcelain -z`: one record per checkout, its attributes NUL-ended, an empty one between. */
73
+ export function parseWorktrees(output: string): Worktree[] {
74
+ const list: Worktree[] = [];
75
+ let current: Worktree | undefined;
76
+ for (const field of output.split("\0")) {
77
+ if (field.startsWith("worktree ")) {
78
+ current = { path: field.slice("worktree ".length), detached: false, locked: false };
79
+ list.push(current);
80
+ } else if (!current) {
81
+ continue;
82
+ } else if (field.startsWith("HEAD ")) {
83
+ const head = field.slice("HEAD ".length);
84
+ if (/^[a-f0-9]{7,64}$/.test(head) && !/^0+$/.test(head)) current.head = head;
85
+ } else if (field.startsWith("branch ")) {
86
+ current.branch = field.slice("branch ".length).replace(/^refs\/heads\//, "");
87
+ } else if (field === "detached") {
88
+ current.detached = true;
89
+ } else if (field === "locked" || field.startsWith("locked ")) {
90
+ current.locked = true;
91
+ } else if (field === "bare") {
92
+ list.pop();
93
+ current = undefined;
94
+ }
95
+ }
96
+ return list;
97
+ }
98
+
99
+ /** Every checkout of the repository this root belongs to, the main one first; nothing when Git did not answer. */
100
+ export async function readWorktrees(root: string, options: { urgent?: boolean } = {}): Promise<Worktree[] | undefined> {
101
+ const output = await readRepositoryGit(root, ["worktree", "list", "--porcelain", "-z"],
102
+ { timeoutMs: 5_000, urgent: options.urgent === true });
103
+ return output === undefined ? undefined : parseWorktrees(output);
104
+ }
@@ -18,7 +18,7 @@ keeps each phone response tied to the exact originating chat and prompt.
18
18
  Install the supported CLI on this computer, then run:
19
19
 
20
20
  ```bash
21
- npm install -g granttap-mcp@0.8.201
21
+ npm install -g granttap-mcp@0.8.202
22
22
  granttap setup
23
23
  granttap status
24
24
  ```
@@ -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.201\";\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.202\";\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.201";
10
+ const PACKAGE = "granttap-mcp@0.8.202";
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.201",
3
+ "version": "0.8.202",
4
4
  "description": "Approve, answer and steer Claude Code, Codex, Cursor and Grok Build from iPhone, iPad and Apple Watch: the local runtime, CLI and MCP server for GrantTap, a free App Store download.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -52,6 +52,8 @@ export const ObservedCapability = z.object({
52
52
  name: CapabilityName,
53
53
  toolName: z.string().min(1).max(240),
54
54
  commandPreview: z.string().trim().min(1).max(160).optional(),
55
+ /** What an MCP tool or a skill was asked: its arguments in one short line, secrets removed. */
56
+ inputPreview: z.string().trim().min(1).max(120).optional(),
55
57
  estimatedContextTokens: z.number().int().nonnegative().optional(),
56
58
  estimatedBaselineTokens: z.number().int().nonnegative().optional(),
57
59
  durationMs: z.number().int().nonnegative().optional(),
@@ -114,6 +116,7 @@ export const CapabilityUsageEvent = z.object({
114
116
  name: CapabilityName,
115
117
  toolName: z.string().min(1).max(240),
116
118
  commandPreview: z.string().trim().min(1).max(160).optional(),
119
+ inputPreview: z.string().trim().min(1).max(120).optional(),
117
120
  deepLinkTarget: CapabilityChatTarget.optional(),
118
121
  createdAt: z.number(),
119
122
  estimatedContextTokens: z.number().int().nonnegative().optional(),
@@ -61,6 +61,12 @@ export const UserMessage = z.object({
61
61
  skill: z.string().min(1).max(180).optional(),
62
62
  /** Project this new chat belongs to. Omitted on home compose and follow-ups. */
63
63
  projectId: z.string().trim().min(1).max(180).optional(),
64
+ /**
65
+ * A new chat the phone starts for another chat ("Run in a sub-chat"): the computer links it
66
+ * beneath that chat, as it links a run one chat started from its shell. Ignored on a follow-up.
67
+ */
68
+ startedBy: z.object({ agent: z.enum(["claude", "codex", "grok", "cursor"]),
69
+ sessionId: z.string().min(1).max(256) }).strict().optional(),
64
70
  model: z.string().min(1).max(120)
65
71
  .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).optional(),
66
72
  // Spelled out as the CLI spells them. An unknown value is refused here rather
@@ -22,17 +22,34 @@ const scope = { sessionId: z.string().min(1).max(512), requestId: z.string().min
22
22
  const TreeToken = z.string().regex(/^[a-f0-9]{64}$/);
23
23
  const RepoPath = z.string().min(1).max(4096);
24
24
 
25
- /** The phone asks for a chat's uncommitted changes, answered only to the phone that asked. */
25
+ /**
26
+ * The phone asks for a chat's uncommitted changes, answered only to the phone that asked. `worktree`,
27
+ * an absolute path a listing named among the repository's worktrees, asks for that checkout instead,
28
+ * read-only: its listing has no `treeToken`. A phone sends it only to a computer whose listing had
29
+ * `worktrees`; an older computer refuses the field.
30
+ */
26
31
  export const SessionChangesQuery = z.object({ type: z.literal('session.changes.query'), ...scope,
27
- createdAt: z.number().finite() }).strict();
32
+ worktree: RepoPath.optional(), createdAt: z.number().finite() }).strict();
28
33
  export type SessionChangesQuery = z.infer<typeof SessionChangesQuery>;
29
34
 
35
+ /**
36
+ * One checkout of the chat's repository, from `git worktree list`: the main one and each linked one.
37
+ * `current` marks the chat's own; `head` is the commit it has out.
38
+ */
39
+ export const SessionWorktree = z.object({ path: RepoPath, branch: z.string().min(1).max(256).optional(),
40
+ detached: z.boolean().optional(), head: z.string().regex(/^[a-f0-9]{7,64}$/).optional(),
41
+ current: z.boolean().optional(), locked: z.boolean().optional() }).strict();
42
+ export type SessionWorktree = z.infer<typeof SessionWorktree>;
43
+
30
44
  /**
31
45
  * Up to 200 changed paths, relative to the checkout's root, with Git's two status letters
32
46
  * (`XY` of `git status --porcelain`, e.g. ` M`, `A `, `??`, `R `); a rename names `from`.
47
+ * `folder` is the listed checkout's root; `worktrees`, at most 100, every checkout of its repository.
33
48
  */
34
49
  export const SessionChangesResult = z.object({ type: z.literal('session.changes.result'), ...scope,
35
50
  branch: z.string().min(1).max(256).optional(), detached: z.boolean().optional(),
51
+ ahead: z.number().int().nonnegative().optional(), behind: z.number().int().nonnegative().optional(),
52
+ folder: RepoPath.optional(), worktrees: z.array(SessionWorktree).max(100).optional(),
36
53
  operation: SessionWorkingTree.shape.operation,
37
54
  files: z.array(z.object({ path: RepoPath, status: z.string().regex(/^[ MADRCUT?!]{2}$/), from: RepoPath.optional() })
38
55
  .strict()).max(200),
@@ -18,7 +18,7 @@ export * from './messages/live-map';
18
18
  import { SessionWorkspaceQuery, SessionWorkspaceResult } from './messages/sessions/workspace';
19
19
  export { SessionWorkspaceQuery, SessionWorkspaceResult } from './messages/sessions/workspace';
20
20
  import { SessionChangesQuery, SessionChangesResult, SessionCommit, SessionCommitResult } from './messages/sessions/working-tree';
21
- export { SessionWorkingTree, SessionChangesQuery, SessionChangesResult, SessionCommit, SessionCommitResult } from './messages/sessions/working-tree';
21
+ export { SessionWorkingTree, SessionWorktree, SessionChangesQuery, SessionChangesResult, SessionCommit, SessionCommitResult } from './messages/sessions/working-tree';
22
22
  export { SessionImageQuery, SessionImageChunk } from './messages/session-images';
23
23
  import { ProviderHookTrust, ProviderHookTrustResult } from "./messages/provider-hooks";
24
24
  import { SignInRequest, SignInResult } from "./messages/sign-in";