cjovs's picture
Add direct plugin action API helper
e735720 verified
Raw
History Blame Contribute Delete
3.1 kB
import type { AgentRecord, CompanyRecord, GlobalProviderConfig } from "../types.js";
type PluginConfigResponse = {
id: string;
pluginId: string;
configJson: Record<string, unknown>;
lastError: string | null;
createdAt: string;
updatedAt: string;
} | null;
type ApiErrorPayload = {
error?: string;
message?: string;
};
async function parseError(response: Response): Promise<string> {
try {
const json = await response.json() as ApiErrorPayload;
return json.error ?? json.message ?? `Request failed (${response.status})`;
} catch {
const text = await response.text();
return text || `Request failed (${response.status})`;
}
}
export async function apiFetchJson<T>(path: string, init?: RequestInit): Promise<T> {
const response = await fetch(`/api${path}`, {
credentials: "include",
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
...init,
});
if (!response.ok) {
throw new Error(await parseError(response));
}
if (response.status === 204) {
return undefined as T;
}
return await response.json() as T;
}
export async function loadPluginConfig(pluginId: string): Promise<GlobalProviderConfig | null> {
const payload = await apiFetchJson<PluginConfigResponse>(`/plugins/${encodeURIComponent(pluginId)}/config`);
if (!payload) return null;
return payload.configJson as GlobalProviderConfig;
}
export async function savePluginConfig(pluginId: string, config: GlobalProviderConfig): Promise<GlobalProviderConfig> {
const payload = await apiFetchJson<Exclude<PluginConfigResponse, null>>(
`/plugins/${encodeURIComponent(pluginId)}/config`,
{
method: "POST",
body: JSON.stringify({ configJson: config }),
},
);
return payload.configJson as GlobalProviderConfig;
}
export async function listCompanies(): Promise<CompanyRecord[]> {
return await apiFetchJson<CompanyRecord[]>("/companies");
}
export async function listCompanyAgents(companyId: string): Promise<AgentRecord[]> {
return await apiFetchJson<AgentRecord[]>(`/companies/${encodeURIComponent(companyId)}/agents`);
}
export async function patchAgent(
agentId: string,
companyId: string,
patch: Record<string, unknown>,
): Promise<AgentRecord> {
return await apiFetchJson<AgentRecord>(
`/agents/${encodeURIComponent(agentId)}?companyId=${encodeURIComponent(companyId)}`,
{
method: "PATCH",
body: JSON.stringify(patch),
},
);
}
export async function invokeFetchModelsAction(
pluginId: string,
input: { baseUrl: string; apiKey: string },
): Promise<{ baseUrl: string; modelCatalog: Array<{ id: string; label: string; raw?: Record<string, unknown> | null }> }> {
const payload = await apiFetchJson<{ data: unknown }>(
`/plugins/${encodeURIComponent(pluginId)}/actions/fetch-openai-models`,
{
method: "POST",
body: JSON.stringify({
params: input,
}),
},
);
return payload.data as {
baseUrl: string;
modelCatalog: Array<{ id: string; label: string; raw?: Record<string, unknown> | null }>;
};
}