granttap-mcp 0.8.165 → 0.8.167
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 +42 -12
- package/apps/bridge/src/bin/cli/setup.ts +49 -12
- package/apps/bridge/src/engine/distribution/README.md +11 -0
- package/apps/bridge/src/engine/distribution/artifacts.ts +3 -4
- package/apps/bridge/src/engine/distribution/download.ts +2 -1
- package/apps/bridge/src/engine/distribution/index.ts +1 -1
- package/apps/bridge/src/engine/distribution/installation.ts +53 -6
- package/apps/bridge/src/engine/distribution/monitor/index.ts +23 -4
- package/apps/bridge/src/limit-continuation/README.md +16 -0
- package/apps/bridge/src/limit-continuation/index.ts +88 -0
- package/apps/bridge/src/limit-continuation/store.ts +27 -0
- package/apps/bridge/src/monitor/handlers/inbound.ts +2 -18
- package/apps/bridge/src/monitor/handlers/session-commands.ts +13 -0
- package/apps/bridge/src/monitor/support/heartbeat.ts +2 -2
- package/apps/bridge/src/monitor/support/runtime.ts +4 -1
- package/apps/bridge/src/provider-account-status/native-usage/credentials.ts +9 -1
- package/apps/bridge/src/provider-account-status/native-usage/index.ts +11 -1
- package/apps/bridge/src/session-catalog/observed-state.ts +5 -2
- package/apps/bridge/src/sessions/scan/claude/parse.ts +5 -3
- package/apps/bridge/src/sessions/scan/claude/shared.ts +3 -0
- package/apps/bridge/src/sessions/scan/claude/turn-state/index.ts +10 -1
- package/apps/bridge/src/sessions/scan/claude/turn-state/waits.ts +94 -0
- package/apps/bridge/src/task-dispatch/sender/store.ts +2 -2
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +5 -1
- package/bin/granttap-mcp.mjs +7 -1
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/package.json +1 -1
- package/packages/protocol/messages/sessions/index.ts +21 -0
- package/packages/protocol/schema.ts +4 -0
package/README.md
CHANGED
|
@@ -519,27 +519,54 @@ hooks, installs the background helper, removes a leftover user GrantTap MCP
|
|
|
519
519
|
entry when Cursor is present, and starts phone pairing when run in an
|
|
520
520
|
interactive terminal. It ends with one exact next action.
|
|
521
521
|
|
|
522
|
-
Setup also
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
is
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
522
|
+
Setup also prepares the separately distributed GrantTap Engine, which Graph,
|
|
523
|
+
Health and Project Governance need. It installs the release pinned for this
|
|
524
|
+
computer, verified by size and SHA-256, or uses the absolute executable given
|
|
525
|
+
with `--engine <path>`; that binary is checksummed here, because the checksum
|
|
526
|
+
is the only thing verified before it is launched. Pinned releases do not exist
|
|
527
|
+
for every computer: today only Apple silicon Macs (Engine 0.1.7) have one; Intel
|
|
528
|
+
Macs, Linux and Windows need an Engine supplied with `--engine` or in a standard
|
|
529
|
+
location. When no release exists for this one, or its download is
|
|
530
|
+
unavailable, setup keeps an Engine it declared earlier whose bytes still match
|
|
531
|
+
the saved checksum. Otherwise it searches the standard locations:
|
|
532
|
+
`engine/granttap-engine` in the GrantTap config directory,
|
|
533
|
+
`~/.local/bin/granttap-engine`, `/usr/local/bin/granttap-engine` and
|
|
534
|
+
`/opt/homebrew/bin/granttap-engine` (on Windows, `granttap-engine.exe` in the
|
|
535
|
+
config directory's `engine` folder and in the profile's
|
|
536
|
+
`AppData\Local\GrantTap\bin`).
|
|
537
|
+
|
|
538
|
+
Without any Engine, setup prints `Graph Engine unavailable on this computer:`
|
|
539
|
+
with the reason, reports `Project Governance No engine found`, and still
|
|
540
|
+
installs the hooks, the background helper and, for an installed agent, the
|
|
541
|
+
local MCP service, checks Codex hook trust, offers pairing in an interactive
|
|
542
|
+
terminal, prints the summary and its next action, and exits 0. Graph and
|
|
543
|
+
Health then report the Engine as unavailable; chats, questions and approvals
|
|
544
|
+
keep working. An `--engine` value that is missing or is not an absolute path to
|
|
545
|
+
an executable file stops setup before it changes anything.
|
|
546
|
+
|
|
547
|
+
A paired monitor prepares the pinned managed Engine in the background and
|
|
548
|
+
retries a failed download. If an update cannot be downloaded, it keeps the
|
|
549
|
+
verified Engine already declared and retries when the helper next starts; a
|
|
550
|
+
computer with no pinned release is not retried. Initial catalog delivery does
|
|
551
|
+
not wait for background preparation.
|
|
532
552
|
|
|
533
553
|
The normal CLI surface is intentionally small:
|
|
534
554
|
|
|
535
555
|
```text
|
|
536
556
|
granttap setup [--engine <path>]
|
|
557
|
+
granttap setup --help
|
|
537
558
|
granttap status [--json]
|
|
538
559
|
granttap connect [--relay <wss-url>]
|
|
539
560
|
granttap reset [--yes]
|
|
540
561
|
granttap mesh connect <one-time-invite>
|
|
562
|
+
granttap --version
|
|
541
563
|
```
|
|
542
564
|
|
|
565
|
+
`granttap --version` (also `-v` or `version`) prints the version of the
|
|
566
|
+
runtime the other commands run, including an automatically updated one, and
|
|
567
|
+
exits. `granttap setup --help` (or `-h`) prints setup usage without
|
|
568
|
+
running setup or writing any configuration.
|
|
569
|
+
|
|
543
570
|
`connect` reuses a valid pairing. If none exists, it creates a one-time QR.
|
|
544
571
|
Custom relays are CLI-only and explicit. `reset` moves active pairing files to
|
|
545
572
|
recoverable local backups before a new pairing can be created.
|
|
@@ -556,16 +583,19 @@ trust.
|
|
|
556
583
|
|
|
557
584
|
## MCP contract
|
|
558
585
|
|
|
559
|
-
`tools/list` returns exactly
|
|
586
|
+
`tools/list` returns exactly nine public tools:
|
|
560
587
|
|
|
561
588
|
| Tool | Contract |
|
|
562
589
|
| --- | --- |
|
|
590
|
+
| `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 |
|
|
563
591
|
| `connection_status` | Open the connection card and inspect saved pairing, QR expiry, relay observations, and provider readiness without changing pairing |
|
|
592
|
+
| `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 |
|
|
564
593
|
| `connect` | Reuse the existing production pairing or return a one-time QR |
|
|
565
594
|
| `reconnect` | After explicit confirmation, show a one-time QR to reconnect or add an independent controller device while retaining the current room |
|
|
566
595
|
| `notify` | Send a non-blocking status update of at most 2,000 characters |
|
|
567
596
|
| `ask_yes_no` | Ask a yes/no question and wait for the explicit answer |
|
|
568
597
|
| `ask` | Ask an open question and wait for typed or spoken text |
|
|
598
|
+
| `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 |
|
|
569
599
|
|
|
570
600
|
MCP `connect` accepts no custom routing, replacement, or key-rotation input.
|
|
571
601
|
`reconnect` is declared destructive and requires `confirmed: true`; the
|
|
@@ -574,7 +604,7 @@ Setup is CLI-only because it changes provider configuration and must not be
|
|
|
574
604
|
available to a model through prompt injection.
|
|
575
605
|
|
|
576
606
|
`notify` may alternatively carry one bounded task-scoped Mesh event. This does
|
|
577
|
-
not add
|
|
607
|
+
not add another MCP tool or grant any global setup capability, and it publishes
|
|
578
608
|
only for the execution whose provider hook attributed the call.
|
|
579
609
|
|
|
580
610
|
`notify`, `ask_yes_no`, and `ask` accept an `operationId`. A named call is
|
|
@@ -11,11 +11,42 @@ import {
|
|
|
11
11
|
type InstallResult,
|
|
12
12
|
} from "../../install";
|
|
13
13
|
import { createOneTimePairing, DEFAULT_RELAY, PAIRING_CODE_TTL_MINUTES } from "../../pairing";
|
|
14
|
-
import {
|
|
14
|
+
import { prepareSetupEngine, type SetupEngine } from "../../engine/distribution";
|
|
15
|
+
import { usableEngineBinary } from "../../engine/protocol/engine-declaration";
|
|
15
16
|
import { isMachineConfigured } from "../../../../mcp/src/status/pairing-status";
|
|
16
17
|
import { removeCursorUserGrantTap } from "../../../../mcp/src/cursor-config";
|
|
17
18
|
import { installHttpMcpService, waitForHttpMcpHealth } from "../../../../mcp/src/http-service";
|
|
18
19
|
|
|
20
|
+
const SETUP_USAGE = [
|
|
21
|
+
"Usage: granttap setup [--engine <path>]",
|
|
22
|
+
"",
|
|
23
|
+
"Detects local coding agents, installs or repairs their GrantTap hooks, the background",
|
|
24
|
+
"helper and the local MCP service, prepares the Graph Engine, and starts phone pairing",
|
|
25
|
+
"when run in an interactive terminal. Without an Engine, everything else is still set up.",
|
|
26
|
+
"",
|
|
27
|
+
"Options:",
|
|
28
|
+
" --engine <path> Use this absolute path to an executable as the Engine",
|
|
29
|
+
" -h, --help Show this help without changing anything",
|
|
30
|
+
"",
|
|
31
|
+
].join("\n");
|
|
32
|
+
|
|
33
|
+
/** Argument mistakes stop setup before it changes any provider configuration. */
|
|
34
|
+
function engineArgument(args: string[]): string | undefined {
|
|
35
|
+
const flag = args.indexOf("--engine");
|
|
36
|
+
if (flag < 0) return undefined;
|
|
37
|
+
const path = args[flag + 1];
|
|
38
|
+
if (!path) throw new Error("Choose an executable after --engine");
|
|
39
|
+
if (!usableEngineBinary(path)) throw new Error("The selected Engine must be an absolute path to an executable regular file");
|
|
40
|
+
return path;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function engineNote(engine: SetupEngine): string[] {
|
|
44
|
+
if (!engine.reason) return [];
|
|
45
|
+
return [engine.declaration
|
|
46
|
+
? `Engine not prepared: ${engine.reason}. Using the verified Engine already installed on this computer.`
|
|
47
|
+
: `Graph Engine unavailable on this computer: ${engine.reason}. Graph and Project Governance stay off.`];
|
|
48
|
+
}
|
|
49
|
+
|
|
19
50
|
function state(result: InstallResult): string {
|
|
20
51
|
return result.status === "manual" ? "Needs attention" : "Ready";
|
|
21
52
|
}
|
|
@@ -49,6 +80,7 @@ async function pairIfNeeded(): Promise<string | null> {
|
|
|
49
80
|
}
|
|
50
81
|
|
|
51
82
|
async function main(): Promise<void> {
|
|
83
|
+
const explicitEngine = engineArgument(process.argv.slice(2));
|
|
52
84
|
const before = {
|
|
53
85
|
cursor: inspectCursorIntegration(),
|
|
54
86
|
agents: inspectAgentIntegrations(),
|
|
@@ -57,10 +89,9 @@ async function main(): Promise<void> {
|
|
|
57
89
|
const claudeHook = installClaudeHook();
|
|
58
90
|
const codexHook = installCodexHook();
|
|
59
91
|
// Declared before the helper is written, so the LaunchAgent picks the engine
|
|
60
|
-
// up in the same run rather than needing a second one.
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const engine = await prepareEngine(engineFlag >= 0 ? process.argv[engineFlag + 1] : undefined);
|
|
92
|
+
// up in the same run rather than needing a second one. A missing Engine never
|
|
93
|
+
// stops the helper, HTTP service, Codex trust or pairing below.
|
|
94
|
+
const engine = await prepareSetupEngine(explicitEngine);
|
|
64
95
|
const helper = installMonitorHelper();
|
|
65
96
|
let httpService: InstallResult | null = null;
|
|
66
97
|
let cursorConfig: InstallResult | null = null;
|
|
@@ -102,8 +133,9 @@ async function main(): Promise<void> {
|
|
|
102
133
|
: "Not installed"}`,
|
|
103
134
|
// Governance is edited on the phone but cannot report until an engine is
|
|
104
135
|
// declared here, so say plainly which of the two is missing.
|
|
105
|
-
`Project Governance ${engine ? "Ready" : "No engine found"}`,
|
|
136
|
+
`Project Governance ${engine.declaration ? "Ready" : "No engine found"}`,
|
|
106
137
|
"",
|
|
138
|
+
...engineNote(engine),
|
|
107
139
|
paired && installed.has("codex")
|
|
108
140
|
? codexHooksReady(codexTrust.hooks) ? "Codex confirmed both GrantTap hooks are trusted and enabled."
|
|
109
141
|
: `Next: review GrantTap hooks in GrantTap Settings → This Mac → Codex hooks, or ${CODEX_TRUST_INSTRUCTION}`
|
|
@@ -116,9 +148,14 @@ async function main(): Promise<void> {
|
|
|
116
148
|
].join("\n"));
|
|
117
149
|
}
|
|
118
150
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
151
|
+
const args = process.argv.slice(2);
|
|
152
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
153
|
+
process.stdout.write(SETUP_USAGE);
|
|
154
|
+
} else {
|
|
155
|
+
void main().catch((error: unknown) => {
|
|
156
|
+
process.stderr.write(
|
|
157
|
+
`[granttap-mcp] setup failed: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
158
|
+
);
|
|
159
|
+
process.exitCode = 1;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -11,10 +11,21 @@ Failed downloads leave the previous declared Engine untouched. Setup and the
|
|
|
11
11
|
paired monitor save a new declaration only after verification.
|
|
12
12
|
Custom executable declarations remain available through `setup --engine`.
|
|
13
13
|
|
|
14
|
+
Setup never aborts because an Engine cannot be prepared. `prepareSetupEngine`
|
|
15
|
+
reports why: no pinned release for this platform, an unavailable or
|
|
16
|
+
unreachable download, or a configured executable that disappeared. It then
|
|
17
|
+
keeps a previously declared Engine only while its bytes match the saved
|
|
18
|
+
checksum, otherwise declares the first usable standard location. With neither,
|
|
19
|
+
setup reports Graph as unavailable and completes its remaining steps. An
|
|
20
|
+
explicit `--engine` executable is never replaced by another one.
|
|
21
|
+
|
|
14
22
|
Provider hooks never download an executable. The catalog can connect and replay
|
|
15
23
|
questions independently of Engine installation and repository analysis.
|
|
16
24
|
The monitor prepares a missing or outdated managed Engine in the background,
|
|
17
25
|
retries failed downloads and recovers verified bindings once it becomes healthy.
|
|
26
|
+
When an update cannot be downloaded, a declared Engine that still verifies stays
|
|
27
|
+
in use until the helper next starts. A platform with no pinned release and no
|
|
28
|
+
declared Engine leaves Graph unavailable without a retry loop.
|
|
18
29
|
Explicit disablement and custom executable declarations remain in force.
|
|
19
30
|
|
|
20
31
|
License: GrantTap Commercial Source License, in the repository-root `LICENSE`.
|
|
@@ -10,10 +10,9 @@ export type EngineArtifact = {
|
|
|
10
10
|
export const ENGINE_ARTIFACTS: readonly EngineArtifact[] = [
|
|
11
11
|
{ version: "0.1.7", platform: "darwin", arch: "arm64",
|
|
12
12
|
sha256: "bf7fcf3d08d78a437da21fcb88057d77840be4b22a0f7388f383059e685a76ef", bytes: 12201856 },
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
sha256: "1a6b227289b69459a64cd13078044960cf83bb858e6be1b70b1b38c950b00cc0", bytes: 14753312 },
|
|
13
|
+
// The 0.1.2 Intel Mac and Linux x64 builds are no longer published. Without a
|
|
14
|
+
// pin, setup reports Graph as unavailable and the helper does not retry a 404;
|
|
15
|
+
// an Engine already installed and verified on such a computer keeps working.
|
|
17
16
|
];
|
|
18
17
|
|
|
19
18
|
export function selectEngineArtifact(platform: string = process.platform, arch: string = process.arch): EngineArtifact | undefined {
|
|
@@ -5,7 +5,8 @@ import { engineArtifactName, type EngineArtifact } from "./artifacts";
|
|
|
5
5
|
export async function downloadEngine(artifact: EngineArtifact, fetcher: typeof fetch): Promise<Buffer> {
|
|
6
6
|
const url = `https://granttap.com/downloads/engine/${artifact.version}/${engineArtifactName(artifact)}`;
|
|
7
7
|
const response = await fetcher(url, { redirect: "error", credentials: "omit",
|
|
8
|
-
headers: { "Accept-Encoding": "identity" }, signal: AbortSignal.timeout(120_000) })
|
|
8
|
+
headers: { "Accept-Encoding": "identity" }, signal: AbortSignal.timeout(120_000) })
|
|
9
|
+
.catch(() => { throw new Error("Engine download could not reach granttap.com"); });
|
|
9
10
|
if (!response.ok || response.redirected) throw new Error("Verified Engine download is unavailable");
|
|
10
11
|
const length = response.headers.get("content-length");
|
|
11
12
|
if (length !== null && Number(length) !== artifact.bytes) throw new Error("Engine download size is invalid");
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { installEngineArtifact, prepareEngine } from "./installation";
|
|
1
|
+
export { installEngineArtifact, prepareEngine, prepareSetupEngine, type SetupEngine } from "./installation";
|
|
2
2
|
export { selectEngineArtifact, type EngineArtifact } from "./artifacts";
|
|
3
3
|
export { prepareMonitorEngine } from "./monitor";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { configDir, loadRuntimeConfig, saveRuntimeConfig } from "../../config";
|
|
3
|
-
import { declarationFor, type EngineDeclaration } from "../protocol/engine-declaration";
|
|
2
|
+
import { configDir, loadRuntimeConfig, saveRuntimeConfig, verifiableEngine } from "../../config";
|
|
3
|
+
import { declarationFor, declareEngine, defaultEngineLocations, type EngineDeclaration } from "../protocol/engine-declaration";
|
|
4
4
|
import { verifyEngineBinary } from "../runtime/engine-supervisor";
|
|
5
5
|
import { activateConfiguredEngine } from "../startup";
|
|
6
6
|
import { selectEngineArtifact, validateEngineArtifact, type EngineArtifact } from "./artifacts";
|
|
@@ -9,6 +9,12 @@ import { privateEngineDirectory, writeEngineExecutable } from "./storage";
|
|
|
9
9
|
|
|
10
10
|
export { selectEngineArtifact, type EngineArtifact } from "./artifacts";
|
|
11
11
|
|
|
12
|
+
/** Host selection and network are injectable so tests never depend on this computer's release. */
|
|
13
|
+
export type EnginePreparationOptions = { platform?: string; arch?: string; fetcher?: typeof fetch };
|
|
14
|
+
|
|
15
|
+
/** Setup's outcome: the declared Engine, if any, and why the pinned release could not be prepared. */
|
|
16
|
+
export type SetupEngine = { declaration: EngineDeclaration | null; reason?: string };
|
|
17
|
+
|
|
12
18
|
export async function installEngineArtifact(artifact: EngineArtifact, options: {
|
|
13
19
|
directory?: string; fetcher?: typeof fetch;
|
|
14
20
|
} = {}): Promise<EngineDeclaration> {
|
|
@@ -25,20 +31,61 @@ export async function installEngineArtifact(artifact: EngineArtifact, options: {
|
|
|
25
31
|
}
|
|
26
32
|
|
|
27
33
|
/** Setup only: downloads never run in a provider hook or delay the first catalog. */
|
|
28
|
-
export async function prepareEngine(explicitPath?: string): Promise<EngineDeclaration> {
|
|
34
|
+
export async function prepareEngine(explicitPath?: string, options: EnginePreparationOptions = {}): Promise<EngineDeclaration> {
|
|
29
35
|
const configured = loadRuntimeConfig();
|
|
30
36
|
const managedRoot = join(configDir(), "engine");
|
|
31
37
|
const customPath = explicitPath ?? (configured.enginePath && !configured.enginePath.startsWith(managedRoot + "/")
|
|
32
38
|
&& !configured.enginePath.startsWith(managedRoot + "\\") ? configured.enginePath : undefined);
|
|
33
39
|
const declaration = customPath ? declarationFor(customPath)
|
|
34
|
-
: await installEngineArtifact(selectEngineArtifact() ?? missingArtifact()
|
|
35
|
-
|
|
40
|
+
: await installEngineArtifact(selectEngineArtifact(options.platform, options.arch) ?? missingArtifact(),
|
|
41
|
+
{ fetcher: options.fetcher });
|
|
42
|
+
if (!declaration) {
|
|
43
|
+
throw new Error(explicitPath ? "The selected Engine must be an executable regular file"
|
|
44
|
+
: "The configured Engine is no longer an executable regular file");
|
|
45
|
+
}
|
|
36
46
|
saveRuntimeConfig({ enginePath: declaration.path, engineSha256: declaration.sha256 });
|
|
47
|
+
activate(declaration);
|
|
48
|
+
return declaration;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Setup never aborts for a missing Engine. When the pinned release cannot be
|
|
53
|
+
* prepared, a verified Engine already declared here is kept; otherwise the
|
|
54
|
+
* standard locations are searched. With neither, Graph stays unavailable.
|
|
55
|
+
* An explicitly selected executable is never replaced by another one.
|
|
56
|
+
*/
|
|
57
|
+
export async function prepareSetupEngine(explicitPath?: string, options: EnginePreparationOptions & {
|
|
58
|
+
locations?: string[];
|
|
59
|
+
} = {}): Promise<SetupEngine> {
|
|
60
|
+
try {
|
|
61
|
+
return { declaration: await prepareEngine(explicitPath, options) };
|
|
62
|
+
} catch (error) {
|
|
63
|
+
const reason = (error instanceof Error ? error.message : String(error)).replace(/\.+$/, "");
|
|
64
|
+
const kept = explicitPath ? null
|
|
65
|
+
: await installedEngine(options.locations ?? defaultEngineLocations()).catch(() => null);
|
|
66
|
+
if (kept) activate(kept);
|
|
67
|
+
return { declaration: kept, reason };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function installedEngine(locations: string[]): Promise<EngineDeclaration | null> {
|
|
72
|
+
const previous = verifiableEngine(loadRuntimeConfig());
|
|
73
|
+
// The saved checksum is the trust anchor for the previous Engine; it is never re-derived from changed bytes.
|
|
74
|
+
if (previous) {
|
|
75
|
+
try { return await verifyEngineBinary(previous.path, previous.sha256); } catch { /* Search the standard locations. */ }
|
|
76
|
+
}
|
|
77
|
+
for (const location of locations) {
|
|
78
|
+
const declaration = declareEngine(location);
|
|
79
|
+
if (declaration) return declaration;
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function activate(declaration: EngineDeclaration): void {
|
|
37
85
|
// Setup's preload may still contain the previous managed declaration.
|
|
38
86
|
process.env.GRANTTAP_ENGINE_BINARY = declaration.path;
|
|
39
87
|
process.env.GRANTTAP_ENGINE_SHA256 = declaration.sha256;
|
|
40
88
|
activateConfiguredEngine();
|
|
41
|
-
return declaration;
|
|
42
89
|
}
|
|
43
90
|
|
|
44
91
|
function missingArtifact(): never { throw new Error("No verified Engine release is available for this computer yet"); }
|
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { isAbsolute, join, relative, sep } from "node:path";
|
|
2
2
|
import { configDir, loadRuntimeConfig, saveRuntimeConfig, verifiableEngine } from "../../../config";
|
|
3
|
+
import type { EngineDeclaration } from "../../protocol/engine-declaration";
|
|
4
|
+
import { verifyEngineBinary } from "../../runtime/engine-supervisor";
|
|
3
5
|
import { activateConfiguredEngine } from "../../startup";
|
|
4
6
|
import { selectEngineArtifact, type EngineArtifact } from "../artifacts";
|
|
5
7
|
import { installEngineArtifact } from "../installation";
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
/** `artifact: null` stands for a platform with no pinned release. */
|
|
10
|
+
type MonitorPreparation = { env?: NodeJS.ProcessEnv; artifact?: EngineArtifact | null; fetcher?: typeof fetch };
|
|
8
11
|
|
|
9
12
|
/** Monitor only: repair the managed installation without touching custom declarations or policy. */
|
|
10
13
|
export async function prepareMonitorEngine(options: MonitorPreparation = {}): Promise<boolean> {
|
|
@@ -18,9 +21,21 @@ export async function prepareMonitorEngine(options: MonitorPreparation = {}): Pr
|
|
|
18
21
|
activateConfiguredEngine(env);
|
|
19
22
|
return true;
|
|
20
23
|
}
|
|
21
|
-
const artifact = options.artifact ?? selectEngineArtifact();
|
|
22
|
-
|
|
23
|
-
|
|
24
|
+
const artifact = options.artifact === null ? undefined : options.artifact ?? selectEngineArtifact();
|
|
25
|
+
let declaration: EngineDeclaration;
|
|
26
|
+
try {
|
|
27
|
+
if (!artifact) throw new Error("No verified Engine release is available for this computer yet");
|
|
28
|
+
declaration = await installEngineArtifact(artifact, { fetcher: options.fetcher });
|
|
29
|
+
} catch (error) {
|
|
30
|
+
// A failed update keeps the verified Engine already declared here; the next helper start retries.
|
|
31
|
+
if (configured && await verified(configured)) {
|
|
32
|
+
activateConfiguredEngine(env);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
// No release for this platform cannot change while this helper runs: Graph stays unavailable, not retried.
|
|
36
|
+
if (!artifact) return false;
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
24
39
|
const current = loadRuntimeConfig();
|
|
25
40
|
// A settings change made during an offline or slow download wins over this preparation.
|
|
26
41
|
if (disabledOrPartial(env)) return false;
|
|
@@ -34,6 +49,10 @@ export async function prepareMonitorEngine(options: MonitorPreparation = {}): Pr
|
|
|
34
49
|
return true;
|
|
35
50
|
}
|
|
36
51
|
|
|
52
|
+
async function verified(engine: { path: string; sha256: string }): Promise<boolean> {
|
|
53
|
+
try { await verifyEngineBinary(engine.path, engine.sha256); return true; } catch { return false; }
|
|
54
|
+
}
|
|
55
|
+
|
|
37
56
|
function disabledOrPartial(env: NodeJS.ProcessEnv): boolean {
|
|
38
57
|
const flag = env.GRANTTAP_ENGINE_ENABLED?.trim().toLowerCase();
|
|
39
58
|
if (flag !== undefined && flag !== "1" && flag !== "true") return true;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Limit continuation
|
|
2
|
+
|
|
3
|
+
Public entry: `index.ts`. When a Claude chat's last request was refused by its subscription
|
|
4
|
+
window, the published session carries `usageLimit { resetsAt, window, autoContinue }`. The
|
|
5
|
+
persistent monitor then queues one "continue" for that chat on the relay's durable task queue,
|
|
6
|
+
due a minute after the reset. The relay holds it while this computer sleeps or the phone is away,
|
|
7
|
+
and offers it back like any queued phone message: the chat receives it when it is idle.
|
|
8
|
+
|
|
9
|
+
The phone turns it off or on per chat with `session.autocontinue.set`. It is on by default.
|
|
10
|
+
Turning it off takes the queued copy back from the relay. A copy the relay still offers afterwards
|
|
11
|
+
is refused at delivery. The same happens when the chat went on by itself first. A limit that reset
|
|
12
|
+
more than an hour ago is treated as abandoned and is never woken by an update.
|
|
13
|
+
|
|
14
|
+
State lives in `limit-continuation.json` in the private config directory. Tests live in `tests/`.
|
|
15
|
+
|
|
16
|
+
License: GrantTap Commercial Source License; see the repository LICENSE.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CodingAgent, UserMessage, type SessionInfo } from '../../../../packages/protocol/schema';
|
|
3
|
+
import type { NativeQueueScope } from '../task-dispatch/sender/store';
|
|
4
|
+
import { readLimitContinuationState, writeLimitContinuationState, type ScheduledContinuation } from './store';
|
|
5
|
+
|
|
6
|
+
/** What the agent reads when the computer continues a chat its subscription had stopped. */
|
|
7
|
+
export const LIMIT_CONTINUE_PROMPT =
|
|
8
|
+
'GrantTap: the subscription limit that stopped this chat has reset. Continue the work from where you stopped.';
|
|
9
|
+
/** The provider's clock and ours differ a little; arriving just before the reset would hit the limit again. */
|
|
10
|
+
export const LIMIT_CONTINUE_GRACE_MS = 60_000;
|
|
11
|
+
/** A chat left at a limit that reset longer ago than this was abandoned, not waiting; an update must not wake it. */
|
|
12
|
+
const STALE_AFTER_RESET_MS = 3_600_000;
|
|
13
|
+
const PREFIX = 'limit-continue-';
|
|
14
|
+
|
|
15
|
+
export type ContinuationQueue = {
|
|
16
|
+
submit: (scope: NativeQueueScope, message: UserMessage, notBefore: number, createdAt: number) => Promise<unknown>;
|
|
17
|
+
cancel: (scope: NativeQueueScope, id: string) => Promise<unknown>;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
let registered: ContinuationQueue | undefined;
|
|
21
|
+
/** Only the persistent monitor owns the durable relay queue; session MCPs never schedule. */
|
|
22
|
+
export function registerLimitContinuationQueue(queue: ContinuationQueue | undefined): void { registered = queue; }
|
|
23
|
+
|
|
24
|
+
export function setAutoContinue(sessionId: string, enabled: boolean): void {
|
|
25
|
+
const state = readLimitContinuationState();
|
|
26
|
+
state.off = enabled ? state.off.filter(id => id !== sessionId) : [...state.off, sessionId];
|
|
27
|
+
writeLimitContinuationState(state);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The phone shows whether a limited chat will go on by itself; that is the default. */
|
|
31
|
+
export function annotateLimitContinuations(sessions: SessionInfo[]): SessionInfo[] {
|
|
32
|
+
if (!sessions.some(session => session.usageLimit)) return sessions;
|
|
33
|
+
const off = new Set(readLimitContinuationState().off);
|
|
34
|
+
return sessions.map(session => session.usageLimit
|
|
35
|
+
? { ...session, usageLimit: { ...session.usageLimit, autoContinue: !off.has(session.sessionId) } } : session);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function wanted(session: SessionInfo, off: Set<string>, now: number): boolean {
|
|
39
|
+
const limit = session.usageLimit;
|
|
40
|
+
return !!limit && session.agent === 'claude' && session.state === 'idle' && !off.has(session.sessionId)
|
|
41
|
+
&& limit.resetsAt > now - STALE_AFTER_RESET_MS;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function continuation(session: SessionInfo, now: number): { job: ScheduledContinuation; message: UserMessage } {
|
|
45
|
+
const resetsAt = session.usageLimit!.resetsAt;
|
|
46
|
+
const messageId = PREFIX + createHash('sha256').update(`${session.sessionId}:${resetsAt}`).digest('hex').slice(0, 40);
|
|
47
|
+
const scope: NativeQueueScope = { sessionId: session.sessionId, provider: CodingAgent.parse(session.agent),
|
|
48
|
+
...(session.projectId ? { projectId: session.projectId } : {}), ...(session.taskId ? { taskId: session.taskId } : {}) };
|
|
49
|
+
const cwd = session.worktree ?? session.cwd;
|
|
50
|
+
const message = UserMessage.parse({ type: 'user.message', messageId, sessionId: session.sessionId, agent: session.agent,
|
|
51
|
+
text: LIMIT_CONTINUE_PROMPT, createdAt: now, ...(cwd ? { cwd } : {}),
|
|
52
|
+
...(session.projectId ? { projectId: session.projectId } : {}) });
|
|
53
|
+
return { job: { resetsAt, messageId, scope }, message };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Puts one "continue" on the relay for every chat its subscription stopped, due when the limit resets,
|
|
58
|
+
* and takes it back when the chat went on by itself or the person turned it off. The relay holds it
|
|
59
|
+
* while this computer sleeps or the phone is away.
|
|
60
|
+
*/
|
|
61
|
+
export async function scheduleLimitContinuations(sessions: SessionInfo[], queue = registered, now = Date.now()): Promise<void> {
|
|
62
|
+
if (!queue) return;
|
|
63
|
+
const state = readLimitContinuationState(), off = new Set(state.off);
|
|
64
|
+
const byId = new Map(sessions.map(session => [session.sessionId, session]));
|
|
65
|
+
let changed = false;
|
|
66
|
+
for (const [sessionId, job] of Object.entries(state.scheduled)) {
|
|
67
|
+
const session = byId.get(sessionId);
|
|
68
|
+
const current = session?.usageLimit?.resetsAt === job.resetsAt && wanted(session, off, now);
|
|
69
|
+
const missing = !session && job.resetsAt > now - 7 * 86_400_000 && !off.has(sessionId);
|
|
70
|
+
if (current || missing) continue;
|
|
71
|
+
await queue.cancel(job.scope, job.messageId).catch(() => {});
|
|
72
|
+
delete state.scheduled[sessionId]; changed = true;
|
|
73
|
+
}
|
|
74
|
+
for (const session of sessions) {
|
|
75
|
+
if (!wanted(session, off, now) || state.scheduled[session.sessionId]) continue;
|
|
76
|
+
const { job, message } = continuation(session, now);
|
|
77
|
+
await queue.submit(job.scope, message, Math.max(now, job.resetsAt + LIMIT_CONTINUE_GRACE_MS), now);
|
|
78
|
+
state.scheduled[session.sessionId] = job; changed = true;
|
|
79
|
+
}
|
|
80
|
+
if (changed) writeLimitContinuationState(state);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A continuation the relay hands back after the person turned it off, or for a limit since lifted, is not delivered. */
|
|
84
|
+
export function limitContinuationUnwanted(message: UserMessage): boolean {
|
|
85
|
+
if (!message.messageId?.startsWith(PREFIX) || !message.sessionId) return false;
|
|
86
|
+
const state = readLimitContinuationState();
|
|
87
|
+
return state.off.includes(message.sessionId) || state.scheduled[message.sessionId]?.messageId !== message.messageId;
|
|
88
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { configDir, writePrivateFile } from '../config';
|
|
5
|
+
import { NativeQueueScope } from '../task-dispatch/sender/store';
|
|
6
|
+
|
|
7
|
+
const Scheduled = z.object({ resetsAt: z.number().int(), messageId: z.string().min(1).max(180), scope: NativeQueueScope }).strict();
|
|
8
|
+
export type ScheduledContinuation = z.infer<typeof Scheduled>;
|
|
9
|
+
const State = z.object({
|
|
10
|
+
/** Chats the person told not to continue by themselves. */
|
|
11
|
+
off: z.array(z.string().min(1).max(180)).max(4_096),
|
|
12
|
+
/** Continuations this computer put on the relay, by chat. */
|
|
13
|
+
scheduled: z.record(z.string(), Scheduled),
|
|
14
|
+
}).strict();
|
|
15
|
+
export type LimitContinuationState = z.infer<typeof State>;
|
|
16
|
+
|
|
17
|
+
const path = () => join(configDir(), 'limit-continuation.json');
|
|
18
|
+
|
|
19
|
+
export function readLimitContinuationState(): LimitContinuationState {
|
|
20
|
+
try { return State.parse(JSON.parse(readFileSync(path(), 'utf8'))); }
|
|
21
|
+
catch { return { off: [], scheduled: {} }; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function writeLimitContinuationState(state: LimitContinuationState): void {
|
|
25
|
+
writePrivateFile(path(), JSON.stringify(State.parse({ off: [...new Set(state.off)].sort().slice(-4_096),
|
|
26
|
+
scheduled: state.scheduled })));
|
|
27
|
+
}
|
|
@@ -26,14 +26,11 @@ import { recordPhoneSeen } from "../../pairing/presence";
|
|
|
26
26
|
import { handleProjectPolicySet } from "../../project-policy/runtime";
|
|
27
27
|
import { sendDeliveryReceipt } from "./receipts";
|
|
28
28
|
import {
|
|
29
|
-
|
|
29
|
+
applySessionSetting,
|
|
30
30
|
handleCompact,
|
|
31
31
|
handleConfigSet,
|
|
32
32
|
handleHostGrant,
|
|
33
|
-
handleMcpSet,
|
|
34
33
|
handleSessionControl,
|
|
35
|
-
handleShellSet,
|
|
36
|
-
handleSkillSet,
|
|
37
34
|
handleSubscription,
|
|
38
35
|
} from "./session-commands";
|
|
39
36
|
import { handleTaskCreate } from "./task-create";
|
|
@@ -102,20 +99,7 @@ export async function handleMonitorMessage(
|
|
|
102
99
|
} else if (payload.type === "sessions.history.query") {
|
|
103
100
|
await publishHistoryPage(client, payload);
|
|
104
101
|
return true;
|
|
105
|
-
} else if (payload
|
|
106
|
-
handleAccessSet(payload);
|
|
107
|
-
void publish(true).catch(() => {});
|
|
108
|
-
return true;
|
|
109
|
-
} else if (payload.type === "session.mcp.set") {
|
|
110
|
-
handleMcpSet(payload);
|
|
111
|
-
void publish(true).catch(() => {});
|
|
112
|
-
return true;
|
|
113
|
-
} else if (payload.type === "session.skill.set") {
|
|
114
|
-
handleSkillSet(payload);
|
|
115
|
-
void publish(true).catch(() => {});
|
|
116
|
-
return true;
|
|
117
|
-
} else if (payload.type === "session.shell.set") {
|
|
118
|
-
handleShellSet(payload);
|
|
102
|
+
} else if (applySessionSetting(payload)) {
|
|
119
103
|
void publish(true).catch(() => {});
|
|
120
104
|
return true;
|
|
121
105
|
} else if (payload.type === "session.compact") {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ConfigSet,
|
|
3
3
|
HostGrant,
|
|
4
|
+
Payload,
|
|
4
5
|
SessionAccessSet,
|
|
5
6
|
SessionCompact,
|
|
6
7
|
SessionControl,
|
|
@@ -10,6 +11,7 @@ import type {
|
|
|
10
11
|
SessionSubscription,
|
|
11
12
|
} from "../../../../../packages/protocol/schema";
|
|
12
13
|
import type { RelayClient } from "../../../../../packages/core/relay-client";
|
|
14
|
+
import { setAutoContinue } from "../../limit-continuation";
|
|
13
15
|
import {
|
|
14
16
|
applyConfigSet,
|
|
15
17
|
loadConfigCommandState,
|
|
@@ -45,6 +47,17 @@ export function handleShellSet(message: SessionShellSet): void {
|
|
|
45
47
|
setSessionShellAllowed(message.sessionId, message.allowed);
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
/** One chat's own settings from the phone; each is answered by republishing the catalog. */
|
|
51
|
+
export function applySessionSetting(payload: Payload): boolean {
|
|
52
|
+
if (payload.type === "session.access.set") handleAccessSet(payload);
|
|
53
|
+
else if (payload.type === "session.mcp.set") handleMcpSet(payload);
|
|
54
|
+
else if (payload.type === "session.skill.set") handleSkillSet(payload);
|
|
55
|
+
else if (payload.type === "session.shell.set") handleShellSet(payload);
|
|
56
|
+
else if (payload.type === "session.autocontinue.set") setAutoContinue(payload.sessionId, payload.enabled);
|
|
57
|
+
else return false;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
48
61
|
export { RESUME_PROMPT } from "../../task-control";
|
|
49
62
|
|
|
50
63
|
/** Phone and local desktop actions share the same computer-enforced implementation. */
|
|
@@ -21,7 +21,7 @@ export const HEARTBEAT_INTERVAL_MS = Number(
|
|
|
21
21
|
export async function publishHeartbeat(client: RelayClient): Promise<void> {
|
|
22
22
|
await client.send(
|
|
23
23
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
24
|
-
taskScheduleControls: true, taskActivityPreviews: true },
|
|
24
|
+
taskScheduleControls: true, taskActivityPreviews: true, limitAutoContinue: true },
|
|
25
25
|
"phone",
|
|
26
26
|
{ ttlMs: HEARTBEAT_INTERVAL_MS * 3, reliable: false },
|
|
27
27
|
);
|
|
@@ -40,7 +40,7 @@ export const HELD_HEARTBEAT_TTL_MS = 60_000;
|
|
|
40
40
|
export async function publishHeldHeartbeat(client: RelayClient): Promise<void> {
|
|
41
41
|
await client.send(
|
|
42
42
|
{ type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
|
|
43
|
-
taskScheduleControls: true, taskActivityPreviews: true },
|
|
43
|
+
taskScheduleControls: true, taskActivityPreviews: true, limitAutoContinue: true },
|
|
44
44
|
"phone",
|
|
45
45
|
{ ttlMs: HELD_HEARTBEAT_TTL_MS, reliable: true },
|
|
46
46
|
);
|
|
@@ -44,6 +44,7 @@ const HISTORY_INTERVAL_MS = 60_000;
|
|
|
44
44
|
const resumedHeads = new WeakSet<RelayClient>();
|
|
45
45
|
import { publishMonitorMeshes, stopMonitorMeshes } from "../mesh-publication";
|
|
46
46
|
import { publishMonitorCapabilities, stopMonitorCapabilities } from "../capability-publication";
|
|
47
|
+
import { annotateLimitContinuations, scheduleLimitContinuations } from "../../limit-continuation";
|
|
47
48
|
|
|
48
49
|
export type SessionMonitor = {
|
|
49
50
|
publish: () => Promise<void>;
|
|
@@ -158,7 +159,8 @@ async function publishMonitorTick(input: {
|
|
|
158
159
|
const includeHistory = forceHistory || (!initial && Date.now() - lastHistoryPublishedAt >= HISTORY_INTERVAL_MS);
|
|
159
160
|
const snapshot = await monitorSnapshot({ includeHistory, forceHistory, subscriptions, history });
|
|
160
161
|
if (!input.active()) return { lastHistoryPublishedAt };
|
|
161
|
-
const
|
|
162
|
+
const observed = decorateTaskOriginCatalog(refreshObservedCatalog(snapshot), client.room);
|
|
163
|
+
const status = { ...observed, sessions: annotateLimitContinuations(observed.sessions) };
|
|
162
164
|
rememberPublishedCatalog(client, status);
|
|
163
165
|
await client.send(status, "phone", { ttlMs: INTERVAL_MS * 24, reliable: false });
|
|
164
166
|
// Provider review is independent of task visibility; a hung hook RPC must
|
|
@@ -167,6 +169,7 @@ async function publishMonitorTick(input: {
|
|
|
167
169
|
if (includeHistory || initial) lastHistoryPublishedAt = Date.now();
|
|
168
170
|
loadLoop.updateStatus(status);
|
|
169
171
|
void refreshMcpLoad(status.sessions).catch(() => {});
|
|
172
|
+
void scheduleLimitContinuations(status.sessions).catch(() => {});
|
|
170
173
|
publishCatalogHeads(client, status, subscriptions, publishSessionEvents);
|
|
171
174
|
if (loadRuntimeConfig().meshEnabled) publishMonitorMeshes(client, status);
|
|
172
175
|
publishMonitorCapabilities(client, status, () => history(false));
|
|
@@ -20,6 +20,10 @@ export function readNativeKeychain(service: string, account?: string, run = exec
|
|
|
20
20
|
(error, stdout) => resolve(error ? undefined : stdout.trim() || undefined)));
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
async function exists(path: string): Promise<boolean> {
|
|
24
|
+
try { await stat(path); return true; } catch { return false; }
|
|
25
|
+
}
|
|
26
|
+
|
|
23
27
|
async function jsonFile(path: string): Promise<any> {
|
|
24
28
|
try {
|
|
25
29
|
if ((await stat(path)).size > 65_536) return undefined;
|
|
@@ -42,7 +46,9 @@ async function claudeCredentialRecord(options: Options = {}): Promise<any> {
|
|
|
42
46
|
const override = env.GRANTTAP_CLAUDE_DIR ?? env.NODVOX_CLAUDE_DIR ?? env.CLAUDE_CONFIG_DIR;
|
|
43
47
|
const saved = await jsonFile(join(override ?? join(home, ".claude"), ".credentials.json"));
|
|
44
48
|
if (claudeToken(saved, options.now ?? Date.now()) || platform !== "darwin" || override || !keychainAllowed) return saved;
|
|
45
|
-
|
|
49
|
+
// Only whether Claude Code is set up here matters; its settings outgrow any parse limit with saved
|
|
50
|
+
// permissions, and reading them used to skip the Keychain for a stale credentials file.
|
|
51
|
+
if (!await exists(join(home, ".claude", "settings.json"))) return saved;
|
|
46
52
|
try {
|
|
47
53
|
const raw = await keychain("Claude Code-credentials");
|
|
48
54
|
return raw ? JSON.parse(raw) : saved;
|
|
@@ -56,6 +62,8 @@ async function claudeCredentialRecord(options: Options = {}): Promise<any> {
|
|
|
56
62
|
export async function claudeCredentialState(options: Options = {}): Promise<"valid" | "expired" | "absent"> {
|
|
57
63
|
const record = await claudeCredentialRecord(options);
|
|
58
64
|
if (!record?.claudeAiOauth) return "absent";
|
|
65
|
+
// An access token lasts hours; Claude Code renews it with its refresh token on the next run.
|
|
66
|
+
if (token(record.claudeAiOauth.refreshToken)) return "valid";
|
|
59
67
|
return claudeToken(record, options.now ?? Date.now()) ? "valid" : "expired";
|
|
60
68
|
}
|
|
61
69
|
|
|
@@ -3,10 +3,20 @@ import type { ProviderAccountUsage } from "../../../../../packages/protocol/sche
|
|
|
3
3
|
import { readClaudeUsage } from "../claude-statusline";
|
|
4
4
|
import { claudeCredentialState, readNativeCredential } from "./credentials";
|
|
5
5
|
import { createNativeAccountUsageReader, isSignedOutUsage } from "./reader";
|
|
6
|
+
import { providerAuthentication } from "../../device-management/provider-command";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Claude Code's own CLI decides whether its login lapsed, whether or not the desktop app runs. A saved
|
|
10
|
+
* record alone said "expired" while phone messages kept running through the CLI.
|
|
11
|
+
*/
|
|
12
|
+
export async function claudeLoginLapsed(read = () => claudeCredentialState(),
|
|
13
|
+
cli = () => providerAuthentication("claude")): Promise<boolean> {
|
|
14
|
+
return await read() === "expired" && await cli() === "signed-out";
|
|
15
|
+
}
|
|
6
16
|
|
|
7
17
|
let scope = "";
|
|
8
18
|
const create = () => createNativeAccountUsageReader({ credential: readNativeCredential,
|
|
9
|
-
expired: async provider => provider === "claude" && await
|
|
19
|
+
expired: async provider => provider === "claude" && await claudeLoginLapsed(),
|
|
10
20
|
report: (provider, reason) => process.stderr.write(reason
|
|
11
21
|
? `[granttap-mcp] ${provider} account limits unavailable: ${reason}\n`
|
|
12
22
|
: `[granttap-mcp] ${provider} account limits readable again\n`) });
|
|
@@ -6,7 +6,7 @@ import {localTaskTransfers} from '../task-transfer';
|
|
|
6
6
|
import {nativeTranscriptSource} from '../sessions/native-source';
|
|
7
7
|
import {claudeLogPath} from '../sessions/scan/claude/shared';
|
|
8
8
|
import {previousNativeLines} from '../transcript-history/native-lines';
|
|
9
|
-
import {observeClaudeTurn,claudeTurnState,type ClaudeTurnClock} from '../sessions/scan/claude/turn-state';
|
|
9
|
+
import {observeClaudeTurn,claudeTurnState,claudeWaits,withClaudeWaits,type ClaudeTurnClock} from '../sessions/scan/claude/turn-state';
|
|
10
10
|
import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/scan/codex/turn-state';
|
|
11
11
|
import {ts} from '../sessions/support/common';
|
|
12
12
|
import {grokResumeActivity} from '../providers/grok-activity';
|
|
@@ -80,6 +80,9 @@ function observeNativeTail(input:SessionInfo,native:SessionInfo):SessionObservat
|
|
|
80
80
|
const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
|
|
81
81
|
const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
|
|
82
82
|
:clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
|
|
83
|
-
return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
|
|
83
|
+
if(native.agent!=='claude')return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
|
|
84
|
+
const waits=claudeWaits(clock!.claude,clock!.claude.turnEnded);
|
|
85
|
+
return {session:withClaudeWaits({...input,state,lastActivityAt:at},waits),
|
|
86
|
+
revision:`${revision}:${state}:${waits.backgroundTasks??0}:${waits.usageLimit?.resetsAt??0}`};
|
|
84
87
|
}catch{return;}
|
|
85
88
|
}
|
|
@@ -5,7 +5,7 @@ import type { ChildThreadInfo, SessionInfo } from "../../../../../../packages/pr
|
|
|
5
5
|
import { aggregateChildThreads, childTitle } from "../../support/child-threads";
|
|
6
6
|
import { plainPreview } from '../../plain-preview';
|
|
7
7
|
import { rememberCapabilityObservation } from "../../telemetry";
|
|
8
|
-
import { observeClaudeTurn } from "./turn-state";
|
|
8
|
+
import { claudeWaits, observeClaudeTurn, withClaudeWaits, type ClaudeTurnClock } from "./turn-state";
|
|
9
9
|
import { claudeContextReport } from "../../context-usage";
|
|
10
10
|
import { LIVE_MS, safeParse, stateFor, ts } from "../../support/common";
|
|
11
11
|
import { finishScan } from "../../cooperative-scan";
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
import { readTranscriptRows } from "./transcript-reading";
|
|
24
24
|
import { readClaudeChild } from "./child-reading";
|
|
25
25
|
|
|
26
|
-
type ClaudeParseState = {
|
|
26
|
+
type ClaudeParseState = ClaudeTurnClock & {
|
|
27
27
|
sessionId: string;
|
|
28
28
|
cwd?: string;
|
|
29
29
|
launchCwd?: string;
|
|
@@ -201,7 +201,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
201
201
|
recordedClaudeUsageIsCurrent(cached.observations)
|
|
202
202
|
) {
|
|
203
203
|
const session = {
|
|
204
|
-
...cached.session,
|
|
204
|
+
...withClaudeWaits(cached.session, claudeWaits(cached.waits ?? {}, cached.turnEnded)),
|
|
205
205
|
state:
|
|
206
206
|
cached.session.childThreads?.some((child) => stateFor(child.lastActivityAt) === "working")
|
|
207
207
|
? "working" as const
|
|
@@ -252,6 +252,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
252
252
|
tokensLastTurn: state.tokensLastTurn,
|
|
253
253
|
contextTokensUsed: state.contextTokensUsed,
|
|
254
254
|
...(state.contextUsage ? { contextUsage: state.contextUsage } : {}),
|
|
255
|
+
...claudeWaits(state, state.turnEnded),
|
|
255
256
|
};
|
|
256
257
|
const actualChildPaths =
|
|
257
258
|
state.sessionId === cachedSessionId ? childPaths : claudeChildLogPaths(file, state.sessionId);
|
|
@@ -268,6 +269,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
|
|
|
268
269
|
tokensSession: session.tokensSession,
|
|
269
270
|
observations,
|
|
270
271
|
turnEnded: state.turnEnded,
|
|
272
|
+
waits: { background: state.background, limit: state.limit },
|
|
271
273
|
// A chat that has gone quiet gives its memory back and is read again if it returns.
|
|
272
274
|
progress: Date.now() - session.lastActivityAt <= LIVE_MS ? progress : undefined,
|
|
273
275
|
});
|
|
@@ -2,6 +2,7 @@ import { diffPreviewFromInput, patchStatsByToolUse, sensitivePath, statsFromInpu
|
|
|
2
2
|
import { redactSecrets } from "../../telemetry/command-preview";
|
|
3
3
|
import { createChildSummary } from "./transcript-reading";
|
|
4
4
|
import { recordObservedWrite, writtenPaths } from "../../../mesh/observed/writes";
|
|
5
|
+
import type { ClaudeWaits } from "./turn-state/waits";
|
|
5
6
|
/**
|
|
6
7
|
* Claude Code session logs:
|
|
7
8
|
* ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl
|
|
@@ -56,6 +57,8 @@ export type CachedClaudeSummary = {
|
|
|
56
57
|
observations: CapabilityObservation[];
|
|
57
58
|
/** The chat's own last turn ended; recent writes no longer mean it is working. */
|
|
58
59
|
turnEnded?: boolean;
|
|
60
|
+
/** What the ended turn waits on besides the person; deadlines are read against the clock at use. */
|
|
61
|
+
waits?: ClaudeWaits;
|
|
59
62
|
/** Where a growing transcript was last read to; see `ClaudeParseProgress`. */
|
|
60
63
|
progress?: unknown;
|
|
61
64
|
};
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {stateFor} from '../../../support/common';
|
|
2
2
|
import type {SessionInfo} from '../../../../../../../packages/protocol/schema';
|
|
3
|
+
import {observeClaudeWaits, type ClaudeWaits} from './waits';
|
|
4
|
+
export {claudeWaits, type ClaudeWaits} from './waits';
|
|
3
5
|
|
|
4
|
-
export type ClaudeTurnClock = {turnEnded?: boolean};
|
|
6
|
+
export type ClaudeTurnClock = {turnEnded?: boolean} & ClaudeWaits;
|
|
5
7
|
const finished = new Set(['end_turn','stop_sequence','max_tokens']);
|
|
6
8
|
|
|
7
9
|
/** Root turn boundaries only; progress and sidechain records cannot resume a finished turn. */
|
|
@@ -9,9 +11,16 @@ export function observeClaudeTurn(row: any, clock: ClaudeTurnClock): void {
|
|
|
9
11
|
if (row.isSidechain === true) return;
|
|
10
12
|
if (row.type === 'user' || row.type === 'queue-operation') clock.turnEnded = false;
|
|
11
13
|
else if (row.type === 'assistant') clock.turnEnded = finished.has(row.message?.stop_reason);
|
|
14
|
+
observeClaudeWaits(row, clock);
|
|
12
15
|
}
|
|
13
16
|
|
|
14
17
|
export function claudeTurnState(clock: ClaudeTurnClock, lastActivityAt: number,
|
|
15
18
|
fallback: SessionInfo['state']): SessionInfo['state'] {
|
|
16
19
|
return clock.turnEnded === undefined ? fallback : clock.turnEnded ? 'idle' : stateFor(lastActivityAt);
|
|
17
20
|
}
|
|
21
|
+
|
|
22
|
+
/** Replaces what an older reading said the chat was waiting on with what this one says. */
|
|
23
|
+
export function withClaudeWaits(session: SessionInfo, waits: Pick<SessionInfo, 'backgroundTasks' | 'usageLimit'>): SessionInfo {
|
|
24
|
+
const {backgroundTasks: _background, usageLimit: _limit, ...rest} = session;
|
|
25
|
+
return {...rest, ...waits};
|
|
26
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {ts} from '../../../support/common';
|
|
2
|
+
|
|
3
|
+
/** Background work the chat started and has not heard back from, keyed by the launching tool call. */
|
|
4
|
+
export type ClaudeBackgroundWork = {taskId?: string; until: number};
|
|
5
|
+
/** The subscription window that refused the chat's last request. */
|
|
6
|
+
export type ClaudeUsageLimit = {resetsAt: number; window?: string};
|
|
7
|
+
export type ClaudeWaits = {background?: Record<string, ClaudeBackgroundWork>; limit?: ClaudeUsageLimit};
|
|
8
|
+
|
|
9
|
+
const BASH_DEFAULT_MS = 600_000, LONGEST_MS = 7_200_000, MAX_TRACKED = 32;
|
|
10
|
+
const BASH_LAUNCH = /^Command running in background with ID: ([\w-]+)/;
|
|
11
|
+
const AGENT_LAUNCH = /^Async agent launched/;
|
|
12
|
+
const AGENT_ID = /agentId: ([\w-]+)/;
|
|
13
|
+
const launched = new Map<string, {name: string; timeout?: number}>();
|
|
14
|
+
|
|
15
|
+
function text(content: unknown): string {
|
|
16
|
+
if (typeof content === 'string') return content;
|
|
17
|
+
if (!Array.isArray(content)) return '';
|
|
18
|
+
return content.map((block: any) => typeof block?.text === 'string' ? block.text
|
|
19
|
+
: typeof block?.content === 'string' ? block.content : '').join('\n');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Bash reports its own bound; an agent is given the longest a background command may run. */
|
|
23
|
+
function bound(name: string | undefined, timeout: unknown): number {
|
|
24
|
+
if (name !== 'Bash') return LONGEST_MS;
|
|
25
|
+
return typeof timeout === 'number' && timeout > 0 ? Math.min(timeout, LONGEST_MS) : BASH_DEFAULT_MS;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function noteLaunch(block: any, at: number, waits: ClaudeWaits): void {
|
|
29
|
+
const id = String(block.tool_use_id ?? ''), body = text(block.content);
|
|
30
|
+
if (!id || block.is_error === true) { if (id && waits.background) delete waits.background[id]; return; }
|
|
31
|
+
const bash = BASH_LAUNCH.exec(body), agent = AGENT_LAUNCH.test(body) ? AGENT_ID.exec(body) : null;
|
|
32
|
+
if (!bash && !AGENT_LAUNCH.test(body)) return;
|
|
33
|
+
const call = launched.get(id);
|
|
34
|
+
const background = waits.background ??= {};
|
|
35
|
+
background[id] = {taskId: bash?.[1] ?? agent?.[1], until: at + bound(call?.name ?? (bash ? 'Bash' : 'Agent'), call?.timeout)};
|
|
36
|
+
const ids = Object.keys(background);
|
|
37
|
+
for (const old of ids.slice(0, Math.max(0, ids.length - MAX_TRACKED))) delete background[old];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function noteNotifications(body: string, waits: ClaudeWaits): void {
|
|
41
|
+
if (!waits.background || !body.includes('<task-notification>')) return;
|
|
42
|
+
for (const note of body.split('<task-notification>').slice(1)) {
|
|
43
|
+
const status = /<status>([^<]+)<\/status>/.exec(note)?.[1];
|
|
44
|
+
if (status === 'running') continue;
|
|
45
|
+
const toolUse = /<tool-use-id>([^<]+)<\/tool-use-id>/.exec(note)?.[1];
|
|
46
|
+
const taskId = /<task-id>([^<]+)<\/task-id>/.exec(note)?.[1];
|
|
47
|
+
for (const [id, work] of Object.entries(waits.background)) {
|
|
48
|
+
if (id === toolUse || (taskId && work.taskId === taskId)) delete waits.background[id];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function usageLimit(row: any): ClaudeUsageLimit | undefined {
|
|
54
|
+
if (row.isApiErrorMessage !== true) return;
|
|
55
|
+
const quota = row.quotaLimits ?? row.apiErrorParams?.rate_limit_info;
|
|
56
|
+
const resetsAt = Number(quota?.resetsAt);
|
|
57
|
+
if (quota?.status !== 'rejected' || !Number.isFinite(resetsAt) || resetsAt <= 0) return;
|
|
58
|
+
const window = typeof quota.rateLimitType === 'string' ? quota.rateLimitType.slice(0, 40) : undefined;
|
|
59
|
+
return {resetsAt: resetsAt * 1_000, ...(window ? {window} : {})};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What a root Claude row says about the chat waiting on something other than the person:
|
|
64
|
+
* background work that will resume it, or a subscription window that refused it.
|
|
65
|
+
*/
|
|
66
|
+
export function observeClaudeWaits(row: any, waits: ClaudeWaits): void {
|
|
67
|
+
const at = ts(row.timestamp) || Date.now(), content = row.message?.content;
|
|
68
|
+
if (row.type === 'assistant') {
|
|
69
|
+
waits.limit = usageLimit(row);
|
|
70
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
71
|
+
if (block?.type === 'tool_use' && typeof block.id === 'string') {
|
|
72
|
+
launched.set(block.id, {name: String(block.name ?? ''), timeout: block.input?.timeout});
|
|
73
|
+
while (launched.size > 512) launched.delete(launched.keys().next().value!);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (row.type !== 'user' && row.type !== 'queue-operation') return;
|
|
79
|
+
const body = typeof row.content === 'string' ? row.content : text(content);
|
|
80
|
+
noteNotifications(body, waits);
|
|
81
|
+
if (row.type === 'user' && !body.includes('<task-notification>')) waits.limit = undefined;
|
|
82
|
+
for (const block of Array.isArray(content) ? content : []) {
|
|
83
|
+
if (block?.type === 'tool_result') noteLaunch(block, at, waits);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Published only once the turn has ended: before that the chat is simply working. */
|
|
88
|
+
export function claudeWaits(waits: ClaudeWaits, turnEnded: boolean | undefined, now = Date.now()):
|
|
89
|
+
{backgroundTasks?: number; usageLimit?: ClaudeUsageLimit} {
|
|
90
|
+
if (!turnEnded) return {};
|
|
91
|
+
const pending = Object.values(waits.background ?? {}).filter(work => work.until > now).length;
|
|
92
|
+
return {...(pending ? {backgroundTasks: Math.min(pending, 32)} : {}),
|
|
93
|
+
...(waits.limit ? {usageLimit: waits.limit} : {})};
|
|
94
|
+
}
|
|
@@ -6,8 +6,8 @@ import { withStoreLock } from '../../../../../packages/core/store-file-lock';
|
|
|
6
6
|
import { Envelope, CodingAgent } from '../../../../../packages/protocol/schema';
|
|
7
7
|
import { digest, readRequest, syncDirectory, writeRequest } from '../journal';
|
|
8
8
|
|
|
9
|
-
export const NativeQueueScope = z.object({ projectId: z.string().min(1).max(180),
|
|
10
|
-
taskId: z.string().min(1).max(180), sessionId: z.string().min(1).max(180), provider: CodingAgent }).strict();
|
|
9
|
+
export const NativeQueueScope = z.object({ projectId: z.string().min(1).max(180).optional(),
|
|
10
|
+
taskId: z.string().min(1).max(180).optional(), sessionId: z.string().min(1).max(180), provider: CodingAgent }).strict();
|
|
11
11
|
export type NativeQueueScope = z.infer<typeof NativeQueueScope>;
|
|
12
12
|
const Header = z.object({ id: z.string(), scope: NativeQueueScope, intent: z.string(),
|
|
13
13
|
createdAt: z.number().int(), notBefore: z.number().int(), expiresAt: z.number().int() }).strict();
|
|
@@ -13,6 +13,7 @@ import { NativeTaskQueueSender } from '../sender';
|
|
|
13
13
|
import { dispatchSessionObservation, newTaskOperationKey, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
|
|
14
14
|
import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
|
|
15
15
|
import { queueFailureReporter } from './failure-report';
|
|
16
|
+
import { limitContinuationUnwanted, registerLimitContinuationQueue } from '../../limit-continuation';
|
|
16
17
|
|
|
17
18
|
/** Only the persistent monitor advertises durable submission capability. */
|
|
18
19
|
export function startTaskDispatchMonitor(input: {
|
|
@@ -28,6 +29,8 @@ export function startTaskDispatchMonitor(input: {
|
|
|
28
29
|
const waitingSince = new Map<string, number>();
|
|
29
30
|
const sender = new NativeTaskQueueSender({ root: join(configDir(), 'native-task-queue'), config: input.config });
|
|
30
31
|
const peerAllowed = (peer: string) => peer === input.config.myPublicKey || input.peerAllowed(peer);
|
|
32
|
+
registerLimitContinuationQueue({ submit: (scope, message, notBefore, createdAt) => sender.submit(scope, message, notBefore, createdAt),
|
|
33
|
+
cancel: (scope, id) => sender.cancel(scope, id) });
|
|
31
34
|
const worker = new TaskDispatchWorker({ inbox, remote: input.remote ?? relayTaskJobRemote(input.config),
|
|
32
35
|
connected: () => !stopped && input.client.isConnected && input.isLeader(),
|
|
33
36
|
authorized: peerAllowed,
|
|
@@ -67,6 +70,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
67
70
|
return ready;
|
|
68
71
|
},
|
|
69
72
|
deliver: async (original, beforeStart, peer) => {
|
|
73
|
+
if (original.operation.type === 'user.message' && limitContinuationUnwanted(original.operation)) return 'rejected';
|
|
70
74
|
if (input.deliver) return input.deliver(original, beforeStart, peer);
|
|
71
75
|
const job = resolve(original, peer).job;
|
|
72
76
|
if (!job || job.operation.type === 'user.message.continue') return 'rejected';
|
|
@@ -101,5 +105,5 @@ export function startTaskDispatchMonitor(input: {
|
|
|
101
105
|
});
|
|
102
106
|
const interval = setInterval(tick, 2_000); interval.unref();
|
|
103
107
|
tick();
|
|
104
|
-
return () => { stopped = true; clearInterval(interval); off(); };
|
|
108
|
+
return () => { stopped = true; clearInterval(interval); off(); registerLimitContinuationQueue(undefined); };
|
|
105
109
|
}
|
package/bin/granttap-mcp.mjs
CHANGED
|
@@ -28,7 +28,7 @@ const usage = [
|
|
|
28
28
|
"GrantTap — personal control center for local coding agents",
|
|
29
29
|
"",
|
|
30
30
|
"Usage:",
|
|
31
|
-
" granttap setup
|
|
31
|
+
" granttap setup [--help] Detect agents and install or repair GrantTap",
|
|
32
32
|
" granttap status [--json] Show pairing, helper, and provider readiness",
|
|
33
33
|
" granttap connect [--relay <url>] Pair this computer with iPhone/Apple Watch",
|
|
34
34
|
" granttap phone add Show a QR for another controller phone",
|
|
@@ -36,6 +36,7 @@ const usage = [
|
|
|
36
36
|
" granttap reset [--yes] Reset this computer's phone pairing",
|
|
37
37
|
" granttap mesh connect <invite> Redeem a one-time Grok Bot Mesh invite",
|
|
38
38
|
" granttap restrictions check [dir] Check files against Mesh / .granttap restrictions",
|
|
39
|
+
" granttap --version Print the installed GrantTap version",
|
|
39
40
|
"",
|
|
40
41
|
"The legacy granttap-mcp command is an alias for granttap.",
|
|
41
42
|
"",
|
|
@@ -45,6 +46,11 @@ if (command === "help" || command === "--help" || command === "-h") {
|
|
|
45
46
|
process.stdout.write(usage);
|
|
46
47
|
process.exit(0);
|
|
47
48
|
}
|
|
49
|
+
if (command === "version" || command === "--version" || command === "-v") {
|
|
50
|
+
// The selected runtime is what every other command runs, so its version is the one reported.
|
|
51
|
+
process.stdout.write(`${runtimeVersion(root)}\n`);
|
|
52
|
+
process.exit(0);
|
|
53
|
+
}
|
|
48
54
|
|
|
49
55
|
let entry;
|
|
50
56
|
if (command === "mcp") {
|
package/cursor-plugin/README.md
CHANGED
|
@@ -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.
|
|
13
|
+
npm install -g granttap-mcp@0.8.167
|
|
14
14
|
granttap setup
|
|
15
15
|
granttap status
|
|
16
16
|
```
|
package/cursor-plugin/mcp.json
CHANGED
|
@@ -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.
|
|
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.167\";\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.
|
|
10
|
+
const PACKAGE = "granttap-mcp@0.8.167";
|
|
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
|
@@ -66,6 +66,14 @@ export const SessionSealed = z.object({
|
|
|
66
66
|
});
|
|
67
67
|
export type SessionSealed = z.infer<typeof SessionSealed>;
|
|
68
68
|
|
|
69
|
+
export const SessionUsageLimit = z.object({
|
|
70
|
+
resetsAt: z.number().int().positive(),
|
|
71
|
+
window: z.string().max(40).optional(),
|
|
72
|
+
/** Whether this computer will continue the chat itself once the limit resets; on unless turned off. */
|
|
73
|
+
autoContinue: z.boolean().optional(),
|
|
74
|
+
});
|
|
75
|
+
export type SessionUsageLimit = z.infer<typeof SessionUsageLimit>;
|
|
76
|
+
|
|
69
77
|
export const SessionInfo = z.object({
|
|
70
78
|
creationOrigins: z.array(z.object({ originId: z.string().min(1).max(180),
|
|
71
79
|
controllerPublicKey: z.string().min(1).max(180) }).strict()).max(32).optional(),
|
|
@@ -100,6 +108,10 @@ export const SessionInfo = z.object({
|
|
|
100
108
|
shellAllowed: z.boolean().optional(),
|
|
101
109
|
/** Held from the phone: its tool calls are refused until it is resumed. */
|
|
102
110
|
paused: z.boolean().optional(),
|
|
111
|
+
/** The turn ended while background work it started still runs; the chat resumes itself when it finishes. */
|
|
112
|
+
backgroundTasks: z.number().int().min(1).max(32).optional(),
|
|
113
|
+
/** The subscription refused the chat's last request until `resetsAt`. */
|
|
114
|
+
usageLimit: SessionUsageLimit.optional(),
|
|
103
115
|
});
|
|
104
116
|
export type SessionInfo = z.infer<typeof SessionInfo>;
|
|
105
117
|
|
|
@@ -224,6 +236,15 @@ export const SessionShellSet = z.object({
|
|
|
224
236
|
});
|
|
225
237
|
export type SessionShellSet = z.infer<typeof SessionShellSet>;
|
|
226
238
|
|
|
239
|
+
/** Whether a chat stopped by its subscription limit is continued automatically when the limit resets. */
|
|
240
|
+
export const SessionAutoContinueSet = z.object({
|
|
241
|
+
type: z.literal("session.autocontinue.set"),
|
|
242
|
+
sessionId: CapabilitySessionId,
|
|
243
|
+
enabled: z.boolean(),
|
|
244
|
+
createdAt: z.number(),
|
|
245
|
+
}).strict();
|
|
246
|
+
export type SessionAutoContinueSet = z.infer<typeof SessionAutoContinueSet>;
|
|
247
|
+
|
|
227
248
|
export const SessionCompact = z.object({
|
|
228
249
|
type: z.literal("session.compact"),
|
|
229
250
|
sessionId: z.string(),
|
|
@@ -74,6 +74,7 @@ import {
|
|
|
74
74
|
SessionMcpSet,
|
|
75
75
|
SessionSealed,
|
|
76
76
|
SessionShellSet,
|
|
77
|
+
SessionAutoContinueSet,
|
|
77
78
|
SessionSkillSet,
|
|
78
79
|
SessionsStatus,
|
|
79
80
|
SessionsHistoryQuery,
|
|
@@ -121,6 +122,8 @@ export const MachineHeartbeat = z.object({
|
|
|
121
122
|
createdAt: z.number().catch(() => Date.now()),
|
|
122
123
|
taskQueueImmediate: z.boolean().optional(),
|
|
123
124
|
taskScheduleControls: z.boolean().optional(),
|
|
125
|
+
/** Continues a chat stopped by its subscription limit when the limit resets, and takes `session.autocontinue.set`. */
|
|
126
|
+
limitAutoContinue: z.boolean().optional(),
|
|
124
127
|
taskActivityPreviews: z.boolean().optional(),
|
|
125
128
|
});
|
|
126
129
|
export type MachineHeartbeat = z.infer<typeof MachineHeartbeat>;
|
|
@@ -165,6 +168,7 @@ export const Payload = z.union([
|
|
|
165
168
|
SessionMcpSet,
|
|
166
169
|
SessionSkillSet,
|
|
167
170
|
SessionShellSet,
|
|
171
|
+
SessionAutoContinueSet,
|
|
168
172
|
SessionCompact,
|
|
169
173
|
SessionCompactResult,
|
|
170
174
|
SessionControl,
|