@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.
@@ -0,0 +1,135 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join } from 'node:path';
4
+ import { failure } from './chat.mjs';
5
+
6
+ const NAME = 'gemini-agy-acp';
7
+ /** The two transport-level auth methods; oauth-personal carries no apiKey at
8
+ * all — its credential is the CLI's own Google login. */
9
+ export const AUTH_METHODS = ['gemini-api-key', 'oauth-personal'];
10
+ const MAX_API_KEY_BYTES = 4096;
11
+ const MAX_HIDDEN_MODEL_CHARS = 128;
12
+ const MAX_HIDDEN_MODELS = 256;
13
+
14
+ export function settingsPath(configDir) {
15
+ return join(configDir, `${NAME}.json`);
16
+ }
17
+
18
+ /** A hidden-model id is a bounded, non-control string (never a secret
19
+ * carrier; C0 controls and DEL cannot appear in advertised model ids). */
20
+ function hiddenModelShapeOk(id) {
21
+ return typeof id === 'string' && id.length > 0 && id.length <= MAX_HIDDEN_MODEL_CHARS &&
22
+ !/[\0-\x1f\x7f]/.test(id);
23
+ }
24
+
25
+ /** The sidecar's hidden-model blacklist, normalized: invalid entries are
26
+ * dropped, duplicates collapse, order is preserved and the list is capped so
27
+ * a hand-edited sidecar can never grow config.json unboundedly. Absent or
28
+ * malformed containers normalize to []. */
29
+ export function hiddenModelsOf(raw) {
30
+ const entries = Array.isArray(raw?.hiddenModels) ? raw.hiddenModels : [];
31
+ const hidden = [];
32
+ const seen = new Set();
33
+ for (const id of entries) {
34
+ if (!hiddenModelShapeOk(id) || seen.has(id)) continue;
35
+ seen.add(id);
36
+ hidden.push(id);
37
+ if (hidden.length >= MAX_HIDDEN_MODELS) break;
38
+ }
39
+ return hidden;
40
+ }
41
+
42
+ /** A sidecar apiKey is configured only as a bounded, non-empty string. */
43
+ export function apiKeyShapeOk(apiKey) {
44
+ return typeof apiKey === 'string' && apiKey.length > 0 && apiKey.length <= MAX_API_KEY_BYTES &&
45
+ !apiKey.includes('\0');
46
+ }
47
+
48
+ function objectOrNothing(raw) {
49
+ return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
50
+ }
51
+
52
+ /** Validate the enabled transport settings, resolving the optional sidecar
53
+ * apiKey. gemini-api-key mode keeps the optional key with the transport's
54
+ * GEMINI_API_KEY process environment fallback (the pre-card behavior);
55
+ * oauth-personal mode must NOT carry an apiKey at all (presence fails closed
56
+ * — its credential is the CLI's own Google login). Any malformed enabled
57
+ * field fails closed. The resolved apiKey never travels anywhere except into
58
+ * the transport factory arguments. */
59
+ export function enabledSettings(raw) {
60
+ if (raw?.enabled !== true) return null;
61
+ const { binary, authMethod, timeoutMs = 60000, maxWorkers = 2, apiKey } = raw;
62
+ if (typeof binary !== 'string' || !isAbsolute(binary) || binary.includes('\0') || !AUTH_METHODS.includes(authMethod) ||
63
+ !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000 ||
64
+ !Number.isSafeInteger(maxWorkers) || maxWorkers < 1 || maxWorkers > 8 ||
65
+ (apiKey != null && (authMethod !== 'gemini-api-key' || !apiKeyShapeOk(apiKey)))) {
66
+ throw failure('agy_config_invalid', 503);
67
+ }
68
+ return { binary, authMethod, timeoutMs, maxWorkers, ...(apiKeyShapeOk(apiKey) ? { apiKey } : {}) };
69
+ }
70
+
71
+ /** Full sidecar read: {raw, mtimeMs, existed}. raw is the parsed JSON object
72
+ * (null when the file is absent) and mtimeMs keys the mtime-gated cache.
73
+ * Malformed JSON or an unexpected read error fails closed. */
74
+ export async function readSidecar(configDir) {
75
+ let text;
76
+ try {
77
+ text = await readFile(settingsPath(configDir), 'utf8');
78
+ } catch (error) {
79
+ if (error.code === 'ENOENT') return { raw: null, mtimeMs: null, existed: false };
80
+ throw failure('agy_config_invalid', 503);
81
+ }
82
+ let raw;
83
+ try {
84
+ raw = JSON.parse(text);
85
+ } catch {
86
+ throw failure('agy_config_invalid', 503);
87
+ }
88
+ let mtimeMs = null;
89
+ try {
90
+ mtimeMs = (await stat(settingsPath(configDir))).mtimeMs;
91
+ } catch { /* raced removal: the parse result above still applies */ }
92
+ return { raw, mtimeMs, existed: true };
93
+ }
94
+
95
+ /** Stat-gated sidecar cache: a full read+parse happens only when the file's
96
+ * mtime changed, so every chat request can notice sidecar edits without a
97
+ * gateway restart and without re-reading an unchanged file. */
98
+ export function sidecarCache(configDir) {
99
+ let cached;
100
+ return {
101
+ async read() {
102
+ let mtimeMs = null;
103
+ try {
104
+ mtimeMs = (await stat(settingsPath(configDir))).mtimeMs;
105
+ } catch (error) {
106
+ if (error.code !== 'ENOENT') throw failure('agy_config_invalid', 503);
107
+ }
108
+ if (cached && cached.mtimeMs === mtimeMs) return cached;
109
+ const fresh = await readSidecar(configDir);
110
+ cached = { mtimeMs: fresh.mtimeMs, raw: fresh.raw };
111
+ return cached;
112
+ },
113
+ invalidate() { cached = undefined; },
114
+ };
115
+ }
116
+
117
+ /** Merge fields into the sidecar atomically and keep it 0600. The apiKey is
118
+ * intentionally persisted here (never in config.json, logs or responses);
119
+ * the mode is enforced with chmod so an existing looser file is tightened. */
120
+ export async function writeSidecar(configDir, merge, prepare) {
121
+ const { raw } = await readSidecar(configDir);
122
+ const next = { ...(objectOrNothing(raw) ?? {}), ...merge };
123
+ await prepare?.(next);
124
+ const path = settingsPath(configDir);
125
+ const temporary = `${path}.${randomUUID()}.tmp`;
126
+ try {
127
+ await mkdir(dirname(path), { recursive: true });
128
+ await writeFile(temporary, JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
129
+ await chmod(temporary, 0o600);
130
+ await rename(temporary, path);
131
+ } catch (error) {
132
+ await rm(temporary, { force: true }).catch(() => {});
133
+ throw failure('agy_config_write_failed', 500);
134
+ }
135
+ }