granttap-mcp 0.8.168 → 0.8.170

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
@@ -583,7 +583,7 @@ trust.
583
583
 
584
584
  ## MCP contract
585
585
 
586
- `tools/list` returns exactly nine public tools:
586
+ `tools/list` returns exactly ten public tools:
587
587
 
588
588
  | Tool | Contract |
589
589
  | --- | --- |
@@ -595,6 +595,7 @@ trust.
595
595
  | `notify` | Send a non-blocking status update of at most 2,000 characters |
596
596
  | `ask_yes_no` | Ask a yes/no question and wait for the explicit answer |
597
597
  | `ask` | Ask an open question and wait for typed or spoken text |
598
+ | `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 |
598
599
  | `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 |
599
600
 
600
601
  MCP `connect` accepts no custom routing, replacement, or key-rotation input.
@@ -619,6 +620,35 @@ Provider-native approvals and mobile continuation require the matching local
619
620
  adapter. MCP registration alone is never reported as proof that an integration
620
621
  is ready.
621
622
 
623
+ ### Signing in from the phone
624
+
625
+ When a CLI or service needs a browser sign-in (`wrangler login`, `gh auth
626
+ login`, `vercel login`, an OAuth consent page, a device-code page), the browser
627
+ would open on the computer, where nobody may be sitting. An agent calls
628
+ `request_sign_in` with the page's `url`, a `service` name, an optional `reason`,
629
+ and, when the CLI waits for a redirect to `http://localhost:<port>/…`, that
630
+ port as `callbackPort`. The request appears as a card in the calling chat on
631
+ the phone and opens in a browser inside GrantTap.
632
+
633
+ A redirect to `localhost` ends on the phone, where the browser is. While the
634
+ sign-in is open the app listens on that same loopback port, reads the request
635
+ line of the redirect, and sends its path and query back in `signin.result`.
636
+ The computer then repeats that one request against its own loopback address:
637
+
638
+ - only `GET`, only to `127.0.0.1` or `::1`, only to the port the request declared;
639
+ - once per request, and only while the request waits and has not expired;
640
+ - the path and query are bounded printable ASCII starting with `/`, so they
641
+ cannot end a request line, add a header or name another host;
642
+ - a redirect in the CLI's answer is reported, never followed, and the answer's
643
+ headers and body are dropped: the tool returns the status code alone;
644
+ - a result is taken only from a phone the request was sealed for, in the same
645
+ pairing room and chat; a result for an unknown request is ignored.
646
+
647
+ Only `https` pages without a user name or password in the address are sent.
648
+ The address, the redirect's query and anything the person typed are never
649
+ logged and never returned to the agent. Phones and computers that do not know
650
+ `signin.request` or `signin.result` ignore them.
651
+
622
652
  ## What the runtime publishes
623
653
 
624
654
  The bounded encrypted protocol preserves:
package/SECURITY.md CHANGED
@@ -105,6 +105,14 @@ background services. The public MCP server can only connect an existing or new
105
105
  phone pairing, notify, and ask bounded questions; it cannot reconfigure the
106
106
  machine or select a custom relay.
107
107
 
108
+ `request_sign_in` sends an https page to the phone and may deliver one loopback
109
+ redirect back. That delivery is a single `GET` to `127.0.0.1` or `::1` on the
110
+ port the pending request declared, made once, only while the request waits, and
111
+ only for a result from a phone the request was sealed for. The path and query
112
+ are bounded printable ASCII starting with `/`; redirects are not followed and
113
+ no response header or body is returned or logged. The agent learns the outcome
114
+ and a status code, never a cookie, token, or the redirect's query.
115
+
108
116
  A Grok Bot endpoint is a separate scoped identity. Its one-time invite is
109
117
  created only on the iPhone, stored on the relay as ciphertext, redeemed only by
110
118
  the trusted `granttap mesh connect` CLI, and written to disk with `0600`
@@ -49,7 +49,7 @@ function canonical(value: unknown): unknown {
49
49
  export function grantTapToolName(rawToolName: unknown): string | undefined {
50
50
  const raw = String(rawToolName ?? "").trim();
51
51
  const tool = raw.includes("__") ? raw.split("__").at(-1)! : raw;
52
- return ["notify", "connect", "ask", "ask_yes_no", "offload_task"].includes(tool) ? tool : undefined;
52
+ return ["notify", "connect", "ask", "ask_yes_no", "offload_task", "request_sign_in"].includes(tool) ? tool : undefined;
53
53
  }
54
54
 
55
55
  export function meshCallKey(tool: string, args: unknown): string {
@@ -0,0 +1,84 @@
1
+ import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
2
+ import type { NativeUsageProvider } from "./projection";
3
+
4
+ /**
5
+ * What every GrantTap process on this computer shares: the last good readings, kept across restarts,
6
+ * and the time before which a provider must not be asked again. Numbers only, never a credential.
7
+ */
8
+ export type SharedUsage = { read: () => ProviderAccountUsage[]; write: (reports: ProviderAccountUsage[]) => void;
9
+ notBefore?: () => Record<string, number>; defer?: (provider: string, until: number) => void };
10
+
11
+ /**
12
+ * A provider limits how often its account may be read: Claude answers the fifth quick request with
13
+ * 429 and five minutes of refusals. Dozens of GrantTap processes run on one computer, so they share
14
+ * one read per provider every three minutes, wait as long as a refusal names, and otherwise back off.
15
+ */
16
+ const READ_EVERY_MS = 180_000;
17
+ /** How often one process looks at the shared state; the network is asked far less often. */
18
+ export const CHECK_EVERY_MS = 60_000;
19
+ const BACKOFF_MS = 60_000, BACKOFF_MAX_MS = 600_000, RETRY_AFTER_MAX_MS = 900_000;
20
+
21
+ /**
22
+ * A limit report with no windows whose id ends in ":signed-out": the provider is
23
+ * installed but its own login has lapsed. The wire format is unchanged, so older
24
+ * phones show no numbers and newer ones say why.
25
+ */
26
+ export const SIGNED_OUT_SUFFIX = ":signed-out";
27
+ export function signedOutUsage(provider: NativeUsageProvider, now: number): ProviderAccountUsage {
28
+ return { provider, limitId: `${provider}${SIGNED_OUT_SUFFIX}`, observedAt: now, windows: [] };
29
+ }
30
+ export function isSignedOutUsage(report: ProviderAccountUsage): boolean {
31
+ return report.windows.length === 0 && report.limitId.endsWith(SIGNED_OUT_SUFFIX);
32
+ }
33
+
34
+ /** The readings one process holds, kept in step with the other processes on the computer. */
35
+ export function createUsageMemory(saved: SharedUsage | undefined, clock: () => number, known: (provider: string) => boolean) {
36
+ const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
37
+ const pauses = new Map<NativeUsageProvider, number>(), failures = new Map<NativeUsageProvider, number>();
38
+ const notBefore = (provider: NativeUsageProvider) => {
39
+ let shared = -Infinity;
40
+ try { shared = Number(saved?.notBefore?.()[provider] ?? -Infinity); } catch { /* Only this process's pause is known. */ }
41
+ return Math.max(pauses.get(provider) ?? -Infinity, Number.isFinite(shared) ? shared : -Infinity);
42
+ };
43
+ const defer = (provider: NativeUsageProvider, until: number) => {
44
+ pauses.set(provider, until);
45
+ try { saved?.defer?.(provider, until); } catch { /* Best effort. */ }
46
+ };
47
+ const restore = () => {
48
+ try {
49
+ for (const report of saved?.read() ?? []) {
50
+ const held = reports.get(report.provider as NativeUsageProvider);
51
+ if (known(report.provider) && !isSignedOutUsage(report) && (held?.observedAt ?? -Infinity) < report.observedAt
52
+ && (!held || !isSignedOutUsage(held))) reports.set(report.provider as NativeUsageProvider, report);
53
+ }
54
+ } catch { /* A missing or damaged file only means nothing is remembered. */ }
55
+ };
56
+ restore();
57
+ return {
58
+ reports, restore,
59
+ remember(): void {
60
+ restore();
61
+ try { saved?.write([...reports.values()].filter(report => !isSignedOutUsage(report))); } catch { /* Best effort. */ }
62
+ },
63
+ /** Not while another process has just read it, or while the provider asked everyone to wait. */
64
+ due(provider: NativeUsageProvider, now: number): boolean {
65
+ const held = reports.get(provider);
66
+ return now >= notBefore(provider) && !(held && !isSignedOutUsage(held) && now - held.observedAt < READ_EVERY_MS);
67
+ },
68
+ claim(provider: NativeUsageProvider, now: number): void { defer(provider, now + READ_EVERY_MS); },
69
+ succeeded(provider: NativeUsageProvider): void { failures.delete(provider); },
70
+ /**
71
+ * A refused or failed request says nothing about the account: the last good reading stays. Every
72
+ * process waits as long as the provider asked, or twice as long after each failure in a row.
73
+ */
74
+ refused(provider: NativeUsageProvider, response?: Response): void {
75
+ const count = (failures.get(provider) ?? 0) + 1;
76
+ failures.set(provider, count);
77
+ const asked = Number(response?.headers.get("retry-after"));
78
+ defer(provider, clock() + (Number.isFinite(asked) && asked > 0 ? Math.min(asked * 1_000, RETRY_AFTER_MAX_MS)
79
+ : Math.min(BACKOFF_MS * 2 ** (count - 1), BACKOFF_MAX_MS)));
80
+ if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
81
+ restore();
82
+ },
83
+ };
84
+ }
@@ -1,5 +1,7 @@
1
1
  import type { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
2
2
  import { projectCursorPeriodUsage, projectNativeAccountUsage, type NativeUsageProvider } from "./projection";
3
+ import { CHECK_EVERY_MS, createUsageMemory, isSignedOutUsage, signedOutUsage, type SharedUsage } from "./memory";
4
+ export { isSignedOutUsage, SIGNED_OUT_SUFFIX, signedOutUsage } from "./memory";
3
5
 
4
6
  type Options = {
5
7
  credential: (provider: NativeUsageProvider) => Promise<string | undefined>;
@@ -7,16 +9,13 @@ type Options = {
7
9
  expired?: (provider: NativeUsageProvider) => Promise<boolean>;
8
10
  /** The login is live, but its access token waits for the provider's own CLI to renew it. */
9
11
  renewable?: (provider: NativeUsageProvider) => Promise<boolean>;
10
- /** The last good readings, kept across restarts. Numbers only, never a credential. */
11
- saved?: { read: () => ProviderAccountUsage[]; write: (reports: ProviderAccountUsage[]) => void };
12
+ saved?: SharedUsage;
12
13
  fetcher?: (url: string, init: RequestInit) => Promise<Response>;
13
14
  clock?: () => number;
14
15
  /** Told when a signed-in account's limits become unreadable or readable again; never given a credential. */
15
16
  report?: (provider: NativeUsageProvider, reason: string | undefined) => void;
16
17
  };
17
18
 
18
- /** A good reading is read again after two minutes; a failed read is tried again much sooner. */
19
- const FRESH_MS = 120_000, RETRY_MS = 20_000;
20
19
  /** How long the last good reading is still offered, with the time it was really read, while reads fail. */
21
20
  export const HELD_USAGE_MS = 24 * 3_600_000;
22
21
  const MARKER_MS = 300_000;
@@ -27,19 +26,6 @@ const requests = {
27
26
  grok: { url: "https://cli-chat-proxy.grok.com/v1/billing?format=credits", method: "GET" },
28
27
  } as const;
29
28
 
30
- /**
31
- * A limit report with no windows whose id ends in ":signed-out": the provider is
32
- * installed but its own login has lapsed. The wire format is unchanged, so older
33
- * phones show no numbers and newer ones say why.
34
- */
35
- export const SIGNED_OUT_SUFFIX = ":signed-out";
36
- export function signedOutUsage(provider: NativeUsageProvider, now: number): ProviderAccountUsage {
37
- return { provider, limitId: `${provider}${SIGNED_OUT_SUFFIX}`, observedAt: now, windows: [] };
38
- }
39
- export function isSignedOutUsage(report: ProviderAccountUsage): boolean {
40
- return report.windows.length === 0 && report.limitId.endsWith(SIGNED_OUT_SUFFIX);
41
- }
42
-
43
29
  async function boundedResponse(response: Response): Promise<unknown> {
44
30
  if (!response.ok || !response.body) return undefined;
45
31
  const reader = response.body.getReader();
@@ -61,22 +47,10 @@ async function boundedResponse(response: Response): Promise<unknown> {
61
47
  export function createNativeAccountUsageReader(options: Options) {
62
48
  const clock = options.clock ?? Date.now;
63
49
  const fetcher = options.fetcher ?? fetch;
64
- const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
50
+ const memory = createUsageMemory(options.saved, clock, provider => provider in requests);
51
+ const { reports, restore, remember } = memory;
65
52
  let pending: Promise<void> | undefined;
66
- let attemptedAt = -Infinity, failed = false;
67
- const restore = () => {
68
- try {
69
- for (const report of options.saved?.read() ?? []) {
70
- const held = reports.get(report.provider as NativeUsageProvider);
71
- if (report.provider in requests && !isSignedOutUsage(report) && (held?.observedAt ?? -Infinity) < report.observedAt
72
- && (!held || !isSignedOutUsage(held))) reports.set(report.provider as NativeUsageProvider, report);
73
- }
74
- } catch { /* A missing or damaged file only means nothing is remembered. */ }
75
- };
76
- const remember = () => {
77
- try { options.saved?.write([...reports.values()].filter(report => !isSignedOutUsage(report))); } catch { /* Best effort. */ }
78
- };
79
- restore();
53
+ let attemptedAt = -Infinity;
80
54
  // Missing limits used to leave no trace; one line per change of reason keeps the log readable.
81
55
  const reasons = new Map<NativeUsageProvider, string | undefined>();
82
56
  const note = (provider: NativeUsageProvider, reason: string | undefined) => {
@@ -85,13 +59,6 @@ export function createNativeAccountUsageReader(options: Options) {
85
59
  options.report?.(provider, reason);
86
60
  };
87
61
 
88
- /** A refused or failed request says nothing about the account: the last good reading stays, and the read is retried soon. */
89
- const unreadable = (provider: NativeUsageProvider) => {
90
- failed = true;
91
- if (isSignedOutUsage(reports.get(provider) ?? signedOutUsage(provider, 0))) reports.delete(provider);
92
- restore();
93
- };
94
-
95
62
  async function update(provider: NativeUsageProvider): Promise<void> {
96
63
  try {
97
64
  const token = await options.credential(provider);
@@ -107,6 +74,11 @@ export function createNativeAccountUsageReader(options: Options) {
107
74
  } else { reports.delete(provider); reasons.delete(provider); remember(); }
108
75
  return;
109
76
  }
77
+ restore();
78
+ const now = clock();
79
+ // Another process on this computer has just read it, or the provider asked everyone to wait.
80
+ if (!memory.due(provider, now)) return;
81
+ memory.claim(provider, now);
110
82
  const request = requests[provider];
111
83
  const response = await fetcher(request.url, {
112
84
  method: request.method, redirect: "error", signal: AbortSignal.timeout(8_000),
@@ -125,12 +97,12 @@ export function createNativeAccountUsageReader(options: Options) {
125
97
  });
126
98
  report = projectCursorPeriodUsage(await boundedResponse(legacy), clock());
127
99
  }
128
- if (report) { reports.set(provider, report); remember(); }
100
+ if (report) { memory.succeeded(provider); reports.set(provider, report); remember(); }
129
101
  else if (response.ok) reports.delete(provider);
130
- else unreadable(provider);
102
+ else memory.refused(provider, response);
131
103
  note(provider, report ? undefined : response.ok ? "unrecognized response" : `HTTP ${response.status}`);
132
104
  } catch (error) {
133
- unreadable(provider);
105
+ memory.refused(provider);
134
106
  note(provider, error instanceof Error ? error.name : "request failed");
135
107
  }
136
108
  }
@@ -146,8 +118,8 @@ export function createNativeAccountUsageReader(options: Options) {
146
118
  },
147
119
  refresh(): Promise<void> {
148
120
  if (pending) return pending;
149
- if (clock() - attemptedAt < (failed ? RETRY_MS : FRESH_MS)) return Promise.resolve();
150
- attemptedAt = clock(); failed = false;
121
+ if (clock() - attemptedAt < CHECK_EVERY_MS) return Promise.resolve();
122
+ attemptedAt = clock();
151
123
  pending = Promise.allSettled((Object.keys(requests) as NativeUsageProvider[]).map(update))
152
124
  .then(() => undefined).finally(() => { pending = undefined; });
153
125
  return pending;
@@ -5,6 +5,7 @@ import { ProviderAccountUsage } from "../../../../../packages/protocol/schema";
5
5
  import { configDir, writePrivateFile } from "../../config";
6
6
 
7
7
  const Saved = z.array(ProviderAccountUsage).max(8);
8
+ const Pauses = z.record(z.string().max(40), z.number().finite());
8
9
 
9
10
  /**
10
11
  * The last good account readings, shared by every GrantTap process on this computer and kept across
@@ -12,7 +13,16 @@ const Saved = z.array(ProviderAccountUsage).max(8);
12
13
  * The file holds percentages and reset times only.
13
14
  */
14
15
  export function savedNativeUsage(path = () => join(configDir(), "native-usage.json")) {
16
+ // Beside the readings: the time before which no process here may ask a provider again.
17
+ const schedule = () => path().replace(/\.json$/, "") + "-schedule.json";
18
+ const pauses = (): Record<string, number> => {
19
+ try { return Pauses.parse(JSON.parse(readFileSync(schedule(), "utf8"))); } catch { return {}; }
20
+ };
15
21
  return {
22
+ notBefore: pauses,
23
+ defer(provider: string, until: number): void {
24
+ try { writePrivateFile(schedule(), JSON.stringify(Pauses.parse({ ...pauses(), [provider]: until }))); } catch { /* Best effort. */ }
25
+ },
16
26
  read(): ProviderAccountUsage[] {
17
27
  try { return Saved.parse(JSON.parse(readFileSync(path(), "utf8"))); } catch { return []; }
18
28
  },
@@ -12,6 +12,10 @@ type TransferProvider = {
12
12
  };
13
13
  const interrupted = (): ReplyResult => ({ ok: false,
14
14
  error: 'The first transfer turn was interrupted. Inspect the destination provider before starting another execution.' });
15
+ /** A transport retry arrives within minutes; a message sent after this long is the person deliberately trying again. */
16
+ const RESTART_AFTER_MS = 10 * 60_000;
17
+ const interruptedUnopened = (): ReplyResult => ({ ok: false,
18
+ error: 'The first transfer turn was interrupted before the agent opened a chat. Send the message again after ten minutes to start it again.' });
15
19
 
16
20
  /** Prepared executions are visible immediately and start only with a person's first message. */
17
21
  export class PreparedTaskTransfers extends TransferPersistence {
@@ -49,7 +53,7 @@ export class PreparedTaskTransfers extends TransferPersistence {
49
53
  }
50
54
 
51
55
  async deliver(id: string, text: string, attachments: UserAttachment[], options: DeliveryOptions,
52
- provider: TransferProvider): Promise<ReplyResult | undefined> {
56
+ provider: TransferProvider, now = Date.now()): Promise<ReplyResult | undefined> {
53
57
  if (!/^transfer-[a-f0-9]{48}$/.test(id)) return undefined;
54
58
  let row = this.load(id);
55
59
  if (!row) return { ok: false, error: 'The prepared transfer is unavailable.' };
@@ -57,6 +61,19 @@ export class PreparedTaskTransfers extends TransferPersistence {
57
61
  const result = await provider.resume({ ...this.session(row), sessionId: row.nativeSessionId }, text, attachments, options);
58
62
  return result.ok ? { ...result, sessionId: id } : result;
59
63
  }
64
+ if (row.phase === 'uncertain') {
65
+ // The launch that owned this transfer is over, whoever ran it. It used to refuse every later message for good.
66
+ if (row.nativeSessionId) {
67
+ // The agent did open its chat: the person's next message continues it, and nothing is started twice.
68
+ const result = await provider.resume({ ...this.session(row), sessionId: row.nativeSessionId }, text, attachments, options);
69
+ if (!result.ok) return result;
70
+ this.update(id, current => current.phase === 'uncertain' ? { ...current, phase: 'active', updatedAt: Date.now() } : current);
71
+ return { ...result, sessionId: id };
72
+ }
73
+ if (now - row.updatedAt < RESTART_AFTER_MS) return interruptedUnopened();
74
+ row = this.update(id, current => current.phase === 'uncertain' && !current.nativeSessionId
75
+ ? { ...current, phase: 'prepared', ownerPid: undefined, updatedAt: Date.now() } : current);
76
+ }
60
77
  if (row.phase !== 'prepared') return interrupted();
61
78
  let ownsLaunch = false;
62
79
  try {
@@ -5,6 +5,7 @@ import { registerConnectionWidget } from "../mcp-tools/connect/widget";
5
5
  import { registerInteractionTools } from "../mcp-tools/interaction";
6
6
  import { registerMeshResource } from "../mcp-tools/mesh/resource";
7
7
  import { registerRoutingTool } from '../mcp-tools/routing';
8
+ import { registerSignInTool } from "../mcp-tools/sign-in";
8
9
  import { packageVersion } from "../status/package-version";
9
10
 
10
11
  export { askOpenQuestion, askYesNo, relay, resetRelay } from "../mcp-tools/connect/relay";
@@ -19,6 +20,7 @@ export function createGrantTapServer(): McpServer {
19
20
  });
20
21
  registerConnectTool(server);
21
22
  registerInteractionTools(server);
23
+ registerSignInTool(server);
22
24
  registerRoutingTool(server);
23
25
  registerMeshResource(server);
24
26
  registerConnectionWidget(server);
@@ -2,7 +2,7 @@
2
2
 
3
3
  The Personal MCP surface is an exact allowlist: `connection_status`, `connect`,
4
4
  `connect_with_passkey`, `reconnect`, `set_runtime_auto_update`, `notify`,
5
- `ask_yes_no`, `ask`, and `offload_task`. Context compilation belongs
5
+ `ask_yes_no`, `ask`, `request_sign_in`, and `offload_task`. Context compilation belongs
6
6
  inside Project Mesh, not as extra tools. `relay.ts` owns one shared encrypted relay connection
7
7
  and the durable question lifecycle. Machine setup, custom relay selection, and
8
8
  pairing reset remains an explicit CLI operation. The narrower `reconnect` MCP
@@ -33,6 +33,12 @@ call, and can never create invites, expand scope, change the relay, or reach
33
33
  License: this module is distributed under the GrantTap Commercial Source License
34
34
  in the repository-root `LICENSE` file.
35
35
 
36
+ `sign-in/` owns `request_sign_in`: `index.ts` registers the tool, `pending.ts`
37
+ binds one request to its id, room, recipients and chat and takes one result,
38
+ and `callback-replay.ts` delivers the browser's loopback redirect to the port
39
+ that request declared. A session's relay link is held while a sign-in waits.
40
+ Tests live in `sign-in/tests/`.
41
+
36
42
  The connection center lives in `../connection-center`. Status requests are
37
43
  read-only. Saved pairing, a connected relay socket, and recent encrypted phone
38
44
  activity are separate observations. Only explicit connect/reconnect requests
@@ -9,17 +9,32 @@ export function createIdleRelease(options: {
9
9
  idleMs: number;
10
10
  isLeader: () => boolean;
11
11
  release: () => void;
12
- }): { touch: () => void; cancel: () => void } {
12
+ }): { touch: () => void; cancel: () => void; hold: () => () => void } {
13
13
  let timer: NodeJS.Timeout | undefined;
14
+ let waits = 0;
14
15
  const cancel = () => { if (timer) clearTimeout(timer); timer = undefined; };
15
16
  const touch = () => {
16
17
  cancel();
17
18
  timer = setTimeout(() => {
18
19
  timer = undefined;
19
- if (options.isLeader()) { touch(); return; }
20
+ if (options.isLeader() || waits > 0) { touch(); return; }
20
21
  options.release();
21
22
  }, options.idleMs);
22
23
  timer.unref?.();
23
24
  };
24
- return { touch, cancel };
25
+ /**
26
+ * Someone is waiting for the phone on this link, for as long as it takes: a sign-in in a
27
+ * browser has no fixed length. The returned function ends that wait, once.
28
+ */
29
+ const hold = () => {
30
+ let held = true;
31
+ waits += 1;
32
+ return () => {
33
+ if (!held) return;
34
+ held = false;
35
+ waits -= 1;
36
+ if (waits === 0) touch();
37
+ };
38
+ };
39
+ return { touch, cancel, hold };
25
40
  }
@@ -77,6 +77,11 @@ export async function relay(): Promise<RelayClient | null> {
77
77
  }
78
78
  }
79
79
 
80
+ /** Keep this process's link for as long as a call waits on the phone; the returned function ends the wait. */
81
+ export function holdRelay(): () => void {
82
+ return idle.hold();
83
+ }
84
+
80
85
  export function resetRelay(): void {
81
86
  idle.cancel();
82
87
  stopEndpointPublisher();
@@ -138,9 +138,12 @@ export function interactionScope(
138
138
  text: string,
139
139
  operation?: string,
140
140
  ): TaskInteractionScope | undefined {
141
- const attributed = consumeAttributedCall(
142
- tool, { question: text, operationId: operation }, Date.now(), sessionFromEnvironment(),
143
- );
141
+ return attributedScope(tool, { question: text, operationId: operation });
142
+ }
143
+
144
+ /** The live chat whose provider hook saw exactly this call; nothing the model said decides it. */
145
+ export function attributedScope(tool: string, args: unknown): TaskInteractionScope | undefined {
146
+ const attributed = consumeAttributedCall(tool, args, Date.now(), sessionFromEnvironment());
144
147
  if (!attributed) return undefined;
145
148
  const live = liveExecutionScope(attributed.sessionId);
146
149
  if (!live || live.execution.provider !== attributed.provider) return undefined;
@@ -0,0 +1,76 @@
1
+ import { request } from "node:http";
2
+ import { SignInCallback } from "../../../../../packages/protocol/schema";
3
+
4
+ /**
5
+ * Hand the browser's redirect to the command that waits for it on this computer.
6
+ *
7
+ * A sign-in that ends at `http://localhost:<port>/…` ended on the phone, where
8
+ * the browser was; the command that started it listens here. This repeats that
9
+ * one request against the loopback address and nowhere else: the address is not
10
+ * an argument, the port is the one the request declared, the method is GET, a
11
+ * redirect in the answer is reported rather than followed, and the answer's
12
+ * headers and body are dropped. Only the status code leaves this function.
13
+ */
14
+ export type CallbackReplay =
15
+ | { delivered: true; status: number }
16
+ | { delivered: false; reason: "invalid" | "unreachable" };
17
+
18
+ /** A command may bind `localhost` to either family; both are this computer. */
19
+ const LOOPBACK = ["127.0.0.1", "::1"] as const;
20
+ const REPLAY_TIMEOUT_MS = 10_000;
21
+
22
+ type Attempt = { status: number } | "not_listening" | "failed";
23
+
24
+ export async function replayLoopbackCallback(
25
+ port: number,
26
+ callback: unknown,
27
+ timeoutMs = REPLAY_TIMEOUT_MS,
28
+ ): Promise<CallbackReplay> {
29
+ const target = SignInCallback.safeParse(callback);
30
+ if (!target.success || !Number.isInteger(port) || port < 1 || port > 65_535) {
31
+ return { delivered: false, reason: "invalid" };
32
+ }
33
+ const path = target.data.query ? `${target.data.path}?${target.data.query}` : target.data.path;
34
+ const deadline = Date.now() + timeoutMs;
35
+ for (const host of LOOPBACK) {
36
+ const attempt = await getOnce(host, port, path, Math.max(1, deadline - Date.now()));
37
+ if (attempt === "not_listening") continue;
38
+ if (attempt === "failed") break;
39
+ return { delivered: true, status: attempt.status };
40
+ }
41
+ return { delivered: false, reason: "unreachable" };
42
+ }
43
+
44
+ /**
45
+ * One GET. "Not listening" means no connection was made, so nothing was sent
46
+ * and the other loopback family may be tried; any failure after a connection
47
+ * ends the replay, because the command may already have the redirect.
48
+ */
49
+ function getOnce(host: string, port: number, path: string, timeoutMs: number): Promise<Attempt> {
50
+ return new Promise((resolve) => {
51
+ let connected = false;
52
+ let settled = false;
53
+ const finish = (attempt: Attempt) => {
54
+ if (settled) return;
55
+ settled = true;
56
+ clearTimeout(timer);
57
+ resolve(attempt);
58
+ };
59
+ const outgoing = request({
60
+ host, port, path, method: "GET", agent: false,
61
+ headers: { host: `localhost:${port}`, accept: "*/*" },
62
+ }, (response) => {
63
+ const status = response.statusCode ?? 0;
64
+ response.resume();
65
+ response.destroy();
66
+ finish({ status });
67
+ });
68
+ const timer = setTimeout(() => {
69
+ outgoing.destroy();
70
+ finish(connected ? "failed" : "not_listening");
71
+ }, timeoutMs);
72
+ outgoing.once("socket", (socket) => socket.once("connect", () => { connected = true; }));
73
+ outgoing.once("error", () => finish(connected ? "failed" : "not_listening"));
74
+ outgoing.end();
75
+ });
76
+ }
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { isSignInUrl } from "../../../../../packages/protocol/schema";
4
+ import { holdRelay, relay } from "../connect/relay";
5
+ import { answered, notPaired, refused, type ToolAnswer } from "../interaction/answers";
6
+ import { attributedScope } from "../interaction/publish";
7
+ import { requestSignIn, type SignInOutcome } from "./pending";
8
+
9
+ const TOOL = "request_sign_in";
10
+
11
+ /** Longer than a question: a sign-in is a password manager, a second factor and a consent page. */
12
+ const SIGN_IN_TIMEOUT_MS = Number(process.env.GRANTTAP_SIGN_IN_TIMEOUT_MS ?? 300_000);
13
+
14
+ const DESCRIPTION =
15
+ "Ask the person to sign in to a service on their phone, in a browser inside GrantTap, and wait for the outcome. "
16
+ + "Use this whenever a CLI or service needs the person to sign in through a browser (wrangler login, gh auth login, "
17
+ + "vercel login, an OAuth consent page, a device-code page): call it with the sign-in URL instead of opening a browser "
18
+ + "on this computer, where nobody may be sitting. When the CLI waits for a redirect to http://localhost:<port>/…, pass "
19
+ + "that port as callbackPort: the redirect the phone's browser receives is delivered once to that port on this "
20
+ + "computer. Returns completed (with the HTTP status the CLI answered the redirect with, when one was delivered), "
21
+ + "cancelled, or timed_out; a timeout is not a refusal, and completed without a delivered redirect means the person "
22
+ + "says they finished, so check the CLI. Never put passwords, tokens or codes in chat: the person enters them only on "
23
+ + "the sign-in page, and this tool never returns the page, its cookies or the redirect's contents.";
24
+
25
+ const input = {
26
+ url: z.string().trim().min(1).max(8_192).describe("The https sign-in page to open on the phone"),
27
+ service: z.string().trim().min(1).max(80).describe('A short name for the service, e.g. "Cloudflare"'),
28
+ callbackPort: z.number().int().min(1).max(65_535).optional().describe(
29
+ "The loopback port on this computer where the CLI waits for the OAuth redirect, e.g. 8976 for wrangler. "
30
+ + "Omit it for a device-code page.",
31
+ ),
32
+ reason: z.string().trim().min(1).max(300).optional().describe("One line on why the sign-in is needed"),
33
+ };
34
+
35
+ const output = {
36
+ status: z.enum(["completed", "cancelled", "timed_out"]).describe(
37
+ "completed: the person finished on the phone; cancelled: the person declined; timed_out: nobody answered in time",
38
+ ),
39
+ callback: z.enum(["relayed", "unreachable", "none"]).describe(
40
+ "relayed: the browser's redirect was delivered to callbackPort; unreachable: there was a redirect but nothing "
41
+ + "accepted it on callbackPort; none: no redirect was captured or no callbackPort was given",
42
+ ),
43
+ callbackStatus: z.number().int().nullable().describe("The HTTP status the CLI answered the delivered redirect with"),
44
+ };
45
+
46
+ export function signInText(outcome: SignInOutcome, callbackPort?: number): string {
47
+ if (outcome.status === "timed_out") return "no-answer (timeout): nobody completed the sign-in on the phone";
48
+ if (outcome.status === "cancelled") return "cancelled: the person declined the sign-in on the phone";
49
+ if (outcome.callback === "relayed") {
50
+ return `signed in: the browser's redirect was delivered to localhost:${callbackPort} (HTTP ${outcome.callbackStatus})`;
51
+ }
52
+ if (outcome.callback === "unreachable") {
53
+ return `signed in on the phone, but nothing accepted the redirect on localhost:${callbackPort}; `
54
+ + "the CLI may have stopped waiting, so start it again and ask once more";
55
+ }
56
+ return "the person finished the sign-in on the phone; no redirect was delivered, so check the CLI";
57
+ }
58
+
59
+ export function registerSignInTool(server: McpServer, options: { timeoutMs?: number } = {}): void {
60
+ const timeoutMs = options.timeoutMs ?? SIGN_IN_TIMEOUT_MS;
61
+ server.registerTool(
62
+ TOOL,
63
+ {
64
+ description: DESCRIPTION,
65
+ inputSchema: input,
66
+ outputSchema: output,
67
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
68
+ },
69
+ async ({ url, service, callbackPort, reason }): Promise<ToolAnswer> => {
70
+ // The address is not repeated in the refusal: a URL can carry what must not reach a transcript.
71
+ if (!isSignInUrl(url)) return refused("request_sign_in opens https pages only, without a user name or password in the address.");
72
+ const client = await relay();
73
+ if (!client) return notPaired();
74
+ const scope = attributedScope(TOOL, { url, service, callbackPort, reason });
75
+ const release = holdRelay();
76
+ try {
77
+ const outcome = await requestSignIn(client, { url, service, reason, callbackPort, sessionId: scope?.sessionId, timeoutMs });
78
+ return answered(signInText(outcome, callbackPort), outcome);
79
+ } catch {
80
+ return refused("The sign-in request could not be sent to the phone. Check the GrantTap connection and try again.");
81
+ } finally {
82
+ release();
83
+ }
84
+ },
85
+ );
86
+ }
@@ -0,0 +1,126 @@
1
+ import type { RelayClient } from "../../../../../packages/core/relay-client";
2
+ import { randomId } from "../../../../../packages/core/crypto";
3
+ import type { SignInRequest, SignInResult } from "../../../../../packages/protocol/schema";
4
+ import { sendSessionPayload } from "../../../../bridge/src/host/session-keys";
5
+ import { replayLoopbackCallback, type CallbackReplay } from "./callback-replay";
6
+
7
+ /**
8
+ * One sign-in the phone was asked for, and the only result that may answer it.
9
+ *
10
+ * The request is bound when it is sent: to its id, to the pairing room, to the
11
+ * phones it was sealed for, and to the chat that asked. A result is taken once,
12
+ * while the request still waits; the redirect it carries is delivered to the
13
+ * port this request declared and to no other.
14
+ */
15
+ export type PendingSignIn = {
16
+ id: string;
17
+ room: string;
18
+ sessionId?: string;
19
+ peers: ReadonlySet<string>;
20
+ callbackPort?: number;
21
+ expiresAt: number;
22
+ state: "waiting" | "settled";
23
+ };
24
+
25
+ export type SignInOutcome =
26
+ | { status: "completed"; callback: "relayed"; callbackStatus: number }
27
+ | { status: "completed"; callback: "unreachable" | "none"; callbackStatus: null }
28
+ | { status: "cancelled" | "timed_out"; callback: "none"; callbackStatus: null };
29
+
30
+ export type SignInAsk = {
31
+ url: string;
32
+ service: string;
33
+ reason?: string;
34
+ callbackPort?: number;
35
+ sessionId?: string;
36
+ timeoutMs: number;
37
+ };
38
+
39
+ type Replay = (port: number, callback: unknown) => Promise<CallbackReplay>;
40
+
41
+ export function answersSignIn(
42
+ pending: PendingSignIn,
43
+ result: SignInResult,
44
+ from: { room: string; peerPublicKey: string },
45
+ now: number,
46
+ ): boolean {
47
+ return pending.state === "waiting"
48
+ && result.id === pending.id
49
+ && from.room === pending.room
50
+ && pending.peers.has(from.peerPublicKey)
51
+ && result.sessionId === pending.sessionId
52
+ && now < pending.expiresAt;
53
+ }
54
+
55
+ /** Send the request to the phone and wait for the person, the redirect, or the end of the wait. */
56
+ export async function requestSignIn(
57
+ client: RelayClient,
58
+ ask: SignInAsk,
59
+ replay: Replay = replayLoopbackCallback,
60
+ ): Promise<SignInOutcome> {
61
+ const createdAt = Date.now();
62
+ const pending: PendingSignIn = {
63
+ id: randomId(12), room: client.room, sessionId: ask.sessionId, peers: new Set(client.authorizedPeers),
64
+ callbackPort: ask.callbackPort, expiresAt: createdAt + ask.timeoutMs, state: "waiting",
65
+ };
66
+ const wait = listen(client, pending, replay);
67
+ try {
68
+ const request: SignInRequest = {
69
+ type: "signin.request", id: pending.id, sessionId: ask.sessionId, url: ask.url, service: ask.service,
70
+ reason: ask.reason, callbackPort: ask.callbackPort, createdAt, expiresAt: pending.expiresAt,
71
+ };
72
+ const options = { ttlMs: ask.timeoutMs, wake: true };
73
+ if (ask.sessionId) await sendSessionPayload(client, request, ask.sessionId, "phone", options);
74
+ else await client.send(request, "phone", options);
75
+ } catch (error) {
76
+ wait.abandon();
77
+ throw error;
78
+ }
79
+ return wait.outcome;
80
+ }
81
+
82
+ function listen(client: RelayClient, pending: PendingSignIn, replay: Replay): {
83
+ outcome: Promise<SignInOutcome>;
84
+ abandon: () => void;
85
+ } {
86
+ let abandon = () => {};
87
+ const outcome = new Promise<SignInOutcome>((resolve) => {
88
+ let off = () => {};
89
+ const finish = (value: SignInOutcome) => {
90
+ pending.state = "settled";
91
+ clearTimeout(timer);
92
+ off();
93
+ resolve(value);
94
+ };
95
+ const quiet = { callback: "none", callbackStatus: null } as const;
96
+ const expire = () => { if (pending.state === "waiting") finish({ status: "timed_out", ...quiet }); };
97
+ const timer = setTimeout(expire, Math.max(0, pending.expiresAt - Date.now()));
98
+ abandon = expire;
99
+ off = client.onMessage(async (payload, peerPublicKey) => {
100
+ if (payload.type !== "signin.result" || payload.id !== pending.id || !pending.peers.has(peerPublicKey)) return false;
101
+ // A repeat of an answer already taken is consumed and dropped; anything else is not ours to take.
102
+ if (!answersSignIn(pending, payload, { room: client.room, peerPublicKey }, Date.now())) {
103
+ return pending.state === "settled";
104
+ }
105
+ // Taken before anything is awaited: a second copy of this result finds nothing waiting.
106
+ pending.state = "settled";
107
+ clearTimeout(timer);
108
+ if (payload.outcome === "cancelled") finish({ status: "cancelled", ...quiet });
109
+ else finish(await deliver(pending, payload, replay));
110
+ return true;
111
+ });
112
+ });
113
+ return { outcome, abandon };
114
+ }
115
+
116
+ async function deliver(pending: PendingSignIn, result: SignInResult, replay: Replay): Promise<SignInOutcome> {
117
+ if (!result.callback || pending.callbackPort === undefined) {
118
+ return { status: "completed", callback: "none", callbackStatus: null };
119
+ }
120
+ const replayed = await replay(pending.callbackPort, result.callback).catch((): CallbackReplay => (
121
+ { delivered: false, reason: "unreachable" }
122
+ ));
123
+ return replayed.delivered
124
+ ? { status: "completed", callback: "relayed", callbackStatus: replayed.status }
125
+ : { status: "completed", callback: "unreachable", callbackStatus: null };
126
+ }
@@ -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.168
13
+ npm install -g granttap-mcp@0.8.170
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.168\";\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.170\";\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.168";
10
+ const PACKAGE = "granttap-mcp@0.8.170";
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.168",
3
+ "version": "0.8.170",
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": {
@@ -62,6 +62,11 @@ export class RelayClient {
62
62
  catch { return false; }
63
63
  }
64
64
 
65
+ /** The peers a broadcast is sealed for right now, so its answer can be held to them. */
66
+ get authorizedPeers(): string[] {
67
+ return peerPublicKeys(this.cfg.peerPublicKey, this.cfg.extraPeerPublicKeys).filter(key => this.peerIsAllowed(key));
68
+ }
69
+
65
70
  connect(timeoutMs = 10_000): Promise<void> {
66
71
  if (this.isConnected) return Promise.resolve();
67
72
  if (this.connectPromise) return this.connectPromise;
@@ -26,6 +26,12 @@ to the requester. It is device-network pairing, not Project membership.
26
26
  `mesh/knowledge/write.ts` carries a Task-bound human decision or correction and a
27
27
  separate Engine-confirmed result.
28
28
 
29
+ `sign-in/index.ts` carries a browser sign-in done on the phone: `signin.request`
30
+ names an https page, the service, and optionally the loopback port a command
31
+ listens on; `signin.result` says `completed` or `cancelled` and may carry the
32
+ path and query of the loopback redirect, bounded and free of characters that
33
+ could end a request line. Tests live in `sign-in/tests/`.
34
+
29
35
  Tests are discoverable in `tests/core.test.ts` and the feature-level bridge and MCP suites.
30
36
 
31
37
  License: this module is distributed under the GrantTap Commercial Source License in the repository-root `LICENSE` file.
@@ -0,0 +1,60 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * A browser sign-in a service asked for, done on the phone.
5
+ *
6
+ * `signin.request` goes from the computer to the phone with the page to open.
7
+ * `signin.result` comes back with what the person did and, when the service
8
+ * redirected the browser to a loopback address, the path and query of that
9
+ * redirect, which the computer delivers to the command waiting for it. The
10
+ * redirect is the only thing that travels: no page, cookie or header does.
11
+ */
12
+ export const SIGN_IN_URL_MAX = 8_192;
13
+ export const SIGN_IN_CALLBACK_MAX = 4_096;
14
+
15
+ const SignInId = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
16
+ /** Printable ASCII without a space: nothing here can end a request line or start a header. */
17
+ const PATH = /^\/[\x21-\x22\x24-\x3e\x40-\x7e]*$/;
18
+ const QUERY = /^[\x21-\x22\x24-\x7e]*$/;
19
+
20
+ export function isSignInUrl(value: string): boolean {
21
+ if (value.length > SIGN_IN_URL_MAX) return false;
22
+ try {
23
+ const url = new URL(value);
24
+ return url.protocol === "https:" && url.hostname.length > 0 && !url.username && !url.password;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ export const SignInRequest = z.object({
31
+ type: z.literal("signin.request"),
32
+ id: SignInId,
33
+ /** The chat that asked; absent when the call could not be attributed to one. */
34
+ sessionId: z.string().trim().min(1).max(256).optional(),
35
+ url: z.string().max(SIGN_IN_URL_MAX).refine(isSignInUrl, "sign-in pages are https"),
36
+ service: z.string().trim().min(1).max(80),
37
+ reason: z.string().trim().min(1).max(300).optional(),
38
+ /** The loopback port a command on the computer listens on for the redirect. */
39
+ callbackPort: z.number().int().min(1).max(65_535).optional(),
40
+ createdAt: z.number().finite(),
41
+ expiresAt: z.number().finite(),
42
+ }).refine((request) => request.expiresAt > request.createdAt, { path: ["expiresAt"] });
43
+ export type SignInRequest = z.infer<typeof SignInRequest>;
44
+
45
+ /** Where the browser was redirected on the loopback address: a path and a query, no host. */
46
+ export const SignInCallback = z.object({
47
+ path: z.string().min(1).max(SIGN_IN_CALLBACK_MAX).regex(PATH),
48
+ query: z.string().max(SIGN_IN_CALLBACK_MAX).regex(QUERY).optional(),
49
+ }).refine((callback) => callback.path.length + (callback.query?.length ?? 0) < SIGN_IN_CALLBACK_MAX);
50
+ export type SignInCallback = z.infer<typeof SignInCallback>;
51
+
52
+ export const SignInResult = z.object({
53
+ type: z.literal("signin.result"),
54
+ id: SignInId,
55
+ sessionId: z.string().trim().min(1).max(256).optional(),
56
+ outcome: z.enum(["completed", "cancelled"]),
57
+ callback: SignInCallback.optional(),
58
+ createdAt: z.number().finite(),
59
+ });
60
+ export type SignInResult = z.infer<typeof SignInResult>;
@@ -15,6 +15,8 @@ import { SessionWorkspaceQuery, SessionWorkspaceResult } from './messages/sessio
15
15
  export { SessionWorkspaceQuery, SessionWorkspaceResult } from './messages/sessions/workspace';
16
16
  export { SessionImageQuery, SessionImageChunk } from './messages/session-images';
17
17
  import { ProviderHookTrust, ProviderHookTrustResult } from "./messages/provider-hooks";
18
+ import { SignInRequest, SignInResult } from "./messages/sign-in";
19
+ export * from "./messages/sign-in";
18
20
  import {
19
21
  ApprovalDecision,
20
22
  ApprovalRequest,
@@ -177,6 +179,8 @@ export const Payload = z.union([
177
179
  ToolUpdateResult,
178
180
  ProviderHookTrust,
179
181
  ProviderHookTrustResult,
182
+ SignInRequest,
183
+ SignInResult,
180
184
  MeshEvent,
181
185
  MeshClaimRelease,
182
186
  MeshClaimReleaseResult,