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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(SkillsIngestion): implement content skills support with database migration and UI updates
nirholas431bb5973afd
diff --git a/api/_lib/migrations/2026-05-01-skills-content-column.sql b/api/_lib/migrations/2026-05-01-skills-content-column.sqlnew file mode 100644index 000000000..53eac95dc--- /dev/null+++ b/api/_lib/migrations/2026-05-01-skills-content-column.sql@@ -0,0 +1,15 @@+-- Migration: add `content` to marketplace_skills, allow content-only skills.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-01-skills-content-column.sql+-- Idempotent.++alter table marketplace_skills+ add column if not exists content text;++alter table marketplace_skills+ alter column schema_json drop not null;++do $$ begin+ alter table marketplace_skills+ add constraint marketplace_skills_has_payload+ check (schema_json is not null or content is not null);+exception when duplicate_object then null; end $$;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 652cfb22d..d54ebdd5d 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -722,8 +722,11 @@ create index if not exists pumpfun_signals_agent on pumpfun_signals(agent_assetcreate index if not exists pumpfun_signals_kind on pumpfun_signals(kind, seen_at desc);-- ── marketplace_skills — community skill registry ────────────────────────────--- schema_json: jsonb array matching the ToolPack schema used in chat/src/tools.js.--- Each element: { clientDefinition: {...}, type, function: { name, description, parameters } }+-- Two flavors:+-- • tool skills — schema_json: jsonb array matching the ToolPack schema used in chat/src/tools.js.+-- Each element: { clientDefinition: {...}, type, function: { name, description, parameters } }+-- • content skills — content: markdown knowledge injected into the system prompt (no tool schema).+-- Every row must have at least one of `schema_json` or `content` (enforced by check constraint).create table if not exists marketplace_skills (id uuid primary key default gen_random_uuid(),author_id uuid references users(id) on delete set null,@@ -731,12 +734,14 @@ create table if not exists marketplace_skills (slug text not null unique,description text not null,category text not null default 'general',- schema_json jsonb not null,+ schema_json jsonb,+ content text,tags text[] not null default '{}',is_public boolean not null default true,install_count integer not null default 0,created_at timestamptz not null default now(),- updated_at timestamptz not null default now()+ updated_at timestamptz not null default now(),+ constraint marketplace_skills_has_payload check (schema_json is not null or content is not null));create index if not exists marketplace_skills_category_idx on marketplace_skills(category);diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelteindex b940c3ecd..d56accbb1 100644--- a/chat/src/SkillsMarketplaceModal.svelte+++ b/chat/src/SkillsMarketplaceModal.svelte@@ -1,6 +1,7 @@<script>import Modal from './Modal.svelte';- import { toolSchema, currentUser, notify, pluginLibraryUrl } from './stores.js';+ import Markdown from './svelte-marked/markdown/Markdown.svelte';+ import { toolSchema, knowledgeSkills, currentUser, notify, pluginLibraryUrl } from './stores.js';export let open = false;@@ -88,7 +89,25 @@}function isInstalled(skill) {- return $toolSchema.some((g) => g.name === skill.name);+ return (+ $toolSchema.some((g) => g.name === skill.name) ||+ $knowledgeSkills.some((k) => k.id === skill.id)+ );+ }++ // A skill is a "content" (knowledge) skill if the API exposes a content+ // payload. The list endpoint returns a boolean `has_content`; the detail+ // endpoint returns the full `content` string. Tool-pack skills have a+ // non-null `schema_json` array.+ function isContentSkill(skill) {+ if (!skill) return false;+ if (typeof skill.content === 'string' && skill.content.length > 0) return true;+ if (skill.has_content) return true;+ return false;+ }++ function isToolPackSkill(skill) {+ return Array.isArray(skill?.schema_json) && skill.schema_json.length > 0;}function formatRating(avg, count) {@@ -184,23 +203,52 @@if (!$currentUser) { notify('Sign in to install skills', 'info'); return; }installPending = { ...installPending, [skill.id]: true };const wasInstalled = isInstalled(skill);++ // Snapshot prior store entries so we can roll back precisely.+ const priorTool = $toolSchema.find((g) => g.name === skill.name) ?? null;+ const priorKnowledge = $knowledgeSkills.find((k) => k.id === skill.id) ?? null;++ // Decide kind from the best info we have. Detail (if loaded for this+ // skill) wins because it carries the full content; otherwise fall back+ // to list-row hints (`has_content`, `schema_json`).+ const src = detail?.id === skill.id ? detail : skill;+ const contentStr = typeof src.content === 'string' && src.content.length > 0 ? src.content : null;+ const schemaArr = Array.isArray(src.schema_json) && src.schema_json.length > 0 ? src.schema_json : null;+ const optimisticKind = contentStr || src.has_content ? 'content' : 'tool';+if (!wasInstalled) {- const schema = detail?.id === skill.id ? (detail.schema_json ?? []) : (skill.schema_json ?? []);- $toolSchema = [...$toolSchema, { name: skill.name, schema }];+ if (optimisticKind === 'content') {+ $knowledgeSkills = [+ ...$knowledgeSkills.filter((k) => k.id !== skill.id),+ { id: skill.id, name: skill.name, slug: skill.slug, content: contentStr ?? '' },+ ];+ } else {+ $toolSchema = [...$toolSchema, { name: skill.name, schema: schemaArr ?? [] }];+ }} else {- $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);+ if (priorKnowledge) $knowledgeSkills = $knowledgeSkills.filter((k) => k.id !== skill.id);+ if (priorTool) $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);}+try {const method = wasInstalled ? 'DELETE' : 'POST';const res = await fetch(`/api/skills/${skill.id}/install`, { method, credentials: 'include' });if (!res.ok) throw new Error('Request failed');if (!wasInstalled) {const data = await res.json().catch(() => null);- if (data?.schema_json) {+ // Reconcile with authoritative server payload.+ if (data?.content) {+ $knowledgeSkills = [+ ...$knowledgeSkills.filter((k) => k.id !== skill.id),+ { id: skill.id, name: skill.name, slug: skill.slug, content: data.content },+ ];+ $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);+ } else if (data?.schema_json) {$toolSchema = [...$toolSchema.filter((g) => g.name !== skill.name),- { name: skill.name, schema: data.schema_json }+ { name: skill.name, schema: data.schema_json },];+ $knowledgeSkills = $knowledgeSkills.filter((k) => k.id !== skill.id);}}skills = skills.map((s) =>@@ -210,11 +258,13 @@);if (detail?.id === skill.id) detail = { ...detail, is_installed: !wasInstalled };} catch (e) {- if (!wasInstalled) {- $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);- } else {- $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json ?? [] }];- }+ // Roll back to snapshots.+ $toolSchema = priorTool+ ? [...$toolSchema.filter((g) => g.name !== skill.name), priorTool]+ : $toolSchema.filter((g) => g.name !== skill.name);+ $knowledgeSkills = priorKnowledge+ ? [...$knowledgeSkills.filter((k) => k.id !== skill.id), priorKnowledge]+ : $knowledgeSkills.filter((k) => k.id !== skill.id);notify(e.message, 'error');} finally {const next = { ...installPending };@@ -595,6 +645,15 @@>{skill.category}</span>{/if}+ {#if isContentSkill(skill)}+ <span class="rounded-full bg-amber-50 px-2 py-0.5 text-[10px] font-medium text-amber-700"+ >Knowledge skill</span+ >+ {:else if Array.isArray(skill.schema_json) && skill.schema_json.length}+ <span class="rounded-full bg-sky-50 px-2 py-0.5 text-[10px] font-medium text-sky-700"+ >{skill.schema_json.length} tool{skill.schema_json.length > 1 ? 's' : ''}</span+ >+ {/if}</div><p class="mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-slate-500">{skill.description || ''}@@ -715,8 +774,21 @@{/if}</div>- <!-- Schema preview -->- {#if detail.schema_json}+ <!-- Type badge -->+ <div>+ {#if isContentSkill(detail)}+ <span class="inline-block rounded-full bg-amber-50 px-2 py-0.5 text-[11px] font-medium text-amber-700"+ >Knowledge skill</span+ >+ {:else if isToolPackSkill(detail)}+ <span class="inline-block rounded-full bg-sky-50 px-2 py-0.5 text-[11px] font-medium text-sky-700"+ >{detail.schema_json.length} tool{detail.schema_json.length > 1 ? 's' : ''}</span+ >+ {/if}+ </div>++ <!-- Schema preview (tool-pack only) -->+ {#if isToolPackSkill(detail)}{@const preview = schemaPreview(detail.schema_json)}{#if preview}<div>@@ -736,6 +808,15 @@</div></div>+ <!-- Markdown content (knowledge skills) -->+ {#if isContentSkill(detail) && typeof detail.content === 'string' && detail.content.length > 0}+ <div class="mt-4 max-h-[420px] overflow-y-auto rounded border border-slate-100 bg-slate-50/50 p-3">+ <div class="markdown prose prose-sm prose-slate max-w-none break-words prose-pre:whitespace-pre-wrap prose-pre:rounded-md prose-pre:border prose-pre:border-slate-200 prose-pre:bg-white">+ <Markdown source={detail.content} />+ </div>+ </div>+ {/if}+<!-- Action row --><div class="mt-4 flex items-center gap-2 border-t border-slate-100 pt-3">{#if !$currentUser}diff --git a/chat/src/convo.js b/chat/src/convo.jsindex 5bf7e90e5..45e3f3f1c 100644--- a/chat/src/convo.js+++ b/chat/src/convo.js@@ -1,7 +1,24 @@import { get } from 'svelte/store';-import { controller, params, toolSchema } from './stores.js';+import { controller, params, toolSchema, knowledgeSkills } from './stores.js';import { headersForFetch, providers } from './providers.js';+const KNOWLEDGE_SOFT_CAP = 60_000;++function buildKnowledgeBlock() {+ const skills = get(knowledgeSkills) || [];+ if (!skills.length) return '';+ const blocks = skills+ .map((s) => `## Skill: ${s.name}\n${(s.content || '').trim()}`)+ .join('\n\n---\n\n');+ const total = blocks.length;+ if (total > KNOWLEDGE_SOFT_CAP) {+ console.warn(+ `[knowledgeSkills] content size ${total} chars exceeds soft cap ${KNOWLEDGE_SOFT_CAP} (${skills.length} skills); sending in full`+ );+ }+ return `\n\n# Installed knowledge skills\n\nThe user has activated the following skills. Apply them when relevant.\n\n${blocks}`;+}+export async function complete(convo, onupdate, onabort) {try {controller.set(new AbortController());@@ -31,8 +48,21 @@ export async function complete(convo, onupdate, onabort) {}}+ const knowledgeBlock = buildKnowledgeBlock();+ if (knowledgeBlock) {+ const sysIdx = messages.findIndex((m) => m.role === 'system');+ if (sysIdx !== -1) {+ messages[sysIdx] = {+ ...messages[sysIdx],+ content: messages[sysIdx].content + knowledgeBlock,+ };+ } else {+ messages.unshift({ role: 'system', content: knowledgeBlock.trimStart() });+ }+ }+let system = undefined;- if (model.provider === 'Anthropic' && messages[0].role === 'system') {+ if (model.provider === 'Anthropic' && messages[0]?.role === 'system') {system = messages.shift().content;}diff --git a/chat/src/manus/TopNav.svelte b/chat/src/manus/TopNav.svelteindex b10538c97..620490baa 100644--- a/chat/src/manus/TopNav.svelte+++ b/chat/src/manus/TopNav.svelte@@ -4,34 +4,11 @@import { feMenu, feX } from '../feather.js';import WalletConnect from '../WalletConnect.svelte';import NotificationBell from '../NotificationBell.svelte';- import FeaturesDropdown from './dropdowns/FeaturesDropdown.svelte';- import ResourcesDropdown from './dropdowns/ResourcesDropdown.svelte';- let featuresOpen = false;- let resourcesOpen = false;- let mobileOpen = false;-- const featOpen = { value: null }; const featClose = { value: null };- const resOpen = { value: null }; const resClose = { value: null };-- function onFeatEnter() { clearTimeout(featClose.value); featOpen.value = setTimeout(() => (featuresOpen = true), 120); }- function onFeatLeave() { clearTimeout(featOpen.value); featClose.value = setTimeout(() => (featuresOpen = false), 200); }- function onResEnter() { clearTimeout(resClose.value); resOpen.value = setTimeout(() => (resourcesOpen = true), 120); }- function onResLeave() { clearTimeout(resOpen.value); resClose.value = setTimeout(() => (resourcesOpen = false), 200); }-- function closeAll() {- featuresOpen = resourcesOpen = false;- }-- let headerEl;- function handleWindowClick(e) {- if (headerEl && !headerEl.contains(e.target)) closeAll();- }+ let mobileOpen = false;</script>-<svelte:window on:click={handleWindowClick} />--<header bind:this={headerEl} class="sticky top-0 z-40 border-b border-rule bg-paper">+<header class="sticky top-0 z-40 border-b border-rule bg-paper"><div class="mx-auto flex h-14 max-w-[1240px] items-center justify-between px-6"><!-- LEFT: logo + wordmark -->@@ -43,50 +20,6 @@<span class="font-serif text-[22px] font-semibold lowercase tracking-tight">three.ws</span></button>- <!-- CENTER: desktop nav -->- <nav class="hidden items-center md:flex">-- <!-- Features -->- <!-- svelte-ignore a11y-no-static-element-interactions -->- <div class="relative" on:mouseenter={onFeatEnter} on:mouseleave={onFeatLeave}>- <button- class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"- aria-haspopup="true"- aria-expanded={featuresOpen}- >Features</button>- {#if featuresOpen}- <!-- svelte-ignore a11y-no-static-element-interactions -->- <div class="absolute left-0 top-full z-50 mt-2"- on:mouseenter={onFeatEnter} on:mouseleave={onFeatLeave}>- <FeaturesDropdown />- </div>- {/if}- </div>-- <!-- Resources -->- <!-- svelte-ignore a11y-no-static-element-interactions -->- <div class="relative" on:mouseenter={onResEnter} on:mouseleave={onResLeave}>- <button- class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"- aria-haspopup="true"- aria-expanded={resourcesOpen}- >Resources</button>- {#if resourcesOpen}- <!-- svelte-ignore a11y-no-static-element-interactions -->- <div class="absolute left-0 top-full z-50 mt-2"- on:mouseenter={onResEnter} on:mouseleave={onResLeave}>- <ResourcesDropdown />- </div>- {/if}- </div>-- <!-- Pricing -->- <button- class="inline-flex h-14 items-center px-3 text-sm font-medium text-ink transition-colors hover:text-ink-soft"- on:click={() => route.set('pricing')}- >Pricing</button>- </nav>-<!-- RIGHT: auth buttons + hamburger --><div class="flex items-center gap-2"><div class="hidden items-center gap-2 md:flex">@@ -106,12 +39,6 @@<!-- Mobile sheet -->{#if mobileOpen}<div class="border-t border-rule bg-paper md:hidden">- {#each ['Features','Resources','Pricing'] as label}- <button- class="block w-full px-6 py-3 text-left text-sm font-medium text-ink hover:bg-paper-deep"- on:click={() => { route.set(label.toLowerCase()); mobileOpen = false; }}- >{label}</button>- {/each}<div class="flex gap-2 px-6 py-4"><WalletConnect /></div>diff --git a/chat/src/stores.js b/chat/src/stores.jsindex 4456e503c..117516663 100644--- a/chat/src/stores.js+++ b/chat/src/stores.js@@ -62,6 +62,9 @@ export const syncServer = persisted('syncServer', {});export const toolSchema = persisted('toolSchemaGroups', []);+// Installed content skills: [{ id, name, slug, content }]+export const knowledgeSkills = persisted('knowledgeSkills', []);+export const ttsEnabled = persisted('ttsEnabled', false);export const localAgentId = persisted('localAgentId', '');export const activeAgent = persisted('activeAgentDetail', null);diff --git a/package.json b/package.jsonindex b36757b87..ddd3bcca5 100644--- a/package.json+++ b/package.json@@ -62,7 +62,8 @@"validate:cards": "node scripts/validate-agent-cards.mjs","db:migrate": "node scripts/apply-migrations.mjs --apply","db:status": "node scripts/apply-migrations.mjs",- "pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js"+ "pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js",+ "seed:skills": "node scripts/seed-skills.js"},"dependencies": {"@avaturn/sdk": "^1.1.4",diff --git a/prompts/skills-ingestion/03-seed-script.md b/prompts/skills-ingestion/03-seed-script.mdnew file mode 100644index 000000000..97ff072d0--- /dev/null+++ b/prompts/skills-ingestion/03-seed-script.md@@ -0,0 +1,104 @@+# Step 3 — Seed script: ingest `data/skills/seed.json` into `marketplace_skills`++Working directory: `/workspaces/3D-Agent`. Read `/workspaces/3D-Agent/api/CLAUDE.md` first.++## Prerequisites++Steps 1 and 2 must be applied. Verify:++```bash+psql "$DATABASE_URL" -c "\d marketplace_skills" | grep content+```++## Source data++`data/skills/seed.json` contains an object `{ generatedAt, skills: [...] }`. Each skill looks like:++```json+{+ "category": "protocol",+ "content": "# Ethereum Gas Optimization\n## When to use ...\n",+ "description": "Optimize Ethereum gas usage by ...",+ "identifier": "ethereum-gas-optimization",+ "manifest": {+ "name": "ethereum-gas-optimization",+ "description": "...",+ "license": "MIT",+ "metadata": {+ "category": "protocol",+ "difficulty": "intermediate",+ "author": "sperax-team",+ "tags": ["protocol", "ethereum", "gas", "optimization", "l2", "transactions"]+ }+ },+ "name": "ethereum-gas-optimization",+ "source": "builtin"+}+```++There are 100+ entries. Categories observed: `analysis`, `community`, `defi`, `development`, `general`, `news`, `portfolio`, `protocol`, `security`, `trading`.++## Task++Create a Node script at `scripts/seed-skills.js` (ESM, matches existing scripts in `scripts/`).++Behavior:++1. Reads `data/skills/seed.json` from the repo root.+2. For each skill, upserts into `marketplace_skills` keyed by `slug` (= the skill's `identifier`):+ - `name` ← `manifest.name` (or `identifier` if missing)+ - `slug` ← `identifier`+ - `description` ← `description` (truncate to 500 chars per existing column constraint)+ - `category` ← `category` (lowercase, trimmed)+ - `tags` ← `manifest.metadata.tags ?? []`+ - `content` ← `content` (markdown body)+ - `schema_json` ← `NULL`+ - `is_public` ← `true`+ - `author_id` ← `NULL` (these are platform-seeded, no author)+3. `ON CONFLICT (slug) DO UPDATE` set name/description/category/tags/content/updated_at. Do NOT reset `install_count`.+4. Logs progress: `[N/total] inserted|updated <slug>`.+5. Exits non-zero if any row fails. Does not swallow errors.++Use the project's existing DB helper: `import { sql } from '../api/_lib/db.js'` (Neon serverless tagged template). Do not instantiate a new pool. Do not mock the DB.++For env vars, the existing scripts read from `.env` or process env — match whatever pattern they use (look at one or two scripts in `scripts/` first). Do not add a new env loader.++Add a `seed:skills` script to `package.json` `scripts`: `"seed:skills": "node scripts/seed-skills.js"`.++## Hard rules++- No mocks, no fakes. Inserts go to the real Neon DB.+- Idempotent: running twice produces the same DB state, no duplicate rows.+- Don't transform or rewrite the markdown content. Insert it verbatim.+- Don't truncate content (column is `text`, no length limit; the 200000 char cap in the API is only for user-submitted skills).++## Verification++```bash+pnpm run seed:skills # or npm run, whichever this repo uses+```++Then:++```bash+psql "$DATABASE_URL" -c "SELECT count(*) FROM marketplace_skills WHERE content IS NOT NULL;"+psql "$DATABASE_URL" -c "SELECT slug, category, length(content) FROM marketplace_skills WHERE content IS NOT NULL ORDER BY slug LIMIT 10;"+```++The count must equal the number of skills in `data/skills/seed.json` (verify with `jq '.skills | length' data/skills/seed.json`).++Run the seed a second time. Count must not increase. `updated_at` should advance for all rows.++Spot-check via API:++```bash+curl -s 'http://localhost:3000/api/skills?category=defi&limit=5' | jq '.skills[] | {slug, has_content, content_preview}'+```++Each row must show `has_content: true` and a non-empty `content_preview`.++## Done means++- 100+ rows inserted, all with non-null `content` and null `schema_json`.+- Re-running the seed is a no-op for inserts (only updates timestamps).+- API list endpoint surfaces them.diff --git a/prompts/skills-ingestion/04-modal-render-content.md b/prompts/skills-ingestion/04-modal-render-content.mdnew file mode 100644index 000000000..86fd0a4d0--- /dev/null+++ b/prompts/skills-ingestion/04-modal-render-content.md@@ -0,0 +1,93 @@+# Step 4 — Modal: render markdown content, install/uninstall content skills++Working directory: `/workspaces/3D-Agent`. Read `/workspaces/3D-Agent/CLAUDE.md` first.++## Prerequisites++Steps 1, 2, 3 applied. Verify a content skill is reachable via API:++```bash+curl -s 'http://localhost:3000/api/skills?category=defi&limit=1' | jq '.skills[0]'+```++Must show `has_content: true`.++## File to modify++`chat/src/SkillsMarketplaceModal.svelte` (~1014 lines). Read the whole file before editing — this modal is the production marketplace UI. The relevant areas:++- Line 10: `let skills = []` — listing state.+- Line 90-91: `isInstalled(skill)` — checks `$toolSchema` (works for tool-pack skills).+- Line 124-143: list fetch from `/api/skills`.+- Line 182-225: `toggleInstall(skill, e)` — POST/DELETE `/api/skills/<id>/install` and updates `$toolSchema`.+- Line 228+: `toggleExpand(skill)` — fetches detail.++## Task++Make the modal handle both kinds of skills:++### A. New store for installed content skills++Add a new persisted store in `chat/src/stores.js` next to `toolSchema` (line 63):++```js+// Installed content skills: [{ id, name, slug, content }]+export const knowledgeSkills = persisted('knowledgeSkills', []);+```++Do NOT remove or rename `toolSchema`.++### B. Update `isInstalled` in the modal++A skill is installed if it appears in `$toolSchema` (tool-pack) OR `$knowledgeSkills` (content). Distinguish by what the API returns:++- Tool-pack skill: `schema_json` is non-null array.+- Content skill: `content` is non-null string (and `schema_json` is null).++### C. Update `toggleInstall`++When installing:+- If detail (or list row) has tools → push to `$toolSchema` exactly as today.+- If detail has content → push `{ id, name, slug, content }` to `$knowledgeSkills`.+- The install API call (`POST /api/skills/<id>/install`) is unchanged. The response from step 2 now includes `content`; use it.++When uninstalling: remove from whichever store it's in.++The existing optimistic update + rollback pattern (lines 184-225) must be preserved. Both stores should be updated in the same optimistic/rollback flow.++### D. Render markdown in the detail view++The detail panel (search for `expandedSkillId` / `detail` rendering, roughly lines 600-900) currently shows description + tool schema. For content skills, render the markdown.++Use the existing markdown renderer in this codebase — look at `chat/src/MessageContent.svelte` and `chat/src/svelte-marked/` for the import. Do NOT add a new markdown library. Do NOT use `{@html}` without sanitization — reuse whatever sanitizer Message rendering uses.++Show a clear visual cue distinguishing tool-pack ("3 tools") vs content ("Knowledge skill") in both the list and detail views.++### E. Filtering / search++The existing category filter and search input must continue to work for both types. No changes needed if the API list already returns mixed results (it does after steps 2-3).++## Hard rules++- No mocks. Test against the real API.+- No new dependencies in `chat/package.json` beyond what's already there.+- Don't break the existing tool-pack install flow — verify it still works after your changes.+- Match Svelte 4 idioms used elsewhere in this file.++## Verification++1. Boot the dev server (whichever command this project uses — check `chat/package.json` scripts).+2. Open the skills marketplace modal in `/chat`.+3. List shows mixed tool-pack and content skills.+4. Click a content skill (e.g., `ethereum-gas-optimization`) — detail renders the full markdown.+5. Install it. Visual state updates to "Installed". `localStorage.knowledgeSkills` (DevTools → Application → Local Storage) contains the skill with full `content` field.+6. Uninstall. Removed from `knowledgeSkills`.+7. Install a tool-pack skill (any existing one). It still goes into `localStorage.toolSchemaGroups` exactly as before. Regression check: send a chat message that should trigger the tool — it works.+8. Refresh page. Both stores rehydrate from localStorage, install state persists.++## Done means++- Content skills can be installed/uninstalled; store updates correctly.+- Markdown renders cleanly in detail view.+- Tool-pack skills regression-tested and unchanged.+- No console errors.diff --git a/prompts/skills-ingestion/05-system-prompt-injection.md b/prompts/skills-ingestion/05-system-prompt-injection.mdnew file mode 100644index 000000000..1e4914e0e--- /dev/null+++ b/prompts/skills-ingestion/05-system-prompt-injection.md@@ -0,0 +1,89 @@+# Step 5 — Inject installed knowledge skills into the system prompt++Working directory: `/workspaces/3D-Agent`. Read `/workspaces/3D-Agent/CLAUDE.md` first.++## Prerequisites++Steps 1-4 applied. Verify:++- `localStorage.knowledgeSkills` contains at least one installed content skill (install one via the modal first).++## Files to modify++- `chat/src/convo.js` — system prompt assembly happens around lines 26-36 and 462-484.+- (Possibly) `chat/src/App.svelte:887-1026` — agent system prompt setup. Read this section before editing to confirm where the canonical system message is built.++The primary integration point is `convo.js` lines 26-36, which currently looks roughly like:++```js+const sysIdx = messages.findIndex((m) => m.role === 'system');+// ... retrievalContext injection ...+let system = undefined;+if (model.provider === 'Anthropic' && messages[0].role === 'system') {+ system = messages.shift().content;+}+```++## Task++When a chat request is being prepared, append every installed knowledge skill's markdown content to the system message, under a clear delimiter so the model can use them as authoritative context.++### A. Build a knowledge-skills block++Helper in `convo.js` (or a new sibling file `chat/src/skillPrompt.js` if cleaner — your call, keep it simple):++```js+import { get } from 'svelte/store';+import { knowledgeSkills } from './stores.js';++function buildKnowledgeBlock() {+ const skills = get(knowledgeSkills);+ if (!skills.length) return '';+ const blocks = skills.map(s => `## Skill: ${s.name}\n${s.content.trim()}`).join('\n\n---\n\n');+ return `\n\n# Installed knowledge skills\n\nThe user has activated the following skills. Apply them when relevant.\n\n${blocks}`;+}+```++### B. Append to the system message++Find the spot in `convo.js` where the outbound `system` (Anthropic) or system role message (OpenAI/others) is finalized. Append `buildKnowledgeBlock()`:++- For Anthropic (`system` is a string): `system = (system || '') + buildKnowledgeBlock();`+- For OpenAI-style (system is `messages[0]`): if a system message exists, append to its content. If not and the block is non-empty, prepend a new `{ role: 'system', content: buildKnowledgeBlock().trimStart() }`.++Apply this **after** existing `retrievalContext` handling so all context is present.++### C. Don't double-inject++Do not write the knowledge block into the persisted `convo.messages` array. It should only appear in the outbound request payload — otherwise it gets re-included on every turn AND saved to chat history, both wrong.++### D. Token budget guardrail++Skills can be long. Add a soft cap: if total knowledge content exceeds 60_000 chars, log `console.warn` once per send with the count, but still include all of it. (Real RAG/selection is out of scope for this step. Just make the cap visible.)++## Hard rules++- No mocks, no fakes. Use the real `knowledgeSkills` store wired up in step 4.+- Don't change the request transport, model selection, or non-skill parts of `convo.js`.+- Don't persist the skill block into chat history.+- Works for both Anthropic and OpenAI/OpenRouter request shapes already handled in this file.++## Verification++End-to-end against a real model:++1. Install one content skill via the modal — pick `ethereum-gas-optimization` (small and unambiguous).+2. Open browser DevTools → Network tab.+3. Send a message: "When is gas cheapest on Ethereum mainnet?"+4. Inspect the outbound request to the LLM provider. The `system` field (Anthropic) or first system message (OpenAI) MUST contain the markdown from the skill, under the `# Installed knowledge skills` delimiter.+5. The model's response should reference the skill's specifics (weekend / early UTC mornings, etc.).+6. Uninstall the skill. Send the same message. The system field MUST NOT contain the block anymore. Model response is generic.+7. Install 2-3 skills. Confirm all appear in the system prompt, separated by `---`.+8. Reload the page. Knowledge skills persist (from `localStorage`). System prompt still includes them.++## Done means++- Outbound system prompt contains installed skills' markdown verbatim.+- Persisted `convo.messages` does not contain the block (check `localStorage` and the visible chat history).+- Toggle (install/uninstall) reflects immediately on next send.+- Both Anthropic and OpenAI request paths covered.diff --git a/prompts/skills-ingestion/06-end-to-end-verification.md b/prompts/skills-ingestion/06-end-to-end-verification.mdnew file mode 100644index 000000000..ae4ef4c5a--- /dev/null+++ b/prompts/skills-ingestion/06-end-to-end-verification.md@@ -0,0 +1,104 @@+# Step 6 — End-to-end verification++Working directory: `/workspaces/3D-Agent`. Read `/workspaces/3D-Agent/CLAUDE.md` first.++## Prerequisites++Steps 1-5 done. Do not skip verification just because earlier steps were verified individually — this step catches integration issues.++## Tasks++Run these in order. Each must pass before moving to the next. If any fails, fix the root cause in the relevant earlier step (do not patch around it here).++### 1. DB state++```bash+psql "$DATABASE_URL" -c "+ SELECT+ COUNT(*) AS total,+ COUNT(*) FILTER (WHERE content IS NOT NULL) AS content_skills,+ COUNT(*) FILTER (WHERE schema_json IS NOT NULL) AS tool_skills,+ COUNT(*) FILTER (WHERE schema_json IS NULL AND content IS NULL) AS broken+ FROM marketplace_skills;+"+```++- `broken` MUST be 0.+- `content_skills` MUST equal `jq '.skills | length' data/skills/seed.json`.++### 2. API smoke++```bash+# List+curl -s 'http://localhost:3000/api/skills?limit=200' | jq '.skills | length, (map(.has_content) | unique)'++# Categories+curl -s 'http://localhost:3000/api/skills/categories' | jq++# Detail of a content skill+SLUG_ID=$(curl -s 'http://localhost:3000/api/skills?limit=1' | jq -r '.skills[0].id')+curl -s "http://localhost:3000/api/skills/$SLUG_ID" | jq '.skill | {id, name, has_content: (.content != null), tool_count: (.schema_json | length // 0)}'+```++Expect: list has both content and tool-pack skills; categories endpoint covers the new categories from seed (`defi`, `trading`, `security`, `protocol`, etc.); detail returns full content for content skills.++### 3. UI install — content skill++1. Open `/chat` (boot dev server).+2. Sign in (knowledge skills install requires a session).+3. Open the skills marketplace modal.+4. Filter by category `DeFi`. Install `cross-chain-bridge-guide`.+5. DevTools → Application → Local Storage → confirm `knowledgeSkills` contains the skill with full `content`.++### 4. UI install — tool-pack skill (regression)++1. Find a tool-pack skill (any pre-existing skill with non-null `schema_json` — e.g., one from the original curated packs in `chat/src/tools.js` or any non-content row).+2. Install. Confirm it lands in `localStorage.toolSchemaGroups`, not `knowledgeSkills`.+3. Send a chat message that should trigger the tool. Tool runs as before.++### 5. Outbound system prompt++1. With the content skill from step 3 installed, send: "How do cross-chain bridges differ in trust assumptions?"+2. DevTools → Network tab → inspect the LLM request payload.+3. Confirm the `system` (Anthropic) or first system-role message (OpenAI) contains the markdown from `cross-chain-bridge-guide` under the `# Installed knowledge skills` delimiter.+4. Confirm the assistant's reply references concrete details only present in that skill (e.g., specific bridges named in the markdown).++### 6. Uninstall++1. Open modal, uninstall the content skill.+2. Send the same message. Confirm system prompt no longer contains the block. Reply degrades to generic.++### 7. Persistence++1. Install 2 content skills + 1 tool-pack skill.+2. Hard reload. All three remain installed (rehydrate from localStorage).+3. Send a message. Outbound system prompt contains both content skills' markdown.++### 8. Constraint guardrail++```bash+psql "$DATABASE_URL" -c "INSERT INTO marketplace_skills (name, slug, description) VALUES ('x','x-broken','x');"+```++MUST fail with check-constraint violation.++### 9. Re-seed idempotency++```bash+COUNT_BEFORE=$(psql "$DATABASE_URL" -tAc "SELECT count(*) FROM marketplace_skills WHERE content IS NOT NULL")+pnpm run seed:skills+COUNT_AFTER=$(psql "$DATABASE_URL" -tAc "SELECT count(*) FROM marketplace_skills WHERE content IS NOT NULL")+[ "$COUNT_BEFORE" = "$COUNT_AFTER" ] && echo OK || echo FAIL+```++Must print `OK`.++## Hard rules++- No mocks. Real DB, real API, real LLM call.+- Do not declare done if any of the 9 checks fail.+- If a check fails: identify the step that introduced the bug and fix it in that step's files. Do not paper over.++## Done means++All 9 checks pass. Skills marketplace fully ingests sperax skills into `/chat`, content reaches the model, install/uninstall/persistence all work, no regression to tool-pack skills.diff --git a/scripts/seed-skills.js b/scripts/seed-skills.jsnew file mode 100644index 000000000..b6a900cd1--- /dev/null+++ b/scripts/seed-skills.js@@ -0,0 +1,93 @@+#!/usr/bin/env node+/**+ * seed-skills.js+ * ──────────────+ * Ingest data/skills/seed.json into marketplace_skills.+ *+ * Idempotent: keyed by slug (= skill identifier). ON CONFLICT updates+ * name/description/category/tags/content/updated_at; install_count is preserved.+ *+ * Usage: node scripts/seed-skills.js+ * Required env: DATABASE_URL+ */++import { readFile } from 'node:fs/promises';+import { readFileSync } from 'node:fs';+import { resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++const __dir = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dir, '..');++// Inline .env.local loader (matches scripts/backfill-erc8004.mjs).+try {+ const raw = readFileSync(resolve(REPO_ROOT, '.env.local'), 'utf8');+ for (const line of raw.split('\n')) {+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2].trim();+ }+} catch { /* no .env.local */ }++if (!process.env.DATABASE_URL) {+ console.error('Missing DATABASE_URL');+ process.exit(1);+}++const { sql } = await import('../api/_lib/db.js');++const seedPath = resolve(REPO_ROOT, 'data/skills/seed.json');+const seedRaw = await readFile(seedPath, 'utf8');+const seed = JSON.parse(seedRaw);+const skills = Array.isArray(seed?.skills) ? seed.skills : [];++if (skills.length === 0) {+ console.error('No skills found in data/skills/seed.json');+ process.exit(1);+}++console.log(`seed-skills — ${skills.length} skills from ${seedPath}\n`);++const total = skills.length;+let failures = 0;++for (let i = 0; i < total; i++) {+ const s = skills[i];+ const slug = s.identifier;+ const name = s.manifest?.name || s.identifier;+ const description = String(s.description ?? '').slice(0, 500);+ const category = String(s.category ?? 'general').trim().toLowerCase();+ const tags = Array.isArray(s.manifest?.metadata?.tags) ? s.manifest.metadata.tags : [];+ const content = s.content ?? null;++ if (!slug || !content) {+ console.error(`[${i + 1}/${total}] FAIL ${slug || '(no slug)'}: missing slug or content`);+ failures++;+ continue;+ }++ try {+ const rows = await sql`+ insert into marketplace_skills (+ author_id, name, slug, description, category, schema_json, content, tags, is_public+ ) values (+ null, ${name}, ${slug}, ${description}, ${category}, null, ${content}, ${tags}, true+ )+ on conflict (slug) do update set+ name = excluded.name,+ description = excluded.description,+ category = excluded.category,+ tags = excluded.tags,+ content = excluded.content,+ updated_at = now()+ returning (xmax = 0) as inserted+ `;+ const action = rows[0]?.inserted ? 'inserted' : 'updated';+ console.log(`[${i + 1}/${total}] ${action} ${slug}`);+ } catch (err) {+ console.error(`[${i + 1}/${total}] FAIL ${slug}: ${err.message}`);+ failures++;+ }+}++console.log(`\ndone — ${total - failures}/${total} ok, ${failures} failed`);+process.exit(failures > 0 ? 1 : 0);