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: implement GitHub memory seeding and subscription management UI

nirholas55b8d079cf98
diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.js
new file mode 100644
index 000000000..151deacbf
--- /dev/null
+++ b/api/agents/_id/memory-seed.js
@@ -0,0 +1,221 @@
+// 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.
+// 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 } from '../../_lib/http.js';
+import { env } from '../../_lib/env.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 res = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'x-api-key': env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 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.',
+ messages: [
+ {
+ role: 'user',
+ content:
+ `Extract up to 15 memory facts from this GitHub profile data:\n` +
+ JSON.stringify(githubData, null, 2),
+ },
+ ],
+ }),
+ });
+
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw new Error(`Claude API error ${res.status}: ${text.slice(0, 200)}`);
+ }
+
+ const data = await res.json();
+ const raw = data.content?.[0]?.text || '[]';
+ try {
+ const facts = JSON.parse(raw);
+ return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
+ } catch {
+ return [];
+ }
+}
+
+// ── Handler ───────────────────────────────────────────────────────────────────
+
+export default async function handleMemorySeed(req, res, agentId) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ 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');
+ }
+
+ // Rate limit: 1 seed per agent per 24 hours
+ const rl = await limits.memorySeed(agentId);
+ if (!rl.success) {
+ return error(res, 429, 'rate_limited', 'memory seeding is limited to once per 24 hours');
+ }
+
+ let accessToken;
+ try {
+ accessToken = await decryptToken(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;
+ try {
+ githubData = await fetchGitHubData(accessToken, conn.username);
+ } catch (e) {
+ return error(res, 502, 'upstream_error', e.message || 'GitHub API fetch failed');
+ }
+
+ let facts;
+ try {
+ facts = await distillFacts(githubData);
+ } catch (e) {
+ console.error('[memory-seed] distill failed', e);
+ return error(res, 502, 'distill_error', 'could not distill facts from GitHub data');
+ }
+
+ if (facts.length === 0) {
+ return json(res, 200, { seeded: 0, facts: [], seeded_at: new Date().toISOString() });
+ }
+
+ // Replace previous github memories with fresh distillation
+ await sql`DELETE FROM agent_memories WHERE agent_id = ${agentId} AND 'github' = ANY(tags)`;
+
+ const seededAt = new Date().toISOString();
+ const ctx = JSON.stringify({ source: 'github_seed', seeded_at: seededAt });
+ for (const fact of facts) {
+ await sql`
+ INSERT INTO agent_memories (agent_id, type, content, tags, context, salience)
+ VALUES (
+ ${agentId},
+ 'reference',
+ ${fact.slice(0, 10000)},
+ ${['github']},
+ ${ctx}::jsonb,
+ 0.7
+ )
+ `;
+ }
+
+ return json(res, 200, { seeded: facts.length, facts, seeded_at: seededAt });
+}
diff --git a/chat/vite.config.js.timestamp-1777603415444-d7d293ad0df52.mjs b/chat/vite.config.js.timestamp-1777603415444-d7d293ad0df52.mjs
new file mode 100644
index 000000000..1b332c42b
--- /dev/null
+++ b/chat/vite.config.js.timestamp-1777603415444-d7d293ad0df52.mjs
@@ -0,0 +1,43 @@
+// vite.config.js
+import { defineConfig } from "file:///workspaces/3D-Agent/chat/node_modules/vite/dist/node/index.js";
+import { svelte } from "file:///workspaces/3D-Agent/node_modules/@sveltejs/vite-plugin-svelte/src/index.js";
+import viteCompression from "file:///workspaces/3D-Agent/node_modules/vite-plugin-compression/dist/index.mjs";
+import path from "path";
+var __vite_injected_original_dirname = "/workspaces/3D-Agent/chat";
+var vite_config_default = defineConfig(function() {
+ const buildTimestamp = /* @__PURE__ */ new Date();
+ return {
+ base: "/chat/",
+ build: {
+ outDir: "../public/chat",
+ emptyOutDir: true
+ },
+ server: {
+ // Forward /api requests to the 3D-Agent dev server (vercel dev on port 3000)
+ proxy: {
+ "/api": { target: "http://localhost:3000", changeOrigin: true }
+ }
+ },
+ plugins: [
+ svelte(),
+ viteCompression({
+ filter: /^(?!.*pdf\.worker\.min-[A-Z0-9]+\.mjs$).*\.(js|mjs|json|css|html)$/i
+ })
+ ],
+ resolve: {
+ alias: {
+ "$src": path.resolve(__vite_injected_original_dirname, "./src")
+ }
+ },
+ define: {
+ "import.meta.env.BUILD_TIMESTAMP": JSON.stringify(buildTimestamp.toLocaleString())
+ },
+ optimizeDeps: {
+ include: ["svelte-fast-dimension/action"]
+ }
+ };
+});
+export {
+ vite_config_default as default
+};
+//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidml0ZS5jb25maWcuanMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImNvbnN0IF9fdml0ZV9pbmplY3RlZF9vcmlnaW5hbF9kaXJuYW1lID0gXCIvd29ya3NwYWNlcy8zRC1BZ2VudC9jaGF0XCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ZpbGVuYW1lID0gXCIvd29ya3NwYWNlcy8zRC1BZ2VudC9jaGF0L3ZpdGUuY29uZmlnLmpzXCI7Y29uc3QgX192aXRlX2luamVjdGVkX29yaWdpbmFsX2ltcG9ydF9tZXRhX3VybCA9IFwiZmlsZTovLy93b3Jrc3BhY2VzLzNELUFnZW50L2NoYXQvdml0ZS5jb25maWcuanNcIjtpbXBvcnQgeyBkZWZpbmVDb25maWcgfSBmcm9tICd2aXRlJztcbmltcG9ydCB7IHN2ZWx0ZSB9IGZyb20gJ0BzdmVsdGVqcy92aXRlLXBsdWdpbi1zdmVsdGUnO1xuaW1wb3J0IHZpdGVDb21wcmVzc2lvbiBmcm9tICd2aXRlLXBsdWdpbi1jb21wcmVzc2lvbic7XG5pbXBvcnQgcGF0aCBmcm9tICdwYXRoJztcblxuZXhwb3J0IGRlZmF1bHQgZGVmaW5lQ29uZmlnKGZ1bmN0aW9uICgpIHtcblx0Y29uc3QgYnVpbGRUaW1lc3RhbXAgPSBuZXcgRGF0ZSgpO1xuXHRyZXR1cm4ge1xuXHRcdGJhc2U6ICcvY2hhdC8nLFxuXHRcdGJ1aWxkOiB7XG5cdFx0XHRvdXREaXI6ICcuLi9wdWJsaWMvY2hhdCcsXG5cdFx0XHRlbXB0eU91dERpcjogdHJ1ZSxcblx0XHR9LFxuXHRcdHNlcnZlcjoge1xuXHRcdFx0Ly8gRm9yd2FyZCAvYXBpIHJlcXVlc3RzIHRvIHRoZSAzRC1BZ2VudCBkZXYgc2VydmVyICh2ZXJjZWwgZGV2IG9uIHBvcnQgMzAwMClcblx0XHRcdHByb3h5OiB7XG5cdFx0XHRcdCcvYXBpJzogeyB0YXJnZXQ6ICdodHRwOi8vbG9jYWxob3N0OjMwMDAnLCBjaGFuZ2VPcmlnaW46IHRydWUgfSxcblx0XHRcdH0sXG5cdFx0fSxcblx0XHRwbHVnaW5zOiBbXG5cdFx0XHRzdmVsdGUoKSxcblx0XHRcdHZpdGVDb21wcmVzc2lvbih7XG5cdFx0XHRcdGZpbHRlcjogL14oPyEuKnBkZlxcLndvcmtlclxcLm1pbi1bQS1aMC05XStcXC5tanMkKS4qXFwuKGpzfG1qc3xqc29ufGNzc3xodG1sKSQvaSxcblx0XHRcdH0pLFxuXHRcdF0sXG5cdFx0cmVzb2x2ZToge1xuXHRcdFx0YWxpYXM6IHtcblx0XHRcdFx0JyRzcmMnOiBwYXRoLnJlc29sdmUoX19kaXJuYW1lLCAnLi9zcmMnKSxcblx0XHRcdH1cblx0XHR9LFxuXHRcdGRlZmluZToge1xuXHRcdFx0J2ltcG9ydC5tZXRhLmVudi5CVUlMRF9USU1FU1RBTVAnOiBKU09OLnN0cmluZ2lmeShidWlsZFRpbWVzdGFtcC50b0xvY2FsZVN0cmluZygpKSxcblx0XHR9LFxuXHRcdG9wdGltaXplRGVwczoge1xuXHRcdFx0aW5jbHVkZTogWydzdmVsdGUtZmFzdC1kaW1lbnNpb24vYWN0aW9uJ10sXG5cdFx0fSxcblx0fTtcbn0pO1xuIl0sCiAgIm1hcHBpbmdzIjogIjtBQUE2UCxTQUFTLG9CQUFvQjtBQUMxUixTQUFTLGNBQWM7QUFDdkIsT0FBTyxxQkFBcUI7QUFDNUIsT0FBTyxVQUFVO0FBSGpCLElBQU0sbUNBQW1DO0FBS3pDLElBQU8sc0JBQVEsYUFBYSxXQUFZO0FBQ3ZDLFFBQU0saUJBQWlCLG9CQUFJLEtBQUs7QUFDaEMsU0FBTztBQUFBLElBQ04sTUFBTTtBQUFBLElBQ04sT0FBTztBQUFBLE1BQ04sUUFBUTtBQUFBLE1BQ1IsYUFBYTtBQUFBLElBQ2Q7QUFBQSxJQUNBLFFBQVE7QUFBQTtBQUFBLE1BRVAsT0FBTztBQUFBLFFBQ04sUUFBUSxFQUFFLFFBQVEseUJBQXlCLGNBQWMsS0FBSztBQUFBLE1BQy9EO0FBQUEsSUFDRDtBQUFBLElBQ0EsU0FBUztBQUFBLE1BQ1IsT0FBTztBQUFBLE1BQ1AsZ0JBQWdCO0FBQUEsUUFDZixRQUFRO0FBQUEsTUFDVCxDQUFDO0FBQUEsSUFDRjtBQUFBLElBQ0EsU0FBUztBQUFBLE1BQ1IsT0FBTztBQUFBLFFBQ04sUUFBUSxLQUFLLFFBQVEsa0NBQVcsT0FBTztBQUFBLE1BQ3hDO0FBQUEsSUFDRDtBQUFBLElBQ0EsUUFBUTtBQUFBLE1BQ1AsbUNBQW1DLEtBQUssVUFBVSxlQUFlLGVBQWUsQ0FBQztBQUFBLElBQ2xGO0FBQUEsSUFDQSxjQUFjO0FBQUEsTUFDYixTQUFTLENBQUMsOEJBQThCO0FBQUEsSUFDekM7QUFBQSxFQUNEO0FBQ0QsQ0FBQzsiLAogICJuYW1lcyI6IFtdCn0K
diff --git a/src/pump/launch-token-modal.css b/src/pump/launch-token-modal.css
new file mode 100644
index 000000000..40d1488ee
--- /dev/null
+++ b/src/pump/launch-token-modal.css
@@ -0,0 +1,277 @@
+/* launch-token-modal.css — dark theme modal for pump.fun token launch */
+
+.ltm-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.72);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 9999;
+ opacity: 0;
+ transition: opacity 0.18s ease;
+}
+.ltm-overlay.ltm-open { opacity: 1; }
+
+.ltm-modal {
+ background: #0d0d18;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 14px;
+ width: min(480px, calc(100vw - 2rem));
+ max-height: calc(100vh - 4rem);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.75);
+ color: #e5e5e5;
+ font: 14px/1.5 Inter, system-ui, sans-serif;
+}
+
+/* Header */
+.ltm-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.9rem 1.25rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+ flex-shrink: 0;
+}
+.ltm-title { font-size: 0.82rem; font-weight: 500; color: rgba(255, 255, 255, 0.85); }
+.ltm-header-right { display: flex; align-items: center; gap: 0.75rem; }
+.ltm-steps { display: flex; gap: 0.3rem; align-items: center; }
+.ltm-step-dot {
+ width: 6px; height: 6px; border-radius: 50%;
+ background: rgba(255, 255, 255, 0.12);
+ transition: background 0.2s;
+}
+.ltm-step-dot.active { background: rgba(120, 200, 140, 0.9); }
+.ltm-step-dot.done { background: rgba(120, 200, 140, 0.35); }
+.ltm-close {
+ background: none; border: none;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 1.2rem; line-height: 1;
+ cursor: pointer; padding: 0.2rem 0.35rem;
+ border-radius: 4px; transition: color 0.15s;
+}
+.ltm-close:hover { color: rgba(255, 255, 255, 0.8); }
+
+/* Body */
+.ltm-body {
+ padding: 1.1rem 1.25rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.82rem;
+ overflow-y: auto;
+ flex: 1;
+}
+
+/* Fields */
+.ltm-field { display: flex; flex-direction: column; gap: 0.28rem; }
+.ltm-label {
+ font-size: 0.7rem;
+ color: rgba(255, 255, 255, 0.45);
+ display: flex;
+ gap: 0.3rem;
+ align-items: baseline;
+}
+.ltm-hint {
+ font-size: 0.62rem;
+ color: rgba(255, 255, 255, 0.25);
+}
+.ltm-input,
+.ltm-textarea {
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #e5e5e5;
+ font-size: 0.83rem;
+ padding: 0.48rem 0.75rem;
+ border-radius: 8px;
+ font-family: inherit;
+ width: 100%;
+ box-sizing: border-box;
+ transition: border-color 0.15s;
+}
+.ltm-textarea { resize: vertical; min-height: 60px; }
+.ltm-input:focus, .ltm-textarea:focus {
+ outline: none;
+ border-color: rgba(120, 200, 140, 0.45);
+}
+.ltm-input.ltm-err { border-color: rgba(239, 68, 68, 0.6); }
+.ltm-field-err {
+ font-size: 0.68rem;
+ color: #fca5a5;
+ min-height: 1em;
+}
+.ltm-row { display: flex; gap: 0.75rem; }
+.ltm-row .ltm-field { flex: 1; }
+
+/* Network toggle */
+.ltm-net-row {
+ display: flex;
+ align-items: center;
+ gap: 0.55rem;
+ font-size: 0.75rem;
+ color: rgba(255, 255, 255, 0.5);
+}
+.ltm-toggle {
+ display: flex;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 6px;
+ overflow: hidden;
+}
+.ltm-toggle-btn {
+ background: none; border: none;
+ color: rgba(255, 255, 255, 0.4);
+ padding: 0.22rem 0.65rem;
+ cursor: pointer; font-size: 0.7rem;
+ font-family: inherit;
+ transition: background 0.12s, color 0.12s;
+}
+.ltm-toggle-btn.active {
+ background: rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.9);
+}
+
+/* Footer */
+.ltm-footer {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 0.82rem 1.25rem;
+ border-top: 1px solid rgba(255, 255, 255, 0.07);
+ gap: 0.75rem;
+ flex-shrink: 0;
+}
+.ltm-btn {
+ padding: 0.55rem 1.15rem;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: rgba(255, 255, 255, 0.05);
+ color: rgba(255, 255, 255, 0.75);
+ cursor: pointer; font-size: 0.8rem;
+ font-family: inherit;
+ transition: background 0.15s, border-color 0.15s;
+ white-space: nowrap;
+}
+.ltm-btn:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.09);
+ border-color: rgba(255, 255, 255, 0.22);
+ color: rgba(255, 255, 255, 0.95);
+}
+.ltm-btn:disabled { opacity: 0.4; cursor: not-allowed; }
+.ltm-btn-primary {
+ background: rgba(120, 200, 140, 0.16);
+ border-color: rgba(120, 200, 140, 0.35);
+ color: #d8f5e2;
+}
+.ltm-btn-primary:hover:not(:disabled) {
+ background: rgba(120, 200, 140, 0.25);
+ border-color: rgba(120, 200, 140, 0.5);
+}
+
+/* Quote rows */
+.ltm-quote-block { display: flex; flex-direction: column; }
+.ltm-quote-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: baseline;
+ padding: 0.42rem 0;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);
+ font-size: 0.78rem;
+}
+.ltm-quote-row:last-child { border-bottom: none; }
+.ltm-q-label { color: rgba(255, 255, 255, 0.45); }
+.ltm-q-val { font-variant-numeric: tabular-nums; }
+.ltm-q-val.ltm-total { color: #d8f5e2; font-weight: 500; }
+
+/* Chart */
+.ltm-chart-wrap { margin: 0.2rem 0 0.4rem; }
+.ltm-chart-title {
+ font-size: 0.65rem;
+ color: rgba(255, 255, 255, 0.3);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ margin-bottom: 0.4rem;
+}
+
+/* Wallet / signing section */
+.ltm-wallet-row {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.75rem;
+ border-radius: 10px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+}
+.ltm-wallet-info { flex: 1; min-width: 0; }
+.ltm-wallet-status { font-size: 0.72rem; }
+.ltm-wallet-status.connected { color: #86efac; }
+.ltm-wallet-status.disconnected { color: rgba(255, 200, 100, 0.85); }
+.ltm-wallet-addr {
+ font-family: ui-monospace, monospace;
+ font-size: 0.75rem;
+ color: rgba(255, 255, 255, 0.5);
+ margin-top: 0.15rem;
+}
+.ltm-status-msg {
+ font-size: 0.76rem;
+ color: rgba(255, 255, 255, 0.45);
+ text-align: center;
+ min-height: 1.2em;
+ padding: 0.2rem 0;
+}
+.ltm-status-msg.ltm-err { color: #fca5a5; }
+
+/* Success state */
+.ltm-success {
+ text-align: center;
+ padding: 0.75rem 0.5rem;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.75rem;
+}
+.ltm-success-icon { font-size: 2.4rem; }
+.ltm-success-title {
+ font-size: 1.05rem;
+ font-weight: 300;
+ color: #d8f5e2;
+}
+.ltm-mint-box {
+ font-family: ui-monospace, monospace;
+ font-size: 0.7rem;
+ color: rgba(255, 255, 255, 0.45);
+ word-break: break-all;
+ background: rgba(255, 255, 255, 0.04);
+ padding: 0.55rem 0.75rem;
+ border-radius: 8px;
+ width: 100%;
+ box-sizing: border-box;
+ text-align: left;
+}
+.ltm-pumpfun-link {
+ display: inline-block;
+ padding: 0.55rem 1.4rem;
+ border-radius: 8px;
+ background: rgba(120, 200, 140, 0.16);
+ border: 1px solid rgba(120, 200, 140, 0.35);
+ color: #d8f5e2;
+ text-decoration: none;
+ font-size: 0.82rem;
+ transition: background 0.15s;
+}
+.ltm-pumpfun-link:hover { background: rgba(120, 200, 140, 0.26); }
+
+/* Status spinner (reuse mp-spinner pattern) */
+@keyframes ltm-spin { to { transform: rotate(360deg); } }
+.ltm-spinner {
+ display: inline-block;
+ width: 12px; height: 12px;
+ border: 1.5px solid rgba(255, 255, 255, 0.12);
+ border-top-color: rgba(120, 200, 140, 0.8);
+ border-radius: 50%;
+ animation: ltm-spin 0.75s linear infinite;
+ vertical-align: middle;
+ margin-right: 0.4rem;
+}
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
new file mode 100644
index 000000000..94e2a98b0
--- /dev/null
+++ b/src/pump/launch-token-modal.js
@@ -0,0 +1,556 @@
+/**
+ * Launch Token Modal — pump.fun token launch flow.
+ *
+ * Steps: 1) details form 2) quote + bonding curve 3) wallet sign 4) success
+ *
+ * Usage:
+ * import { openLaunchTokenModal } from './launch-token-modal.js';
+ * openLaunchTokenModal({ agentId, agentName, imageUrl });
+ */
+
+import { mountLaunchBondingCurve } from './bonding-curve-chart.js';
+
+const _isDev =
+ typeof location !== 'undefined' &&
+ (location.hostname === 'localhost' || location.hostname === '127.0.0.1');
+
+function _esc(s) {
+ return String(s ?? '').replace(
+ /[<>&"]/g,
+ (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c],
+ );
+}
+
+function _nameToSymbol(name) {
+ const words = String(name || '')
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ const raw =
+ words.length === 1
+ ? words[0].slice(0, 5)
+ : words.map((w) => w[0] || '').join('').slice(0, 5);
+ return raw.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 5) || 'AGENT';
+}
+
+function _solFmt(v) {
+ if (v == null) return '—';
+ const n = Number(v);
+ return `${n >= 10 ? n.toFixed(3) : n.toFixed(4)} SOL`;
+}
+
+function _apiError(status, data) {
+ const code = data?.error || '';
+ const desc = data?.error_description || '';
+ if (status === 429 || code === 'rate_limited')
+ return 'Too many launch attempts, try again tomorrow';
+ if (status === 404 || code === 'not_found') return null; // caller should close
+ if (
+ status === 403 ||
+ code === 'forbidden' ||
+ code === 'wallet_mismatch' ||
+ desc.toLowerCase().includes('wallet')
+ )
+ return 'Wrong wallet — connect the wallet that owns this agent';
+ return desc || `Request failed (${status})`;
+}
+
+export class LaunchTokenModal {
+ /**
+ * @param {{ agentId: string, agentName?: string, imageUrl?: string }} opts
+ */
+ constructor({ agentId, agentName = 'Agent', imageUrl = '' }) {
+ this.agentId = agentId;
+ this._d = {
+ name: String(agentName).slice(0, 32),
+ symbol: _nameToSymbol(agentName),
+ description: '',
+ image: String(imageUrl),
+ initialBuySol: 0,
+ cluster: 'mainnet',
+ };
+ this._step = 1;
+ this._overlay = null;
+ this._chart = null;
+ this._keyHandler = null;
+ }
+
+ open() {
+ if (this._overlay) return;
+ const el = document.createElement('div');
+ el.className = 'ltm-overlay';
+ document.body.appendChild(el);
+ this._overlay = el;
+ el.addEventListener('click', (e) => {
+ if (e.target === el) this._close();
+ });
+ this._keyHandler = (e) => {
+ if (e.key === 'Escape') this._close();
+ };
+ window.addEventListener('keydown', this._keyHandler);
+ requestAnimationFrame(() => el.classList.add('ltm-open'));
+ this._renderStep1();
+ }
+
+ _close() {
+ if (this._chart) {
+ this._chart.destroy();
+ this._chart = null;
+ }
+ if (!this._overlay) return;
+ this._overlay.classList.remove('ltm-open');
+ const el = this._overlay;
+ this._overlay = null;
+ setTimeout(() => el.remove(), 200);
+ if (this._keyHandler) {
+ window.removeEventListener('keydown', this._keyHandler);
+ this._keyHandler = null;
+ }
+ }
+
+ _stepDots() {
+ return [1, 2, 3, 4]
+ .map(
+ (i) =>
+ `<div class="ltm-step-dot ${this._step === i ? 'active' : this._step > i ? 'done' : ''}"></div>`,
+ )
+ .join('');
+ }
+
+ _shell(title, body, footer) {
+ return `
+ <div class="ltm-modal" role="dialog" aria-modal="true" aria-label="Launch Agent Token">
+ <div class="ltm-header">
+ <span class="ltm-title">${_esc(title)}</span>
+ <div class="ltm-header-right">
+ <div class="ltm-steps">${this._stepDots()}</div>
+ <button class="ltm-close" aria-label="Close modal">×</button>
+ </div>
+ </div>
+ <div class="ltm-body">${body}</div>
+ <div class="ltm-footer">${footer}</div>
+ </div>`;
+ }
+
+ _paint(html) {
+ if (this._chart) {
+ this._chart.destroy();
+ this._chart = null;
+ }
+ if (!this._overlay) return;
+ this._overlay.innerHTML = html;
+ this._overlay.querySelector('.ltm-close')?.addEventListener('click', () => this._close());
+ }
+
+ // ── Step 1 — Token details ────────────────────────────────────────────────
+
+ _renderStep1() {
+ this._step = 1;
+ const d = this._d;
+ const netToggle = _isDev
+ ? `<div class="ltm-net-row">
+ <span>Network:</span>
+ <div class="ltm-toggle">
+ <button class="ltm-toggle-btn${d.cluster === 'mainnet' ? ' active' : ''}" data-net="mainnet">Mainnet</button>
+ <button class="ltm-toggle-btn${d.cluster === 'devnet' ? ' active' : ''}" data-net="devnet">Devnet</button>
+ </div>
+ </div>`
+ : '';
+
+ this._paint(
+ this._shell(
+ 'Launch Token — Details',
+ `<div class="ltm-field">
+ <label class="ltm-label" for="ltm-name">
+ Token name <span class="ltm-hint">max 32 chars</span>
+ </label>
+ <input class="ltm-input" id="ltm-name" maxlength="32"
+ value="${_esc(d.name)}" autocomplete="off">
+ </div>
+ <div class="ltm-field">
+ <label class="ltm-label" for="ltm-sym">
+ Symbol <span class="ltm-hint">2–10 alphanumeric</span>
+ </label>
+ <input class="ltm-input" id="ltm-sym" maxlength="10"
+ value="${_esc(d.symbol)}" autocomplete="off">
+ <span class="ltm-field-err" id="ltm-sym-err"></span>
+ </div>
+ <div class="ltm-field">
+ <label class="ltm-label" for="ltm-desc">
+ Description <span class="ltm-hint">optional, max 280</span>
+ </label>
+ <textarea class="ltm-textarea" id="ltm-desc"
+ maxlength="280" rows="2">${_esc(d.description)}</textarea>
+ </div>
+ <div class="ltm-field">
+ <label class="ltm-label" for="ltm-img">
+ Image URL <span class="ltm-hint">optional</span>
+ </label>
+ <input class="ltm-input" id="ltm-img"
+ value="${_esc(d.image)}" autocomplete="off" placeholder="https://…">
+ </div>
+ <div class="ltm-field">
+ <label class="ltm-label" for="ltm-buy">
+ Dev buy <span class="ltm-hint">optional, 0–50 SOL</span>
+ </label>
+ <input class="ltm-input" type="number" id="ltm-buy"
+ min="0" max="50" step="0.1" value="${d.initialBuySol}">
+ </div>
+ ${netToggle}`,
+ `<div></div>
+ <button class="ltm-btn ltm-btn-primary" id="ltm-s1-next">Preview →</button>`,
+ ),
+ );
+
+ const nameInput = this._overlay.querySelector('#ltm-name');
+ const symInput = this._overlay.querySelector('#ltm-sym');
+ const symErr = this._overlay.querySelector('#ltm-sym-err');
+ let symTouched = d.symbol !== _nameToSymbol(d.name);
+
+ nameInput.addEventListener('input', () => {
+ if (!symTouched) symInput.value = _nameToSymbol(nameInput.value);
+ });
+ symInput.addEventListener('input', () => {
+ symInput.value = symInput.value.toUpperCase();
+ symTouched = true;
+ symErr.textContent = '';
+ symInput.classList.remove('ltm-err');
+ });
+
+ this._overlay.querySelectorAll('[data-net]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ this._d.cluster = btn.dataset.net;
+ this._overlay
+ .querySelectorAll('[data-net]')
+ .forEach((b) => b.classList.toggle('active', b === btn));
+ });
+ });
+
+ this._overlay.querySelector('#ltm-s1-next').addEventListener('click', () => {
+ const name = nameInput.value.trim();
+ const symbol = symInput.value.toUpperCase().trim();
+
+ if (!name) {
+ nameInput.classList.add('ltm-err');
+ nameInput.focus();
+ return;
+ }
+ nameInput.classList.remove('ltm-err');
+
+ if (!/^[A-Za-z0-9]{2,10}$/.test(symbol)) {
+ symInput.classList.add('ltm-err');
+ symErr.textContent = 'Must be 2–10 alphanumeric characters (A-Z, 0-9)';
+ symInput.focus();
+ return;
+ }
+ symInput.classList.remove('ltm-err');
+ symErr.textContent = '';
+
+ this._d.name = name;
+ this._d.symbol = symbol;
+ this._d.description = this._overlay.querySelector('#ltm-desc').value.trim();
+ this._d.image = this._overlay.querySelector('#ltm-img').value.trim();
+ this._d.initialBuySol = Math.min(
+ 50,
+ Math.max(0, parseFloat(this._overlay.querySelector('#ltm-buy').value) || 0),
+ );
+
+ this._renderStep2();
+ });
+ }
+
+ // ── Step 2 — Preview quote + bonding curve ────────────────────────────────
+
+ async _renderStep2() {
+ this._step = 2;
+
+ this._paint(
+ this._shell(
+ 'Launch Token — Preview',
+ `<div class="ltm-chart-title">Bonding curve (price vs supply)</div>
+ <div class="ltm-chart-wrap" id="ltm-chart"></div>
+ <div id="ltm-quote" class="ltm-quote-block">
+ <div class="ltm-status-msg">
+ <span class="ltm-spinner"></span>Fetching quote…
+ </div>
+ </div>`,
+ `<button class="ltm-btn" id="ltm-s2-back">← Back</button>
+ <button class="ltm-btn ltm-btn-primary" id="ltm-s2-next" disabled>Continue →</button>`,
+ ),
+ );
+
+ const chartEl = this._overlay.querySelector('#ltm-chart');
+ if (chartEl) this._chart = mountLaunchBondingCurve(chartEl);
+
+ this._overlay.querySelector('#ltm-s2-back').addEventListener('click', () => this._renderStep1());
+
+ try {
+ const qs = new URLSearchParams({
+ initial_buy_sol: String(this._d.initialBuySol),
+ cluster: this._d.cluster,
+ });
+ const resp = await fetch(`/api/agents/tokens/launch-quote?${qs}`, {
+ credentials: 'include',
+ });
+ const data = await resp.json();
+
+ if (!resp.ok) {
+ if (resp.status === 404) { this._close(); return; }
+ const msg = _apiError(resp.status, data) || 'Request failed';
+ this._overlay.querySelector('#ltm-quote').innerHTML =
+ `<div class="ltm-status-msg ltm-err">${_esc(msg)}</div>`;
+ return;
+ }
+
+ const rows = [['Fixed costs (rent + fees)', _solFmt(data.fixed_total_sol)]];
+ if (data.initial_buy && data.initial_buy.sol > 0) {
+ rows.push(['Dev buy', _solFmt(data.initial_buy.sol)]);
+ if (data.initial_buy.protocol_fee_sol > 0)
+ rows.push(['Protocol fee (~1%)', _solFmt(data.initial_buy.protocol_fee_sol)]);
+ if (data.initial_buy.tokens_out) {
+ const n = Number(data.initial_buy.tokens_out).toLocaleString();
+ rows.push([`Tokens you receive`, `${n} ${this._d.symbol}`]);
+ }
+ }
+ rows.push(['Total SOL needed', _solFmt(data.total_sol)]);
+
+ this._overlay.querySelector('#ltm-quote').innerHTML = rows
+ .map(
+ ([label, val], i) =>
+ `<div class="ltm-quote-row">
+ <span class="ltm-q-label">${_esc(label)}</span>
+ <span class="ltm-q-val${i === rows.length - 1 ? ' ltm-total' : ''}">${_esc(val)}</span>
+ </div>`,
+ )
+ .join('');
+
+ const nextBtn = this._overlay.querySelector('#ltm-s2-next');
+ nextBtn.disabled = false;
+ nextBtn.addEventListener('click', () => this._renderStep3());
+ } catch {
+ if (!this._overlay) return;
+ this._overlay.querySelector('#ltm-quote').innerHTML =
+ `<div class="ltm-status-msg ltm-err">Connection error, please try again</div>`;
+ }
+ }
+
+ // ── Step 3 — Connect wallet & sign ────────────────────────────────────────
+
+ _renderStep3() {
+ this._step = 3;
+
+ this._paint(
+ this._shell(
+ 'Launch Token — Sign',
+ `<div class="ltm-wallet-row">
+ <div class="ltm-wallet-info">
+ <div class="ltm-wallet-status disconnected" id="ltm-ws">Wallet not connected</div>
+ <div class="ltm-wallet-addr" id="ltm-wa"></div>
+ </div>
+ <button class="ltm-btn" id="ltm-connect">Connect Wallet</button>
+ </div>
+ <div class="ltm-status-msg" id="ltm-msg"></div>`,
+ `<button class="ltm-btn" id="ltm-s3-back">← Back</button>
+ <button class="ltm-btn ltm-btn-primary" id="ltm-launch" disabled>Sign &amp; Launch</button>`,
+ ),
+ );
+
+ this._overlay.querySelector('#ltm-s3-back').addEventListener('click', () => this._renderStep2());
+
+ const connectBtn = this._overlay.querySelector('#ltm-connect');
+ const launchBtn = this._overlay.querySelector('#ltm-launch');
+ let walletAddr = null;
+
+ const _setConnected = (addr) => {
+ walletAddr = addr;
+ const ws = this._overlay.querySelector('#ltm-ws');
+ const wa = this._overlay.querySelector('#ltm-wa');
+ if (ws) { ws.textContent = 'Connected'; ws.className = 'ltm-wallet-status connected'; }
+ if (wa) wa.textContent = `${addr.slice(0, 4)}…${addr.slice(-4)}`;
+ connectBtn.style.display = 'none';
+ launchBtn.disabled = false;
+ };
+
+ const sol = window.solana ?? window.phantom?.solana ?? window.backpack ?? window.solflare;
+ if (sol?.isConnected && sol?.publicKey) {
+ _setConnected(sol.publicKey.toString());
+ }
+
+ connectBtn.addEventListener('click', async () => {
+ if (!sol) {
+ this._msg('No Solana wallet detected. Install Phantom or Backpack.', true);
+ return;
+ }
+ connectBtn.disabled = true;
+ connectBtn.textContent = 'Connecting…';
+ try {
+ await sol.connect();
+ _setConnected(sol.publicKey.toString());
+ } catch {
+ connectBtn.disabled = false;
+ connectBtn.textContent = 'Connect Wallet';
+ this._msg('Wallet connection cancelled.', true);
+ }
+ });
+
+ launchBtn.addEventListener('click', () => this._doLaunch(walletAddr));
+ }
+
+ // ── Launch: prep → sign → broadcast → confirm ─────────────────────────────
+
+ async _doLaunch(walletAddress) {
+ const launchBtn = this._overlay.querySelector('#ltm-launch');
+ const backBtn = this._overlay.querySelector('#ltm-s3-back');
+ launchBtn.disabled = true;
+ backBtn.disabled = true;
+
+ const reset = () => {
+ if (!this._overlay) return;
+ if (launchBtn) launchBtn.disabled = false;
+ if (backBtn) backBtn.disabled = false;
+ };
+
+ try {
+ this._msg('Preparing transaction…');
+ const prepResp = await fetch('/api/agents/tokens/launch-prep', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: this.agentId,
+ provider: 'pumpfun',
+ cluster: this._d.cluster,
+ wallet_address: walletAddress,
+ name: this._d.name,
+ symbol: this._d.symbol,
+ description: this._d.description,
+ image: this._d.image,
+ initial_buy_sol: this._d.initialBuySol,
+ }),
+ });
+ const prep = await prepResp.json();
+
+ if (!prepResp.ok) {
+ if (prepResp.status === 404) { this._close(); return; }
+ const msg = _apiError(prepResp.status, prep) || 'Preparation failed';
+ this._msg(msg, true);
+ reset();
+ return;
+ }
+
+ this._msg('Sign transaction in your wallet…');
+ const sol = window.solana ?? window.phantom?.solana ?? window.backpack ?? window.solflare;
+ const { Transaction } = await import('@solana/web3.js');
+ const txBytes = Uint8Array.from(atob(prep.tx_base64), (c) => c.charCodeAt(0));
+ const tx = Transaction.from(txBytes);
+
+ let signed;
+ try {
+ signed = await sol.signTransaction(tx);
+ } catch {
+ this._msg('Transaction signing cancelled.', true);
+ reset();
+ return;
+ }
+
+ this._msg('Broadcasting to Solana…');
+ const { Connection } = await import('@solana/web3.js');
+ const rpcUrl =
+ prep.cluster === 'devnet'
+ ? 'https://api.devnet.solana.com'
+ : 'https://api.mainnet-beta.solana.com';
+ const conn = new Connection(rpcUrl, 'confirmed');
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(signed.serialize(), {
+ skipPreflight: false,
+ preflightCommitment: 'confirmed',
+ });
+ } catch (e) {
+ this._msg(
+ `Broadcast failed: ${(e.message || String(e)).slice(0, 100)}`,
+ true,
+ );
+ reset();
+ return;
+ }
+
+ this._msg('Confirming on-chain…');
+ const confirmResp = await fetch('/api/agents/tokens/launch-confirm', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ prep_id: prep.prep_id,
+ tx_signature: signature,
+ wallet_address: walletAddress,
+ }),
+ });
+ const confirmed = await confirmResp.json();
+
+ if (!confirmResp.ok) {
+ const msg = _apiError(confirmResp.status, confirmed) || 'Confirmation failed';
+ this._msg(msg, true);
+ reset();
+ return;
+ }
+
+ const mint = confirmed.agent?.token?.mint || prep.mint;
+ const pumpUrl =
+ prep.cluster === 'mainnet' ? `https://pump.fun/coin/${mint}` : null;
+ this._renderStep4(mint, pumpUrl);
+ } catch {
+ this._msg('Connection error, please try again', true);
+ reset();
+ }
+ }
+
+ // ── Step 4 — Success ──────────────────────────────────────────────────────
+
+ _renderStep4(mint, pumpUrl) {
+ this._step = 4;
+ this._paint(
+ this._shell(
+ 'Token Launched!',
+ `<div class="ltm-success">
+ <div class="ltm-success-icon">🎉</div>
+ <div class="ltm-success-title">Token launched successfully!</div>
+ <div class="ltm-mint-box">${_esc(mint)}</div>
+ ${pumpUrl ? `<a class="ltm-pumpfun-link" href="${_esc(pumpUrl)}" target="_blank" rel="noopener noreferrer">View on pump.fun →</a>` : ''}
+ </div>`,
+ `<div></div>
+ <button class="ltm-btn ltm-btn-primary" id="ltm-done">Done</button>`,
+ ),
+ );
+
+ this._overlay.querySelector('#ltm-done').addEventListener('click', () => {
+ this._close();
+ location.reload();
+ });
+
+ window.dispatchEvent(
+ new CustomEvent('agent-token-launched', { detail: { mint, pumpUrl } }),
+ );
+ }
+
+ // ── Helpers ───────────────────────────────────────────────────────────────
+
+ _msg(text, err = false) {
+ const el = this._overlay?.querySelector('#ltm-msg');
+ if (!el) return;
+ el.textContent = text;
+ el.className = `ltm-status-msg${err ? ' ltm-err' : ''}`;
+ }
+}
+
+/**
+ * Open the launch token modal.
+ * @param {{ agentId: string, agentName?: string, imageUrl?: string }} opts
+ * @returns {LaunchTokenModal}
+ */
+export function openLaunchTokenModal(opts) {
+ const modal = new LaunchTokenModal(opts);
+ modal.open();
+ return modal;
+}