loopable / web /src /apps /code /bridgeTools.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
c72f0a1 verified
Raw History Blame
11 kB
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
export const CODE_APP_TOOLS = Object.freeze([
"tools.listBrainFiles", "tools.readBrainFile", "tools.sendRequest", "tools.createSchedule",
] as const);
type Json = Record<string, unknown>;
export type ToolConfirmation =
| { kind: "request"; to: string; title: string; body: string }
| { kind: "schedule"; database: string; payload: Json; when: string; tz: "UTC"; onceAt?: string };
export type ConfirmTool = (request: ToolConfirmation, abort: AbortSignal) => Promise<boolean>;
export class BridgeRefused extends Error {
code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
}
}
function object(value: unknown): Json {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new BridgeRefused("bad_arguments", "Send an object for this tool.");
}
return value as Json;
}
function keys(value: unknown, allowed: string[]): Json {
const result = object(value);
if (Object.keys(result).some((key) => !allowed.includes(key))) {
throw new BridgeRefused("bad_arguments", "This tool includes an unsupported option.");
}
return result;
}
function text(value: unknown, name: string): string {
if (typeof value !== "string" || !value.trim()) {
throw new BridgeRefused("bad_arguments", `Send ${name} as text.`);
}
return value;
}
async function route(path: string, abort: AbortSignal, applicationId: string, body?: Json): Promise<Json> {
if (abort.aborted) throw new BridgeRefused("bridge_closed", "This App was closed.");
let response: Response;
try {
response = await fetch(`${API_V1}${path}`, {
credentials: CREDENTIALS, cache: "no-store", signal: abort,
...(body ? { method: "POST", headers: { "Content-Type": "application/json", "X-Loopable-App": applicationId },
body: JSON.stringify(body) } : {}),
});
} catch { throw new BridgeRefused("tool_unavailable", "This tool could not complete its request."); }
if (checkTenant(response)) throw new BridgeRefused("tenant_changed", "Open this App again.");
if (response.status === 401) signal(UNAUTHORIZED_EVENT);
let payload: Json;
try { payload = object(await response.json()); }
catch { throw new BridgeRefused("tool_unavailable", "This tool returned an invalid response."); }
if (!response.ok) {
const error = payload.error as Partial<BridgeRefused> | undefined;
throw new BridgeRefused(typeof error?.code === "string" ? error.code : `http_${response.status}`,
typeof error?.message === "string" ? error.message : "This tool could not complete its request.");
}
return payload;
}
function file(value: unknown, body = false): Json {
const source = object(value);
if (typeof source.path !== "string" || typeof source.title !== "string"
|| (body && typeof source.body !== "string")) {
throw new BridgeRefused("invalid_response", "This Brain file could not be read.");
}
return { path: source.path, title: source.title,
...Object.fromEntries(["section", "description", "updated"].filter((key) => typeof source[key] === "string")
.map((key) => [key, source[key]])),
...(Number.isSafeInteger(source.version) ? { version: source.version } : {}),
...(body ? { body: source.body } : {}) };
}
async function listBrainFiles(abort: AbortSignal, applicationId: string): Promise<Json[]> {
const files: Json[] = [];
const paths = new Set<string>();
let total: number | undefined;
do {
const query = new URLSearchParams({ q: "", folder: "", direct: "false", offset: String(files.length), limit: "100" });
const page = await route(`/intelligence/files?${query}`, abort, applicationId);
if (!Array.isArray(page.files) || !Number.isSafeInteger(page.total) || Number(page.total) < 0
|| page.offset !== files.length || (total !== undefined && page.total !== total)) {
throw new BridgeRefused("incomplete_files", "Brain could not supply every file.");
}
total = Number(page.total);
const rows = page.files.map((value) => file(value));
if (files.length + rows.length > total || (!rows.length && files.length < total)
|| rows.some((row) => paths.has(String(row.path)))
|| new Set(rows.map((row) => row.path)).size !== rows.length) {
throw new BridgeRefused("incomplete_files", "Brain could not supply every file.");
}
for (const row of rows) paths.add(String(row.path));
files.push(...rows);
} while (files.length < total);
return files;
}
function queryPayload(value: unknown): Json {
const payload = keys(value, ["fields", "filters", "sorts", "limit", "cursor", "aggregates", "groupBy"]);
for (const key of ["fields", "sorts", "aggregates"]) {
if (payload[key] != null && !Array.isArray(payload[key])) {
throw new BridgeRefused("bad_arguments", `${key} must be a list.`);
}
}
if (payload.fields != null && (payload.fields as unknown[]).some((key) => typeof key !== "string" || !key)) {
throw new BridgeRefused("bad_arguments", "fields must name database fields.");
}
if (payload.filters != null && typeof payload.filters !== "object") {
throw new BridgeRefused("bad_arguments", "filters must contain query rules.");
}
if (payload.limit !== undefined && (!Number.isSafeInteger(payload.limit) || Number(payload.limit) < 1)) {
throw new BridgeRefused("bad_arguments", "limit must be a positive page size.");
}
if (payload.cursor != null && typeof payload.cursor !== "string") {
throw new BridgeRefused("bad_arguments", "cursor must be text.");
}
if (payload.groupBy != null && typeof payload.groupBy !== "string"
&& !(Array.isArray(payload.groupBy) && payload.groupBy.every((key) => typeof key === "string" && key))) {
throw new BridgeRefused("bad_arguments", "groupBy must name database fields.");
}
return payload;
}
function cronField(part: string, low: number, high: number): boolean {
return part.split(",").every((item) => {
const match = /^(\*|\?|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(item);
if (!match) return false;
if (match[2] && (!Number.isSafeInteger(Number(match[2])) || Number(match[2]) < 1)) return false;
if (match[1] === "*" || match[1] === "?") return true;
const bounds = match[1].split("-").map(Number);
return bounds.every((number) => Number.isSafeInteger(number) && number >= low && number <= high)
&& (bounds.length === 1 || bounds[0] <= bounds[1]);
});
}
function scheduleTime(when: string): Json {
if (when === "sync") return { trigger: "sync" };
const parts = when.trim().split(/\s+/);
const ranges = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 6]];
if (parts.length === 5 && parts.every((part, index) => cronField(part, ranges[index][0], ranges[index][1]))) {
return { cron: parts.join(" ") };
}
const instant = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|[+-]\d{2}:\d{2})$/.exec(when);
if (instant) {
const [year, month, day, hour, minute, second] = instant.slice(1, 7).map(Number);
const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
const zone = instant[7];
const date = new Date(when);
if (month >= 1 && month <= 12 && day >= 1 && day <= days && hour <= 23 && minute <= 59 && second <= 59
&& (zone === "Z" || (Number(zone.slice(1, 3)) <= 23 && Number(zone.slice(4)) <= 59))
&& Number.isFinite(date.getTime())) return { once_at: date.toISOString() };
}
throw new BridgeRefused("unsupported_when", "Use an ISO date and time with a time zone, five cron fields, or sync.");
}
export async function serveTool(call: string, args: unknown[], applicationId: string,
confirm: ConfirmTool, abort: AbortSignal): Promise<unknown> {
if (!(CODE_APP_TOOLS as readonly string[]).includes(call)) {
throw new BridgeRefused("tool_not_allowed", "This App tool is not allowed.");
}
if (args.length !== (call === "tools.listBrainFiles" ? 0 : 1)) {
throw new BridgeRefused("bad_arguments", "Send the arguments for this tool.");
}
if (call === "tools.listBrainFiles") return listBrainFiles(abort, applicationId);
if (call === "tools.readBrainFile") {
const path = text(args[0], "a Brain file path");
const result = await route(`/intelligence/files?${new URLSearchParams({ path })}`, abort, applicationId);
const projected = file(result, true);
if (projected.path !== path) throw new BridgeRefused("invalid_response", "This Brain file could not be read.");
return projected;
}
let request: ToolConfirmation;
let path: string;
let body: Json;
if (call === "tools.sendRequest") {
const input = keys(args[0], ["to", "title", "body"]);
request = { kind: "request", to: text(input.to, "a recipient"), title: text(input.title, "a title"),
body: typeof input.body === "string" ? input.body : text(input.body, "a request body") };
path = "/requests";
body = { to: request.to, kind: "question", title: request.title, body: request.body };
} else {
const input = keys(args[0], ["database", "payload", "when"]);
const database = text(input.database, "a database key");
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(database)) throw new BridgeRefused("bad_arguments", "Send a database key.");
const payload = queryPayload(input.payload), when = text(input.when, "a schedule time");
const timing = scheduleTime(when);
request = { kind: "schedule", database, payload, when, tz: "UTC",
...(typeof timing.once_at === "string" ? { onceAt: timing.once_at } : {}) };
path = "/schedules";
body = { action: { kind: "query", database, payload, words: `Read ${database} at ${when}.`, scope: [database] },
...timing, label: `Query ${database} at ${when}`, tz: "UTC" };
}
if (!await confirm(request, abort)) throw new BridgeRefused("tool_canceled", "This tool request was canceled.");
if (abort.aborted) throw new BridgeRefused("bridge_closed", "This App was closed.");
const result = await route(path, abort, applicationId, body);
// Only the receipt crosses the frame boundary. Server identity and auth metadata stay in the host.
const receipt = object(call === "tools.sendRequest" ? result.request : result.schedule);
if (typeof receipt.id !== "string" || (call === "tools.sendRequest" && typeof receipt.state !== "string")
|| (call === "tools.createSchedule" && (typeof result.id !== "string" || result.id !== receipt.id
|| typeof receipt.label !== "string" || typeof receipt.tz !== "string"
|| (receipt.cron != null && typeof receipt.cron !== "string")
|| (receipt.onceAt != null && typeof receipt.onceAt !== "string")
|| (receipt.trigger != null && receipt.trigger !== "sync")))) {
throw new BridgeRefused("invalid_response", "This tool returned an invalid receipt.");
}
return call === "tools.sendRequest"
? { id: receipt.id, state: receipt.state }
: { id: result.id, label: receipt.label, cron: receipt.cron, onceAt: receipt.onceAt,
trigger: receipt.trigger, tz: receipt.tz };
}