granttap-mcp 0.8.138 → 0.8.140
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/apps/bridge/src/bin/hooks/claude-hook.ts +8 -2
- package/apps/bridge/src/claude-open-questions/README.md +30 -0
- package/apps/bridge/src/claude-open-questions/index.ts +132 -0
- package/apps/bridge/src/claude-open-questions/observations.ts +102 -0
- package/apps/bridge/src/claude-open-questions/records.ts +59 -0
- package/apps/bridge/src/claude-open-questions/source.ts +33 -0
- package/apps/bridge/src/claude-questions/README.md +8 -3
- package/apps/bridge/src/claude-questions/index.ts +12 -0
- package/apps/bridge/src/monitor/handlers/inbound.ts +13 -5
- package/apps/bridge/src/monitor/support/leadership.ts +10 -2
- package/apps/bridge/src/monitor/support/runtime.ts +11 -3
- package/apps/bridge/src/sessions/native-capability-history/index.ts +3 -1
- package/apps/bridge/src/task-dispatch/README.md +5 -0
- package/apps/bridge/src/task-dispatch/worker/failure-report.ts +41 -0
- package/apps/bridge/src/task-dispatch/worker/monitor.ts +3 -11
- 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/core/task-job-http/README.md +5 -0
- package/packages/core/task-job-http/index.ts +14 -1
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
import { recordProjectDecision } from "../../policy/decision-log";
|
|
16
16
|
import { claudeToRequest, decisionToClaudeOutput, type HookInput } from "../../host/adapters";
|
|
17
17
|
import { isUnanswered, requestApproval } from "../../approvals";
|
|
18
|
-
import { questionRequest, claudeQuestionOutput } from "../../claude-questions";
|
|
18
|
+
import { questionRequest, claudeQuestionOutput, deferredQuestionOutput } from "../../claude-questions";
|
|
19
19
|
import { permitsProjectAskAutomation } from "../../task-automation";
|
|
20
20
|
import {
|
|
21
21
|
autoAcceptLevelFor,
|
|
@@ -166,9 +166,15 @@ async function answerNativeQuestion(input: HookInput, config: Parameters<typeof
|
|
|
166
166
|
if (!request) return; // Unsupported native shape keeps Claude's question UI.
|
|
167
167
|
request.projectId = scope.projectId;
|
|
168
168
|
request.policyRevision = scope.policy_revision;
|
|
169
|
+
// Claude stops this hook at its configured 120 s, so the phone window ends first.
|
|
169
170
|
const decision = await requestApproval(config, request, {
|
|
170
|
-
timeoutMs: Math.min(
|
|
171
|
+
timeoutMs: Math.min(100_000, Number(process.env.GRANTTAP_APPROVAL_TIMEOUT_MS ?? 100_000)),
|
|
171
172
|
});
|
|
173
|
+
const deferred = deferredQuestionOutput(decision);
|
|
174
|
+
if (deferred) {
|
|
175
|
+
process.stdout.write(JSON.stringify(deferred));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
172
178
|
if (isUnanswered(decision)) return;
|
|
173
179
|
const output = claudeQuestionOutput(input, decision, request);
|
|
174
180
|
if (output) process.stdout.write(JSON.stringify(output));
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Claude open questions
|
|
2
|
+
|
|
3
|
+
Public entry: `index.ts`. A Claude chat that stopped to wait for the person keeps
|
|
4
|
+
its question on paired phones until it is answered, however long that takes.
|
|
5
|
+
Two native shapes count: the desktop app's end-of-turn ask (`mcp__ccd_turn__wrap_up`
|
|
6
|
+
with `ask`) and an `AskUserQuestion` the hook handed to the phone after its
|
|
7
|
+
window passed (see `claude-questions`). Tool approvals stay quick: they live only
|
|
8
|
+
while the hook waits.
|
|
9
|
+
|
|
10
|
+
The question travels as an ordinary GrantTap question card. Reply buttons become
|
|
11
|
+
trailing `• ` choices; desktop app actions (commit, merge…) are left out because
|
|
12
|
+
only the desktop app runs them. The answer is an ordinary message to that chat,
|
|
13
|
+
so current provider, pause, Task policy, the queue and receipts all apply.
|
|
14
|
+
|
|
15
|
+
A later message from the person closes the card on every device: typed at the
|
|
16
|
+
computer, a desktop button, or the phone reply itself. A newer question replaces
|
|
17
|
+
an older one. Records survive monitor restart and are replayed when a phone
|
|
18
|
+
reconnects or refreshes; repeat scans do not notify again. A question first seen
|
|
19
|
+
more than an hour after it was asked arrives without a wake notification. After
|
|
20
|
+
seven days a card expires without claiming that it was answered.
|
|
21
|
+
|
|
22
|
+
Reads cost one stat for an unchanged chat. A changed one is read from its last
|
|
23
|
+
megabyte, and only small rows that can matter are parsed. Working chats are read
|
|
24
|
+
only to close a card they left open. History is included, because a chat can wait
|
|
25
|
+
long after it leaves the live list. Native transcripts are never modified.
|
|
26
|
+
|
|
27
|
+
Tests under `tests/` cover publication, replacement, desk answers, the deferred
|
|
28
|
+
`AskUserQuestion`, replies, quiet late discovery and expiry.
|
|
29
|
+
|
|
30
|
+
License: GrantTap Commercial Source License in the repository-root `LICENSE`.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { RelayClient } from '../../../../packages/core/relay-client';
|
|
2
|
+
import type { SessionInfo, UserMessage } from '../../../../packages/protocol/schema';
|
|
3
|
+
import { nativeTranscriptSource, restoreNativeTranscriptSource } from '../sessions';
|
|
4
|
+
import { handleInboundUserMessage } from '../monitor/message-delivery';
|
|
5
|
+
import { sendDeliveryReceipt } from '../monitor/handlers/receipts';
|
|
6
|
+
import { openQuestionClosed } from './observations';
|
|
7
|
+
import { forgetOpenQuestion, readOpenQuestion, saveOpenQuestion, storedOpenQuestions,
|
|
8
|
+
type OpenQuestionRecord } from './records';
|
|
9
|
+
import { observedOpenQuestion } from './source';
|
|
10
|
+
export { DEFERRED_QUESTION_REASON } from './observations';
|
|
11
|
+
|
|
12
|
+
/** The chat waits for the person however long it takes; a week bounds what the phone keeps. */
|
|
13
|
+
export const OPEN_QUESTION_RETENTION_MS = 7 * 24 * 60 * 60_000;
|
|
14
|
+
const QUIET_AFTER_MS = 60 * 60_000;
|
|
15
|
+
const expired = (record: OpenQuestionRecord) => Date.now() - record.createdAt > OPEN_QUESTION_RETENTION_MS;
|
|
16
|
+
|
|
17
|
+
/** A question a Claude chat stopped on stays on the phone until it is answered anywhere. */
|
|
18
|
+
export async function publishClaudeOpenQuestions(client: RelayClient, sessions: SessionInfo[],
|
|
19
|
+
options: { replay?: boolean; peerPublicKey?: string; requestId?: string } = {}): Promise<void> {
|
|
20
|
+
const chats = [...new Map(sessions.filter(s => s.agent === 'claude'
|
|
21
|
+
&& Date.now() - s.lastActivityAt <= OPEN_QUESTION_RETENTION_MS).map(s => [s.sessionId, s])).values()];
|
|
22
|
+
if (!chats.length) return;
|
|
23
|
+
const stored = (options.requestId
|
|
24
|
+
? [readOpenQuestion(options.requestId)].filter((record): record is OpenQuestionRecord => !!record)
|
|
25
|
+
: storedOpenQuestions()).filter(record => {
|
|
26
|
+
// Even a chat that left every list cannot keep its records forever.
|
|
27
|
+
if (Date.now() - record.createdAt <= 2 * OPEN_QUESTION_RETENTION_MS) return true;
|
|
28
|
+
forgetOpenQuestion(record.requestId);
|
|
29
|
+
return false;
|
|
30
|
+
});
|
|
31
|
+
for (const session of chats) {
|
|
32
|
+
// History can hold hundreds of chats; let relay traffic through between them.
|
|
33
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
34
|
+
const records = stored.filter(q => q.room === client.room && q.sessionId === session.sessionId);
|
|
35
|
+
// A working chat is not stopped on a question; read it only to close one it left open.
|
|
36
|
+
if (session.state === 'working' && !records.some(q => !q.resolvedSent)) continue;
|
|
37
|
+
const path = nativeTranscriptSource(session);
|
|
38
|
+
if (!path) continue;
|
|
39
|
+
let observed;
|
|
40
|
+
try { observed = observedOpenQuestion(session.sessionId, path); }
|
|
41
|
+
catch { continue; }
|
|
42
|
+
const open = observed.open;
|
|
43
|
+
if (open && !records.some(q => q.requestId === open.requestId) && !readOpenQuestion(open.requestId)
|
|
44
|
+
&& Date.now() - open.createdAt <= OPEN_QUESTION_RETENTION_MS) {
|
|
45
|
+
const record = { ...open, room: client.room, sourcePath: path };
|
|
46
|
+
saveOpenQuestion(record);
|
|
47
|
+
records.push(record);
|
|
48
|
+
}
|
|
49
|
+
for (const candidate of records.sort((a, b) => a.createdAt - b.createdAt)) {
|
|
50
|
+
if (options.requestId && candidate.requestId !== options.requestId) continue;
|
|
51
|
+
const record = readOpenQuestion(candidate.requestId);
|
|
52
|
+
if (!record || record.room !== client.room || record.sessionId !== session.sessionId) continue;
|
|
53
|
+
if (!record.answered && openQuestionClosed(record, observed)) {
|
|
54
|
+
record.answered = true;
|
|
55
|
+
saveOpenQuestion(record);
|
|
56
|
+
}
|
|
57
|
+
await announceOrResolve(client, session, record, options);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function announceOrResolve(client: RelayClient, session: SessionInfo, record: OpenQuestionRecord,
|
|
63
|
+
options: { replay?: boolean; peerPublicKey?: string }): Promise<void> {
|
|
64
|
+
if (record.answered || expired(record)) {
|
|
65
|
+
// A phone keeps a card no longer than the retention, so older ones need no repeat.
|
|
66
|
+
if (!record.resolvedSent || options.replay && !expired(record)) {
|
|
67
|
+
await resolveQuestion(client, record, options.peerPublicKey, !record.answered);
|
|
68
|
+
saveOpenQuestion({ ...record, resolvedSent: true });
|
|
69
|
+
} else if (expired(record)) forgetOpenQuestion(record.requestId);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (record.announced && !options.replay) return;
|
|
73
|
+
// A question found long after it was asked (an update, a waking Mac) arrives quietly.
|
|
74
|
+
const wake = !record.announced && Date.now() - record.createdAt <= QUIET_AFTER_MS;
|
|
75
|
+
const text = [record.question, ...record.options.map(value => '• ' + value)].join('\n');
|
|
76
|
+
await client.send({ type: 'agent.event', kind: 'question', requestId: record.requestId,
|
|
77
|
+
sessionId: session.sessionId, agent: 'claude', projectId: session.projectId,
|
|
78
|
+
taskId: session.taskId, computerId: session.computerId, text, createdAt: record.createdAt },
|
|
79
|
+
'phone', { ttlMs: Math.max(1, record.createdAt + OPEN_QUESTION_RETENTION_MS - Date.now()),
|
|
80
|
+
wake, urgent: true, peerPublicKey: options.peerPublicKey,
|
|
81
|
+
deliveryId: 'native-question-' + record.requestId });
|
|
82
|
+
saveOpenQuestion({ ...record, announced: true });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Restore one notification from private owned records; catalog discovery is not a prerequisite. */
|
|
86
|
+
export async function replayClaudeOpenQuestion(client: RelayClient, requestId: string,
|
|
87
|
+
peerPublicKey?: string): Promise<boolean> {
|
|
88
|
+
if (!peerPublicKey) return false;
|
|
89
|
+
const record = readOpenQuestion(requestId);
|
|
90
|
+
if (!record || record.room !== client.room) return false;
|
|
91
|
+
const identity = { sessionId: record.sessionId, agent: 'claude' as const };
|
|
92
|
+
if (!nativeTranscriptSource(identity)
|
|
93
|
+
&& (!record.sourcePath || !restoreNativeTranscriptSource(identity, record.sourcePath))) return false;
|
|
94
|
+
const session: SessionInfo = { ...identity, state: 'idle', startedAt: record.createdAt,
|
|
95
|
+
lastActivityAt: record.createdAt, tokensSession: 0, tokensLastTurn: 0 };
|
|
96
|
+
await publishClaudeOpenQuestions(client, [session], { replay: true, peerPublicKey, requestId });
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The answer is an ordinary message to the stopped chat: same policy, queue and receipts. */
|
|
101
|
+
export async function handleClaudeOpenQuestionReply(client: RelayClient, message: UserMessage,
|
|
102
|
+
publish: () => Promise<void>, peerPublicKey?: string,
|
|
103
|
+
deliver = handleInboundUserMessage): Promise<boolean> {
|
|
104
|
+
if (!message.requestId || !peerPublicKey) return false;
|
|
105
|
+
const record = readOpenQuestion(message.requestId);
|
|
106
|
+
if (!record || record.room !== client.room || record.sessionId !== message.sessionId) return false;
|
|
107
|
+
const path = nativeTranscriptSource({ sessionId: record.sessionId, agent: 'claude' });
|
|
108
|
+
if (!path) return false;
|
|
109
|
+
try {
|
|
110
|
+
if (!record.answered && openQuestionClosed(record, observedOpenQuestion(record.sessionId, path))) {
|
|
111
|
+
record.answered = true;
|
|
112
|
+
saveOpenQuestion(record);
|
|
113
|
+
}
|
|
114
|
+
} catch { return false; }
|
|
115
|
+
if (record.answered || expired(record)) {
|
|
116
|
+
if (message.messageId) await sendDeliveryReceipt(client, message.messageId, 'rejected',
|
|
117
|
+
record.answered ? 'This question was already answered at the computer.' : 'This question has expired.',
|
|
118
|
+
record.sessionId, peerPublicKey);
|
|
119
|
+
await resolveQuestion(client, record, peerPublicKey, !record.answered);
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
if (!message.text.trim() || message.text.length > 4_000) return false;
|
|
123
|
+
return deliver(client, { ...message, requestId: undefined,
|
|
124
|
+
messageId: message.messageId ?? 'claude-answer-' + record.requestId }, publish, peerPublicKey);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function resolveQuestion(client: RelayClient, record: OpenQuestionRecord, peerPublicKey?: string, lapsed = false) {
|
|
128
|
+
return client.send({ type: 'approval.resolved', requestId: record.requestId,
|
|
129
|
+
sessionId: record.sessionId, status: lapsed ? 'expired' : 'applied',
|
|
130
|
+
nativeUiCleared: record.answered === true, resolvedAt: Date.now() },
|
|
131
|
+
'phone', { ttlMs: 15 * 60_000, wake: false, peerPublicKey });
|
|
132
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { safeParse, ts } from '../sessions/support/common';
|
|
4
|
+
|
|
5
|
+
/** Written by the hook when the phone window passes; its tool result marks a question handed to the phone. */
|
|
6
|
+
export const DEFERRED_QUESTION_REASON = 'The person is away from this computer. GrantTap keeps this question open '
|
|
7
|
+
+ 'on their phone, and their answer will arrive as their next message. Stop here: end your turn and ask the '
|
|
8
|
+
+ 'same question in your final message, so it can also be answered at the computer.';
|
|
9
|
+
|
|
10
|
+
const WrapUp = z.object({ ask: z.string().trim().min(1).max(2_000),
|
|
11
|
+
actions: z.array(z.object({ label: z.string().trim().max(512).optional(), action: z.string().optional() }))
|
|
12
|
+
.max(4).optional() });
|
|
13
|
+
const Ask = z.object({ questions: z.array(z.object({ question: z.string().trim().min(1).max(2_000),
|
|
14
|
+
options: z.array(z.object({ label: z.string().trim().min(1).max(512) })).max(8).optional() })).min(1).max(4) });
|
|
15
|
+
|
|
16
|
+
export type OpenQuestion = { requestId: string; sessionId: string; callId: string;
|
|
17
|
+
question: string; options: string[]; createdAt: number };
|
|
18
|
+
|
|
19
|
+
export function openQuestionId(sessionId: string, callId: string): string {
|
|
20
|
+
return 'claude-open-question-' + createHash('sha256').update(JSON.stringify([sessionId, callId]))
|
|
21
|
+
.digest('hex').slice(0, 32);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The question a Claude chat stopped on: the desktop app's end-of-turn ask, or an
|
|
26
|
+
* AskUserQuestion the hook handed to the phone. Any later message from the person
|
|
27
|
+
* (typed, a desktop button, a phone reply) closes it.
|
|
28
|
+
*/
|
|
29
|
+
export function openQuestionObservation(sessionId: string, lines: string[]) {
|
|
30
|
+
let open: OpenQuestion | undefined;
|
|
31
|
+
let lastHumanAt = 0;
|
|
32
|
+
const asks = new Map<string, OpenQuestion>();
|
|
33
|
+
for (const line of lines) {
|
|
34
|
+
if (!mayMatter(line)) continue;
|
|
35
|
+
const row = safeParse(line);
|
|
36
|
+
if (!row || row.isSidechain === true || row.isMeta === true) continue;
|
|
37
|
+
const content = row.message?.content;
|
|
38
|
+
const at = ts(row.timestamp);
|
|
39
|
+
if (row.type === 'assistant' && Array.isArray(content) && at) {
|
|
40
|
+
for (const block of content) {
|
|
41
|
+
if (block?.type !== 'tool_use' || typeof block.id !== 'string') continue;
|
|
42
|
+
const found = toolQuestion(sessionId, block, at);
|
|
43
|
+
if (found && block.name === 'AskUserQuestion') asks.set(block.id, found);
|
|
44
|
+
else if (found) open = found;
|
|
45
|
+
}
|
|
46
|
+
} else if (row.type === 'user' && (typeof content === 'string'
|
|
47
|
+
|| Array.isArray(content) && content.some((block: any) => block?.type !== 'tool_result'))) {
|
|
48
|
+
open = undefined;
|
|
49
|
+
lastHumanAt = Math.max(lastHumanAt, at || Date.now());
|
|
50
|
+
} else if (row.type === 'user' && Array.isArray(content)) {
|
|
51
|
+
for (const block of content) {
|
|
52
|
+
const ask = asks.get(block?.tool_use_id);
|
|
53
|
+
if (ask && resultText(block.content).includes(DEFERRED_QUESTION_REASON)) open = ask;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { open, lastHumanAt };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Closed once the person spoke after it or a newer question replaced it. */
|
|
61
|
+
export function openQuestionClosed(question: Pick<OpenQuestion, 'requestId' | 'createdAt'>,
|
|
62
|
+
observed: ReturnType<typeof openQuestionObservation>): boolean {
|
|
63
|
+
if (observed.open?.requestId === question.requestId) return false;
|
|
64
|
+
return question.createdAt <= observed.lastHumanAt
|
|
65
|
+
|| !!observed.open && question.createdAt <= observed.open.createdAt;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function toolQuestion(sessionId: string, block: any, createdAt: number): OpenQuestion | undefined {
|
|
69
|
+
const base = { requestId: openQuestionId(sessionId, block.id), sessionId, callId: block.id, createdAt };
|
|
70
|
+
if (block.name === 'mcp__ccd_turn__wrap_up') {
|
|
71
|
+
const input = WrapUp.safeParse(block.input);
|
|
72
|
+
if (!input.success) return undefined;
|
|
73
|
+
// App actions (commit, merge…) run in the desktop app; only reply buttons become phone choices.
|
|
74
|
+
const options = [...new Set((input.data.actions ?? []).filter(a => !a.action && a.label).map(a => a.label!))];
|
|
75
|
+
return { ...base, question: input.data.ask, options };
|
|
76
|
+
}
|
|
77
|
+
if (block.name !== 'AskUserQuestion') return undefined;
|
|
78
|
+
const input = Ask.safeParse(block.input);
|
|
79
|
+
if (!input.success) return undefined;
|
|
80
|
+
const [only] = input.data.questions;
|
|
81
|
+
if (input.data.questions.length === 1 && only) {
|
|
82
|
+
return { ...base, question: only.question, options: [...new Set((only.options ?? []).map(o => o.label))] };
|
|
83
|
+
}
|
|
84
|
+
const question = input.data.questions.map(q => [q.question, ...(q.options ?? []).map(o => ' - ' + o.label)]
|
|
85
|
+
.join('\n')).join('\n\n');
|
|
86
|
+
return { ...base, question, options: [] };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Large tool results and request records are skipped before parsing; quotes inside text are escaped. */
|
|
90
|
+
function mayMatter(line: string): boolean {
|
|
91
|
+
if (line.includes('"type":"tool_result"')) return line.includes(DEFERRED_QUESTION_REASON);
|
|
92
|
+
if (line.includes('"type":"assistant"')) {
|
|
93
|
+
return line.includes('"mcp__ccd_turn__wrap_up"') || line.includes('"AskUserQuestion"');
|
|
94
|
+
}
|
|
95
|
+
return line.includes('"type":"user"');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function resultText(content: unknown): string {
|
|
99
|
+
if (typeof content === 'string') return content;
|
|
100
|
+
return Array.isArray(content) ? content.map((part: any) => typeof part?.text === 'string' ? part.text : '').join('\n')
|
|
101
|
+
: '';
|
|
102
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { configDir, writePrivateFile } from '../config';
|
|
5
|
+
import { openQuestionId } from './observations';
|
|
6
|
+
|
|
7
|
+
const Record = z.object({ requestId: z.string(), sessionId: z.string(), callId: z.string(),
|
|
8
|
+
question: z.string().max(10_000), options: z.array(z.string().max(512)).max(8), createdAt: z.number(),
|
|
9
|
+
room: z.string(), sourcePath: z.string().min(1).max(4096).optional(),
|
|
10
|
+
announced: z.boolean().optional(), answered: z.boolean().optional(), resolvedSent: z.boolean().optional() });
|
|
11
|
+
export type OpenQuestionRecord = z.infer<typeof Record>;
|
|
12
|
+
const NAME = /^claude-open-question-[a-f0-9]{32}$/;
|
|
13
|
+
const directory = () => join(configDir(), 'claude-open-question-records');
|
|
14
|
+
const observations = new Map<string, { revision: string; record: OpenQuestionRecord }>();
|
|
15
|
+
|
|
16
|
+
function revision(path: string): string {
|
|
17
|
+
const stat = statSync(path, { bigint: true });
|
|
18
|
+
if (!stat.isFile() || stat.size > 32_768n) throw Error('Invalid open question record');
|
|
19
|
+
return [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(':');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readOpenQuestion(requestId: string): OpenQuestionRecord | undefined {
|
|
23
|
+
if (!NAME.test(requestId)) return undefined;
|
|
24
|
+
const path = join(directory(), requestId + '.json');
|
|
25
|
+
try {
|
|
26
|
+
const before = revision(path), cached = observations.get(path);
|
|
27
|
+
if (cached?.revision === before) return structuredClone(cached.record);
|
|
28
|
+
const record = Record.parse(JSON.parse(readFileSync(path, 'utf8')));
|
|
29
|
+
if (record.requestId !== requestId || openQuestionId(record.sessionId, record.callId) !== requestId
|
|
30
|
+
|| revision(path) !== before) { observations.delete(path); return undefined; }
|
|
31
|
+
if (observations.size >= 512) observations.delete(observations.keys().next().value!);
|
|
32
|
+
observations.set(path, { revision: before, record });
|
|
33
|
+
return structuredClone(record);
|
|
34
|
+
} catch { observations.delete(path); return undefined; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function saveOpenQuestion(record: OpenQuestionRecord): void {
|
|
38
|
+
if (!NAME.test(record.requestId)) throw new Error('Invalid open question identity');
|
|
39
|
+
const path = join(directory(), record.requestId + '.json');
|
|
40
|
+
writePrivateFile(path, JSON.stringify(record));
|
|
41
|
+
observations.delete(path);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A resolved record past its retention has nothing left to tell any phone. */
|
|
45
|
+
export function forgetOpenQuestion(requestId: string): void {
|
|
46
|
+
if (!NAME.test(requestId)) return;
|
|
47
|
+
const path = join(directory(), requestId + '.json');
|
|
48
|
+
rmSync(path, { force: true });
|
|
49
|
+
observations.delete(path);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function storedOpenQuestions(): OpenQuestionRecord[] {
|
|
53
|
+
if (!existsSync(directory())) return [];
|
|
54
|
+
return readdirSync(directory()).filter(name => name.endsWith('.json') && NAME.test(name.slice(0, -5)))
|
|
55
|
+
.slice(-300).flatMap(name => {
|
|
56
|
+
const record = readOpenQuestion(name.slice(0, -5));
|
|
57
|
+
return record ? [record] : [];
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync, statSync } from 'node:fs';
|
|
2
|
+
import { openQuestionObservation } from './observations';
|
|
3
|
+
|
|
4
|
+
/** An ended turn's question and the rows after it fit well inside this tail. */
|
|
5
|
+
const TAIL_BYTES = 1024 * 1024;
|
|
6
|
+
type Cached = { revision: string; observation: ReturnType<typeof openQuestionObservation> };
|
|
7
|
+
const sources = new Map<string, Cached>();
|
|
8
|
+
|
|
9
|
+
/** Read only the tail of a discovered transcript; an unchanged chat costs one stat. */
|
|
10
|
+
export function observedOpenQuestion(sessionId: string, path: string) {
|
|
11
|
+
const stat = statSync(path);
|
|
12
|
+
const key = JSON.stringify([sessionId, path]);
|
|
13
|
+
const revision = `${stat.ino}:${stat.mtimeMs}:${stat.size}`;
|
|
14
|
+
const cached = sources.get(key);
|
|
15
|
+
if (cached?.revision === revision) return cached.observation;
|
|
16
|
+
const observation = openQuestionObservation(sessionId, tailLines(path, stat.size));
|
|
17
|
+
// Sized for the full history list, so a quiet chat is read once, not every pass.
|
|
18
|
+
sources.delete(key);
|
|
19
|
+
if (sources.size >= 512) sources.delete(sources.keys().next().value!);
|
|
20
|
+
sources.set(key, { revision, observation });
|
|
21
|
+
return observation;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function tailLines(path: string, size: number): string[] {
|
|
25
|
+
const start = Math.max(0, size - TAIL_BYTES);
|
|
26
|
+
const buffer = Buffer.allocUnsafe(size - start);
|
|
27
|
+
const fd = openSync(path, 'r');
|
|
28
|
+
let read = 0;
|
|
29
|
+
try { read = readSync(fd, buffer, 0, buffer.length, start); } finally { closeSync(fd); }
|
|
30
|
+
const text = buffer.subarray(0, read).toString('utf8');
|
|
31
|
+
// The first line of a cut tail is partial; the parser skips it as invalid JSON anyway.
|
|
32
|
+
return (start > 0 ? text.slice(text.indexOf('\n') + 1) : text).split('\n');
|
|
33
|
+
}
|
|
@@ -4,9 +4,14 @@ Public entry point: `index.ts`. Handles Claude Code `AskUserQuestion` through th
|
|
|
4
4
|
existing encrypted, durable approval channel. All original questions, options,
|
|
5
5
|
descriptions, multiple selections and custom answers stay attached to the exact
|
|
6
6
|
native chat and call. A permission Allow without complete answers is rejected.
|
|
7
|
-
Auto allow never invents an answer.
|
|
8
|
-
question UI available.
|
|
9
|
-
an
|
|
7
|
+
Auto allow never invents an answer. An unreachable relay leaves Claude's local
|
|
8
|
+
question UI available. When the phone received the question and 100 seconds pass
|
|
9
|
+
without an answer (Claude stops the hook at 120), `deferredQuestionOutput` denies
|
|
10
|
+
the call with a reason that asks Claude to end its turn with the same question.
|
|
11
|
+
The `claude-open-questions` feature then keeps it on the phone until it is
|
|
12
|
+
answered there or at the computer. Successful answers return the original
|
|
13
|
+
`questions` and an `answers` mapping using Claude's documented PreToolUse
|
|
14
|
+
`updatedInput` contract.
|
|
10
15
|
|
|
11
16
|
Tests: `tests/`. Engineering contract: the Apple repository `AGENTS.md`.
|
|
12
17
|
|
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import type { ApprovalDecision, ApprovalRequest } from "../../../../packages/protocol/schema";
|
|
3
3
|
import { ApprovalQuestions, questionAnswers } from "../../../../packages/protocol/messages/approval-questions";
|
|
4
4
|
import { claudeToRequest, type HookInput } from "../host/adapters";
|
|
5
|
+
import { DEFERRED_QUESTION_REASON } from "../claude-open-questions/observations";
|
|
5
6
|
|
|
6
7
|
export function questionRequest(input: HookInput): ApprovalRequest | undefined {
|
|
7
8
|
if (input.tool_name !== "AskUserQuestion") return undefined;
|
|
@@ -24,3 +25,14 @@ export function claudeQuestionOutput(input: HookInput, decision: ApprovalDecisio
|
|
|
24
25
|
return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow",
|
|
25
26
|
updatedInput: { ...input.tool_input, questions: input.tool_input!.questions, answers } } };
|
|
26
27
|
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The phone saw the question and the window passed: it stays open there, and the
|
|
31
|
+
* chat stops with it rather than block on a local prompt the phone cannot answer.
|
|
32
|
+
* An unreachable relay keeps Claude's own question UI.
|
|
33
|
+
*/
|
|
34
|
+
export function deferredQuestionOutput(decision: ApprovalDecision) {
|
|
35
|
+
if (decision.decision !== "deny" || decision.decidedBy !== "expired") return undefined;
|
|
36
|
+
return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny",
|
|
37
|
+
permissionDecisionReason: DEFERRED_QUESTION_REASON } };
|
|
38
|
+
}
|
|
@@ -48,6 +48,8 @@ import { acceptPhoneAccountLink } from "../../account-recovery/phone-link";
|
|
|
48
48
|
import { approvalsStatus } from '../../approvals/state';
|
|
49
49
|
import { handleDeliveryReceiptQuery } from '../message-delivery/status-query';
|
|
50
50
|
import { handleCodexQuestionReply, publishCodexQuestions, replayCodexQuestion } from '../../codex-questions';
|
|
51
|
+
import { handleClaudeOpenQuestionReply, publishClaudeOpenQuestions, replayClaudeOpenQuestion }
|
|
52
|
+
from '../../claude-open-questions';
|
|
51
53
|
import { publishedCatalog } from '../../session-catalog';
|
|
52
54
|
|
|
53
55
|
export async function handleMonitorMessage(
|
|
@@ -152,8 +154,11 @@ export async function handleMonitorMessage(
|
|
|
152
154
|
|
|
153
155
|
function handlePhoneUserMessage(client: RelayClient, payload: Extract<Payload, { type: 'user.message' }>,
|
|
154
156
|
publish: (forceHistory?: boolean) => Promise<void>, peerPublicKey?: string) {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
+
if (payload.requestId?.startsWith('codex-question-')) {
|
|
158
|
+
return handleCodexQuestionReply(client, payload, () => publish(), peerPublicKey);
|
|
159
|
+
}
|
|
160
|
+
return payload.requestId?.startsWith('claude-open-question-')
|
|
161
|
+
? handleClaudeOpenQuestionReply(client, payload, () => publish(), peerPublicKey)
|
|
157
162
|
: handleInboundUserMessage(client, payload, publish, peerPublicKey);
|
|
158
163
|
}
|
|
159
164
|
|
|
@@ -206,12 +211,15 @@ async function handleInboundRefresh(
|
|
|
206
211
|
await client.send(approvalsStatus(), 'phone', { peerPublicKey, reliable: false, ttlMs: 90_000 })
|
|
207
212
|
.catch(() => {});
|
|
208
213
|
if (payload.notificationRequestId) {
|
|
209
|
-
|
|
214
|
+
const requestId = payload.notificationRequestId;
|
|
215
|
+
await (requestId.startsWith('claude-open-question-') ? replayClaudeOpenQuestion(client, requestId, peerPublicKey)
|
|
216
|
+
: replayCodexQuestion(client, requestId, peerPublicKey)).catch(() => false);
|
|
210
217
|
return true;
|
|
211
218
|
}
|
|
212
219
|
const known = publishedCatalog(client);
|
|
213
|
-
|
|
214
|
-
|
|
220
|
+
const sessions = known ? [...known.sessions, ...(known.history ?? [])] : [];
|
|
221
|
+
await publishCodexQuestions(client, sessions, { replay: true, peerPublicKey }).catch(() => {});
|
|
222
|
+
await publishClaudeOpenQuestions(client, sessions, { replay: true, peerPublicKey }).catch(() => {});
|
|
215
223
|
// An explicit refresh may pay for the full history scan; routine Mesh
|
|
216
224
|
// snapshots use the cached history and fresh live sessions.
|
|
217
225
|
invalidateMeshSessionHistory();
|
|
@@ -31,6 +31,7 @@ import { configDir } from "../../config";
|
|
|
31
31
|
// meant five minutes of a silent phone.
|
|
32
32
|
export const LEADERSHIP_TTL_MS = 90_000;
|
|
33
33
|
const REPORT_INTERVAL_MS = 10 * 60_000;
|
|
34
|
+
const INSTALLED = "installed-";
|
|
34
35
|
|
|
35
36
|
export type MonitorLeadership = { acquire: () => boolean; release: () => void };
|
|
36
37
|
|
|
@@ -101,7 +102,11 @@ export function monitorLeadership(
|
|
|
101
102
|
primary = false,
|
|
102
103
|
): MonitorLeadership {
|
|
103
104
|
const path = join(configDir(), "monitor.lock");
|
|
104
|
-
|
|
105
|
+
// Chats started by an older monitor inherited its primary flag and still run
|
|
106
|
+
// that release, so ":primary" alone no longer proves the installed monitor.
|
|
107
|
+
// The marker sits mid-token: older releases keep reading the suffix and so
|
|
108
|
+
// never take the lease from the installed monitor.
|
|
109
|
+
const token = `${process.pid}:${primary ? INSTALLED : ""}${randomUUID()}:${primary ? "primary" : "peer"}`;
|
|
105
110
|
let leader = false;
|
|
106
111
|
let reportedAt = 0;
|
|
107
112
|
|
|
@@ -139,7 +144,10 @@ export function monitorLeadership(
|
|
|
139
144
|
}
|
|
140
145
|
};
|
|
141
146
|
|
|
142
|
-
const ownerIsPrimary = (): boolean =>
|
|
147
|
+
const ownerIsPrimary = (): boolean => {
|
|
148
|
+
const owner = read()?.trim() ?? "";
|
|
149
|
+
return owner.endsWith(":primary") && owner.includes(`:${INSTALLED}`);
|
|
150
|
+
};
|
|
143
151
|
|
|
144
152
|
const reportRefusal = (): void => {
|
|
145
153
|
if (now() - reportedAt < REPORT_INTERVAL_MS) return;
|
|
@@ -36,6 +36,7 @@ import { sweepAttachments } from "../handlers/receipts";
|
|
|
36
36
|
import { handleMonitorMessage } from "../handlers/inbound";
|
|
37
37
|
import { decorateTaskOriginCatalog } from '../../task-origins';
|
|
38
38
|
import { publishCodexQuestions } from '../../codex-questions';
|
|
39
|
+
import { publishClaudeOpenQuestions } from '../../claude-open-questions';
|
|
39
40
|
|
|
40
41
|
const HISTORY_INTERVAL_MS = 60_000;
|
|
41
42
|
const resumedHeads = new WeakSet<RelayClient>();
|
|
@@ -277,15 +278,22 @@ function startQuestionLoop(client: RelayClient, leadership: { acquire: () => boo
|
|
|
277
278
|
publish: async () => {
|
|
278
279
|
if (!leadership.acquire()) return;
|
|
279
280
|
const known = publishedCatalog(client);
|
|
280
|
-
if (known)
|
|
281
|
-
|
|
281
|
+
if (!known) return;
|
|
282
|
+
const history = known.history ?? [];
|
|
283
|
+
await publishCodexQuestions(client, [...known.sessions,
|
|
284
|
+
...history.filter(s => subscriptions.has(s.sessionId))]).catch(() => {});
|
|
285
|
+
// A Claude chat can wait on its question long after it leaves the live list.
|
|
286
|
+
await publishClaudeOpenQuestions(client, [...known.sessions, ...history]).catch(() => {});
|
|
282
287
|
},
|
|
283
288
|
});
|
|
284
289
|
}
|
|
285
290
|
|
|
286
291
|
async function replayNativeQuestions(client: RelayClient, peerPublicKey: string) {
|
|
287
292
|
const known = publishedCatalog(client);
|
|
288
|
-
if (known)
|
|
293
|
+
if (!known) return;
|
|
294
|
+
await publishCodexQuestions(client, known.sessions, { replay: true, peerPublicKey }).catch(() => {});
|
|
295
|
+
await publishClaudeOpenQuestions(client, [...known.sessions, ...(known.history ?? [])],
|
|
296
|
+
{ replay: true, peerPublicKey }).catch(() => {});
|
|
289
297
|
}
|
|
290
298
|
|
|
291
299
|
function restoreMonitorState(client: RelayClient): void {
|
|
@@ -42,7 +42,9 @@ export function readCodexCapabilityHistory(
|
|
|
42
42
|
function readWorker(database: string, bindings: [string, string][]): Promise<NativeCapabilityEvidence> {
|
|
43
43
|
return new Promise(resolve => {
|
|
44
44
|
const requested = new Set(bindings.map(([thread]) => thread));
|
|
45
|
-
|
|
45
|
+
// Each read is a fresh worker; without the flag every one prints SQLite's experimental notice.
|
|
46
|
+
const worker = new Worker(new URL('./reader.js', import.meta.url), {
|
|
47
|
+
execArgv: ['--disable-warning=ExperimentalWarning'],
|
|
46
48
|
workerData: { database, bindings, now: Date.now(),
|
|
47
49
|
previous: (cursors.get(database) ?? []).filter(cursor => requested.has(cursor.threadId)) },
|
|
48
50
|
resourceLimits: { maxOldGenerationSizeMb: 64 } });
|
|
@@ -45,3 +45,8 @@ permission. The worker checks that exact native execution before claiming the
|
|
|
45
45
|
job, refreshes its catalog while held, and starts automatically once it is idle.
|
|
46
46
|
This does not turn a temporary native busy state into a failed delivery or ask
|
|
47
47
|
the person to resend. It does not claim provider-native mid-turn Steer support.
|
|
48
|
+
|
|
49
|
+
Relay queue errors are logged by `worker/failure-report.ts`. A dropped connection,
|
|
50
|
+
a timeout or a relay 5xx is retried on the next two-second pass and is logged only
|
|
51
|
+
after 30 seconds of continuing failures; storage faults are logged at once. Both
|
|
52
|
+
are limited to one line a minute and never include a prompt.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { TaskJobHttpError } from '../../../../../packages/core/task-job-http';
|
|
2
|
+
|
|
3
|
+
const NETWORK = new Set(['UND_ERR_SOCKET', 'UND_ERR_CLOSED', 'UND_ERR_CONNECT_TIMEOUT', 'ECONNRESET', 'EPIPE',
|
|
4
|
+
'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'ENETDOWN']);
|
|
5
|
+
/** The worker retries every two seconds; a blip shorter than this is not news. */
|
|
6
|
+
export const NETWORK_GRACE_MS = 30_000;
|
|
7
|
+
/** A quiet gap this long between failures means the previous outage ended. */
|
|
8
|
+
const OUTAGE_GAP_MS = 10_000;
|
|
9
|
+
|
|
10
|
+
/** A dropped connection, a timeout or a relay 5xx heals on the next pass; storage errors do not. */
|
|
11
|
+
export function transientQueueFailure(error: unknown): boolean {
|
|
12
|
+
if (error instanceof TaskJobHttpError) return error.status >= 500;
|
|
13
|
+
if (!(error instanceof Error)) return false;
|
|
14
|
+
if (error.name === 'TimeoutError' || error.name === 'AbortError') return true;
|
|
15
|
+
return NETWORK.has(String((error.cause as NodeJS.ErrnoException | undefined)?.code));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Storage and relay errors name a status or a path, never a prompt. */
|
|
19
|
+
export function queueFailureReporter(write = (line: string) => { process.stderr.write(line); }, now = Date.now) {
|
|
20
|
+
let reportedAt = 0, failingSince = 0, failedAt = 0;
|
|
21
|
+
return {
|
|
22
|
+
report(error: unknown) {
|
|
23
|
+
const transient = transientQueueFailure(error);
|
|
24
|
+
if (transient) {
|
|
25
|
+
if (now() - failedAt > OUTAGE_GAP_MS) failingSince = now();
|
|
26
|
+
failedAt = now();
|
|
27
|
+
if (now() - failingSince < NETWORK_GRACE_MS) return;
|
|
28
|
+
}
|
|
29
|
+
if (now() - reportedAt < 60_000) return;
|
|
30
|
+
reportedAt = now();
|
|
31
|
+
// A failed fetch keeps its reason (DNS, TLS, a closed socket) in `cause`.
|
|
32
|
+
const reason = error instanceof Error && error.cause instanceof Error
|
|
33
|
+
? ` [${(error.cause as NodeJS.ErrnoException).code ?? error.cause.name}]` : '';
|
|
34
|
+
const cause = error instanceof Error ? `${error.name}: ${error.message}${reason}`.slice(0, 200) : 'unknown';
|
|
35
|
+
write(transient
|
|
36
|
+
? `[monitor] Relay task queue unreachable for ${Math.round((now() - failingSince) / 1000)} s (${cause}); `
|
|
37
|
+
+ 'retrying. No prompt was replayed.\n'
|
|
38
|
+
: `[monitor] Durable task queue needs storage or relay recovery (${cause}). No prompt was replayed.\n`);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
@@ -12,6 +12,7 @@ import { relayTaskJobRemote } from './remote';
|
|
|
12
12
|
import { NativeTaskQueueSender } from '../sender';
|
|
13
13
|
import { dispatchSessionObservation, newTaskOperationKey, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
|
|
14
14
|
import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
|
|
15
|
+
import { queueFailureReporter } from './failure-report';
|
|
15
16
|
|
|
16
17
|
/** Only the persistent monitor advertises durable submission capability. */
|
|
17
18
|
export function startTaskDispatchMonitor(input: {
|
|
@@ -23,7 +24,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
23
24
|
const origins = localTaskOrigins();
|
|
24
25
|
const resolve = (job: Parameters<typeof resolveTaskOriginJob>[1], peer: string) =>
|
|
25
26
|
resolveTaskOriginJob(origins, job, input.config.room, peer);
|
|
26
|
-
let stopped = false,
|
|
27
|
+
let stopped = false, maintainedAt = 0, refreshedAt = 0;
|
|
27
28
|
const waitingSince = new Map<string, number>();
|
|
28
29
|
const sender = new NativeTaskQueueSender({ root: join(configDir(), 'native-task-queue'), config: input.config });
|
|
29
30
|
const peerAllowed = (peer: string) => peer === input.config.myPublicKey || input.peerAllowed(peer);
|
|
@@ -76,16 +77,7 @@ export function startTaskDispatchMonitor(input: {
|
|
|
76
77
|
return outcome;
|
|
77
78
|
},
|
|
78
79
|
});
|
|
79
|
-
const reportFailure = (
|
|
80
|
-
if (Date.now() - reportedAt < 60_000) return;
|
|
81
|
-
reportedAt = Date.now();
|
|
82
|
-
// Storage and relay errors name a status or a path, never a prompt.
|
|
83
|
-
// A failed fetch keeps its reason (DNS, TLS, connect timeout) in `cause`.
|
|
84
|
-
const reason = error instanceof Error && error.cause instanceof Error
|
|
85
|
-
? ` [${(error.cause as NodeJS.ErrnoException).code ?? error.cause.name}]` : '';
|
|
86
|
-
const cause = error instanceof Error ? `${error.name}: ${error.message}${reason}`.slice(0, 200) : 'unknown';
|
|
87
|
-
process.stderr.write(`[monitor] Durable task queue needs storage or relay recovery (${cause}). No prompt was replayed.\n`);
|
|
88
|
-
};
|
|
80
|
+
const reportFailure = queueFailureReporter().report;
|
|
89
81
|
const tick = () => {
|
|
90
82
|
if (Date.now() - maintainedAt > 3_600_000) {
|
|
91
83
|
maintainedAt = Date.now(); void inbox.maintain().catch(reportFailure);
|
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.140
|
|
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.140\";\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.140";
|
|
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
|
@@ -7,3 +7,8 @@ Redirects are rejected. HTTP failure text never includes credentials or content.
|
|
|
7
7
|
`TaskJobHttpError.status` supports a bounded product error mapping.
|
|
8
8
|
|
|
9
9
|
Licensed under the GrantTap Commercial Source License. See LICENSE and NOTICE.
|
|
10
|
+
|
|
11
|
+
A request that fails because the relay closed an idle pooled connection
|
|
12
|
+
(`UND_ERR_SOCKET`, `ECONNRESET`, …) is sent once more on a fresh connection.
|
|
13
|
+
Claims and outcomes carry their claim id, so the repeat is idempotent.
|
|
14
|
+
Tests: [`tests/dropped-connection.test.ts`](tests/dropped-connection.test.ts).
|
|
@@ -9,6 +9,12 @@ export class TaskJobHttpError extends Error {
|
|
|
9
9
|
constructor(readonly status: number) { super('The relay did not confirm the queued task operation.'); }
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
const DROPPED = new Set(['UND_ERR_SOCKET', 'UND_ERR_CLOSED', 'ECONNRESET', 'EPIPE']);
|
|
13
|
+
function droppedConnection(error: unknown): boolean {
|
|
14
|
+
const code = error instanceof Error ? (error.cause as NodeJS.ErrnoException | undefined)?.code : undefined;
|
|
15
|
+
return error instanceof TypeError && code !== undefined && DROPPED.has(code);
|
|
16
|
+
}
|
|
17
|
+
|
|
12
18
|
/** Only a bounded receipt is returned; prompt and photo ciphertext are never echoed into status polling. */
|
|
13
19
|
export async function requestTaskJob(config: PeerConfig, input: {
|
|
14
20
|
id: string; method: 'GET' | 'PUT' | 'POST' | 'DELETE'; action?: 'claim' | 'finish'; body?: unknown;
|
|
@@ -17,10 +23,17 @@ export async function requestTaskJob(config: PeerConfig, input: {
|
|
|
17
23
|
const url = new URL(`/task-jobs/${input.id}${input.action ? '/' + input.action : ''}`, config.relayUrl);
|
|
18
24
|
url.protocol = url.protocol === 'wss:' ? 'https:' : url.protocol === 'ws:' ? 'http:' : url.protocol;
|
|
19
25
|
url.searchParams.set('room', config.room); url.searchParams.set('metadata', '1');
|
|
20
|
-
const
|
|
26
|
+
const send = () => request(url, { method: input.method, redirect: 'error', signal: AbortSignal.timeout(20_000),
|
|
21
27
|
headers: { authorization: `Bearer ${config.pushAuth ?? ''}`, accept: 'application/json',
|
|
22
28
|
...(input.body ? { 'content-type': 'application/json' } : {}) },
|
|
23
29
|
body: input.body ? JSON.stringify(input.body) : undefined });
|
|
30
|
+
// A long-lived monitor reuses a pooled connection the relay already closed
|
|
31
|
+
// while idle; that request fails before it is sent. Claims and outcomes carry
|
|
32
|
+
// their claim id, so asking once more on a fresh connection is safe.
|
|
33
|
+
const response = await send().catch(error => {
|
|
34
|
+
if (!droppedConnection(error)) throw error;
|
|
35
|
+
return send();
|
|
36
|
+
});
|
|
24
37
|
if ([404, 409].includes(response.status)) return null;
|
|
25
38
|
if (!response.ok) throw new TaskJobHttpError(response.status);
|
|
26
39
|
const raw = await response.text();
|