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

58 lines
1.9 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 error = new Error(detail || `request failed: ${response.status}`);
error.status = response.status;
throw error;
}
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("Please sign in to run ContractClock.");
}
return session;
}
export async function callSkill(config, skillName, args) {
try {
if (config.auth?.invokeRequiresSession) await requireSession(config);
return await requestJson(`${config.endpoints.invoke}/${encodeURIComponent(skillName)}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ arguments: args }),
});
} catch (error) {
if (error.status === 401) {
const target = signInUrl(config);
if (target) window.location.assign(target);
throw new Error("Session expired. Re-authorizing…");
}
throw error;
}
}