Files
chat/api/server/services/Config/loadCustomConfig.js
zeekay 551236b1a5 route: one namespace — everything chat serves lives under /v1/chat
Five things answered outside /v1/chat/. Four of them are chat's; they move.

  /health                -> /v1/chat/health
  POST /oauth/iam/session-> POST /v1/chat/auth/iam/session   (it is auth)
  GET  /oauth/openid[/callback], /oauth/error
                         -> /v1/chat/auth/openid[/callback], /v1/chat/auth/error
  /images/               -> /v1/chat/images/

The fifth — the built assets at / and the SPA catch-all — is the SPA's, and
stays. Every caller moved in the same commit: api-endpoints (health, iamSession),
the metrics + telemetry health filter, the helm probes, the PR-preview workflow,
the PWA nav-fallback denylist. `ErrorController` matched a failed OIDC callback
by the substring '/oauth/', which the move would have silently broken; it now
matches the route.

Images are the one persisted case: a conversation stores the served path, and
history is immutable. New writes emit /v1/chat/images/…; /images/* answers one
permanent redirect; `isServedImage` (data-provider, the one place that knows the
namespace) recognises both. Local deletion maps the served path back to disk.

Two routers were written, tested, advertised to the browser — and never mounted,
so both were a guaranteed 404: skills (types say /v1/chat/skills) and the RUM
OTLP proxy (`rum/proxy` advertises /v1/chat/rum). Mounted where they said.

Deleted, with zero callers: server/experimental.js — a drifted second copy of
the whole mount table, still referencing a router that no longer exists, that
would have silently absorbed this move and diverged again; and nginx.hanzo.conf,
referenced by no compose/Dockerfile/chart, whose own /health shadowed chat's.

Gates collapsed to their one behavior, and the env deleted:

  ALLOW_SOCIAL_LOGIN     IAM is the one identity provider; false produced a
                         server with no way to sign in. socialLogins.js is now
                         iamLogin.js — one name for one thing.
  CONTINUE_ON_UNCAUGHT_EXCEPTION  keeps a process alive in an unknown state
                         instead of letting the kubelet replace it.
  CONFIG_BYPASS_VALIDATION        boots on invalid config, on request.
  MCP_SKIP_CODE_CHALLENGE_CHECK   turns off PKCE verification.
  OPENID_JWKS_URL_CACHE_ENABLED   read as `isEnabled(x) || true` — never off.
                         A second, differently-defaulted read lived in
                         remoteAgentAuth; both are now just on.
  NO_INDEX               a third boolean idiom for a header we always want.
  DISABLE_COMPRESSION, ENABLE_IMAGE_OUTPUT_GZIP_SCAN — we write these images
                         ourselves, as PNG/GIF; none is gzipped on disk.

Tests fail without the change: the auth router spec (6 of 7) against the old
router, the static spec against the old env-gated one, the config spec now sets
CONFIG_BYPASS_VALIDATION=true and still expects the exit, the error spec against
the '/oauth/' matcher, and index.spec asserts the top level serves HTML — so a
probe or caller left behind fails loudly instead of looking green.
2026-07-26 17:04:33 -07:00

173 lines
5.7 KiB
JavaScript

const path = require('path');
const axios = require('axios');
const yaml = require('js-yaml');
const keyBy = require('lodash/keyBy');
const { loadYaml } = require('@hanzochat/api');
const { logger } = require('@hanzochat/data-schemas');
const {
configSchema,
paramSettings,
EImageOutputType,
agentParamSettings,
validateSettingDefinitions,
} = require('@hanzochat/data-provider');
const projectRoot = path.resolve(__dirname, '..', '..', '..', '..');
const defaultConfigPath = path.resolve(projectRoot, 'chat.yaml');
let i = 0;
/**
* Load custom configuration files and caches the object if the `cache` field at root is true.
* Validation via parsing the config file with the config schema.
* @function loadCustomConfig
* @returns {Promise<TCustomConfig | null>} A promise that resolves to null or the custom config object.
* */
async function loadCustomConfig(printConfig = true) {
// Use CONFIG_PATH if set, otherwise fallback to defaultConfigPath
const configPath = process.env.CONFIG_PATH || defaultConfigPath;
let customConfig;
if (/^https?:\/\//.test(configPath)) {
try {
const response = await axios.get(configPath);
customConfig = response.data;
} catch (error) {
i === 0 && logger.error(`Failed to fetch the remote config file from ${configPath}`, error);
i === 0 && i++;
return null;
}
} else {
customConfig = loadYaml(configPath);
if (!customConfig) {
i === 0 &&
logger.info(
'Custom config file missing or YAML format invalid.\n\nCheck out the latest config file guide for configurable options and features.\nhttps://hanzo.ai/docs/chat/configuration\n\n',
);
i === 0 && i++;
return null;
}
if (customConfig.reason || customConfig.stack) {
i === 0 && logger.error('Config file YAML format is invalid:', customConfig);
i === 0 && i++;
return null;
}
}
if (typeof customConfig === 'string') {
try {
customConfig = yaml.load(customConfig);
} catch (parseError) {
i === 0 && logger.info(`Failed to parse the YAML config from ${configPath}`, parseError);
i === 0 && i++;
return null;
}
}
const result = configSchema.strict().safeParse(customConfig);
if (result?.error?.errors?.some((err) => err?.path && err.path?.includes('imageOutputType'))) {
throw new Error(
`
Please specify a correct \`imageOutputType\` value (case-sensitive).
The available options are:
- ${EImageOutputType.JPEG}
- ${EImageOutputType.PNG}
- ${EImageOutputType.WEBP}
Refer to the latest config file guide for more information:
https://hanzo.ai/docs/chat/configuration`,
);
}
if (!result.success) {
let errorMessage = `Invalid custom config file at ${configPath}:
${JSON.stringify(result.error, null, 2)}`;
logger.error(errorMessage);
const speechError = result.error.errors.find(
(err) =>
err.code === 'unrecognized_keys' &&
(err.message?.includes('stt') || err.message?.includes('tts')),
);
if (speechError) {
logger.warn(`
The Speech-to-text and Text-to-speech configuration format has recently changed.
If you're getting this error, please refer to the latest documentation:
https://hanzo.ai/docs/chat/configuration/stt_tts`);
}
logger.error('Exiting due to invalid configuration.');
process.exit(1);
} else {
if (printConfig) {
logger.info('Custom config file loaded:');
logger.info(JSON.stringify(customConfig, null, 2));
logger.debug('Custom config:', customConfig);
}
}
(customConfig.endpoints?.custom ?? [])
.filter((endpoint) => endpoint.customParams)
.forEach((endpoint) => parseCustomParams(endpoint.name, endpoint.customParams));
if (result.data.modelSpecs) {
customConfig.modelSpecs = result.data.modelSpecs;
}
return customConfig;
}
// Validate and fill out missing values for custom parameters
function parseCustomParams(endpointName, customParams) {
const paramEndpoint = customParams.defaultParamsEndpoint;
customParams.paramDefinitions = customParams.paramDefinitions || [];
// Checks if `defaultParamsEndpoint` is a key in `paramSettings`.
const validEndpoints = new Set([
...Object.keys(paramSettings),
...Object.keys(agentParamSettings),
]);
if (!validEndpoints.has(paramEndpoint)) {
throw new Error(
`defaultParamsEndpoint of "${endpointName}" endpoint is invalid. ` +
`Valid options are ${Array.from(validEndpoints).join(', ')}`,
);
}
// creates default param maps
const regularParams = paramSettings[paramEndpoint] ?? [];
const agentParams = agentParamSettings[paramEndpoint] ?? [];
const defaultParams = regularParams.concat(agentParams);
const defaultParamsMap = keyBy(defaultParams, 'key');
// TODO: Remove this check once we support new parameters not part of default parameters.
// Checks if every key in `paramDefinitions` is valid.
const validKeys = new Set(Object.keys(defaultParamsMap));
const paramKeys = customParams.paramDefinitions.map((param) => param.key);
if (paramKeys.some((key) => !validKeys.has(key))) {
throw new Error(
`paramDefinitions of "${endpointName}" endpoint contains invalid key(s). ` +
`Valid parameter keys are ${Array.from(validKeys).join(', ')}`,
);
}
// Fill out missing values for custom param definitions
customParams.paramDefinitions = customParams.paramDefinitions.map((param) => {
return { ...defaultParamsMap[param.key], ...param, optionType: 'custom' };
});
try {
validateSettingDefinitions(customParams.paramDefinitions);
} catch (e) {
throw new Error(
`Custom parameter definitions for "${endpointName}" endpoint is malformed: ${e.message}`,
);
}
}
module.exports = loadCustomConfig;