@wengine-ai/ccr-provider-gemini-agy-acp 0.0.2 → 0.2.1
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/CHANGELOG.md +28 -0
- package/README.md +38 -9
- package/dist/card.js +380 -54
- package/dist/package.json +1 -1
- package/dist/plugin.json +2 -2
- package/dist/src/account.mjs +33 -0
- package/dist/src/acp-config.mjs +25 -1
- package/dist/src/acp-errors.mjs +1 -1
- package/dist/src/acp-stdio.mjs +69 -2
- package/dist/src/acp-usage.mjs +58 -0
- package/dist/src/admin-routes.mjs +161 -0
- package/dist/src/agy-mcp-stdio-bridge.mjs +77 -0
- package/dist/src/agy-tool-bridge.mjs +389 -0
- package/dist/src/agy-tool-budget.mjs +120 -0
- package/dist/src/agy-tools.mjs +146 -0
- package/dist/src/card.mjs +380 -54
- package/dist/src/chat.mjs +98 -19
- package/dist/src/install.mjs +185 -0
- package/dist/src/plugin.mjs +643 -35
- package/dist/src/settings.mjs +135 -0
- package/dist/src/transport.mjs +513 -41
- package/package.json +1 -1
package/dist/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"0.
|
|
1
|
+
{"type":"module","version":"0.2.1"}
|
package/dist/plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gemini-agy-acp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"coreApi": "1",
|
|
5
|
-
"description": "Experimental local Antigravity CLI provider for text-only chat over ACP stdio. Requires explicit opt-in
|
|
5
|
+
"description": "Experimental local Antigravity CLI provider for text-only chat over ACP stdio, with card-driven connect, disconnect, status and model sync over local-only admin routes. Requires explicit opt-in with Gemini API key or Google-account (oauth-personal) authentication."
|
|
6
6
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Bounded account-email helpers for the oauth-personal login verification.
|
|
2
|
+
* The ONLY accepted provenance is the just-verified ACP handshake of the
|
|
3
|
+
* selected binary: explicit ACP account metadata or the verifying child's own
|
|
4
|
+
* captured diagnostics. Stale CLI log files, keychain/token stores and other
|
|
5
|
+
* processes' state are never read; only a validated email string travels
|
|
6
|
+
* onward — never tokens or raw diagnostics. */
|
|
7
|
+
|
|
8
|
+
const MAX_EMAIL_CHARS = 254;
|
|
9
|
+
// First pattern wins: the structured login line beats the plain success line,
|
|
10
|
+
// and within one text the first occurrence is used.
|
|
11
|
+
const EMAIL_PATTERNS = [
|
|
12
|
+
/applyAuthResult: email=([^,\s"']+)/,
|
|
13
|
+
/authenticated successfully as ([^\s,"']+)/,
|
|
14
|
+
];
|
|
15
|
+
const EMAIL_SHAPE = /^[^\s@,;:<>"']+@[^\s@,;:<>"']+$/;
|
|
16
|
+
|
|
17
|
+
/** A display-safe, bounded email-ish string (≤254 chars, exactly one @, no
|
|
18
|
+
* whitespace or control characters). */
|
|
19
|
+
export function accountEmailShapeOk(value) {
|
|
20
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_EMAIL_CHARS &&
|
|
21
|
+
EMAIL_SHAPE.test(value) && !/[\0-\x1f\x7f]/.test(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Scan captured handshake text for the account email; null when the text
|
|
25
|
+
* carries no email-shaped login line. */
|
|
26
|
+
export function extractAccountEmail(text) {
|
|
27
|
+
if (typeof text !== 'string') return null;
|
|
28
|
+
for (const pattern of EMAIL_PATTERNS) {
|
|
29
|
+
const email = pattern.exec(text)?.[1];
|
|
30
|
+
if (accountEmailShapeOk(email)) return email;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
package/dist/src/acp-config.mjs
CHANGED
|
@@ -5,7 +5,7 @@ const selectorIds = {
|
|
|
5
5
|
thought_level: ['thought_level', 'thinking', 'thinking_level'],
|
|
6
6
|
};
|
|
7
7
|
|
|
8
|
-
function
|
|
8
|
+
function selectorFor(options, category) {
|
|
9
9
|
if (!Array.isArray(options)) throw new AcpError('unsupported_option');
|
|
10
10
|
const selectors = options.filter(option => option?.type === 'select' && (
|
|
11
11
|
option.category == null ? selectorIds[category].includes(option.id) : option.category === category
|
|
@@ -15,6 +15,30 @@ function select(options, category, requested) {
|
|
|
15
15
|
if (typeof selector.id !== 'string' || !Array.isArray(selector.options)) {
|
|
16
16
|
throw new AcpError('unsupported_option');
|
|
17
17
|
}
|
|
18
|
+
return selector;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The single advertised model selector, shared by session configuration and
|
|
22
|
+
* the model-sync route's catalog discovery. */
|
|
23
|
+
export function modelSelector(options) {
|
|
24
|
+
return selectorFor(options, 'model');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Flat {id,name} options of a selector, deduplicated by wire value. */
|
|
28
|
+
export function modelOptions(selector) {
|
|
29
|
+
const models = [];
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
for (const entry of selector.options.flatMap(option => option?.options ?? [option])) {
|
|
32
|
+
if (typeof entry?.value !== 'string' || !entry.value || seen.has(entry.value)) continue;
|
|
33
|
+
seen.add(entry.value);
|
|
34
|
+
models.push({ id: entry.value, name: typeof entry.name === 'string' && entry.name ? entry.name : entry.value });
|
|
35
|
+
if (models.length >= 256) break;
|
|
36
|
+
}
|
|
37
|
+
return models;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function select(options, category, requested) {
|
|
41
|
+
const selector = selectorFor(options, category);
|
|
18
42
|
const values = selector.options.flatMap(entry => entry?.options ?? [entry])
|
|
19
43
|
.filter(entry => typeof entry?.value === 'string');
|
|
20
44
|
const normalized = requested.toLowerCase();
|
package/dist/src/acp-errors.mjs
CHANGED
|
@@ -2,7 +2,7 @@ const errors = {
|
|
|
2
2
|
invalid_config: [400, 'Invalid ACP transport configuration'],
|
|
3
3
|
invalid_request: [400, 'Invalid ACP request'],
|
|
4
4
|
input_limit: [413, 'ACP prompt exceeds the input limit'],
|
|
5
|
-
auth_required: [401, 'ACP
|
|
5
|
+
auth_required: [401, 'ACP authentication is required'],
|
|
6
6
|
unsupported_version: [502, 'Antigravity CLI 1.5.1 or later is required'],
|
|
7
7
|
unsupported_option: [400, 'Requested ACP session option is unavailable'],
|
|
8
8
|
busy: [503, 'ACP worker pool is full'],
|
package/dist/src/acp-stdio.mjs
CHANGED
|
@@ -12,6 +12,11 @@ export class AcpStdio {
|
|
|
12
12
|
this.nextId = 1;
|
|
13
13
|
this.partial = Buffer.alloc(0);
|
|
14
14
|
this.partialBytes = 0;
|
|
15
|
+
this.onText = null;
|
|
16
|
+
this.onToolCall = null;
|
|
17
|
+
this.onPermission = null;
|
|
18
|
+
// Set for the duration of a prompt that may park on a tool call.
|
|
19
|
+
this.parked = null;
|
|
15
20
|
this.resetBudget();
|
|
16
21
|
child.stdout.on('data', chunk => {
|
|
17
22
|
if (this.failure) return;
|
|
@@ -70,6 +75,18 @@ export class AcpStdio {
|
|
|
70
75
|
return new Promise((resolve, reject) => { this.pending = { id, method, resolve, reject, errorCode }; });
|
|
71
76
|
}
|
|
72
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Drop an in-flight request without failing the worker. Used when a turn
|
|
80
|
+
* parks on a tool call: the agent will answer that prompt later, once the
|
|
81
|
+
* caller's result unblocks its MCP request, and a resume turn then issues a
|
|
82
|
+
* fresh prompt on the same session.
|
|
83
|
+
*/
|
|
84
|
+
abandon() {
|
|
85
|
+
if (this.pending?.method !== 'session/prompt') return;
|
|
86
|
+
this.pending.reject(new AcpError('cancelled'));
|
|
87
|
+
this.pending = null;
|
|
88
|
+
}
|
|
89
|
+
|
|
73
90
|
receive(frame) {
|
|
74
91
|
if (frame?.jsonrpc !== '2.0' || Array.isArray(frame)) throw new AcpError('protocol_error');
|
|
75
92
|
if (Object.hasOwn(frame, 'method')) {
|
|
@@ -79,7 +96,18 @@ export class AcpStdio {
|
|
|
79
96
|
if (Object.hasOwn(frame, 'id')) {
|
|
80
97
|
if (typeof frame.id !== 'string' && !Number.isSafeInteger(frame.id)) throw new AcpError('protocol_error');
|
|
81
98
|
if (frame.method === 'session/request_permission') {
|
|
82
|
-
|
|
99
|
+
// The caller owns every permission decision. No handler means deny,
|
|
100
|
+
// which is also the safe default for an unsolicited request.
|
|
101
|
+
const handler = this.onPermission;
|
|
102
|
+
if (!handler) {
|
|
103
|
+
this.send({ id: frame.id, result: { outcome: { outcome: 'cancelled' } } });
|
|
104
|
+
} else {
|
|
105
|
+
Promise.resolve(handler(frame.params)).then(outcome => {
|
|
106
|
+
this.send({ id: frame.id, result: { outcome } });
|
|
107
|
+
}).catch(() => {
|
|
108
|
+
this.send({ id: frame.id, result: { outcome: { outcome: 'cancelled' } } });
|
|
109
|
+
});
|
|
110
|
+
}
|
|
83
111
|
} else {
|
|
84
112
|
this.send({ id: frame.id, error: { code: -32601, message: 'Method not supported' } });
|
|
85
113
|
}
|
|
@@ -89,6 +117,12 @@ export class AcpStdio {
|
|
|
89
117
|
if (update?.sessionUpdate === 'agent_message_chunk' && update.content?.type === 'text') {
|
|
90
118
|
if (typeof update.content.text !== 'string') throw new AcpError('protocol_error');
|
|
91
119
|
this.onText(update.content.text);
|
|
120
|
+
} else if (update?.sessionUpdate === 'tool_call' && this.onToolCall) {
|
|
121
|
+
// A raised call parks the turn: the agent is now blocked inside its
|
|
122
|
+
// own MCP request and will not answer the prompt until the caller
|
|
123
|
+
// does. Let the transport stop waiting on the prompt.
|
|
124
|
+
this.parked?.();
|
|
125
|
+
this.onToolCall(normalizeToolCall(update));
|
|
92
126
|
}
|
|
93
127
|
}
|
|
94
128
|
return;
|
|
@@ -99,7 +133,17 @@ export class AcpStdio {
|
|
|
99
133
|
if (!this.pending || frame.id !== this.pending.id) return; // stale response
|
|
100
134
|
const { resolve, reject, errorCode } = this.pending;
|
|
101
135
|
this.pending = null;
|
|
102
|
-
if (Object.hasOwn(frame, 'error'))
|
|
136
|
+
if (Object.hasOwn(frame, 'error')) {
|
|
137
|
+
const failure = new AcpError(errorCode);
|
|
138
|
+
// Keep the agent's own error text for internal classification only (the
|
|
139
|
+
// startup auth-race retry). Non-enumerable and never copied into the
|
|
140
|
+
// caller-facing `message`, so diagnostics cannot leak through responses
|
|
141
|
+
// or serialization.
|
|
142
|
+
if (typeof frame.error?.message === 'string') {
|
|
143
|
+
Object.defineProperty(failure, 'agentMessage', { value: frame.error.message });
|
|
144
|
+
}
|
|
145
|
+
reject(failure);
|
|
146
|
+
}
|
|
103
147
|
else if (!frame.result || typeof frame.result !== 'object' || Array.isArray(frame.result)) {
|
|
104
148
|
reject(new AcpError('protocol_error'));
|
|
105
149
|
} else resolve(frame.result);
|
|
@@ -114,5 +158,28 @@ export class AcpStdio {
|
|
|
114
158
|
this.pending?.reject(error);
|
|
115
159
|
this.pending = null;
|
|
116
160
|
this.onText = null;
|
|
161
|
+
this.onToolCall = null;
|
|
162
|
+
this.onPermission = null;
|
|
163
|
+
this.parked = null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* ACP tool_call update → the caller's tool-call shape. Only the fields the
|
|
169
|
+
* caller needs are read; anything malformed is dropped rather than guessed.
|
|
170
|
+
*/
|
|
171
|
+
function normalizeToolCall(update) {
|
|
172
|
+
const id = typeof update.toolCallId === 'string' && update.toolCallId ? update.toolCallId : undefined;
|
|
173
|
+
const title = typeof update.title === 'string' ? update.title : '';
|
|
174
|
+
if (!id || !title) return null;
|
|
175
|
+
let args = {};
|
|
176
|
+
const raw = update.rawInput;
|
|
177
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) args = raw;
|
|
178
|
+
else if (typeof raw === 'string') {
|
|
179
|
+
try {
|
|
180
|
+
const parsed = JSON.parse(raw);
|
|
181
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) args = parsed;
|
|
182
|
+
} catch { /* keep empty */ }
|
|
117
183
|
}
|
|
184
|
+
return { id, name: title, arguments: args };
|
|
118
185
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
function count(value) {
|
|
2
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function chatUsage(prompt, completion) {
|
|
6
|
+
const total = prompt + completion;
|
|
7
|
+
if (!Number.isSafeInteger(total)) return undefined;
|
|
8
|
+
return { usage_source: 'gemini-agy-acp', prompt_tokens: prompt, completion_tokens: completion, total_tokens: total };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// OpenAI prompt and completion counts include their respective detail counters.
|
|
12
|
+
export function promptUsage(result) {
|
|
13
|
+
const standard = result.usage;
|
|
14
|
+
const input = count(standard?.inputTokens);
|
|
15
|
+
const output = count(standard?.outputTokens);
|
|
16
|
+
if (input === undefined || output === undefined) {
|
|
17
|
+
// Quota already reports gross counts. Do not mix them with standard ACP counters.
|
|
18
|
+
const quota = result._meta?.quota?.token_count;
|
|
19
|
+
const quotaInput = count(quota?.input_tokens);
|
|
20
|
+
const quotaOutput = count(quota?.output_tokens);
|
|
21
|
+
return quotaInput === undefined || quotaOutput === undefined ? undefined : chatUsage(quotaInput, quotaOutput);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const read = count(standard.cachedReadTokens);
|
|
25
|
+
const write = count(standard.cachedWriteTokens);
|
|
26
|
+
const thought = count(standard.thoughtTokens);
|
|
27
|
+
const total = count(standard.totalTokens);
|
|
28
|
+
const cache = (read ?? 0) + (write ?? 0);
|
|
29
|
+
const thoughts = thought ?? 0;
|
|
30
|
+
let prompt = input + cache;
|
|
31
|
+
let completion = output >= thoughts ? output : output + thoughts;
|
|
32
|
+
if (standard.totalTokens !== undefined) {
|
|
33
|
+
if (total === undefined) return undefined;
|
|
34
|
+
// Input can exclude both cache buckets, include reads only, or include both.
|
|
35
|
+
// Output can include or exclude thoughts. The total must identify one split.
|
|
36
|
+
const prompts = new Set([prompt, input + (write ?? 0), input]);
|
|
37
|
+
const completions = new Set([completion, output + thoughts]);
|
|
38
|
+
const matches = [];
|
|
39
|
+
for (const candidate of prompts) {
|
|
40
|
+
if (candidate < cache) continue;
|
|
41
|
+
for (const candidateCompletion of completions) {
|
|
42
|
+
if (candidate + candidateCompletion === total) matches.push([candidate, candidateCompletion]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (matches.length !== 1) return undefined;
|
|
46
|
+
[[prompt, completion]] = matches;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const usage = chatUsage(prompt, completion);
|
|
50
|
+
if (!usage) return undefined;
|
|
51
|
+
return {
|
|
52
|
+
...usage,
|
|
53
|
+
...(read !== undefined || write !== undefined ? { prompt_tokens_details: {
|
|
54
|
+
cached_tokens: read, cache_write_tokens: write,
|
|
55
|
+
} } : {}),
|
|
56
|
+
...(thought !== undefined ? { completion_tokens_details: { reasoning_tokens: thought } } : {}),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gemini Agy ACP — the local-only, explicit user-action admin routes under the
|
|
3
|
+
* `/api/gemini-agy-acp` namespace, mirroring the codex / gemini-oauth guard
|
|
4
|
+
* shape: the loopback socket address is the only trustworthy identity, plus a
|
|
5
|
+
* Host/Origin allowlist pinned to the actual bound port. A browser Origin must
|
|
6
|
+
* match our authority; an originless loopback request (local CLI) is allowed.
|
|
7
|
+
*
|
|
8
|
+
* GET /status → redacted status shape for the management card
|
|
9
|
+
* POST /install {} — kick off the official agy auto-install
|
|
10
|
+
* POST /connect {binary?, apiKey?}
|
|
11
|
+
* POST /disconnect {}
|
|
12
|
+
* POST /models/sync {}
|
|
13
|
+
* POST /models/visibility {hide?: [ids], restore?: [ids]}
|
|
14
|
+
*
|
|
15
|
+
* Two secrecy rules travel with every route:
|
|
16
|
+
* - the sidecar apiKey is never serialized, logged or echoed — responses
|
|
17
|
+
* carry `apiKeyConfigured` only;
|
|
18
|
+
* - no route ever answers 401: the UI's global fetch layer intercepts every
|
|
19
|
+
* 401 as an expired CCR api key (wipe + redirect), so account-level auth
|
|
20
|
+
* failures travel as 422 and keep their stable code.
|
|
21
|
+
* Failures are stable code tokens (agy_* / acp_*) with a mapped HTTP status;
|
|
22
|
+
* raw upstream messages, subprocess stderr and binary diagnostics never cross.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export function registerAdminRoutes(app, { getService }) {
|
|
26
|
+
/** Local-only guard, identical in shape to the codex plugin's. */
|
|
27
|
+
function assertLocalAgyRequest(req) {
|
|
28
|
+
const deny = () => {
|
|
29
|
+
const error = new Error('agy_unauthorized');
|
|
30
|
+
error.statusCode = 403;
|
|
31
|
+
throw error;
|
|
32
|
+
};
|
|
33
|
+
const ip = req.ip || req.connection?.remoteAddress || '';
|
|
34
|
+
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
|
|
35
|
+
if (!isLoopback) deny();
|
|
36
|
+
const origin = req.headers?.origin;
|
|
37
|
+
let host = '';
|
|
38
|
+
try {
|
|
39
|
+
if (origin !== undefined && origin !== '') {
|
|
40
|
+
if (typeof origin !== 'string') deny();
|
|
41
|
+
const parsed = new URL(origin);
|
|
42
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) deny();
|
|
43
|
+
host = parsed.host;
|
|
44
|
+
}
|
|
45
|
+
} catch {
|
|
46
|
+
deny();
|
|
47
|
+
}
|
|
48
|
+
const address = app.server?.address?.();
|
|
49
|
+
const port = typeof address?.port === 'number' && address.port > 0 ? address.port : 3456;
|
|
50
|
+
const allowed = new Set([
|
|
51
|
+
`127.0.0.1:${port}`,
|
|
52
|
+
`localhost:${port}`,
|
|
53
|
+
`[::1]:${port}`,
|
|
54
|
+
]);
|
|
55
|
+
const authority = req.headers?.host;
|
|
56
|
+
if (typeof authority === 'string' && !allowed.has(authority)) deny();
|
|
57
|
+
if (host && !allowed.has(host)) deny();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const SAFE_CODE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
61
|
+
|
|
62
|
+
/** Shared catch: 403 from the socket guard, otherwise the error's own safe
|
|
63
|
+
* code and mapped status (401 deliberately remapped to 422, see header);
|
|
64
|
+
* unknown errors collapse to a constant 500 label with the message dropped. */
|
|
65
|
+
function agyRouteError(error, reply, route) {
|
|
66
|
+
if (error?.statusCode === 403) {
|
|
67
|
+
reply.status(403);
|
|
68
|
+
return { ok: false, success: false, error: 'agy_unauthorized' };
|
|
69
|
+
}
|
|
70
|
+
const code = typeof error?.code === 'string' && SAFE_CODE.test(error.code) ? error.code : 'agy_route_failed';
|
|
71
|
+
const raw = error?.statusCode;
|
|
72
|
+
const status = Number.isInteger(raw) && raw >= 400 && raw <= 599 ? (raw === 401 ? 422 : raw) : 500;
|
|
73
|
+
if (status === 500) {
|
|
74
|
+
app.log?.warn?.({ route: `gemini-agy-acp/${route}`, code }, 'gemini-agy-acp management route failed');
|
|
75
|
+
}
|
|
76
|
+
reply.status(status);
|
|
77
|
+
return { ok: false, success: false, error: code };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function service(reply) {
|
|
81
|
+
const resolved = getService();
|
|
82
|
+
if (!resolved) {
|
|
83
|
+
reply.status(503);
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return resolved;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
app.get('/api/gemini-agy-acp/status', async (req, reply) => {
|
|
90
|
+
try {
|
|
91
|
+
assertLocalAgyRequest(req);
|
|
92
|
+
const resolved = service(reply);
|
|
93
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
94
|
+
return await resolved.status();
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return agyRouteError(error, reply, 'status');
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
app.post('/api/gemini-agy-acp/install', async (req, reply) => {
|
|
101
|
+
try {
|
|
102
|
+
assertLocalAgyRequest(req);
|
|
103
|
+
const resolved = service(reply);
|
|
104
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
105
|
+
// Kicks off the single-flight background install and answers with the
|
|
106
|
+
// current status immediately; the card polls /status for completion.
|
|
107
|
+
return { ok: true, success: true, ...(await resolved.install()) };
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return agyRouteError(error, reply, 'install');
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
app.post('/api/gemini-agy-acp/connect', async (req, reply) => {
|
|
114
|
+
try {
|
|
115
|
+
assertLocalAgyRequest(req);
|
|
116
|
+
const resolved = service(reply);
|
|
117
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
118
|
+
// {ok,success,...status}: the card refreshes its status line straight
|
|
119
|
+
// from the mutation response; the status shape carries no key material.
|
|
120
|
+
return { ok: true, success: true, ...(await resolved.connect(req.body)) };
|
|
121
|
+
} catch (error) {
|
|
122
|
+
return agyRouteError(error, reply, 'connect');
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
app.post('/api/gemini-agy-acp/disconnect', async (req, reply) => {
|
|
127
|
+
try {
|
|
128
|
+
assertLocalAgyRequest(req);
|
|
129
|
+
const resolved = service(reply);
|
|
130
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
131
|
+
return { ok: true, success: true, ...(await resolved.disconnect()) };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return agyRouteError(error, reply, 'disconnect');
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
app.post('/api/gemini-agy-acp/models/sync', async (req, reply) => {
|
|
138
|
+
try {
|
|
139
|
+
assertLocalAgyRequest(req);
|
|
140
|
+
const resolved = service(reply);
|
|
141
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
142
|
+
const result = await resolved.syncModels();
|
|
143
|
+
return { ok: true, success: true, ...result };
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return agyRouteError(error, reply, 'models/sync');
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
app.post('/api/gemini-agy-acp/models/visibility', async (req, reply) => {
|
|
150
|
+
try {
|
|
151
|
+
assertLocalAgyRequest(req);
|
|
152
|
+
const resolved = service(reply);
|
|
153
|
+
if (!resolved) return { ok: false, success: false, error: 'agy_route_failed' };
|
|
154
|
+
// {ok,success,...status}: same envelope as the other mutations, so the
|
|
155
|
+
// card refreshes its model list straight from the response.
|
|
156
|
+
return { ok: true, success: true, ...(await resolved.hideModels(req.body)) };
|
|
157
|
+
} catch (error) {
|
|
158
|
+
return agyRouteError(error, reply, 'models/visibility');
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stdio MCP forwarder spawned by the ACP agent as a stdio MCP server.
|
|
3
|
+
*
|
|
4
|
+
* The agent's HTTP MCP path does not surface bridged tools to the model, so
|
|
5
|
+
* `session/new` advertises this script instead: the agent spawns it with the
|
|
6
|
+
* internal bridge's endpoint and bearer token in its environment, and every
|
|
7
|
+
* newline-delimited JSON-RPC message on stdin is POSTed verbatim to that
|
|
8
|
+
* loopback endpoint with node:http (never fetch, so no proxy is involved).
|
|
9
|
+
* Request responses are written back as single stdout lines; notifications
|
|
10
|
+
* produce no output. stdout carries JSON-RPC only — never logs.
|
|
11
|
+
*
|
|
12
|
+
* A tools/call can park for minutes while the caller executes the tool, so
|
|
13
|
+
* requests are forwarded concurrently with no timeout, and a backend failure
|
|
14
|
+
* answers the waiting request with a JSON-RPC error instead of exiting.
|
|
15
|
+
*/
|
|
16
|
+
import { request as httpRequest } from 'node:http';
|
|
17
|
+
import { createInterface } from 'node:readline';
|
|
18
|
+
|
|
19
|
+
const endpoint = process.env.CCR_MCP_ENDPOINT;
|
|
20
|
+
const token = process.env.CCR_MCP_TOKEN;
|
|
21
|
+
if (!endpoint || !token) process.exit(1);
|
|
22
|
+
try { new URL(endpoint); } catch { process.exit(1); }
|
|
23
|
+
|
|
24
|
+
// One whole line per response, in a single write, so concurrent responses
|
|
25
|
+
// cannot interleave inside a line.
|
|
26
|
+
const reply = message => { process.stdout.write(JSON.stringify(message) + '\n'); };
|
|
27
|
+
|
|
28
|
+
// The agent going away closes stdout; leave quietly instead of crashing.
|
|
29
|
+
process.stdout.on('error', () => process.exit(0));
|
|
30
|
+
|
|
31
|
+
const input = createInterface({ input: process.stdin });
|
|
32
|
+
input.on('line', line => {
|
|
33
|
+
if (!line.trim()) return;
|
|
34
|
+
let message;
|
|
35
|
+
try { message = JSON.parse(line); } catch {
|
|
36
|
+
reply({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
40
|
+
reply({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'invalid request' } });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const hasId = message.id !== undefined && message.id !== null;
|
|
44
|
+
let settled = false;
|
|
45
|
+
const unavailable = () => {
|
|
46
|
+
if (settled) return;
|
|
47
|
+
settled = true;
|
|
48
|
+
// Diagnostics must never carry the token or endpoint; the error message
|
|
49
|
+
// is a fixed string and nothing is logged.
|
|
50
|
+
if (hasId) reply({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: 'bridge unavailable' } });
|
|
51
|
+
};
|
|
52
|
+
const forwarded = httpRequest(endpoint, {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
|
|
55
|
+
});
|
|
56
|
+
forwarded.on('error', unavailable);
|
|
57
|
+
forwarded.on('response', response => {
|
|
58
|
+
if (!hasId) { response.resume(); return; }
|
|
59
|
+
const chunks = [];
|
|
60
|
+
response.on('data', chunk => chunks.push(chunk));
|
|
61
|
+
response.on('error', unavailable);
|
|
62
|
+
response.on('end', () => {
|
|
63
|
+
if (settled) return;
|
|
64
|
+
settled = true;
|
|
65
|
+
const body = Buffer.concat(chunks).toString('utf8');
|
|
66
|
+
let parsed;
|
|
67
|
+
try { parsed = JSON.parse(body); } catch { parsed = null; }
|
|
68
|
+
if (response.statusCode !== 200 || !parsed || typeof parsed !== 'object') {
|
|
69
|
+
reply({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: 'bridge unavailable' } });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
reply(parsed);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
forwarded.end(line);
|
|
76
|
+
});
|
|
77
|
+
input.on('close', () => process.exit(0));
|