@evomap/evolver 1.89.8 → 1.89.10

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.
Files changed (64) hide show
  1. package/README.ja-JP.md +1 -1
  2. package/README.ko-KR.md +1 -1
  3. package/README.md +1 -1
  4. package/README.zh-CN.md +1 -1
  5. package/package.json +1 -1
  6. package/src/evolve/guards.js +1 -1
  7. package/src/evolve/pipeline/collect.js +1 -1
  8. package/src/evolve/pipeline/dispatch.js +1 -1
  9. package/src/evolve/pipeline/enrich.js +1 -1
  10. package/src/evolve/pipeline/hub.js +1 -1
  11. package/src/evolve/pipeline/select.js +1 -1
  12. package/src/evolve/pipeline/signals.js +1 -1
  13. package/src/evolve/utils.js +1 -1
  14. package/src/evolve.js +1 -1
  15. package/src/gep/a2aProtocol.js +1 -1
  16. package/src/gep/antiAbuseTelemetry.js +1 -1
  17. package/src/gep/autoDistillConv.js +1 -1
  18. package/src/gep/autoDistillLlm.js +1 -1
  19. package/src/gep/candidateEval.js +1 -1
  20. package/src/gep/candidates.js +1 -1
  21. package/src/gep/contentHash.js +1 -1
  22. package/src/gep/conversationSniffer.js +1 -1
  23. package/src/gep/crypto.js +1 -1
  24. package/src/gep/curriculum.js +1 -1
  25. package/src/gep/deviceId.js +1 -1
  26. package/src/gep/envFingerprint.js +1 -1
  27. package/src/gep/epigenetics.js +1 -1
  28. package/src/gep/execBridge.js +1 -1
  29. package/src/gep/explore.js +1 -1
  30. package/src/gep/hash.js +1 -1
  31. package/src/gep/hubFetch.js +1 -1
  32. package/src/gep/hubReview.js +1 -1
  33. package/src/gep/hubSearch.js +1 -1
  34. package/src/gep/hubVerify.js +1 -1
  35. package/src/gep/learningSignals.js +1 -1
  36. package/src/gep/memoryGraph.js +1 -1
  37. package/src/gep/memoryGraphAdapter.js +1 -1
  38. package/src/gep/mutation.js +1 -1
  39. package/src/gep/narrativeMemory.js +1 -1
  40. package/src/gep/openPRRegistry.js +1 -1
  41. package/src/gep/personality.js +1 -1
  42. package/src/gep/policyCheck.js +1 -1
  43. package/src/gep/prompt.js +1 -1
  44. package/src/gep/recallInject.js +1 -1
  45. package/src/gep/recallVerifier.js +1 -1
  46. package/src/gep/reflection.js +1 -1
  47. package/src/gep/savingsCore.js +1 -1
  48. package/src/gep/selector.js +1 -1
  49. package/src/gep/skillDistiller.js +1 -1
  50. package/src/gep/solidify.js +1 -1
  51. package/src/gep/strategy.js +1 -1
  52. package/src/gep/tokenSavings.js +1 -1
  53. package/src/gep/workspaceKeychain.js +1 -1
  54. package/src/proxy/extensions/traceControl.js +1 -1
  55. package/src/proxy/index.js +367 -15
  56. package/src/proxy/inject.js +1 -1
  57. package/src/proxy/router/gemini_route.js +154 -0
  58. package/src/proxy/router/models_route.js +52 -0
  59. package/src/proxy/router/ollama_route.js +103 -0
  60. package/src/proxy/router/responses_route.js +14 -3
  61. package/src/proxy/router/vertex_route.js +110 -0
  62. package/src/proxy/server/routes.js +31 -0
  63. package/src/proxy/trace/extractor.js +1 -1
  64. package/src/proxy/trace/usage.js +1 -1
@@ -0,0 +1,154 @@
1
+ 'use strict';
2
+
3
+ // Gemini passthrough handler (format-aware routing, NO translation). A Gemini-shaped request — Google's native
4
+ // `/v1beta/models/<model>:generateContent` | `:streamGenerateContent` path, body `{contents, generationConfig,
5
+ // systemInstruction, tools}` — is forwarded verbatim to the Gemini upstream. The model + action live in the
6
+ // PATH (not the body), so we reconstruct the path (+ query like ?alt=sse) and pass it through. Trace capture
7
+ // mirrors the other providers (usage/finish/stream tee). Point the Gemini CLI/SDK's base URL at the proxy and
8
+ // it works unmodified — no Anthropic/OpenAI conversion (lossy translation is deliberately avoided).
9
+
10
+ const { createProxyTrace } = require('../trace/extractor');
11
+
12
+ const GEMINI_RESPONSE_HEADER_ALLOWLIST = new Set([
13
+ 'content-type',
14
+ 'retry-after',
15
+ 'x-request-id',
16
+ ]);
17
+
18
+ function hasGeminiUpstreamCredential() {
19
+ return !!(process.env.EVOMAP_GEMINI_API_KEY || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
20
+ }
21
+
22
+ function upstreamStatus(err, fallback = 502) {
23
+ const status = Number(err && err.statusCode);
24
+ return Number.isFinite(status) ? status : fallback;
25
+ }
26
+
27
+ function asUpstreamError(err, fallback = 502) {
28
+ if (err && err.statusCode && /^gemini upstream /.test(err.message || '')) return err;
29
+ const out = new Error('gemini upstream request failed');
30
+ out.statusCode = upstreamStatus(err, fallback);
31
+ out.cause = err;
32
+ return out;
33
+ }
34
+
35
+ function responseToBody(raw, status, headers, log) {
36
+ if (!raw) return {};
37
+ try {
38
+ return JSON.parse(raw);
39
+ } catch {
40
+ log.warn?.(JSON.stringify({
41
+ event: 'gemini_fallback',
42
+ reason: 'upstream_non_json',
43
+ upstream_status: status,
44
+ content_type: (headers && headers['content-type']) || '',
45
+ response_bytes: Buffer.byteLength(raw),
46
+ }));
47
+ return { error: raw };
48
+ }
49
+ }
50
+
51
+ function copyGeminiResponseHeaders(headers = {}) {
52
+ const out = {};
53
+ for (const [name, value] of Object.entries(headers || {})) {
54
+ const lower = String(name || '').toLowerCase();
55
+ if (!GEMINI_RESPONSE_HEADER_ALLOWLIST.has(lower) && !lower.startsWith('x-goog-')) continue;
56
+ if (value === undefined || value === null) continue;
57
+ const headerValue = Array.isArray(value) ? value.join(', ') : String(value);
58
+ if (/[\r\n]/.test(headerValue)) continue;
59
+ out[lower] = headerValue;
60
+ }
61
+ return out;
62
+ }
63
+
64
+ // `<model>:<action>` — the model can contain dots/dashes; the action is the part after the LAST colon
65
+ // (generateContent | streamGenerateContent | countTokens | ...). Returns {model, action} (action '' if absent).
66
+ function parseModelAction(modelAction) {
67
+ const s = String(modelAction || '');
68
+ const idx = s.lastIndexOf(':');
69
+ if (idx === -1) return { model: s, action: '' };
70
+ return { model: s.slice(0, idx), action: s.slice(idx + 1) };
71
+ }
72
+
73
+ function buildGeminiHandler({ geminiProxy, logger, traceStore, onTraceQueued } = {}) {
74
+ if (typeof geminiProxy !== 'function') {
75
+ throw new Error('buildGeminiHandler requires geminiProxy(path, body, opts)');
76
+ }
77
+ const log = logger || console;
78
+
79
+ return async ({ body, headers, params, query }) => {
80
+ const inboundHeaders = headers || {};
81
+ if (!hasGeminiUpstreamCredential()) {
82
+ throw Object.assign(new Error('gemini api key required'), { statusCode: 401 });
83
+ }
84
+
85
+ const modelAction = (params && params.modelAction) || '';
86
+ const { model, action } = parseModelAction(modelAction);
87
+ // Reconstruct the native Gemini path + query (e.g. ?alt=sse for streaming) and forward verbatim.
88
+ const qs = query && Object.keys(query).length ? '?' + new URLSearchParams(query).toString() : '';
89
+ const reqPath = `/v1beta/models/${modelAction}${qs}`;
90
+
91
+ let trace = null;
92
+ try {
93
+ trace = createProxyTrace({
94
+ route: `POST /v1beta/models/${modelAction}`,
95
+ headers: inboundHeaders,
96
+ body,
97
+ upstreamMode: 'gemini',
98
+ originalModel: model,
99
+ chosenModel: model,
100
+ store: traceStore,
101
+ logger: traceStore ? log : null,
102
+ onTraceQueued,
103
+ });
104
+ } catch (_) { /* best-effort trace; never break the request */ }
105
+
106
+ let upstream;
107
+ try {
108
+ upstream = await geminiProxy(reqPath, body, { inboundHeaders, upstreamMode: 'gemini' });
109
+ } catch (err) {
110
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
111
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'gemini', model });
112
+ throw wrapped;
113
+ }
114
+
115
+ if (upstream.stream) {
116
+ const forwardHeaders = copyGeminiResponseHeaders(upstream.headers);
117
+ const ct = upstream.headers && upstream.headers['content-type'];
118
+ if (ct) forwardHeaders['Content-Type'] = ct;
119
+ trace?.recordStreamStart({ status: upstream.status, upstreamMode: 'gemini', model, headers: forwardHeaders });
120
+ return {
121
+ status: upstream.status,
122
+ // Tee the Gemini SSE body so the deferred trace captures usageMetadata + finishReason. Bytes unchanged.
123
+ stream: trace ? trace.observeStream(upstream.stream) : upstream.stream,
124
+ headers: forwardHeaders,
125
+ };
126
+ }
127
+
128
+ let raw = '';
129
+ if (upstream.text) {
130
+ try {
131
+ raw = await upstream.text();
132
+ } catch (err) {
133
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
134
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'gemini', model });
135
+ throw wrapped;
136
+ }
137
+ }
138
+ const respBody = responseToBody(raw, upstream.status, upstream.headers, log);
139
+ trace?.record({ status: upstream.status, responseBody: respBody, upstreamMode: 'gemini', model, headers: upstream.headers });
140
+ return {
141
+ status: upstream.status,
142
+ body: respBody,
143
+ headers: copyGeminiResponseHeaders(upstream.headers),
144
+ };
145
+ };
146
+ }
147
+
148
+ module.exports = {
149
+ buildGeminiHandler,
150
+ copyGeminiResponseHeaders,
151
+ hasGeminiUpstreamCredential,
152
+ responseToBody,
153
+ parseModelAction,
154
+ };
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ // GET /v1/models — model-list probe passthrough (format-aware routing, no translation). Many clients (codex,
4
+ // opencode, cursor in OpenAI mode, OpenAI/Anthropic SDKs) hit GET /v1/models on startup to validate the endpoint
5
+ // and list models; without a route they get a 404 and may fail to initialize or fall back. Route by the client's
6
+ // intended provider: Anthropic clients send the `anthropic-version` header → Anthropic /v1/models; everyone else
7
+ // → OpenAI /v1/models (the convention's home). Forwarded verbatim to the native upstream, no body, no translation.
8
+ // Not traced: it is a metadata probe, not an LLM call.
9
+
10
+ function detectModelsProvider(headers = {}) {
11
+ const lower = {};
12
+ for (const [k, v] of Object.entries(headers || {})) lower[String(k).toLowerCase()] = v;
13
+ // anthropic-version (and anthropic-beta) are sent by every Anthropic SDK request and by nothing else.
14
+ if (lower['anthropic-version'] || lower['anthropic-beta']) return 'anthropic';
15
+ return 'openai';
16
+ }
17
+
18
+ function buildModelsHandler({ anthropicProxy, openAIProxy, logger } = {}) {
19
+ if (typeof anthropicProxy !== 'function' || typeof openAIProxy !== 'function') {
20
+ throw new Error('buildModelsHandler requires anthropicProxy(path,body,opts) + openAIProxy(path,body,opts)');
21
+ }
22
+ const log = logger || console;
23
+
24
+ return async ({ headers }) => {
25
+ const inboundHeaders = headers || {};
26
+ const provider = detectModelsProvider(inboundHeaders);
27
+ const [proxyFn, reqPath, mode] = provider === 'anthropic'
28
+ ? [anthropicProxy, '/v1/models', 'anthropic']
29
+ : [openAIProxy, '/models', 'openai'];
30
+
31
+ let up;
32
+ try {
33
+ up = await proxyFn(reqPath, null, { method: 'GET', inboundHeaders, upstreamMode: mode });
34
+ } catch (err) {
35
+ const status = Number(err && err.statusCode) || 502;
36
+ return { status, body: { error: (err && err.message) || 'models upstream request failed' } };
37
+ }
38
+
39
+ let raw = '';
40
+ try { raw = up.text ? await up.text() : ''; } catch { raw = ''; }
41
+ let body;
42
+ try {
43
+ body = raw ? JSON.parse(raw) : {};
44
+ } catch {
45
+ log.warn?.(JSON.stringify({ event: 'models_fallback', reason: 'upstream_non_json', upstream_status: up.status }));
46
+ body = { error: raw };
47
+ }
48
+ return { status: up.status, body };
49
+ };
50
+ }
51
+
52
+ module.exports = { buildModelsHandler, detectModelsProvider };
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ // Ollama native passthrough (local/self-hosted model server). Native paths POST /api/chat and /api/generate are
4
+ // forwarded verbatim to the Ollama upstream (EVOMAP_OLLAMA_BASE_URL, default 127.0.0.1:11434). Format-aware, no
5
+ // translation: an Ollama-shaped request goes to Ollama. Streaming is newline-delimited JSON (NDJSON), not SSE —
6
+ // the trace tee scans it the same way. apiPath is fixed per registration (/api/chat vs /api/generate). Ollama is
7
+ // typically auth-less; an optional bearer (EVOMAP_OLLAMA_API_KEY) covers a remote/protected instance.
8
+
9
+ const { createProxyTrace } = require('../trace/extractor');
10
+
11
+ function upstreamStatus(err, fallback = 502) {
12
+ const status = Number(err && err.statusCode);
13
+ return Number.isFinite(status) ? status : fallback;
14
+ }
15
+
16
+ function asUpstreamError(err, fallback = 502) {
17
+ if (err && err.statusCode && /^ollama upstream /.test(err.message || '')) return err;
18
+ const out = new Error('ollama upstream request failed');
19
+ out.statusCode = upstreamStatus(err, fallback);
20
+ out.cause = err;
21
+ return out;
22
+ }
23
+
24
+ function responseToBody(raw, status, headers, log) {
25
+ if (!raw) return {};
26
+ try {
27
+ return JSON.parse(raw);
28
+ } catch {
29
+ log.warn?.(JSON.stringify({
30
+ event: 'ollama_fallback',
31
+ reason: 'upstream_non_json',
32
+ upstream_status: status,
33
+ content_type: (headers && headers['content-type']) || '',
34
+ response_bytes: Buffer.byteLength(raw),
35
+ }));
36
+ return { error: raw };
37
+ }
38
+ }
39
+
40
+ function buildOllamaHandler({ ollamaProxy, logger, traceStore, onTraceQueued, apiPath = '/api/chat' } = {}) {
41
+ if (typeof ollamaProxy !== 'function') {
42
+ throw new Error('buildOllamaHandler requires ollamaProxy(path, body, opts)');
43
+ }
44
+ const log = logger || console;
45
+
46
+ return async ({ body, headers }) => {
47
+ const inboundHeaders = headers || {};
48
+ const originalModel = body && typeof body.model === 'string' ? body.model : null;
49
+
50
+ let trace = null;
51
+ try {
52
+ trace = createProxyTrace({
53
+ route: `POST ${apiPath}`,
54
+ headers: inboundHeaders,
55
+ body,
56
+ upstreamMode: 'ollama',
57
+ originalModel,
58
+ chosenModel: originalModel,
59
+ store: traceStore,
60
+ logger: traceStore ? log : null,
61
+ onTraceQueued,
62
+ });
63
+ } catch (_) { /* best-effort trace; never break the request */ }
64
+
65
+ let upstream;
66
+ try {
67
+ upstream = await ollamaProxy(apiPath, body, { inboundHeaders, upstreamMode: 'ollama' });
68
+ } catch (err) {
69
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
70
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'ollama', model: originalModel });
71
+ throw wrapped;
72
+ }
73
+
74
+ if (upstream.stream) {
75
+ const forwardHeaders = {};
76
+ const ct = upstream.headers && upstream.headers['content-type'];
77
+ if (ct) forwardHeaders['Content-Type'] = ct;
78
+ trace?.recordStreamStart({ status: upstream.status, upstreamMode: 'ollama', model: originalModel, headers: forwardHeaders });
79
+ return {
80
+ status: upstream.status,
81
+ // Tee the NDJSON body so the deferred trace captures the final chunk's eval counts + done_reason. Bytes unchanged.
82
+ stream: trace ? trace.observeStream(upstream.stream) : upstream.stream,
83
+ headers: forwardHeaders,
84
+ };
85
+ }
86
+
87
+ let raw = '';
88
+ if (upstream.text) {
89
+ try {
90
+ raw = await upstream.text();
91
+ } catch (err) {
92
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
93
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'ollama', model: originalModel });
94
+ throw wrapped;
95
+ }
96
+ }
97
+ const respBody = responseToBody(raw, upstream.status, upstream.headers, log);
98
+ trace?.record({ status: upstream.status, responseBody: respBody, upstreamMode: 'ollama', model: originalModel, headers: upstream.headers });
99
+ return { status: upstream.status, body: respBody };
100
+ };
101
+ }
102
+
103
+ module.exports = { buildOllamaHandler, responseToBody };
@@ -66,7 +66,11 @@ function copyOpenAIResponseHeaders(headers = {}) {
66
66
  return out;
67
67
  }
68
68
 
69
- function buildResponsesHandler({ openAIProxy, logger, traceStore, onTraceQueued } = {}) {
69
+ // Generic OpenAI passthrough handler. `upstreamPath` selects the OpenAI endpoint (/responses for codex's
70
+ // Responses API, /chat/completions for the Chat Completions API used by cursor's OpenAI mode + generic OpenAI
71
+ // clients). Both share the same upstream, auth, header allow-list, trace, and stream tee — the only difference
72
+ // is the path + the trace route label. No translation: each OpenAI dialect goes to its native OpenAI endpoint.
73
+ function buildResponsesHandler({ openAIProxy, logger, traceStore, onTraceQueued, upstreamPath = '/responses', traceRoute = 'POST /v1/responses' } = {}) {
70
74
  if (typeof openAIProxy !== 'function') {
71
75
  throw new Error('buildResponsesHandler requires openAIProxy(path, body, opts)');
72
76
  }
@@ -82,7 +86,7 @@ function buildResponsesHandler({ openAIProxy, logger, traceStore, onTraceQueued
82
86
  let trace = null;
83
87
  try {
84
88
  trace = createProxyTrace({
85
- route: 'POST /v1/responses',
89
+ route: traceRoute,
86
90
  headers: inboundHeaders,
87
91
  body,
88
92
  upstreamMode: 'openai',
@@ -96,7 +100,7 @@ function buildResponsesHandler({ openAIProxy, logger, traceStore, onTraceQueued
96
100
 
97
101
  let upstream;
98
102
  try {
99
- upstream = await openAIProxy('/responses', body, {
103
+ upstream = await openAIProxy(upstreamPath, body, {
100
104
  inboundHeaders,
101
105
  upstreamMode: 'openai',
102
106
  });
@@ -151,8 +155,15 @@ function buildResponsesHandler({ openAIProxy, logger, traceStore, onTraceQueued
151
155
  };
152
156
  }
153
157
 
158
+ // OpenAI Chat Completions ingress (cursor's OpenAI mode + generic OpenAI clients). Same OpenAI upstream as the
159
+ // Responses handler, just the /chat/completions endpoint — point an OpenAI-Chat client's base URL at the proxy.
160
+ function buildChatCompletionsHandler(opts = {}) {
161
+ return buildResponsesHandler({ ...opts, upstreamPath: '/chat/completions', traceRoute: 'POST /v1/chat/completions' });
162
+ }
163
+
154
164
  module.exports = {
155
165
  buildResponsesHandler,
166
+ buildChatCompletionsHandler,
156
167
  copyOpenAIResponseHeaders,
157
168
  hasOpenAIUpstreamCredential,
158
169
  responseToBody,
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ // Vertex AI Gemini passthrough (enterprise GCP). Same Gemini request/response body as the AI Studio route, but
4
+ // the native Vertex path — POST /v1/projects/<project>/locations/<location>/publishers/google/models/<model>:
5
+ // generateContent | :streamGenerateContent — a region-specific upstream (<location>-aiplatform.googleapis.com),
6
+ // and OAuth Bearer auth (EVOMAP_VERTEX_ACCESS_TOKEN). Forwarded verbatim, no translation. Trace reuses the Gemini
7
+ // shape (usageMetadata + candidates[].finishReason), so only the path + base + auth differ from the AI Studio route.
8
+
9
+ const { createProxyTrace } = require('../trace/extractor');
10
+ const { parseModelAction } = require('./gemini_route');
11
+
12
+ function upstreamStatus(err, fallback = 502) {
13
+ const status = Number(err && err.statusCode);
14
+ return Number.isFinite(status) ? status : fallback;
15
+ }
16
+
17
+ function asUpstreamError(err, fallback = 502) {
18
+ if (err && err.statusCode && /^vertex /.test(err.message || '')) return err;
19
+ const out = new Error('vertex upstream request failed');
20
+ out.statusCode = upstreamStatus(err, fallback);
21
+ out.cause = err;
22
+ return out;
23
+ }
24
+
25
+ function responseToBody(raw, status, headers, log) {
26
+ if (!raw) return {};
27
+ try {
28
+ return JSON.parse(raw);
29
+ } catch {
30
+ log.warn?.(JSON.stringify({
31
+ event: 'vertex_fallback', reason: 'upstream_non_json', upstream_status: status,
32
+ content_type: (headers && headers['content-type']) || '', response_bytes: Buffer.byteLength(raw),
33
+ }));
34
+ return { error: raw };
35
+ }
36
+ }
37
+
38
+ // Region-specific Vertex base. EVOMAP_VERTEX_BASE_URL overrides (e.g. the global aiplatform endpoint); otherwise
39
+ // derive <location>-aiplatform.googleapis.com. `global` uses the un-prefixed host.
40
+ function vertexBaseUrl(location) {
41
+ const override = (process.env.EVOMAP_VERTEX_BASE_URL || '').trim();
42
+ if (override) return override.replace(/\/+$/, '');
43
+ const loc = String(location || '').trim();
44
+ if (!loc || loc === 'global') return 'https://aiplatform.googleapis.com';
45
+ return `https://${loc}-aiplatform.googleapis.com`;
46
+ }
47
+
48
+ function buildVertexHandler({ vertexProxy, logger, traceStore, onTraceQueued } = {}) {
49
+ if (typeof vertexProxy !== 'function') {
50
+ throw new Error('buildVertexHandler requires vertexProxy(path, body, opts)');
51
+ }
52
+ const log = logger || console;
53
+
54
+ return async ({ body, headers, params, query }) => {
55
+ const inboundHeaders = headers || {};
56
+ const project = (params && params.project) || '';
57
+ const location = (params && params.location) || '';
58
+ const modelAction = (params && params.modelAction) || '';
59
+ const { model } = parseModelAction(modelAction);
60
+ const baseUrl = vertexBaseUrl(location);
61
+ const qs = query && Object.keys(query).length ? '?' + new URLSearchParams(query).toString() : '';
62
+ const reqPath = `/v1/projects/${project}/locations/${location}/publishers/google/models/${modelAction}${qs}`;
63
+
64
+ let trace = null;
65
+ try {
66
+ trace = createProxyTrace({
67
+ route: `POST /v1/projects/${project}/locations/${location}/publishers/google/models/${modelAction}`,
68
+ headers: inboundHeaders, body, upstreamMode: 'vertex', originalModel: model, chosenModel: model,
69
+ store: traceStore, logger: traceStore ? log : null, onTraceQueued,
70
+ });
71
+ } catch (_) { /* best-effort trace */ }
72
+
73
+ let upstream;
74
+ try {
75
+ upstream = await vertexProxy(reqPath, body, { baseUrl, inboundHeaders, upstreamMode: 'vertex' });
76
+ } catch (err) {
77
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
78
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'vertex', model });
79
+ throw wrapped;
80
+ }
81
+
82
+ if (upstream.stream) {
83
+ const forwardHeaders = {};
84
+ const ct = upstream.headers && upstream.headers['content-type'];
85
+ if (ct) forwardHeaders['Content-Type'] = ct;
86
+ trace?.recordStreamStart({ status: upstream.status, upstreamMode: 'vertex', model, headers: forwardHeaders });
87
+ return {
88
+ status: upstream.status,
89
+ stream: trace ? trace.observeStream(upstream.stream) : upstream.stream,
90
+ headers: forwardHeaders,
91
+ };
92
+ }
93
+
94
+ let raw = '';
95
+ if (upstream.text) {
96
+ try {
97
+ raw = await upstream.text();
98
+ } catch (err) {
99
+ const wrapped = asUpstreamError(err, upstreamStatus(err));
100
+ trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'vertex', model });
101
+ throw wrapped;
102
+ }
103
+ }
104
+ const respBody = responseToBody(raw, upstream.status, upstream.headers, log);
105
+ trace?.record({ status: upstream.status, responseBody: respBody, upstreamMode: 'vertex', model, headers: upstream.headers });
106
+ return { status: upstream.status, body: respBody };
107
+ };
108
+ }
109
+
110
+ module.exports = { buildVertexHandler, vertexBaseUrl };
@@ -10,6 +10,12 @@ function buildRoutes(store, proxyHandlers, taskMonitor, extensions) {
10
10
  sessionHandler,
11
11
  messagesHandler,
12
12
  responsesHandler,
13
+ geminiHandler,
14
+ chatCompletionsHandler,
15
+ modelsHandler,
16
+ ollamaChatHandler,
17
+ ollamaGenerateHandler,
18
+ vertexHandler,
13
19
  } = extensions || {};
14
20
  const routes = {
15
21
  // -- Mailbox --
@@ -476,6 +482,31 @@ function buildRoutes(store, proxyHandlers, taskMonitor, extensions) {
476
482
  if (responsesHandler) {
477
483
  routes['POST /v1/responses'] = responsesHandler;
478
484
  }
485
+ if (geminiHandler) {
486
+ // Native Gemini path: model + action (generateContent | streamGenerateContent) are one path segment
487
+ // (`<model>:<action>`), matched as :modelAction and split by the handler.
488
+ routes['POST /v1beta/models/:modelAction'] = geminiHandler;
489
+ }
490
+ if (chatCompletionsHandler) {
491
+ // OpenAI Chat Completions ingress (cursor's OpenAI mode + generic OpenAI clients) → OpenAI upstream.
492
+ routes['POST /v1/chat/completions'] = chatCompletionsHandler;
493
+ }
494
+ if (modelsHandler) {
495
+ // Model-list probe (codex/opencode/cursor/SDKs hit it on startup) → routed by anthropic-version header to
496
+ // the Anthropic or OpenAI upstream's /v1/models, so the probe never 404s.
497
+ routes['GET /v1/models'] = modelsHandler;
498
+ }
499
+ if (ollamaChatHandler) {
500
+ // Ollama native ingress (local/self-hosted models) → Ollama upstream, NDJSON streaming.
501
+ routes['POST /api/chat'] = ollamaChatHandler;
502
+ }
503
+ if (ollamaGenerateHandler) {
504
+ routes['POST /api/generate'] = ollamaGenerateHandler;
505
+ }
506
+ if (vertexHandler) {
507
+ // Vertex AI Gemini native path: project/location/model:action across fixed segments + :modelAction.
508
+ routes['POST /v1/projects/:project/locations/:location/publishers/google/models/:modelAction'] = vertexHandler;
509
+ }
479
510
 
480
511
  return routes;
481
512
  }