Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

9.6 KB
Raw Blame
import {
  isProviderDriverKind,
  resolveProviderInstanceEnabled,
  type ModelSelection,
  type ProviderDriverKind,
  ProviderInstanceId,
  ServerSettings,
  type ServerSettingsPatch,
} from "@akeru/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { deepMerge } from "./Struct.ts";
import { fromLenientJson } from "./schemaJson.ts";
import { createModelSelection } from "./model.ts";
import {
  getBackgroundActivityBaseProfile,
  normalizeBackgroundActivitySettings,
  normalizeServerBackgroundActivitySettings,
  resolveBackgroundActivitySettings,
} from "./backgroundActivitySettings.ts";

const ServerSettingsJson = fromLenientJson(ServerSettings);

const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);

type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];

const hasLegacyProviderSettings = (
  settings: ServerSettings,
  provider: string,
): provider is keyof ServerSettings["providers"] => provider in settings.providers;

const getLegacyProviderSettings = (
  settings: ServerSettings,
  provider: ProviderDriverKind,
): LegacyProviderSettings | undefined => {
  const key = String(provider);

  return hasLegacyProviderSettings(settings, key) ? settings.providers[key] : undefined;
};

export function isModelSelectionProviderEnabled(
  settings: ServerSettings,
  selection: ModelSelection,
): boolean {
  const instanceConfig = settings.providerInstances[selection.instanceId];

  if (instanceConfig !== undefined) {
    return resolveProviderInstanceEnabled(instanceConfig);
  }

  return (
    isProviderDriverKind(selection.instanceId) &&
    getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true
  );
}

function providerDriverForSelection(
  settings: ServerSettings,
  selection: ModelSelection,
): ProviderDriverKind | undefined {
  const instance = settings.providerInstances[selection.instanceId];

  if (instance !== undefined) return instance.driver;

  return isProviderDriverKind(selection.instanceId) ? selection.instanceId : undefined;
}

/**
 * Map a text-generation model onto another environment by enabled provider
 * identity (driver), not by copying instance IDs blindly.
 */
export function textGenerationSelectionForTarget(
  selection: ModelSelection,
  sourceSettings: ServerSettings,
  targetSettings: ServerSettings,
): ModelSelection | undefined {
  const sourceDriver = providerDriverForSelection(sourceSettings, selection);

  if (sourceDriver === undefined) return undefined;

  const sameId = targetSettings.providerInstances[selection.instanceId];

  if (
    sameId !== undefined &&
    sameId.driver === sourceDriver &&
    resolveProviderInstanceEnabled(sameId)
  ) {
    return createModelSelection(selection.instanceId, selection.model, selection.options);
  }

  const targetInstances = Object.entries(targetSettings.providerInstances);

  const matched = targetInstances.find(
    ([, instance]) => instance.driver === sourceDriver && resolveProviderInstanceEnabled(instance),
  );

  if (matched !== undefined) {
    return createModelSelection(
      ProviderInstanceId.make(matched[0]),
      selection.model,
      selection.options,
    );
  }

  if (targetInstances.some(([, instance]) => instance.driver === sourceDriver)) {
    return undefined;
  }

  const legacyInstanceId = ProviderInstanceId.make(sourceDriver);

  if (
    targetSettings.providerInstances[legacyInstanceId] === undefined &&
    getLegacyProviderSettings(targetSettings, sourceDriver)?.enabled === true
  ) {
    return createModelSelection(legacyInstanceId, selection.model, selection.options);
  }

  return undefined;
}

export interface PersistedServerObservabilitySettings {
  readonly otlpTracesUrl: string | undefined;
  readonly otlpMetricsUrl: string | undefined;
}

export function normalizePersistedServerSettingString(
  value: string | null | undefined,
): string | undefined {
  const trimmed = value?.trim();

  return trimmed && trimmed.length > 0 ? trimmed : undefined;
}

export function extractPersistedServerObservabilitySettings(input: {
  readonly observability?: {
    readonly otlpTracesUrl?: string;
    readonly otlpMetricsUrl?: string;
  };
}): PersistedServerObservabilitySettings {
  return {
    otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),
    otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),
  };
}

export function parsePersistedServerObservabilitySettings(
  raw: string,
): PersistedServerObservabilitySettings {
  const decoded = decodeServerSettingsJson(raw);

  if (Option.isSome(decoded)) {
    return extractPersistedServerObservabilitySettings(decoded.value);
  }

  return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}

function mergeModelSelectionOptionsById(input: {
  current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
  patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;
}): Array<{ id: string; value: string | boolean }> | undefined {
  if (input.patch === undefined) {
    return input.current ? [...input.current] : undefined;
  }

  if (input.patch.length === 0) {
    return undefined;
  }

  const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));

  for (const selection of input.patch) {
    merged.set(selection.id, selection.value);
  }

  return [...merged.entries()].map(([id, value]) => ({ id, value }));
}

export function applyServerSettingsPatch(
  current: ServerSettings,
  patch: ServerSettingsPatch,
): ServerSettings {
  const selectionPatch = patch.textGenerationModelSelection;

  const {
    automaticGitFetchInterval,
    providerHealthRefreshInterval,
    backgroundActivityProfile,
    backgroundActivity,
    ...patchForMerge
  } = patch;

  const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);

  const backgroundActivityPatch =
    backgroundActivityProfile !== undefined
      ? {
          schemaVersion: 1 as const,
          profile:
            automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
              ? ("custom" as const)
              : backgroundActivityProfile,
          ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
            ? { baseProfile: backgroundActivityProfile }
            : {}),
          overrides: {
            ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
            ...(providerHealthRefreshInterval !== undefined
              ? { providerHealthRefreshInterval }
              : {}),
          },
        }
      : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined
        ? {
            schemaVersion: 1 as const,
            profile: "custom" as const,
            baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),
            overrides: {
              ...(currentBackgroundActivity.profile === "custom"
                ? currentBackgroundActivity.overrides
                : {}),
              ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),
              ...(providerHealthRefreshInterval !== undefined
                ? { providerHealthRefreshInterval }
                : {}),
            },
          }
        : undefined;

  const next = deepMerge(current, patchForMerge);

  const nextWithReplacementsBase = {
    ...next,
    ...(backgroundActivity !== undefined
      ? {
          backgroundActivity: {
            ...deepMerge(currentBackgroundActivity, backgroundActivity),
            ...(backgroundActivity.overrides !== undefined
              ? { overrides: backgroundActivity.overrides }
              : {}),
          },
        }
      : { backgroundActivity: currentBackgroundActivity }),
    ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined
      ? { backgroundActivity: backgroundActivityPatch }
      : {}),
    ...(patch.providerInstances !== undefined
      ? { providerInstances: patch.providerInstances }
      : {}),
    ...(patch.channelConnections !== undefined
      ? { channelConnections: patch.channelConnections }
      : {}),
    ...(patch.sourceControlWriterModelSelection !== undefined
      ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }
      : {}),
  };

  const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(
    nextWithReplacementsBase.backgroundActivity,
  );

  const resolvedBackgroundActivity = resolveBackgroundActivitySettings(
    normalizedBackgroundActivity,
  );

  const nextWithReplacements = {
    ...nextWithReplacementsBase,
    backgroundActivity: normalizedBackgroundActivity,
    automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,
    providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,
    backgroundActivityProfile: resolvedBackgroundActivity.profile,
  };

  if (!selectionPatch) {
    return nextWithReplacements;
  }

  const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;
  const model = selectionPatch.model ?? current.textGenerationModelSelection.model;

  const options =
    selectionPatch.instanceId !== undefined || selectionPatch.model !== undefined
      ? selectionPatch.options
      : mergeModelSelectionOptionsById({
          current: current.textGenerationModelSelection.options,
          patch: selectionPatch.options,
        });

  return {
    ...nextWithReplacements,
    textGenerationModelSelection: createModelSelection(instanceId, model, options),
  };
}