Files
contract-clock-studio-v1/frontend/src/a2a.js
2026-07-18 07:39:17 +00:00

69 lines
2.1 KiB
JavaScript

export const CONFIG_URL = import.meta.env.DEV ? "/config.json" : "./config.json";
export async function requestJson(url, init = {}) {
const response = await fetch(url, { credentials: "same-origin", ...init });
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (!response.ok) {
const detail = data && (data.detail || data.message);
const err = new Error(detail || `request failed: ${response.status}`);
err.status = response.status;
throw err;
}
return data;
}
export async function loadAgentConfig() {
return requestJson(CONFIG_URL);
}
export async function loadSession(config) {
return requestJson(config.endpoints.session);
}
export function signInUrl(config) {
const target = config.auth?.authorizeUrl || config.auth?.loginUrl;
if (!target) return null;
const next = encodeURIComponent(
window.location.pathname + window.location.search + window.location.hash,
);
return `${target}${target.includes("?") ? "&" : "?"}next=${next}`;
}
export async function requireSession(config) {
const session = await loadSession(config);
if (!session?.authenticated) {
const target = signInUrl(config);
if (target) window.location.assign(target);
throw new Error("sign in required");
}
return session;
}
export async function callSkill(config, skillName, args) {
try {
if (config.auth?.invokeRequiresSession) {
await requireSession(config);
}
const data = await requestJson(
`${config.endpoints.invoke}/${encodeURIComponent(skillName)}`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ arguments: args }),
},
);
if (data?.status === "setup_required") {
throw new Error(data.message || "Setup required before running this workflow.");
}
return data;
} catch (err) {
if (err?.status === 401) {
const target = signInUrl(config);
if (target) window.location.assign(target);
throw new Error("Session expired. Sign in again to run ContractClock.");
}
throw err;
}
}