Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(memory): seed an agent from GitHub only from items the user ticked

nirholas819f7a6bfb4d
diff --git a/api/_lib/github-api.js b/api/_lib/github-api.js
new file mode 100644
index 000000000..2b3db2428
--- /dev/null
+++ b/api/_lib/github-api.js
@@ -0,0 +1,120 @@
+// Thin GitHub REST/GraphQL client for the memory-seeding endpoints.
+//
+// Every call is read-only and scoped to the connected user's own OAuth token.
+// Upstream failures are tagged with `status` so wrap() reports them as 502
+// upstream errors rather than as our own 500.
+
+const API = 'https://api.github.com';
+const UA = 'three.ws/1.0';
+const TIMEOUT_MS = 15_000;
+
+function headers(token, accept = 'application/vnd.github+json') {
+ return {
+ authorization: `token ${token}`,
+ accept,
+ 'user-agent': UA,
+ 'x-github-api-version': '2022-11-28',
+ };
+}
+
+function upstream(message, status = 502) {
+ return Object.assign(new Error(message), { status });
+}
+
+async function ghJson(path, token) {
+ const res = await fetch(`${API}${path}`, {
+ headers: headers(token),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (res.status === 401) throw upstream('GitHub rejected the stored token', 401);
+ if (!res.ok) throw upstream(`GitHub ${path} failed: ${res.status}`);
+ return res.json();
+}
+
+export function fetchProfile(token) {
+ return ghJson('/user', token);
+}
+
+/** Public repos the user owns, most recently pushed first. */
+export function fetchRepos(token, perPage = 40) {
+ return ghJson(
+ `/user/repos?sort=pushed&direction=desc&per_page=${perPage}&visibility=public&affiliation=owner`,
+ token,
+ );
+}
+
+const PINNED_QUERY = `query($login:String!){
+ user(login:$login){
+ pinnedItems(first:6, types:[REPOSITORY]){
+ nodes{
+ ... on Repository{
+ nameWithOwner name description stargazerCount pushedAt isFork url
+ primaryLanguage{ name }
+ repositoryTopics(first:8){ nodes{ topic{ name } } }
+ }
+ }
+ }
+ }
+}`;
+
+/**
+ * Repos the developer pinned to their own profile. A pin is the strongest
+ * signal of what they consider their work, so these lead the consent catalog.
+ * GraphQL is the only API that exposes pins; a failure here degrades to an
+ * empty pin list rather than failing the whole catalog.
+ */
+export async function fetchPinnedRepos(token, login) {
+ const res = await fetch(`${API}/graphql`, {
+ method: 'POST',
+ headers: { ...headers(token), 'content-type': 'application/json' },
+ body: JSON.stringify({ query: PINNED_QUERY, variables: { login } }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!res.ok) return [];
+ const body = await res.json().catch(() => null);
+ const nodes = body?.data?.user?.pinnedItems?.nodes;
+ if (!Array.isArray(nodes)) return [];
+ return nodes.filter(Boolean).map((n) => ({
+ full_name: n.nameWithOwner,
+ name: n.name,
+ description: n.description,
+ language: n.primaryLanguage?.name ?? null,
+ stargazerCount: n.stargazerCount,
+ topics: (n.repositoryTopics?.nodes ?? []).map((t) => t?.topic?.name).filter(Boolean),
+ pushedAt: n.pushedAt,
+ isFork: n.isFork,
+ url: n.url,
+ }));
+}
+
+/**
+ * A repo's README as raw markdown, or null when it has none. A missing README
+ * is an ordinary state, not an error: the seed run continues with the repos
+ * that do have one.
+ */
+export async function fetchReadme(token, repoKey) {
+ const res = await fetch(`${API}/repos/${repoKey}/readme`, {
+ headers: headers(token, 'application/vnd.github.raw'),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (res.status === 404) return null;
+ if (!res.ok) throw upstream(`GitHub README fetch failed for ${repoKey}: ${res.status}`);
+ return res.text();
+}
+
+/** Best-effort revocation of our OAuth grant on GitHub's side. */
+export async function revokeGrant(token, clientId, clientSecret) {
+ const creds = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
+ const res = await fetch(`${API}/applications/${clientId}/grant`, {
+ method: 'DELETE',
+ headers: {
+ authorization: `Basic ${creds}`,
+ accept: 'application/vnd.github+json',
+ 'content-type': 'application/json',
+ 'user-agent': UA,
+ },
+ body: JSON.stringify({ access_token: token }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ return res.status === 204;
+}
diff --git a/api/_lib/github-seed.js b/api/_lib/github-seed.js
new file mode 100644
index 000000000..0b4175102
--- /dev/null
+++ b/api/_lib/github-seed.js
@@ -0,0 +1,311 @@
+// Pure transform core for consent-first GitHub memory seeding.
+//
+// The privacy contract this module enforces: a seed run may only ever read the
+// items the user ticked. Every stage below is a narrowing. buildCatalog turns
+// the GitHub API response into the inventory the user is shown, resolveSelection
+// rejects anything the user sent that is not in that inventory, and
+// buildSeedDocument renders ONLY the resolved items into the text handed to the
+// LLM. Nothing in here fetches or writes, so the narrowing is directly testable
+// without a network or a database.
+
+import { z } from 'zod';
+
+export const GITHUB_SEED_SOURCE = 'github_seed';
+export const GITHUB_SEED_TAGS = ['github', 'github_seed'];
+
+export const MAX_CATALOG_REPOS = 40;
+export const MAX_SELECTED_REPOS = 12;
+export const MAX_README_CHARS = 8000;
+export const MAX_FACTS = 20;
+export const MAX_FACT_CHARS = 600;
+
+const REPO_KEY = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/[A-Za-z0-9._-]{1,100}$/;
+
+export const selectionSchema = z
+ .object({
+ include_profile: z.boolean().default(false),
+ repos: z.array(z.string().trim().regex(REPO_KEY)).max(MAX_SELECTED_REPOS).default([]),
+ readmes: z.array(z.string().trim().regex(REPO_KEY)).max(MAX_SELECTED_REPOS).default([]),
+ })
+ .strict();
+
+// ── Catalog ───────────────────────────────────────────────────────────────────
+
+function repoKey(raw) {
+ if (raw?.full_name) return raw.full_name;
+ const owner = raw?.owner?.login ?? raw?.owner ?? '';
+ return owner && raw?.name ? `${owner}/${raw.name}` : '';
+}
+
+function toCatalogRepo(raw, pinned) {
+ const key = repoKey(raw);
+ if (!key) return null;
+ return {
+ key,
+ name: raw.name ?? key.split('/')[1],
+ owner: key.split('/')[0],
+ description: raw.description ?? null,
+ language: raw.language ?? raw.primaryLanguage?.name ?? null,
+ stars: raw.stargazers_count ?? raw.stargazerCount ?? 0,
+ topics: Array.isArray(raw.topics) ? raw.topics.slice(0, 8) : [],
+ pushed_at: raw.pushed_at ?? raw.pushedAt ?? null,
+ fork: Boolean(raw.fork ?? raw.isFork ?? false),
+ url: raw.html_url ?? raw.url ?? `https://github.com/${key}`,
+ pinned,
+ };
+}
+
+function toCatalogProfile(raw) {
+ if (!raw?.login) return null;
+ return {
+ login: raw.login,
+ name: raw.name ?? null,
+ bio: raw.bio ?? null,
+ company: raw.company ?? null,
+ location: raw.location ?? null,
+ blog: raw.blog || null,
+ public_repos: raw.public_repos ?? 0,
+ followers: raw.followers ?? 0,
+ url: raw.html_url ?? `https://github.com/${raw.login}`,
+ };
+}
+
+/**
+ * Build the inventory the user picks from. Pinned repos lead because they are
+ * what the developer chose to show on their own profile, then the rest by most
+ * recently pushed. Private repos never enter the catalog: the OAuth scope is
+ * read-only public, and a private repo appearing in a consent list the user
+ * cannot meaningfully audit is exactly the surprise this feature exists to
+ * avoid.
+ */
+export function buildCatalog({ profile, pinned = [], repos = [] } = {}) {
+ const pinnedKeys = new Set();
+ const out = [];
+
+ for (const raw of Array.isArray(pinned) ? pinned : []) {
+ const entry = toCatalogRepo(raw, true);
+ if (!entry || pinnedKeys.has(entry.key)) continue;
+ pinnedKeys.add(entry.key);
+ out.push(entry);
+ }
+
+ const rest = (Array.isArray(repos) ? repos : [])
+ .filter((r) => !r?.private)
+ .map((r) => toCatalogRepo(r, false))
+ .filter((r) => r && !pinnedKeys.has(r.key))
+ .sort((a, b) => String(b.pushed_at ?? '').localeCompare(String(a.pushed_at ?? '')));
+
+ out.push(...rest);
+
+ return {
+ profile: toCatalogProfile(profile),
+ repos: out.slice(0, MAX_CATALOG_REPOS),
+ };
+}
+
+// ── Selection ─────────────────────────────────────────────────────────────────
+
+/**
+ * Narrow a user selection against the catalog. Anything the caller asked for
+ * that is not in the catalog, or a README for a repo they did not also select,
+ * comes back in `rejected` so the endpoint can refuse the whole run rather than
+ * silently seeding a different set than the user believes they approved.
+ */
+export function resolveSelection(catalog, selection) {
+ const byKey = new Map((catalog?.repos ?? []).map((r) => [r.key, r]));
+ const rejected = [];
+
+ const repos = [];
+ const seen = new Set();
+ for (const key of selection.repos ?? []) {
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const entry = byKey.get(key);
+ if (!entry) {
+ rejected.push({ key, reason: 'not_in_catalog' });
+ continue;
+ }
+ repos.push(entry);
+ }
+
+ const readmeKeys = [];
+ const seenReadme = new Set();
+ for (const key of selection.readmes ?? []) {
+ if (seenReadme.has(key)) continue;
+ seenReadme.add(key);
+ if (!byKey.has(key)) {
+ rejected.push({ key, reason: 'not_in_catalog' });
+ continue;
+ }
+ if (!seen.has(key)) {
+ rejected.push({ key, reason: 'readme_without_repo' });
+ continue;
+ }
+ readmeKeys.push(key);
+ }
+
+ const includeProfile = Boolean(selection.include_profile);
+ if (includeProfile && !catalog?.profile) {
+ rejected.push({ key: 'profile', reason: 'not_in_catalog' });
+ }
+
+ return {
+ profile: includeProfile && catalog?.profile ? catalog.profile : null,
+ repos,
+ readmeKeys,
+ rejected,
+ isEmpty: !includeProfile && repos.length === 0,
+ };
+}
+
+/**
+ * The preset used by the older non-granular seed route: the developer's public
+ * profile plus the repos they pinned to it. It is the smallest selection that
+ * still says something real about their work, and it reads nothing the visitor
+ * to their GitHub profile page cannot already see.
+ */
+export function defaultSelection(catalog) {
+ return {
+ include_profile: Boolean(catalog?.profile),
+ repos: (catalog?.repos ?? []).filter((r) => r.pinned).map((r) => r.key),
+ readmes: [],
+ };
+}
+
+// ── README normalisation ──────────────────────────────────────────────────────
+
+/**
+ * Strip a README down to prose. Badge rows, raw HTML blocks, and image links
+ * are pure noise to a fact distiller and burn the token budget that the actual
+ * project description needs.
+ */
+export function readmeExcerpt(markdown, limit = MAX_README_CHARS) {
+ if (typeof markdown !== 'string') return '';
+ const cleaned = markdown
+ .replace(/<!--[\s\S]*?-->/g, ' ')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/^[ \t]*\|.*\|[ \t]*$/gm, ' ')
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+ return cleaned.length > limit ? `${cleaned.slice(0, limit).trimEnd()}…` : cleaned;
+}
+
+// ── Seed document ─────────────────────────────────────────────────────────────
+
+function repoBlock(repo, readme) {
+ const lines = [`### ${repo.key}${repo.pinned ? ' (pinned)' : ''}`];
+ if (repo.description) lines.push(`Description: ${repo.description}`);
+ if (repo.language) lines.push(`Primary language: ${repo.language}`);
+ if (repo.topics.length) lines.push(`Topics: ${repo.topics.join(', ')}`);
+ if (repo.stars) lines.push(`Stars: ${repo.stars}`);
+ if (readme) lines.push(`README:\n${readme}`);
+ return lines.join('\n');
+}
+
+/**
+ * Render the resolved selection into the text the distiller sees. `readmes` is
+ * consulted only for keys in `resolved.readmeKeys`, so a README fetched for a
+ * repo the user did not tick can never reach the prompt.
+ */
+export function buildSeedDocument(resolved, readmes = new Map()) {
+ const allowed = new Set(resolved.readmeKeys ?? []);
+ const sections = [];
+
+ if (resolved.profile) {
+ const p = resolved.profile;
+ const bits = [`## Public profile`, `Handle: @${p.login}`];
+ if (p.name) bits.push(`Name: ${p.name}`);
+ if (p.bio) bits.push(`Bio: ${p.bio}`);
+ if (p.company) bits.push(`Company: ${p.company}`);
+ if (p.location) bits.push(`Location: ${p.location}`);
+ if (p.blog) bits.push(`Site: ${p.blog}`);
+ bits.push(`Public repos: ${p.public_repos}`, `Followers: ${p.followers}`);
+ sections.push(bits.join('\n'));
+ }
+
+ if (resolved.repos.length) {
+ const blocks = resolved.repos.map((repo) =>
+ repoBlock(repo, allowed.has(repo.key) ? readmes.get(repo.key) || '' : ''),
+ );
+ sections.push(['## Selected repositories', ...blocks].join('\n\n'));
+ }
+
+ return sections.join('\n\n');
+}
+
+export const SEED_SYSTEM_PROMPT =
+ 'You distill a developer\'s GitHub material into concise memory facts for their AI agent. ' +
+ 'Each fact is one self-contained sentence the agent can say out loud about this person: ' +
+ 'what they build, the stack they reach for, the problems their projects solve, and how they ' +
+ 'describe their own work. Use only what the material states; never guess or extrapolate. ' +
+ `Output ONLY a JSON array of at most ${MAX_FACTS} strings, no other text.`;
+
+// ── Fact parsing ──────────────────────────────────────────────────────────────
+
+/**
+ * Parse the model's reply into clean fact strings. Models fence JSON often
+ * enough that an unfenced parse silently seeds zero memories and reads to the
+ * user as "GitHub had nothing to say about me".
+ */
+export function parseFacts(raw, max = MAX_FACTS) {
+ if (typeof raw !== 'string') return [];
+ let body = raw.trim();
+ const fenced = body.match(/```(?:json)?\s*([\s\S]*?)```/i);
+ if (fenced) body = fenced[1].trim();
+ const start = body.indexOf('[');
+ const end = body.lastIndexOf(']');
+ if (start < 0 || end <= start) return [];
+
+ let parsed;
+ try {
+ parsed = JSON.parse(body.slice(start, end + 1));
+ } catch {
+ return [];
+ }
+ if (!Array.isArray(parsed)) return [];
+
+ const seen = new Set();
+ const facts = [];
+ for (const item of parsed) {
+ if (typeof item !== 'string') continue;
+ const fact = item.trim().slice(0, MAX_FACT_CHARS);
+ if (!fact) continue;
+ const dedupeKey = fact.toLowerCase();
+ if (seen.has(dedupeKey)) continue;
+ seen.add(dedupeKey);
+ facts.push(fact);
+ if (facts.length >= max) break;
+ }
+ return facts;
+}
+
+// ── Memory rows ───────────────────────────────────────────────────────────────
+
+/** The audit trail stored on every seeded memory: exactly what the user ticked. */
+export function selectionManifest(resolved) {
+ return {
+ profile: Boolean(resolved.profile),
+ repos: resolved.repos.map((r) => r.key),
+ readmes: [...(resolved.readmeKeys ?? [])],
+ };
+}
+
+export function toMemoryRows(agentId, facts, { login, resolved, seededAt }) {
+ const context = {
+ source: GITHUB_SEED_SOURCE,
+ login,
+ seeded_at: seededAt,
+ selection: selectionManifest(resolved),
+ };
+ return facts.map((fact) => ({
+ agent_id: agentId,
+ type: 'reference',
+ content: fact,
+ tags: GITHUB_SEED_TAGS,
+ context,
+ salience: 0.7,
+ }));
+}
diff --git a/api/_lib/github-token.js b/api/_lib/github-token.js
new file mode 100644
index 000000000..f9e4037a8
--- /dev/null
+++ b/api/_lib/github-token.js
@@ -0,0 +1,55 @@
+// Encryption for stored GitHub OAuth access tokens.
+//
+// The key is derived from JWT_SECRET with HKDF-SHA256 and the fixed salt
+// 'github-token', so a rotated JWT_SECRET invalidates stored tokens (the user
+// reconnects) rather than decrypting them into garbage. This module is the one
+// definition of that derivation: the OAuth callback, the seeding endpoints, and
+// disconnect all import it, so the salt can never drift between writer and
+// reader.
+
+import { webcrypto } from 'node:crypto';
+import { env } from './env.js';
+
+const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
+const IV_BYTES = 12;
+
+async function deriveKey(usages) {
+ const raw = new TextEncoder().encode(env.JWT_SECRET);
+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
+ return subtle.deriveKey(
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: new TextEncoder().encode('github-token'),
+ info: new Uint8Array(0),
+ },
+ base,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ usages,
+ );
+}
+
+export async function encryptGithubToken(plaintext) {
+ const key = await deriveKey(['encrypt', 'decrypt']);
+ const iv = new Uint8Array(IV_BYTES);
+ (globalThis.crypto || webcrypto).getRandomValues(iv);
+ const ct = await subtle.encrypt(
+ { name: 'AES-GCM', iv },
+ key,
+ new TextEncoder().encode(plaintext),
+ );
+ const buf = new Uint8Array(iv.length + ct.byteLength);
+ buf.set(iv, 0);
+ buf.set(new Uint8Array(ct), iv.length);
+ return Buffer.from(buf).toString('base64');
+}
+
+export async function decryptGithubToken(ciphertext) {
+ const key = await deriveKey(['decrypt']);
+ const buf = Buffer.from(ciphertext, 'base64');
+ const iv = buf.subarray(0, IV_BYTES);
+ const ct = buf.subarray(IV_BYTES);
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
+ return new TextDecoder().decode(plain);
+}
diff --git a/api/agents/[id]/memory-seed-github.js b/api/agents/[id]/memory-seed-github.js
new file mode 100644
index 000000000..8a8fcc618
--- /dev/null
+++ b/api/agents/[id]/memory-seed-github.js
@@ -0,0 +1,236 @@
+// GET /api/agents/:id/memory/seed/github — connection status + the catalog the user picks from
+// POST /api/agents/:id/memory/seed/github — seed memory from the selection the user ticked
+// DELETE /api/agents/:id/memory/seed/github — delete every GitHub-seeded memory on this agent
+//
+// Consent-first: the GET reads GitHub and stores nothing. The POST reads only
+// the profile, repos, and READMEs named in the body, and refuses the whole run
+// if any of them is outside the catalog the user was shown.
+//
+// Auth: session (or bearer) user must own the agent AND hold a live 'github'
+// social_connection. Rate limit: 1 seed per agent per 6 hours.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { llmComplete } from '../../_lib/llm.js';
+import { isUuid, parse } from '../../_lib/validate.js';
+import { decryptGithubToken } from '../../_lib/github-token.js';
+import { fetchProfile, fetchRepos, fetchPinnedRepos, fetchReadme } from '../../_lib/github-api.js';
+import {
+ buildCatalog,
+ buildSeedDocument,
+ parseFacts,
+ readmeExcerpt,
+ resolveSelection,
+ selectionManifest,
+ selectionSchema,
+ toMemoryRows,
+ MAX_FACTS,
+ SEED_SYSTEM_PROMPT,
+} from '../../_lib/github-seed.js';
+
+// ── Shared preconditions ──────────────────────────────────────────────────────
+
+async function requireOwnedAgent(req, agentId) {
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId;
+ if (!userId) throw Object.assign(new Error('sign in required'), { status: 401, code: 'unauthorized' });
+
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
+ `;
+ if (!agent) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });
+ return userId;
+}
+
+async function githubConnection(userId) {
+ const [conn] = await sql`
+ SELECT id, username, access_token, connected_at FROM social_connections
+ WHERE user_id = ${userId} AND provider = 'github'
+ LIMIT 1
+ `;
+ return conn ?? null;
+}
+
+async function seedStats(agentId) {
+ const [row] = await sql`
+ SELECT
+ count(*)::int AS fact_count,
+ max(created_at) AS seeded_at,
+ (array_agg(context ORDER BY created_at DESC))[1] AS latest_context
+ FROM agent_memories
+ WHERE agent_id = ${agentId} AND context->>'source' = 'github_seed'
+ `;
+ const ctx = row?.latest_context ?? null;
+ const parsed = typeof ctx === 'string' ? JSON.parse(ctx) : ctx;
+ return {
+ fact_count: row?.fact_count ?? 0,
+ seeded_at: row?.seeded_at ?? null,
+ selection: parsed?.selection ?? null,
+ };
+}
+
+async function loadCatalog(token) {
+ const profile = await fetchProfile(token);
+ const [pinned, repos] = await Promise.all([
+ fetchPinnedRepos(token, profile.login),
+ fetchRepos(token),
+ ]);
+ return buildCatalog({ profile, pinned, repos });
+}
+
+// ── GET — status and consent catalog ─────────────────────────────────────────
+
+async function handleGet(req, res, agentId) {
+ const userId = await requireOwnedAgent(req, agentId);
+ const conn = await githubConnection(userId);
+ const stats = await seedStats(agentId);
+
+ if (!conn) {
+ return json(res, 200, {
+ connected: false,
+ username: null,
+ connect_url: `/api/auth/github/connect?agent_id=${encodeURIComponent(agentId)}`,
+ catalog: null,
+ ...stats,
+ });
+ }
+
+ const token = await decryptGithubToken(conn.access_token);
+ const catalog = await loadCatalog(token);
+
+ return json(res, 200, {
+ connected: true,
+ username: conn.username,
+ connected_at: conn.connected_at,
+ catalog,
+ ...stats,
+ });
+}
+
+// ── POST — seed from the user's selection ────────────────────────────────────
+
+async function handlePost(req, res, agentId) {
+ const userId = await requireOwnedAgent(req, agentId);
+
+ // The seed budget is consumed only after ownership is proven, so a signed-in
+ // stranger cannot burn another agent's window by guessing its id.
+ const rl = await limits.githubSeed(agentId);
+ if (!rl.success) return rateLimited(res, rl, 'this agent can only be re-seeded every 6 hours');
+
+ const conn = await githubConnection(userId);
+ if (!conn) {
+ return error(res, 412, 'not_connected', 'connect GitHub first', {
+ connect_url: `/api/auth/github/connect?agent_id=${encodeURIComponent(agentId)}`,
+ });
+ }
+
+ const selection = parse(selectionSchema, (await readJson(req)) ?? {});
+ const token = await decryptGithubToken(conn.access_token);
+ const catalog = await loadCatalog(token);
+ const resolved = resolveSelection(catalog, selection);
+
+ if (resolved.rejected.length) {
+ return error(
+ res,
+ 400,
+ 'invalid_selection',
+ 'some selected items are not in your GitHub catalog',
+ { rejected: resolved.rejected },
+ );
+ }
+ if (resolved.isEmpty) {
+ return error(
+ res,
+ 400,
+ 'empty_selection',
+ 'pick your profile or at least one repository to seed from',
+ );
+ }
+
+ const readmes = new Map();
+ for (const key of resolved.readmeKeys) {
+ const markdown = await fetchReadme(token, key);
+ if (markdown) readmes.set(key, readmeExcerpt(markdown));
+ }
+
+ const document = buildSeedDocument(resolved, readmes);
+ const { text: raw } = await llmComplete({
+ maxTokens: 1500,
+ system: SEED_SYSTEM_PROMPT,
+ user: `Extract up to ${MAX_FACTS} memory facts from this GitHub material:\n\n${document}`,
+ });
+ const facts = parseFacts(raw);
+ const seededAt = new Date().toISOString();
+ const manifest = selectionManifest(resolved);
+
+ if (facts.length === 0) {
+ return error(
+ res,
+ 502,
+ 'distill_error',
+ 'the selected material did not yield any usable facts — try adding a README or another repository',
+ );
+ }
+
+ const rows = toMemoryRows(agentId, facts, {
+ login: conn.username,
+ resolved,
+ seededAt,
+ });
+
+ // Replace the previous GitHub seed atomically. A mid-loop failure must not
+ // leave the agent with its old memories deleted and only part of the new set,
+ // because the 6-hour limiter would then block the repair.
+ await sql.transaction([
+ sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND context->>'source' = 'github_seed'`,
+ ...rows.map(
+ (row) => sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)
+ VALUES (${row.agent_id}, ${row.type}, ${row.content}, ${row.tags}, ${JSON.stringify(row.context)}::jsonb, ${row.salience})
+ `,
+ ),
+ ]);
+
+ return json(res, 200, {
+ username: conn.username,
+ seeded: facts.length,
+ facts,
+ seeded_at: seededAt,
+ selection: manifest,
+ readmes_read: [...readmes.keys()],
+ });
+}
+
+// ── DELETE — revoke this agent's seeded memories ─────────────────────────────
+
+async function handleDelete(req, res, agentId) {
+ await requireOwnedAgent(req, agentId);
+ const deleted = await sql`
+ DELETE FROM agent_memories
+ WHERE agent_id = ${agentId} AND context->>'source' = 'github_seed'
+ RETURNING id
+ `;
+ return json(res, 200, { deleted: deleted.length });
+}
+
+// ── dispatch ──────────────────────────────────────────────────────────────────
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+
+ const agentId = req.query?.id;
+ if (!agentId) return error(res, 400, 'validation_error', 'agent id required');
+ // This route has its own rewrite, so the uuid gate in api/agents/[id].js never
+ // runs for it. A malformed id would otherwise reach a uuid column and turn a
+ // Postgres 22P02 into a 500.
+ if (!isUuid(agentId)) return error(res, 404, 'not_found', 'agent not found');
+
+ if (req.method === 'GET') return handleGet(req, res, agentId);
+ if (req.method === 'POST') return handlePost(req, res, agentId);
+ if (req.method === 'DELETE') return handleDelete(req, res, agentId);
+ return method(req, res, ['GET', 'POST', 'DELETE']);
+});
diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.js
index 00968fea5..814139bd7 100644
--- a/api/agents/_id/memory-seed.js
+++ b/api/agents/_id/memory-seed.js
@@ -1,123 +1,38 @@
// POST /api/agents/:id/memory-seed
-// Seeds agent memories from GitHub activity using Claude Haiku to distill facts.
-// Requires: session auth, agent ownership, github social connection.
+//
+// The preset GitHub seed: with no body it uses the smallest meaningful
+// selection, the developer's public profile plus the repos they pinned to it.
+// A body may narrow or widen that within the same consent catalog, using the
+// identical schema as POST /api/agents/:id/memory/seed/github, which is the
+// granular surface where the user ticks items one by one.
+//
+// Both routes share api/_lib/github-seed.js, so they read the same public-only
+// catalog, write the same memory shape, and are revoked by the same delete.
+//
+// Requires: session or bearer auth, agent ownership, a github social connection.
// Rate-limited to 1 seed per agent per 24 hours.
-import { webcrypto } from 'node:crypto';
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, error, rateLimited, serverError } from '../../_lib/http.js';
-import { env } from '../../_lib/env.js';
+import { cors, json, method, readJson, error, rateLimited, serverError } from '../../_lib/http.js';
import { llmComplete } from '../../_lib/llm.js';
import { limits } from '../../_lib/rate-limit.js';
-
-const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
-
-// ── Token decryption (mirrors the HKDF derivation in auth/github/[action].js) ─
-
-async function decryptToken(ciphertext) {
- const raw = new TextEncoder().encode(env.JWT_SECRET);
- const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
- const key = await subtle.deriveKey(
- {
- name: 'HKDF',
- hash: 'SHA-256',
- salt: new TextEncoder().encode('github-token'),
- info: new Uint8Array(0),
- },
- base,
- { name: 'AES-GCM', length: 256 },
- false,
- ['decrypt'],
- );
- const buf = Buffer.from(ciphertext, 'base64');
- const iv = buf.subarray(0, 12);
- const ct = buf.subarray(12);
- const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
- return new TextDecoder().decode(plain);
-}
-
-// ── GitHub data fetch ─────────────────────────────────────────────────────────
-
-async function fetchGitHubData(accessToken, login) {
- const headers = {
- authorization: `token ${accessToken}`,
- 'user-agent': 'three.ws/1.0',
- };
-
- const [profileRes, reposRes] = await Promise.all([
- fetch('https://api.github.com/user', { headers }),
- fetch('https://api.github.com/user/repos?sort=pushed&per_page=30', { headers }),
- ]);
-
- if (!profileRes.ok) throw new Error(`GitHub profile fetch failed: ${profileRes.status}`);
- if (!reposRes.ok) throw new Error(`GitHub repos fetch failed: ${reposRes.status}`);
-
- const profile = await profileRes.json();
- const repos = await reposRes.json();
-
- // Commits from top 3 non-fork repos
- const topRepos = Array.isArray(repos) ? repos.filter((r) => !r.fork).slice(0, 3) : [];
- const commitLists = await Promise.all(
- topRepos.map((repo) =>
- fetch(
- `https://api.github.com/repos/${repo.full_name}/commits?author=${login}&per_page=5`,
- { headers },
- )
- .then((r) => (r.ok ? r.json() : []))
- .then((commits) =>
- Array.isArray(commits)
- ? commits.map((c) => c.commit?.message).filter(Boolean)
- : [],
- ),
- ),
- );
-
- return {
- profile: {
- login: profile.login,
- name: profile.name,
- bio: profile.bio,
- company: profile.company,
- location: profile.location,
- public_repos: profile.public_repos,
- followers: profile.followers,
- },
- repos: (Array.isArray(repos) ? repos : []).slice(0, 20).map((r) => ({
- name: r.name,
- description: r.description,
- language: r.language,
- stars: r.stargazers_count,
- pushed_at: r.pushed_at,
- fork: r.fork,
- })),
- recent_commits: commitLists.flat().slice(0, 20),
- };
-}
-
-// ── Claude Haiku distillation ─────────────────────────────────────────────────
-
-async function distillFacts(githubData) {
- const { text: raw } = await llmComplete({
- maxTokens: 1024,
- system:
- 'You distill GitHub activity into concise memory facts for an AI agent. ' +
- 'Each fact is a single self-contained sentence about the developer: tech stack, ' +
- 'project types, commit style, interests, or notable contributions. ' +
- 'Output ONLY a JSON array of strings, no other text.',
- user:
- `Extract up to 15 memory facts from this GitHub profile data:\n` +
- JSON.stringify(githubData, null, 2),
- });
- try {
- const facts = JSON.parse(raw);
- return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
- } catch {
- return [];
- }
-}
-
-// ── Handler ───────────────────────────────────────────────────────────────────
+import { parse } from '../../_lib/validate.js';
+import { decryptGithubToken } from '../../_lib/github-token.js';
+import { fetchProfile, fetchRepos, fetchPinnedRepos, fetchReadme } from '../../_lib/github-api.js';
+import {
+ buildCatalog,
+ buildSeedDocument,
+ defaultSelection,
+ parseFacts,
+ readmeExcerpt,
+ resolveSelection,
+ selectionManifest,
+ selectionSchema,
+ toMemoryRows,
+ MAX_FACTS,
+ SEED_SYSTEM_PROMPT,
+} from '../../_lib/github-seed.js';
export default async function handleMemorySeed(req, res, agentId) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -128,77 +43,123 @@ export default async function handleMemorySeed(req, res, agentId) {
const userId = session?.id ?? bearer?.userId;
if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
- // Verify agent ownership
const [agent] = await sql`
SELECT id FROM agent_identities
WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
- // Verify GitHub connection
const [conn] = await sql`
SELECT access_token, username FROM social_connections
WHERE user_id = ${userId} AND provider = 'github'
`;
if (!conn) {
- return error(res, 412, 'not_connected', 'connect GitHub first at /settings?tab=connected-accounts');
+ return error(
+ res,
+ 412,
+ 'not_connected',
+ 'connect GitHub first at /settings?tab=connected-accounts',
+ );
}
- // Rate limit: 1 seed per agent per 24 hours
const rl = await limits.memorySeed(agentId);
if (!rl.success) {
return rateLimited(res, rl, 'memory seeding is limited to once per 24 hours');
}
+ const body = (await readJson(req)) ?? {};
+ const requested = Object.keys(body).length ? parse(selectionSchema, body) : null;
+
let accessToken;
try {
- accessToken = await decryptToken(conn.access_token);
+ accessToken = await decryptGithubToken(conn.access_token);
} catch (e) {
console.error('[memory-seed] token decrypt failed', e);
return error(res, 500, 'internal_error', 'could not decrypt stored token');
}
- let githubData;
+ let catalog;
try {
- githubData = await fetchGitHubData(accessToken, conn.username);
+ const profile = await fetchProfile(accessToken);
+ const [pinned, repos] = await Promise.all([
+ fetchPinnedRepos(accessToken, profile.login),
+ fetchRepos(accessToken),
+ ]);
+ catalog = buildCatalog({ profile, pinned, repos });
} catch (e) {
console.error('[memory-seed] GitHub API fetch failed', e?.message);
return serverError(res, 502, 'upstream_error', e);
}
+ const selection = requested ?? defaultSelection(catalog);
+ const resolved = resolveSelection(catalog, selection);
+ if (resolved.rejected.length) {
+ return error(res, 400, 'invalid_selection', 'some selected items are not in your GitHub catalog', {
+ rejected: resolved.rejected,
+ });
+ }
+ if (resolved.isEmpty) {
+ return error(
+ res,
+ 400,
+ 'empty_selection',
+ 'no public profile or pinned repositories to seed from — pick repositories explicitly',
+ );
+ }
+
+ const readmes = new Map();
+ try {
+ for (const key of resolved.readmeKeys) {
+ const markdown = await fetchReadme(accessToken, key);
+ if (markdown) readmes.set(key, readmeExcerpt(markdown));
+ }
+ } catch (e) {
+ console.error('[memory-seed] README fetch failed', e?.message);
+ return serverError(res, 502, 'upstream_error', e);
+ }
+
let facts;
try {
- facts = await distillFacts(githubData);
+ const { text: raw } = await llmComplete({
+ maxTokens: 1500,
+ system: SEED_SYSTEM_PROMPT,
+ user: `Extract up to ${MAX_FACTS} memory facts from this GitHub material:\n\n${buildSeedDocument(resolved, readmes)}`,
+ });
+ facts = parseFacts(raw);
} catch (e) {
console.error('[memory-seed] distill failed', e);
return error(res, 502, 'distill_error', 'could not distill facts from GitHub data');
}
+ const seededAt = new Date().toISOString();
if (facts.length === 0) {
- return json(res, 200, { seeded: 0, facts: [], seeded_at: new Date().toISOString() });
+ return json(res, 200, {
+ seeded: 0,
+ facts: [],
+ seeded_at: seededAt,
+ selection: selectionManifest(resolved),
+ });
}
- // Replace previous github memories with the fresh distillation atomically, so
- // a mid-loop failure can't leave the agent with its old memories deleted and
- // only a partial new set (the 24h rate limit would then block a retry).
- const seededAt = new Date().toISOString();
- const ctx = JSON.stringify({ source: 'github_seed', seeded_at: seededAt });
+ const rows = toMemoryRows(agentId, facts, { login: conn.username, resolved, seededAt });
+
+ // Replace the previous GitHub seed atomically, so a mid-loop failure can't
+ // leave the agent with its old memories deleted and only a partial new set
+ // (the 24h rate limit would then block a retry).
await sql.transaction([
- sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND 'github' = ANY(tags)`,
- ...facts.map(
- (fact) => sql`
+ sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND context->>'source' = 'github_seed'`,
+ ...rows.map(
+ (row) => sql`
INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)
- VALUES (
- ${agentId},
- 'reference',
- ${fact.slice(0, 10000)},
- ${['github']},
- ${ctx}::jsonb,
- 0.7
- )
+ VALUES (${row.agent_id}, ${row.type}, ${row.content}, ${row.tags}, ${JSON.stringify(row.context)}::jsonb, ${row.salience})
`,
),
]);
- return json(res, 200, { seeded: facts.length, facts, seeded_at: seededAt });
+ return json(res, 200, {
+ seeded: facts.length,
+ facts,
+ seeded_at: seededAt,
+ selection: selectionManifest(resolved),
+ });
}
diff --git a/api/auth/github/[action].js b/api/auth/github/[action].js
index 48a8ba3bd..17f15bb9e 100644
--- a/api/auth/github/[action].js
+++ b/api/auth/github/[action].js
@@ -1,47 +1,18 @@
// GitHub OAuth social connect.
-// Routes: /api/auth/github/connect — redirect to GitHub OAuth
-// /api/auth/github/callback — exchange code, store encrypted token
-// /api/auth/github/status — connection status for the signed-in user
+// Routes: /api/auth/github/connect — redirect to GitHub OAuth
+// /api/auth/github/callback — exchange code, store encrypted token
+// /api/auth/github/status — connection status for the signed-in user
+// /api/auth/github/disconnect — revoke the grant and delete every memory
+// seeded from GitHub across the user's agents
-import { webcrypto } from 'node:crypto';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { cors, json, redirect, error, method, wrap, rateLimited } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
-
-const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
-
-// ── Key derivation (HKDF from JWT_SECRET, info = 'github-token') ──────────────
-
-async function deriveKey() {
- const raw = new TextEncoder().encode(env.JWT_SECRET);
- const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
- return subtle.deriveKey(
- {
- name: 'HKDF',
- hash: 'SHA-256',
- salt: new TextEncoder().encode('github-token'),
- info: new Uint8Array(0),
- },
- base,
- { name: 'AES-GCM', length: 256 },
- false,
- ['encrypt', 'decrypt'],
- );
-}
-
-async function encryptToken(plaintext) {
- const key = await deriveKey();
- const iv = new Uint8Array(12);
- (globalThis.crypto || webcrypto).getRandomValues(iv);
- const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));
- const buf = new Uint8Array(iv.length + ct.byteLength);
- buf.set(iv, 0);
- buf.set(new Uint8Array(ct), iv.length);
- return Buffer.from(buf).toString('base64');
-}
+import { encryptGithubToken, decryptGithubToken } from '../../_lib/github-token.js';
+import { revokeGrant } from '../../_lib/github-api.js';
// ── CSRF state (HMAC-signed payload) ─────────────────────────────────────────
@@ -166,7 +137,7 @@ async function handleCallback(req, res) {
}
const profile = await profileRes.json();
- const encryptedToken = await encryptToken(tokenData.access_token);
+ const encryptedToken = await encryptGithubToken(tokenData.access_token);
await sql`
INSERT INTO social_connections (user_id, provider, provider_uid, username, access_token, scopes)
@@ -207,11 +178,74 @@ async function handleStatus(req, res) {
WHERE user_id = ${session.id} AND provider = 'github'
`;
- if (!row) return json(res, 200, { connected: false });
+ if (!row) return json(res, 200, { connected: false, seeded_fact_count: 0 });
+
+ const [seeded] = await sql`
+ SELECT count(*)::int AS n
+ FROM agent_memories m
+ JOIN agent_identities a ON a.id = m.agent_id
+ WHERE a.user_id = ${session.id} AND m.context->>'source' = 'github_seed'
+ `;
+
return json(res, 200, {
connected: true,
username: row.username,
connected_at: row.connected_at,
+ seeded_fact_count: seeded?.n ?? 0,
+ });
+}
+
+// ── disconnect ────────────────────────────────────────────────────────────────
+
+/**
+ * Revocation is not just "forget the token". Everything the connection was used
+ * to learn goes with it: every memory seeded from GitHub, on every agent this
+ * user owns, is deleted in the same transaction that drops the connection. The
+ * grant is also revoked on GitHub's side so the token stops working there too.
+ */
+async function handleDisconnect(req, res) {
+ if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST', 'DELETE'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [row] = await sql`
+ SELECT id, access_token FROM social_connections
+ WHERE user_id = ${session.id} AND provider = 'github'
+ `;
+ if (!row) return json(res, 200, { disconnected: false, memories_deleted: 0 });
+
+ const [deleted] = await sql.transaction([
+ sql`
+ DELETE FROM agent_memories
+ WHERE context->>'source' = 'github_seed'
+ AND agent_id IN (SELECT id FROM agent_identities WHERE user_id = ${session.id})
+ RETURNING id
+ `,
+ sql`DELETE FROM social_connections WHERE id = ${row.id}`,
+ ]);
+
+ // GitHub-side revocation is best effort: the local grant is already gone, and
+ // a GitHub outage must not leave the user's memories un-deleted.
+ let revoked = false;
+ if (env.GITHUB_OAUTH_CLIENT_ID && env.GITHUB_OAUTH_CLIENT_SECRET) {
+ try {
+ const token = await decryptGithubToken(row.access_token);
+ revoked = await revokeGrant(
+ token,
+ env.GITHUB_OAUTH_CLIENT_ID,
+ env.GITHUB_OAUTH_CLIENT_SECRET,
+ );
+ } catch (e) {
+ console.error('[auth/github] grant revoke failed', e?.message);
+ }
+ }
+
+ return json(res, 200, {
+ disconnected: true,
+ memories_deleted: deleted.length,
+ grant_revoked: revoked,
});
}
@@ -224,5 +258,6 @@ export default wrap(async (req, res) => {
if (action === 'connect') return handleConnect(req, res);
if (action === 'callback') return handleCallback(req, res);
if (action === 'status') return handleStatus(req, res);
+ if (action === 'disconnect') return handleDisconnect(req, res);
return error(res, 404, 'not_found', 'unknown github auth action');
});
diff --git a/vercel.json b/vercel.json
index 0718d45a2..006bafad5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2756,6 +2756,10 @@
"src": "/api/agents/([^/]+)/memory/seed/x",
"dest": "/api/agents/[id]/memory-seed-x?id=$1"
},
+ {
+ "src": "/api/agents/([^/]+)/memory/seed/github",
+ "dest": "/api/agents/[id]/memory-seed-github?id=$1"
+ },
{
"src": "/api/agents/([^/]+)/memory/seed/farcaster",
"dest": "/api/agents/[id]"
@@ -2896,6 +2900,10 @@
"src": "/api/auth/github/status",
"dest": "/api/auth/github/[action]?action=status"
},
+ {
+ "src": "/api/auth/github/disconnect",
+ "dest": "/api/auth/github/[action]?action=disconnect"
+ },
{
"src": "/api/auth/x/connect",
"dest": "/api/auth/x/[action]?action=connect"