@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/src/plugin.mjs
CHANGED
|
@@ -1,26 +1,74 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { access, stat } from 'node:fs/promises';
|
|
2
|
+
import { constants, statSync } from 'node:fs';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
2
4
|
import { isAbsolute, join } from 'node:path';
|
|
3
|
-
import {
|
|
5
|
+
import { AcpError } from './acp-errors.mjs';
|
|
6
|
+
import { AgyToolBridge } from './agy-tool-bridge.mjs';
|
|
7
|
+
import { declaresTools, declaredTools, hasCompleteResults, historyToolCalls, toolChoiceShapeOk, toolResultPrompt, toolResults } from './agy-tools.mjs';
|
|
8
|
+
import { registerAdminRoutes } from './admin-routes.mjs';
|
|
9
|
+
import { accountEmailShapeOk } from './account.mjs';
|
|
10
|
+
import { chatResponse, failure, textTurns, textTurnsOnly, toPrompt } from './chat.mjs';
|
|
11
|
+
import { createInstaller } from './install.mjs';
|
|
12
|
+
import { AUTH_METHODS, apiKeyShapeOk, enabledSettings, hiddenModelsOf, readSidecar, sidecarCache, writeSidecar } from './settings.mjs';
|
|
4
13
|
|
|
5
14
|
const NAME = 'gemini-agy-acp';
|
|
6
15
|
const MARKER = `ccr-managed-${NAME}`;
|
|
16
|
+
const SAFE_CODE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
7
17
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
18
|
+
// Importing transport.mjs must not start a subprocess; loading and installing
|
|
19
|
+
// this prototype alone stays inert.
|
|
20
|
+
const loadTransportModule = () => import('./transport.mjs');
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Carry the caller's tools, and on a follow-up request its results, into the
|
|
24
|
+
* transport.
|
|
25
|
+
*
|
|
26
|
+
* The plugin owns the MCP bridge. It starts before the turn so the agent can
|
|
27
|
+
* discover the tools, and stays open while a call is parked, so a follow-up
|
|
28
|
+
* request reuses the same bridge and resolves the parked call from the
|
|
29
|
+
* caller's result.
|
|
30
|
+
*/
|
|
31
|
+
function withToolResults(transport, tools, answered, parkedIds) {
|
|
32
|
+
// A resume turn reuses the bridge that parked exactly these calls. Matching
|
|
33
|
+
// on the ids keeps two interleaved conversations from stealing each other's
|
|
34
|
+
// bridge — and with it each other's ACP session.
|
|
35
|
+
const bridge = transport.toolBridge?.(parkedIds) ?? new AgyToolBridge(tools, () => new Promise(() => {}));
|
|
36
|
+
return {
|
|
37
|
+
async run(request) {
|
|
38
|
+
if (bridge.empty) {
|
|
39
|
+
// Nothing representable: tell the caller instead of silently answering
|
|
40
|
+
// as if the agent had simply chosen not to use a tool.
|
|
41
|
+
await bridge.close();
|
|
42
|
+
throw failure('agy_tools_unsupported', 400,
|
|
43
|
+
'This Agy ACP agent cannot serve the requested tools (' +
|
|
44
|
+
(bridge.omitted.map(entry => entry.reason).join(', ') || 'none projected') + ').');
|
|
45
|
+
}
|
|
46
|
+
if (!answered) await bridge.start();
|
|
47
|
+
try {
|
|
48
|
+
if (answered) {
|
|
49
|
+
// Deliver the caller's results into the still-parked MCP requests.
|
|
50
|
+
for (const [id, answer] of bridge.pending) {
|
|
51
|
+
bridge.pending.delete(id);
|
|
52
|
+
answer(answered.get(id) ?? { content: [{ type: 'text', text: 'The caller did not return a result for this tool call' }], isError: true });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const result = await transport.run({ ...request, bridge, ...(answered ? { resume: true } : {}) });
|
|
56
|
+
return result;
|
|
57
|
+
} finally {
|
|
58
|
+
// A bridge with nothing parked has served its purpose; leaving it
|
|
59
|
+
// listening would keep the process alive and expose a needless port.
|
|
60
|
+
if (bridge.pending.size === 0) await bridge.close();
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Short non-reversible fingerprint of the configured credential so the card
|
|
67
|
+
// can show WHICH key is connected without ever serializing the key itself.
|
|
68
|
+
function credentialFingerprint(apiKey) {
|
|
69
|
+
const key = apiKeyShapeOk(apiKey) ? apiKey : process.env.GEMINI_API_KEY;
|
|
70
|
+
if (!apiKeyShapeOk(key)) return null;
|
|
71
|
+
return createHash('sha256').update(key, 'utf8').digest('hex').slice(0, 10);
|
|
24
72
|
}
|
|
25
73
|
|
|
26
74
|
function assertProvider(provider) {
|
|
@@ -29,29 +77,545 @@ function assertProvider(provider) {
|
|
|
29
77
|
}
|
|
30
78
|
}
|
|
31
79
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
80
|
+
function safeCode(error) {
|
|
81
|
+
return typeof error?.code === 'string' && SAFE_CODE.test(error.code) ? error.code : 'agy_route_error';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The card-facing model list: ids/names only, deduplicated and bounded. */
|
|
85
|
+
function publicModels(value) {
|
|
86
|
+
if (!Array.isArray(value)) return undefined;
|
|
87
|
+
const models = [];
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
for (const entry of value) {
|
|
90
|
+
if (!entry || typeof entry.id !== 'string' || !entry.id || seen.has(entry.id)) continue;
|
|
91
|
+
seen.add(entry.id);
|
|
92
|
+
models.push({ id: entry.id, name: typeof entry.name === 'string' && entry.name ? entry.name : entry.id });
|
|
93
|
+
if (models.length >= 256) break;
|
|
94
|
+
}
|
|
95
|
+
return models.length ? models : undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function configuredBinary(raw) {
|
|
99
|
+
return typeof raw?.binary === 'string' && isAbsolute(raw.binary) && !raw.binary.includes('\0') ? raw.binary : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function assertExecutable(binary) {
|
|
35
103
|
try {
|
|
36
|
-
|
|
37
|
-
|
|
104
|
+
if (!(await stat(binary)).isFile()) throw new Error('not a file');
|
|
105
|
+
await access(binary, constants.X_OK);
|
|
38
106
|
} catch {
|
|
39
|
-
|
|
107
|
+
throw new AcpError('invalid_config');
|
|
40
108
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Resolve the proxy the agy CLI must use for its own upstream calls, with the
|
|
112
|
+
// same semantics as the core's resolveProviderProxyUrl: the configured proxy
|
|
113
|
+
// (compatibility keys included) applies when the global proxy is enabled (the
|
|
114
|
+
// core default when unset) or when this managed provider entry opts in.
|
|
115
|
+
// Reads never throw: an unreadable config simply yields no proxy.
|
|
116
|
+
const PROXY_URL_KEYS = ['HTTPS_PROXY', 'https_proxy', 'httpsProxy', 'PROXY_URL'];
|
|
117
|
+
|
|
118
|
+
function globalProxyEnabled(value) {
|
|
119
|
+
if (value === undefined || value === null || value === '') return true;
|
|
120
|
+
if (typeof value === 'string') {
|
|
121
|
+
const normalized = value.trim().toLowerCase();
|
|
122
|
+
if (normalized === 'false' || normalized === '0') return false;
|
|
123
|
+
if (normalized === 'true' || normalized === '1') return true;
|
|
124
|
+
return Boolean(normalized);
|
|
125
|
+
}
|
|
126
|
+
return Boolean(value);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Same $VAR/${VAR} interpolation the core read path applies, limited to the
|
|
130
|
+
// few scalar values this resolver consumes.
|
|
131
|
+
function interpolateString(value) {
|
|
132
|
+
return value.replace(/\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/g,
|
|
133
|
+
(match, braced, unbraced) => process.env[braced || unbraced] || match);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// mtime-gated snapshot cache: the request path must not re-read and re-parse
|
|
137
|
+
// the whole config on every turn. Keyed by host so tests stay isolated.
|
|
138
|
+
const configSnapshots = new WeakMap();
|
|
139
|
+
// Dedupe rejected-proxy diagnostics per host: a persistent bad value must
|
|
140
|
+
// not warn on every turn.
|
|
141
|
+
const proxyWarnState = new WeakMap();
|
|
142
|
+
|
|
143
|
+
async function readConfigSnapshot(host) {
|
|
144
|
+
// Non-fatal raw read only: readConfigFile exits the process on parse errors
|
|
145
|
+
// and auto-creates a default on ENOENT — never call it from the request path.
|
|
146
|
+
if (typeof host?.readRawConfig !== 'function') return undefined;
|
|
147
|
+
let cacheKey = null;
|
|
148
|
+
try {
|
|
149
|
+
const info = await stat(join(host.configDir, 'config.json'));
|
|
150
|
+
cacheKey = `${info.mtimeMs}:${info.size}`;
|
|
151
|
+
const cached = configSnapshots.get(host);
|
|
152
|
+
if (cached && cached.key === cacheKey) return cached.raw;
|
|
153
|
+
} catch { /* no usable stat: read uncached */ }
|
|
154
|
+
// One retry softens the torn-read window of the core's non-atomic save.
|
|
155
|
+
let raw;
|
|
156
|
+
try {
|
|
157
|
+
raw = await host.readRawConfig();
|
|
158
|
+
} catch {
|
|
159
|
+
try {
|
|
160
|
+
raw = await host.readRawConfig();
|
|
161
|
+
} catch {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
|
|
166
|
+
if (cacheKey) configSnapshots.set(host, { key: cacheKey, raw });
|
|
167
|
+
return raw;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export async function resolveProxyUrl(host, providerName = 'gemini-agy-acp', log) {
|
|
171
|
+
let raw;
|
|
172
|
+
try {
|
|
173
|
+
raw = await readConfigSnapshot(host);
|
|
174
|
+
} catch {
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
if (!raw) return undefined;
|
|
178
|
+
let proxyUrl;
|
|
179
|
+
for (const key of PROXY_URL_KEYS) {
|
|
180
|
+
const value = raw[key];
|
|
181
|
+
if (value === undefined || value === null) continue;
|
|
182
|
+
// Interpolate before trimming, matching the core read-then-normalize order.
|
|
183
|
+
const normalized = interpolateString(String(value)).trim();
|
|
184
|
+
if (normalized) { proxyUrl = normalized; break; }
|
|
185
|
+
}
|
|
186
|
+
if (!proxyUrl) return undefined;
|
|
187
|
+
if (!/^https?:\/\//i.test(proxyUrl)) {
|
|
188
|
+
// Diagnostics carry the scheme or the placeholder fact only — never the
|
|
189
|
+
// value, which can embed credentials.
|
|
190
|
+
const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(proxyUrl)?.[1];
|
|
191
|
+
const kind = scheme ? 'scheme:' + scheme : proxyUrl.startsWith('$') ? 'placeholder' : null;
|
|
192
|
+
if (kind) {
|
|
193
|
+
const last = host && typeof host === 'object' ? proxyWarnState.get(host) : undefined;
|
|
194
|
+
if (last !== kind) {
|
|
195
|
+
if (host && typeof host === 'object') proxyWarnState.set(host, kind);
|
|
196
|
+
log?.warn?.(scheme
|
|
197
|
+
? 'gemini-agy-acp ignored a configured proxy with unsupported scheme (' + scheme + ')'
|
|
198
|
+
: 'gemini-agy-acp ignored a configured proxy with an unresolved environment placeholder');
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return undefined;
|
|
202
|
+
}
|
|
203
|
+
const flag = typeof raw.PROXY_GLOBAL_ENABLED === 'string' ? interpolateString(raw.PROXY_GLOBAL_ENABLED) : raw.PROXY_GLOBAL_ENABLED;
|
|
204
|
+
if (globalProxyEnabled(flag)) return proxyUrl;
|
|
205
|
+
const providers = Array.isArray(raw.Providers) ? raw.Providers : Array.isArray(raw.providers) ? raw.providers : [];
|
|
206
|
+
const entry = providers.find(item => item?.name === providerName);
|
|
207
|
+
return entry?.proxyEnabled === true || entry?.proxy_enabled === true ? proxyUrl : undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export async function activateWithTransport(ctx, createTransport, options = {}) {
|
|
211
|
+
const configDir = ctx.host.configDir;
|
|
212
|
+
const log = ctx.log;
|
|
213
|
+
// Metadata-only default instance (targetBinary for status); the install
|
|
214
|
+
// kick below builds a proxy-aware instance per attempt.
|
|
215
|
+
const installer = options.installer ?? createInstaller();
|
|
216
|
+
const cache = sidecarCache(configDir);
|
|
217
|
+
let transport;
|
|
218
|
+
// Fingerprint of the settings the live pool was built from; a changed
|
|
219
|
+
// fingerprint (binary, auth method, apiKey, limits) is what actually swaps
|
|
220
|
+
// the pool, so a models-sync write never retires healthy workers.
|
|
221
|
+
let fingerprint;
|
|
222
|
+
let rebuilding;
|
|
223
|
+
let adminMutation = Promise.resolve();
|
|
224
|
+
let lastError;
|
|
225
|
+
// Background install state: single-flight promise while the official agy
|
|
226
|
+
// download runs, the last failure token, and the path placed by a successful
|
|
227
|
+
// install (reported as detectedBinary until Connect persists it).
|
|
228
|
+
let installing = null;
|
|
229
|
+
let installError = null;
|
|
230
|
+
let installedBinary = null;
|
|
231
|
+
|
|
232
|
+
const note = error => {
|
|
233
|
+
lastError = { code: safeCode(error), at: Date.now() };
|
|
234
|
+
return error;
|
|
235
|
+
};
|
|
236
|
+
const baseKeyOf = settings => JSON.stringify([settings.binary, settings.authMethod, settings.apiKey ?? null, settings.timeoutMs, settings.maxWorkers]);
|
|
237
|
+
const fingerprintOf = settings => JSON.stringify([settings.binary, settings.authMethod, settings.apiKey ?? null, settings.timeoutMs, settings.maxWorkers, settings.proxyUrl ?? null]);
|
|
238
|
+
let lastBaseKey = null;
|
|
239
|
+
|
|
240
|
+
async function applyTransport(force = false) {
|
|
241
|
+
const snapshot = await cache.read();
|
|
242
|
+
const base = enabledSettings(snapshot.raw);
|
|
243
|
+
// Re-resolve on every (re)build so a proxy config change swaps the pool.
|
|
244
|
+
const proxyUrl = base ? await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log) : undefined;
|
|
245
|
+
const settings = base ? { ...base, ...(proxyUrl ? { proxyUrl } : {}) } : undefined;
|
|
246
|
+
const next = settings ? fingerprintOf(settings) : null;
|
|
247
|
+
if (!force && next === fingerprint) return;
|
|
248
|
+
const previous = transport;
|
|
249
|
+
// A proxy-only change drains idle workers instead of killing in-flight
|
|
250
|
+
// turns; busy workers finish on the old pool and idle-retire naturally.
|
|
251
|
+
const proxyOnly = previous && base && baseKeyOf(base) === lastBaseKey;
|
|
252
|
+
// A parked tool call reserves its worker AND bridge on the current pool;
|
|
253
|
+
// the caller's resume is routed through the live transport, so defer the
|
|
254
|
+
// swap until the parked call resolves rather than orphaning its bridge.
|
|
255
|
+
if (proxyOnly && previous.hasParked?.()) return;
|
|
256
|
+
transport = settings ? await createTransport({ ...settings, ...(log ? { log } : {}) }) : undefined;
|
|
257
|
+
fingerprint = next;
|
|
258
|
+
lastBaseKey = base ? baseKeyOf(base) : null;
|
|
259
|
+
await (proxyOnly ? previous.retireIdle() : previous?.retireExisting());
|
|
44
260
|
}
|
|
45
261
|
|
|
262
|
+
function queueTransportUpdate(update) {
|
|
263
|
+
const next = Promise.resolve(rebuilding).catch(() => {}).then(update).finally(() => {
|
|
264
|
+
if (rebuilding === next) rebuilding = null;
|
|
265
|
+
});
|
|
266
|
+
rebuilding = next;
|
|
267
|
+
return next;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Single-flight settings refresh; safe to await from every request. */
|
|
271
|
+
function requireTransport(force = false) {
|
|
272
|
+
return !rebuilding || force ? queueTransportUpdate(() => applyTransport(force)) : rebuilding;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function connected(req) {
|
|
276
|
+
await requireTransport();
|
|
277
|
+
if (transport) return transport;
|
|
278
|
+
|
|
279
|
+
// Only a same-machine client may initiate installation. Read the actual
|
|
280
|
+
// TCP peer and port, never a forwarded address or model-supplied path.
|
|
281
|
+
const socket = req?.raw?.socket;
|
|
282
|
+
// A loopback proxy can rewrite every request header. The server owner's
|
|
283
|
+
// opt-in authorizes the fixed vendor download independently of the peer.
|
|
284
|
+
const forwarded = Object.keys(req?.headers ?? {}).some(key => /^(?:forwarded$|x-forwarded-|x-real-ip$|via$)/i.test(key));
|
|
285
|
+
if (process.env.CCR_AGY_INSTALL_ON_USE === '1' && !forwarded &&
|
|
286
|
+
['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(socket?.remoteAddress) && socket.localPort) {
|
|
287
|
+
const hosts = ['localhost', '127.0.0.1', '[::1]'].map(host => host + ':' + socket.localPort);
|
|
288
|
+
const host = req.headers?.host;
|
|
289
|
+
const origin = req.headers?.origin;
|
|
290
|
+
if (hosts.includes(host) && (origin === undefined || origin === 'http://' + host || origin === 'https://' + host)) {
|
|
291
|
+
const { existed } = await readSidecar(configDir);
|
|
292
|
+
if (!existed) {
|
|
293
|
+
if (installError) throw failure(installError.code, 503);
|
|
294
|
+
if (installedBinary || statSync(installer.targetBinary, { throwIfNoEntry: false })?.isFile()) {
|
|
295
|
+
throw failure('agy_connect_required', 503);
|
|
296
|
+
}
|
|
297
|
+
void startInstall();
|
|
298
|
+
throw failure('agy_install_in_progress', 503);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
throw failure('agy_disabled', 503);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Single-flight background install of the official agy binary for this
|
|
306
|
+
// platform/architecture. The route kicks it off and answers immediately;
|
|
307
|
+
// the card polls /status until the download finishes. Success never touches
|
|
308
|
+
// the sidecar — Connect remains the only action that persists settings and
|
|
309
|
+
// enables the provider.
|
|
310
|
+
function startInstall() {
|
|
311
|
+
if (installing) return installing;
|
|
312
|
+
installError = null;
|
|
313
|
+
installing = (async () => {
|
|
314
|
+
const proxyUrl = await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log);
|
|
315
|
+
return (options.installer ?? createInstaller({ proxyUrl })).install();
|
|
316
|
+
})()
|
|
317
|
+
.then(result => { installedBinary = result.binary; })
|
|
318
|
+
.catch(error => { installError = { code: safeCode(error), at: Date.now() }; })
|
|
319
|
+
.finally(() => { installing = null; });
|
|
320
|
+
return installing;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function install() {
|
|
324
|
+
void startInstall();
|
|
325
|
+
return status();
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function status() {
|
|
329
|
+
let raw = null;
|
|
330
|
+
try {
|
|
331
|
+
({ raw } = await readSidecar(configDir));
|
|
332
|
+
} catch (error) {
|
|
333
|
+
note(error);
|
|
334
|
+
}
|
|
335
|
+
const binary = configuredBinary(raw);
|
|
336
|
+
let binaryFound = false;
|
|
337
|
+
if (binary) {
|
|
338
|
+
try {
|
|
339
|
+
binaryFound = statSync(binary).isFile();
|
|
340
|
+
} catch { /* reported as not found */ }
|
|
341
|
+
}
|
|
342
|
+
// With no sidecar binary, surface an agy found at the official default
|
|
343
|
+
// location (or placed by the background install) so the card can prefill
|
|
344
|
+
// it without any config write.
|
|
345
|
+
let detectedBinary = null;
|
|
346
|
+
if (!binary) {
|
|
347
|
+
const candidate = installedBinary ?? installer.targetBinary;
|
|
348
|
+
try { if (statSync(candidate).isFile()) detectedBinary = candidate; } catch { /* not installed */ }
|
|
349
|
+
}
|
|
350
|
+
const version = typeof raw?.version === 'string' && raw.version.length > 0 && raw.version.length <= 128
|
|
351
|
+
? raw.version : null;
|
|
352
|
+
const models = publicModels(raw?.models);
|
|
353
|
+
const modelsSyncedAt = typeof raw?.modelsSyncedAt === 'number' && Number.isSafeInteger(raw.modelsSyncedAt)
|
|
354
|
+
? raw.modelsSyncedAt : undefined;
|
|
355
|
+
const authMethod = AUTH_METHODS.includes(raw?.authMethod) ? raw.authMethod : null;
|
|
356
|
+
const oauth = authMethod === 'oauth-personal';
|
|
357
|
+
// The account email is only ever the one persisted from connect's verified
|
|
358
|
+
// handshake of the selected binary — never discovered from stale logs.
|
|
359
|
+
const accountEmail = oauth && accountEmailShapeOk(raw?.accountEmail) ? raw.accountEmail : null;
|
|
360
|
+
return {
|
|
361
|
+
loaded: transport !== undefined,
|
|
362
|
+
enabled: raw?.enabled === true,
|
|
363
|
+
binary,
|
|
364
|
+
binaryFound,
|
|
365
|
+
detectedBinary,
|
|
366
|
+
installing: installing !== null,
|
|
367
|
+
installError: installError ?? null,
|
|
368
|
+
version,
|
|
369
|
+
lastError: lastError ?? null,
|
|
370
|
+
authMethod,
|
|
371
|
+
// oauth-personal pools carry no API key credential at all: the CLI uses
|
|
372
|
+
// its own OS-keyring Google login, so the key fields stay empty.
|
|
373
|
+
apiKeyConfigured: !oauth && (apiKeyShapeOk(raw?.apiKey) || apiKeyShapeOk(process.env.GEMINI_API_KEY)),
|
|
374
|
+
apiKeyFingerprint: oauth ? null : credentialFingerprint(raw?.apiKey),
|
|
375
|
+
...(accountEmail ? { accountEmail } : {}),
|
|
376
|
+
...(models ? { models } : {}),
|
|
377
|
+
...(modelsSyncedAt !== undefined ? { modelsSyncedAt } : {}),
|
|
378
|
+
hiddenModels: hiddenModelsOf(raw).filter(id => models?.some(model => model.id === id)),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function connect(body) {
|
|
383
|
+
const input = body && typeof body === 'object' && !Array.isArray(body) ? body : {};
|
|
384
|
+
const { raw } = await readSidecar(configDir);
|
|
385
|
+
const merged = { ...(raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) };
|
|
386
|
+
const authMethod = input.authMethod === undefined ? AUTH_METHODS[0]
|
|
387
|
+
: AUTH_METHODS.includes(input.authMethod) ? input.authMethod : null;
|
|
388
|
+
if (!authMethod) throw new AcpError('invalid_config');
|
|
389
|
+
const oauth = authMethod === 'oauth-personal';
|
|
390
|
+
// oauth-personal must not carry an apiKey: its credential is the CLI's
|
|
391
|
+
// own Google login, and a stored key would poison the pool settings.
|
|
392
|
+
if (oauth && input.apiKey !== undefined) throw new AcpError('invalid_config');
|
|
393
|
+
if (input.binary !== undefined) {
|
|
394
|
+
if (typeof input.binary !== 'string' || !isAbsolute(input.binary) || input.binary.includes('\0')) {
|
|
395
|
+
throw new AcpError('invalid_config');
|
|
396
|
+
}
|
|
397
|
+
merged.binary = input.binary;
|
|
398
|
+
}
|
|
399
|
+
if (!configuredBinary(merged)) throw new AcpError('invalid_config');
|
|
400
|
+
await assertExecutable(merged.binary);
|
|
401
|
+
// Bounded version probe BEFORE anything is persisted: a failed connect
|
|
402
|
+
// never enables a broken binary. The probe runs in the same auth mode as
|
|
403
|
+
// the pool that follows.
|
|
404
|
+
const { probeVersion } = await loadTransportModule();
|
|
405
|
+
const version = await probeVersion(merged.binary, authMethod, await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log));
|
|
406
|
+
let accountEmail = null;
|
|
407
|
+
if (oauth) {
|
|
408
|
+
// A `--version` probe cannot prove the OS-keyring Google login works:
|
|
409
|
+
// verify with one real bounded ACP handshake (authenticate + session/new)
|
|
410
|
+
// on a temporary worker of the selected binary. Any handshake failure
|
|
411
|
+
// maps to auth_required so the card surfaces the terminal-login hint.
|
|
412
|
+
const { verifyOauthHandshake } = await loadTransportModule();
|
|
413
|
+
try {
|
|
414
|
+
({ accountEmail } = await verifyOauthHandshake({ binary: merged.binary, log, proxyUrl: await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log) }));
|
|
415
|
+
} catch (error) {
|
|
416
|
+
log?.warn?.(`gemini-agy-acp oauth handshake failed (${safeCode(error)})`);
|
|
417
|
+
throw new AcpError('auth_required');
|
|
418
|
+
}
|
|
419
|
+
} else if (input.apiKey !== undefined) {
|
|
420
|
+
if (!apiKeyShapeOk(input.apiKey) || !input.apiKey.trim()) throw new AcpError('invalid_config');
|
|
421
|
+
merged.apiKey = input.apiKey;
|
|
422
|
+
}
|
|
423
|
+
// Write payload (not the merged view): switching to oauth evicts any
|
|
424
|
+
// stored apiKey, and switching back to gemini-api-key evicts the stale
|
|
425
|
+
// account email. `undefined` merge values delete the persisted keys.
|
|
426
|
+
const payload = oauth
|
|
427
|
+
? { enabled: true, binary: merged.binary, authMethod, version,
|
|
428
|
+
apiKey: undefined, ...(accountEmail ? { accountEmail } : { accountEmail: undefined }) }
|
|
429
|
+
: { enabled: true, binary: merged.binary, authMethod, version,
|
|
430
|
+
...(input.apiKey !== undefined ? { apiKey: merged.apiKey } : {}),
|
|
431
|
+
...(typeof raw?.accountEmail === 'string' ? { accountEmail: undefined } : {}) };
|
|
432
|
+
await queueTransportUpdate(async () => {
|
|
433
|
+
let replacement;
|
|
434
|
+
let settings;
|
|
435
|
+
let proxyUrl;
|
|
436
|
+
try {
|
|
437
|
+
// Validate the complete merged settings and prepare the new pool before
|
|
438
|
+
// replacing the saved credentials or the live pool.
|
|
439
|
+
await writeSidecar(configDir, payload, async next => {
|
|
440
|
+
settings = enabledSettings(next);
|
|
441
|
+
proxyUrl = await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log);
|
|
442
|
+
replacement = await createTransport({ ...settings, ...(proxyUrl ? { proxyUrl } : {}), ...(log ? { log } : {}) });
|
|
443
|
+
if (!replacement) throw failure('agy_config_invalid', 503);
|
|
444
|
+
});
|
|
445
|
+
} catch (error) {
|
|
446
|
+
await replacement?.close()?.catch(() => {});
|
|
447
|
+
throw error;
|
|
448
|
+
}
|
|
449
|
+
cache.invalidate();
|
|
450
|
+
const previous = transport;
|
|
451
|
+
transport = replacement;
|
|
452
|
+
fingerprint = fingerprintOf({ ...settings, ...(proxyUrl ? { proxyUrl } : {}) });
|
|
453
|
+
lastBaseKey = baseKeyOf(settings);
|
|
454
|
+
lastError = undefined;
|
|
455
|
+
await previous?.retireExisting().catch(error => {
|
|
456
|
+
log?.warn?.(`gemini-agy-acp could not retire the previous worker pool (${safeCode(error)})`);
|
|
457
|
+
});
|
|
458
|
+
});
|
|
459
|
+
return status();
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
async function disconnect() {
|
|
463
|
+
await writeSidecar(configDir, { enabled: false });
|
|
464
|
+
cache.invalidate();
|
|
465
|
+
await requireTransport(true).catch(error => {
|
|
466
|
+
note(error);
|
|
467
|
+
log?.warn?.(`gemini-agy-acp disconnect could not refresh the worker pool (${safeCode(error)})`);
|
|
468
|
+
});
|
|
469
|
+
return status();
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Register the managed provider entry and the discovered models so the
|
|
473
|
+
// router accepts them, mirroring the codex plugin's sync semantics: Router
|
|
474
|
+
// untouched, best-effort rollback on a failed write. A missing entry is
|
|
475
|
+
// created with the managed marker and a placeholder URL (never dialed), so
|
|
476
|
+
// the card alone is enough to go from install to first message.
|
|
477
|
+
async function registerProviderModels(models) {
|
|
478
|
+
const { readConfig, writeConfig, reloadRuntime } = ctx.host;
|
|
479
|
+
if (typeof readConfig !== 'function' || typeof writeConfig !== 'function') return;
|
|
480
|
+
const previous = await readConfig();
|
|
481
|
+
if (!Array.isArray(previous?.Providers)) return;
|
|
482
|
+
const config = structuredClone(previous);
|
|
483
|
+
let provider = config.Providers.find(entry => entry?.name === NAME);
|
|
484
|
+
const ids = models.map(model => model.id);
|
|
485
|
+
if (!provider) {
|
|
486
|
+
provider = { name: NAME, api_base_url: 'https://example.com/unused', api_key: MARKER, models: ids, transformer: { use: [NAME] } };
|
|
487
|
+
config.Providers.push(provider);
|
|
488
|
+
} else if (JSON.stringify(provider.models ?? []) === JSON.stringify(ids) &&
|
|
489
|
+
provider.api_key === MARKER && Array.isArray(provider.transformer?.use) && provider.transformer.use.includes(NAME)) {
|
|
490
|
+
return;
|
|
491
|
+
} else {
|
|
492
|
+
provider.models = ids;
|
|
493
|
+
}
|
|
494
|
+
const rollback = async () => {
|
|
495
|
+
try {
|
|
496
|
+
await writeConfig(previous);
|
|
497
|
+
await reloadRuntime?.(previous);
|
|
498
|
+
} catch {
|
|
499
|
+
log?.warn?.('gemini-agy-acp could not restore the previous provider catalog');
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
try {
|
|
503
|
+
await writeConfig(config);
|
|
504
|
+
await reloadRuntime?.(config);
|
|
505
|
+
return rollback;
|
|
506
|
+
} catch {
|
|
507
|
+
await rollback();
|
|
508
|
+
throw failure('agy_config_write_failed', 500);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async function updateCatalog(visibleModels, sidecarPatch) {
|
|
513
|
+
const rollback = await registerProviderModels(visibleModels);
|
|
514
|
+
try {
|
|
515
|
+
await writeSidecar(configDir, sidecarPatch);
|
|
516
|
+
cache.invalidate();
|
|
517
|
+
} catch (error) {
|
|
518
|
+
await rollback?.();
|
|
519
|
+
throw error;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async function syncModels() {
|
|
524
|
+
const { raw } = await readSidecar(configDir);
|
|
525
|
+
const settings = enabledSettings(raw);
|
|
526
|
+
if (!settings) throw failure('agy_disabled', 503);
|
|
527
|
+
const { syncModelOptions } = await loadTransportModule();
|
|
528
|
+
const oauth = settings.authMethod === 'oauth-personal';
|
|
529
|
+
// oauth-personal pools have no credential: the sync worker authenticates
|
|
530
|
+
// the CLI's own login, exactly like the request pool.
|
|
531
|
+
const apiKey = oauth ? undefined : settings.apiKey ?? process.env.GEMINI_API_KEY;
|
|
532
|
+
if (!oauth && !apiKey?.trim()) throw new AcpError('auth_required');
|
|
533
|
+
const proxyUrl = await resolveProxyUrl(ctx.host, 'gemini-agy-acp', log);
|
|
534
|
+
const { models, version } = await syncModelOptions(oauth
|
|
535
|
+
? { binary: settings.binary, authMethod: 'oauth-personal', log, proxyUrl }
|
|
536
|
+
: { binary: settings.binary, apiKey, log, proxyUrl });
|
|
537
|
+
const modelsSyncedAt = Date.now();
|
|
538
|
+
// The operator's hide set survives re-syncs; ids that disappeared
|
|
539
|
+
// upstream are dropped from it silently (always persisted so a pruned
|
|
540
|
+
// empty set actually replaces the stale list).
|
|
541
|
+
const hiddenModels = hiddenModelsOf(raw).filter(id => models.some(model => model.id === id));
|
|
542
|
+
await updateCatalog(models.filter(model => !hiddenModels.includes(model.id)),
|
|
543
|
+
{ models, modelsSyncedAt, version, hiddenModels });
|
|
544
|
+
return { models, modelsSyncedAt, version };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// Hide/restore synced models: every id is validated against the synced
|
|
548
|
+
// catalog (unknown → unsupported_option), the merged set persists in the
|
|
549
|
+
// sidecar (hide wins for ids in both lists) and the provider entry is
|
|
550
|
+
// re-registered with the visible models only. Hiding never retires
|
|
551
|
+
// workers — the pool fingerprint does not include models.
|
|
552
|
+
async function hideModels(input) {
|
|
553
|
+
const body = input && typeof input === 'object' && !Array.isArray(input) ? input : null;
|
|
554
|
+
if (!body) throw new AcpError('unsupported_option');
|
|
555
|
+
const { raw } = await readSidecar(configDir);
|
|
556
|
+
const synced = publicModels(raw?.models);
|
|
557
|
+
if (!synced) throw new AcpError('unsupported_option');
|
|
558
|
+
const known = new Set(synced.map(model => model.id));
|
|
559
|
+
const requested = value => {
|
|
560
|
+
if (value === undefined) return [];
|
|
561
|
+
if (!Array.isArray(value)) throw new AcpError('unsupported_option');
|
|
562
|
+
return value;
|
|
563
|
+
};
|
|
564
|
+
for (const id of [...requested(body.hide), ...requested(body.restore)]) {
|
|
565
|
+
if (!known.has(id)) throw new AcpError('unsupported_option');
|
|
566
|
+
}
|
|
567
|
+
// hide wins for ids present in both lists: restores apply first.
|
|
568
|
+
const hidden = new Set(hiddenModelsOf(raw).filter(id => known.has(id)));
|
|
569
|
+
for (const id of requested(body.restore)) hidden.delete(id);
|
|
570
|
+
for (const id of requested(body.hide)) hidden.add(id);
|
|
571
|
+
const hiddenModels = [...hidden];
|
|
572
|
+
await updateCatalog(synced.filter(model => !hidden.has(model.id)), { hiddenModels });
|
|
573
|
+
return status();
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// Eager load at activation: a valid sidecar starts the pool now; a missing
|
|
577
|
+
// or malformed one stays a per-request failure until Connect fixes it — the
|
|
578
|
+
// mtime-gated cache retries on every request without a gateway restart.
|
|
579
|
+
try {
|
|
580
|
+
await requireTransport();
|
|
581
|
+
} catch (error) {
|
|
582
|
+
note(error);
|
|
583
|
+
log?.warn?.(`gemini-agy-acp starts disabled (${safeCode(error)})`);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const guarded = operation => async (...args) => {
|
|
587
|
+
try {
|
|
588
|
+
return await operation(...args);
|
|
589
|
+
} catch (error) {
|
|
590
|
+
throw note(error);
|
|
591
|
+
}
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
// Serialize admin updates that read and write both the sidecar and catalog.
|
|
595
|
+
// A failed mutation must not prevent the next admin operation from running.
|
|
596
|
+
const serialized = operation => (...args) => {
|
|
597
|
+
const next = adminMutation.then(() => operation(...args));
|
|
598
|
+
adminMutation = next.catch(() => {});
|
|
599
|
+
return next;
|
|
600
|
+
};
|
|
601
|
+
|
|
46
602
|
class AgyTransformer {
|
|
47
603
|
static TransformerName = NAME;
|
|
48
604
|
name = NAME;
|
|
49
605
|
|
|
50
|
-
transformRequestIn(body, provider, context) {
|
|
606
|
+
async transformRequestIn(body, provider, context) {
|
|
51
607
|
if (provider?.name === NAME && context?.req) context.req.enableFallback = false;
|
|
52
608
|
assertProvider(provider);
|
|
53
|
-
|
|
54
|
-
|
|
609
|
+
// A tool-bearing request is served by the runtime's tool path, which
|
|
610
|
+
// does its own validation; only a text-only request is rejected here.
|
|
611
|
+
// A malformed tool choice is not a tool request at all: it must fail
|
|
612
|
+
// here, before the runtime could route it as one.
|
|
613
|
+
if (context?.req?.body) {
|
|
614
|
+
const declared = declaresTools(context.req.body) && toolChoiceShapeOk(context.req.body);
|
|
615
|
+
if (declared) textTurnsOnly(context.req.body);
|
|
616
|
+
else textTurns(context.req.body);
|
|
617
|
+
}
|
|
618
|
+
await connected(context?.req);
|
|
55
619
|
return { body };
|
|
56
620
|
}
|
|
57
621
|
}
|
|
@@ -59,6 +623,14 @@ export async function activateWithTransport(ctx, createTransport) {
|
|
|
59
623
|
// Read-only management card; the UI renders a hard failure for enabled
|
|
60
624
|
// plugins that ship none, so this prototype must always declare one.
|
|
61
625
|
ctx.registerUiCard?.({ cardPath: 'card.js' });
|
|
626
|
+
ctx.registerAdminRoutes?.(app => registerAdminRoutes(app, { getService: () => ({
|
|
627
|
+
status: () => status(),
|
|
628
|
+
install: guarded(install),
|
|
629
|
+
connect: guarded(serialized(connect)),
|
|
630
|
+
disconnect: guarded(serialized(disconnect)),
|
|
631
|
+
syncModels: guarded(serialized(syncModels)),
|
|
632
|
+
hideModels: guarded(serialized(hideModels)),
|
|
633
|
+
}) }));
|
|
62
634
|
ctx.registerManagedRuntime({
|
|
63
635
|
name: NAME,
|
|
64
636
|
// Claim this exact reserved name even on a malformed entry, so it fails
|
|
@@ -71,14 +643,50 @@ export async function activateWithTransport(ctx, createTransport) {
|
|
|
71
643
|
async dispatchRequest({ requestBody, req, config, provider }) {
|
|
72
644
|
if (req) req.enableFallback = false;
|
|
73
645
|
assertProvider(provider);
|
|
74
|
-
const local =
|
|
75
|
-
|
|
76
|
-
|
|
646
|
+
const local = await connected(req);
|
|
647
|
+
const tools = declaresTools(requestBody) ? declaredTools(requestBody) : [];
|
|
648
|
+
if (!tools.length || !toolChoiceShapeOk(requestBody)) {
|
|
649
|
+
if (req?.body) textTurns(req.body);
|
|
650
|
+
return chatResponse(local, toPrompt(requestBody, provider, req?.body), requestBody.stream === true, req, config);
|
|
651
|
+
}
|
|
652
|
+
// Tool path: the agent raises calls through the bridge and the caller
|
|
653
|
+
// executes them. A follow-up request that answers every carried call
|
|
654
|
+
// resumes the same ACP turn instead of starting a new one.
|
|
655
|
+
const calls = historyToolCalls(requestBody?.messages);
|
|
656
|
+
const answered = toolResults(requestBody?.messages);
|
|
657
|
+
const resuming = hasCompleteResults(calls, requestBody?.messages);
|
|
658
|
+
let prompt;
|
|
659
|
+
// Only a bridge this pool is still holding is a resume. "The history
|
|
660
|
+
// contains complete tool results" is not enough: a third turn of a tool
|
|
661
|
+
// conversation also matches, and treating it as a resume would start a
|
|
662
|
+
// fresh ACP session that has lost all real context and replays a growing
|
|
663
|
+
// recap of every completed call on every turn.
|
|
664
|
+
const held = resuming ? local.toolBridge?.(calls.map(call => call.id)) : undefined;
|
|
665
|
+
const resumingTurn = !!held;
|
|
666
|
+
let model = requestBody?.model;
|
|
667
|
+
if (resumingTurn) {
|
|
668
|
+
prompt = toolResultPrompt(calls, requestBody?.messages);
|
|
669
|
+
} else {
|
|
670
|
+
const base = toPrompt(requestBody, provider, req?.body);
|
|
671
|
+
prompt = base.prompt;
|
|
672
|
+
model = base.model;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
return await chatResponse(withToolResults(local, tools, resumingTurn ? answered : undefined, resumingTurn ? calls.map(call => call.id) : []),
|
|
676
|
+
{ model, prompt, tools }, requestBody.stream === true, req, config);
|
|
677
|
+
} catch (error) {
|
|
678
|
+
// A tool set the agent cannot serve is a caller-visible rejection, not a
|
|
679
|
+
// transport failure: the caller chose a model that cannot run its tools.
|
|
680
|
+
if (error?.code === 'agy_tools_unsupported') {
|
|
681
|
+
return new Response(JSON.stringify({ error: { type: error.code, code: error.code, message: error.message } }),
|
|
682
|
+
{ status: 400, headers: { 'content-type': 'application/json' } });
|
|
683
|
+
}
|
|
684
|
+
throw error;
|
|
685
|
+
}
|
|
77
686
|
},
|
|
78
687
|
});
|
|
79
688
|
}
|
|
80
689
|
|
|
81
690
|
export function activate(ctx) {
|
|
82
|
-
|
|
83
|
-
return activateWithTransport(ctx, async options => (await import('./transport.mjs')).createTransport(options));
|
|
691
|
+
return activateWithTransport(ctx, async options => (await loadTransportModule()).createTransport(options));
|
|
84
692
|
}
|