All files / src/services/api/routers NetworkRouter.tsx

85.71% Statements 18/21
88.23% Branches 15/17
85.71% Functions 6/7
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                      69x       9x 9x 9x 15x   9x                           2209x         2209x           6x       6x 6x       6x 6x         2209x       3x       3x 3x          
import {
  KnowledgeNetworkSummary,
  MemoryGraphSummary,
  NetworkGraph,
} from "@/objects/Network";
import { Dictionary } from "@/types/ext";
import { AxiosRequestConfig } from "axios";
import { APIRouter } from "../ApiRouter";
 
/** `agent_id` repeated, as FastAPI reads a list — `endpoint()` would write
 *  `agent_id[]=`, which it does not. */
const withAgents = (
  agentIds: string[] | undefined,
  rest: Record<string, string | number | boolean>,
): URLSearchParams => {
  const params = new URLSearchParams();
  (agentIds ?? []).forEach((id) => params.append("agent_id", id));
  Object.entries(rest).forEach(([key, value]) =>
    params.append(key, String(value)),
  );
  return params;
};
 
/**
 * How the caller's agents, knowledge and memory connect. Read-only graphs
 * built from stored records; nothing here reaches a model.
 */
export class NetworkRouter extends APIRouter {
  constructor(
    host: string,
    token: string | null = null,
    default_config: AxiosRequestConfig | null = null,
    headers: Dictionary<string> = {},
  ) {
    super("network", host, token, default_config, headers);
  }
 
  /** `knowledgeIds` draws where those sources are used instead: the
   *  workspace's repositories holding them and its agents granted those. */
  getKnowledgeNetwork = async (opts?: {
    agentIds?: string[];
    knowledgeIds?: string[];
    includeMemory?: boolean;
    includeUnconnected?: boolean;
  }): Promise<NetworkGraph<KnowledgeNetworkSummary> | null> => {
    const params = withAgents(opts?.agentIds, {
      include_memory: opts?.includeMemory ?? true,
      include_unconnected: opts?.includeUnconnected ?? true,
    });
    (opts?.knowledgeIds ?? []).forEach((id) => params.append("knowledge_id", id));
    const res = await this.api.get<NetworkGraph<KnowledgeNetworkSummary>>(
      super.endpoint("knowledge"),
      { params },
    );
    Eif (super.validRes(res)) {
      return res.data;
    }
    return null;
  };
 
  getMemoryGraph = async (opts?: {
    agentIds?: string[];
    recent?: number;
  }): Promise<NetworkGraph<MemoryGraphSummary> | null> => {
    const res = await this.api.get<NetworkGraph<MemoryGraphSummary>>(
      super.endpoint("memory"),
      { params: withAgents(opts?.agentIds, { recent: opts?.recent ?? 20 }) },
    );
    Eif (super.validRes(res)) {
      return res.data;
    }
    return null;
  };
}