Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

25.7 KB
Raw Blame
// This file was auto-generated by Fern from our API Definition.

import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";
import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js";
import { mergeHeaders } from "../../../../core/headers.js";
import * as core from "../../../../core/index.js";
import { mergeAdditionalBodyParameters } from "../../../../core/requestBody.js";
import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";
import * as errors from "../../../../errors/index.js";
import * as serializers from "../../../../serialization/index.js";
import * as TrueForge from "../../../index.js";

export declare namespace AgentsClient {
    export type Options = BaseClientOptions;

    export interface RequestOptions extends BaseRequestOptions {}
}

export class AgentsClient {
    protected readonly _options: NormalizedClientOptionsWithAuth<AgentsClient.Options>;

    constructor(options: AgentsClient.Options) {
        this._options = normalizeClientOptionsWithAuth(options);
    }

    /**
     * List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.
     *
     * @param {TrueForge.ListAgentsRequest} request
     * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link TrueForge.BadRequestError}
     * @throws {@link TrueForge.UnauthorizedError}
     * @throws {@link errors.TrueForgeError}
     * @throws {@link errors.TrueForgeTimeoutError}
     *
     * @example
     *     await client.agents.list()
     */
    public async list(
        request: TrueForge.ListAgentsRequest = {},
        requestOptions?: AgentsClient.RequestOptions,
    ): Promise<core.Page<TrueForge.Agent, TrueForge.ListAgentsResponse>> {
        const list = core.HttpResponsePromise.interceptFunction(
            async (
                request: TrueForge.ListAgentsRequest,
            ): Promise<core.WithRawResponse<TrueForge.ListAgentsResponse>> => {
                const { limit = 50, pageToken, agentName } = request;
                const _queryParams: Record<string, unknown> = {
                    limit,
                    page_token: pageToken,
                    agent_name: agentName,
                };
                const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
                const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
                    _authRequest.headers,
                    this._options?.headers,
                    requestOptions?.headers,
                );
                const _response = await (this._options.fetcher ?? core.fetcher)({
                    url: core.url.join(
                        (await core.Supplier.get(this._options.baseUrl)) ??
                            (await core.Supplier.get(this._options.environment)),
                        "api/v1/agents",
                    ),
                    method: "GET",
                    headers: _headers,
                    queryString: core.url
                        .queryBuilder()
                        .addMany(_queryParams)
                        .mergeAdditional(requestOptions?.queryParams)
                        .build(),
                    timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
                    maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
                    abortSignal: requestOptions?.abortSignal,
                    fetchFn: this._options?.fetch,
                    logging: this._options.logging,
                });
                if (_response.ok) {
                    return {
                        data: serializers.ListAgentsResponse.parseOrThrow(_response.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        rawResponse: _response.rawResponse,
                    };
                }
                if (_response.error.reason === "status-code") {
                    switch (_response.error.statusCode) {
                        case 400:
                            throw new TrueForge.BadRequestError(
                                serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                                    unrecognizedObjectKeys: "passthrough",
                                    allowUnrecognizedUnionMembers: true,
                                    allowUnrecognizedEnumValues: true,
                                    skipValidation: true,
                                    breadcrumbsPrefix: ["response"],
                                }),
                                _response.rawResponse,
                            );
                        case 401:
                            throw new TrueForge.UnauthorizedError(
                                serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                                    unrecognizedObjectKeys: "passthrough",
                                    allowUnrecognizedUnionMembers: true,
                                    allowUnrecognizedEnumValues: true,
                                    skipValidation: true,
                                    breadcrumbsPrefix: ["response"],
                                }),
                                _response.rawResponse,
                            );
                        default:
                            throw new errors.TrueForgeError({
                                statusCode: _response.error.statusCode,
                                body: _response.error.body,
                                rawResponse: _response.rawResponse,
                            });
                    }
                }
                return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents");
            },
        );
        const dataWithRawResponse = await list(request).withRawResponse();
        return new core.Page<TrueForge.Agent, TrueForge.ListAgentsResponse>({
            response: dataWithRawResponse.data,
            rawResponse: dataWithRawResponse.rawResponse,
            hasNextPage: (response) =>
                response?.pagination.nextPageToken != null &&
                !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),
            getItems: (response) => response?.data ?? [],
            loadPage: (response) => {
                return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));
            },
        });
    }

    /**
     * Creates an agent and allocates an immutable id. Fails if `name` is already taken. Name cannot be changed later.
     *
     * @param {TrueForge.CreateAgentRequest} request
     * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link TrueForge.BadRequestError}
     * @throws {@link TrueForge.ConflictError}
     * @throws {@link TrueForge.UnprocessableEntityError}
     * @throws {@link errors.TrueForgeError}
     * @throws {@link errors.TrueForgeTimeoutError}
     *
     * @example
     *     await client.agents.create({
     *         description: "description",
     *         manifest: {
     *             model: {
     *                 name: "name"
     *             }
     *         },
     *         name: "name"
     *     })
     */
    public create(
        request: TrueForge.CreateAgentRequest,
        requestOptions?: AgentsClient.RequestOptions,
    ): core.HttpResponsePromise<TrueForge.GetAgentResponse> {
        return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));
    }

    private async __create(
        request: TrueForge.CreateAgentRequest,
        requestOptions?: AgentsClient.RequestOptions,
    ): Promise<core.WithRawResponse<TrueForge.GetAgentResponse>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                "api/v1/agents",
            ),
            method: "POST",
            headers: _headers,
            contentType: "application/json",
            queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
            requestType: "json",
            body: mergeAdditionalBodyParameters(
                serializers.CreateAgentRequest.jsonOrThrow(request, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    omitUndefined: true,
                }),
                requestOptions?.additionalBodyParameters,
            ),
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return {
                data: serializers.GetAgentResponse.parseOrThrow(_response.body, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    skipValidation: true,
                    breadcrumbsPrefix: ["response"],
                }),
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new TrueForge.BadRequestError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                case 409:
                    throw new TrueForge.ConflictError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                case 422:
                    throw new TrueForge.UnprocessableEntityError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                default:
                    throw new errors.TrueForgeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/agents");
    }

    /**
     * Fetch a configured agent by immutable id.
     *
     * @param {string} agent_id - Immutable agent identifier.
     * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link TrueForge.NotFoundError}
     * @throws {@link errors.TrueForgeError}
     * @throws {@link errors.TrueForgeTimeoutError}
     *
     * @example
     *     await client.agents.get("agent_id")
     */
    public get(
        agent_id: string,
        requestOptions?: AgentsClient.RequestOptions,
    ): core.HttpResponsePromise<TrueForge.GetAgentResponse> {
        return core.HttpResponsePromise.fromPromise(this.__get(agent_id, requestOptions));
    }

    private async __get(
        agent_id: string,
        requestOptions?: AgentsClient.RequestOptions,
    ): Promise<core.WithRawResponse<TrueForge.GetAgentResponse>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                `api/v1/agents/${core.url.encodePathParam(agent_id, errors.TrueForgeError)}`,
            ),
            method: "GET",
            headers: _headers,
            queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return {
                data: serializers.GetAgentResponse.parseOrThrow(_response.body, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    skipValidation: true,
                    breadcrumbsPrefix: ["response"],
                }),
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 404:
                    throw new TrueForge.NotFoundError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                default:
                    throw new errors.TrueForgeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents/{agent_id}");
    }

    /**
     * Update an existing agent by immutable id.
     *
     * @param {string} agent_id - Immutable agent identifier.
     * @param {TrueForge.UpdateAgentRequest} request
     * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link TrueForge.BadRequestError}
     * @throws {@link TrueForge.NotFoundError}
     * @throws {@link TrueForge.UnprocessableEntityError}
     * @throws {@link errors.TrueForgeError}
     * @throws {@link errors.TrueForgeTimeoutError}
     *
     * @example
     *     await client.agents.update("agent_id", {
     *         manifest: {
     *             model: {
     *                 name: "name"
     *             }
     *         }
     *     })
     */
    public update(
        agent_id: string,
        request: TrueForge.UpdateAgentRequest,
        requestOptions?: AgentsClient.RequestOptions,
    ): core.HttpResponsePromise<TrueForge.GetAgentResponse> {
        return core.HttpResponsePromise.fromPromise(this.__update(agent_id, request, requestOptions));
    }

    private async __update(
        agent_id: string,
        request: TrueForge.UpdateAgentRequest,
        requestOptions?: AgentsClient.RequestOptions,
    ): Promise<core.WithRawResponse<TrueForge.GetAgentResponse>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                `api/v1/agents/${core.url.encodePathParam(agent_id, errors.TrueForgeError)}`,
            ),
            method: "PUT",
            headers: _headers,
            contentType: "application/json",
            queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
            requestType: "json",
            body: mergeAdditionalBodyParameters(
                serializers.UpdateAgentRequest.jsonOrThrow(request, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    omitUndefined: true,
                }),
                requestOptions?.additionalBodyParameters,
            ),
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return {
                data: serializers.GetAgentResponse.parseOrThrow(_response.body, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    skipValidation: true,
                    breadcrumbsPrefix: ["response"],
                }),
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 400:
                    throw new TrueForge.BadRequestError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                case 404:
                    throw new TrueForge.NotFoundError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                case 422:
                    throw new TrueForge.UnprocessableEntityError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                default:
                    throw new errors.TrueForgeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/api/v1/agents/{agent_id}");
    }

    /**
     * Delete a configured agent by immutable id.
     *
     * @param {string} agent_id - Immutable agent identifier.
     * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
     *
     * @throws {@link TrueForge.UnauthorizedError}
     * @throws {@link TrueForge.NotFoundError}
     * @throws {@link errors.TrueForgeError}
     * @throws {@link errors.TrueForgeTimeoutError}
     *
     * @example
     *     await client.agents.delete("agent_id")
     */
    public delete(
        agent_id: string,
        requestOptions?: AgentsClient.RequestOptions,
    ): core.HttpResponsePromise<TrueForge.DeleteAgentResponse> {
        return core.HttpResponsePromise.fromPromise(this.__delete(agent_id, requestOptions));
    }

    private async __delete(
        agent_id: string,
        requestOptions?: AgentsClient.RequestOptions,
    ): Promise<core.WithRawResponse<TrueForge.DeleteAgentResponse>> {
        const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();
        const _headers: core.Fetcher.Args["headers"] = mergeHeaders(
            _authRequest.headers,
            this._options?.headers,
            requestOptions?.headers,
        );
        const _response = await (this._options.fetcher ?? core.fetcher)({
            url: core.url.join(
                (await core.Supplier.get(this._options.baseUrl)) ??
                    (await core.Supplier.get(this._options.environment)),
                `api/v1/agents/${core.url.encodePathParam(agent_id, errors.TrueForgeError)}`,
            ),
            method: "DELETE",
            headers: _headers,
            queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
            timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,
            maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
            abortSignal: requestOptions?.abortSignal,
            fetchFn: this._options?.fetch,
            logging: this._options.logging,
        });
        if (_response.ok) {
            return {
                data: serializers.DeleteAgentResponse.parseOrThrow(_response.body, {
                    unrecognizedObjectKeys: "passthrough",
                    allowUnrecognizedUnionMembers: true,
                    allowUnrecognizedEnumValues: true,
                    skipValidation: true,
                    breadcrumbsPrefix: ["response"],
                }),
                rawResponse: _response.rawResponse,
            };
        }

        if (_response.error.reason === "status-code") {
            switch (_response.error.statusCode) {
                case 401:
                    throw new TrueForge.UnauthorizedError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                case 404:
                    throw new TrueForge.NotFoundError(
                        serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
                            unrecognizedObjectKeys: "passthrough",
                            allowUnrecognizedUnionMembers: true,
                            allowUnrecognizedEnumValues: true,
                            skipValidation: true,
                            breadcrumbsPrefix: ["response"],
                        }),
                        _response.rawResponse,
                    );
                default:
                    throw new errors.TrueForgeError({
                        statusCode: _response.error.statusCode,
                        body: _response.error.body,
                        rawResponse: _response.rawResponse,
                    });
            }
        }

        return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/api/v1/agents/{agent_id}");
    }
}