import { API_V1, CREDENTIALS, checkTenant, signal, UNAUTHORIZED_EVENT } from "../apiContract"; import { refusalPair } from "../query/queryApi"; export const INTELLIGENCE_SECTIONS = [ { key: "playbooks", label: "Playbooks" }, { key: "agent-prompts", label: "Agent prompts" }, { key: "company-facts", label: "Company facts" }, { key: "dictionary-and-preferences", label: "Dictionary and preferences" }, { key: "shared-results", label: "Shared results" }, { key: "agent-memory", label: "Agent memory" }, { key: "database-notes", label: "Database notes" }, { key: "wiki", label: "Wiki" }, ] as const; export type IntelligenceSection = typeof INTELLIGENCE_SECTIONS[number]["key"]; /** New files outside Wiki use the ordinary Brain file section. */ export const BRAIN_FILE_SECTION: IntelligenceSection = "playbooks"; export const BRAIN_MAX_BODY_BYTES = 128 * 1024; export const BRAIN_BODY_LIMIT_MESSAGE = "A Brain file can be at most 128 KB"; export const BRAIN_FILES_CHANGED = "aios:brain-files-changed"; export interface IntelligenceFileRow { path: string; title: string; section: IntelligenceSection; description: string; author: string; updated: string; version: number; lastUsed?: string | null; databaseKey?: string; canEdit?: boolean; revisionHistory?: "database-note"; } export interface IntelligenceTool { name: string; group: string; action: string | null; description: string; schema: Record; } export interface IntelligenceFile extends IntelligenceFileRow { body: string; metadata?: { title: string; description?: string }; agent?: string; onBehalfOf?: string; approvedBy?: string[]; proposalId?: string; restoredFrom?: number; promptText?: string; resolvedTools?: IntelligenceTool[]; } export interface IntelligenceVersion { version: number; author: string; authorKind: "user" | "agent" | "system"; created: string; agent?: string; onBehalfOf?: string; approvedBy?: string[]; restoredFrom?: number; } export interface IntelligenceHistory { path: string; history: IntelligenceVersion[]; trimmed: number; latestVersion: number; selectedVersion: number; previousVersion: number | null; diff: string | null; canRestore: boolean; limits: { maxVersions: number }; } export interface IntelligenceChangeCount { person: string; section: string; hand: number; agent: number } export interface IntelligenceInsights { since: string; until: string; days: number; rows: IntelligenceChangeCount[]; totals: { hand: number; agent: number }; activity: "included" | "absent" | "unavailable"; sections: Array<{ key: string; label: string }>; } export interface IntelligenceProposal { id: string; path: string; title: string; diff: string; status: "pending" | "approving" | "approved" | "rejected" | "stale"; baseVersion: number; author: string; authorKind?: "user" | "agent"; agent: string; onBehalfOf: string; approvedBy: string[]; recipients: string[]; policy: { approvals_needed: number }; canDecide: boolean; created: string; approvedVersion?: number; } export interface IntelligenceDecision { proposal: IntelligenceProposal; file?: IntelligenceFile } export interface IntelligencePendingSave { proposal: IntelligenceProposal; delivery: string } export interface IntelligenceList { files: IntelligenceFileRow[]; total: number; offset: number; limit: number; folders: string[]; cacheable?: boolean; canManageFolders?: boolean; folderRevision?: number; } export interface IntelligenceQuery { q: string; /** Optional server filter. The Brain screen does not send it. */ section?: IntelligenceSection | ""; folder: string; /** Only files directly in `folder`, as a module home level shows them. */ direct?: boolean; offset: number; limit: number; } export interface NewIntelligenceFile { title: string; section: IntelligenceSection; folder: string; markdown: string; tools?: string[]; } export interface IntelligenceApi { listFiles(query: IntelligenceQuery, signal?: AbortSignal): Promise; readFile(path: string, signal?: AbortSignal): Promise; createFile(input: NewIntelligenceFile): Promise; saveFile?(path: string, body: string, expectedVersion: number, signal?: AbortSignal): Promise; listProposals(path: string, signal?: AbortSignal): Promise; decideProposal(id: string, decision: "approve" | "reject"): Promise; history(path: string, version: number, signal?: AbortSignal): Promise; restore(path: string, version: number, expectedVersion: number): Promise; insights(signal?: AbortSignal): Promise; renameFile?: (path: string, title: string, expectedVersion: number) => Promise; deleteFile?: (path: string, expectedVersion: number) => Promise<{ deleted: string }>; renameFolder?: (path: string, name: string, expectedRevision: number) => Promise<{ path: string }>; deleteFolder?: (path: string, expectedRevision: number) => Promise<{ deleted: string }>; } export class IntelligenceApiError extends Error { status: number; code?: string; constructor(message: string, status = 0, code?: string) { super(message); this.status = status; this.code = code; } } export function intelligenceProblem(error: unknown, fallback: string): string { return error instanceof IntelligenceApiError ? error.message : fallback; } export function fileDate(value: string): string { return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(new Date(value)); } const object = (value: unknown): value is Record => !!value && typeof value === "object" && !Array.isArray(value); const date = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value)); const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0; function readRow(value: unknown): IntelligenceFileRow { if (!object(value) || typeof value.path !== "string" || !value.path || typeof value.title !== "string" || !value.title.trim() || !INTELLIGENCE_SECTIONS.some((section) => section.key === value.section) || typeof value.description !== "string" || typeof value.author !== "string" || !date(value.updated) || !count(value.version) || value.version < 1 || (value.lastUsed != null && !date(value.lastUsed))) throw new Error("Invalid file."); if (value.section === "database-notes" && (typeof value.databaseKey !== "string" || !value.databaseKey || value.databaseKey.includes("/") || value.path !== `database-notes/${value.databaseKey}.md` || typeof value.canEdit !== "boolean" || value.revisionHistory !== "database-note")) throw new Error("Invalid note."); if (value.canEdit != null && typeof value.canEdit !== "boolean") throw new Error("Invalid permission."); return value as unknown as IntelligenceFileRow; } function readFile(value: unknown): IntelligenceFile { const row = readRow(value); if (!object(value) || typeof value.body !== "string") throw new Error("Invalid file."); if (value.canEdit != null && typeof value.canEdit !== "boolean") throw new Error("Invalid permission."); if (row.section === "agent-prompts") { if (typeof value.promptText !== "string" || !Array.isArray(value.resolvedTools) || value.resolvedTools.some((tool) => !object(tool) || typeof tool.name !== "string" || !tool.name || typeof tool.group !== "string" || !tool.group || (tool.action !== null && typeof tool.action !== "string") || typeof tool.description !== "string" || !tool.description || !object(tool.schema)) || new Set(value.resolvedTools.map((tool) => tool.name)).size !== value.resolvedTools.length) throw new Error("Invalid prompt."); return { ...row, body: value.body, promptText: value.promptText, resolvedTools: value.resolvedTools as IntelligenceTool[] }; } return { ...row, body: value.body }; } function readProposal(value: unknown): IntelligenceProposal { if (!object(value) || ["id", "path", "title", "diff", "author", "agent", "onBehalfOf"].some((key) => typeof value[key] !== "string") || !["pending", "approving", "approved", "rejected", "stale"].includes(String(value.status)) || !count(value.baseVersion) || !date(value.created) || typeof value.canDecide !== "boolean" || !Array.isArray(value.approvedBy) || value.approvedBy.some((name) => typeof name !== "string") || !Array.isArray(value.recipients) || value.recipients.some((name) => typeof name !== "string") || !object(value.policy) || !count(value.policy.approvals_needed) || value.policy.approvals_needed < 1) throw new Error("Invalid proposal."); return value as unknown as IntelligenceProposal; } function readList(value: unknown, response: Response): IntelligenceList { if (!object(value) || !Array.isArray(value.files) || !count(value.total) || !count(value.offset) || !count(value.limit) || value.limit < 1 || value.limit > 100 || !Array.isArray(value.folders) || value.folders.some((folder) => typeof folder !== "string") || value.files.length > value.limit || (value.files.length > 0 && value.offset + value.files.length > value.total)) throw new Error("Invalid list."); const files = value.files.map(readRow); if (new Set(files.map((file) => file.path)).size !== files.length) throw new Error("Invalid list."); if ((value.canManageFolders != null && typeof value.canManageFolders !== "boolean") || (value.folderRevision != null && !count(value.folderRevision))) throw new Error("Invalid folder permission."); return { files, total: value.total, offset: value.offset, limit: value.limit, folders: value.folders as string[], cacheable: response.headers.get("X-Brain-List-Cache") === "private-revalidate", ...(typeof value.canManageFolders === "boolean" ? { canManageFolders: value.canManageFolders } : {}), ...(count(value.folderRevision) ? { folderRevision: value.folderRevision } : {}) }; } function readDeleted(value: unknown, path: string): { deleted: string } { if (!object(value) || value.deleted !== path) throw new Error("Invalid deletion."); return { deleted: path }; } function readHistory(value: unknown): IntelligenceHistory { if (!object(value) || typeof value.path !== "string" || !Array.isArray(value.history) || !count(value.trimmed) || !count(value.latestVersion) || !count(value.selectedVersion) || (value.previousVersion !== null && !count(value.previousVersion)) || (value.diff !== null && typeof value.diff !== "string") || typeof value.canRestore !== "boolean" || !object(value.limits) || !count(value.limits.maxVersions) || value.limits.maxVersions < 1) throw new Error("Invalid history."); let previous = Infinity; for (const entry of value.history) { if (!object(entry) || !count(entry.version) || entry.version < 1 || entry.version >= previous || !date(entry.created) || typeof entry.author !== "string" || !["user", "agent", "system"].includes(String(entry.authorKind)) || (entry.authorKind === "system" && (!/^wiki\/(log|index|purposes)\//.test(value.path) || entry.author !== "system" || value.canRestore || entry.agent != null || entry.onBehalfOf != null || entry.approvedBy != null || entry.restoredFrom != null)) || (entry.authorKind === "agent" && (typeof entry.onBehalfOf !== "string" || !entry.onBehalfOf)) || (entry.approvedBy != null && (!Array.isArray(entry.approvedBy) || entry.approvedBy.some((person) => typeof person !== "string"))) || (entry.restoredFrom != null && !count(entry.restoredFrom))) throw new Error("Invalid history."); previous = entry.version; } if (!value.history.some((entry) => entry.version === value.selectedVersion)) throw new Error("Invalid history."); return value as unknown as IntelligenceHistory; } function readInsights(value: unknown): IntelligenceInsights { if (!object(value) || !date(value.since) || !date(value.until) || value.days !== 30 || !["included", "absent", "unavailable"].includes(String(value.activity)) || !Array.isArray(value.rows) || !Array.isArray(value.sections) || value.sections.some((row) => !object(row) || typeof row.key !== "string" || typeof row.label !== "string") || !object(value.totals) || !count(value.totals.hand) || !count(value.totals.agent)) throw new Error("Invalid insights."); const totals = { hand: 0, agent: 0 }; for (const row of value.rows) { if (!object(row) || typeof row.person !== "string" || !row.person || typeof row.section !== "string" || !value.sections.some((section) => section.key === row.section) || !count(row.hand) || !count(row.agent)) throw new Error("Invalid insights."); totals.hand += row.hand; totals.agent += row.agent; } if (totals.hand !== value.totals.hand || totals.agent !== value.totals.agent) throw new Error("Invalid insights."); return value as unknown as IntelligenceInsights; } async function request(query: string, init: RequestInit, parse: (value: unknown, response: Response) => T, resource = "files"): Promise { let response: Response; try { response = await fetch(`${API_V1}/intelligence/${resource}${query}`, { credentials: CREDENTIALS, cache: "no-store", ...init }); } catch (error) { if (init.signal?.aborted) throw error; throw new IntelligenceApiError("Cannot reach the server. Try again."); } if (checkTenant(response)) throw new IntelligenceApiError("Your session changed. Sign in again.", 401); if (response.status === 401) signal(UNAUTHORIZED_EVENT); const body: unknown = await response.json().catch(() => null); if (!response.ok) { if ([401, 403, 404].includes(response.status) && (init.method !== "GET" || new URLSearchParams(query).has("path"))) { signal(BRAIN_FILES_CHANGED); } const refusal = refusalPair(body); const message = response.status >= 500 ? (init.method === "PATCH" || init.method === "DELETE" ? "The change could not be confirmed. Reload and try again." : init.method === "PUT" ? "The file save could not be confirmed. Reload and try again." : init.method === "POST" ? resource === "restore" ? "The restore could not be confirmed. Reload and try again." : "The decision could not be confirmed. Reload and try again." : "Brain files could not be read. Try again.") : refusal.message; throw new IntelligenceApiError(message || "This file is unavailable.", response.status, refusal.code); } try { const value = parse(body, response); if (init.method !== "GET") signal(BRAIN_FILES_CHANGED); return value; } catch { throw new IntelligenceApiError("Brain files could not be read. Try again."); } } /** The server assigns the owner and refuses an existing path with expectedVersion zero. */ export function newFilePayload(input: NewIntelligenceFile): { path: string; body: string; expectedVersion: number; authorKind: string } { const title = input.title.trim(); if (!title) throw new IntelligenceApiError("Enter a title."); const folder = input.folder.trim(); if (folder && (!/^[a-zA-Z0-9._/-]+$/.test(folder) || folder.split("/").some((part) => !part || part === "." || part === ".."))) { throw new IntelligenceApiError("Use letters, numbers and slashes in the folder name."); } const name = title.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase() .replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 100) || `file-${crypto.randomUUID()}`; const path = `${folder ? `${folder}/` : ""}${name}.md`; if (path.length > 200) throw new IntelligenceApiError("Use a shorter folder name."); const body = `---\ntitle: ${JSON.stringify(title)}\nsection: ${input.section}\napprovers: []\napprovals_needed: 1\nreads: []\ntools: ${JSON.stringify(input.tools || [])}\n---\n${input.markdown}`; if (new TextEncoder().encode(body).length > BRAIN_MAX_BODY_BYTES) throw new IntelligenceApiError(BRAIN_BODY_LIMIT_MESSAGE, 413, "body_too_long"); return { path, body, expectedVersion: 0, authorKind: "user" }; } export const intelligenceApi: IntelligenceApi = { renameFile(path, title, expectedVersion) { return request("", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path, title, expectedVersion }) }, (value) => { const file = readFile(value); if (file.path !== path || file.version <= expectedVersion) throw new Error("Invalid rename."); return file; }); }, deleteFile(path, expectedVersion) { return request(`?${new URLSearchParams({ path, expectedVersion: String(expectedVersion) })}`, { method: "DELETE" }, (value) => readDeleted(value, path)); }, renameFolder(path, name, expectedRevision) { return request("", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path, name, expectedRevision }) }, (value) => { if (!object(value) || typeof value.path !== "string" || !value.path) throw new Error("Invalid folder rename."); return { path: value.path }; }, "folders"); }, deleteFolder(path, expectedRevision) { return request(`?${new URLSearchParams({ path, expectedRevision: String(expectedRevision) })}`, { method: "DELETE" }, (value) => readDeleted(value, path), "folders"); }, history(path, version, signal) { return request(`?${new URLSearchParams({ path, version: String(version) })}`, { method: "GET", signal }, readHistory, "history"); }, restore(path, version, expectedVersion) { return request("", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path, version, expectedVersion }) }, readFile, "restore"); }, insights(signal) { return request("", { method: "GET", signal }, readInsights, "insights"); }, listProposals(path, signal) { return request(`?${new URLSearchParams({ path })}`, { method: "GET", signal }, (value) => { if (!object(value) || !Array.isArray(value.proposals)) throw new Error("Invalid proposals."); return value.proposals.map(readProposal); }, "proposals"); }, decideProposal(id, decision) { return request("", { method: "POST" }, (value) => { if (!object(value)) throw new Error("Invalid decision."); return { proposal: readProposal(value.proposal), ...(value.file ? { file: readFile(value.file) } : {}) }; }, `proposals/${encodeURIComponent(id)}/${decision}`); }, listFiles(query, signal) { const params = new URLSearchParams({ q: query.q, ...(query.section ? { section: query.section } : {}), folder: query.folder, ...(query.direct ? { direct: "true" } : {}), offset: String(query.offset), limit: String(query.limit) }); return request(`?${params}`, { method: "GET", signal }, readList); }, readFile(path, signal) { return request(`?${new URLSearchParams({ path })}`, { method: "GET", signal }, readFile); }, saveFile(path, body, expectedVersion, signal) { if (new TextEncoder().encode(body).length > BRAIN_MAX_BODY_BYTES) return Promise.reject(new IntelligenceApiError(BRAIN_BODY_LIMIT_MESSAGE, 413, "body_too_long")); return request("", { method: "PUT", signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path, body, expectedVersion, authorKind: "user" }) }, (value) => { if (object(value) && value.proposal) { if (typeof value.delivery !== "string") throw new Error("Invalid delivery."); return { proposal: readProposal(value.proposal), delivery: value.delivery }; } return readFile(value); }); }, async createFile(input) { try { return await request("", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newFilePayload(input)) }, readFile); } catch (error) { if (error instanceof IntelligenceApiError && error.code === "version_conflict") { throw new IntelligenceApiError("A file with that name already exists. Change the title or folder.", 409, error.code); } throw error; } }, };