File size: 20,204 Bytes
98c8696
 
 
 
 
 
 
 
 
 
c72f0a1
81a8217
98c8696
 
81a8217
a9ff272
81a8217
 
868b75a
98c8696
 
 
 
 
 
 
 
 
c72f0a1
 
 
98c8696
 
 
 
 
 
 
 
 
 
81a8217
98c8696
 
 
 
 
 
 
 
 
 
 
81a8217
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
98c8696
 
 
 
 
 
 
 
 
 
81a8217
98c8696
 
 
 
 
 
868b75a
071ce2b
 
98c8696
 
 
a9ff272
 
98c8696
a9ff272
 
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
98c8696
 
 
 
 
071ce2b
 
 
 
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
071ce2b
98c8696
 
 
 
 
81a8217
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
98c8696
 
 
 
 
 
071ce2b
 
 
868b75a
071ce2b
 
 
 
 
 
 
98c8696
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
 
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
868b75a
98c8696
 
 
 
 
 
 
 
 
 
 
868b75a
 
 
98c8696
071ce2b
 
98c8696
 
a596902
98c8696
 
868b75a
 
 
 
 
a596902
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
81a8217
 
 
98c8696
 
 
 
071ce2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9ff272
 
98c8696
 
 
c72f0a1
81a8217
c72f0a1
81a8217
 
 
 
 
 
 
c72f0a1
98c8696
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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<string, unknown>;
}
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<IntelligenceList>;
  readFile(path: string, signal?: AbortSignal): Promise<IntelligenceFile>;
  createFile(input: NewIntelligenceFile): Promise<IntelligenceFile>;
  saveFile?(path: string, body: string, expectedVersion: number, signal?: AbortSignal): Promise<IntelligenceFile | IntelligencePendingSave>;
  listProposals(path: string, signal?: AbortSignal): Promise<IntelligenceProposal[]>;
  decideProposal(id: string, decision: "approve" | "reject"): Promise<IntelligenceDecision>;
  history(path: string, version: number, signal?: AbortSignal): Promise<IntelligenceHistory>;
  restore(path: string, version: number, expectedVersion: number): Promise<IntelligenceFile>;
  insights(signal?: AbortSignal): Promise<IntelligenceInsights>;
  renameFile?: (path: string, title: string, expectedVersion: number) => Promise<IntelligenceFile>;
  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<string, unknown> =>
  !!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<T>(query: string, init: RequestInit, parse: (value: unknown, response: Response) => T, resource = "files"): Promise<T> {
  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;
    }
  },
};