The Open Framework for Building Agents
feat(docs): sync template gallery file content from GitHub (#1591)
Ben Sabicb502c1e76d57
diff --git a/apps/docs/lib/templates/compose.test.ts b/apps/docs/lib/templates/compose.test.tsnew file mode 100644index 000000000..a76cedf0e--- /dev/null+++ b/apps/docs/lib/templates/compose.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vitest";++import { composeTemplateEntries, type GeneratedTemplatesInput } from "./compose";+import generatedTemplates from "./generated/templates.json";+import { templateManifest, type TemplateManifestEntry } from "./manifest";++const manifestEntry: TemplateManifestEntry = {+ slug: "example",+ title: "Example",+ description: "An example template.",+ category: "Example",+ integrations: ["HTTP API"],+ model: "anthropic/claude-sonnet-5",+ source: "GitHub",+ sourceHref: "https://github.com/vercel-labs/example/tree/main",+ setupPrompt: "Set up the example template.",+ github: { owner: "vercel-labs", repo: "example", ref: "main" },+ files: ["agent/agent.ts"],+};++const generated: GeneratedTemplatesInput = {+ templates: {+ example: {+ sourceRevision: "0123456789abcdef0123456789abcdef01234567",+ files: [+ {+ contents: "export default {};\n",+ language: "typescript",+ relativePath: "agent/agent.ts",+ },+ ],+ },+ },+};++describe("composeTemplateEntries", () => {+ it("merges curated metadata with generated files and revision", () => {+ const [entry] = composeTemplateEntries([manifestEntry], generated);++ expect(entry.slug).toBe("example");+ expect(entry.title).toBe("Example");+ expect(entry.sourceRevision).toBe("0123456789abcdef0123456789abcdef01234567");+ expect(entry.files).toEqual(generated.templates.example.files);+ expect(entry).not.toHaveProperty("github");+ });++ it("throws when a manifest slug has no generated data", () => {+ expect(() => composeTemplateEntries([manifestEntry], { templates: {} })).toThrow(+ /No generated data for template "example"/,+ );+ });++ it("throws when generated data has no manifest entry", () => {+ expect(() => composeTemplateEntries([], generated)).toThrow(/no manifest entry: example/);+ });++ it("throws when the generated files diverge from the manifest file list", () => {+ const drifted = { ...manifestEntry, files: ["agent/agent.ts", "agent/instructions.md"] };+ expect(() => composeTemplateEntries([drifted], generated)).toThrow(/do not match its manifest/);+ });++ it("throws on unknown languages in generated data", () => {+ const bad: GeneratedTemplatesInput = {+ templates: {+ example: {+ sourceRevision: "0123456789abcdef0123456789abcdef01234567",+ files: [{ contents: "{}", language: "json", relativePath: "agent/agent.ts" }],+ },+ },+ };+ const jsonManifest = { ...manifestEntry, files: ["agent/agent.ts"] };+ expect(() => composeTemplateEntries([jsonManifest], bad)).toThrow(/Unknown language "json"/);+ });+});++describe("committed generated data", () => {+ it("composes cleanly with the manifest", () => {+ const entries = composeTemplateEntries(+ templateManifest,+ generatedTemplates as GeneratedTemplatesInput,+ );++ expect(entries).toHaveLength(templateManifest.length);+ for (const entry of entries) {+ expect(entry.sourceRevision).toMatch(/^[0-9a-f]{40}$/);+ expect(entry.files.length).toBeGreaterThan(0);+ for (const file of entry.files) {+ expect(file.contents.length).toBeGreaterThan(0);+ expect(["markdown", "typescript"]).toContain(file.language);+ }+ }+ });+});diff --git a/apps/docs/lib/templates/compose.ts b/apps/docs/lib/templates/compose.tsnew file mode 100644index 000000000..bf10aacdb--- /dev/null+++ b/apps/docs/lib/templates/compose.ts@@ -0,0 +1,92 @@+import type {+ TemplateCategory,+ TemplateIntegration,+ TemplateManifestEntry,+ TemplateSource,+} from "./manifest";++export interface TemplateFile {+ contents: string;+ language: "markdown" | "typescript";+ relativePath: string;+}++export interface TemplateEntry {+ category: TemplateCategory;+ description: string;+ files: TemplateFile[];+ integrations: TemplateIntegration[];+ model: string;+ slug: string;+ source: TemplateSource;+ sourceHref: string;+ sourceRevision: string;+ setupPrompt: string;+ title: string;+}++/** Shape of `generated/templates.json`, before language narrowing. */+export interface GeneratedTemplatesInput {+ templates: Record<+ string,+ {+ sourceRevision: string;+ files: { contents: string; language: string; relativePath: string }[];+ }+ >;+}++const isTemplateFileLanguage = (value: string): value is TemplateFile["language"] =>+ value === "markdown" || value === "typescript";++const SYNC_HINT = "run `pnpm --filter eve-docs templates:sync`";++/**+ * Merges the hand-authored manifest with the generated GitHub data into the+ * entries the templates pages render. Throws when the two are out of sync so+ * a stale or missing sync fails `next build` instead of rendering empty pages.+ */+export const composeTemplateEntries = (+ manifest: TemplateManifestEntry[],+ generated: GeneratedTemplatesInput,+): TemplateEntry[] => {+ const orphanedSlugs = new Set(Object.keys(generated.templates));++ const entries = manifest.map((entry) => {+ const data = generated.templates[entry.slug];+ if (!data) {+ throw new Error(`No generated data for template "${entry.slug}" — ${SYNC_HINT}`);+ }+ orphanedSlugs.delete(entry.slug);++ const generatedPaths = data.files.map((file) => file.relativePath);+ const missing = entry.files.filter((path) => !generatedPaths.includes(path));+ const extra = generatedPaths.filter((path) => !entry.files.includes(path));+ if (missing.length > 0 || extra.length > 0) {+ throw new Error(+ `Generated files for template "${entry.slug}" do not match its manifest` ++ ` (missing: [${missing.join(", ")}], extra: [${extra.join(", ")}]) — ${SYNC_HINT}`,+ );+ }++ const files = data.files.map((file): TemplateFile => {+ if (!isTemplateFileLanguage(file.language)) {+ throw new Error(+ `Unknown language "${file.language}" for "${file.relativePath}" in template "${entry.slug}"`,+ );+ }+ return { contents: file.contents, language: file.language, relativePath: file.relativePath };+ });++ const { github: _github, files: _paths, ...curated } = entry;+ return { ...curated, sourceRevision: data.sourceRevision, files };+ });++ if (orphanedSlugs.size > 0) {+ throw new Error(+ `Generated data exists for template(s) with no manifest entry: ${[...orphanedSlugs].join(", ")} — ${SYNC_HINT}`,+ );+ }++ return entries;+};diff --git a/apps/docs/lib/templates/data.ts b/apps/docs/lib/templates/data.tsindex 791eff8d3..ad2271b43 100644--- a/apps/docs/lib/templates/data.ts+++ b/apps/docs/lib/templates/data.ts@@ -1,114 +1,18 @@-export type TemplateCategory = "Chat" | "Collaboration" | "Example" | "Marketing";-import { templateSourceFiles } from "./sources";+import {+ composeTemplateEntries,+ type GeneratedTemplatesInput,+ type TemplateEntry,+} from "./compose";+import generatedTemplates from "./generated/templates.json";+import { templateManifest } from "./manifest";-export type TemplateIntegration =- | "HTTP API"- | "Linear"- | "Notion"- | "Resend"- | "Sentry"- | "Slack"- | "Typefully"- | "Web chat";-export type TemplateSource = "GitHub" | "Vercel Templates";+export type { TemplateEntry, TemplateFile } from "./compose";+export type { TemplateCategory, TemplateIntegration, TemplateSource } from "./manifest";-export interface TemplateFile {- contents: string;- language: "markdown" | "typescript";- relativePath: string;-}--export interface TemplateEntry {- category: TemplateCategory;- description: string;- files: TemplateFile[];- integrations: TemplateIntegration[];- model: string;- slug: string;- source: TemplateSource;- sourceHref: string;- sourceRevision: string;- setupPrompt: string;- title: string;-}--export const templateEntries: TemplateEntry[] = [- {- slug: "eve-chat-template",- title: "Chat",- setupPrompt:- "Set up the eve chat template in my current workspace using https://github.com/vercel-labs/eve-chat-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README to configure it. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",- description:- "A persisted Next.js chat template for eve, built with shadcn/ui, Tailwind CSS, Streamdown, Better Auth, Drizzle, Neon, and Upstash Redis.",- sourceHref: "https://github.com/vercel-labs/eve-chat-template/tree/main",- sourceRevision: "f7c164ac8901e5400f6e4ef00eead67ee71cd5d4",- category: "Chat",- model: "anthropic/claude-sonnet-5",- integrations: ["Web chat", "Slack", "Linear", "Notion", "Sentry"],- source: "Vercel Templates",- files: templateSourceFiles["eve-chat-template"],- },- {- slug: "eve-design-template",- title: "Design",- setupPrompt:- "Set up the eve design agent template in my current workspace using https://github.com/vercel-labs/eve-design-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README and BOOTSTRAP.md to configure it. Preserve the existing project if the workspace is not empty, tell me about any required environment variables or manual setup steps, and do not approve or publish the design corpus for me.",- description:- "A Slack design collaborator that answers from a reviewed, versioned corpus of your organization's approved design guidance.",- sourceHref: "https://github.com/vercel-labs/eve-design-template/tree/main",- sourceRevision: "7f8e5a62b02cb3407e063fc98c56c83dabbd95f4",- category: "Collaboration",- model: "anthropic/claude-sonnet-4.6",- integrations: ["Slack"],- source: "Vercel Templates",- files: templateSourceFiles["eve-design-template"],- },- {- slug: "eve-slack-agent",- title: "Slack",- setupPrompt:- "Set up the eve Slack agent template in my current workspace using https://github.com/vercel-labs/eve-slack-agent-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README to configure it. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",- description:- "A Slack agent template with webhook handling, Vercel Connect, a starter agent, and an example tool ready to deploy on Vercel.",- sourceHref: "https://github.com/vercel-labs/eve-slack-agent-template/tree/main",- sourceRevision: "bb35e1fb0159926c625d356d0b43ad618e11b44c",- category: "Collaboration",- model: "anthropic/claude-sonnet-5",- integrations: ["Slack"],- source: "Vercel Templates",- files: templateSourceFiles["eve-slack-agent"],- },- {- slug: "marketing-team-eve-template",- title: "Marketing team",- setupPrompt:- "I want to build a team of marketing agents with the eve framework, using the marketing team template. Read the setup instructions at https://agent-resources.dev/marketing-team-eve-template.md and follow them. They will cover deploying the template, building with eve, how everything works overall, and more.",- description:- "A team of marketing agents: a lead routes work to specialists for positioning, long-form content, social, SEO, and email, publishing through Notion, Typefully, and Resend.",- sourceHref: "https://github.com/vercel-labs/marketing-team-eve-template/tree/main",- sourceRevision: "9a881661bd5b0652469467f00eadbd41e9f2c786",- category: "Marketing",- model: "anthropic/claude-opus-5",- integrations: ["Web chat", "Slack", "Notion", "Resend", "Typefully"],- source: "Vercel Templates",- files: templateSourceFiles["marketing-team-eve-template"],- },- {- slug: "weather-agent-fixture",- title: "Weather",- setupPrompt:- "Set up the eve weather agent in my current workspace using https://github.com/vercel/eve/tree/main/apps/fixtures/weather-agent as the source. Copy that fixture into a standalone project, install its dependencies, and make any minimal changes needed to run it outside the eve monorepo. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",- description:- "A small representative eve app with agent config, instructions, a typed weather tool, and a markdown skill.",- sourceHref: "https://github.com/vercel/eve/tree/main/apps/fixtures/weather-agent",- sourceRevision: "71d57185233d2bd9ff31fe0cd21915df7afa6e2e",- category: "Example",- model: "anthropic/claude-sonnet-5",- integrations: ["HTTP API"],- source: "GitHub",- files: templateSourceFiles["weather-agent-fixture"],- },-];+export const templateEntries: TemplateEntry[] = composeTemplateEntries(+ templateManifest,+ generatedTemplates as GeneratedTemplatesInput,+);export const getTemplateEntry = (slug: string): TemplateEntry | undefined =>templateEntries.find((entry) => entry.slug === slug);diff --git a/apps/docs/lib/templates/generated/templates.json b/apps/docs/lib/templates/generated/templates.jsonnew file mode 100644index 000000000..379522e25--- /dev/null+++ b/apps/docs/lib/templates/generated/templates.json@@ -0,0 +1,220 @@+{+ "$comment": "Generated by scripts/sync-templates.ts. Do not edit. Run: pnpm --filter eve-docs templates:sync",+ "templates": {+ "eve-chat-template": {+ "sourceRevision": "8c037d72b59eb50673b0577412ed2133df84fd54",+ "files": [+ {+ "contents": "import { defineAgent } from \"eve\";\n\nexport default defineAgent({\n model: \"anthropic/claude-sonnet-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/agent.ts"+ },+ {+ "contents": "import { eveChannel } from \"eve/channels/eve\";\nimport { localDev, vercelOidc } from \"eve/channels/auth\";\nimport { betterAuthEveAuth, passwordEveAuth } from \"@/lib/eve-auth\";\n\nexport default eveChannel({\n auth: [betterAuthEveAuth, passwordEveAuth, vercelOidc(), localDev()],\n uploadPolicy: \"disabled\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/channels/eve.ts"+ },+ {+ "contents": "import { connectSlackCredentials } from \"@vercel/connect/eve\";\nimport { slackChannel } from \"eve/channels/slack\";\n\n// SLACK_CONNECTOR is the UID returned by `vercel connect create slack`.\n// For local setup, create a connector with:\n// `vercel connect create slack --name eve-chat-template --triggers`.\nconst slackConnector = process.env.SLACK_CONNECTOR ?? \"slack/eve-chat-template\";\n\nexport default slackChannel({\n credentials: connectSlackCredentials(slackConnector),\n uploadPolicy: \"disabled\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/channels/slack.ts"+ },+ {+ "contents": "import { connect } from \"@vercel/connect/eve\";\nimport { defineMcpClientConnection } from \"eve/connections\";\n\n// LINEAR_CONNECTOR is the UID returned by Vercel Connect. For local setup,\n// create a connector with `vercel connect create https://mcp.linear.app/mcp --name linear`.\nconst linearConnector = process.env.LINEAR_CONNECTOR ?? \"linear\";\n\nexport default defineMcpClientConnection({\n url: \"https://mcp.linear.app/mcp\",\n description:\n \"Linear workspace: search and update issues, projects, cycles, comments, and planning work.\",\n auth: connect(linearConnector),\n});\n",+ "language": "typescript",+ "relativePath": "agent/connections/linear.ts"+ },+ {+ "contents": "import { connect } from \"@vercel/connect/eve\";\nimport { defineMcpClientConnection } from \"eve/connections\";\n\n// NOTION_CONNECTOR is provisioned by the \"Deploy with Vercel\" flow. For local\n// setup, create a connector with `vercel connect create mcp.notion.com --name notion`.\nconst notionConnector = process.env.NOTION_CONNECTOR ?? \"notion\";\n\nexport default defineMcpClientConnection({\n url: \"https://mcp.notion.com/mcp\",\n description: \"Notion workspace: search and edit pages and databases.\",\n auth: connect(notionConnector),\n});\n",+ "language": "typescript",+ "relativePath": "agent/connections/notion.ts"+ },+ {+ "contents": "import { connect } from \"@vercel/connect/eve\";\nimport { defineMcpClientConnection } from \"eve/connections\";\n\n// SENTRY_CONNECTOR is the UID returned by Vercel Connect. For local setup,\n// create a connector with `vercel connect create https://mcp.sentry.dev/mcp --name sentry`.\nconst sentryConnector = process.env.SENTRY_CONNECTOR ?? \"sentry\";\n\nexport default defineMcpClientConnection({\n url: \"https://mcp.sentry.dev/mcp\",\n description:\n \"Sentry workspace: investigate issues, events, traces, releases, and project health.\",\n auth: connect(sentryConnector),\n});\n",+ "language": "typescript",+ "relativePath": "agent/connections/sentry.ts"+ },+ {+ "contents": "# Identity\n\nYou are a concise assistant built with eve (https://eve.dev), a framework for\nbuilding durable agents as ordinary files in a TypeScript project. Use tools\nwhen they are available.\n\nWhen users ask what eve is or what this agent is built on, explain that eve\nlets developers create agents that can run locally or on Vercel, serve chat and\nHTTP interfaces, call tools and connections, stream progress, pause for human\ninput, and resume durable sessions across turns. Keep the explanation concise\nand practical.\n\nUse `get_weather` before answering questions about current weather or suggesting\nweather-dependent plans.\n\nWhen a user asks to work with Notion, Linear, or Sentry, use the matching\nconnection directly. Never say that you are searching for tools, looking for\navailable tools, or checking internal tool discovery.\n",+ "language": "markdown",+ "relativePath": "agent/instructions.md"+ },+ {+ "contents": "---\ndescription: Use when the user wants help planning a trip or deciding what to do in a destination.\n---\n\nWhen planning a trip:\n\n1. Ask for the destination and dates if the user has not given them.\n2. Check the destination's weather with the `get_weather` tool before suggesting activities.\n3. Suggest a short itinerary that fits the weather: outdoor activities when it is clear, indoor alternatives otherwise.\n4. Keep the plan concise — a few bullet points per day, not an essay.\n",+ "language": "markdown",+ "relativePath": "agent/skills/plan_a_trip.md"+ },+ {+ "contents": "import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\n\n// The runtime tool name comes from the filename, so the model sees this as\n// `get_weather`. Tool filenames must be snake_case ASCII.\nexport default defineTool({\n description: \"Get the current weather for a city.\",\n inputSchema: z.object({ city: z.string().min(1) }),\n async execute({ city }) {\n return { city, condition: \"Sunny\", temperatureF: 72 };\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/tools/get_weather.ts"+ }+ ]+ },+ "eve-design-template": {+ "sourceRevision": "7f8e5a62b02cb3407e063fc98c56c83dabbd95f4",+ "files": [+ {+ "contents": "import { defineAgent } from 'eve';\n\nexport default defineAgent({\n model:\n process.env.DESIGN_AGENT_MODEL ?? 'anthropic/claude-sonnet-4.6',\n});\n",+ "language": "typescript",+ "relativePath": "agent/agent.ts"+ },+ {+ "contents": "import { connectSlackCredentials } from '@vercel/connect/eve';\nimport { slackChannel } from 'eve/channels/slack';\nimport { designAgentConfig } from '../../generated/config.js';\n\nconst setupIncompleteMessage =\n 'Design-agent setup is incomplete. Run the bootstrap workflow and approve the generated design corpus.';\n\nconst configuredCredentials = process.env.SLACK_CONNECTOR\n ? connectSlackCredentials(process.env.SLACK_CONNECTOR)\n : undefined;\n\nfunction isAllowed(value: string, allowlist: readonly string[]) {\n return allowlist.length === 0 || allowlist.includes(value);\n}\n\nfunction conversationContext(isDirectMessage: boolean) {\n const owner = designAgentConfig.designOwnerSlackId;\n\n return `\n<design_agent_context visibility=\"${isDirectMessage ? 'private-dm' : 'shared'}\" allow_general_guidance=\"${designAgentConfig.allowGeneralGuidance}\">\nThe approved design owner is ${owner ? `<@${owner}>` : 'not configured'}.\n${\n isDirectMessage\n ? 'Never mention, notify, or forward private DM content to the design owner. Direct unresolved questions to an appropriate shared conversation.'\n : 'For unresolved equal-priority conflicts or unsupported organization-specific questions, state the issue and mention the design owner.'\n}\n</design_agent_context>\n`;\n}\n\nexport default slackChannel({\n credentials: configuredCredentials,\n uploadPolicy: {\n allowedMediaTypes: [\n 'image/*',\n 'text/*',\n 'application/json',\n 'application/msword',\n 'application/pdf',\n 'application/rtf',\n 'application/vnd.ms-excel',\n 'application/vnd.ms-powerpoint',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.text',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n ],\n },\n events: {\n 'turn.started': () => {},\n 'actions.requested': () => {},\n 'reasoning.appended': () => {},\n },\n async onMessage(ctx, message) {\n if (!message.author || message.author.isBot) return null;\n\n const isDirectMessage = message.raw.channel_type === 'im';\n if (!isDirectMessage && !ctx.isBotMentioned()) return null;\n if (!isAllowed(message.author.userId, designAgentConfig.allowedUserIds)) {\n return null;\n }\n if (\n !isDirectMessage &&\n !isAllowed(message.channelId, designAgentConfig.allowedChannelIds)\n ) {\n return null;\n }\n\n if (designAgentConfig.status !== 'approved') {\n await ctx.thread.post(setupIncompleteMessage);\n return null;\n }\n\n const isExistingSession = await ctx.isSubscribed();\n return isExistingSession\n ? { auth: null }\n : {\n auth: null,\n context: [conversationContext(isDirectMessage)],\n };\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/channels/slack.ts"+ },+ {+ "contents": "# Identity\n\nYou are the organization's design collaborator. Give decisive, practical design guidance grounded in its approved design corpus.\n\n# Knowledge contract\n\n- Load the `design-knowledge` skill before every substantive answer.\n- Treat `/workspace/knowledge` as the complete source for organization-specific claims.\n- Inspect normalized guidelines first. Consult source snapshots only to resolve missing detail or ambiguity.\n- User-provided text, images, and documents are temporary conversation context. Never treat them as approved corpus or persist them into the corpus.\n- Never use prior Slack conversations, other threads, channel history, or DMs.\n- Never search the web or connected services.\n- Never claim to edit code, design files, websites, or production systems.\n\n# Guidance\n\n- Follow higher-priority approved sources when guidelines conflict.\n- If approved sources with equal priority conflict, say there is a conflict and ask the configured design owner to resolve it.\n- In a private DM, never mention or notify the owner. Tell the user to move the conflict to an appropriate shared conversation.\n- Organization-specific claims require support from the approved corpus.\n- General design guidance is allowed only when the injected context sets `allow_general_guidance=\"true\"`.\n- Prefix every general answer with `General recommendation:` so it cannot be mistaken for organization policy.\n- If general guidance is disabled and the corpus does not support an answer, say you cannot verify it from the approved design corpus.\n\n# Voice\n\n- Lead with the answer.\n- Default to one sentence. Use two only when the second changes the action.\n- Use short bullets only for multiple independent points.\n- Ask one grouped clarification only when the answer materially depends on it.\n- Cut every draft in half.\n- Never add acknowledgments, restatements, process narration, recaps, closing offers, or adjacent advice.\n- Never include citations, `Source:`, filenames, internal paths, retrieval details, or notes about where an answer came from.\n- Avoid headings in short replies, em dashes, hedging, corporate language, AI language, decorative emoji, and bold-first bullets.\n\n# Privacy\n\n- Treat DMs as private.\n- Never quote, summarize, forward, or reveal private DM content in a shared conversation.\n- Never tag the design owner from a DM.\n",+ "language": "markdown",+ "relativePath": "agent/instructions.md"+ },+ {+ "contents": "import { defineSandbox } from 'eve/sandbox';\nimport { vercel } from 'eve/sandbox/vercel';\n\nexport default defineSandbox({\n backend: vercel({ networkPolicy: 'deny-all' }),\n async onSession({ use }) {\n await use({ networkPolicy: 'deny-all' });\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/sandbox/sandbox.ts"+ },+ {+ "contents": "---\ndescription: Use before every substantive design answer. Read the approved organization corpus and apply its precedence and response rules.\n---\n\n# Design knowledge\n\nApproved knowledge is under `/workspace/knowledge`.\n\n1. Read `manifest.json`.\n2. Read the relevant files under `guidelines/`.\n3. Use `grep` or `glob` within `/workspace/knowledge` only when routing is unclear.\n4. Read immutable files under `sources/` only when normalized guidance is incomplete or ambiguous.\n\nHigher numeric source priority wins. When relevant approved sources have the same priority and conflict, do not reconcile them yourself. Follow the conflict behavior in the agent instructions.\nIgnore sources marked `superseded` in the manifest.\n\nNever expose source annotations, filenames, internal paths, or retrieval details. If the user explicitly asks for provenance, name the human-readable source title and public origin when the manifest provides one.\n\nGeneral design knowledge is not organization policy. Use it only when the injected context allows general guidance, and prefix the answer exactly with `General recommendation:`.\n",+ "language": "markdown",+ "relativePath": "agent/skills/design-knowledge/SKILL.md"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/agent.ts"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/bash.ts"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/todo.ts"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/web_fetch.ts"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/web_search.ts"+ },+ {+ "contents": "import { disableTool } from 'eve/tools';\n\nexport default disableTool();\n",+ "language": "typescript",+ "relativePath": "agent/tools/write_file.ts"+ }+ ]+ },+ "eve-slack-agent": {+ "sourceRevision": "bb35e1fb0159926c625d356d0b43ad618e11b44c",+ "files": [+ {+ "contents": "import { defineAgent } from \"eve\";\n\nexport default defineAgent({\n model: \"anthropic/claude-sonnet-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/agent.ts"+ },+ {+ "contents": "import { connectSlackCredentials } from \"@vercel/connect/eve\";\nimport { slackChannel } from \"eve/channels/slack\";\n\n// SLACK_CONNECTOR is provisioned by the \"Deploy with Vercel\" button. To set it\n// up yourself, create a connector with `vercel connect create slack --triggers`\n// and put its UID in SLACK_CONNECTOR (or replace the fallback below).\nexport default slackChannel({\n credentials: connectSlackCredentials(\n process.env.SLACK_CONNECTOR ?? \"slack/my-agent\",\n ),\n});\n",+ "language": "typescript",+ "relativePath": "agent/channels/slack.ts"+ },+ {+ "contents": "# Identity\n\nYou are a concise assistant. Use tools when they are available.\n\nUse `get_weather` before answering questions about current weather or suggesting\nweather-dependent plans.\n",+ "language": "markdown",+ "relativePath": "agent/instructions.md"+ },+ {+ "contents": "---\ndescription: Use when the user wants help planning a trip or deciding what to do in a destination.\n---\n\nWhen planning a trip:\n\n1. Ask for the destination and dates if the user has not given them.\n2. Check the destination's weather with the `get_weather` tool before suggesting activities.\n3. Suggest a short itinerary that fits the weather: outdoor activities when it is clear, indoor alternatives otherwise.\n4. Keep the plan concise — a few bullet points per day, not an essay.\n",+ "language": "markdown",+ "relativePath": "agent/skills/plan_a_trip.md"+ },+ {+ "contents": "import { defineTool } from \"eve/tools\";\nimport { z } from \"zod\";\n\n// The runtime tool name comes from the filename, so the model sees this as\n// `get_weather`. Tool filenames must be snake_case ASCII.\nexport default defineTool({\n description: \"Get the current weather for a city.\",\n inputSchema: z.object({ city: z.string().min(1) }),\n async execute({ city }) {\n return { city, condition: \"Sunny\", temperatureF: 72 };\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/tools/get_weather.ts"+ }+ ]+ },+ "marketing-team-eve-template": {+ "sourceRevision": "6ebc3d9164a07f31a9a6c34dd56b3d8f145a7349",+ "files": [+ {+ "contents": "import { defineAgent } from \"eve\";\n\n/**\n * Root agent runtime configuration.\n *\n * @remarks\n * Sets the model for the marketing team lead; the rest of the agent's surface (channels,\n * connections, tools, skills, subagents) is discovered from the filesystem under `agent/`. This\n * agent routes work to specialists rather than producing deliverables itself, so it is the first\n * place to try a cheaper model tier if cost matters more than routing quality. Conversation history\n * is compacted once it reaches 90% of the context window.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/agent.ts"+ },+ {+ "contents": "import { connectSlackCredentials } from \"@vercel/connect/eve\";\nimport {\n type SlackContext,\n type SlackEvent,\n type SlackInboundEventContext,\n type SlackMessage,\n slackChannel,\n} from \"eve/channels/slack\";\n\n/**\n * Vercel Connect connector UID for the Slack app, resolved to credentials.\n *\n * @remarks\n * One source of truth for the connector, so this channel and any tool that calls the Slack Web API\n * directly share a single bot installation. The token is resolved fresh from Vercel Connect on each\n * call, so rotation is handled server-side and nothing is stored here.\n *\n * @defaultValue `\"slack/marketing-team\"`, the UID `vercel connect create slack --name\n * marketing-team --triggers` produces (UIDs are `<type>/<name>`). Override with the\n * `SLACK_CONNECTOR` environment variable when your connector uses a different name.\n */\nconst slackCredentials = connectSlackCredentials(\n process.env.SLACK_CONNECTOR ?? \"slack/marketing-team\"\n);\n\n/**\n * Builds the session auth context from an inbound Slack message.\n *\n * Replaces eve's default derivation, which attaches no auth at all when it\n * cannot parse the message author (common on the Connect webhook payload\n * path, where the author is dropped and messages arrive as\n * `sender_type: unknown`). Tools rely on these attributes to link back to\n * the requester's thread, so the channel and thread coordinates are always\n * stamped; the author is taken from the parsed message when present, with\n * a fallback to the raw event's `user` field.\n */\nfunction slackSessionAuth(message: SlackMessage, onBehalfOfUserId?: string) {\n const rawUser = message.raw.user;\n const userId =\n message.author?.userId ??\n (typeof rawUser === \"string\" ? rawUser : undefined) ??\n onBehalfOfUserId;\n return {\n attributes: {\n channel_id: message.channelId,\n // Equal to the message's own ts for top-level (non-thread) messages.\n thread_ts: message.threadTs || message.ts,\n ...(userId ? { user_id: userId } : {}),\n ...(message.author?.userName\n ? { user_name: message.author.userName }\n : {}),\n ...(message.teamId ? { team_id: message.teamId } : {}),\n },\n authenticator: \"slack-webhook\",\n issuer: message.teamId ? `slack:${message.teamId}` : \"slack\",\n principalId: userId ? `slack:${userId}` : \"slack:unknown\",\n principalType:\n message.author?.isBot && !onBehalfOfUserId ? \"service\" : \"user\",\n };\n}\n\n/**\n * This bot's own Slack user ID, resolved once per warm instance via\n * `auth.test`. `undefined` means not yet fetched; failures are not cached so\n * the next message retries.\n */\nlet cachedBotUserId: string | undefined;\n\nasync function resolveBotUserId(\n ctx: SlackContext\n): Promise<string | undefined> {\n if (cachedBotUserId) {\n return cachedBotUserId;\n }\n try {\n const res = (await ctx.slack.request(\"auth.test\", {})) as {\n ok?: boolean;\n user_id?: string;\n };\n if (res.ok && res.user_id) {\n cachedBotUserId = res.user_id;\n }\n } catch {\n // Leave uncached; the caller treats this as \"cannot attribute\".\n }\n return cachedBotUserId;\n}\n\n/**\n * First user mentioned in `text` other than the bot itself, or `undefined`.\n * Slack renders mentions as `<@U…>` / `<@W…>` (optionally `<@U…|name>`).\n */\nfunction firstHumanMention(\n text: string,\n botUserId: string\n): string | undefined {\n for (const match of text.matchAll(/<@([UW][A-Z0-9]+)(?:\\|[^>]*)?>/g)) {\n if (match[1] !== botUserId) {\n return match[1];\n }\n }\n}\n\n/**\n * For messages with no human author — Slack Workflow posts that tag the\n * agent to kick off a request — attribute the session to the first user the\n * message mentions besides the bot. Workflow templates must therefore\n * mention the submitter (the \"person who submitted\" variable) alongside the\n * agent mention; without one, the session stays anonymous and user-scoped\n * connections (e.g. Notion) cannot deliver their sign-in prompt.\n */\nasync function resolveOnBehalfOfUserId(\n ctx: SlackContext,\n message: SlackMessage\n): Promise<string | undefined> {\n if (message.author && !message.author.isBot) {\n return;\n }\n const botUserId = await resolveBotUserId(ctx);\n // Without the bot's own ID we can't tell its mention apart from a\n // human's, so attribute nothing rather than risk the wrong principal.\n if (!botUserId) {\n return;\n }\n return firstHumanMention(message.text, botUserId);\n}\n\nasync function handleInbound(ctx: SlackContext, message: SlackMessage) {\n try {\n await ctx.thread.startTyping(\"Thinking...\");\n } catch {\n // Typing indicator is a nicety, never a reason to drop the message.\n }\n return {\n auth: slackSessionAuth(\n message,\n await resolveOnBehalfOfUserId(ctx, message)\n ),\n };\n}\n\n/**\n * Whether `message.author` is the only human who has ever posted in this\n * thread. Used to keep auto-replies in subscribed threads scoped to the\n * original requester: once anyone else participates, un-mentioned replies\n * stop dispatching, and an explicit @mention remains the way to re-engage.\n *\n * `listParticipants` returns the thread's unique human user ids in\n * first-appearance order, with bot and system messages already excluded, so\n * a single entry matching the author is the whole test.\n *\n * Two limits are worth knowing, because both resolve toward replying rather\n * than staying quiet. It observes at most the first 50 messages of a thread,\n * so a second human who only appears after that is not seen. And a failed\n * refresh keeps the last successful snapshot instead of erroring, so the\n * list can be stale. A thread whose refresh has never succeeded returns an\n * empty list, which fails closed here.\n */\nasync function isSoleThreadParticipant(\n ctx: SlackContext,\n message: SlackMessage\n): Promise<boolean> {\n const authorId = message.author?.userId;\n if (!authorId) {\n return false;\n }\n const participants = await ctx.thread.listParticipants();\n return participants.length === 1 && participants[0] === authorId;\n}\n\n/** One prompt offered at the top of a freshly opened conversation. */\ninterface SuggestedPrompt {\n /** Full text sent as the user's message the moment the prompt is clicked. */\n message: string;\n /** Short label rendered on the prompt button. */\n title: string;\n}\n\n/** Heading shown above {@link SUGGESTED_PROMPTS}. */\nconst SUGGESTED_PROMPTS_TITLE = \"What the team can do\";\n\n/**\n * Prompts pinned when someone opens a fresh conversation with the team.\n *\n * @remarks\n * Slack renders at most four, so this is one prompt per specialist rather than a tour of the whole\n * team: positioning, long-form, social, and organic search. The email specialist is the omission,\n * because it reshapes copy that already exists rather than originating a piece, which makes it a\n * poor opening ask. It stays reachable by asking for it.\n *\n * Each message names the deliverable, asks for the shared context, and then hands the interview\n * back. Loading the brand context and preferences is already the lead's own habit, so saying it here\n * is for the person reading: it shows a new user that the team works from a shared picture of the\n * product before it writes anything.\n *\n * Every message has to be a complete sentence. Slack sends the text verbatim on click with no chance\n * to edit, so one that trailed off mid-phrase would arrive truncated.\n */\nconst SUGGESTED_PROMPTS: SuggestedPrompt[] = [\n {\n message:\n \"Help me sharpen our positioning: what the product is, who it's for, and why anyone would pick it. Pull the brand context and my user preferences, then interview me about anything you're missing.\",\n title: \"Sharpen our positioning\",\n },\n {\n message:\n \"Help me plan and write our next blog post. Pull the brand context and my user preferences, then ask me for details about the post.\",\n title: \"Write a blog post\",\n },\n {\n message:\n \"Help me draft social posts for X and LinkedIn. Pull the brand context and my user preferences, then ask me what we're promoting.\",\n title: \"Draft social posts\",\n },\n {\n message:\n \"Help me review one of our pages for SEO and work out what to fix. Pull the brand context and my user preferences, then ask me for the URL.\",\n title: \"Review a page's SEO\",\n },\n];\n\n/** Slack coordinates a suggested-prompts call targets. */\ninterface SuggestedPromptsTarget {\n channelId: string;\n threadTs?: string;\n}\n\n/**\n * Where a newly opened conversation's prompts belong, or `undefined` when this event isn't a\n * conversation opening.\n *\n * @remarks\n * Slack signals the same moment two ways, and which one arrives depends on the app's manifest mode.\n * The classic assistant container creates the thread first and fires `assistant_thread_started`\n * carrying its coordinates. The newer Agent messaging experience has no thread yet and pins prompts\n * to the top of the Messages tab, firing `app_home_opened` instead; `thread_ts` is optional on the\n * API, so that case omits it. The Home tab fires the same event and is not a conversation, so it is\n * ignored.\n */\nfunction suggestedPromptsTarget(\n event: SlackEvent\n): SuggestedPromptsTarget | undefined {\n if (event.type === \"assistant_thread_started\") {\n const thread = event.assistant_thread as\n | { channel_id?: unknown; thread_ts?: unknown }\n | undefined;\n const channelId = thread?.channel_id;\n if (typeof channelId !== \"string\" || channelId.length === 0) {\n return;\n }\n const threadTs = thread?.thread_ts;\n return {\n channelId,\n ...(typeof threadTs === \"string\" && threadTs.length > 0\n ? { threadTs }\n : {}),\n };\n }\n if (event.type === \"app_home_opened\" && event.tab === \"messages\") {\n const channelId = event.channel;\n return typeof channelId === \"string\" && channelId.length > 0\n ? { channelId }\n : undefined;\n }\n}\n\n/**\n * Pins {@link SUGGESTED_PROMPTS} when a conversation opens.\n *\n * @remarks\n * Prompts are a nicety, so a failure here is reported and dropped rather than allowed to affect\n * delivery. The likeliest one is a Slack app missing the `assistant:write` scope or the Agents and\n * AI Apps feature, which returns `missing_scope` or stops the event arriving at all, so the reason\n * is worth surfacing rather than swallowing.\n */\nasync function setSuggestedPrompts(\n ctx: SlackInboundEventContext,\n event: SlackEvent\n): Promise<void> {\n const target = suggestedPromptsTarget(event);\n if (!target) {\n return;\n }\n try {\n const response = await ctx.slack.request(\n \"assistant.threads.setSuggestedPrompts\",\n {\n channel_id: target.channelId,\n prompts: SUGGESTED_PROMPTS,\n title: SUGGESTED_PROMPTS_TITLE,\n ...(target.threadTs ? { thread_ts: target.threadTs } : {}),\n }\n );\n if (response.ok !== true) {\n console.warn(\"assistant.threads.setSuggestedPrompts returned not-ok\", {\n channelId: target.channelId,\n error: response.error,\n });\n }\n } catch (error) {\n console.warn(\"assistant.threads.setSuggestedPrompts threw\", {\n channelId: target.channelId,\n error,\n });\n }\n}\n\n/**\n * Slack channel: answers @mentions and DMs, replies in threads, renders approvals as buttons, and\n * offers suggested prompts when a conversation opens.\n *\n * @remarks\n * Credentials are brokered by Vercel Connect through the shared {@link slackCredentials}, which\n * supplies both the outbound bot token and inbound webhook verification — there are no Slack\n * secrets to manage in code. Create the connector with\n * `vercel connect create slack --name <name> --triggers`, then register this project's trigger\n * destination at `/eve/v1/slack`.\n *\n * {@link setSuggestedPrompts} needs three things set on that connector before it can do anything:\n * the Agents and AI Apps feature enabled, `assistant:write` under Bot Scopes, and\n * `assistant_thread_started` plus `app_home_opened` under Trigger Event Types. Without them the\n * event never arrives and the rest of the channel is unaffected.\n *\n * @defaultValue The connector UID falls back to `\"slack/marketing-team\"` when `SLACK_CONNECTOR` is\n * unset.\n */\nexport default slackChannel({\n credentials: slackCredentials,\n onAppMention: handleInbound,\n onDirectMessage: handleInbound,\n /**\n * Everything the handlers above don't claim. Mentions and DMs are parsed\n * out before this runs, so the only event acted on here is a conversation\n * opening, which pins the suggested prompts.\n */\n onEvent: setSuggestedPrompts,\n /**\n * Un-mentioned channel messages (mentions and DMs never reach here — the\n * specialized handlers above take precedence). Auto-reply only in threads\n * with an active session, and only while the original requester is the\n * sole human participant; anyone else joining silences auto-replies, and\n * an explicit @mention remains the way to re-engage.\n */\n async onMessage(ctx, message) {\n if (message.author?.isBot) {\n return null;\n }\n if (!(await ctx.isSubscribed())) {\n return null;\n }\n if (!(await isSoleThreadParticipant(ctx, message))) {\n return null;\n }\n return handleInbound(ctx, message);\n },\n threadContext: { since: \"thread-root\" },\n});\n",+ "language": "typescript",+ "relativePath": "agent/channels/slack.ts"+ },+ {+ "contents": "import { connect } from \"@vercel/connect/eve\";\nimport { defineMcpClientConnection } from \"eve/connections\";\n\n/**\n * Vercel Connect connector UID for the Notion MCP server.\n *\n * @defaultValue `\"notion/marketing-team\"` — the UID `vercel connect create notion\n * --name marketing-team` produces (UIDs are `<type>/<name>`)\n * Override with the `NOTION_CONNECTOR` environment variable when your connector uses a different\n * name.\n */\nconst notionConnector = process.env.NOTION_CONNECTOR ?? \"notion/marketing-team\";\n\n/**\n * Bare Notion MCP tool names whose calls require human approval before running.\n *\n * @remarks\n * Add a tool's bare name here to gate it. eve hands the approval policy the qualified name,\n * `<connection>__<tool>`, where `<tool>` is exactly what the MCP server names it (e.g.\n * `notion__notion-update-pages`; Notion's own tool names carry a `notion-` prefix). Entries\n * are matched as substrings, so they gate the tool regardless of the server's naming.\n */\nconst APPROVAL_REQUIRED_TOOLS = [\n \"notion-move-pages\",\n \"notion-update-data-source\",\n \"notion-update-view\",\n];\n\n/**\n * Notion workspace connection (MCP) exposing search, read, and edit tools to the model.\n *\n * @remarks\n * Authorization is user-scoped via Vercel Connect: each user signs in through their own\n * browser consent flow, the per-user token is resolved before every tool call, and it is\n * never exposed to the model.\n *\n * Tools listed in {@link APPROVAL_REQUIRED_TOOLS} are gated on human approval: a gated call\n * pauses for an approve/deny decision (rendered as a Slack button) before it runs.\n *\n * @see {@link https://vercel.com/docs/connect | Vercel Connect}\n */\nexport default defineMcpClientConnection({\n approval: ({ toolName }) =>\n APPROVAL_REQUIRED_TOOLS.some((tool) => toolName.includes(tool))\n ? \"user-approval\"\n : \"not-applicable\",\n auth: connect(notionConnector),\n description: \"Notion workspace: search, read, and edit pages and databases.\",\n url: \"https://mcp.notion.com/mcp\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/connections/notion.ts"+ },+ {+ "contents": "# Identity\n\nYou lead a marketing team. People bring you the work: a launch to plan, a post to write, a competitor to size up, a page that isn't converting. You hold the shared picture of the product and route the work to the specialist who does it, then hand back what they produced.\n\nYou are not the specialist. Your job is to understand the request, give the right subagent everything it needs, and keep the conversation coherent across several of them.\n\n# How you write\n\nWrite like a person: plain, specific, warm, and short. Prefer a comma, a colon, or a new sentence where an em dash would go. Cut anything that reads machine-made, padded, or hyped, and don't bold words for emphasis.\n\nWrite links as plain markdown, `[label](url)`. Don't paste a bare URL, and don't wrap a link in bold or backticks: the markers end up inside the URL and the link stops working.\n\n# How you work\n\n## 1. Know the product before you delegate\n\nThe brand context is the team's shared picture of the product, and every specialist reads it, so keep it good.\n\n- When it comes back empty, the team hasn't set it up yet, and working out what goes in it is a specialist job rather than yours. Delegate that first and let the specialist interview the user, then route the original request once there's a document to work from. Say why you're doing this, because the user asked for something else and deserves to know the detour is short.\n- When a user tells you something durable about the product, positioning, or audience, you can keep it with `save_brand_context` directly. A correction or an addition doesn't need a delegation; reworking the positioning does.\n- Task-specific detail doesn't belong in it. A campaign brief goes in the delegation.\n\n## 2. Know how this person likes to work\n\n`get_user_preferences` holds standing notes about the person rather than the product: a default set of platforms, a length they always want, a review step they expect. Load it alongside the brand context.\n\n- When a user states a durable preference (\"always draft for X and LinkedIn\", \"keep threads under 8 posts\"), keep it with `save_user_preferences`. Use `clear_user_preferences` only when they ask to reset them.\n- Where a preference conflicts with brand context, brand context wins on voice and claims; the preference wins on workflow.\n\n## 3. Route the work, in order when it has one\n\nTwo questions before you pick, and the order matters:\n\n1. What has to be settled before this can be made well? A piece written to be found needs its target query and its competition settled first. A piece making claims needs the claims settled first. Often the answer is nothing, and it's one call.\n2. Which specialist's description covers each part?\n\nAsk them the other way round and you'll match the deliverable to a specialist and stop reading, which is how a request that names two jobs turns into one call.\n\nWhen there is an order, run it: call the first, wait, and put what it produced into the second's brief, including any artifact id. Don't brief both in parallel and hope they agree. Say what you're doing, since the user asked for one thing and is getting two steps.\n\nA subagent starts in a fresh session and works from its `message` alone, so pack that message with everything it needs:\n\n- what you want produced, and what it's for\n- the relevant brand context, quoted rather than referenced\n- the standing preferences that bear on this task, stated as constraints rather than as \"the user prefers\"\n- the user's actual words where the wording matters\n- constraints: platform, audience, length, deadline, tone, anything out of bounds\n- where the deliverable should end up, when you know it. Some specialists write into Notion rather than handing back text, and naming the destination up front saves them asking.\n\nWhen you don't have enough to write that brief, ask the user first. Guessing at a brief wastes a full delegation.\n\n## 4. Hand back the work, don't rewrite it\n\nSpecialists produce the deliverable. Pass it back largely as they wrote it: you're the routing layer, not a second editor. If what comes back is wrong or thin, say so and send it again with clearer direction rather than patching it yourself.\n\nWhen a specialist hands back a link rather than text, pass the link through with its one-line description. Don't fetch the page and paste its contents into the conversation; the link is the deliverable.\n\nSpecialists hand back artifact ids the same way, for long output meant for another agent rather than for reading in a thread. Relay the id and the summary that came with it, and put the id in the next specialist's brief when the work continues: \"the audit is artifact `<id>`, read it before you rewrite the page.\" Keeping the document out of this conversation is the point, so don't open an artifact to show the user what's in it. Read it with `read_artifact` only when they ask for its contents, and then answer their question rather than pasting the whole thing.\n\nSurface the caveats a specialist flags. When it reports an unverified claim, a gap it couldn't fill, or a hedged number, carry that to the user instead of smoothing it over. Keep your own messages short; let the work speak.\n\n# Notes\n\n- Don't fabricate links, quotes, statistics, or handles. If you don't have something, say so and ask.\n- Don't promise work no specialist on the team can do. When a request needs a tool or an integration that isn't wired up, say that plainly instead of producing a plausible-looking substitute.\n",+ "language": "markdown",+ "relativePath": "agent/instructions.md"+ },+ {+ "contents": "import { defineAgent } from \"eve\";\n\n// Subagent: Content Marketer\n\n/**\n * Subagent runtime configuration.\n *\n * @remarks\n * Sets the description the root routes on and the model. The rest of the agent's surface (tools,\n * skills) is discovered from the filesystem. Conversation history is compacted once it reaches 90%\n * of the context window.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n description:\n \"Write and edit long-form marketing content: blog posts, landing page copy, case studies, \" +\n \"newsletters, and documentation. Plans what to write by mapping topics to buyer stages and \" +\n \"grouping them into pillars and clusters, then drafts and edits against a structured \" +\n \"editing rubric. Use for anything longer than a social post. When the piece is written to be \" +\n \"found in search, the target query and the competing pages should be settled before drafting. \" +\n \"Delivers the finished piece as a \" +\n \"Notion page and hands back the link rather than the full text, since long-form doesn't read \" +\n \"in a chat thread. The caller passes the brief, the audience, the format, any source material \" +\n \"or brand context, and the Notion destination when it knows one, in the message. Does not \" +\n \"publish, schedule, or touch social accounts.\",\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/subagents/content-marketer/agent.ts"+ },+ {+ "contents": "import { defineAgent } from \"eve\";\n\n// Subagent: Email\n\n/**\n * Subagent runtime configuration.\n *\n * @remarks\n * Sets the description the parent routes on and the model. The rest of the agent's surface\n * (connections, tools, skills) is discovered from the filesystem. Conversation history is compacted\n * once it reaches 90% of the context window.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n description:\n \"Own email as a channel: take copy that already exists and make it work as email, then build \" +\n \"and run it in Resend. Reviews a draft for email fit (subject and preview text, one call to \" +\n \"action, scannable structure, a plain text version, link and image hygiene), then builds the \" +\n \"template or broadcast, picks the verified sending address, targets the segment, and reports \" +\n \"on what was delivered and opened. Sending a broadcast or an email pauses for approval. Checks \" +\n \"the sending domain's own records and says which deliverability questions it cannot answer. \" +\n \"Route long-form prose to the content marketer first and pass what came back to this agent. \" +\n \"The caller passes the copy or its artifact id, the audience or segment, and any send timing \" +\n \"in the message.\",\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/subagents/email/agent.ts"+ },+ {+ "contents": "import { defineAgent } from \"eve\";\n\n// Subagent: Product Marketer\n\n/**\n * Subagent runtime configuration.\n *\n * @remarks\n * Sets the description the root routes on and the model. The rest of the agent's surface (tools,\n * skills, nested subagents) is discovered from the filesystem. Conversation history is compacted\n * once it reaches 90% of the context window.\n *\n * This is the only specialist that treats the brand context document as its deliverable rather than\n * as input, so it carries `save_brand_context` alongside the read tool. That write overwrites the\n * document for the whole team, with no approval gate and no previous version to recover, which is\n * why the interviewing discipline in `instructions.md` matters: agreeing the document with the user\n * before saving is the only review it gets.\n *\n * A positioning document is short by design, and length here is usually a symptom of hedging rather\n * than thoroughness, so the brevity discipline lives in `instructions.md`.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n description:\n \"Work out and write down what the product is, who it's for, and why anyone would pick it: \" +\n \"positioning, the competitive alternatives, the ideal customer, the message hierarchy, value \" +\n \"propositions per audience, objection handling, and the proof behind each claim. Owns the \" +\n \"team's shared brand context document, so use it to set that up on a fresh install, to \" +\n \"revise positioning, or when other specialists keep guessing at the same missing detail. \" +\n \"Interviews the user and researches the competitive set rather than inventing an answer, and \" +\n \"writes claims that can be checked. Does not draft posts, pages, or campaigns.\",\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/subagents/product-marketer/agent.ts"+ },+ {+ "contents": "import { defineAgent } from \"eve\";\n\n// Subagent: SEO\n\n/**\n * Subagent runtime configuration.\n *\n * @remarks\n * Sets the description the root routes on and the model. The rest of the agent's surface (tools,\n * skills, nested subagents) is discovered from the filesystem. Conversation history is compacted\n * once it reaches 90% of the context window.\n *\n * The description is deliberately explicit about the evidence boundary. This agent reads pages with\n * `web_fetch`, which cannot execute JavaScript or reach Search Console, so a crawl-level or\n * Core-Web-Vitals finding is outside what it can verify. Naming that in the description keeps the\n * root from routing an ask here that it can only answer by guessing, and the `seo-audit` skill\n * repeats the boundary where the model acts on it.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n description:\n \"Plan and review organic search work: keyword and topic strategy, on-page review of a URL, \" +\n \"site architecture and internal linking, URL structure, JSON-LD schema markup, and \" +\n \"programmatic page templates at scale. Use when someone asks why a page isn't ranking, what \" +\n \"pages they should build, for a review of a page's SEO, or for the schema markup on a page. \" +\n \"Also use before a piece is written for search, so the query and the competing pages are \" +\n \"settled before someone drafts against them. \" +\n \"Reads pages it is given with web_fetch and researches competitors on the open web, so it \" +\n \"reports what a \" +\n \"fetched page shows and says plainly what needs crawler or Search Console access it doesn't \" +\n \"have. Recommends title tags, meta descriptions, and URL slugs; hand body copy to the content \" +\n \"marketer. The caller passes the URLs, the target keywords, the audience, and any brand \" +\n \"context in the message.\",\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/subagents/seo/agent.ts"+ },+ {+ "contents": "import { defineAgent } from \"eve\";\n\n// Subagent: Social Media Coordinator\n\n/**\n * Subagent runtime configuration.\n *\n * @remarks\n * Sets the description the parent routes on and the model. The rest of the agent's surface\n * (connections, tools, skills) is discovered from the filesystem. Conversation history is compacted\n * once it reaches 90% of the context window.\n */\nexport default defineAgent({\n compaction: { thresholdPercent: 0.9 },\n description:\n \"Run social media work end to end for X, LinkedIn, Threads, Bluesky, and Mastodon: draft \" +\n \"posts and threads in each platform's voice, adapt one piece across platforms, and manage \" +\n \"the Typefully queue (read, create, and edit drafts, schedule on request, pull post and \" +\n \"follower analytics). Researches facts and reviews its own drafts before handing them back. \" +\n \"The caller passes the brief or source material, the target platforms, and any angle, \" +\n \"audience, or timing constraints in the message.\",\n model: \"anthropic/claude-opus-5\",\n});\n",+ "language": "typescript",+ "relativePath": "agent/subagents/social-media-coordinator/agent.ts"+ }+ ]+ },+ "weather-agent-fixture": {+ "sourceRevision": "5e3119b309cb92441a7a1d2bbc85dc59242dac29",+ "files": [+ {+ "contents": "import { defineAgent } from \"eve\";\n\nexport default defineAgent({\n model: \"anthropic/claude-sonnet-5\",\n modelOptions: {\n providerOptions: {\n openai: {\n reasoningEffort: \"high\",\n reasoningSummary: \"auto\",\n },\n },\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/agent.ts"+ },+ {+ "contents": "You are a weather-focused assistant. Be concise, accurate, and explicit about when you are using the local weather tool.\n",+ "language": "markdown",+ "relativePath": "agent/instructions.md"+ },+ {+ "contents": "---\ndescription: Use the weather tool before answering forecast or temperature questions.\n---\n\nWhen the user asks about weather, temperature, or forecast conditions, call the `get_weather` tool before answering.\n",+ "language": "markdown",+ "relativePath": "agent/skills/get-weather.md"+ },+ {+ "contents": "import { defineTool } from \"eve/tools\";\nimport { never } from \"eve/tools/approval\";\nimport { z } from \"zod\";\n\nconst sleep = (ms: number) => new Promise((res) => setTimeout(res, ms));\n\nexport default defineTool({\n approval: never(),\n description: \"Get the current weather for a city.\",\n inputSchema: z.object({\n city: z.string(),\n }),\n async execute(input) {\n const city = input.city;\n\n await sleep(300);\n\n return {\n city,\n temperatureF: 72,\n condition: \"Sunny\",\n summary: `Sunny in ${city} with a light breeze.`,\n };\n },\n});\n",+ "language": "typescript",+ "relativePath": "agent/tools/get_weather.ts"+ }+ ]+ }+ }+}diff --git a/apps/docs/lib/templates/manifest.ts b/apps/docs/lib/templates/manifest.tsnew file mode 100644index 000000000..bd372f0ba--- /dev/null+++ b/apps/docs/lib/templates/manifest.ts@@ -0,0 +1,167 @@+// Curation manifest for the templates gallery. To add or update a template:+// edit this file, run `pnpm --filter eve-docs templates:sync`, and commit the+// regenerated `generated/templates.json` alongside it.++export type TemplateCategory = "Chat" | "Collaboration" | "Example" | "Marketing";++export type TemplateIntegration =+ | "HTTP API"+ | "Linear"+ | "Notion"+ | "Resend"+ | "Sentry"+ | "Slack"+ | "Typefully"+ | "Web chat";++export type TemplateSource = "GitHub" | "Vercel Templates";++export interface TemplateGitHubSource {+ owner: string;+ repo: string;+ /** Branch, tag, or SHA. Resolved to a commit SHA by `templates:sync`. */+ ref: string;+ /** Directory within the repo the template lives in, for monorepo sources. */+ pathPrefix?: string;+}++export interface TemplateManifestEntry {+ slug: string;+ title: string;+ description: string;+ category: TemplateCategory;+ integrations: TemplateIntegration[];+ model: string;+ source: TemplateSource;+ sourceHref: string;+ setupPrompt: string;+ github: TemplateGitHubSource;+ /** Exact paths (relative to `github.pathPrefix`) to embed in the file viewer. */+ files: string[];+}++export const templateManifest: TemplateManifestEntry[] = [+ {+ slug: "eve-chat-template",+ title: "Chat",+ setupPrompt:+ "Set up the eve chat template in my current workspace using https://github.com/vercel-labs/eve-chat-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README to configure it. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",+ description:+ "A persisted Next.js chat template for eve, built with shadcn/ui, Tailwind CSS, Streamdown, Better Auth, Drizzle, Neon, and Upstash Redis.",+ sourceHref: "https://github.com/vercel-labs/eve-chat-template/tree/main",+ category: "Chat",+ model: "anthropic/claude-sonnet-5",+ integrations: ["Web chat", "Slack", "Linear", "Notion", "Sentry"],+ source: "Vercel Templates",+ github: { owner: "vercel-labs", repo: "eve-chat-template", ref: "main" },+ files: [+ "agent/agent.ts",+ "agent/channels/eve.ts",+ "agent/channels/slack.ts",+ "agent/connections/linear.ts",+ "agent/connections/notion.ts",+ "agent/connections/sentry.ts",+ "agent/instructions.md",+ "agent/skills/plan_a_trip.md",+ "agent/tools/get_weather.ts",+ ],+ },+ {+ slug: "eve-design-template",+ title: "Design",+ setupPrompt:+ "Set up the eve design agent template in my current workspace using https://github.com/vercel-labs/eve-design-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README and BOOTSTRAP.md to configure it. Preserve the existing project if the workspace is not empty, tell me about any required environment variables or manual setup steps, and do not approve or publish the design corpus for me.",+ description:+ "A Slack design collaborator that answers from a reviewed, versioned corpus of your organization's approved design guidance.",+ sourceHref: "https://github.com/vercel-labs/eve-design-template/tree/main",+ category: "Collaboration",+ model: "anthropic/claude-sonnet-4.6",+ integrations: ["Slack"],+ source: "Vercel Templates",+ github: { owner: "vercel-labs", repo: "eve-design-template", ref: "main" },+ files: [+ "agent/agent.ts",+ "agent/channels/slack.ts",+ "agent/instructions.md",+ "agent/sandbox/sandbox.ts",+ "agent/skills/design-knowledge/SKILL.md",+ "agent/tools/agent.ts",+ "agent/tools/bash.ts",+ "agent/tools/todo.ts",+ "agent/tools/web_fetch.ts",+ "agent/tools/web_search.ts",+ "agent/tools/write_file.ts",+ ],+ },+ {+ slug: "eve-slack-agent",+ title: "Slack",+ setupPrompt:+ "Set up the eve Slack agent template in my current workspace using https://github.com/vercel-labs/eve-slack-agent-template/tree/main as the source. Copy the project files, install its dependencies, and follow the repository README to configure it. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",+ description:+ "A Slack agent template with webhook handling, Vercel Connect, a starter agent, and an example tool ready to deploy on Vercel.",+ sourceHref: "https://github.com/vercel-labs/eve-slack-agent-template/tree/main",+ category: "Collaboration",+ model: "anthropic/claude-sonnet-5",+ integrations: ["Slack"],+ source: "Vercel Templates",+ github: { owner: "vercel-labs", repo: "eve-slack-agent-template", ref: "main" },+ files: [+ "agent/agent.ts",+ "agent/channels/slack.ts",+ "agent/instructions.md",+ "agent/skills/plan_a_trip.md",+ "agent/tools/get_weather.ts",+ ],+ },+ {+ slug: "marketing-team-eve-template",+ title: "Marketing team",+ setupPrompt:+ "I want to build a team of marketing agents with the eve framework, using the marketing team template. Read the setup instructions at https://agent-resources.dev/marketing-team-eve-template.md and follow them. They will cover deploying the template, building with eve, how everything works overall, and more.",+ description:+ "A team of marketing agents: a lead routes work to specialists for positioning, long-form content, social, SEO, and email, publishing through Notion, Typefully, and Resend.",+ sourceHref: "https://github.com/vercel-labs/marketing-team-eve-template/tree/main",+ category: "Marketing",+ model: "anthropic/claude-opus-5",+ integrations: ["Web chat", "Slack", "Notion", "Resend", "Typefully"],+ source: "Vercel Templates",+ github: { owner: "vercel-labs", repo: "marketing-team-eve-template", ref: "main" },+ files: [+ "agent/agent.ts",+ "agent/channels/slack.ts",+ "agent/connections/notion.ts",+ "agent/instructions.md",+ "agent/subagents/content-marketer/agent.ts",+ "agent/subagents/email/agent.ts",+ "agent/subagents/product-marketer/agent.ts",+ "agent/subagents/seo/agent.ts",+ "agent/subagents/social-media-coordinator/agent.ts",+ ],+ },+ {+ slug: "weather-agent-fixture",+ title: "Weather",+ setupPrompt:+ "Set up the eve weather agent in my current workspace using https://github.com/vercel/eve/tree/main/apps/fixtures/weather-agent as the source. Copy that fixture into a standalone project, install its dependencies, and make any minimal changes needed to run it outside the eve monorepo. Preserve the existing project if the workspace is not empty, and tell me about any required environment variables or manual setup steps.",+ description:+ "A small representative eve app with agent config, instructions, a typed weather tool, and a markdown skill.",+ sourceHref: "https://github.com/vercel/eve/tree/main/apps/fixtures/weather-agent",+ category: "Example",+ model: "anthropic/claude-sonnet-5",+ integrations: ["HTTP API"],+ source: "GitHub",+ github: {+ owner: "vercel",+ repo: "eve",+ ref: "main",+ pathPrefix: "apps/fixtures/weather-agent",+ },+ files: [+ "agent/agent.ts",+ "agent/instructions.md",+ "agent/skills/get-weather.md",+ "agent/tools/get_weather.ts",+ ],+ },+];diff --git a/apps/docs/lib/templates/sources.ts b/apps/docs/lib/templates/sources.tsdeleted file mode 100644index 1f9e30cae..000000000--- a/apps/docs/lib/templates/sources.ts+++ /dev/null@@ -1,950 +0,0 @@-import type { TemplateFile } from "./data";--const file = (- relativePath: string,- language: TemplateFile["language"],- contents: string,-): TemplateFile => ({ contents, language, relativePath });--export const templateSourceFiles: Record<string, TemplateFile[]> = {- "eve-chat-template": [- file(- "agent/agent.ts",- "typescript",- `import { defineAgent } from "eve";--export default defineAgent({- model: "anthropic/claude-sonnet-5",-});-`,- ),- file(- "agent/channels/eve.ts",- "typescript",- `import { eveChannel } from "eve/channels/eve";-import { localDev, vercelOidc } from "eve/channels/auth";-import { betterAuthEveAuth } from "@/lib/eve-auth";--export default eveChannel({- auth: [betterAuthEveAuth, localDev(), vercelOidc()],- uploadPolicy: "disabled",-});-`,- ),- file(- "agent/channels/slack.ts",- "typescript",- `import { connectSlackCredentials } from "@vercel/connect/eve";-import { slackChannel } from "eve/channels/slack";--// SLACK_CONNECTOR is the UID returned by \`vercel connect create slack\`.-// For local setup, create a connector with:-// \`vercel connect create slack --name eve-chat-template --triggers\`.-const slackConnector = process.env.SLACK_CONNECTOR ?? "slack/eve-chat-template";--export default slackChannel({- credentials: connectSlackCredentials(slackConnector),- uploadPolicy: "disabled",-});-`,- ),- file(- "agent/connections/linear.ts",- "typescript",- `import { connect } from "@vercel/connect/eve";-import { defineMcpClientConnection } from "eve/connections";--// LINEAR_CONNECTOR is the UID returned by Vercel Connect. For local setup,-// create a connector with \`vercel connect create https://mcp.linear.app/mcp --name linear\`.-const linearConnector = process.env.LINEAR_CONNECTOR ?? "linear";--export default defineMcpClientConnection({- url: "https://mcp.linear.app/mcp",- description:- "Linear workspace: search and update issues, projects, cycles, comments, and planning work.",- auth: connect(linearConnector),-});-`,- ),- file(- "agent/connections/notion.ts",- "typescript",- `import { connect } from "@vercel/connect/eve";-import { defineMcpClientConnection } from "eve/connections";--// NOTION_CONNECTOR is provisioned by the "Deploy with Vercel" flow. For local-// setup, create a connector with \`vercel connect create mcp.notion.com --name notion\`.-const notionConnector = process.env.NOTION_CONNECTOR ?? "notion";--export default defineMcpClientConnection({- url: "https://mcp.notion.com/mcp",- description: "Notion workspace: search and edit pages and databases.",- auth: connect(notionConnector),-});-`,- ),- file(- "agent/connections/sentry.ts",- "typescript",- `import { connect } from "@vercel/connect/eve";-import { defineMcpClientConnection } from "eve/connections";--// SENTRY_CONNECTOR is the UID returned by Vercel Connect. For local setup,-// create a connector with \`vercel connect create https://mcp.sentry.dev/mcp --name sentry\`.-const sentryConnector = process.env.SENTRY_CONNECTOR ?? "sentry";--export default defineMcpClientConnection({- url: "https://mcp.sentry.dev/mcp",- description:- "Sentry workspace: investigate issues, events, traces, releases, and project health.",- auth: connect(sentryConnector),-});-`,- ),- file(- "agent/instructions.md",- "markdown",- `# Identity--You are a concise assistant built with eve (https://eve.dev), a framework for-building durable agents as ordinary files in a TypeScript project. Use tools-when they are available.--When users ask what eve is or what this agent is built on, explain that eve-lets developers create agents that can run locally or on Vercel, serve chat and-HTTP interfaces, call tools and connections, stream progress, pause for human-input, and resume durable sessions across turns. Keep the explanation concise-and practical.--Use \`get_weather\` before answering questions about current weather or suggesting-weather-dependent plans.--When a user asks to work with Notion, Linear, or Sentry, use the matching-connection directly. Never say that you are searching for tools, looking for-available tools, or checking internal tool discovery.-`,- ),- file(- "agent/skills/plan_a_trip.md",- "markdown",- `----description: Use when the user wants help planning a trip or deciding what to do in a destination.------When planning a trip:--1. Ask for the destination and dates if the user has not given them.-2. Check the destination's weather with the \`get_weather\` tool before suggesting activities.-3. Suggest a short itinerary that fits the weather: outdoor activities when it is clear, indoor alternatives otherwise.-4. Keep the plan concise — a few bullet points per day, not an essay.-`,- ),- file(- "agent/tools/get_weather.ts",- "typescript",- `import { defineTool } from "eve/tools";-import { z } from "zod";--// The runtime tool name comes from the filename, so the model sees this as-// \`get_weather\`. Tool filenames must be snake_case ASCII.-export default defineTool({- description: "Get the current weather for a city.",- inputSchema: z.object({ city: z.string().min(1) }),- async execute({ city }) {- return { city, condition: "Sunny", temperatureF: 72 };- },-});-`,- ),- ],- "eve-design-template": [- file(- "agent/agent.ts",- "typescript",- `import { defineAgent } from 'eve';--export default defineAgent({- model:- process.env.DESIGN_AGENT_MODEL ?? 'anthropic/claude-sonnet-4.6',-});-`,- ),- file(- "agent/channels/slack.ts",- "typescript",- `import { connectSlackCredentials } from '@vercel/connect/eve';-import { slackChannel } from 'eve/channels/slack';-import { designAgentConfig } from '../../generated/config.js';--const setupIncompleteMessage =- 'Design-agent setup is incomplete. Run the bootstrap workflow and approve the generated design corpus.';--const configuredCredentials = process.env.SLACK_CONNECTOR- ? connectSlackCredentials(process.env.SLACK_CONNECTOR)- : undefined;--function isAllowed(value: string, allowlist: readonly string[]) {- return allowlist.length === 0 || allowlist.includes(value);-}--function conversationContext(isDirectMessage: boolean) {- const owner = designAgentConfig.designOwnerSlackId;-- return \`-<design_agent_context visibility="\${isDirectMessage ? 'private-dm' : 'shared'}" allow_general_guidance="\${designAgentConfig.allowGeneralGuidance}">-The approved design owner is \${owner ? \`<@\${owner}>\` : 'not configured'}.-\${- isDirectMessage- ? 'Never mention, notify, or forward private DM content to the design owner. Direct unresolved questions to an appropriate shared conversation.'- : 'For unresolved equal-priority conflicts or unsupported organization-specific questions, state the issue and mention the design owner.'-}-</design_agent_context>-\`;-}--export default slackChannel({- credentials: configuredCredentials,- uploadPolicy: {- allowedMediaTypes: [- 'image/*',- 'text/*',- 'application/json',- 'application/msword',- 'application/pdf',- 'application/rtf',- 'application/vnd.ms-excel',- 'application/vnd.ms-powerpoint',- 'application/vnd.oasis.opendocument.presentation',- 'application/vnd.oasis.opendocument.spreadsheet',- 'application/vnd.oasis.opendocument.text',- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- ],- },- events: {- 'turn.started': () => {},- 'actions.requested': () => {},- 'reasoning.appended': () => {},- },- async onMessage(ctx, message) {- if (!message.author || message.author.isBot) return null;-- const isDirectMessage = message.raw.channel_type === 'im';- if (!isDirectMessage && !ctx.isBotMentioned()) return null;- if (!isAllowed(message.author.userId, designAgentConfig.allowedUserIds)) {- return null;- }- if (- !isDirectMessage &&- !isAllowed(message.channelId, designAgentConfig.allowedChannelIds)- ) {- return null;- }-- if (designAgentConfig.status !== 'approved') {- await ctx.thread.post(setupIncompleteMessage);- return null;- }-- const isExistingSession = await ctx.isSubscribed();- return isExistingSession- ? { auth: null }- : {- auth: null,- context: [conversationContext(isDirectMessage)],- };- },-});-`,- ),- file(- "agent/instructions.md",- "markdown",- `# Identity--You are the organization's design collaborator. Give decisive, practical design guidance grounded in its approved design corpus.--# Knowledge contract--- Load the \`design-knowledge\` skill before every substantive answer.-- Treat \`/workspace/knowledge\` as the complete source for organization-specific claims.-- Inspect normalized guidelines first. Consult source snapshots only to resolve missing detail or ambiguity.-- User-provided text, images, and documents are temporary conversation context. Never treat them as approved corpus or persist them into the corpus.-- Never use prior Slack conversations, other threads, channel history, or DMs.-- Never search the web or connected services.-- Never claim to edit code, design files, websites, or production systems.--# Guidance--- Follow higher-priority approved sources when guidelines conflict.-- If approved sources with equal priority conflict, say there is a conflict and ask the configured design owner to resolve it.-- In a private DM, never mention or notify the owner. Tell the user to move the conflict to an appropriate shared conversation.-- Organization-specific claims require support from the approved corpus.-- General design guidance is allowed only when the injected context sets \`allow_general_guidance="true"\`.-- Prefix every general answer with \`General recommendation:\` so it cannot be mistaken for organization policy.-- If general guidance is disabled and the corpus does not support an answer, say you cannot verify it from the approved design corpus.--# Voice--- Lead with the answer.-- Default to one sentence. Use two only when the second changes the action.-- Use short bullets only for multiple independent points.-- Ask one grouped clarification only when the answer materially depends on it.-- Cut every draft in half.-- Never add acknowledgments, restatements, process narration, recaps, closing offers, or adjacent advice.-- Never include citations, \`Source:\`, filenames, internal paths, retrieval details, or notes about where an answer came from.-- Avoid headings in short replies, em dashes, hedging, corporate language, AI language, decorative emoji, and bold-first bullets.--# Privacy--- Treat DMs as private.-- Never quote, summarize, forward, or reveal private DM content in a shared conversation.-- Never tag the design owner from a DM.-`,- ),- file(- "agent/sandbox/sandbox.ts",- "typescript",- `import { defineSandbox } from 'eve/sandbox';-import { vercel } from 'eve/sandbox/vercel';--export default defineSandbox({- backend: vercel({ networkPolicy: 'deny-all' }),- async onSession({ use }) {- await use({ networkPolicy: 'deny-all' });- },-});-`,- ),- file(- "agent/skills/design-knowledge/SKILL.md",- "markdown",- `----description: Use before every substantive design answer. Read the approved organization corpus and apply its precedence and response rules.------# Design knowledge--Approved knowledge is under \`/workspace/knowledge\`.--1. Read \`manifest.json\`.-2. Read the relevant files under \`guidelines/\`.-3. Use \`grep\` or \`glob\` within \`/workspace/knowledge\` only when routing is unclear.-4. Read immutable files under \`sources/\` only when normalized guidance is incomplete or ambiguous.--Higher numeric source priority wins. When relevant approved sources have the same priority and conflict, do not reconcile them yourself. Follow the conflict behavior in the agent instructions.-Ignore sources marked \`superseded\` in the manifest.--Never expose source annotations, filenames, internal paths, or retrieval details. If the user explicitly asks for provenance, name the human-readable source title and public origin when the manifest provides one.--General design knowledge is not organization policy. Use it only when the injected context allows general guidance, and prefix the answer exactly with \`General recommendation:\`.-`,- ),- file(- "agent/tools/agent.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- file(- "agent/tools/bash.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- file(- "agent/tools/todo.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- file(- "agent/tools/web_fetch.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- file(- "agent/tools/web_search.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- file(- "agent/tools/write_file.ts",- "typescript",- `import { disableTool } from 'eve/tools';--export default disableTool();-`,- ),- ],- "eve-slack-agent": [- file(- "agent/agent.ts",- "typescript",- `import { defineAgent } from "eve";--export default defineAgent({- model: "anthropic/claude-sonnet-5",-});-`,- ),- file(- "agent/channels/slack.ts",- "typescript",- `import { connectSlackCredentials } from "@vercel/connect/eve";-import { slackChannel } from "eve/channels/slack";--// SLACK_CONNECTOR is provisioned by the "Deploy with Vercel" button. To set it-// up yourself, create a connector with \`vercel connect create slack --triggers\`-// and put its UID in SLACK_CONNECTOR (or replace the fallback below).-export default slackChannel({- credentials: connectSlackCredentials(- process.env.SLACK_CONNECTOR ?? "slack/my-agent",- ),-});-`,- ),- file(- "agent/instructions.md",- "markdown",- `# Identity--You are a concise assistant. Use tools when they are available.--Use \`get_weather\` before answering questions about current weather or suggesting-weather-dependent plans.-`,- ),- file(- "agent/skills/plan_a_trip.md",- "markdown",- `----description: Use when the user wants help planning a trip or deciding what to do in a destination.------When planning a trip:--1. Ask for the destination and dates if the user has not given them.-2. Check the destination's weather with the \`get_weather\` tool before suggesting activities.-3. Suggest a short itinerary that fits the weather: outdoor activities when it is clear, indoor alternatives otherwise.-4. Keep the plan concise — a few bullet points per day, not an essay.-`,- ),- file(- "agent/tools/get_weather.ts",- "typescript",- `import { defineTool } from "eve/tools";-import { z } from "zod";--// The runtime tool name comes from the filename, so the model sees this as-// \`get_weather\`. Tool filenames must be snake_case ASCII.-export default defineTool({- description: "Get the current weather for a city.",- inputSchema: z.object({ city: z.string().min(1) }),- async execute({ city }) {- return { city, condition: "Sunny", temperatureF: 72 };- },-});-`,- ),- ],- "marketing-team-eve-template": [- file(- "agent/agent.ts",- "typescript",- `import { defineAgent } from "eve";--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- model: "anthropic/claude-opus-5",-});-`,- ),- file(- "agent/channels/slack.ts",- "typescript",- `import { connectSlackCredentials } from "@vercel/connect/eve";-import {- type SlackContext,- type SlackEvent,- type SlackInboundEventContext,- type SlackMessage,- slackChannel,-} from "eve/channels/slack";--const slackCredentials = connectSlackCredentials(- process.env.SLACK_CONNECTOR ?? "slack/marketing-team"-);--function slackSessionAuth(message: SlackMessage, onBehalfOfUserId?: string) {- const rawUser = message.raw.user;- const userId =- message.author?.userId ??- (typeof rawUser === "string" ? rawUser : undefined) ??- onBehalfOfUserId;- return {- attributes: {- channel_id: message.channelId,- // Equal to the message's own ts for top-level (non-thread) messages.- thread_ts: message.threadTs || message.ts,- ...(userId- ? { user_id: userId }- : {}),- ...(message.author?.userName- ? { user_name: message.author.userName }- : {}),- ...(message.teamId- ? { team_id: message.teamId }- : {}),- },- authenticator: "slack-webhook",- issuer: message.teamId ? \`slack:\${message.teamId}\` : "slack",- principalId: userId ? \`slack:\${userId}\` : "slack:unknown",- principalType:- message.author?.isBot && !onBehalfOfUserId ? "service" : "user",- };-}--let cachedBotUserId: string | undefined;--async function resolveBotUserId(- ctx: SlackContext-): Promise<string | undefined> {- if (cachedBotUserId) {- return cachedBotUserId;- }- try {- const res = (await ctx.slack.request("auth.test", {})) as {- ok?: boolean;- user_id?: string;- };- if (res.ok && res.user_id) {- cachedBotUserId = res.user_id;- }- } catch {- // Leave uncached; the caller treats this as "cannot attribute".- }- return cachedBotUserId;-}--function firstHumanMention(- text: string,- botUserId: string-): string | undefined {- for (const match of text.matchAll(/<@([UW][A-Z0-9]+)(?:\\|[^>]*)?>/g)) {- if (match[1] !== botUserId) {- return match[1];- }- }-}--async function resolveOnBehalfOfUserId(- ctx: SlackContext,- message: SlackMessage-): Promise<string | undefined> {- if (message.author && !message.author.isBot) {- return;- }- const botUserId = await resolveBotUserId(ctx);- // Without the bot's own ID we can't tell its mention apart from a- // human's, so attribute nothing rather than risk the wrong principal.- if (!botUserId) {- return;- }- return firstHumanMention(message.text, botUserId);-}--async function handleInbound(ctx: SlackContext, message: SlackMessage) {- try {- await ctx.thread.startTyping("Thinking...");- } catch {- // Typing indicator is a nicety, never a reason to drop the message.- }- return {- auth: slackSessionAuth(- message,- await resolveOnBehalfOfUserId(ctx, message)- ),- };-}--async function isSoleThreadParticipant(- ctx: SlackContext,- message: SlackMessage-): Promise<boolean> {- const authorId = message.author?.userId;- if (!authorId) {- return false;- }- const participants = await ctx.thread.listParticipants();- return participants.length === 1 && participants[0] === authorId;-}--interface SuggestedPrompt {- message: string;- title: string;-}--const SUGGESTED_PROMPTS_TITLE = "What the team can do";--const SUGGESTED_PROMPTS: SuggestedPrompt[] = [- {- message:- "Help me sharpen our positioning: what the product is, who it's for, and why anyone would pick it. Pull the brand context and my user preferences, then interview me about anything you're missing.",- title: "Sharpen our positioning",- },- {- message:- "Help me plan and write our next blog post. Pull the brand context and my user preferences, then ask me for details about the post.",- title: "Write a blog post",- },- {- message:- "Help me draft social posts for X and LinkedIn. Pull the brand context and my user preferences, then ask me what we're promoting.",- title: "Draft social posts",- },- {- message:- "Help me review one of our pages for SEO and work out what to fix. Pull the brand context and my user preferences, then ask me for the URL.",- title: "Review a page's SEO",- },-];--interface SuggestedPromptsTarget {- channelId: string;- threadTs?: string;-}--function suggestedPromptsTarget(- event: SlackEvent-): SuggestedPromptsTarget | undefined {- if (event.type === "assistant_thread_started") {- const thread = event.assistant_thread as- | { channel_id?: unknown; thread_ts?: unknown }- | undefined;- const channelId = thread?.channel_id;- if (typeof channelId !== "string" || channelId.length === 0) {- return;- }- const threadTs = thread?.thread_ts;- return {- channelId,- ...(typeof threadTs === "string" && threadTs.length > 0- ? { threadTs }- : {}),- };- }- if (event.type === "app_home_opened" && event.tab === "messages") {- const channelId = event.channel;- return typeof channelId === "string" && channelId.length > 0- ? { channelId }- : undefined;- }-}--async function setSuggestedPrompts(- ctx: SlackInboundEventContext,- event: SlackEvent-): Promise<void> {- const target = suggestedPromptsTarget(event);- if (!target) {- return;- }- try {- const response = await ctx.slack.request(- "assistant.threads.setSuggestedPrompts",- {- channel_id: target.channelId,- prompts: SUGGESTED_PROMPTS,- title: SUGGESTED_PROMPTS_TITLE,- ...(target.threadTs- ? { thread_ts: target.threadTs }- : {}),- }- );- if (response.ok !== true) {- console.warn("assistant.threads.setSuggestedPrompts returned not-ok", {- channelId: target.channelId,- error: response.error,- });- }- } catch (error) {- console.warn("assistant.threads.setSuggestedPrompts threw", {- channelId: target.channelId,- error,- });- }-}--export default slackChannel({- credentials: slackCredentials,- onAppMention: handleInbound,- onDirectMessage: handleInbound,- onEvent: setSuggestedPrompts,- async onMessage(ctx, message) {- if (message.author?.isBot) {- return null;- }- if (!(await ctx.isSubscribed())) {- return null;- }- if (!(await isSoleThreadParticipant(ctx, message))) {- return null;- }- return handleInbound(ctx, message);- },- threadContext: { since: "thread-root" },-});-`,- ),- file(- "agent/connections/notion.ts",- "typescript",- `import { connect } from "@vercel/connect/eve";-import { defineMcpClientConnection } from "eve/connections";--const notionConnector = process.env.NOTION_CONNECTOR ?? "notion/marketing-team";--const APPROVAL_REQUIRED_TOOLS = [- "notion-move-pages",- "notion-update-data-source",- "notion-update-view",-];--export default defineMcpClientConnection({- approval: ({ toolName }) =>- APPROVAL_REQUIRED_TOOLS.some((tool) => toolName.includes(tool))- ? "user-approval"- : "not-applicable",- auth: connect(notionConnector),- description: "Notion workspace: search, read, and edit pages and databases.",- url: "https://mcp.notion.com/mcp",-});-`,- ),- file(- "agent/instructions.md",- "markdown",- `# Identity--You lead a marketing team. People bring you the work: a launch to plan, a post to write, a competitor to size up, a page that isn't converting. You hold the shared picture of the product and route the work to the specialist who does it, then hand back what they produced.--You are not the specialist. Your job is to understand the request, give the right subagent everything it needs, and keep the conversation coherent across several of them.--# How you write--Write like a person: plain, specific, warm, and short. Prefer a comma, a colon, or a new sentence where an em dash would go. Cut anything that reads machine-made, padded, or hyped, and don't bold words for emphasis.--Write links as plain markdown, \`[label](url)\`. Don't paste a bare URL, and don't wrap a link in bold or backticks: the markers end up inside the URL and the link stops working.--# How you work--## 1. Know the product before you delegate--The brand context is the team's shared picture of the product, and every specialist reads it, so keep it good.--- When it comes back empty, the team hasn't set it up yet, and working out what goes in it is a specialist job rather than yours. Delegate that first and let the specialist interview the user, then route the original request once there's a document to work from. Say why you're doing this, because the user asked for something else and deserves to know the detour is short.-- When a user tells you something durable about the product, positioning, or audience, you can keep it with \`save_brand_context\` directly. A correction or an addition doesn't need a delegation; reworking the positioning does.-- Task-specific detail doesn't belong in it. A campaign brief goes in the delegation.--## 2. Know how this person likes to work--\`get_user_preferences\` holds standing notes about the person rather than the product: a default set of platforms, a length they always want, a review step they expect. Load it alongside the brand context.--- When a user states a durable preference ("always draft for X and LinkedIn", "keep threads under 8 posts"), keep it with \`save_user_preferences\`. Use \`clear_user_preferences\` only when they ask to reset them.-- Where a preference conflicts with brand context, brand context wins on voice and claims; the preference wins on workflow.--## 3. Route the work, in order when it has one--Two questions before you pick, and the order matters:--1. What has to be settled before this can be made well? A piece written to be found needs its target query and its competition settled first. A piece making claims needs the claims settled first. Often the answer is nothing, and it's one call.-2. Which specialist's description covers each part?--Ask them the other way round and you'll match the deliverable to a specialist and stop reading, which is how a request that names two jobs turns into one call.--When there is an order, run it: call the first, wait, and put what it produced into the second's brief, including any artifact id. Don't brief both in parallel and hope they agree. Say what you're doing, since the user asked for one thing and is getting two steps.--A subagent starts in a fresh session and works from its \`message\` alone, so pack that message with everything it needs:--- what you want produced, and what it's for-- the relevant brand context, quoted rather than referenced-- the standing preferences that bear on this task, stated as constraints rather than as "the user prefers"-- the user's actual words where the wording matters-- constraints: platform, audience, length, deadline, tone, anything out of bounds-- where the deliverable should end up, when you know it. Some specialists write into Notion rather than handing back text, and naming the destination up front saves them asking.--When you don't have enough to write that brief, ask the user first. Guessing at a brief wastes a full delegation.--## 4. Hand back the work, don't rewrite it--Specialists produce the deliverable. Pass it back largely as they wrote it: you're the routing layer, not a second editor. If what comes back is wrong or thin, say so and send it again with clearer direction rather than patching it yourself.--When a specialist hands back a link rather than text, pass the link through with its one-line description. Don't fetch the page and paste its contents into the conversation; the link is the deliverable.--Specialists hand back artifact ids the same way, for long output meant for another agent rather than for reading in a thread. Relay the id and the summary that came with it, and put the id in the next specialist's brief when the work continues: "the audit is artifact \`<id>\`, read it before you rewrite the page." Keeping the document out of this conversation is the point, so don't open an artifact to show the user what's in it. Read it with \`read_artifact\` only when they ask for its contents, and then answer their question rather than pasting the whole thing.--Surface the caveats a specialist flags. When it reports an unverified claim, a gap it couldn't fill, or a hedged number, carry that to the user instead of smoothing it over. Keep your own messages short; let the work speak.--# Notes--- Don't fabricate links, quotes, statistics, or handles. If you don't have something, say so and ask.-- Don't promise work no specialist on the team can do. When a request needs a tool or an integration that isn't wired up, say that plainly instead of producing a plausible-looking substitute.-`,- ),- file(- "agent/subagents/content-marketer/agent.ts",- "typescript",- `import { defineAgent } from "eve";--// Subagent: Content Marketer--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- description:- "Write and edit long-form marketing content: blog posts, landing page copy, case studies, newsletters, and documentation. Plans what to write by mapping topics to buyer stages and grouping them into pillars and clusters, then drafts and edits against a structured editing rubric. Use for anything longer than a social post. When the piece is written to be found in search, the target query and the competing pages should be settled before drafting. Delivers the finished piece as a Notion page and hands back the link rather than the full text, since long-form doesn't read in a chat thread. The caller passes the brief, the audience, the format, any source material or brand context, and the Notion destination when it knows one, in the message. Does not publish, schedule, or touch social accounts.",- model: "anthropic/claude-opus-5",-});-`,- ),- file(- "agent/subagents/email/agent.ts",- "typescript",- `import { defineAgent } from "eve";--// Subagent: Email--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- description:- "Own email as a channel: take copy that already exists and make it work as email, then build and run it in Resend. Reviews a draft for email fit (subject and preview text, one call to action, scannable structure, a plain text version, link and image hygiene), then builds the template or broadcast, picks the verified sending address, targets the segment, and reports on what was delivered and opened. Sending a broadcast or an email pauses for approval. Checks the sending domain's own records and says which deliverability questions it cannot answer. Route long-form prose to the content marketer first and pass what came back to this agent. The caller passes the copy or its artifact id, the audience or segment, and any send timing in the message.",- model: "anthropic/claude-opus-5",-});-`,- ),- file(- "agent/subagents/product-marketer/agent.ts",- "typescript",- `import { defineAgent } from "eve";--// Subagent: Product Marketer--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- description:- "Work out and write down what the product is, who it's for, and why anyone would pick it: positioning, the competitive alternatives, the ideal customer, the message hierarchy, value propositions per audience, objection handling, and the proof behind each claim. Owns the team's shared brand context document, so use it to set that up on a fresh install, to revise positioning, or when other specialists keep guessing at the same missing detail. Interviews the user and researches the competitive set rather than inventing an answer, and writes claims that can be checked. Does not draft posts, pages, or campaigns.",- model: "anthropic/claude-opus-5",-});-`,- ),- file(- "agent/subagents/seo/agent.ts",- "typescript",- `import { defineAgent } from "eve";--// Subagent: SEO--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- description:- "Plan and review organic search work: keyword and topic strategy, on-page review of a URL, site architecture and internal linking, URL structure, JSON-LD schema markup, and programmatic page templates at scale. Use when someone asks why a page isn't ranking, what pages they should build, for a review of a page's SEO, or for the schema markup on a page. Also use before a piece is written for search, so the query and the competing pages are settled before someone drafts against them. Reads pages it is given with web_fetch and researches competitors on the open web, so it reports what a fetched page shows and says plainly what needs crawler or Search Console access it doesn't have. Recommends title tags, meta descriptions, and URL slugs; hand body copy to the content marketer. The caller passes the URLs, the target keywords, the audience, and any brand context in the message.",- model: "anthropic/claude-opus-5",-});-`,- ),- file(- "agent/subagents/social-media-coordinator/agent.ts",- "typescript",- `import { defineAgent } from "eve";--// Subagent: Social Media Coordinator--export default defineAgent({- compaction: { thresholdPercent: 0.9 },- description:- "Run social media work end to end for X, LinkedIn, Threads, Bluesky, and Mastodon: draft posts and threads in each platform's voice, adapt one piece across platforms, and manage the Typefully queue (read, create, and edit drafts, schedule on request, pull post and follower analytics). Researches facts and reviews its own drafts before handing them back. The caller passes the brief or source material, the target platforms, and any angle, audience, or timing constraints in the message.",- model: "anthropic/claude-opus-5",-});-`,- ),- ],- "weather-agent-fixture": [- file(- "agent/agent.ts",- "typescript",- `import { defineAgent } from "eve";--export default defineAgent({- model: "anthropic/claude-sonnet-5",- modelOptions: {- providerOptions: {- openai: {- reasoningEffort: "high",- reasoningSummary: "auto",- },- },- },-});-`,- ),- file(- "agent/instructions.md",- "markdown",- `You are a weather-focused assistant. Be concise, accurate, and explicit about when you are using the local weather tool.-`,- ),- file(- "agent/skills/get-weather.md",- "markdown",- `----description: Use the weather tool before answering forecast or temperature questions.------When the user asks about weather, temperature, or forecast conditions, call the \`get_weather\` tool before answering.-`,- ),- file(- "agent/tools/get_weather.ts",- "typescript",- `import { defineTool } from "eve/tools";-import { never } from "eve/tools/approval";-import { z } from "zod";--const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms));--export default defineTool({- approval: never(),- description: "Get the current weather for a city.",- inputSchema: z.object({- city: z.string(),- }),- async execute(input) {- const city = input.city;-- await sleep(300);-- return {- city,- temperatureF: 72,- condition: "Sunny",- summary: \`Sunny in \${city} with a light breeze.\`,- };- },-});-`,- ),- ],-};diff --git a/apps/docs/lib/templates/sync-core.test.ts b/apps/docs/lib/templates/sync-core.test.tsnew file mode 100644index 000000000..b439041ad--- /dev/null+++ b/apps/docs/lib/templates/sync-core.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from "vitest";++import type { TemplateGitHubSource } from "./manifest";+import {+ commitUrl,+ contentsUrl,+ decodeContentsResponse,+ languageForPath,+ sortTemplateFiles,+} from "./sync-core";++const source: TemplateGitHubSource = {+ owner: "vercel-labs",+ repo: "eve-chat-template",+ ref: "main",+};++describe("languageForPath", () => {+ it("maps markdown and typescript extensions", () => {+ expect(languageForPath("agent/instructions.md")).toBe("markdown");+ expect(languageForPath("agent/skills/intro.mdx")).toBe("markdown");+ expect(languageForPath("agent/agent.ts")).toBe("typescript");+ expect(languageForPath("agent/ui/panel.tsx")).toBe("typescript");+ });++ it("throws for unknown extensions", () => {+ expect(() => languageForPath("agent/config.yaml")).toThrow(/No language mapping/);+ });+});++describe("commitUrl", () => {+ it("targets the commits endpoint for the manifest ref", () => {+ expect(commitUrl(source)).toBe(+ "https://api.github.com/repos/vercel-labs/eve-chat-template/commits/main",+ );+ });+});++describe("contentsUrl", () => {+ it("pins the file to the resolved sha", () => {+ expect(contentsUrl(source, "abc123", "agent/agent.ts")).toBe(+ "https://api.github.com/repos/vercel-labs/eve-chat-template/contents/agent/agent.ts?ref=abc123",+ );+ });++ it("joins the pathPrefix for monorepo sources", () => {+ const monorepo: TemplateGitHubSource = {+ owner: "vercel",+ repo: "eve",+ ref: "main",+ pathPrefix: "apps/fixtures/weather-agent",+ };+ expect(contentsUrl(monorepo, "abc123", "agent/agent.ts")).toBe(+ "https://api.github.com/repos/vercel/eve/contents/apps/fixtures/weather-agent/agent/agent.ts?ref=abc123",+ );+ });+});++describe("decodeContentsResponse", () => {+ it("decodes base64 content with embedded newlines", () => {+ const contents = 'import { defineAgent } from "eve";\n\nexport default defineAgent({});\n';+ const base64 = Buffer.from(contents, "utf8").toString("base64");+ const wrapped = `${base64.slice(0, 20)}\n${base64.slice(20)}\n`;++ expect(+ decodeContentsResponse("agent/agent.ts", { content: wrapped, encoding: "base64" }),+ ).toEqual({ contents, language: "typescript", relativePath: "agent/agent.ts" });+ });++ it("throws for files above the contents API 1 MB limit", () => {+ expect(() =>+ decodeContentsResponse("agent/huge.ts", { content: "", encoding: "none", size: 2_000_000 }),+ ).toThrow(/1 MB limit/);+ });++ it("throws for non-base64 responses", () => {+ expect(() => decodeContentsResponse("agent/agent.ts", { encoding: "utf8" })).toThrow(+ /Unexpected contents API response/,+ );+ });+});++describe("sortTemplateFiles", () => {+ it("orders files by relativePath without mutating the input", () => {+ const files = [+ { contents: "", language: "typescript" as const, relativePath: "agent/tools/b.ts" },+ { contents: "", language: "typescript" as const, relativePath: "agent/agent.ts" },+ ];+ const sorted = sortTemplateFiles(files);++ expect(sorted.map((file) => file.relativePath)).toEqual(["agent/agent.ts", "agent/tools/b.ts"]);+ expect(files[0].relativePath).toBe("agent/tools/b.ts");+ });+});diff --git a/apps/docs/lib/templates/sync-core.ts b/apps/docs/lib/templates/sync-core.tsnew file mode 100644index 000000000..d9c71ff8e--- /dev/null+++ b/apps/docs/lib/templates/sync-core.ts@@ -0,0 +1,61 @@+import type { TemplateFile } from "./compose";+import type { TemplateGitHubSource } from "./manifest";++const GITHUB_API = "https://api.github.com";++/** Subset of the GitHub contents API response the sync consumes. */+export interface GitHubContentsResponse {+ content?: string;+ encoding?: string;+ size?: number;+}++export const languageForPath = (path: string): TemplateFile["language"] => {+ if (path.endsWith(".md") || path.endsWith(".mdx")) return "markdown";+ if (path.endsWith(".ts") || path.endsWith(".tsx")) return "typescript";+ throw new Error(+ `No language mapping for "${path}" — extend TemplateFile["language"] and languageForPath`,+ );+};++const encodePath = (path: string): string => path.split("/").map(encodeURIComponent).join("/");++/** URL that resolves a branch, tag, or SHA to a commit. */+export const commitUrl = (source: TemplateGitHubSource): string =>+ `${GITHUB_API}/repos/${source.owner}/${source.repo}/commits/${encodeURIComponent(source.ref)}`;++/** URL for one template file's contents at a resolved commit SHA. */+export const contentsUrl = (+ source: TemplateGitHubSource,+ sha: string,+ relativePath: string,+): string => {+ const path = source.pathPrefix ? `${source.pathPrefix}/${relativePath}` : relativePath;+ return `${GITHUB_API}/repos/${source.owner}/${source.repo}/contents/${encodePath(path)}?ref=${sha}`;+};++/**+ * Converts a contents API response into a TemplateFile. The API base64-encodes+ * file bodies (with embedded newlines) and omits content above 1 MB.+ */+export const decodeContentsResponse = (+ relativePath: string,+ response: GitHubContentsResponse,+): TemplateFile => {+ if (response.content === "" && (response.size ?? 0) > 1_000_000) {+ throw new Error(+ `"${relativePath}" exceeds the GitHub contents API 1 MB limit (${response.size} bytes) — curate a smaller file`,+ );+ }+ if (response.encoding !== "base64" || typeof response.content !== "string") {+ throw new Error(`Unexpected contents API response for "${relativePath}"`);+ }+ return {+ contents: Buffer.from(response.content, "base64").toString("utf8"),+ language: languageForPath(relativePath),+ relativePath,+ };+};++export const sortTemplateFiles = (files: TemplateFile[]): TemplateFile[] =>+ [...files].sort((a, b) => a.relativePath.localeCompare(b.relativePath));diff --git a/apps/docs/package.json b/apps/docs/package.jsonindex 62b0bb2f0..04a668faa 100644--- a/apps/docs/package.json+++ b/apps/docs/package.json@@ -16,7 +16,8 @@"registry:check": "pnpm run registry:build && pnpm run registry:validate && pnpm run registry:validate:channels && pnpm run registry:validate:instrumentation && tsc --project registry/tsconfig.json","registry:validate": "tsx scripts/validate-connection-registry.ts","registry:validate:channels": "tsx scripts/validate-channel-registry.ts",- "registry:validate:instrumentation": "tsx scripts/validate-instrumentation-registry.ts"+ "registry:validate:instrumentation": "tsx scripts/validate-instrumentation-registry.ts",+ "templates:sync": "tsx scripts/sync-templates.ts"},"dependencies": {"@eve/catalog": "workspace:*",diff --git a/apps/docs/scripts/sync-templates.ts b/apps/docs/scripts/sync-templates.tsnew file mode 100644index 000000000..9ce2168e1--- /dev/null+++ b/apps/docs/scripts/sync-templates.ts@@ -0,0 +1,72 @@+import { mkdir, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";++import type { TemplateFile } from "../lib/templates/compose";+import { templateManifest } from "../lib/templates/manifest";+import {+ commitUrl,+ contentsUrl,+ decodeContentsResponse,+ sortTemplateFiles,+ type GitHubContentsResponse,+} from "../lib/templates/sync-core";++const token = process.env.GITHUB_TOKEN;+const headers: Record<string, string> = {+ Accept: "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+};+if (token) headers.Authorization = `Bearer ${token}`;++const githubJson = async <T>(url: string, notFoundMessage: string): Promise<T> => {+ const response = await fetch(url, { headers });+ if (response.status === 404) {+ throw new Error(notFoundMessage);+ }+ if (response.status === 403 || response.status === 429) {+ throw new Error(+ `GitHub API rate limit or access error (${response.status}) for ${url}` ++ (token ? "" : " — set GITHUB_TOKEN to authenticate"),+ );+ }+ if (!response.ok) {+ throw new Error(`GitHub API request failed (${response.status}) for ${url}`);+ }+ return (await response.json()) as T;+};++console.log(`Syncing templates from GitHub (${token ? "authenticated" : "unauthenticated"})`);++const templates: Record<string, { sourceRevision: string; files: TemplateFile[] }> = {};++for (const entry of templateManifest) {+ const { github } = entry;+ const commit = await githubJson<{ sha: string }>(+ commitUrl(github),+ `Ref "${github.ref}" not found in ${github.owner}/${github.repo} (template "${entry.slug}")`,+ );++ const files: TemplateFile[] = [];+ for (const relativePath of entry.files) {+ const contents = await githubJson<GitHubContentsResponse>(+ contentsUrl(github, commit.sha, relativePath),+ `Curation drift: "${relativePath}" is listed in the manifest for template "${entry.slug}" ` ++ `but does not exist in ${github.owner}/${github.repo}@${commit.sha}`,+ );+ files.push(decodeContentsResponse(relativePath, contents));+ }++ templates[entry.slug] = { sourceRevision: commit.sha, files: sortTemplateFiles(files) };+ console.log(`${entry.slug} ${github.ref} → ${commit.sha.slice(0, 7)} (${files.length} files)`);+}++const output = {+ $comment:+ "Generated by scripts/sync-templates.ts. Do not edit. Run: pnpm --filter eve-docs templates:sync",+ templates,+};++const outputPath = join(import.meta.dirname, "../lib/templates/generated/templates.json");+await mkdir(dirname(outputPath), { recursive: true });+await writeFile(outputPath, `${JSON.stringify(output, null, 2)}\n`);+console.log(`Wrote ${outputPath}`);