File size: 3,795 Bytes
8145bee
 
 
 
82f0f29
8145bee
 
 
 
 
 
 
 
 
b2aa446
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82f0f29
 
 
 
 
 
b2aa446
8145bee
 
 
 
 
 
b2aa446
 
8145bee
 
 
 
 
 
 
 
 
 
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
import { API_V1, CREDENTIALS, checkTenant, signal, UNAUTHORIZED_EVENT } from "../apiContract";
import type { Result } from "../query/queryApi";

export type MemoryKind = "person" | "preference" | "fact";
export type MemoryOrder = "newest" | "oldest";
export interface MemoryEntry {
  id: string;
  text: string;
  kind: MemoryKind;
  scope: "personal" | "company";
  sources: Array<{ database: string; fields: string[] }>;
  door: string;
  at: string;
}
export interface MemoryList { entries: MemoryEntry[]; total: number; dropped: number; next: string | null; }

function record(raw: unknown): Record<string, unknown> | null {
  return raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : null;
}

function entry(raw: unknown): MemoryEntry | null {
  const row = record(raw);
  if (!row || typeof row.id !== "string" || !row.id || typeof row.text !== "string") return null;
  if (row.scope !== undefined && row.scope !== "personal" && row.scope !== "company") return null;
  if (row.kind !== undefined && !["person", "preference", "fact"].includes(String(row.kind))) return null;
  return {
    id: row.id, text: row.text, kind: (row.kind || "fact") as MemoryKind,
    scope: row.scope === "company" ? "company" : "personal",
    sources: (Array.isArray(row.sources) ? row.sources : []).flatMap((rawSource) => {
      const source = record(rawSource);
      return source && typeof source.database === "string" ? [{ database: source.database,
        fields: Array.isArray(source.fields) ? source.fields.filter((field): field is string => typeof field === "string") : [] }] : [];
    }),
    door: typeof row.door === "string" ? row.door : "",
    at: typeof row.at === "string" ? row.at : "",
  };
}

async function request<T>(url: string, method: string, parse: (body: unknown) => T | null): Promise<Result<T>> {
  try {
    const response = await fetch(url, { method, credentials: CREDENTIALS, cache: "no-store" });
    if (checkTenant(response)) return { ok: false, status: 401, message: "Your session changed. Sign in again." };
    if (response.status === 401) signal(UNAUTHORIZED_EVENT);
    if (!response.ok) return { ok: false, status: response.status, message: "Memory could not be saved. Try again." };
    const value = parse(await response.json().catch(() => null));
    return value === null ? { ok: false, status: response.status, message: "Memory could not be loaded. Try again." }
      : { ok: true, value };
  } catch {
    return { ok: false, status: 0, message: "Cannot reach the server." };
  }
}

/** Follow the server cursor in the selected order, defaulting to newest first. */
export function fetchMemory(next?: string | null, order?: MemoryOrder): Promise<Result<MemoryList>> {
  const params = new URLSearchParams();
  if (next) params.set("cursor", next);
  if (order) params.set("order", order);
  const page = params.size ? `?${params}` : "";
  return request(`${API_V1}/assistant/memory${page}`, "GET", (raw) => {
    const body = record(raw);
    if (!body || !Array.isArray(body.entries)) return null;
    const entries = body.entries.map(entry);
    if (entries.some((row) => row === null)) return null;
    return { entries: entries as MemoryEntry[],
      total: typeof body.total === "number" ? body.total : entries.length,
      dropped: typeof body.dropped === "number" ? body.dropped : 0,
      next: typeof body.next === "string" && body.next ? body.next : null };
  });
}

export function eraseMemory(id: string): Promise<Result<boolean>> {
  return request(`${API_V1}/assistant/memory/${encodeURIComponent(id)}`, "DELETE", () => true);
}

export function promoteMemory(id: string): Promise<Result<boolean>> {
  return request(`${API_V1}/assistant/memory/${encodeURIComponent(id)}/promote`, "POST", () => true);
}