@evomap/evolver 1.89.20 → 2.0.0-beta.0

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 (231) hide show
  1. package/README.md +27 -564
  2. package/bin/evolver-llm-proxy.js +3 -0
  3. package/bin/evolver-mcp.js +2 -0
  4. package/bin/evolver-proxy.js +3 -0
  5. package/bin/evolver.js +4 -0
  6. package/index.js +1 -3586
  7. package/package.json +32 -62
  8. package/CONTRIBUTING.md +0 -19
  9. package/LICENSE +0 -641
  10. package/README.ja-JP.md +0 -521
  11. package/README.ko-KR.md +0 -520
  12. package/README.zh-CN.md +0 -531
  13. package/SKILL.md +0 -365
  14. package/assets/cover.png +0 -0
  15. package/assets/gep/genes.seed.json +0 -496
  16. package/conformance/savings-core/constants.json +0 -30
  17. package/conformance/savings-core/golden-vectors.json +0 -333
  18. package/scripts/a2a_export.js +0 -63
  19. package/scripts/a2a_ingest.js +0 -79
  20. package/scripts/a2a_promote.js +0 -118
  21. package/scripts/analyze_by_skill.js +0 -121
  22. package/scripts/build_binaries.js +0 -479
  23. package/scripts/check-changelog.js +0 -166
  24. package/scripts/extract_log.js +0 -85
  25. package/scripts/generate_history.js +0 -75
  26. package/scripts/gep_append_event.js +0 -96
  27. package/scripts/gep_personality_report.js +0 -234
  28. package/scripts/human_report.js +0 -147
  29. package/scripts/recall-verify-report.js +0 -234
  30. package/scripts/recover_loop.js +0 -61
  31. package/scripts/refresh_stars_badge.js +0 -168
  32. package/scripts/seed-merchants.js +0 -91
  33. package/scripts/skill2recipes.js +0 -118
  34. package/scripts/suggest_version.js +0 -89
  35. package/scripts/validate-modules.js +0 -38
  36. package/scripts/validate-suite.js +0 -78
  37. package/skills/_meta/SKILL.md +0 -41
  38. package/skills/index.json +0 -14
  39. package/src/adapters/claudeCode.js +0 -194
  40. package/src/adapters/codex.js +0 -216
  41. package/src/adapters/cursor.js +0 -91
  42. package/src/adapters/hookAdapter.js +0 -469
  43. package/src/adapters/kiro.js +0 -195
  44. package/src/adapters/opencode.js +0 -326
  45. package/src/adapters/scripts/_lockPaths.js +0 -74
  46. package/src/adapters/scripts/_memoryFiltering.js +0 -35
  47. package/src/adapters/scripts/_runtimePaths.js +0 -440
  48. package/src/adapters/scripts/evolver-session-end.js +0 -321
  49. package/src/adapters/scripts/evolver-session-start.js +0 -587
  50. package/src/adapters/scripts/evolver-signal-detect.js +0 -98
  51. package/src/adapters/scripts/evolver-task-recall.js +0 -173
  52. package/src/atp/atpExecute.js +0 -283
  53. package/src/atp/atpTaskPickup.js +0 -233
  54. package/src/atp/autoBuyer.js +0 -382
  55. package/src/atp/autoDeliver.js +0 -215
  56. package/src/atp/cli.js +0 -354
  57. package/src/atp/cliAutobuyPrompt.js +0 -154
  58. package/src/atp/consumerAgent.js +0 -157
  59. package/src/atp/defaultHandler.js +0 -69
  60. package/src/atp/heartbeatSignalsHandler.js +0 -254
  61. package/src/atp/hubClient.js +0 -317
  62. package/src/atp/index.js +0 -38
  63. package/src/atp/merchantAgent.js +0 -118
  64. package/src/atp/protocol.js +0 -41
  65. package/src/atp/questionComposer.js +0 -133
  66. package/src/atp/serviceHelper.js +0 -92
  67. package/src/canary.js +0 -13
  68. package/src/config.js +0 -351
  69. package/src/evolve/guards.js +0 -1
  70. package/src/evolve/pipeline/collect.js +0 -1
  71. package/src/evolve/pipeline/dispatch.js +0 -1
  72. package/src/evolve/pipeline/enrich.js +0 -1
  73. package/src/evolve/pipeline/hub.js +0 -1
  74. package/src/evolve/pipeline/select.js +0 -1
  75. package/src/evolve/pipeline/signals.js +0 -1
  76. package/src/evolve/utils.js +0 -1
  77. package/src/evolve.js +0 -1
  78. package/src/experiment/agentRunner.js +0 -229
  79. package/src/experiment/cli.js +0 -159
  80. package/src/experiment/comparison.js +0 -233
  81. package/src/experiment/metrics.js +0 -75
  82. package/src/forceUpdate.js +0 -991
  83. package/src/gep/a2a.js +0 -173
  84. package/src/gep/a2aProtocol.js +0 -1
  85. package/src/gep/analyzer.js +0 -35
  86. package/src/gep/antiAbuseTelemetry.js +0 -1
  87. package/src/gep/assetCallLog.js +0 -197
  88. package/src/gep/assetStore.js +0 -723
  89. package/src/gep/assets.js +0 -36
  90. package/src/gep/autoDistillConv.js +0 -1
  91. package/src/gep/autoDistillLlm.js +0 -1
  92. package/src/gep/bridge.js +0 -138
  93. package/src/gep/candidateEval.js +0 -1
  94. package/src/gep/candidates.js +0 -1
  95. package/src/gep/claimNudge.js +0 -121
  96. package/src/gep/cliContracts.js +0 -1190
  97. package/src/gep/contentHash.js +0 -1
  98. package/src/gep/conversationDistiller.js +0 -1
  99. package/src/gep/conversationSniffer.js +0 -1
  100. package/src/gep/crypto.js +0 -1
  101. package/src/gep/curriculum.js +0 -1
  102. package/src/gep/deviceId.js +0 -1
  103. package/src/gep/directoryClient.js +0 -115
  104. package/src/gep/envFingerprint.js +0 -1
  105. package/src/gep/epigenetics.js +0 -1
  106. package/src/gep/execBridge.js +0 -1
  107. package/src/gep/executionTrace.js +0 -291
  108. package/src/gep/explore.js +0 -1
  109. package/src/gep/featureFlags.js +0 -121
  110. package/src/gep/gitOps.js +0 -265
  111. package/src/gep/hash.js +0 -1
  112. package/src/gep/hostErrorClassifier.js +0 -34
  113. package/src/gep/hubFetch.js +0 -1
  114. package/src/gep/hubReview.js +0 -1
  115. package/src/gep/hubSearch.js +0 -1
  116. package/src/gep/hubVerify.js +0 -1
  117. package/src/gep/idleScheduler.js +0 -400
  118. package/src/gep/issueReporter.js +0 -416
  119. package/src/gep/learningSignals.js +0 -1
  120. package/src/gep/llmReview.js +0 -92
  121. package/src/gep/localStateAwareness.js +0 -243
  122. package/src/gep/mailboxTransport.js +0 -119
  123. package/src/gep/memoryGraph.js +0 -1
  124. package/src/gep/memoryGraphAdapter.js +0 -1
  125. package/src/gep/mutation.js +0 -1
  126. package/src/gep/narrativeMemory.js +0 -1
  127. package/src/gep/oauthLogin.js +0 -181
  128. package/src/gep/openPRRegistry.js +0 -1
  129. package/src/gep/paths.js +0 -522
  130. package/src/gep/personality.js +0 -1
  131. package/src/gep/policyCheck.js +0 -1
  132. package/src/gep/portable.js +0 -103
  133. package/src/gep/privacyClient.js +0 -235
  134. package/src/gep/prompt.js +0 -1
  135. package/src/gep/questionGenerator.js +0 -518
  136. package/src/gep/recallInject.js +0 -1
  137. package/src/gep/recallVerifier.js +0 -1
  138. package/src/gep/reflection.js +0 -1
  139. package/src/gep/sanitize.js +0 -264
  140. package/src/gep/savingsCore.js +0 -1
  141. package/src/gep/schemas/capsule.js +0 -170
  142. package/src/gep/schemas/gene.js +0 -154
  143. package/src/gep/schemas/index.js +0 -8
  144. package/src/gep/schemas/protocol.js +0 -51
  145. package/src/gep/schemas/task.js +0 -74
  146. package/src/gep/selector.js +0 -1
  147. package/src/gep/selfPR.js +0 -469
  148. package/src/gep/signals.js +0 -776
  149. package/src/gep/skill2gep.js +0 -1056
  150. package/src/gep/skill2gepAudit.js +0 -303
  151. package/src/gep/skill2recipes.js +0 -511
  152. package/src/gep/skillDistiller.js +0 -1
  153. package/src/gep/skillPublisher.js +0 -358
  154. package/src/gep/solidify.js +0 -1
  155. package/src/gep/strategy.js +0 -1
  156. package/src/gep/taskReceiver.js +0 -575
  157. package/src/gep/tokenSavings.js +0 -1
  158. package/src/gep/trajectoryExport.js +0 -1
  159. package/src/gep/validationReport.js +0 -55
  160. package/src/gep/validator/index.js +0 -411
  161. package/src/gep/validator/reporter.js +0 -210
  162. package/src/gep/validator/sandboxExecutor.js +0 -480
  163. package/src/gep/validator/stakeBootstrap.js +0 -357
  164. package/src/gep/workspaceKeychain.js +0 -1
  165. package/src/ops/cleanup.js +0 -80
  166. package/src/ops/commentary.js +0 -60
  167. package/src/ops/health_check.js +0 -104
  168. package/src/ops/index.js +0 -11
  169. package/src/ops/innovation.js +0 -67
  170. package/src/ops/lifecycle.js +0 -798
  171. package/src/ops/self_repair.js +0 -76
  172. package/src/ops/skills_monitor.js +0 -147
  173. package/src/ops/trigger.js +0 -33
  174. package/src/proxy/clientSettings.js +0 -405
  175. package/src/proxy/envelope.js +0 -59
  176. package/src/proxy/extensions/dmHandler.js +0 -45
  177. package/src/proxy/extensions/sessionHandler.js +0 -141
  178. package/src/proxy/extensions/skillUpdater.js +0 -64
  179. package/src/proxy/extensions/traceControl.js +0 -1
  180. package/src/proxy/index.js +0 -1395
  181. package/src/proxy/inject.js +0 -1
  182. package/src/proxy/lifecycle/manager.js +0 -1568
  183. package/src/proxy/mailbox/state.js +0 -207
  184. package/src/proxy/mailbox/store.js +0 -590
  185. package/src/proxy/router/cache_passthrough.js +0 -26
  186. package/src/proxy/router/features.js +0 -84
  187. package/src/proxy/router/gemini_route.js +0 -154
  188. package/src/proxy/router/messages_route.js +0 -535
  189. package/src/proxy/router/model_router.js +0 -113
  190. package/src/proxy/router/models_route.js +0 -52
  191. package/src/proxy/router/ollama_route.js +0 -103
  192. package/src/proxy/router/responses_route.js +0 -170
  193. package/src/proxy/router/vertex_route.js +0 -110
  194. package/src/proxy/server/http.js +0 -363
  195. package/src/proxy/server/routes.js +0 -558
  196. package/src/proxy/server/settings.js +0 -115
  197. package/src/proxy/sync/engine.js +0 -179
  198. package/src/proxy/sync/inbound.js +0 -211
  199. package/src/proxy/sync/outbound.js +0 -320
  200. package/src/proxy/task/monitor.js +0 -131
  201. package/src/proxy/trace/extractor.js +0 -1
  202. package/src/proxy/trace/usage.js +0 -1
  203. package/src/webui/client/clientJs/assets.js +0 -111
  204. package/src/webui/client/clientJs/bootstrap.js +0 -92
  205. package/src/webui/client/clientJs/common.js +0 -77
  206. package/src/webui/client/clientJs/i18n.js +0 -366
  207. package/src/webui/client/clientJs/index.js +0 -35
  208. package/src/webui/client/clientJs/interactions.js +0 -351
  209. package/src/webui/client/clientJs/overview.js +0 -152
  210. package/src/webui/client/clientJs/personality.js +0 -285
  211. package/src/webui/client/clientJs/pipelines.js +0 -330
  212. package/src/webui/client/indexHtml.js +0 -221
  213. package/src/webui/client/static.js +0 -23
  214. package/src/webui/client/stylesCss.js +0 -639
  215. package/src/webui/client/vendor/README.md +0 -15
  216. package/src/webui/client/vendor/echarts.min.js +0 -45
  217. package/src/webui/index.js +0 -14
  218. package/src/webui/observer/assets.js +0 -146
  219. package/src/webui/observer/index.js +0 -37
  220. package/src/webui/observer/interactions.js +0 -127
  221. package/src/webui/observer/jsonl.js +0 -75
  222. package/src/webui/observer/paths.js +0 -46
  223. package/src/webui/observer/personality.js +0 -43
  224. package/src/webui/observer/pipelineEvents.js +0 -58
  225. package/src/webui/observer/redact.js +0 -63
  226. package/src/webui/observer/runs.js +0 -356
  227. package/src/webui/observer/safety.js +0 -57
  228. package/src/webui/observer/skills.js +0 -70
  229. package/src/webui/observer/status.js +0 -71
  230. package/src/webui/server/http.js +0 -138
  231. package/src/webui/server/routes.js +0 -41
@@ -1,113 +0,0 @@
1
- 'use strict';
2
-
3
- // Phase C of the EvoX multi-tier router. The authoritative algorithm
4
- // lives in Rust at
5
- // evox/crates/evox-agent-core/src/model_router.rs
6
- // and ships a generated JSON fixture at
7
- // evox/crates/evox-agent-core/tests/fixtures/model_router_cases.json
8
- // A vendored copy of that fixture (test/fixtures/model_router_cases.json)
9
- // pins this port byte-for-byte; CI diffs against a regenerated copy so
10
- // silent drift turns red.
11
- //
12
- // Why a fresh module under src/proxy/router/ and not a fold into an
13
- // existing router-ish helper: src/proxy/ has no prior router/classifier
14
- // concept (mailbox/, sync/, task/, extensions/, lifecycle/ all sit at a
15
- // different layer). A first-class subdir is the cheapest place to grow
16
- // the Phase C pieces (cache_passthrough, anthropic egress) without
17
- // muddying the proxy core.
18
-
19
- const REASONS = Object.freeze({
20
- ROUTER_DISABLED: 'router_disabled',
21
- HARD_PINNED: 'hard_pinned',
22
- GENE_HINT: 'gene_hint',
23
- POST_TOOL_RESULT_SYNTHESIS: 'post_tool_result_synthesis',
24
- USER_REQUESTED_PLANNING: 'user_requested_planning',
25
- HIGH_TOOL_USE_DENSITY: 'high_tool_use_density',
26
- TRIVIAL_LOOKUP: 'trivial_lookup',
27
- DEFAULT_TIER: 'default_tier',
28
- ESCALATED_FROM_HISTORY: 'escalated_from_history',
29
- });
30
-
31
- const TIER_ORDER = Object.freeze({ cheap: 0, mid: 1, expensive: 2 });
32
-
33
- function tierStepUp(tier) {
34
- if (tier === 'cheap') return 'mid';
35
- if (tier === 'mid') return 'expensive';
36
- return 'expensive';
37
- }
38
-
39
- function classify(features, config) {
40
- // Parity invariant with model_router.rs:340 — branch order matters.
41
- // post_tool_result_synthesis must win over high_tool_use_density when
42
- // both signal: the synthesis turn is just summarising tool output.
43
- if (
44
- features.last_user_is_tool_result_only &&
45
- features.last_assistant_stop_reason === 'ToolUse'
46
- ) {
47
- return ['cheap', REASONS.POST_TOOL_RESULT_SYNTHESIS];
48
- }
49
- if (features.user_requested_planning) {
50
- return ['expensive', REASONS.USER_REQUESTED_PLANNING];
51
- }
52
- if (features.last_assistant_tool_call_count > 3) {
53
- return ['expensive', REASONS.HIGH_TOOL_USE_DENSITY];
54
- }
55
- if (features.user_simple_lookup) {
56
- return ['cheap', REASONS.TRIVIAL_LOOKUP];
57
- }
58
- return [config.default_tier, REASONS.DEFAULT_TIER];
59
- }
60
-
61
- function maybeEscalate(base, history) {
62
- // Stalled-turn signal from model_router.rs:373: the last decision
63
- // produced <50 output tokens with no tool call. Bump one tier up,
64
- // never above expensive, and never weaker than what classify chose.
65
- if (!history || history.length === 0) return [base, null];
66
- const last = history[history.length - 1];
67
- const stalled = last.output_tokens < 50 && !last.had_tool_call;
68
- if (!stalled) return [base, null];
69
- if (last.tier === 'expensive') return [base, null];
70
- const target = tierStepUp(last.tier);
71
- if (TIER_ORDER[target] > TIER_ORDER[base]) {
72
- return [target, last.tier];
73
- }
74
- return [base, null];
75
- }
76
-
77
- function pickForTurn(input) {
78
- const { features, router_state, config } = input;
79
- const geneHint = input.gene_hint;
80
-
81
- if (config.disable) {
82
- return {
83
- tier: config.default_tier,
84
- reason: REASONS.ROUTER_DISABLED,
85
- escalated_from: null,
86
- };
87
- }
88
- if (config.hard_pin_after_plan && router_state && router_state.pinned) {
89
- return {
90
- tier: router_state.pinned,
91
- reason: REASONS.HARD_PINNED,
92
- escalated_from: null,
93
- };
94
- }
95
- if (geneHint) {
96
- return {
97
- tier: geneHint,
98
- reason: REASONS.GENE_HINT,
99
- escalated_from: null,
100
- };
101
- }
102
- const [baseTier, baseReason] = classify(features, config);
103
- const history = router_state ? router_state.history : [];
104
- const [escalatedTier, escalatedFrom] = maybeEscalate(baseTier, history);
105
- const reason = escalatedFrom !== null ? REASONS.ESCALATED_FROM_HISTORY : baseReason;
106
- return {
107
- tier: escalatedTier,
108
- reason,
109
- escalated_from: escalatedFrom,
110
- };
111
- }
112
-
113
- module.exports = { pickForTurn, REASONS };
@@ -1,52 +0,0 @@
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 };
@@ -1,103 +0,0 @@
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 };
@@ -1,170 +0,0 @@
1
- 'use strict';
2
-
3
- const { createProxyTrace } = require('../trace/extractor');
4
-
5
- const OPENAI_RESPONSE_HEADER_ALLOWLIST = new Set([
6
- 'openai-processing-ms',
7
- 'openai-version',
8
- 'retry-after',
9
- 'x-request-id',
10
- ]);
11
-
12
- function hasOpenAIUpstreamCredential() {
13
- if (process.env.EVOMAP_OPENAI_API_KEY || process.env.OPENAI_API_KEY) return true;
14
- return false;
15
- }
16
-
17
- function upstreamStatus(err, fallback = 502) {
18
- const status = Number(err && err.statusCode);
19
- return Number.isFinite(status) ? status : fallback;
20
- }
21
-
22
- function safeOpenAIConfigDiagnostic(err) {
23
- const message = err && typeof err.message === 'string' ? err.message : '';
24
- if (message.startsWith('[proxy] EVOMAP_OPENAI_BASE_URL ')) return message;
25
- return '';
26
- }
27
-
28
- function asUpstreamError(err, fallback = 502) {
29
- if (err && err.statusCode && /^openai upstream /.test(err.message || '')) return err;
30
- const diagnostic = safeOpenAIConfigDiagnostic(err);
31
- const message = diagnostic
32
- ? `openai upstream request failed: ${diagnostic}`
33
- : 'openai upstream request failed';
34
- const out = new Error(message);
35
- out.statusCode = upstreamStatus(err, fallback);
36
- out.cause = err;
37
- return out;
38
- }
39
-
40
- function responseToBody(raw, status, headers, log) {
41
- if (!raw) return {};
42
- try {
43
- return JSON.parse(raw);
44
- } catch {
45
- log.warn?.(JSON.stringify({
46
- event: 'openai_responses_fallback',
47
- reason: 'upstream_non_json',
48
- upstream_status: status,
49
- content_type: headers && headers['content-type'] || '',
50
- response_bytes: Buffer.byteLength(raw),
51
- }));
52
- return { error: raw };
53
- }
54
- }
55
-
56
- function copyOpenAIResponseHeaders(headers = {}) {
57
- const out = {};
58
- for (const [name, value] of Object.entries(headers || {})) {
59
- const lower = String(name || '').toLowerCase();
60
- if (!OPENAI_RESPONSE_HEADER_ALLOWLIST.has(lower) && !lower.startsWith('x-ratelimit-')) continue;
61
- if (value === undefined || value === null) continue;
62
- const headerValue = Array.isArray(value) ? value.join(', ') : String(value);
63
- if (/[\r\n]/.test(headerValue)) continue;
64
- out[lower] = headerValue;
65
- }
66
- return out;
67
- }
68
-
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' } = {}) {
74
- if (typeof openAIProxy !== 'function') {
75
- throw new Error('buildResponsesHandler requires openAIProxy(path, body, opts)');
76
- }
77
- const log = logger || console;
78
-
79
- return async ({ body, headers }) => {
80
- const inboundHeaders = headers || {};
81
- if (!hasOpenAIUpstreamCredential()) {
82
- throw Object.assign(new Error('openai api key required'), { statusCode: 401 });
83
- }
84
-
85
- const originalModel = body && typeof body.model === 'string' ? body.model : null;
86
- let trace = null;
87
- try {
88
- trace = createProxyTrace({
89
- route: traceRoute,
90
- headers: inboundHeaders,
91
- body,
92
- upstreamMode: 'openai',
93
- originalModel,
94
- chosenModel: originalModel,
95
- store: traceStore,
96
- logger: traceStore ? log : null,
97
- onTraceQueued,
98
- });
99
- } catch (_) { /* best-effort trace; never break the request */ }
100
-
101
- let upstream;
102
- try {
103
- upstream = await openAIProxy(upstreamPath, body, {
104
- inboundHeaders,
105
- upstreamMode: 'openai',
106
- });
107
- } catch (err) {
108
- const wrapped = asUpstreamError(err, upstreamStatus(err));
109
- trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'openai', model: originalModel });
110
- throw wrapped;
111
- }
112
-
113
- if (upstream.stream) {
114
- const forwardHeaders = copyOpenAIResponseHeaders(upstream.headers);
115
- const ct = upstream.headers && upstream.headers['content-type'];
116
- if (ct) forwardHeaders['Content-Type'] = ct;
117
- trace?.recordStreamStart({
118
- status: upstream.status,
119
- upstreamMode: 'openai',
120
- model: originalModel,
121
- headers: forwardHeaders,
122
- });
123
- return {
124
- status: upstream.status,
125
- // Tee the codex SSE body so the deferred trace captures usage + response.id from response.completed.
126
- // Bytes forward unchanged; emits once on stream end/cancel/error.
127
- stream: trace ? trace.observeStream(upstream.stream) : upstream.stream,
128
- headers: forwardHeaders,
129
- };
130
- }
131
-
132
- let raw = '';
133
- if (upstream.text) {
134
- try {
135
- raw = await upstream.text();
136
- } catch (err) {
137
- const wrapped = asUpstreamError(err, upstreamStatus(err));
138
- trace?.record({ status: wrapped.statusCode, error: wrapped, upstreamMode: 'openai', model: originalModel });
139
- throw wrapped;
140
- }
141
- }
142
- const respBody = responseToBody(raw, upstream.status, upstream.headers, log);
143
- trace?.record({
144
- status: upstream.status,
145
- responseBody: respBody,
146
- upstreamMode: 'openai',
147
- model: originalModel,
148
- headers: upstream.headers,
149
- });
150
- return {
151
- status: upstream.status,
152
- body: respBody,
153
- headers: copyOpenAIResponseHeaders(upstream.headers),
154
- };
155
- };
156
- }
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
-
164
- module.exports = {
165
- buildResponsesHandler,
166
- buildChatCompletionsHandler,
167
- copyOpenAIResponseHeaders,
168
- hasOpenAIUpstreamCredential,
169
- responseToBody,
170
- };
@@ -1,110 +0,0 @@
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 };